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