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

server.ts

899 lines34.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 { 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​
317export const ServerTraceDiagnosticsErrorKind = Schema.Literals([
318 "trace-file-not-found",
319 "trace-file-read-failed",
320]);
321export type ServerTraceDiagnosticsErrorKind = typeof ServerTraceDiagnosticsErrorKind.Type;
322​
323export const ServerTraceDiagnosticsSpanSummary = Schema.Struct({
324 name: TrimmedNonEmptyString,
325 count: NonNegativeInt,
326 failureCount: NonNegativeInt,
327 totalDurationMs: Schema.Number,
328 averageDurationMs: Schema.Number,
329 maxDurationMs: Schema.Number,
330});
331export type ServerTraceDiagnosticsSpanSummary = typeof ServerTraceDiagnosticsSpanSummary.Type;
332​
333export const ServerTraceDiagnosticsFailureSummary = Schema.Struct({
334 name: TrimmedNonEmptyString,
335 cause: TrimmedNonEmptyString,
336 count: NonNegativeInt,
337 lastSeenAt: Schema.DateTimeUtc,
338 traceId: TrimmedNonEmptyString,
339 spanId: TrimmedNonEmptyString,
340});
341export type ServerTraceDiagnosticsFailureSummary = typeof ServerTraceDiagnosticsFailureSummary.Type;
342​
343export const ServerTraceDiagnosticsRecentFailure = Schema.Struct({
344 name: TrimmedNonEmptyString,
345 cause: TrimmedNonEmptyString,
346 durationMs: Schema.Number,
347 endedAt: Schema.DateTimeUtc,
348 traceId: TrimmedNonEmptyString,
349 spanId: TrimmedNonEmptyString,
350});
351export type ServerTraceDiagnosticsRecentFailure = typeof ServerTraceDiagnosticsRecentFailure.Type;
352​
353export const ServerTraceDiagnosticsSpanOccurrence = Schema.Struct({
354 name: TrimmedNonEmptyString,
355 durationMs: Schema.Number,
356 endedAt: Schema.DateTimeUtc,
357 traceId: TrimmedNonEmptyString,
358 spanId: TrimmedNonEmptyString,
359});
360export type ServerTraceDiagnosticsSpanOccurrence = typeof ServerTraceDiagnosticsSpanOccurrence.Type;
361​
362export const ServerTraceDiagnosticsLogEvent = Schema.Struct({
363 spanName: TrimmedNonEmptyString,
364 level: TrimmedNonEmptyString,
365 message: TrimmedNonEmptyString,
366 seenAt: Schema.DateTimeUtc,
367 traceId: TrimmedNonEmptyString,
368 spanId: TrimmedNonEmptyString,
369});
370export type ServerTraceDiagnosticsLogEvent = typeof ServerTraceDiagnosticsLogEvent.Type;
371​
372export const ServerTraceDiagnosticsResult = Schema.Struct({
373 traceFilePath: TrimmedNonEmptyString,
374 scannedFilePaths: Schema.Array(TrimmedNonEmptyString),
375 readAt: Schema.DateTimeUtc,
376 recordCount: NonNegativeInt,
377 parseErrorCount: NonNegativeInt,
378 firstSpanAt: Schema.Option(Schema.DateTimeUtc),
379 lastSpanAt: Schema.Option(Schema.DateTimeUtc),
380 failureCount: NonNegativeInt,
381 interruptionCount: NonNegativeInt,
382 slowSpanThresholdMs: NonNegativeInt,
383 slowSpanCount: NonNegativeInt,
384 logLevelCounts: Schema.Record(TrimmedNonEmptyString, NonNegativeInt),
385 topSpansByCount: Schema.Array(ServerTraceDiagnosticsSpanSummary),
386 slowestSpans: Schema.Array(ServerTraceDiagnosticsSpanOccurrence),
387 commonFailures: Schema.Array(ServerTraceDiagnosticsFailureSummary),
388 latestFailures: Schema.Array(ServerTraceDiagnosticsRecentFailure),
389 latestWarningAndErrorLogs: Schema.Array(ServerTraceDiagnosticsLogEvent),
390 partialFailure: Schema.Option(Schema.Boolean),
391 error: Schema.Option(
392 Schema.Struct({
393 kind: ServerTraceDiagnosticsErrorKind,
394 message: TrimmedNonEmptyString,
395 }),
396 ),
397});
398export type ServerTraceDiagnosticsResult = typeof ServerTraceDiagnosticsResult.Type;
399​
400export const ServerProcessSignal = Schema.Literals(["SIGINT", "SIGKILL"]);
401export type ServerProcessSignal = typeof ServerProcessSignal.Type;
402​
403export const ServerProcessDiagnosticsEntry = Schema.Struct({
404 pid: PositiveInt,
405 startTimeMs: NonNegativeInt,
406 ppid: NonNegativeInt,
407 pgid: Schema.Option(Schema.Int),
408 status: TrimmedNonEmptyString,
409 cpuPercent: Schema.Number,
410 rssBytes: NonNegativeInt,
411 elapsed: TrimmedNonEmptyString,
412 command: TrimmedNonEmptyString,
413 depth: NonNegativeInt,
414 childPids: Schema.Array(PositiveInt),
415});
416export type ServerProcessDiagnosticsEntry = typeof ServerProcessDiagnosticsEntry.Type;
417​
418export const ServerProcessDiagnosticsResult = Schema.Struct({
419 serverPid: PositiveInt,
420 readAt: Schema.DateTimeUtc,
421 processCount: NonNegativeInt,
422 totalRssBytes: NonNegativeInt,
423 totalCpuPercent: Schema.Number,
424 processes: Schema.Array(ServerProcessDiagnosticsEntry),
425 error: Schema.Option(
426 Schema.Struct({
427 message: TrimmedNonEmptyString,
428 }),
429 ),
430});
431export type ServerProcessDiagnosticsResult = typeof ServerProcessDiagnosticsResult.Type;
432​
433export const ServerProcessResourceHistoryInput = Schema.Struct({
434 windowMs: NonNegativeInt,
435 bucketMs: NonNegativeInt,
436});
437export type ServerProcessResourceHistoryInput = typeof ServerProcessResourceHistoryInput.Type;
438​
439export const ServerProcessResourceHistoryBucket = Schema.Struct({
440 startedAt: Schema.DateTimeUtc,
441 endedAt: Schema.DateTimeUtc,
442 avgCpuPercent: Schema.Number,
443 maxCpuPercent: Schema.Number,
444 maxRssBytes: NonNegativeInt,
445 maxProcessCount: NonNegativeInt,
446});
447export type ServerProcessResourceHistoryBucket = typeof ServerProcessResourceHistoryBucket.Type;
448​
449export const ServerProcessResourceHistorySummary = Schema.Struct({
450 processKey: TrimmedNonEmptyString,
451 pid: PositiveInt,
452 ppid: NonNegativeInt,
453 command: TrimmedNonEmptyString,
454 depth: NonNegativeInt,
455 isServerRoot: Schema.Boolean,
456 firstSeenAt: Schema.DateTimeUtc,
457 lastSeenAt: Schema.DateTimeUtc,
458 currentCpuPercent: Schema.Number,
459 avgCpuPercent: Schema.Number,
460 maxCpuPercent: Schema.Number,
461 cpuSecondsApprox: Schema.Number,
462 currentRssBytes: NonNegativeInt,
463 maxRssBytes: NonNegativeInt,
464 sampleCount: NonNegativeInt,
465});
466export type ServerProcessResourceHistorySummary = typeof ServerProcessResourceHistorySummary.Type;
467​
468export const ServerProcessResourceHistoryFailureTag = Schema.Literals([
469 "ProcessDiagnosticsQueryTimeoutError",
470 "ProcessDiagnosticsQueryFailedError",
471 "ProcessDiagnosticsServerProcessSignalError",
472 "ProcessDiagnosticsNotDescendantError",
473 "ProcessDiagnosticsSignalFailedError",
474]);
475export type ServerProcessResourceHistoryFailureTag =
476 typeof ServerProcessResourceHistoryFailureTag.Type;
477​
478export const ServerProcessResourceHistoryResult = Schema.Struct({
479 readAt: Schema.DateTimeUtc,
480 windowMs: NonNegativeInt,
481 bucketMs: NonNegativeInt,
482 sampleIntervalMs: NonNegativeInt,
483 retainedSampleCount: NonNegativeInt,
484 totalCpuSecondsApprox: Schema.Number,
485 buckets: Schema.Array(ServerProcessResourceHistoryBucket),
486 topProcesses: Schema.Array(ServerProcessResourceHistorySummary),
487 error: Schema.Option(
488 Schema.Struct({
489 failureTag: ServerProcessResourceHistoryFailureTag,
490 message: TrimmedNonEmptyString,
491 }),
492 ),
493});
494export type ServerProcessResourceHistoryResult = typeof ServerProcessResourceHistoryResult.Type;
495​
496export const ServerSignalProcessInput = Schema.Struct({
497 pid: PositiveInt,
498 startTimeMs: NonNegativeInt,
499 signal: ServerProcessSignal,
500});
501export type ServerSignalProcessInput = typeof ServerSignalProcessInput.Type;
502​
503export const ServerSignalProcessResult = Schema.Struct({
504 pid: PositiveInt,
505 signal: ServerProcessSignal,
506 signaled: Schema.Boolean,
507 message: Schema.Option(TrimmedNonEmptyString),
508});
509export type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;
510​
511export const EnvironmentThemeColor = Schema.String.check(
512 Schema.isPattern(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/),
513);
514export type EnvironmentThemeColor = typeof EnvironmentThemeColor.Type;
515​
516/** Reserve appearance keywords so published themes cannot replace stock preferences. */
517export const EnvironmentThemeId = Schema.String.check(
518 Schema.isPattern(/^(?!(?:system|light|dark)$)[a-z0-9](?:[a-z0-9-]{0,47})$/),
519);
520export type EnvironmentThemeId = typeof EnvironmentThemeId.Type;
521​
522const EnvironmentThemeColors = Schema.Record(
523 Schema.String.check(Schema.isPattern(/^[a-zA-Z][a-zA-Z0-9]{0,63}$/)),
524 TrimmedNonEmptyString.check(Schema.isMaxLength(64)),
525);
526​
527const environmentThemeFields = {
528 version: Schema.optional(Schema.Literal(1)),
529 name: TrimmedNonEmptyString.check(Schema.isMaxLength(48)),
530 appearance: Schema.Literals(["light", "dark"]),
531 /** Derive the palette from canvas/accent, then overlay colors; without them, colors is the palette. */
532 canvas: Schema.optional(EnvironmentThemeColor),
533 accent: Schema.optional(EnvironmentThemeColor),
534 colors: Schema.optional(EnvironmentThemeColors),
535 variants: Schema.optional(
536 Schema.Struct({
537 light: Schema.optional(EnvironmentThemeColors),
538 dark: Schema.optional(EnvironmentThemeColors),
539 }),
540 ),
541};
542​
543export const EnvironmentThemeFile = Schema.Struct(environmentThemeFields);
544export type EnvironmentThemeFile = typeof EnvironmentThemeFile.Type;
545​
546export const EnvironmentTheme = Schema.Struct({
547 id: EnvironmentThemeId,
548 ...environmentThemeFields,
549});
550export type EnvironmentTheme = typeof EnvironmentTheme.Type;
551​
552export function environmentThemeFileHasColors(file: EnvironmentThemeFile): boolean {
553 return (
554 (file.canvas !== undefined && file.accent !== undefined) ||
555 (file.colors !== undefined && Object.keys(file.colors).length > 0)
556 );
558​
559/** tailnet means this machine's Tailscale interface; other private addresses are lan. */
560export const ServerDirectEndpointKind = Schema.Literals(["lan", "tailnet"]);
561export type ServerDirectEndpointKind = typeof ServerDirectEndpointKind.Type;
562​
563export const ServerDirectEndpoint = Schema.Struct({
564 kind: ServerDirectEndpointKind,
565 httpBaseUrl: TrimmedNonEmptyString,
566});
567export type ServerDirectEndpoint = typeof ServerDirectEndpoint.Type;
568​
569/**
570 * A stretch where the server's event loop could not run, so it answered
571 * nothing and clients may have dropped the connection.
572 */
573export const ServerEventLoopStall = Schema.Struct({
574 detectedAt: IsoDateTime,
575 durationMs: NonNegativeInt,
576 /** One-minute load average when the stall was seen. Absent on Windows, which has none. */
577 loadAverage: Schema.optionalKey(Schema.Number),
578 cpuCount: PositiveInt,
579});
580export type ServerEventLoopStall = typeof ServerEventLoopStall.Type;
581​
582export const ServerConfig = Schema.Struct({
583 environment: ExecutionEnvironmentDescriptor,
584 auth: ServerAuthDescriptor,
585 cwd: TrimmedNonEmptyString,
586 keybindingsConfigPath: TrimmedNonEmptyString,
587 keybindings: ResolvedKeybindingsConfig,
588 issues: ServerConfigIssues,
589 providers: ServerProviders,
590 availableEditors: ForwardCompatibleArray(EditorId),
591 remoteOpenTargets: Schema.optionalKey(ForwardCompatibleArray(RemoteOpenTarget)),
592 /** Hints only; verify each address answers as this environment. */
593 directEndpoints: Schema.optionalKey(ForwardCompatibleArray(ServerDirectEndpoint)),
594 observability: ServerObservability,
595 settings: ServerSettings,
596 shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
597 /**
598 * The shell can leave idle subagent children out of snapshots (`omitIdleSubagents`), and
599 * `getThreadFamily` and `getWorktreeThreadIds` serve the rows it leaves out.
600 */
601 shellThreadFamilies: Schema.optionalKey(Schema.Boolean),
602 /**
603 * The shell can leave older settled threads out of snapshots (`omitOlderSettled`), and
604 * `getOlderSettledThreads` serves them. Only servers that also advertise `shellThreadFamilies`.
605 */
606 shellOlderSettled: Schema.optionalKey(Schema.Boolean),
607 shellRevealInFileManager: Schema.optionalKey(Schema.Boolean),
608 shellRevealInFileManagerKind: Schema.optionalKey(FileManagerRevealKind),
609 threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
610 /** Send window fields only when advertised. */
611 threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),
612 reasoningMessages: Schema.optionalKey(Schema.Boolean),
613 threadFind: Schema.optionalKey(Schema.Boolean),
614 threadFindProgressive: Schema.optionalKey(Schema.Boolean),
615 scratchWorkspaceRoot: Schema.optionalKey(TrimmedNonEmptyString),
616 newProjectsRoot: Schema.optionalKey(TrimmedNonEmptyString),
617 /**
618 * The latest stall long enough to notice, sent only for a few minutes after
619 * it. A client that reconnects reads it to say why the host stopped
620 * answering. Clients do not cache it, since it describes the host at connect.
621 */
622 lastEventLoopStall: Schema.optionalKey(ServerEventLoopStall),
623 /**
624 * Never sent in a config snapshot: the theme stream emits the current set
625 * before any change, so a snapshot carrying it too would hand every
626 * subscriber the same array twice per connect.
627 */
628 environmentThemes: Schema.optional(Schema.Array(EnvironmentTheme)),
629 /** Stream-only and opt-in; the source stream emits the current set on subscribe. */
630 usageLimitSources: Schema.optional(UsageLimitSourceSnapshots),
631});
632export type ServerConfig = typeof ServerConfig.Type;
633​
634export function resolveEnvironmentMachineKind(
635 config: {
636 readonly environment: Pick<ExecutionEnvironmentDescriptor, "platform">;
637 readonly settings?: Pick<ServerSettings, "environmentIcon">;
638 } | null,
639): EnvironmentMachineKind {
640 return config?.settings?.environmentIcon ?? config?.environment.platform.machine ?? "server";
642​
643const ServerUpsertKeybindingReplaceTarget = Schema.Struct({
644 key: KeybindingValue,
645 command: KeybindingCommand,
646 when: Schema.optional(KeybindingWhen),
647});
648​
649export const ServerUpsertKeybindingInput = Schema.Struct({
650 key: KeybindingValue,
651 command: KeybindingCommand,
652 when: Schema.optional(KeybindingWhen),
653 replace: Schema.optional(ServerUpsertKeybindingReplaceTarget),
654});
655export type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;
656​
657export const ServerRemoveKeybindingInput = ServerUpsertKeybindingReplaceTarget;
658export type ServerRemoveKeybindingInput = typeof ServerRemoveKeybindingInput.Type;
659​
660export const ServerUpsertKeybindingResult = Schema.Struct({
661 keybindings: ResolvedKeybindingsConfig,
662 issues: ServerConfigIssues,
663});
664export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.Type;
665​
666export const ServerRemoveKeybindingResult = ServerUpsertKeybindingResult;
667export type ServerRemoveKeybindingResult = typeof ServerRemoveKeybindingResult.Type;
668​
669export const ServerConfigUpdatedPayload = Schema.Struct({
670 issues: ServerConfigIssues,
671 providers: ServerProviders,
672 settings: Schema.optional(ServerSettings),
673});
674export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
675​
676export const ServerConfigKeybindingsUpdatedPayload = Schema.Struct({
677 keybindings: ResolvedKeybindingsConfig,
678 issues: ServerConfigIssues,
679});
680export type ServerConfigKeybindingsUpdatedPayload =
681 typeof ServerConfigKeybindingsUpdatedPayload.Type;
682​
683export const ServerConfigProviderStatusesPayload = Schema.Struct({
684 providers: ServerProviders,
685});
686export type ServerConfigProviderStatusesPayload = typeof ServerConfigProviderStatusesPayload.Type;
687​
688export const ServerConfigSettingsUpdatedPayload = Schema.Struct({
689 settings: ServerSettings,
690});
691export type ServerConfigSettingsUpdatedPayload = typeof ServerConfigSettingsUpdatedPayload.Type;
692​
693export const ServerConfigStreamSnapshotEvent = Schema.Struct({
694 version: Schema.Literal(1),
695 type: Schema.Literal("snapshot"),
696 config: ServerConfig,
697});
698export type ServerConfigStreamSnapshotEvent = typeof ServerConfigStreamSnapshotEvent.Type;
699​
700export const ServerConfigStreamKeybindingsUpdatedEvent = Schema.Struct({
701 version: Schema.Literal(1),
702 type: Schema.Literal("keybindingsUpdated"),
703 payload: ServerConfigKeybindingsUpdatedPayload,
704});
705export type ServerConfigStreamKeybindingsUpdatedEvent =
706 typeof ServerConfigStreamKeybindingsUpdatedEvent.Type;
707​
708export const ServerConfigStreamProviderStatusesEvent = Schema.Struct({
709 version: Schema.Literal(1),
710 type: Schema.Literal("providerStatuses"),
711 payload: ServerConfigProviderStatusesPayload,
712});
713export type ServerConfigStreamProviderStatusesEvent =
714 typeof ServerConfigStreamProviderStatusesEvent.Type;
715​
716export const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({
717 version: Schema.Literal(1),
718 type: Schema.Literal("settingsUpdated"),
719 payload: ServerConfigSettingsUpdatedPayload,
720});
721export type ServerConfigStreamSettingsUpdatedEvent =
722 typeof ServerConfigStreamSettingsUpdatedEvent.Type;
723​
724export const ServerConfigEnvironmentThemesUpdatedPayload = Schema.Struct({
725 themes: Schema.Array(EnvironmentTheme),
726});
727export type ServerConfigEnvironmentThemesUpdatedPayload =
728 typeof ServerConfigEnvironmentThemesUpdatedPayload.Type;
729​
730export const ServerConfigStreamEnvironmentThemesUpdatedEvent = Schema.Struct({
731 version: Schema.Literal(1),
732 type: Schema.Literal("environmentThemesUpdated"),
733 payload: ServerConfigEnvironmentThemesUpdatedPayload,
734});
735export type ServerConfigStreamEnvironmentThemesUpdatedEvent =
736 typeof ServerConfigStreamEnvironmentThemesUpdatedEvent.Type;
737​
738export const ServerConfigUsageLimitSourcesUpdatedPayload = Schema.Struct({
739 sources: UsageLimitSourceSnapshots,
740});
741export type ServerConfigUsageLimitSourcesUpdatedPayload =
742 typeof ServerConfigUsageLimitSourcesUpdatedPayload.Type;
743​
744export const ServerConfigStreamUsageLimitSourcesUpdatedEvent = Schema.Struct({
745 version: Schema.Literal(1),
746 type: Schema.Literal("usageLimitSourcesUpdated"),
747 payload: ServerConfigUsageLimitSourcesUpdatedPayload,
748});
749export type ServerConfigStreamUsageLimitSourcesUpdatedEvent =
750 typeof ServerConfigStreamUsageLimitSourcesUpdatedEvent.Type;
751​
752export const ServerConfigStreamEvent = Schema.Union([
753 ServerConfigStreamSnapshotEvent,
754 ServerConfigStreamKeybindingsUpdatedEvent,
755 ServerConfigStreamProviderStatusesEvent,
756 ServerConfigStreamSettingsUpdatedEvent,
757 ServerConfigStreamEnvironmentThemesUpdatedEvent,
758 ServerConfigStreamUsageLimitSourcesUpdatedEvent,
759]);
760export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;
761​
762export const ServerSelfUpdateOutcome = Schema.Struct({
763 id: TrimmedNonEmptyString,
764 fromVersion: TrimmedNonEmptyString,
765 targetVersion: TrimmedNonEmptyString,
766 status: Schema.Literals(["committed", "rolled-back", "failed"]),
767 reason: Schema.optionalKey(TrimmedNonEmptyString),
768});
769export type ServerSelfUpdateOutcome = typeof ServerSelfUpdateOutcome.Type;
770​
771export const ServerLifecycleReadyPayload = Schema.Struct({
772 at: IsoDateTime,
773 environment: ExecutionEnvironmentDescriptor,
774 updateOutcome: Schema.optionalKey(ServerSelfUpdateOutcome),
775});
776export type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type;
777​
778export const ServerLifecycleWelcomePayload = Schema.Struct({
779 environment: ExecutionEnvironmentDescriptor,
780 cwd: TrimmedNonEmptyString,
781 projectName: TrimmedNonEmptyString,
782 bootstrapStatus: Schema.optional(Schema.Literals(["pending", "complete"])),
783 bootstrapProjectId: Schema.optional(ProjectId),
784 bootstrapThreadId: Schema.optional(ThreadId),
785 bootstrapProjectCreated: Schema.optional(Schema.Boolean),
786 bootstrapThreadCreated: Schema.optional(Schema.Boolean),
787});
788export type ServerLifecycleWelcomePayload = typeof ServerLifecycleWelcomePayload.Type;
789​
790export const ServerLifecycleLegacyThreadMigrationPayload = Schema.Struct({
791 status: Schema.Union([Schema.Literal("running"), Schema.Literal("complete")]),
792 totalThreadCount: NonNegativeInt,
793});
794export type ServerLifecycleLegacyThreadMigrationPayload =
795 typeof ServerLifecycleLegacyThreadMigrationPayload.Type;
796​
797export const ServerLifecycleStreamWelcomeEvent = Schema.Struct({
798 version: Schema.Literal(1),
799 sequence: NonNegativeInt,
800 type: Schema.Literal("welcome"),
801 payload: ServerLifecycleWelcomePayload,
802});
803export type ServerLifecycleStreamWelcomeEvent = typeof ServerLifecycleStreamWelcomeEvent.Type;
804​
805export const ServerLifecycleStreamReadyEvent = Schema.Struct({
806 version: Schema.Literal(1),
807 sequence: NonNegativeInt,
808 type: Schema.Literal("ready"),
809 payload: ServerLifecycleReadyPayload,
810});
811export type ServerLifecycleStreamReadyEvent = typeof ServerLifecycleStreamReadyEvent.Type;
812​
813export const ServerLifecycleStreamLegacyThreadMigrationEvent = Schema.Struct({
814 version: Schema.Literal(1),
815 sequence: NonNegativeInt,
816 type: Schema.Literal("legacyThreadMigration"),
817 payload: ServerLifecycleLegacyThreadMigrationPayload,
818});
819export type ServerLifecycleStreamLegacyThreadMigrationEvent =
820 typeof ServerLifecycleStreamLegacyThreadMigrationEvent.Type;
821​
822export const ServerLifecycleStreamEvent = Schema.Union([
823 ServerLifecycleStreamWelcomeEvent,
824 ServerLifecycleStreamReadyEvent,
825 ServerLifecycleStreamLegacyThreadMigrationEvent,
826]);
827export type ServerLifecycleStreamEvent = typeof ServerLifecycleStreamEvent.Type;
828​
829export const ServerProviderUpdatedPayload = Schema.Struct({
830 providers: ServerProviders,
831});
832export type ServerProviderUpdatedPayload = typeof ServerProviderUpdatedPayload.Type;
833​
834export const ServerProviderUpdateInput = Schema.Struct({
835 provider: ProviderDriverKind,
836 targetVersion: Schema.optionalKey(TrimmedNonEmptyString),
837 instanceId: Schema.optionalKey(ProviderInstanceId),
838});
839export type ServerProviderUpdateInput = typeof ServerProviderUpdateInput.Type;
840​
841export class ServerProviderUpdateError extends Schema.TaggedError<ServerProviderUpdateError>()(
842 "ServerProviderUpdateError",
843 {
844 provider: ProviderDriverKind,
845 reason: TrimmedNonEmptyString,
846 cause: Schema.optional(Schema.Defect()),
847 },
848) {
849 override get message(): string {
850 return `Provider update failed for ${this.provider}: ${this.reason}`;
851 }
853​
854export const ServerSelfUpdateInput = Schema.Struct({
855 /** Exact npm version, never a dist-tag, so server and client agree on the request. */
856 targetVersion: TrimmedNonEmptyString,
857 continueRunningThreads: Schema.optionalKey(Schema.Boolean),
858});
859export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
860​
861export const ServerSelfUpdateResult = Schema.Struct({
862 targetVersion: TrimmedNonEmptyString,
863 method: ServerSelfUpdateMethod,
864 updateId: Schema.optionalKey(TrimmedNonEmptyString),
865 desktopUpdateToken: Schema.optionalKey(TrimmedNonEmptyString),
866});
867export type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;
868​
869export const DesktopUpdateCommitInput = Schema.Struct({
870 requestId: TrimmedNonEmptyString,
871});
872export type DesktopUpdateCommitInput = typeof DesktopUpdateCommitInput.Type;
873​
874export const ServerSelfUpdateProgressStage = Schema.Literals(["downloading", "installing"]);
875export type ServerSelfUpdateProgressStage = typeof ServerSelfUpdateProgressStage.Type;
876​
877export const ServerSelfUpdateProgressEvent = Schema.Union([
878 Schema.Struct({
879 type: Schema.Literal("progress"),
880 stage: ServerSelfUpdateProgressStage,
881 }),
882 Schema.Struct({
883 type: Schema.Literal("complete"),
884 result: ServerSelfUpdateResult,
885 }),
886]);
887export type ServerSelfUpdateProgressEvent = typeof ServerSelfUpdateProgressEvent.Type;
888​
889export class ServerSelfUpdateError extends Schema.TaggedError<ServerSelfUpdateError>()(
890 "ServerSelfUpdateError",
891 {
892 reason: TrimmedNonEmptyString,
893 cause: Schema.optional(Schema.Defect()),
894 },
895) {
896 override get message(): string {
897 return `Server update failed: ${this.reason}`;
898 }