Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server.ts

926 lines35.9 KB

1import * as Effect from "effect/Effect";
2import * as Schema from "effect/Schema";
3import { AcpRegistryUrlAuthAction } from "./acpRegistry.ts";
4import {
5 type EnvironmentMachineKind,
6 ExecutionEnvironmentDescriptor,
7 ServerSelfUpdateMethod,
8} from "./environment.ts";
9import { AuthClientPresentationMetadata, ServerAuthDescriptor } from "./auth.ts";
10import {
11 ForwardCompatibleArray,
12 IsoDateTime,
13 NonNegativeInt,
14 PositiveInt,
15 ProjectId,
16 ThreadId,
17 TrimmedNonEmptyString,
18} from "./baseSchemas.ts";
19import {
20 KeybindingCommand,
21 KeybindingValue,
22 KeybindingWhen,
23 ResolvedKeybindingsConfig,
24} from "./keybindings.ts";
25import { EditorId, FileManagerRevealKind, RemoteOpenTarget } from "./editor.ts";
26import { ModelCapabilities, ProviderOptionDescriptor } from "./model.ts";
27import { RuntimeMode } from "./providerPolicy.ts";
28import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
29import { ServerProviderUsageLimits, UsageLimitSourceSnapshots } from "./providerUsageLimits.ts";
30import { ServerSettings } from "./settings.ts";
31​
32const KeybindingsMalformedConfigIssue = Schema.Struct({
33 kind: Schema.Literal("keybindings.malformed-config"),
34 message: TrimmedNonEmptyString,
35});
36​
37const KeybindingsInvalidEntryIssue = Schema.Struct({
38 kind: Schema.Literal("keybindings.invalid-entry"),
39 message: TrimmedNonEmptyString,
40 index: Schema.Number,
41});
42​
43export const ServerConfigIssue = Schema.Union([
44 KeybindingsMalformedConfigIssue,
45 KeybindingsInvalidEntryIssue,
46]);
47export type ServerConfigIssue = typeof ServerConfigIssue.Type;
48​
49const ServerConfigIssues = ForwardCompatibleArray(ServerConfigIssue);
50​
51export const ServerProviderState = Schema.Literals(["ready", "warning", "error", "disabled"]);
52export type ServerProviderState = typeof ServerProviderState.Type;
53​
54export const ServerProviderAuthStatus = Schema.Literals([
55 "authenticated",
56 "unauthenticated",
57 "unknown",
58]);
59export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
60​
61export const ServerProviderAuth = Schema.Struct({
62 status: ServerProviderAuthStatus,
63 type: Schema.optional(TrimmedNonEmptyString),
64 label: Schema.optional(TrimmedNonEmptyString),
65 email: Schema.optional(TrimmedNonEmptyString),
66 action: Schema.optional(AcpRegistryUrlAuthAction),
67 canLogout: Schema.optional(Schema.Boolean),
68 subscriptionSharing: Schema.optional(Schema.Boolean),
69 profileId: Schema.optional(TrimmedNonEmptyString),
70 workspaceId: Schema.optional(TrimmedNonEmptyString),
71});
72export type ServerProviderAuth = typeof ServerProviderAuth.Type;
73​
74export const ServerProviderModel = Schema.Struct({
75 slug: TrimmedNonEmptyString,
76 name: TrimmedNonEmptyString,
77 shortName: Schema.optional(TrimmedNonEmptyString),
78 subProvider: Schema.optional(TrimmedNonEmptyString),
79 aliases: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
80 badge: Schema.optional(Schema.Literal("new")),
81 isCustom: Schema.Boolean,
82 isDefault: Schema.optional(Schema.Boolean),
83 isLegacy: Schema.optional(Schema.Boolean),
84 capabilities: Schema.NullOr(ModelCapabilities),
85});
86export type ServerProviderModel = typeof ServerProviderModel.Type;
87​
88export const ServerProviderUpdateRequiredModel = Schema.Struct({
89 slug: TrimmedNonEmptyString,
90 name: TrimmedNonEmptyString,
91 badge: Schema.optional(Schema.Literal("new")),
92 minVersion: TrimmedNonEmptyString,
93});
94export type ServerProviderUpdateRequiredModel = typeof ServerProviderUpdateRequiredModel.Type;
95​
96export const ServerProviderSlashCommandInput = Schema.Struct({
97 hint: TrimmedNonEmptyString,
98});
99export type ServerProviderSlashCommandInput = typeof ServerProviderSlashCommandInput.Type;
100​
101export const ServerProviderSlashCommand = Schema.Struct({
102 name: TrimmedNonEmptyString,
103 description: Schema.optional(TrimmedNonEmptyString),
104 input: Schema.optional(ServerProviderSlashCommandInput),
105});
106export type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type;
107​
108export const ServerProviderSkill = Schema.Struct({
109 name: TrimmedNonEmptyString,
110 description: Schema.optional(TrimmedNonEmptyString),
111 path: TrimmedNonEmptyString,
112 scope: Schema.optional(TrimmedNonEmptyString),
113 enabled: Schema.Boolean,
114 displayName: Schema.optional(TrimmedNonEmptyString),
115 shortDescription: Schema.optional(TrimmedNonEmptyString),
116 /** Claude disable-model-invocation: only users can invoke; composers must offer a slash command. */
117 userInvocationOnly: Schema.optional(Schema.Boolean),
118 /** Claude user-invocable:false: only agents can invoke; composers must hide the slash command. */
119 userInvocable: Schema.optional(Schema.Boolean),
120});
121export type ServerProviderSkill = typeof ServerProviderSkill.Type;
122​
123export const ServerProviderWorkspaceSnapshot = Schema.Struct({
124 cwd: TrimmedNonEmptyString,
125 checkedAt: IsoDateTime,
126 slashCommands: Schema.Array(ServerProviderSlashCommand),
127 slashCommandsPending: Schema.optional(Schema.Boolean),
128 skills: Schema.Array(ServerProviderSkill),
129 optionDescriptors: Schema.optional(Schema.Array(ProviderOptionDescriptor)),
130});
131export type ServerProviderWorkspaceSnapshot = typeof ServerProviderWorkspaceSnapshot.Type;
132​
133export const PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS = 5 * 60_000;
134​
135export function isProviderWorkspaceSnapshotCurrent(
136 snapshot: Pick<ServerProviderWorkspaceSnapshot, "checkedAt">,
137 nowMs: number,
138): boolean {
139 return nowMs - Date.parse(snapshot.checkedAt) < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS;
141​
142/** Unavailable snapshots must set installed and enabled false. */
143export const ServerProviderAvailability = Schema.Literals(["available", "unavailable"]);
144export type ServerProviderAvailability = typeof ServerProviderAvailability.Type;
145​
146export const ServerProviderContinuation = Schema.Struct({
147 groupKey: TrimmedNonEmptyString,
148});
149export type ServerProviderContinuation = typeof ServerProviderContinuation.Type;
150​
151export const ServerProviderCompatibilityStatus = Schema.Literals([
152 "unknown",
153 "supported",
154 "graceful",
155 "unsupported",
156 "broken",
157]);
158export const ServerProviderCompatibilityAdvisory = Schema.Struct({
159 status: ServerProviderCompatibilityStatus,
160 latestVersionStatus: Schema.optionalKey(ServerProviderCompatibilityStatus),
161 message: Schema.NullOr(TrimmedNonEmptyString),
162 recommendedVersion: Schema.NullOr(TrimmedNonEmptyString),
163 recommendedRange: Schema.NullOr(TrimmedNonEmptyString),
164});
165export type ServerProviderCompatibilityAdvisory = typeof ServerProviderCompatibilityAdvisory.Type;
166​
167export const ServerProviderVersionAdvisoryStatus = Schema.Literals([
168 "unknown",
169 "current",
170 "behind_latest",
171]);
172export type ServerProviderVersionAdvisoryStatus = typeof ServerProviderVersionAdvisoryStatus.Type;
173​
174export const ServerProviderVersionAdvisory = Schema.Struct({
175 status: ServerProviderVersionAdvisoryStatus,
176 currentVersion: Schema.NullOr(TrimmedNonEmptyString),
177 latestVersion: Schema.NullOr(TrimmedNonEmptyString),
178 updateCommand: Schema.NullOr(TrimmedNonEmptyString),
179 canUpdate: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
180 canInstallVersion: Schema.optionalKey(Schema.Boolean),
181 checkedAt: Schema.NullOr(IsoDateTime),
182 message: Schema.NullOr(TrimmedNonEmptyString),
183});
184export type ServerProviderVersionAdvisory = typeof ServerProviderVersionAdvisory.Type;
185​
186export const ServerProviderUpdateStatus = Schema.Literals([
187 "idle",
188 "queued",
189 "running",
190 "succeeded",
191 "failed",
192 "unchanged",
193]);
194export type ServerProviderUpdateStatus = typeof ServerProviderUpdateStatus.Type;
195​
196export const ServerProviderUpdateState = Schema.Struct({
197 status: ServerProviderUpdateStatus,
198 startedAt: Schema.NullOr(IsoDateTime),
199 finishedAt: Schema.NullOr(IsoDateTime),
200 message: Schema.NullOr(TrimmedNonEmptyString),
201 output: Schema.NullOr(Schema.String.check(Schema.isMaxLength(10_000))),
202});
203export type ServerProviderUpdateState = typeof ServerProviderUpdateState.Type;
204​
205export const ServerProvider = Schema.Struct({
206 // Only instanceId is stable enough for provider routing.
207 instanceId: ProviderInstanceId,
208 driver: ProviderDriverKind,
209 displayName: Schema.optional(TrimmedNonEmptyString),
210 accentColor: Schema.optional(TrimmedNonEmptyString),
211 // Validate driver-supplied remote icons against the driver's trusted origin.
212 iconUrl: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(2_048))),
213 badgeLabel: Schema.optional(TrimmedNonEmptyString),
214 continuation: Schema.optional(ServerProviderContinuation),
215 showInteractionModeToggle: Schema.optional(Schema.Boolean),
216 reportsContextWindow: Schema.optional(Schema.Boolean),
217 supportedRuntimeModes: Schema.optional(ForwardCompatibleArray(RuntimeMode)),
218 requiresNewThreadForModelChange: Schema.optional(Schema.Boolean),
219 supportsConversationRollback: Schema.optional(Schema.Boolean),
220 supportsTextGeneration: Schema.optional(Schema.Boolean),
221 setup: Schema.optional(
222 Schema.Struct({
223 canAuthenticate: Schema.Boolean,
224 canInstall: Schema.Boolean,
225 documentationUrl: Schema.optionalKey(TrimmedNonEmptyString.check(Schema.isMaxLength(2_048))),
226 }),
227 ),
228 nativeSessions: Schema.optional(
229 Schema.Struct({
230 canList: Schema.Boolean,
231 canLoad: Schema.Boolean,
232 canResume: Schema.Boolean,
233 canDelete: Schema.optional(Schema.Boolean),
234 }),
235 ),
236 configurableProviders: Schema.optional(Schema.Boolean),
237 runtimePaths: Schema.optionalKey(
238 Schema.Struct({
239 homePath: TrimmedNonEmptyString,
240 shadowHomePath: Schema.NullOr(TrimmedNonEmptyString),
241 }),
242 ),
243 enabled: Schema.Boolean,
244 installed: Schema.Boolean,
245 version: Schema.NullOr(TrimmedNonEmptyString),
246 // Version reported by the installed CLI for a local provider with a separate
247 // server. Null means unknown; absence keeps legacy snapshots on `version`.
248 installedVersion: Schema.optionalKey(Schema.NullOr(TrimmedNonEmptyString)),
249 status: ServerProviderState,
250 auth: ServerProviderAuth,
251 checkedAt: IsoDateTime,
252 message: Schema.optional(TrimmedNonEmptyString),
253 availability: Schema.optional(ServerProviderAvailability),
254 unavailableReason: Schema.optional(TrimmedNonEmptyString),
255 models: Schema.Array(ServerProviderModel),
256 // Kept apart from `models` so clients that predate it never offer them.
257 updateRequiredModels: Schema.optionalKey(Schema.Array(ServerProviderUpdateRequiredModel)),
258 slashCommands: Schema.Array(ServerProviderSlashCommand).pipe(
259 Schema.withDecodingDefault(Effect.succeed([])),
260 ),
261 skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
262 workspaceSnapshots: Schema.optionalKey(Schema.Array(ServerProviderWorkspaceSnapshot)),
263 usageLimits: Schema.optional(ServerProviderUsageLimits),
264 versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory),
265 compatibilityAdvisory: Schema.optionalKey(ServerProviderCompatibilityAdvisory),
266 updateState: Schema.optionalKey(ServerProviderUpdateState),
267});
268export type ServerProvider = typeof ServerProvider.Type;
269​
270export const ServerProviders = ForwardCompatibleArray(ServerProvider);
271export type ServerProviders = typeof ServerProviders.Type;
272​
273export const isProviderAvailable = (snapshot: ServerProvider): boolean =>
274 snapshot.availability !== "unavailable";
275​
276/** Legacy producers omit this field and support text generation. */
277export const isProviderTextGenerationCapable = (snapshot: ServerProvider): boolean =>
278 snapshot.supportsTextGeneration !== false;
279​
280export const OtlpEndpointSource = Schema.Literals(["environment", "bootstrap", "settings"]);
281export type OtlpEndpointSource = typeof OtlpEndpointSource.Type;
282​
283export const ServerObservability = Schema.Struct({
284 logsDirectoryPath: TrimmedNonEmptyString,
285 localTracingEnabled: Schema.Boolean,
286 otlpTracesUrl: Schema.optional(TrimmedNonEmptyString),
287 otlpTracesSource: Schema.optional(OtlpEndpointSource),
288 otlpTracesVariable: Schema.optional(TrimmedNonEmptyString),
289 otlpTracesEnabled: Schema.Boolean,
290 otlpMetricsUrl: Schema.optional(TrimmedNonEmptyString),
291 otlpMetricsSource: Schema.optional(OtlpEndpointSource),
292 otlpMetricsVariable: Schema.optional(TrimmedNonEmptyString),
293 otlpMetricsEnabled: Schema.Boolean,
294 otlpLogsUrl: Schema.optional(TrimmedNonEmptyString),
295 otlpLogsSource: Schema.optional(OtlpEndpointSource),
296 otlpLogsVariable: Schema.optional(TrimmedNonEmptyString),
297 otlpLogsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
298});
299export type ServerObservability = typeof ServerObservability.Type;
300​
301export const OtlpSignal = Schema.Literals(["traces", "metrics", "logs"]);
302export type OtlpSignal = typeof OtlpSignal.Type;
303​
304export const OtlpEndpointCheckInput = Schema.Struct({
305 signal: OtlpSignal,
306 url: TrimmedNonEmptyString.check(Schema.isPattern(/^https?:\/\/./i)),
307});
308export type OtlpEndpointCheckInput = typeof OtlpEndpointCheckInput.Type;
309​
310export const OtlpEndpointCheckResult = Schema.Union([
311 Schema.TaggedStruct("Accepted", { latencyMs: Schema.Number }),
312 Schema.TaggedStruct("Rejected", { status: Schema.Number }),
313 Schema.TaggedStruct("Unreachable", { timedOut: Schema.Boolean }),
314]);
315export type OtlpEndpointCheckResult = typeof OtlpEndpointCheckResult.Type;
316​
317/** The client tells the server what it is, so the triage context can name it. */
318export const ServerPrepareTriageInput = Schema.Struct({
319 client: AuthClientPresentationMetadata,
320});
321export type ServerPrepareTriageInput = typeof ServerPrepareTriageInput.Type;
322​
323export const ServerPrepareTriageResult = Schema.Struct({
324 /** Composer text that links the session's prompt file. */
325 prompt: Schema.String,
326});
327export type ServerPrepareTriageResult = typeof ServerPrepareTriageResult.Type;
328​
329/**
330 * The prompt file links as a chip in the user's message; clients spot a triage
331 * draft by it.
332 */
333export const TRIAGE_PROMPT_FILE_NAME = "triage-playbook.md";
334​
335export class ServerPrepareTriageError extends Schema.TaggedError<ServerPrepareTriageError>()(
336 "ServerPrepareTriageError",
337 { cause: Schema.optional(Schema.Defect()) },
338) {
339 override get message(): string {
340 return "Could not write the triage session files.";
341 }
343​
344export const ServerTraceDiagnosticsErrorKind = Schema.Literals([
345 "trace-file-not-found",
346 "trace-file-read-failed",
347]);
348export type ServerTraceDiagnosticsErrorKind = typeof ServerTraceDiagnosticsErrorKind.Type;
349​
350export const ServerTraceDiagnosticsSpanSummary = Schema.Struct({
351 name: TrimmedNonEmptyString,
352 count: NonNegativeInt,
353 failureCount: NonNegativeInt,
354 totalDurationMs: Schema.Number,
355 averageDurationMs: Schema.Number,
356 maxDurationMs: Schema.Number,
357});
358export type ServerTraceDiagnosticsSpanSummary = typeof ServerTraceDiagnosticsSpanSummary.Type;
359​
360export const ServerTraceDiagnosticsFailureSummary = Schema.Struct({
361 name: TrimmedNonEmptyString,
362 cause: TrimmedNonEmptyString,
363 count: NonNegativeInt,
364 lastSeenAt: Schema.DateTimeUtc,
365 traceId: TrimmedNonEmptyString,
366 spanId: TrimmedNonEmptyString,
367});
368export type ServerTraceDiagnosticsFailureSummary = typeof ServerTraceDiagnosticsFailureSummary.Type;
369​
370export const ServerTraceDiagnosticsRecentFailure = Schema.Struct({
371 name: TrimmedNonEmptyString,
372 cause: TrimmedNonEmptyString,
373 durationMs: Schema.Number,
374 endedAt: Schema.DateTimeUtc,
375 traceId: TrimmedNonEmptyString,
376 spanId: TrimmedNonEmptyString,
377});
378export type ServerTraceDiagnosticsRecentFailure = typeof ServerTraceDiagnosticsRecentFailure.Type;
379​
380export const ServerTraceDiagnosticsSpanOccurrence = Schema.Struct({
381 name: TrimmedNonEmptyString,
382 durationMs: Schema.Number,
383 endedAt: Schema.DateTimeUtc,
384 traceId: TrimmedNonEmptyString,
385 spanId: TrimmedNonEmptyString,
386});
387export type ServerTraceDiagnosticsSpanOccurrence = typeof ServerTraceDiagnosticsSpanOccurrence.Type;
388​
389export const ServerTraceDiagnosticsLogEvent = Schema.Struct({
390 spanName: TrimmedNonEmptyString,
391 level: TrimmedNonEmptyString,
392 message: TrimmedNonEmptyString,
393 seenAt: Schema.DateTimeUtc,
394 traceId: TrimmedNonEmptyString,
395 spanId: TrimmedNonEmptyString,
396});
397export type ServerTraceDiagnosticsLogEvent = typeof ServerTraceDiagnosticsLogEvent.Type;
398​
399export const ServerTraceDiagnosticsResult = Schema.Struct({
400 traceFilePath: TrimmedNonEmptyString,
401 scannedFilePaths: Schema.Array(TrimmedNonEmptyString),
402 readAt: Schema.DateTimeUtc,
403 recordCount: NonNegativeInt,
404 parseErrorCount: NonNegativeInt,
405 firstSpanAt: Schema.Option(Schema.DateTimeUtc),
406 lastSpanAt: Schema.Option(Schema.DateTimeUtc),
407 failureCount: NonNegativeInt,
408 interruptionCount: NonNegativeInt,
409 slowSpanThresholdMs: NonNegativeInt,
410 slowSpanCount: NonNegativeInt,
411 logLevelCounts: Schema.Record(TrimmedNonEmptyString, NonNegativeInt),
412 topSpansByCount: Schema.Array(ServerTraceDiagnosticsSpanSummary),
413 slowestSpans: Schema.Array(ServerTraceDiagnosticsSpanOccurrence),
414 commonFailures: Schema.Array(ServerTraceDiagnosticsFailureSummary),
415 latestFailures: Schema.Array(ServerTraceDiagnosticsRecentFailure),
416 latestWarningAndErrorLogs: Schema.Array(ServerTraceDiagnosticsLogEvent),
417 partialFailure: Schema.Option(Schema.Boolean),
418 error: Schema.Option(
419 Schema.Struct({
420 kind: ServerTraceDiagnosticsErrorKind,
421 message: TrimmedNonEmptyString,
422 }),
423 ),
424});
425export type ServerTraceDiagnosticsResult = typeof ServerTraceDiagnosticsResult.Type;
426​
427export const ServerProcessSignal = Schema.Literals(["SIGINT", "SIGKILL"]);
428export type ServerProcessSignal = typeof ServerProcessSignal.Type;
429​
430export const ServerProcessDiagnosticsEntry = Schema.Struct({
431 pid: PositiveInt,
432 startTimeMs: NonNegativeInt,
433 ppid: NonNegativeInt,
434 pgid: Schema.Option(Schema.Int),
435 status: TrimmedNonEmptyString,
436 cpuPercent: Schema.Number,
437 rssBytes: NonNegativeInt,
438 elapsed: TrimmedNonEmptyString,
439 command: TrimmedNonEmptyString,
440 depth: NonNegativeInt,
441 childPids: Schema.Array(PositiveInt),
442});
443export type ServerProcessDiagnosticsEntry = typeof ServerProcessDiagnosticsEntry.Type;
444​
445export const ServerProcessDiagnosticsResult = Schema.Struct({
446 serverPid: PositiveInt,
447 readAt: Schema.DateTimeUtc,
448 processCount: NonNegativeInt,
449 totalRssBytes: NonNegativeInt,
450 totalCpuPercent: Schema.Number,
451 processes: Schema.Array(ServerProcessDiagnosticsEntry),
452 error: Schema.Option(
453 Schema.Struct({
454 message: TrimmedNonEmptyString,
455 }),
456 ),
457});
458export type ServerProcessDiagnosticsResult = typeof ServerProcessDiagnosticsResult.Type;
459​
460export const ServerProcessResourceHistoryInput = Schema.Struct({
461 windowMs: NonNegativeInt,
462 bucketMs: NonNegativeInt,
463});
464export type ServerProcessResourceHistoryInput = typeof ServerProcessResourceHistoryInput.Type;
465​
466export const ServerProcessResourceHistoryBucket = Schema.Struct({
467 startedAt: Schema.DateTimeUtc,
468 endedAt: Schema.DateTimeUtc,
469 avgCpuPercent: Schema.Number,
470 maxCpuPercent: Schema.Number,
471 maxRssBytes: NonNegativeInt,
472 maxProcessCount: NonNegativeInt,
473});
474export type ServerProcessResourceHistoryBucket = typeof ServerProcessResourceHistoryBucket.Type;
475​
476export const ServerProcessResourceHistorySummary = Schema.Struct({
477 processKey: TrimmedNonEmptyString,
478 pid: PositiveInt,
479 ppid: NonNegativeInt,
480 command: TrimmedNonEmptyString,
481 depth: NonNegativeInt,
482 isServerRoot: Schema.Boolean,
483 firstSeenAt: Schema.DateTimeUtc,
484 lastSeenAt: Schema.DateTimeUtc,
485 currentCpuPercent: Schema.Number,
486 avgCpuPercent: Schema.Number,
487 maxCpuPercent: Schema.Number,
488 cpuSecondsApprox: Schema.Number,
489 currentRssBytes: NonNegativeInt,
490 maxRssBytes: NonNegativeInt,
491 sampleCount: NonNegativeInt,
492});
493export type ServerProcessResourceHistorySummary = typeof ServerProcessResourceHistorySummary.Type;
494​
495export const ServerProcessResourceHistoryFailureTag = Schema.Literals([
496 "ProcessDiagnosticsQueryTimeoutError",
497 "ProcessDiagnosticsQueryFailedError",
498 "ProcessDiagnosticsServerProcessSignalError",
499 "ProcessDiagnosticsNotDescendantError",
500 "ProcessDiagnosticsSignalFailedError",
501]);
502export type ServerProcessResourceHistoryFailureTag =
503 typeof ServerProcessResourceHistoryFailureTag.Type;
504​
505export const ServerProcessResourceHistoryResult = Schema.Struct({
506 readAt: Schema.DateTimeUtc,
507 windowMs: NonNegativeInt,
508 bucketMs: NonNegativeInt,
509 sampleIntervalMs: NonNegativeInt,
510 retainedSampleCount: NonNegativeInt,
511 totalCpuSecondsApprox: Schema.Number,
512 buckets: Schema.Array(ServerProcessResourceHistoryBucket),
513 topProcesses: Schema.Array(ServerProcessResourceHistorySummary),
514 error: Schema.Option(
515 Schema.Struct({
516 failureTag: ServerProcessResourceHistoryFailureTag,
517 message: TrimmedNonEmptyString,
518 }),
519 ),
520});
521export type ServerProcessResourceHistoryResult = typeof ServerProcessResourceHistoryResult.Type;
522​
523export const ServerSignalProcessInput = Schema.Struct({
524 pid: PositiveInt,
525 startTimeMs: NonNegativeInt,
526 signal: ServerProcessSignal,
527});
528export type ServerSignalProcessInput = typeof ServerSignalProcessInput.Type;
529​
530export const ServerSignalProcessResult = Schema.Struct({
531 pid: PositiveInt,
532 signal: ServerProcessSignal,
533 signaled: Schema.Boolean,
534 message: Schema.Option(TrimmedNonEmptyString),
535});
536export type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;
537​
538export const EnvironmentThemeColor = Schema.String.check(
539 Schema.isPattern(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/),
540);
541export type EnvironmentThemeColor = typeof EnvironmentThemeColor.Type;
542​
543/** Reserve appearance keywords so published themes cannot replace stock preferences. */
544export const EnvironmentThemeId = Schema.String.check(
545 Schema.isPattern(/^(?!(?:system|light|dark)$)[a-z0-9](?:[a-z0-9-]{0,47})$/),
546);
547export type EnvironmentThemeId = typeof EnvironmentThemeId.Type;
548​
549const EnvironmentThemeColors = Schema.Record(
550 Schema.String.check(Schema.isPattern(/^[a-zA-Z][a-zA-Z0-9]{0,63}$/)),
551 TrimmedNonEmptyString.check(Schema.isMaxLength(64)),
552);
553​
554const environmentThemeFields = {
555 version: Schema.optional(Schema.Literal(1)),
556 name: TrimmedNonEmptyString.check(Schema.isMaxLength(48)),
557 appearance: Schema.Literals(["light", "dark"]),
558 /** Derive the palette from canvas/accent, then overlay colors; without them, colors is the palette. */
559 canvas: Schema.optional(EnvironmentThemeColor),
560 accent: Schema.optional(EnvironmentThemeColor),
561 colors: Schema.optional(EnvironmentThemeColors),
562 variants: Schema.optional(
563 Schema.Struct({
564 light: Schema.optional(EnvironmentThemeColors),
565 dark: Schema.optional(EnvironmentThemeColors),
566 }),
567 ),
568};
569​
570export const EnvironmentThemeFile = Schema.Struct(environmentThemeFields);
571export type EnvironmentThemeFile = typeof EnvironmentThemeFile.Type;
572​
573export const EnvironmentTheme = Schema.Struct({
574 id: EnvironmentThemeId,
575 ...environmentThemeFields,
576});
577export type EnvironmentTheme = typeof EnvironmentTheme.Type;
578​
579export function environmentThemeFileHasColors(file: EnvironmentThemeFile): boolean {
580 return (
581 (file.canvas !== undefined && file.accent !== undefined) ||
582 (file.colors !== undefined && Object.keys(file.colors).length > 0)
583 );
585​
586/** tailnet means this machine's Tailscale interface; other private addresses are lan. */
587export const ServerDirectEndpointKind = Schema.Literals(["lan", "tailnet"]);
588export type ServerDirectEndpointKind = typeof ServerDirectEndpointKind.Type;
589​
590export const ServerDirectEndpoint = Schema.Struct({
591 kind: ServerDirectEndpointKind,
592 httpBaseUrl: TrimmedNonEmptyString,
593});
594export type ServerDirectEndpoint = typeof ServerDirectEndpoint.Type;
595​
596/**
597 * A stretch where the server's event loop could not run, so it answered
598 * nothing and clients may have dropped the connection.
599 */
600export const ServerEventLoopStall = Schema.Struct({
601 detectedAt: IsoDateTime,
602 durationMs: NonNegativeInt,
603 /** One-minute load average when the stall was seen. Absent on Windows, which has none. */
604 loadAverage: Schema.optionalKey(Schema.Number),
605 cpuCount: PositiveInt,
606});
607export type ServerEventLoopStall = typeof ServerEventLoopStall.Type;
608​
609export const ServerConfig = Schema.Struct({
610 environment: ExecutionEnvironmentDescriptor,
611 auth: ServerAuthDescriptor,
612 cwd: TrimmedNonEmptyString,
613 keybindingsConfigPath: TrimmedNonEmptyString,
614 keybindings: ResolvedKeybindingsConfig,
615 issues: ServerConfigIssues,
616 providers: ServerProviders,
617 availableEditors: ForwardCompatibleArray(EditorId),
618 remoteOpenTargets: Schema.optionalKey(ForwardCompatibleArray(RemoteOpenTarget)),
619 /** Hints only; verify each address answers as this environment. */
620 directEndpoints: Schema.optionalKey(ForwardCompatibleArray(ServerDirectEndpoint)),
621 observability: ServerObservability,
622 settings: ServerSettings,
623 shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
624 /**
625 * The shell can leave idle subagent children out of snapshots (`omitIdleSubagents`), and
626 * `getThreadFamily` and `getWorktreeThreadIds` serve the rows it leaves out.
627 */
628 shellThreadFamilies: Schema.optionalKey(Schema.Boolean),
629 /**
630 * The shell can leave older settled threads out of snapshots (`omitOlderSettled`), and
631 * `getOlderSettledThreads` serves them. Only servers that also advertise `shellThreadFamilies`.
632 */
633 shellOlderSettled: Schema.optionalKey(Schema.Boolean),
634 shellRevealInFileManager: Schema.optionalKey(Schema.Boolean),
635 shellRevealInFileManagerKind: Schema.optionalKey(FileManagerRevealKind),
636 threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
637 /** Send window fields only when advertised. */
638 threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),
639 reasoningMessages: Schema.optionalKey(Schema.Boolean),
640 threadFind: Schema.optionalKey(Schema.Boolean),
641 threadFindProgressive: Schema.optionalKey(Schema.Boolean),
642 scratchWorkspaceRoot: Schema.optionalKey(TrimmedNonEmptyString),
643 newProjectsRoot: Schema.optionalKey(TrimmedNonEmptyString),
644 /**
645 * The latest stall long enough to notice, sent only for a few minutes after
646 * it. A client that reconnects reads it to say why the host stopped
647 * answering. Clients do not cache it, since it describes the host at connect.
648 */
649 lastEventLoopStall: Schema.optionalKey(ServerEventLoopStall),
650 /**
651 * Never sent in a config snapshot: the theme stream emits the current set
652 * before any change, so a snapshot carrying it too would hand every
653 * subscriber the same array twice per connect.
654 */
655 environmentThemes: Schema.optional(Schema.Array(EnvironmentTheme)),
656 /** Stream-only and opt-in; the source stream emits the current set on subscribe. */
657 usageLimitSources: Schema.optional(UsageLimitSourceSnapshots),
658});
659export type ServerConfig = typeof ServerConfig.Type;
660​
661export function resolveEnvironmentMachineKind(
662 config: {
663 readonly environment: Pick<ExecutionEnvironmentDescriptor, "platform">;
664 readonly settings?: Pick<ServerSettings, "environmentIcon">;
665 } | null,
666): EnvironmentMachineKind {
667 return config?.settings?.environmentIcon ?? config?.environment.platform.machine ?? "server";
669​
670const ServerUpsertKeybindingReplaceTarget = Schema.Struct({
671 key: KeybindingValue,
672 command: KeybindingCommand,
673 when: Schema.optional(KeybindingWhen),
674});
675​
676export const ServerUpsertKeybindingInput = Schema.Struct({
677 key: KeybindingValue,
678 command: KeybindingCommand,
679 when: Schema.optional(KeybindingWhen),
680 replace: Schema.optional(ServerUpsertKeybindingReplaceTarget),
681});
682export type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;
683​
684export const ServerRemoveKeybindingInput = ServerUpsertKeybindingReplaceTarget;
685export type ServerRemoveKeybindingInput = typeof ServerRemoveKeybindingInput.Type;
686​
687export const ServerUpsertKeybindingResult = Schema.Struct({
688 keybindings: ResolvedKeybindingsConfig,
689 issues: ServerConfigIssues,
690});
691export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.Type;
692​
693export const ServerRemoveKeybindingResult = ServerUpsertKeybindingResult;
694export type ServerRemoveKeybindingResult = typeof ServerRemoveKeybindingResult.Type;
695​
696export const ServerConfigUpdatedPayload = Schema.Struct({
697 issues: ServerConfigIssues,
698 providers: ServerProviders,
699 settings: Schema.optional(ServerSettings),
700});
701export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
702​
703export const ServerConfigKeybindingsUpdatedPayload = Schema.Struct({
704 keybindings: ResolvedKeybindingsConfig,
705 issues: ServerConfigIssues,
706});
707export type ServerConfigKeybindingsUpdatedPayload =
708 typeof ServerConfigKeybindingsUpdatedPayload.Type;
709​
710export const ServerConfigProviderStatusesPayload = Schema.Struct({
711 providers: ServerProviders,
712});
713export type ServerConfigProviderStatusesPayload = typeof ServerConfigProviderStatusesPayload.Type;
714​
715export const ServerConfigSettingsUpdatedPayload = Schema.Struct({
716 settings: ServerSettings,
717});
718export type ServerConfigSettingsUpdatedPayload = typeof ServerConfigSettingsUpdatedPayload.Type;
719​
720export const ServerConfigStreamSnapshotEvent = Schema.Struct({
721 version: Schema.Literal(1),
722 type: Schema.Literal("snapshot"),
723 config: ServerConfig,
724});
725export type ServerConfigStreamSnapshotEvent = typeof ServerConfigStreamSnapshotEvent.Type;
726​
727export const ServerConfigStreamKeybindingsUpdatedEvent = Schema.Struct({
728 version: Schema.Literal(1),
729 type: Schema.Literal("keybindingsUpdated"),
730 payload: ServerConfigKeybindingsUpdatedPayload,
731});
732export type ServerConfigStreamKeybindingsUpdatedEvent =
733 typeof ServerConfigStreamKeybindingsUpdatedEvent.Type;
734​
735export const ServerConfigStreamProviderStatusesEvent = Schema.Struct({
736 version: Schema.Literal(1),
737 type: Schema.Literal("providerStatuses"),
738 payload: ServerConfigProviderStatusesPayload,
739});
740export type ServerConfigStreamProviderStatusesEvent =
741 typeof ServerConfigStreamProviderStatusesEvent.Type;
742​
743export const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({
744 version: Schema.Literal(1),
745 type: Schema.Literal("settingsUpdated"),
746 payload: ServerConfigSettingsUpdatedPayload,
747});
748export type ServerConfigStreamSettingsUpdatedEvent =
749 typeof ServerConfigStreamSettingsUpdatedEvent.Type;
750​
751export const ServerConfigEnvironmentThemesUpdatedPayload = Schema.Struct({
752 themes: Schema.Array(EnvironmentTheme),
753});
754export type ServerConfigEnvironmentThemesUpdatedPayload =
755 typeof ServerConfigEnvironmentThemesUpdatedPayload.Type;
756​
757export const ServerConfigStreamEnvironmentThemesUpdatedEvent = Schema.Struct({
758 version: Schema.Literal(1),
759 type: Schema.Literal("environmentThemesUpdated"),
760 payload: ServerConfigEnvironmentThemesUpdatedPayload,
761});
762export type ServerConfigStreamEnvironmentThemesUpdatedEvent =
763 typeof ServerConfigStreamEnvironmentThemesUpdatedEvent.Type;
764​
765export const ServerConfigUsageLimitSourcesUpdatedPayload = Schema.Struct({
766 sources: UsageLimitSourceSnapshots,
767});
768export type ServerConfigUsageLimitSourcesUpdatedPayload =
769 typeof ServerConfigUsageLimitSourcesUpdatedPayload.Type;
770​
771export const ServerConfigStreamUsageLimitSourcesUpdatedEvent = Schema.Struct({
772 version: Schema.Literal(1),
773 type: Schema.Literal("usageLimitSourcesUpdated"),
774 payload: ServerConfigUsageLimitSourcesUpdatedPayload,
775});
776export type ServerConfigStreamUsageLimitSourcesUpdatedEvent =
777 typeof ServerConfigStreamUsageLimitSourcesUpdatedEvent.Type;
778​
779export const ServerConfigStreamEvent = Schema.Union([
780 ServerConfigStreamSnapshotEvent,
781 ServerConfigStreamKeybindingsUpdatedEvent,
782 ServerConfigStreamProviderStatusesEvent,
783 ServerConfigStreamSettingsUpdatedEvent,
784 ServerConfigStreamEnvironmentThemesUpdatedEvent,
785 ServerConfigStreamUsageLimitSourcesUpdatedEvent,
786]);
787export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;
788​
789export const ServerSelfUpdateOutcome = Schema.Struct({
790 id: TrimmedNonEmptyString,
791 fromVersion: TrimmedNonEmptyString,
792 targetVersion: TrimmedNonEmptyString,
793 status: Schema.Literals(["committed", "rolled-back", "failed"]),
794 reason: Schema.optionalKey(TrimmedNonEmptyString),
795});
796export type ServerSelfUpdateOutcome = typeof ServerSelfUpdateOutcome.Type;
797​
798export const ServerLifecycleReadyPayload = Schema.Struct({
799 at: IsoDateTime,
800 environment: ExecutionEnvironmentDescriptor,
801 updateOutcome: Schema.optionalKey(ServerSelfUpdateOutcome),
802});
803export type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type;
804​
805export const ServerLifecycleWelcomePayload = Schema.Struct({
806 environment: ExecutionEnvironmentDescriptor,
807 cwd: TrimmedNonEmptyString,
808 projectName: TrimmedNonEmptyString,
809 bootstrapStatus: Schema.optional(Schema.Literals(["pending", "complete"])),
810 bootstrapProjectId: Schema.optional(ProjectId),
811 bootstrapThreadId: Schema.optional(ThreadId),
812 bootstrapProjectCreated: Schema.optional(Schema.Boolean),
813 bootstrapThreadCreated: Schema.optional(Schema.Boolean),
814});
815export type ServerLifecycleWelcomePayload = typeof ServerLifecycleWelcomePayload.Type;
816​
817export const ServerLifecycleLegacyThreadMigrationPayload = Schema.Struct({
818 status: Schema.Union([Schema.Literal("running"), Schema.Literal("complete")]),
819 totalThreadCount: NonNegativeInt,
820});
821export type ServerLifecycleLegacyThreadMigrationPayload =
822 typeof ServerLifecycleLegacyThreadMigrationPayload.Type;
823​
824export const ServerLifecycleStreamWelcomeEvent = Schema.Struct({
825 version: Schema.Literal(1),
826 sequence: NonNegativeInt,
827 type: Schema.Literal("welcome"),
828 payload: ServerLifecycleWelcomePayload,
829});
830export type ServerLifecycleStreamWelcomeEvent = typeof ServerLifecycleStreamWelcomeEvent.Type;
831​
832export const ServerLifecycleStreamReadyEvent = Schema.Struct({
833 version: Schema.Literal(1),
834 sequence: NonNegativeInt,
835 type: Schema.Literal("ready"),
836 payload: ServerLifecycleReadyPayload,
837});
838export type ServerLifecycleStreamReadyEvent = typeof ServerLifecycleStreamReadyEvent.Type;
839​
840export const ServerLifecycleStreamLegacyThreadMigrationEvent = Schema.Struct({
841 version: Schema.Literal(1),
842 sequence: NonNegativeInt,
843 type: Schema.Literal("legacyThreadMigration"),
844 payload: ServerLifecycleLegacyThreadMigrationPayload,
845});
846export type ServerLifecycleStreamLegacyThreadMigrationEvent =
847 typeof ServerLifecycleStreamLegacyThreadMigrationEvent.Type;
848​
849export const ServerLifecycleStreamEvent = Schema.Union([
850 ServerLifecycleStreamWelcomeEvent,
851 ServerLifecycleStreamReadyEvent,
852 ServerLifecycleStreamLegacyThreadMigrationEvent,
853]);
854export type ServerLifecycleStreamEvent = typeof ServerLifecycleStreamEvent.Type;
855​
856export const ServerProviderUpdatedPayload = Schema.Struct({
857 providers: ServerProviders,
858});
859export type ServerProviderUpdatedPayload = typeof ServerProviderUpdatedPayload.Type;
860​
861export const ServerProviderUpdateInput = Schema.Struct({
862 provider: ProviderDriverKind,
863 targetVersion: Schema.optionalKey(TrimmedNonEmptyString),
864 instanceId: Schema.optionalKey(ProviderInstanceId),
865});
866export type ServerProviderUpdateInput = typeof ServerProviderUpdateInput.Type;
867​
868export class ServerProviderUpdateError extends Schema.TaggedError<ServerProviderUpdateError>()(
869 "ServerProviderUpdateError",
870 {
871 provider: ProviderDriverKind,
872 reason: TrimmedNonEmptyString,
873 cause: Schema.optional(Schema.Defect()),
874 },
875) {
876 override get message(): string {
877 return `Provider update failed for ${this.provider}: ${this.reason}`;
878 }
880​
881export const ServerSelfUpdateInput = Schema.Struct({
882 /** Exact npm version, never a dist-tag, so server and client agree on the request. */
883 targetVersion: TrimmedNonEmptyString,
884 continueRunningThreads: Schema.optionalKey(Schema.Boolean),
885});
886export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
887​
888export const ServerSelfUpdateResult = Schema.Struct({
889 targetVersion: TrimmedNonEmptyString,
890 method: ServerSelfUpdateMethod,
891 updateId: Schema.optionalKey(TrimmedNonEmptyString),
892 desktopUpdateToken: Schema.optionalKey(TrimmedNonEmptyString),
893});
894export type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;
895​
896export const DesktopUpdateCommitInput = Schema.Struct({
897 requestId: TrimmedNonEmptyString,
898});
899export type DesktopUpdateCommitInput = typeof DesktopUpdateCommitInput.Type;
900​
901export const ServerSelfUpdateProgressStage = Schema.Literals(["downloading", "installing"]);
902export type ServerSelfUpdateProgressStage = typeof ServerSelfUpdateProgressStage.Type;
903​
904export const ServerSelfUpdateProgressEvent = Schema.Union([
905 Schema.Struct({
906 type: Schema.Literal("progress"),
907 stage: ServerSelfUpdateProgressStage,
908 }),
909 Schema.Struct({
910 type: Schema.Literal("complete"),
911 result: ServerSelfUpdateResult,
912 }),
913]);
914export type ServerSelfUpdateProgressEvent = typeof ServerSelfUpdateProgressEvent.Type;
915​
916export class ServerSelfUpdateError extends Schema.TaggedError<ServerSelfUpdateError>()(
917 "ServerSelfUpdateError",
918 {
919 reason: TrimmedNonEmptyString,
920 cause: Schema.optional(Schema.Defect()),
921 },
922) {
923 override get message(): string {
924 return `Server update failed: ${this.reason}`;
925 }