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

server.ts

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