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