Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Schema from "effect/Schema";
3import {
4 type EnvironmentMachineKind,
5 ExecutionEnvironmentDescriptor,
6 ServerSelfUpdateMethod,
7} from "./environment.ts";
8import { ServerAuthDescriptor } from "./auth.ts";
9import {
10 ForwardCompatibleArray,
11 IsoDateTime,
12 NonNegativeInt,
13 PositiveInt,
14 ProjectId,
15 ThreadId,
16 TrimmedNonEmptyString,
17} from "./baseSchemas.ts";
18import {
19 KeybindingCommand,
20 KeybindingValue,
21 KeybindingWhen,
22 ResolvedKeybindingsConfig,
23} from "./keybindings.ts";
24import { EditorId, FileManagerRevealKind, RemoteOpenTarget } from "./editor.ts";
25import { ModelCapabilities } from "./model.ts";
26import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
27import { ServerProviderUsageLimits, UsageLimitSourceSnapshots } from "./providerUsageLimits.ts";
28import { ServerSettings } from "./settings.ts";
29
30const KeybindingsMalformedConfigIssue = Schema.Struct({
31 kind: Schema.Literal("keybindings.malformed-config"),
32 message: TrimmedNonEmptyString,
33});
34
35const KeybindingsInvalidEntryIssue = Schema.Struct({
36 kind: Schema.Literal("keybindings.invalid-entry"),
37 message: TrimmedNonEmptyString,
38 index: Schema.Number,
39});
40
41export const ServerConfigIssue = Schema.Union([
42 KeybindingsMalformedConfigIssue,
43 KeybindingsInvalidEntryIssue,
44]);
45export type ServerConfigIssue = typeof ServerConfigIssue.Type;
46
47// Issue kinds grow over time; older clients must not fail the whole config
48// decode over a kind they cannot render.
49const ServerConfigIssues = ForwardCompatibleArray(ServerConfigIssue);
50
51export const ServerProviderState = Schema.Literals(["ready", "warning", "error", "disabled"]);
52export type ServerProviderState = typeof ServerProviderState.Type;
53
54export const ServerProviderAuthStatus = Schema.Literals([
55 "authenticated",
56 "unauthenticated",
57 "unknown",
58]);
59export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
60
61export const ServerProviderAuth = Schema.Struct({
62 status: ServerProviderAuthStatus,
63 type: Schema.optional(TrimmedNonEmptyString),
64 label: Schema.optional(TrimmedNonEmptyString),
65 email: Schema.optional(TrimmedNonEmptyString),
66 subscriptionSharing: Schema.optional(Schema.Boolean),
67 profileId: Schema.optional(TrimmedNonEmptyString),
68});
69export type ServerProviderAuth = typeof ServerProviderAuth.Type;
70
71export const ServerProviderModel = Schema.Struct({
72 slug: TrimmedNonEmptyString,
73 name: TrimmedNonEmptyString,
74 shortName: Schema.optional(TrimmedNonEmptyString),
75 subProvider: Schema.optional(TrimmedNonEmptyString),
76 aliases: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
77 badge: Schema.optional(Schema.Literal("new")),
78 isCustom: Schema.Boolean,
79 isDefault: Schema.optional(Schema.Boolean),
80 isLegacy: Schema.optional(Schema.Boolean),
81 capabilities: Schema.NullOr(ModelCapabilities),
82});
83export type ServerProviderModel = typeof ServerProviderModel.Type;
84
85export const ServerProviderSlashCommandInput = Schema.Struct({
86 hint: TrimmedNonEmptyString,
87});
88export type ServerProviderSlashCommandInput = typeof ServerProviderSlashCommandInput.Type;
89
90export const ServerProviderSlashCommand = Schema.Struct({
91 name: TrimmedNonEmptyString,
92 description: Schema.optional(TrimmedNonEmptyString),
93 input: Schema.optional(ServerProviderSlashCommandInput),
94});
95export type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type;
96
97export const ServerProviderSkill = Schema.Struct({
98 name: TrimmedNonEmptyString,
99 description: Schema.optional(TrimmedNonEmptyString),
100 path: TrimmedNonEmptyString,
101 scope: Schema.optional(TrimmedNonEmptyString),
102 enabled: Schema.Boolean,
103 displayName: Schema.optional(TrimmedNonEmptyString),
104 shortDescription: Schema.optional(TrimmedNonEmptyString),
105 /**
106 * The skill is hidden from the agent's own skill tool, so only the user can
107 * start it — Claude Code's `disable-model-invocation`. Composers must offer
108 * it as a slash command; naming it in prose does nothing.
109 */
110 userInvocationOnly: Schema.optional(Schema.Boolean),
111 /**
112 * The mirror of {@link ServerProviderSkill.userInvocationOnly}: Claude Code's
113 * `user-invocable: false` keeps the skill out of its own slash commands, so
114 * only the agent can start it. Composers must not offer it under `/`.
115 */
116 userInvocable: Schema.optional(Schema.Boolean),
117});
118export type ServerProviderSkill = typeof ServerProviderSkill.Type;
119
120export const ServerProviderWorkspaceSnapshot = Schema.Struct({
121 cwd: TrimmedNonEmptyString,
122 checkedAt: IsoDateTime,
123 slashCommands: Schema.Array(ServerProviderSlashCommand),
124 skills: Schema.Array(ServerProviderSkill),
125});
126export type ServerProviderWorkspaceSnapshot = typeof ServerProviderWorkspaceSnapshot.Type;
127
128/**
129 * Availability of a configured provider instance from the runtime's POV.
130 *
131 * - `available` — the build ships this driver and an instance is wired
132 * up. Default for legacy snapshots produced from the closed
133 * `ServerSettings.providers` map.
134 * - `unavailable` — the user's `ServerSettings.providerInstances` (or a
135 * persisted thread / session binding) references a driver this build
136 * doesn't ship. Common after rolling back from a fork or PR branch
137 * that introduced a new driver. The snapshot is preserved so the UI
138 * can render "missing driver" affordances and so the data round-trips
139 * when the user moves back to the fork.
140 *
141 * Snapshots with `availability: "unavailable"` MUST set
142 * `installed: false` and `enabled: false`; the runtime refuses turn
143 * starts against them with a structured error.
144 */
145export const ServerProviderAvailability = Schema.Literals(["available", "unavailable"]);
146export type ServerProviderAvailability = typeof ServerProviderAvailability.Type;
147
148export const ServerProviderContinuation = Schema.Struct({
149 groupKey: TrimmedNonEmptyString,
150});
151export type ServerProviderContinuation = typeof ServerProviderContinuation.Type;
152
153export const ServerProviderCompatibilityStatus = Schema.Literals([
154 "unknown",
155 "supported",
156 "graceful",
157 "unsupported",
158 "broken",
159]);
160export const ServerProviderCompatibilityAdvisory = Schema.Struct({
161 status: ServerProviderCompatibilityStatus,
162 latestVersionStatus: Schema.optionalKey(ServerProviderCompatibilityStatus),
163 message: Schema.NullOr(TrimmedNonEmptyString),
164 recommendedVersion: Schema.NullOr(TrimmedNonEmptyString),
165 recommendedRange: Schema.NullOr(TrimmedNonEmptyString),
166});
167export type ServerProviderCompatibilityAdvisory = typeof ServerProviderCompatibilityAdvisory.Type;
168
169export const ServerProviderVersionAdvisoryStatus = Schema.Literals([
170 "unknown",
171 "current",
172 "behind_latest",
173]);
174export type ServerProviderVersionAdvisoryStatus = typeof ServerProviderVersionAdvisoryStatus.Type;
175
176export const ServerProviderVersionAdvisory = Schema.Struct({
177 status: ServerProviderVersionAdvisoryStatus,
178 currentVersion: Schema.NullOr(TrimmedNonEmptyString),
179 latestVersion: Schema.NullOr(TrimmedNonEmptyString),
180 updateCommand: Schema.NullOr(TrimmedNonEmptyString),
181 canUpdate: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
182 canInstallVersion: Schema.optionalKey(Schema.Boolean),
183 checkedAt: Schema.NullOr(IsoDateTime),
184 message: Schema.NullOr(TrimmedNonEmptyString),
185});
186export type ServerProviderVersionAdvisory = typeof ServerProviderVersionAdvisory.Type;
187
188export const ServerProviderUpdateStatus = Schema.Literals([
189 "idle",
190 "queued",
191 "running",
192 "succeeded",
193 "failed",
194 "unchanged",
195]);
196export type ServerProviderUpdateStatus = typeof ServerProviderUpdateStatus.Type;
197
198export const ServerProviderUpdateState = Schema.Struct({
199 status: ServerProviderUpdateStatus,
200 startedAt: Schema.NullOr(IsoDateTime),
201 finishedAt: Schema.NullOr(IsoDateTime),
202 message: Schema.NullOr(TrimmedNonEmptyString),
203 output: Schema.NullOr(Schema.String.check(Schema.isMaxLength(10_000))),
204});
205export type ServerProviderUpdateState = typeof ServerProviderUpdateState.Type;
206
207export const ServerProvider = Schema.Struct({
208 // Routing key for the configured instance this snapshot represents. This
209 // is the only stable identity consumers may use for provider routing.
210 instanceId: ProviderInstanceId,
211 // Open driver kind slug that selects the implementation handling this
212 // instance. It is metadata/capability context, not a routing key.
213 driver: ProviderDriverKind,
214 displayName: Schema.optional(TrimmedNonEmptyString),
215 accentColor: Schema.optional(TrimmedNonEmptyString),
216 badgeLabel: Schema.optional(TrimmedNonEmptyString),
217 continuation: Schema.optional(ServerProviderContinuation),
218 showInteractionModeToggle: Schema.optional(Schema.Boolean),
219 // The driver streams context window usage, so a started thread will have a
220 // meter once its activities load. Clients reserve the meter's space on it.
221 reportsContextWindow: Schema.optional(Schema.Boolean),
222 requiresNewThreadForModelChange: Schema.optional(Schema.Boolean),
223 supportsConversationRollback: Schema.optional(Schema.Boolean),
224 supportsTextGeneration: Schema.optional(Schema.Boolean),
225 setup: Schema.optional(
226 Schema.Struct({
227 canAuthenticate: Schema.Boolean,
228 canInstall: Schema.Boolean,
229 }),
230 ),
231 runtimePaths: Schema.optionalKey(
232 Schema.Struct({
233 homePath: TrimmedNonEmptyString,
234 shadowHomePath: Schema.NullOr(TrimmedNonEmptyString),
235 }),
236 ),
237 enabled: Schema.Boolean,
238 installed: Schema.Boolean,
239 version: Schema.NullOr(TrimmedNonEmptyString),
240 status: ServerProviderState,
241 auth: ServerProviderAuth,
242 checkedAt: IsoDateTime,
243 message: Schema.optional(TrimmedNonEmptyString),
244 // Optional for back-compat: every legacy producer omits this field and
245 // an absent value is interpreted as `"available"` by consumers (see
246 // `isProviderAvailable`). New `ProviderInstanceRegistry` outputs set it
247 // explicitly so the UI can render unavailable shadows from
248 // `ServerSettings.providerInstances`.
249 availability: Schema.optional(ServerProviderAvailability),
250 // Human-readable reason populated when `availability === "unavailable"`.
251 // Surfaces in the UI alongside the missing-driver affordance.
252 unavailableReason: Schema.optional(TrimmedNonEmptyString),
253 models: Schema.Array(ServerProviderModel),
254 slashCommands: Schema.Array(ServerProviderSlashCommand).pipe(
255 Schema.withDecodingDefault(Effect.succeed([])),
256 ),
257 skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
258 workspaceSnapshots: Schema.optionalKey(Schema.Array(ServerProviderWorkspaceSnapshot)),
259 // Absent when the driver has no notion of subscription usage.
260 usageLimits: Schema.optional(ServerProviderUsageLimits),
261 versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory),
262 compatibilityAdvisory: Schema.optionalKey(ServerProviderCompatibilityAdvisory),
263 updateState: Schema.optionalKey(ServerProviderUpdateState),
264});
265export type ServerProvider = typeof ServerProvider.Type;
266
267// Provider status kinds grow over time (ServerProviderState,
268// ServerProviderAuthStatus, ServerProviderVersionAdvisoryStatus,
269// ServerProviderUpdateStatus); an older client must not fail the whole config
270// decode over one provider it cannot render.
271export const ServerProviders = ForwardCompatibleArray(ServerProvider);
272export type ServerProviders = typeof ServerProviders.Type;
273
274/**
275 * Treat the optional `availability` as "available" when absent. This is
276 * the rule legacy producers (which omit the field) and new producers
277 * (which set it explicitly) agree on so consumers never have to thread
278 * `?? "available"` defaults through their code paths.
279 */
280export const isProviderAvailable = (snapshot: ServerProvider): boolean =>
281 snapshot.availability !== "unavailable";
282
283export const ServerObservability = Schema.Struct({
284 logsDirectoryPath: TrimmedNonEmptyString,
285 localTracingEnabled: Schema.Boolean,
286 otlpTracesUrl: Schema.optional(TrimmedNonEmptyString),
287 otlpTracesEnabled: Schema.Boolean,
288 otlpMetricsUrl: Schema.optional(TrimmedNonEmptyString),
289 otlpMetricsEnabled: Schema.Boolean,
290 otlpLogsUrl: Schema.optional(TrimmedNonEmptyString),
291 // Absent on servers from before the log signal shipped, so a newer client
292 // reads those as having no log export rather than rejecting the whole config.
293 otlpLogsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
294});
295export type ServerObservability = typeof ServerObservability.Type;
296
297export const ServerTraceDiagnosticsErrorKind = Schema.Literals([
298 "trace-file-not-found",
299 "trace-file-read-failed",
300]);
301export type ServerTraceDiagnosticsErrorKind = typeof ServerTraceDiagnosticsErrorKind.Type;
302
303export const ServerTraceDiagnosticsSpanSummary = Schema.Struct({
304 name: TrimmedNonEmptyString,
305 count: NonNegativeInt,
306 failureCount: NonNegativeInt,
307 totalDurationMs: Schema.Number,
308 averageDurationMs: Schema.Number,
309 maxDurationMs: Schema.Number,
310});
311export type ServerTraceDiagnosticsSpanSummary = typeof ServerTraceDiagnosticsSpanSummary.Type;
312
313export const ServerTraceDiagnosticsFailureSummary = Schema.Struct({
314 name: TrimmedNonEmptyString,
315 cause: TrimmedNonEmptyString,
316 count: NonNegativeInt,
317 lastSeenAt: Schema.DateTimeUtc,
318 traceId: TrimmedNonEmptyString,
319 spanId: TrimmedNonEmptyString,
320});
321export type ServerTraceDiagnosticsFailureSummary = typeof ServerTraceDiagnosticsFailureSummary.Type;
322
323export const ServerTraceDiagnosticsRecentFailure = Schema.Struct({
324 name: TrimmedNonEmptyString,
325 cause: TrimmedNonEmptyString,
326 durationMs: Schema.Number,
327 endedAt: Schema.DateTimeUtc,
328 traceId: TrimmedNonEmptyString,
329 spanId: TrimmedNonEmptyString,
330});
331export type ServerTraceDiagnosticsRecentFailure = typeof ServerTraceDiagnosticsRecentFailure.Type;
332
333export const ServerTraceDiagnosticsSpanOccurrence = Schema.Struct({
334 name: TrimmedNonEmptyString,
335 durationMs: Schema.Number,
336 endedAt: Schema.DateTimeUtc,
337 traceId: TrimmedNonEmptyString,
338 spanId: TrimmedNonEmptyString,
339});
340export type ServerTraceDiagnosticsSpanOccurrence = typeof ServerTraceDiagnosticsSpanOccurrence.Type;
341
342export const ServerTraceDiagnosticsLogEvent = Schema.Struct({
343 spanName: TrimmedNonEmptyString,
344 level: TrimmedNonEmptyString,
345 message: TrimmedNonEmptyString,
346 seenAt: Schema.DateTimeUtc,
347 traceId: TrimmedNonEmptyString,
348 spanId: TrimmedNonEmptyString,
349});
350export type ServerTraceDiagnosticsLogEvent = typeof ServerTraceDiagnosticsLogEvent.Type;
351
352export const ServerTraceDiagnosticsResult = Schema.Struct({
353 traceFilePath: TrimmedNonEmptyString,
354 scannedFilePaths: Schema.Array(TrimmedNonEmptyString),
355 readAt: Schema.DateTimeUtc,
356 recordCount: NonNegativeInt,
357 parseErrorCount: NonNegativeInt,
358 firstSpanAt: Schema.Option(Schema.DateTimeUtc),
359 lastSpanAt: Schema.Option(Schema.DateTimeUtc),
360 failureCount: NonNegativeInt,
361 interruptionCount: NonNegativeInt,
362 slowSpanThresholdMs: NonNegativeInt,
363 slowSpanCount: NonNegativeInt,
364 logLevelCounts: Schema.Record(TrimmedNonEmptyString, NonNegativeInt),
365 topSpansByCount: Schema.Array(ServerTraceDiagnosticsSpanSummary),
366 slowestSpans: Schema.Array(ServerTraceDiagnosticsSpanOccurrence),
367 commonFailures: Schema.Array(ServerTraceDiagnosticsFailureSummary),
368 latestFailures: Schema.Array(ServerTraceDiagnosticsRecentFailure),
369 latestWarningAndErrorLogs: Schema.Array(ServerTraceDiagnosticsLogEvent),
370 partialFailure: Schema.Option(Schema.Boolean),
371 error: Schema.Option(
372 Schema.Struct({
373 kind: ServerTraceDiagnosticsErrorKind,
374 message: TrimmedNonEmptyString,
375 }),
376 ),
377});
378export type ServerTraceDiagnosticsResult = typeof ServerTraceDiagnosticsResult.Type;
379
380export const ServerProcessSignal = Schema.Literals(["SIGINT", "SIGKILL"]);
381export type ServerProcessSignal = typeof ServerProcessSignal.Type;
382
383export const ServerProcessDiagnosticsEntry = Schema.Struct({
384 pid: PositiveInt,
385 startTimeMs: NonNegativeInt,
386 ppid: NonNegativeInt,
387 pgid: Schema.Option(Schema.Int),
388 status: TrimmedNonEmptyString,
389 cpuPercent: Schema.Number,
390 rssBytes: NonNegativeInt,
391 elapsed: TrimmedNonEmptyString,
392 command: TrimmedNonEmptyString,
393 depth: NonNegativeInt,
394 childPids: Schema.Array(PositiveInt),
395});
396export type ServerProcessDiagnosticsEntry = typeof ServerProcessDiagnosticsEntry.Type;
397
398export const ServerProcessDiagnosticsResult = Schema.Struct({
399 serverPid: PositiveInt,
400 readAt: Schema.DateTimeUtc,
401 processCount: NonNegativeInt,
402 totalRssBytes: NonNegativeInt,
403 totalCpuPercent: Schema.Number,
404 processes: Schema.Array(ServerProcessDiagnosticsEntry),
405 error: Schema.Option(
406 Schema.Struct({
407 message: TrimmedNonEmptyString,
408 }),
409 ),
410});
411export type ServerProcessDiagnosticsResult = typeof ServerProcessDiagnosticsResult.Type;
412
413export const ServerProcessResourceHistoryInput = Schema.Struct({
414 windowMs: NonNegativeInt,
415 bucketMs: NonNegativeInt,
416});
417export type ServerProcessResourceHistoryInput = typeof ServerProcessResourceHistoryInput.Type;
418
419export const ServerProcessResourceHistoryBucket = Schema.Struct({
420 startedAt: Schema.DateTimeUtc,
421 endedAt: Schema.DateTimeUtc,
422 avgCpuPercent: Schema.Number,
423 maxCpuPercent: Schema.Number,
424 maxRssBytes: NonNegativeInt,
425 maxProcessCount: NonNegativeInt,
426});
427export type ServerProcessResourceHistoryBucket = typeof ServerProcessResourceHistoryBucket.Type;
428
429export const ServerProcessResourceHistorySummary = Schema.Struct({
430 processKey: TrimmedNonEmptyString,
431 pid: PositiveInt,
432 ppid: NonNegativeInt,
433 command: TrimmedNonEmptyString,
434 depth: NonNegativeInt,
435 isServerRoot: Schema.Boolean,
436 firstSeenAt: Schema.DateTimeUtc,
437 lastSeenAt: Schema.DateTimeUtc,
438 currentCpuPercent: Schema.Number,
439 avgCpuPercent: Schema.Number,
440 maxCpuPercent: Schema.Number,
441 cpuSecondsApprox: Schema.Number,
442 currentRssBytes: NonNegativeInt,
443 maxRssBytes: NonNegativeInt,
444 sampleCount: NonNegativeInt,
445});
446export type ServerProcessResourceHistorySummary = typeof ServerProcessResourceHistorySummary.Type;
447
448export const ServerProcessResourceHistoryFailureTag = Schema.Literals([
449 "ProcessDiagnosticsQueryTimeoutError",
450 "ProcessDiagnosticsQueryFailedError",
451 "ProcessDiagnosticsServerProcessSignalError",
452 "ProcessDiagnosticsNotDescendantError",
453 "ProcessDiagnosticsSignalFailedError",
454]);
455export type ServerProcessResourceHistoryFailureTag =
456 typeof ServerProcessResourceHistoryFailureTag.Type;
457
458export const ServerProcessResourceHistoryResult = Schema.Struct({
459 readAt: Schema.DateTimeUtc,
460 windowMs: NonNegativeInt,
461 bucketMs: NonNegativeInt,
462 sampleIntervalMs: NonNegativeInt,
463 retainedSampleCount: NonNegativeInt,
464 totalCpuSecondsApprox: Schema.Number,
465 buckets: Schema.Array(ServerProcessResourceHistoryBucket),
466 topProcesses: Schema.Array(ServerProcessResourceHistorySummary),
467 error: Schema.Option(
468 Schema.Struct({
469 failureTag: ServerProcessResourceHistoryFailureTag,
470 message: TrimmedNonEmptyString,
471 }),
472 ),
473});
474export type ServerProcessResourceHistoryResult = typeof ServerProcessResourceHistoryResult.Type;
475
476export const ServerSignalProcessInput = Schema.Struct({
477 pid: PositiveInt,
478 startTimeMs: NonNegativeInt,
479 signal: ServerProcessSignal,
480});
481export type ServerSignalProcessInput = typeof ServerSignalProcessInput.Type;
482
483export const ServerSignalProcessResult = Schema.Struct({
484 pid: PositiveInt,
485 signal: ServerProcessSignal,
486 signaled: Schema.Boolean,
487 message: Schema.Option(TrimmedNonEmptyString),
488});
489export type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;
490
491/**
492 * A palette the environment's machine publishes for T3 Code to follow, read
493 * from a theme file next to the rest of the environment's state. Two seed
494 * colors rather than a full palette: clients derive the remaining roles with
495 * the same generator the guided theme editor uses, so a desktop theme carries
496 * over as a coherent T3 Code palette instead of a foreign one.
497 */
498export const EnvironmentThemeColor = Schema.String.check(
499 Schema.isPattern(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/),
500);
501export type EnvironmentThemeColor = typeof EnvironmentThemeColor.Type;
502
503/**
504 * Matches the client-side theme id rule, so a published id is selectable.
505 * The appearance keywords are excluded outright: a published `dark.json`
506 * would otherwise capture every client whose stored preference is the stock
507 * `"dark"`, retinting people who never chose it.
508 */
509export const EnvironmentThemeId = Schema.String.check(
510 Schema.isPattern(/^(?!(?:system|light|dark)$)[a-z0-9](?:[a-z0-9-]{0,47})$/),
511);
512export type EnvironmentThemeId = typeof EnvironmentThemeId.Type;
513
514/**
515 * Role colors as published. Values are any CSS color the client's theme
516 * parser accepts (exported theme files use oklch), canonicalized client-side;
517 * roles a build does not know are dropped there, so a machine may publish
518 * roles a newer client added without breaking an older one. Keys must still
519 * be role-shaped and values color-sized, so the record stays open to future
520 * vocabulary without being an arbitrary-payload channel.
521 */
522const EnvironmentThemeColors = Schema.Record(
523 Schema.String.check(Schema.isPattern(/^[a-zA-Z][a-zA-Z0-9]{0,63}$/)),
524 TrimmedNonEmptyString.check(Schema.isMaxLength(64)),
525);
526
527const environmentThemeFields = {
528 /**
529 * Standard exported theme files (the Download button's output) carry
530 * `version: 1`; the seeded short form a desktop generates has no version.
531 */
532 version: Schema.optional(Schema.Literal(1)),
533 /** Shown on the theme card, e.g. the desktop theme's own name. */
534 name: TrimmedNonEmptyString.check(Schema.isMaxLength(48)),
535 appearance: Schema.Literals(["light", "dark"]),
536 /**
537 * Seed colors. When present, clients derive the full palette from them with
538 * the guided theme editor's generator and layer `colors` on top; when
539 * absent, `colors` is the palette, as in an exported theme file.
540 */
541 canvas: Schema.optional(EnvironmentThemeColor),
542 accent: Schema.optional(EnvironmentThemeColor),
543 colors: Schema.optional(EnvironmentThemeColors),
544 /** The other appearance's palette, as exported theme files carry it. */
545 variants: Schema.optional(
546 Schema.Struct({
547 light: Schema.optional(EnvironmentThemeColors),
548 dark: Schema.optional(EnvironmentThemeColors),
549 }),
550 ),
551};
552
553/** One published theme file. The id is the filename, not part of the content,
554 * so a file cannot claim another file's identity; an embedded `id` is ignored. */
555export const EnvironmentThemeFile = Schema.Struct(environmentThemeFields);
556export type EnvironmentThemeFile = typeof EnvironmentThemeFile.Type;
557
558export const EnvironmentTheme = Schema.Struct({
559 /** The publishing filename without its extension, stable across recolors. */
560 id: EnvironmentThemeId,
561 ...environmentThemeFields,
562});
563export type EnvironmentTheme = typeof EnvironmentTheme.Type;
564
565/**
566 * Whether a theme file carries anything to render. A file with neither seeds
567 * nor colors would show as the stock palette wearing a name, which reads as a
568 * bug rather than a theme — the CLI and the server watcher both reject it,
569 * through this one predicate so they cannot drift.
570 */
571export function environmentThemeFileHasColors(file: EnvironmentThemeFile): boolean {
572 return (
573 (file.canvas !== undefined && file.accent !== undefined) ||
574 (file.colors !== undefined && Object.keys(file.colors).length > 0)
575 );
576}
577
578export const ServerConfig = Schema.Struct({
579 environment: ExecutionEnvironmentDescriptor,
580 auth: ServerAuthDescriptor,
581 cwd: TrimmedNonEmptyString,
582 keybindingsConfigPath: TrimmedNonEmptyString,
583 keybindings: ResolvedKeybindingsConfig,
584 issues: ServerConfigIssues,
585 providers: ServerProviders,
586 // Editor ids grow over time; drop ones this build does not know rather than
587 // failing the whole config decode.
588 availableEditors: ForwardCompatibleArray(EditorId),
589 /**
590 * SSH hosts this environment advertises for remote open-in-editor links.
591 * Absent on servers that predate the feature; empty when the machine has no
592 * sshd or no advertisable name.
593 */
594 remoteOpenTargets: Schema.optionalKey(ForwardCompatibleArray(RemoteOpenTarget)),
595 observability: ServerObservability,
596 settings: ServerSettings,
597 /** Whether shell subscriptions can emit an opt-in catch-up completion marker. */
598 shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
599 /** Whether shell.openInEditor honors `LaunchEditorInput.reveal` for the
600 file-manager editor. */
601 shellRevealInFileManager: Schema.optionalKey(Schema.Boolean),
602 /** File-manager wording clients should use for reveal actions. */
603 shellRevealInFileManagerKind: Schema.optionalKey(FileManagerRevealKind),
604 /** Whether thread subscriptions can emit an opt-in catch-up completion marker. */
605 threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
606 /**
607 * Whether thread detail reads accept a turn window (`turnLimit`/
608 * `beforeCursor`) and return `page` metadata. Clients must not send window
609 * fields to servers that don't advertise this.
610 */
611 threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),
612 /** Whether thread reads accept the reasoningMessages opt-in. */
613 reasoningMessages: Schema.optionalKey(Schema.Boolean),
614 /**
615 * Folder behind this environment's Scratch project, for threads that need
616 * no repository. Present only on servers that answer projects.ensureScratch
617 * and whose data dir is outside a Git checkout.
618 */
619 scratchWorkspaceRoot: Schema.optionalKey(TrimmedNonEmptyString),
620 /**
621 * Palettes published by this environment's machine. Never sent in a config
622 * snapshot: the theme stream emits the current set before any change, so a
623 * snapshot carrying it too would hand every subscriber the same array twice
624 * per connect. Clients populate this by projecting `environmentThemesUpdated`,
625 * and it stays absent for subscribers that did not opt in.
626 */
627 environmentThemes: Schema.optional(Schema.Array(EnvironmentTheme)),
628 /**
629 * Quota reported by configured `usageLimitSources`. Like themes, never in
630 * a snapshot: the source stream emits the current set on subscribe, and it
631 * stays absent for subscribers that did not opt in.
632 */
633 usageLimitSources: Schema.optional(UsageLimitSourceSnapshots),
634});
635export type ServerConfig = typeof ServerConfig.Type;
636
637/**
638 * The machine an environment should be drawn as: the user's pick, else what
639 * the server detected, else a generic server. Settings only exist once
640 * connected; a descriptor alone (relay discovery, before any connection)
641 * still yields the detected kind. A null config (nothing known yet, or an
642 * older server) resolves to the same generic so rows never flicker between
643 * glyphs.
644 */
645export function resolveEnvironmentMachineKind(
646 config: {
647 readonly environment: Pick<ExecutionEnvironmentDescriptor, "platform">;
648 readonly settings?: Pick<ServerSettings, "environmentIcon">;
649 } | null,
650): EnvironmentMachineKind {
651 return config?.settings?.environmentIcon ?? config?.environment.platform.machine ?? "server";
652}
653
654const ServerUpsertKeybindingReplaceTarget = Schema.Struct({
655 key: KeybindingValue,
656 command: KeybindingCommand,
657 when: Schema.optional(KeybindingWhen),
658});
659
660export const ServerUpsertKeybindingInput = Schema.Struct({
661 key: KeybindingValue,
662 command: KeybindingCommand,
663 when: Schema.optional(KeybindingWhen),
664 replace: Schema.optional(ServerUpsertKeybindingReplaceTarget),
665});
666export type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;
667
668export const ServerRemoveKeybindingInput = ServerUpsertKeybindingReplaceTarget;
669export type ServerRemoveKeybindingInput = typeof ServerRemoveKeybindingInput.Type;
670
671export const ServerUpsertKeybindingResult = Schema.Struct({
672 keybindings: ResolvedKeybindingsConfig,
673 issues: ServerConfigIssues,
674});
675export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.Type;
676
677export const ServerRemoveKeybindingResult = ServerUpsertKeybindingResult;
678export type ServerRemoveKeybindingResult = typeof ServerRemoveKeybindingResult.Type;
679
680export const ServerConfigUpdatedPayload = Schema.Struct({
681 issues: ServerConfigIssues,
682 providers: ServerProviders,
683 settings: Schema.optional(ServerSettings),
684});
685export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
686
687export const ServerConfigKeybindingsUpdatedPayload = Schema.Struct({
688 keybindings: ResolvedKeybindingsConfig,
689 issues: ServerConfigIssues,
690});
691export type ServerConfigKeybindingsUpdatedPayload =
692 typeof ServerConfigKeybindingsUpdatedPayload.Type;
693
694export const ServerConfigProviderStatusesPayload = Schema.Struct({
695 providers: ServerProviders,
696});
697export type ServerConfigProviderStatusesPayload = typeof ServerConfigProviderStatusesPayload.Type;
698
699export const ServerConfigSettingsUpdatedPayload = Schema.Struct({
700 settings: ServerSettings,
701});
702export type ServerConfigSettingsUpdatedPayload = typeof ServerConfigSettingsUpdatedPayload.Type;
703
704export const ServerConfigStreamSnapshotEvent = Schema.Struct({
705 version: Schema.Literal(1),
706 type: Schema.Literal("snapshot"),
707 config: ServerConfig,
708});
709export type ServerConfigStreamSnapshotEvent = typeof ServerConfigStreamSnapshotEvent.Type;
710
711export const ServerConfigStreamKeybindingsUpdatedEvent = Schema.Struct({
712 version: Schema.Literal(1),
713 type: Schema.Literal("keybindingsUpdated"),
714 payload: ServerConfigKeybindingsUpdatedPayload,
715});
716export type ServerConfigStreamKeybindingsUpdatedEvent =
717 typeof ServerConfigStreamKeybindingsUpdatedEvent.Type;
718
719export const ServerConfigStreamProviderStatusesEvent = Schema.Struct({
720 version: Schema.Literal(1),
721 type: Schema.Literal("providerStatuses"),
722 payload: ServerConfigProviderStatusesPayload,
723});
724export type ServerConfigStreamProviderStatusesEvent =
725 typeof ServerConfigStreamProviderStatusesEvent.Type;
726
727export const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({
728 version: Schema.Literal(1),
729 type: Schema.Literal("settingsUpdated"),
730 payload: ServerConfigSettingsUpdatedPayload,
731});
732export type ServerConfigStreamSettingsUpdatedEvent =
733 typeof ServerConfigStreamSettingsUpdatedEvent.Type;
734
735export const ServerConfigEnvironmentThemesUpdatedPayload = Schema.Struct({
736 /** The full published set; empty once the machine publishes none. */
737 themes: Schema.Array(EnvironmentTheme),
738});
739export type ServerConfigEnvironmentThemesUpdatedPayload =
740 typeof ServerConfigEnvironmentThemesUpdatedPayload.Type;
741
742export const ServerConfigStreamEnvironmentThemesUpdatedEvent = Schema.Struct({
743 version: Schema.Literal(1),
744 type: Schema.Literal("environmentThemesUpdated"),
745 payload: ServerConfigEnvironmentThemesUpdatedPayload,
746});
747export type ServerConfigStreamEnvironmentThemesUpdatedEvent =
748 typeof ServerConfigStreamEnvironmentThemesUpdatedEvent.Type;
749
750export const ServerConfigUsageLimitSourcesUpdatedPayload = Schema.Struct({
751 /** The full set; empty once no source is configured. */
752 sources: UsageLimitSourceSnapshots,
753});
754export type ServerConfigUsageLimitSourcesUpdatedPayload =
755 typeof ServerConfigUsageLimitSourcesUpdatedPayload.Type;
756
757export const ServerConfigStreamUsageLimitSourcesUpdatedEvent = Schema.Struct({
758 version: Schema.Literal(1),
759 type: Schema.Literal("usageLimitSourcesUpdated"),
760 payload: ServerConfigUsageLimitSourcesUpdatedPayload,
761});
762export type ServerConfigStreamUsageLimitSourcesUpdatedEvent =
763 typeof ServerConfigStreamUsageLimitSourcesUpdatedEvent.Type;
764
765export const ServerConfigStreamEvent = Schema.Union([
766 ServerConfigStreamSnapshotEvent,
767 ServerConfigStreamKeybindingsUpdatedEvent,
768 ServerConfigStreamProviderStatusesEvent,
769 ServerConfigStreamSettingsUpdatedEvent,
770 ServerConfigStreamEnvironmentThemesUpdatedEvent,
771 ServerConfigStreamUsageLimitSourcesUpdatedEvent,
772]);
773export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;
774
775/** Terminal selection recorded by the service launcher for one update. */
776export const ServerSelfUpdateOutcome = Schema.Struct({
777 id: TrimmedNonEmptyString,
778 fromVersion: TrimmedNonEmptyString,
779 targetVersion: TrimmedNonEmptyString,
780 status: Schema.Literals(["committed", "rolled-back", "failed"]),
781 reason: Schema.optionalKey(TrimmedNonEmptyString),
782});
783export type ServerSelfUpdateOutcome = typeof ServerSelfUpdateOutcome.Type;
784
785export const ServerLifecycleReadyPayload = Schema.Struct({
786 at: IsoDateTime,
787 environment: ExecutionEnvironmentDescriptor,
788 /** Present when this process resumed a launcher-managed update. */
789 updateOutcome: Schema.optionalKey(ServerSelfUpdateOutcome),
790});
791export type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type;
792
793export const ServerLifecycleWelcomePayload = Schema.Struct({
794 environment: ExecutionEnvironmentDescriptor,
795 cwd: TrimmedNonEmptyString,
796 projectName: TrimmedNonEmptyString,
797 bootstrapStatus: Schema.optional(Schema.Literals(["pending", "complete"])),
798 bootstrapProjectId: Schema.optional(ProjectId),
799 bootstrapThreadId: Schema.optional(ThreadId),
800 bootstrapProjectCreated: Schema.optional(Schema.Boolean),
801 bootstrapThreadCreated: Schema.optional(Schema.Boolean),
802});
803export type ServerLifecycleWelcomePayload = typeof ServerLifecycleWelcomePayload.Type;
804
805export const ServerLifecycleStreamWelcomeEvent = Schema.Struct({
806 version: Schema.Literal(1),
807 sequence: NonNegativeInt,
808 type: Schema.Literal("welcome"),
809 payload: ServerLifecycleWelcomePayload,
810});
811export type ServerLifecycleStreamWelcomeEvent = typeof ServerLifecycleStreamWelcomeEvent.Type;
812
813export const ServerLifecycleStreamReadyEvent = Schema.Struct({
814 version: Schema.Literal(1),
815 sequence: NonNegativeInt,
816 type: Schema.Literal("ready"),
817 payload: ServerLifecycleReadyPayload,
818});
819export type ServerLifecycleStreamReadyEvent = typeof ServerLifecycleStreamReadyEvent.Type;
820
821export const ServerLifecycleStreamEvent = Schema.Union([
822 ServerLifecycleStreamWelcomeEvent,
823 ServerLifecycleStreamReadyEvent,
824]);
825export type ServerLifecycleStreamEvent = typeof ServerLifecycleStreamEvent.Type;
826
827export const ServerProviderUpdatedPayload = Schema.Struct({
828 providers: ServerProviders,
829});
830export type ServerProviderUpdatedPayload = typeof ServerProviderUpdatedPayload.Type;
831
832export const ServerProviderUpdateInput = Schema.Struct({
833 provider: ProviderDriverKind,
834 targetVersion: Schema.optionalKey(TrimmedNonEmptyString),
835 instanceId: Schema.optionalKey(ProviderInstanceId),
836});
837export type ServerProviderUpdateInput = typeof ServerProviderUpdateInput.Type;
838
839export class ServerProviderUpdateError extends Schema.TaggedError<ServerProviderUpdateError>()(
840 "ServerProviderUpdateError",
841 {
842 provider: ProviderDriverKind,
843 reason: TrimmedNonEmptyString,
844 cause: Schema.optional(Schema.Defect()),
845 },
846) {
847 override get message(): string {
848 return `Provider update failed for ${this.provider}: ${this.reason}`;
849 }
850}
851
852export const ServerSelfUpdateInput = Schema.Struct({
853 /** Exact npm version of the `t3` package to install (never a dist-tag, so
854 the server and the acknowledging client agree on what was requested). */
855 targetVersion: TrimmedNonEmptyString,
856 /** Opt-in recovery for provider turns that are running when the server
857 hands off to its replacement. Missing and false keep restart behavior
858 conservative under version skew. */
859 continueRunningThreads: Schema.optionalKey(Schema.Boolean),
860});
861export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
862
863/** Acknowledgement that the update artifact is installed and the server is
864 about to restart into it — the connection will drop moments later. */
865export const ServerSelfUpdateResult = Schema.Struct({
866 targetVersion: TrimmedNonEmptyString,
867 method: ServerSelfUpdateMethod,
868 /** Launcher-generated correlation ID. Absent when talking to older servers. */
869 updateId: Schema.optionalKey(TrimmedNonEmptyString),
870 /** Desktop preparation token. Present only for the desktop-app method. */
871 desktopUpdateToken: Schema.optionalKey(TrimmedNonEmptyString),
872});
873export type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;
874
875export const DesktopUpdateCommitInput = Schema.Struct({
876 requestId: TrimmedNonEmptyString,
877});
878export type DesktopUpdateCommitInput = typeof DesktopUpdateCommitInput.Type;
879
880export const ServerSelfUpdateProgressStage = Schema.Literals(["downloading", "installing"]);
881export type ServerSelfUpdateProgressStage = typeof ServerSelfUpdateProgressStage.Type;
882
883export const ServerSelfUpdateProgressEvent = Schema.Union([
884 Schema.Struct({
885 type: Schema.Literal("progress"),
886 stage: ServerSelfUpdateProgressStage,
887 }),
888 Schema.Struct({
889 type: Schema.Literal("complete"),
890 result: ServerSelfUpdateResult,
891 }),
892]);
893export type ServerSelfUpdateProgressEvent = typeof ServerSelfUpdateProgressEvent.Type;
894
895export class ServerSelfUpdateError extends Schema.TaggedError<ServerSelfUpdateError>()(
896 "ServerSelfUpdateError",
897 {
898 reason: TrimmedNonEmptyString,
899 cause: Schema.optional(Schema.Defect()),
900 },
901) {
902 override get message(): string {
903 return `Server update failed: ${this.reason}`;
904 }
905}