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