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

server.ts

1,136 lines45.5 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 { ManagedPolicySummary } from "./managedPolicy.ts";
27import { ModelCapabilities, ProviderOptionDescriptor } from "./model.ts";
28import { RuntimeMode } from "./providerPolicy.ts";
29import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
30import { ServerProviderUsageLimits, UsageLimitSourceSnapshots } from "./providerUsageLimits.ts";
31import { ServerSettings } from "./settings.ts";
32import { DesktopUpdateChannelSchema } from "./ipc.ts";
33​
34const KeybindingsMalformedConfigIssue = Schema.Struct({
35 kind: Schema.Literal("keybindings.malformed-config"),
36 message: TrimmedNonEmptyString,
37});
38​
39const KeybindingsInvalidEntryIssue = Schema.Struct({
40 kind: Schema.Literal("keybindings.invalid-entry"),
41 message: TrimmedNonEmptyString,
42 index: Schema.Number,
43});
44​
45export const ServerConfigIssue = Schema.Union([
46 KeybindingsMalformedConfigIssue,
47 KeybindingsInvalidEntryIssue,
48]);
49export type ServerConfigIssue = typeof ServerConfigIssue.Type;
50​
51const ServerConfigIssues = ForwardCompatibleArray(ServerConfigIssue);
52​
53export const ServerProviderState = Schema.Literals(["ready", "warning", "error", "disabled"]);
54export type ServerProviderState = typeof ServerProviderState.Type;
55​
56export const ServerProviderAuthStatus = Schema.Literals([
57 "authenticated",
58 "unauthenticated",
59 "unknown",
60]);
61export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
62​
63export const ServerProviderAuth = Schema.Struct({
64 status: ServerProviderAuthStatus,
65 type: Schema.optional(TrimmedNonEmptyString),
66 label: Schema.optional(TrimmedNonEmptyString),
67 email: Schema.optional(TrimmedNonEmptyString),
68 action: Schema.optional(AcpRegistryUrlAuthAction),
69 canLogout: Schema.optional(Schema.Boolean),
70 subscriptionSharing: Schema.optional(Schema.Boolean),
71 profileId: Schema.optional(TrimmedNonEmptyString),
72 workspaceId: Schema.optional(TrimmedNonEmptyString),
73 /** Origin of the custom endpoint the instance sends its requests to. */
74 endpoint: Schema.optional(TrimmedNonEmptyString),
75});
76export type ServerProviderAuth = typeof ServerProviderAuth.Type;
77​
78export const ServerProviderModel = Schema.Struct({
79 slug: TrimmedNonEmptyString,
80 name: TrimmedNonEmptyString,
81 shortName: Schema.optional(TrimmedNonEmptyString),
82 subProvider: Schema.optional(TrimmedNonEmptyString),
83 aliases: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
84 badge: Schema.optional(Schema.Literal("new")),
85 isCustom: Schema.Boolean,
86 isDefault: Schema.optional(Schema.Boolean),
87 isLegacy: Schema.optional(Schema.Boolean),
88 // False when the provider can run this model in sessions but not for
89 // application text generation. Absent means supported.
90 supportsTextGeneration: Schema.optional(Schema.Boolean),
91 capabilities: Schema.NullOr(ModelCapabilities),
92});
93export type ServerProviderModel = typeof ServerProviderModel.Type;
94​
95/** A backend a provider's models run on, such as one of fx's. */
96export const ServerProviderSubProvider = Schema.Struct({
97 name: TrimmedNonEmptyString,
98 /** Why none of its models can run now, such as a signed-out backend. */
99 unavailableReason: Schema.optional(TrimmedNonEmptyString),
100});
101export type ServerProviderSubProvider = typeof ServerProviderSubProvider.Type;
102​
103export const ServerProviderUpdateRequiredModel = Schema.Struct({
104 slug: TrimmedNonEmptyString,
105 name: TrimmedNonEmptyString,
106 badge: Schema.optional(Schema.Literal("new")),
107 minVersion: TrimmedNonEmptyString,
108});
109export type ServerProviderUpdateRequiredModel = typeof ServerProviderUpdateRequiredModel.Type;
110​
111export const ServerProviderSlashCommandInput = Schema.Struct({
112 hint: TrimmedNonEmptyString,
113});
114export type ServerProviderSlashCommandInput = typeof ServerProviderSlashCommandInput.Type;
115​
116export const ServerProviderSlashCommand = Schema.Struct({
117 name: TrimmedNonEmptyString,
118 description: Schema.optional(TrimmedNonEmptyString),
119 input: Schema.optional(ServerProviderSlashCommandInput),
120});
121export type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type;
122​
123export const ServerProviderSkill = Schema.Struct({
124 name: TrimmedNonEmptyString,
125 description: Schema.optional(TrimmedNonEmptyString),
126 path: TrimmedNonEmptyString,
127 scope: Schema.optional(TrimmedNonEmptyString),
128 enabled: Schema.Boolean,
129 displayName: Schema.optional(TrimmedNonEmptyString),
130 shortDescription: Schema.optional(TrimmedNonEmptyString),
131 /** Claude disable-model-invocation: only users can invoke; composers must offer a slash command. */
132 userInvocationOnly: Schema.optional(Schema.Boolean),
133 /** Claude user-invocable:false: only agents can invoke; composers must hide the slash command. */
134 userInvocable: Schema.optional(Schema.Boolean),
135});
136export type ServerProviderSkill = typeof ServerProviderSkill.Type;
137​
138export const ServerProviderWorkspaceSnapshot = Schema.Struct({
139 cwd: TrimmedNonEmptyString,
140 checkedAt: IsoDateTime,
141 slashCommands: Schema.Array(ServerProviderSlashCommand),
142 slashCommandsPending: Schema.optional(Schema.Boolean),
143 skills: Schema.Array(ServerProviderSkill),
144 optionDescriptors: Schema.optional(Schema.Array(ProviderOptionDescriptor)),
145 // Absent means the provider's machine `models`, which keeps most snapshots small.
146 models: Schema.optional(Schema.Array(ServerProviderModel)),
147 modelsPending: Schema.optional(Schema.Boolean),
148});
149export type ServerProviderWorkspaceSnapshot = typeof ServerProviderWorkspaceSnapshot.Type;
150​
151export const PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS = 5 * 60_000;
152​
153export function isProviderWorkspaceSnapshotCurrent(
154 snapshot: Pick<ServerProviderWorkspaceSnapshot, "checkedAt">,
155 nowMs: number,
156): boolean {
157 return nowMs - Date.parse(snapshot.checkedAt) < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS;
159​
160/** A pending snapshot keeps what it found before and is rescanned before its TTL. */
161export function isProviderWorkspaceSnapshotPending(
162 snapshot: Pick<ServerProviderWorkspaceSnapshot, "slashCommandsPending" | "modelsPending">,
163): boolean {
164 return snapshot.slashCommandsPending === true || snapshot.modelsPending === true;
166​
167/** Whose settings keep a provider from running a mode; "settings" when the source is not known. */
168export const ProviderRuntimeModeLimitReason = Schema.Literals([
169 "managed-settings",
170 "user-settings",
171 "project-settings",
172 "settings",
173]);
174export type ProviderRuntimeModeLimitReason = typeof ProviderRuntimeModeLimitReason.Type;
175​
176/**
177 * A mode a provider offers that cannot run in one folder. The mode stays selectable by every
178 * caller; clients show it as unavailable with the reason.
179 */
180export const ProviderRuntimeModeLimit = Schema.Struct({
181 mode: RuntimeMode,
182 reason: ProviderRuntimeModeLimitReason,
183});
184export type ProviderRuntimeModeLimit = typeof ProviderRuntimeModeLimit.Type;
185​
186export const ProviderRuntimeModeLimitsInput = Schema.Struct({
187 instanceId: ProviderInstanceId,
188 cwd: TrimmedNonEmptyString,
189});
190export const ProviderRuntimeModeLimitsResult = Schema.Struct({
191 limits: ForwardCompatibleArray(ProviderRuntimeModeLimit),
192});
193export type ProviderRuntimeModeLimitsResult = typeof ProviderRuntimeModeLimitsResult.Type;
194​
195/** Unavailable snapshots must set installed and enabled false. */
196export const ServerProviderAvailability = Schema.Literals(["available", "unavailable"]);
197export type ServerProviderAvailability = typeof ServerProviderAvailability.Type;
198​
199export const ServerProviderContinuation = Schema.Struct({
200 groupKey: TrimmedNonEmptyString,
201});
202export type ServerProviderContinuation = typeof ServerProviderContinuation.Type;
203​
204export const ServerProviderCompatibilityStatus = Schema.Literals([
205 "unknown",
206 "supported",
207 "graceful",
208 "unsupported",
209 "broken",
210]);
211export const ServerProviderCompatibilityAdvisory = Schema.Struct({
212 status: ServerProviderCompatibilityStatus,
213 latestVersionStatus: Schema.optionalKey(ServerProviderCompatibilityStatus),
214 message: Schema.NullOr(TrimmedNonEmptyString),
215 recommendedVersion: Schema.NullOr(TrimmedNonEmptyString),
216 recommendedRange: Schema.NullOr(TrimmedNonEmptyString),
217});
218export type ServerProviderCompatibilityAdvisory = typeof ServerProviderCompatibilityAdvisory.Type;
219​
220export const ServerProviderVersionAdvisoryStatus = Schema.Literals([
221 "unknown",
222 "current",
223 "behind_latest",
224]);
225export type ServerProviderVersionAdvisoryStatus = typeof ServerProviderVersionAdvisoryStatus.Type;
226​
227export const ServerProviderVersionAdvisory = Schema.Struct({
228 status: ServerProviderVersionAdvisoryStatus,
229 currentVersion: Schema.NullOr(TrimmedNonEmptyString),
230 latestVersion: Schema.NullOr(TrimmedNonEmptyString),
231 updateCommand: Schema.NullOr(TrimmedNonEmptyString),
232 canUpdate: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
233 canInstallVersion: Schema.optionalKey(Schema.Boolean),
234 checkedAt: Schema.NullOr(IsoDateTime),
235 message: Schema.NullOr(TrimmedNonEmptyString),
236});
237export type ServerProviderVersionAdvisory = typeof ServerProviderVersionAdvisory.Type;
238​
239export const ServerProviderUpdateStatus = Schema.Literals([
240 "idle",
241 "queued",
242 "running",
243 "succeeded",
244 "failed",
245 "unchanged",
246]);
247export type ServerProviderUpdateStatus = typeof ServerProviderUpdateStatus.Type;
248​
249export const ServerProviderUpdateState = Schema.Struct({
250 status: ServerProviderUpdateStatus,
251 startedAt: Schema.NullOr(IsoDateTime),
252 finishedAt: Schema.NullOr(IsoDateTime),
253 message: Schema.NullOr(TrimmedNonEmptyString),
254 output: Schema.NullOr(Schema.String.check(Schema.isMaxLength(10_000))),
255});
256export type ServerProviderUpdateState = typeof ServerProviderUpdateState.Type;
257​
258export const ServerProvider = Schema.Struct({
259 // Only instanceId is stable enough for provider routing.
260 instanceId: ProviderInstanceId,
261 driver: ProviderDriverKind,
262 displayName: Schema.optional(TrimmedNonEmptyString),
263 accentColor: Schema.optional(TrimmedNonEmptyString),
264 // Validate driver-supplied remote icons against the driver's trusted origin.
265 iconUrl: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(2_048))),
266 badgeLabel: Schema.optional(TrimmedNonEmptyString),
267 continuation: Schema.optional(ServerProviderContinuation),
268 showInteractionModeToggle: Schema.optional(Schema.Boolean),
269 reportsContextWindow: Schema.optional(Schema.Boolean),
270 supportedRuntimeModes: Schema.optional(ForwardCompatibleArray(RuntimeMode)),
271 supportsConversationRollback: Schema.optional(Schema.Boolean),
272 supportsTextGeneration: Schema.optional(Schema.Boolean),
273 setup: Schema.optional(
274 Schema.Struct({
275 canAuthenticate: Schema.Boolean,
276 canInstall: Schema.Boolean,
277 documentationUrl: Schema.optionalKey(TrimmedNonEmptyString.check(Schema.isMaxLength(2_048))),
278 }),
279 ),
280 nativeSessions: Schema.optional(
281 Schema.Struct({
282 canList: Schema.Boolean,
283 canLoad: Schema.Boolean,
284 canResume: Schema.Boolean,
285 canDelete: Schema.optional(Schema.Boolean),
286 }),
287 ),
288 configurableProviders: Schema.optional(Schema.Boolean),
289 runtimePaths: Schema.optionalKey(
290 Schema.Struct({
291 homePath: TrimmedNonEmptyString,
292 shadowHomePath: Schema.NullOr(TrimmedNonEmptyString),
293 }),
294 ),
295 enabled: Schema.Boolean,
296 installed: Schema.Boolean,
297 version: Schema.NullOr(TrimmedNonEmptyString),
298 // Version reported by the installed CLI for a local provider with a separate
299 // server. Null means unknown; absence keeps legacy snapshots on `version`.
300 installedVersion: Schema.optionalKey(Schema.NullOr(TrimmedNonEmptyString)),
301 status: ServerProviderState,
302 auth: ServerProviderAuth,
303 checkedAt: IsoDateTime,
304 message: Schema.optional(TrimmedNonEmptyString),
305 availability: Schema.optional(ServerProviderAvailability),
306 unavailableReason: Schema.optional(TrimmedNonEmptyString),
307 models: Schema.Array(ServerProviderModel),
308 // Pickers group `models` under these, in order, by `subProvider`.
309 subProviders: Schema.optional(Schema.Array(ServerProviderSubProvider)),
310 // Set for the one failed check that follows a ready one: pickers keep offering `models`.
311 modelsRetained: Schema.optionalKey(Schema.Boolean),
312 // Kept apart from `models` so clients that predate it never offer them.
313 updateRequiredModels: Schema.optionalKey(Schema.Array(ServerProviderUpdateRequiredModel)),
314 slashCommands: Schema.Array(ServerProviderSlashCommand).pipe(
315 Schema.withDecodingDefault(Effect.succeed([])),
316 ),
317 skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
318 workspaceSnapshots: Schema.optionalKey(Schema.Array(ServerProviderWorkspaceSnapshot)),
319 /**
320 * Set when the server rescanned a workspace after a session start and its skills or commands
321 * changed. Clients holding fetched workspace snapshots for this provider fetch them again.
322 */
323 workspaceRescannedAt: Schema.optionalKey(IsoDateTime),
324 usageLimits: Schema.optional(ServerProviderUsageLimits),
325 versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory),
326 compatibilityAdvisory: Schema.optionalKey(ServerProviderCompatibilityAdvisory),
327 updateState: Schema.optionalKey(ServerProviderUpdateState),
328 /**
329 * Stands for the machine slash commands and skills, which are then left out. Sent to clients
330 * that ask for catalog digests; they load both lists with their next cwd snapshot.
331 */
332 catalogDigest: Schema.optionalKey(TrimmedNonEmptyString),
333 /** Set by the client, never sent: the `catalogDigest` its slash commands and skills belong to. */
334 loadedCatalogDigest: Schema.optionalKey(TrimmedNonEmptyString),
335});
336export type ServerProvider = typeof ServerProvider.Type;
337​
338/** A provider without the lists that equal the ones its reader already holds. */
339export const ServerProviderDelta = ServerProvider.mapFields((fields) => ({
340 ...fields,
341 models: Schema.optionalKey(fields.models),
342 // Declared again without the decoding default, which would read as a change to an empty list.
343 slashCommands: Schema.optionalKey(Schema.Array(ServerProviderSlashCommand)),
344 skills: Schema.optionalKey(Schema.Array(ServerProviderSkill)),
345}));
346export type ServerProviderDelta = typeof ServerProviderDelta.Type;
347​
348const sameJson = (left: unknown, right: unknown) =>
349 left === right || JSON.stringify(left) === JSON.stringify(right);
350​
351/** Leaves each provider's models, slash commands, and skills out when `previous` has the same. */
352export function serverProviderDeltas(
353 previous: ReadonlyArray<ServerProvider>,
354 next: ReadonlyArray<ServerProvider>,
355): ServerProviderDelta[] {
356 const held = new Map(previous.map((provider) => [provider.instanceId, provider]));
357 return next.map((provider) => {
358 const base = held.get(provider.instanceId);
359 if (base === undefined) return provider;
360 const { models, slashCommands, skills, ...rest } = provider;
361 return {
362 ...rest,
363 ...(sameJson(base.models, models) ? {} : { models }),
364 ...(sameJson(base.slashCommands, slashCommands) ? {} : { slashCommands }),
365 ...(sameJson(base.skills, skills) ? {} : { skills }),
366 };
367 });
369​
370/** Rebuilds the provider list `serverProviderDeltas` was made from. */
371export function applyServerProviderDeltas(
372 previous: ReadonlyArray<ServerProvider>,
373 deltas: ReadonlyArray<ServerProviderDelta>,
374): ServerProvider[] {
375 const held = new Map(previous.map((provider) => [provider.instanceId, provider]));
376 return deltas.flatMap((delta) => {
377 const base = held.get(delta.instanceId);
378 const models = delta.models ?? base?.models;
379 const slashCommands = delta.slashCommands ?? base?.slashCommands;
380 const skills = delta.skills ?? base?.skills;
381 // A list this reader never held cannot be rebuilt; drop the provider like an unreadable one.
382 return models && slashCommands && skills ? [{ ...delta, models, slashCommands, skills }] : [];
383 });
385​
386export const ServerProviders = ForwardCompatibleArray(ServerProvider);
387export type ServerProviders = typeof ServerProviders.Type;
388​
389export const isProviderAvailable = (snapshot: ServerProvider): boolean =>
390 snapshot.availability !== "unavailable";
391​
392/** Legacy producers omit this field and support text generation. */
393export const isProviderTextGenerationCapable = (snapshot: ServerProvider): boolean =>
394 snapshot.supportsTextGeneration !== false;
395​
396export const OtlpEndpointSource = Schema.Literals(["environment", "bootstrap", "settings"]);
397export type OtlpEndpointSource = typeof OtlpEndpointSource.Type;
398​
399export const ServerObservability = Schema.Struct({
400 logsDirectoryPath: TrimmedNonEmptyString,
401 localTracingEnabled: Schema.Boolean,
402 otlpTracesUrl: Schema.optional(TrimmedNonEmptyString),
403 otlpTracesSource: Schema.optional(OtlpEndpointSource),
404 otlpTracesVariable: Schema.optional(TrimmedNonEmptyString),
405 otlpTracesEnabled: Schema.Boolean,
406 otlpMetricsUrl: Schema.optional(TrimmedNonEmptyString),
407 otlpMetricsSource: Schema.optional(OtlpEndpointSource),
408 otlpMetricsVariable: Schema.optional(TrimmedNonEmptyString),
409 otlpMetricsEnabled: Schema.Boolean,
410 otlpLogsUrl: Schema.optional(TrimmedNonEmptyString),
411 otlpLogsSource: Schema.optional(OtlpEndpointSource),
412 otlpLogsVariable: Schema.optional(TrimmedNonEmptyString),
413 otlpLogsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
414 /** Relay tracing policy for browsers opened from this server. */
415 relayTracingAllowed: Schema.optionalKey(Schema.Boolean),
416});
417export type ServerObservability = typeof ServerObservability.Type;
418​
419export const OtlpSignal = Schema.Literals(["traces", "metrics", "logs"]);
420export type OtlpSignal = typeof OtlpSignal.Type;
421​
422export const OtlpEndpointCheckInput = Schema.Struct({
423 signal: OtlpSignal,
424 url: TrimmedNonEmptyString.check(Schema.isPattern(/^https?:\/\/./i)),
425});
426export type OtlpEndpointCheckInput = typeof OtlpEndpointCheckInput.Type;
427​
428export const OtlpEndpointCheckResult = Schema.Union([
429 Schema.TaggedStruct("Accepted", { latencyMs: Schema.Number }),
430 Schema.TaggedStruct("Rejected", { status: Schema.Number }),
431 Schema.TaggedStruct("Unreachable", { timedOut: Schema.Boolean }),
432]);
433export type OtlpEndpointCheckResult = typeof OtlpEndpointCheckResult.Type;
434​
435/** The client tells the server what it is, so the triage context can name it. */
436export const ServerPrepareTriageInput = Schema.Struct({
437 client: AuthClientPresentationMetadata,
438});
439export type ServerPrepareTriageInput = typeof ServerPrepareTriageInput.Type;
440​
441export const ServerPrepareTriageResult = Schema.Struct({
442 /** Composer text that links the session's prompt file. */
443 prompt: Schema.String,
444});
445export type ServerPrepareTriageResult = typeof ServerPrepareTriageResult.Type;
446​
447/**
448 * The prompt file links as a chip in the user's message; clients spot a triage
449 * draft by it.
450 */
451export const TRIAGE_PROMPT_FILE_NAME = "triage-playbook.md";
452​
453export class ServerPrepareTriageError extends Schema.TaggedError<ServerPrepareTriageError>()(
454 "ServerPrepareTriageError",
455 { cause: Schema.optional(Schema.Defect()) },
456) {
457 override get message(): string {
458 return "Could not write the triage session files.";
459 }
461​
462export const ServerTraceDiagnosticsErrorKind = Schema.Literals([
463 "trace-file-not-found",
464 "trace-file-read-failed",
465]);
466export type ServerTraceDiagnosticsErrorKind = typeof ServerTraceDiagnosticsErrorKind.Type;
467​
468export const ServerTraceDiagnosticsSpanSummary = Schema.Struct({
469 name: TrimmedNonEmptyString,
470 count: NonNegativeInt,
471 failureCount: NonNegativeInt,
472 totalDurationMs: Schema.Number,
473 averageDurationMs: Schema.Number,
474 maxDurationMs: Schema.Number,
475});
476export type ServerTraceDiagnosticsSpanSummary = typeof ServerTraceDiagnosticsSpanSummary.Type;
477​
478export const ServerTraceDiagnosticsFailureSummary = Schema.Struct({
479 name: TrimmedNonEmptyString,
480 cause: TrimmedNonEmptyString,
481 count: NonNegativeInt,
482 lastSeenAt: Schema.DateTimeUtc,
483 traceId: TrimmedNonEmptyString,
484 spanId: TrimmedNonEmptyString,
485});
486export type ServerTraceDiagnosticsFailureSummary = typeof ServerTraceDiagnosticsFailureSummary.Type;
487​
488export const ServerTraceDiagnosticsRecentFailure = Schema.Struct({
489 name: TrimmedNonEmptyString,
490 cause: TrimmedNonEmptyString,
491 durationMs: Schema.Number,
492 endedAt: Schema.DateTimeUtc,
493 traceId: TrimmedNonEmptyString,
494 spanId: TrimmedNonEmptyString,
495});
496export type ServerTraceDiagnosticsRecentFailure = typeof ServerTraceDiagnosticsRecentFailure.Type;
497​
498export const ServerTraceDiagnosticsSpanOccurrence = Schema.Struct({
499 name: TrimmedNonEmptyString,
500 durationMs: Schema.Number,
501 endedAt: Schema.DateTimeUtc,
502 traceId: TrimmedNonEmptyString,
503 spanId: TrimmedNonEmptyString,
504});
505export type ServerTraceDiagnosticsSpanOccurrence = typeof ServerTraceDiagnosticsSpanOccurrence.Type;
506​
507export const ServerTraceDiagnosticsLogEvent = Schema.Struct({
508 spanName: TrimmedNonEmptyString,
509 level: TrimmedNonEmptyString,
510 message: TrimmedNonEmptyString,
511 seenAt: Schema.DateTimeUtc,
512 traceId: TrimmedNonEmptyString,
513 spanId: TrimmedNonEmptyString,
514});
515export type ServerTraceDiagnosticsLogEvent = typeof ServerTraceDiagnosticsLogEvent.Type;
516​
517export const ServerTraceDiagnosticsResult = Schema.Struct({
518 traceFilePath: TrimmedNonEmptyString,
519 scannedFilePaths: Schema.Array(TrimmedNonEmptyString),
520 readAt: Schema.DateTimeUtc,
521 recordCount: NonNegativeInt,
522 parseErrorCount: NonNegativeInt,
523 firstSpanAt: Schema.Option(Schema.DateTimeUtc),
524 lastSpanAt: Schema.Option(Schema.DateTimeUtc),
525 failureCount: NonNegativeInt,
526 interruptionCount: NonNegativeInt,
527 slowSpanThresholdMs: NonNegativeInt,
528 slowSpanCount: NonNegativeInt,
529 logLevelCounts: Schema.Record(TrimmedNonEmptyString, NonNegativeInt),
530 topSpansByCount: Schema.Array(ServerTraceDiagnosticsSpanSummary),
531 slowestSpans: Schema.Array(ServerTraceDiagnosticsSpanOccurrence),
532 commonFailures: Schema.Array(ServerTraceDiagnosticsFailureSummary),
533 latestFailures: Schema.Array(ServerTraceDiagnosticsRecentFailure),
534 latestWarningAndErrorLogs: Schema.Array(ServerTraceDiagnosticsLogEvent),
535 partialFailure: Schema.Option(Schema.Boolean),
536 error: Schema.Option(
537 Schema.Struct({
538 kind: ServerTraceDiagnosticsErrorKind,
539 message: TrimmedNonEmptyString,
540 }),
541 ),
542});
543export type ServerTraceDiagnosticsResult = typeof ServerTraceDiagnosticsResult.Type;
544​
545export const ServerProcessSignal = Schema.Literals(["SIGINT", "SIGKILL"]);
546export type ServerProcessSignal = typeof ServerProcessSignal.Type;
547​
548export const ServerProcessDiagnosticsEntry = Schema.Struct({
549 pid: PositiveInt,
550 startTimeMs: NonNegativeInt,
551 ppid: NonNegativeInt,
552 pgid: Schema.Option(Schema.Int),
553 status: TrimmedNonEmptyString,
554 cpuPercent: Schema.Number,
555 rssBytes: NonNegativeInt,
556 elapsed: TrimmedNonEmptyString,
557 command: TrimmedNonEmptyString,
558 depth: NonNegativeInt,
559 childPids: Schema.Array(PositiveInt),
560});
561export type ServerProcessDiagnosticsEntry = typeof ServerProcessDiagnosticsEntry.Type;
562​
563export const ServerProcessDiagnosticsResult = Schema.Struct({
564 serverPid: PositiveInt,
565 readAt: Schema.DateTimeUtc,
566 processCount: NonNegativeInt,
567 totalRssBytes: NonNegativeInt,
568 totalCpuPercent: Schema.Number,
569 processes: Schema.Array(ServerProcessDiagnosticsEntry),
570 error: Schema.Option(
571 Schema.Struct({
572 message: TrimmedNonEmptyString,
573 }),
574 ),
575});
576export type ServerProcessDiagnosticsResult = typeof ServerProcessDiagnosticsResult.Type;
577​
578export const ServerProcessResourceHistoryInput = Schema.Struct({
579 windowMs: NonNegativeInt,
580 bucketMs: NonNegativeInt,
581});
582export type ServerProcessResourceHistoryInput = typeof ServerProcessResourceHistoryInput.Type;
583​
584export const ServerProcessResourceHistoryBucket = Schema.Struct({
585 startedAt: Schema.DateTimeUtc,
586 endedAt: Schema.DateTimeUtc,
587 avgCpuPercent: Schema.Number,
588 maxCpuPercent: Schema.Number,
589 maxRssBytes: NonNegativeInt,
590 maxProcessCount: NonNegativeInt,
591});
592export type ServerProcessResourceHistoryBucket = typeof ServerProcessResourceHistoryBucket.Type;
593​
594export const ServerProcessResourceHistorySummary = Schema.Struct({
595 processKey: TrimmedNonEmptyString,
596 pid: PositiveInt,
597 ppid: NonNegativeInt,
598 command: TrimmedNonEmptyString,
599 depth: NonNegativeInt,
600 isServerRoot: Schema.Boolean,
601 firstSeenAt: Schema.DateTimeUtc,
602 lastSeenAt: Schema.DateTimeUtc,
603 currentCpuPercent: Schema.Number,
604 avgCpuPercent: Schema.Number,
605 maxCpuPercent: Schema.Number,
606 cpuSecondsApprox: Schema.Number,
607 currentRssBytes: NonNegativeInt,
608 maxRssBytes: NonNegativeInt,
609 sampleCount: NonNegativeInt,
610});
611export type ServerProcessResourceHistorySummary = typeof ServerProcessResourceHistorySummary.Type;
612​
613export const ServerProcessResourceHistoryFailureTag = Schema.Literals([
614 "ProcessDiagnosticsQueryTimeoutError",
615 "ProcessDiagnosticsQueryFailedError",
616 "ProcessDiagnosticsServerProcessSignalError",
617 "ProcessDiagnosticsNotDescendantError",
618 "ProcessDiagnosticsSignalFailedError",
619]);
620export type ServerProcessResourceHistoryFailureTag =
621 typeof ServerProcessResourceHistoryFailureTag.Type;
622​
623export const ServerProcessResourceHistoryResult = Schema.Struct({
624 readAt: Schema.DateTimeUtc,
625 windowMs: NonNegativeInt,
626 bucketMs: NonNegativeInt,
627 sampleIntervalMs: NonNegativeInt,
628 retainedSampleCount: NonNegativeInt,
629 totalCpuSecondsApprox: Schema.Number,
630 buckets: Schema.Array(ServerProcessResourceHistoryBucket),
631 topProcesses: Schema.Array(ServerProcessResourceHistorySummary),
632 error: Schema.Option(
633 Schema.Struct({
634 failureTag: ServerProcessResourceHistoryFailureTag,
635 message: TrimmedNonEmptyString,
636 }),
637 ),
638});
639export type ServerProcessResourceHistoryResult = typeof ServerProcessResourceHistoryResult.Type;
640​
641export const ServerSignalProcessInput = Schema.Struct({
642 pid: PositiveInt,
643 startTimeMs: NonNegativeInt,
644 signal: ServerProcessSignal,
645});
646export type ServerSignalProcessInput = typeof ServerSignalProcessInput.Type;
647​
648export const ServerSignalProcessResult = Schema.Struct({
649 pid: PositiveInt,
650 signal: ServerProcessSignal,
651 signaled: Schema.Boolean,
652 message: Schema.Option(TrimmedNonEmptyString),
653});
654export type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;
655​
656export const EnvironmentThemeColor = Schema.String.check(
657 Schema.isPattern(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/),
658);
659export type EnvironmentThemeColor = typeof EnvironmentThemeColor.Type;
660​
661/** Reserve appearance keywords so published themes cannot replace stock preferences. */
662export const EnvironmentThemeId = Schema.String.check(
663 Schema.isPattern(/^(?!(?:system|light|dark)$)[a-z0-9](?:[a-z0-9-]{0,47})$/),
664);
665export type EnvironmentThemeId = typeof EnvironmentThemeId.Type;
666​
667const EnvironmentThemeColors = Schema.Record(
668 Schema.String.check(Schema.isPattern(/^[a-zA-Z][a-zA-Z0-9]{0,63}$/)),
669 TrimmedNonEmptyString.check(Schema.isMaxLength(64)),
670);
671​
672export const THEME_CSS_MAX_LENGTH = 100_000;
673​
674const environmentThemeFields = {
675 version: Schema.optional(Schema.Literal(1)),
676 name: TrimmedNonEmptyString.check(Schema.isMaxLength(48)),
677 appearance: Schema.Literals(["light", "dark"]),
678 /** Derive the palette from canvas/accent, then overlay colors; without them, colors is the palette. */
679 canvas: Schema.optional(EnvironmentThemeColor),
680 accent: Schema.optional(EnvironmentThemeColor),
681 colors: Schema.optional(EnvironmentThemeColors),
682 variants: Schema.optional(
683 Schema.Struct({
684 light: Schema.optional(EnvironmentThemeColors),
685 dark: Schema.optional(EnvironmentThemeColors),
686 }),
687 ),
688 /** Custom styles for web and desktop clients. */
689 css: Schema.optional(Schema.String.check(Schema.isMaxLength(THEME_CSS_MAX_LENGTH))),
690};
691​
692export const EnvironmentThemeFile = Schema.Struct(environmentThemeFields);
693export type EnvironmentThemeFile = typeof EnvironmentThemeFile.Type;
694​
695export const EnvironmentTheme = Schema.Struct({
696 id: EnvironmentThemeId,
697 ...environmentThemeFields,
698 /** Revision of the image file published beside the theme; absent without one. */
699 background: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(64))),
700});
701export type EnvironmentTheme = typeof EnvironmentTheme.Type;
702​
703export function environmentThemeFileHasColors(file: EnvironmentThemeFile): boolean {
704 return (
705 (file.canvas !== undefined && file.accent !== undefined) ||
706 (file.colors !== undefined && Object.keys(file.colors).length > 0)
707 );
709​
710/** tailnet means this machine's Tailscale interface; other private addresses are lan. */
711export const ServerDirectEndpointKind = Schema.Literals(["lan", "tailnet"]);
712export type ServerDirectEndpointKind = typeof ServerDirectEndpointKind.Type;
713​
714export const ServerDirectEndpoint = Schema.Struct({
715 kind: ServerDirectEndpointKind,
716 httpBaseUrl: TrimmedNonEmptyString,
717});
718export type ServerDirectEndpoint = typeof ServerDirectEndpoint.Type;
719​
720/**
721 * A stretch where the server's event loop could not run, so it answered
722 * nothing and clients may have dropped the connection.
723 */
724export const ServerEventLoopStall = Schema.Struct({
725 detectedAt: IsoDateTime,
726 durationMs: NonNegativeInt,
727 /** One-minute load average when the stall was seen. Absent on Windows, which has none. */
728 loadAverage: Schema.optionalKey(Schema.Number),
729 cpuCount: PositiveInt,
730});
731export type ServerEventLoopStall = typeof ServerEventLoopStall.Type;
732​
733/** The boolean `T3CODE_FEATURE_FLAGS` a server started with. Unset flags are off. */
734export const ServerFeatureFlags = Schema.Struct({
735 secretProviders: Schema.optionalKey(Schema.Boolean),
736 tanstackSource: Schema.optionalKey(Schema.Boolean),
737});
738export type ServerFeatureFlags = typeof ServerFeatureFlags.Type;
739​
740export const ServerConfig = Schema.Struct({
741 environment: ExecutionEnvironmentDescriptor,
742 auth: ServerAuthDescriptor,
743 cwd: TrimmedNonEmptyString,
744 /** The machine's own name, which file URIs from its shells may carry. Older servers omit it. */
745 hostname: Schema.optionalKey(Schema.String),
746 keybindingsConfigPath: TrimmedNonEmptyString,
747 keybindings: ResolvedKeybindingsConfig,
748 issues: ServerConfigIssues,
749 providers: ServerProviders,
750 availableEditors: ForwardCompatibleArray(EditorId),
751 remoteOpenTargets: Schema.optionalKey(ForwardCompatibleArray(RemoteOpenTarget)),
752 /** Hints only; verify each address answers as this environment. */
753 directEndpoints: Schema.optionalKey(ForwardCompatibleArray(ServerDirectEndpoint)),
754 observability: ServerObservability,
755 settings: ServerSettings,
756 /** Present when an administrator's policy file manages this environment. */
757 managedPolicy: Schema.optionalKey(ManagedPolicySummary),
758 shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
759 /**
760 * The shell can leave idle subagent children out of snapshots (`omitIdleSubagents`), and
761 * `getThreadFamily` and `getWorktreeThreadIds` serve the rows it leaves out.
762 */
763 shellThreadFamilies: Schema.optionalKey(Schema.Boolean),
764 threadLinkMetadata: Schema.optionalKey(Schema.Boolean),
765 /**
766 * The shell can leave older settled threads out of snapshots (`omitOlderSettled`), and
767 * `getOlderSettledThreads` serves them. Only servers that also advertise `shellThreadFamilies`.
768 */
769 shellOlderSettled: Schema.optionalKey(Schema.Boolean),
770 shellRevealInFileManager: Schema.optionalKey(Schema.Boolean),
771 shellRevealInFileManagerKind: Schema.optionalKey(FileManagerRevealKind),
772 threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
773 /** Send window fields only when advertised. */
774 threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),
775 threadFind: Schema.optionalKey(Schema.Boolean),
776 threadFindProgressive: Schema.optionalKey(Schema.Boolean),
777 featureFlags: Schema.optionalKey(ServerFeatureFlags),
778 /** Settings patches may carry `secretProviders`; older servers drop the key without an error. */
779 secretProviderSettings: Schema.optionalKey(Schema.Boolean),
780 /** Secret settings may point at a secret provider; older servers drop the reference. */
781 secretReferences: Schema.optionalKey(Schema.Boolean),
782 /** A secret request card may be answered with a secret provider reference. */
783 secretRequestReferences: Schema.optionalKey(Schema.Boolean),
784 scratchWorkspaceRoot: Schema.optionalKey(TrimmedNonEmptyString),
785 newProjectsRoot: Schema.optionalKey(TrimmedNonEmptyString),
786 /**
787 * The latest stall long enough to notice, sent only for a few minutes after
788 * it. A client that reconnects reads it to say why the host stopped
789 * answering. Clients do not cache it, since it describes the host at connect.
790 */
791 lastEventLoopStall: Schema.optionalKey(ServerEventLoopStall),
792 /**
793 * The host's clock when it built the config, so clients can count live
794 * elapsed times against host timestamps despite clock skew. Only a
795 * subscription's first snapshot is fresh; later snapshots may repeat it.
796 */
797 serverTime: Schema.optionalKey(IsoDateTime),
798 /**
799 * Never sent in a config snapshot: the theme stream emits the current set
800 * before any change, so a snapshot carrying it too would hand every
801 * subscriber the same array twice per connect.
802 */
803 environmentThemes: Schema.optional(Schema.Array(EnvironmentTheme)),
804 /** Stream-only and opt-in; the source stream emits the current set on subscribe. */
805 usageLimitSources: Schema.optional(UsageLimitSourceSnapshots),
806});
807export type ServerConfig = typeof ServerConfig.Type;
808​
809export function resolveEnvironmentMachineKind(
810 config: {
811 readonly environment: Pick<ExecutionEnvironmentDescriptor, "platform">;
812 readonly settings?: Pick<ServerSettings, "environmentIcon">;
813 } | null,
814): EnvironmentMachineKind {
815 return config?.settings?.environmentIcon ?? config?.environment.platform.machine ?? "server";
817​
818const ServerUpsertKeybindingReplaceTarget = Schema.Struct({
819 key: KeybindingValue,
820 command: KeybindingCommand,
821 when: Schema.optional(KeybindingWhen),
822});
823​
824export const ServerUpsertKeybindingInput = Schema.Struct({
825 key: KeybindingValue,
826 command: KeybindingCommand,
827 when: Schema.optional(KeybindingWhen),
828 replace: Schema.optional(ServerUpsertKeybindingReplaceTarget),
829});
830export type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;
831​
832export const ServerRemoveKeybindingInput = ServerUpsertKeybindingReplaceTarget;
833export type ServerRemoveKeybindingInput = typeof ServerRemoveKeybindingInput.Type;
834​
835export const ServerUpsertKeybindingResult = Schema.Struct({
836 keybindings: ResolvedKeybindingsConfig,
837 issues: ServerConfigIssues,
838});
839export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.Type;
840​
841export const ServerRemoveKeybindingResult = ServerUpsertKeybindingResult;
842export type ServerRemoveKeybindingResult = typeof ServerRemoveKeybindingResult.Type;
843​
844export const ServerConfigUpdatedPayload = Schema.Struct({
845 issues: ServerConfigIssues,
846 providers: ServerProviders,
847 settings: Schema.optional(ServerSettings),
848});
849export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
850​
851export const ServerConfigKeybindingsUpdatedPayload = Schema.Struct({
852 keybindings: ResolvedKeybindingsConfig,
853 issues: ServerConfigIssues,
854});
855export type ServerConfigKeybindingsUpdatedPayload =
856 typeof ServerConfigKeybindingsUpdatedPayload.Type;
857​
858export const ServerConfigProviderStatusesPayload = Schema.Struct({
859 providers: ServerProviders,
860});
861export type ServerConfigProviderStatusesPayload = typeof ServerConfigProviderStatusesPayload.Type;
862​
863export const ServerConfigProviderStatusDeltasPayload = Schema.Struct({
864 /** Every provider in order, as `serverProviderDeltas` from the list this client last received. */
865 providers: ForwardCompatibleArray(ServerProviderDelta),
866});
867export type ServerConfigProviderStatusDeltasPayload =
868 typeof ServerConfigProviderStatusDeltasPayload.Type;
869​
870export const ServerConfigSettingsUpdatedPayload = Schema.Struct({
871 settings: ServerSettings,
872});
873export type ServerConfigSettingsUpdatedPayload = typeof ServerConfigSettingsUpdatedPayload.Type;
874​
875export const ServerConfigStreamSnapshotEvent = Schema.Struct({
876 version: Schema.Literal(1),
877 type: Schema.Literal("snapshot"),
878 config: ServerConfig,
879});
880export type ServerConfigStreamSnapshotEvent = typeof ServerConfigStreamSnapshotEvent.Type;
881​
882export const ServerConfigStreamKeybindingsUpdatedEvent = Schema.Struct({
883 version: Schema.Literal(1),
884 type: Schema.Literal("keybindingsUpdated"),
885 payload: ServerConfigKeybindingsUpdatedPayload,
886});
887export type ServerConfigStreamKeybindingsUpdatedEvent =
888 typeof ServerConfigStreamKeybindingsUpdatedEvent.Type;
889​
890export const ServerConfigStreamProviderStatusesEvent = Schema.Struct({
891 version: Schema.Literal(1),
892 type: Schema.Literal("providerStatuses"),
893 payload: ServerConfigProviderStatusesPayload,
894});
895export type ServerConfigStreamProviderStatusesEvent =
896 typeof ServerConfigStreamProviderStatusesEvent.Type;
897​
898export const ServerConfigStreamProviderStatusDeltasEvent = Schema.Struct({
899 version: Schema.Literal(1),
900 type: Schema.Literal("providerStatusDeltas"),
901 payload: ServerConfigProviderStatusDeltasPayload,
902});
903export type ServerConfigStreamProviderStatusDeltasEvent =
904 typeof ServerConfigStreamProviderStatusDeltasEvent.Type;
905​
906export const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({
907 version: Schema.Literal(1),
908 type: Schema.Literal("settingsUpdated"),
909 payload: ServerConfigSettingsUpdatedPayload,
910});
911export type ServerConfigStreamSettingsUpdatedEvent =
912 typeof ServerConfigStreamSettingsUpdatedEvent.Type;
913​
914export const ServerConfigEnvironmentThemesUpdatedPayload = Schema.Struct({
915 themes: Schema.Array(EnvironmentTheme),
916});
917export type ServerConfigEnvironmentThemesUpdatedPayload =
918 typeof ServerConfigEnvironmentThemesUpdatedPayload.Type;
919​
920export const ServerConfigStreamEnvironmentThemesUpdatedEvent = Schema.Struct({
921 version: Schema.Literal(1),
922 type: Schema.Literal("environmentThemesUpdated"),
923 payload: ServerConfigEnvironmentThemesUpdatedPayload,
924});
925export type ServerConfigStreamEnvironmentThemesUpdatedEvent =
926 typeof ServerConfigStreamEnvironmentThemesUpdatedEvent.Type;
927​
928export const ServerConfigUsageLimitSourcesUpdatedPayload = Schema.Struct({
929 sources: UsageLimitSourceSnapshots,
930});
931export type ServerConfigUsageLimitSourcesUpdatedPayload =
932 typeof ServerConfigUsageLimitSourcesUpdatedPayload.Type;
933​
934export const ServerConfigStreamUsageLimitSourcesUpdatedEvent = Schema.Struct({
935 version: Schema.Literal(1),
936 type: Schema.Literal("usageLimitSourcesUpdated"),
937 payload: ServerConfigUsageLimitSourcesUpdatedPayload,
938});
939export type ServerConfigStreamUsageLimitSourcesUpdatedEvent =
940 typeof ServerConfigStreamUsageLimitSourcesUpdatedEvent.Type;
941​
942export const ServerConfigStreamEvent = Schema.Union([
943 ServerConfigStreamSnapshotEvent,
944 ServerConfigStreamKeybindingsUpdatedEvent,
945 ServerConfigStreamProviderStatusesEvent,
946 ServerConfigStreamProviderStatusDeltasEvent,
947 ServerConfigStreamSettingsUpdatedEvent,
948 ServerConfigStreamEnvironmentThemesUpdatedEvent,
949 ServerConfigStreamUsageLimitSourcesUpdatedEvent,
950]);
951export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;
952​
953export const ServerSelfUpdateOutcome = Schema.Struct({
954 id: TrimmedNonEmptyString,
955 fromVersion: TrimmedNonEmptyString,
956 targetVersion: TrimmedNonEmptyString,
957 status: Schema.Literals(["committed", "rolled-back", "failed"]),
958 reason: Schema.optionalKey(TrimmedNonEmptyString),
959});
960export type ServerSelfUpdateOutcome = typeof ServerSelfUpdateOutcome.Type;
961​
962export const ServerLifecycleReadyPayload = Schema.Struct({
963 at: IsoDateTime,
964 environment: ExecutionEnvironmentDescriptor,
965 updateOutcome: Schema.optionalKey(ServerSelfUpdateOutcome),
966});
967export type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type;
968​
969export const ServerLifecycleWelcomePayload = Schema.Struct({
970 environment: ExecutionEnvironmentDescriptor,
971 cwd: TrimmedNonEmptyString,
972 projectName: TrimmedNonEmptyString,
973 bootstrapStatus: Schema.optional(Schema.Literals(["pending", "complete"])),
974 bootstrapProjectId: Schema.optional(ProjectId),
975 bootstrapThreadId: Schema.optional(ThreadId),
976 bootstrapProjectCreated: Schema.optional(Schema.Boolean),
977 bootstrapThreadCreated: Schema.optional(Schema.Boolean),
978});
979export type ServerLifecycleWelcomePayload = typeof ServerLifecycleWelcomePayload.Type;
980​
981export const ServerLifecycleLegacyThreadMigrationPayload = Schema.Struct({
982 status: Schema.Union([Schema.Literal("running"), Schema.Literal("complete")]),
983 totalThreadCount: NonNegativeInt,
984});
985export type ServerLifecycleLegacyThreadMigrationPayload =
986 typeof ServerLifecycleLegacyThreadMigrationPayload.Type;
987​
988export const ServerLifecycleStreamWelcomeEvent = Schema.Struct({
989 version: Schema.Literal(1),
990 sequence: NonNegativeInt,
991 type: Schema.Literal("welcome"),
992 payload: ServerLifecycleWelcomePayload,
993});
994export type ServerLifecycleStreamWelcomeEvent = typeof ServerLifecycleStreamWelcomeEvent.Type;
995​
996export const ServerLifecycleStreamReadyEvent = Schema.Struct({
997 version: Schema.Literal(1),
998 sequence: NonNegativeInt,
999 type: Schema.Literal("ready"),
1000 payload: ServerLifecycleReadyPayload,
1001});
1002export type ServerLifecycleStreamReadyEvent = typeof ServerLifecycleStreamReadyEvent.Type;
1003​
1004export const ServerLifecycleStreamLegacyThreadMigrationEvent = Schema.Struct({
1005 version: Schema.Literal(1),
1006 sequence: NonNegativeInt,
1007 type: Schema.Literal("legacyThreadMigration"),
1008 payload: ServerLifecycleLegacyThreadMigrationPayload,
1009});
1010export type ServerLifecycleStreamLegacyThreadMigrationEvent =
1011 typeof ServerLifecycleStreamLegacyThreadMigrationEvent.Type;
1012​
1013export const ServerLifecycleStreamEvent = Schema.Union([
1014 ServerLifecycleStreamWelcomeEvent,
1015 ServerLifecycleStreamReadyEvent,
1016 ServerLifecycleStreamLegacyThreadMigrationEvent,
1017]);
1018export type ServerLifecycleStreamEvent = typeof ServerLifecycleStreamEvent.Type;
1019​
1020export const ServerProviderUpdatedPayload = Schema.Struct({
1021 providers: ServerProviders,
1022});
1023export type ServerProviderUpdatedPayload = typeof ServerProviderUpdatedPayload.Type;
1024​
1025export const ServerProviderUpdateInput = Schema.Struct({
1026 provider: ProviderDriverKind,
1027 targetVersion: Schema.optionalKey(TrimmedNonEmptyString),
1028 instanceId: Schema.optionalKey(ProviderInstanceId),
1029});
1030export type ServerProviderUpdateInput = typeof ServerProviderUpdateInput.Type;
1031​
1032export class ServerProviderUpdateError extends Schema.TaggedError<ServerProviderUpdateError>()(
1033 "ServerProviderUpdateError",
1035 provider: ProviderDriverKind,
1036 reason: TrimmedNonEmptyString,
1037 cause: Schema.optional(Schema.Defect()),
1038 },
1039) {
1040 override get message(): string {
1041 return `Provider update failed for ${this.provider}: ${this.reason}`;
1044​
1045export const DatabaseMigrationProgress = Schema.Struct({
1046 current: Schema.Int.check(Schema.isGreaterThan(0)),
1047 total: Schema.Int.check(Schema.isGreaterThan(0)),
1048});
1049export type DatabaseMigrationProgress = typeof DatabaseMigrationProgress.Type;
1050​
1051export const ServerStartupStatus = Schema.Struct({
1052 status: Schema.Literal("starting"),
1053 migration: Schema.NullOr(DatabaseMigrationProgress),
1054});
1055export type ServerStartupStatus = typeof ServerStartupStatus.Type;
1056​
1057export const ServerNpmReleaseInput = Schema.Struct({
1058 spec: Schema.String.check(
1059 Schema.isMaxLength(64),
1060 Schema.isPattern(/^(?:latest|nightly|\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/),
1061 ),
1062});
1063export type ServerNpmReleaseInput = typeof ServerNpmReleaseInput.Type;
1064​
1065export const ServerNpmRelease = Schema.Struct({
1066 version: Schema.String,
1067 databaseMigration: Schema.optionalKey(Schema.Int),
1068});
1069export type ServerNpmRelease = typeof ServerNpmRelease.Type;
1070​
1071export class ServerNpmReleaseError extends Schema.TaggedError<ServerNpmReleaseError>()(
1072 "ServerNpmReleaseError",
1073 { reason: Schema.String },
1074) {
1075 override get message(): string {
1076 return `Could not check the configured npm registry: ${this.reason}`;
1079​
1080export const ServerSelfUpdateInput = Schema.Struct({
1081 /** Exact npm version, never a dist-tag, so server and client agree on the request. */
1082 targetVersion: TrimmedNonEmptyString,
1083 /** Desktop-managed hosts move their app to this update track first. Sent only for a track switch. */
1084 channel: Schema.optionalKey(DesktopUpdateChannelSchema),
1085 /** The target release's highest migration; the host refuses to leave Nightly without it. */
1086 targetDatabaseMigration: Schema.optionalKey(Schema.Int),
1087 stageOnly: Schema.optionalKey(Schema.Boolean),
1088});
1089export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
1090​
1091export const ServerSelfUpdateResult = Schema.Struct({
1092 targetVersion: TrimmedNonEmptyString,
1093 method: ServerSelfUpdateMethod,
1094 updateId: Schema.optionalKey(TrimmedNonEmptyString),
1095 desktopUpdateToken: Schema.optionalKey(TrimmedNonEmptyString),
1096});
1097export type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;
1098​
1099export const DesktopUpdateCommitInput = Schema.Struct({
1100 requestId: TrimmedNonEmptyString,
1101});
1102export type DesktopUpdateCommitInput = typeof DesktopUpdateCommitInput.Type;
1103​
1104export const ServerSelfUpdateProgressStage = Schema.Literals(["downloading", "installing"]);
1105export type ServerSelfUpdateProgressStage = typeof ServerSelfUpdateProgressStage.Type;
1106​
1107export const ServerSelfUpdateProgressEvent = Schema.Union([
1108 Schema.Struct({
1109 type: Schema.Literal("progress"),
1110 stage: ServerSelfUpdateProgressStage,
1111 }),
1112 Schema.Struct({
1113 type: Schema.Literal("complete"),
1114 result: ServerSelfUpdateResult,
1115 }),
1116]);
1117export type ServerSelfUpdateProgressEvent = typeof ServerSelfUpdateProgressEvent.Type;
1118​
1119export class ServerSelfUpdateError extends Schema.TaggedError<ServerSelfUpdateError>()(
1120 "ServerSelfUpdateError",
1122 reason: TrimmedNonEmptyString,
1123 /** Set when the host's desktop app refused only because its build and saved tracks differ. */
1124 trackMismatch: Schema.optionalKey(
1125 Schema.Struct({
1126 buildChannel: DesktopUpdateChannelSchema,
1127 savedChannel: DesktopUpdateChannelSchema,
1128 }),
1129 ),
1130 cause: Schema.optional(Schema.Defect()),
1131 },
1132) {
1133 override get message(): string {
1134 return `Server update failed: ${this.reason}`;