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});
265export type ServerObservability = typeof ServerObservability.Type;
266
267export const ServerTraceDiagnosticsErrorKind = Schema.Literals([
268 "trace-file-not-found",
269 "trace-file-read-failed",
270]);
271export type ServerTraceDiagnosticsErrorKind = typeof ServerTraceDiagnosticsErrorKind.Type;
272
273export const ServerTraceDiagnosticsSpanSummary = Schema.Struct({
274 name: TrimmedNonEmptyString,
275 count: NonNegativeInt,
276 failureCount: NonNegativeInt,
277 totalDurationMs: Schema.Number,
278 averageDurationMs: Schema.Number,
279 maxDurationMs: Schema.Number,
280});
281export type ServerTraceDiagnosticsSpanSummary = typeof ServerTraceDiagnosticsSpanSummary.Type;
282
283export const ServerTraceDiagnosticsFailureSummary = Schema.Struct({
284 name: TrimmedNonEmptyString,
285 cause: TrimmedNonEmptyString,
286 count: NonNegativeInt,
287 lastSeenAt: Schema.DateTimeUtc,
288 traceId: TrimmedNonEmptyString,
289 spanId: TrimmedNonEmptyString,
290});
291export type ServerTraceDiagnosticsFailureSummary = typeof ServerTraceDiagnosticsFailureSummary.Type;
292
293export const ServerTraceDiagnosticsRecentFailure = Schema.Struct({
294 name: TrimmedNonEmptyString,
295 cause: TrimmedNonEmptyString,
296 durationMs: Schema.Number,
297 endedAt: Schema.DateTimeUtc,
298 traceId: TrimmedNonEmptyString,
299 spanId: TrimmedNonEmptyString,
300});
301export type ServerTraceDiagnosticsRecentFailure = typeof ServerTraceDiagnosticsRecentFailure.Type;
302
303export const ServerTraceDiagnosticsSpanOccurrence = Schema.Struct({
304 name: TrimmedNonEmptyString,
305 durationMs: Schema.Number,
306 endedAt: Schema.DateTimeUtc,
307 traceId: TrimmedNonEmptyString,
308 spanId: TrimmedNonEmptyString,
309});
310export type ServerTraceDiagnosticsSpanOccurrence = typeof ServerTraceDiagnosticsSpanOccurrence.Type;
311
312export const ServerTraceDiagnosticsLogEvent = Schema.Struct({
313 spanName: TrimmedNonEmptyString,
314 level: TrimmedNonEmptyString,
315 message: TrimmedNonEmptyString,
316 seenAt: Schema.DateTimeUtc,
317 traceId: TrimmedNonEmptyString,
318 spanId: TrimmedNonEmptyString,
319});
320export type ServerTraceDiagnosticsLogEvent = typeof ServerTraceDiagnosticsLogEvent.Type;
321
322export const ServerTraceDiagnosticsResult = Schema.Struct({
323 traceFilePath: TrimmedNonEmptyString,
324 scannedFilePaths: Schema.Array(TrimmedNonEmptyString),
325 readAt: Schema.DateTimeUtc,
326 recordCount: NonNegativeInt,
327 parseErrorCount: NonNegativeInt,
328 firstSpanAt: Schema.Option(Schema.DateTimeUtc),
329 lastSpanAt: Schema.Option(Schema.DateTimeUtc),
330 failureCount: NonNegativeInt,
331 interruptionCount: NonNegativeInt,
332 slowSpanThresholdMs: NonNegativeInt,
333 slowSpanCount: NonNegativeInt,
334 logLevelCounts: Schema.Record(TrimmedNonEmptyString, NonNegativeInt),
335 topSpansByCount: Schema.Array(ServerTraceDiagnosticsSpanSummary),
336 slowestSpans: Schema.Array(ServerTraceDiagnosticsSpanOccurrence),
337 commonFailures: Schema.Array(ServerTraceDiagnosticsFailureSummary),
338 latestFailures: Schema.Array(ServerTraceDiagnosticsRecentFailure),
339 latestWarningAndErrorLogs: Schema.Array(ServerTraceDiagnosticsLogEvent),
340 partialFailure: Schema.Option(Schema.Boolean),
341 error: Schema.Option(
342 Schema.Struct({
343 kind: ServerTraceDiagnosticsErrorKind,
344 message: TrimmedNonEmptyString,
345 }),
346 ),
347});
348export type ServerTraceDiagnosticsResult = typeof ServerTraceDiagnosticsResult.Type;
349
350export const ServerProcessSignal = Schema.Literals(["SIGINT", "SIGKILL"]);
351export type ServerProcessSignal = typeof ServerProcessSignal.Type;
352
353export const ServerProcessDiagnosticsEntry = Schema.Struct({
354 pid: PositiveInt,
355 startTimeMs: NonNegativeInt,
356 ppid: NonNegativeInt,
357 pgid: Schema.Option(Schema.Int),
358 status: TrimmedNonEmptyString,
359 cpuPercent: Schema.Number,
360 rssBytes: NonNegativeInt,
361 elapsed: TrimmedNonEmptyString,
362 command: TrimmedNonEmptyString,
363 depth: NonNegativeInt,
364 childPids: Schema.Array(PositiveInt),
365});
366export type ServerProcessDiagnosticsEntry = typeof ServerProcessDiagnosticsEntry.Type;
367
368export const ServerProcessDiagnosticsResult = Schema.Struct({
369 serverPid: PositiveInt,
370 readAt: Schema.DateTimeUtc,
371 processCount: NonNegativeInt,
372 totalRssBytes: NonNegativeInt,
373 totalCpuPercent: Schema.Number,
374 processes: Schema.Array(ServerProcessDiagnosticsEntry),
375 error: Schema.Option(
376 Schema.Struct({
377 message: TrimmedNonEmptyString,
378 }),
379 ),
380});
381export type ServerProcessDiagnosticsResult = typeof ServerProcessDiagnosticsResult.Type;
382
383export const ServerProcessResourceHistoryInput = Schema.Struct({
384 windowMs: NonNegativeInt,
385 bucketMs: NonNegativeInt,
386});
387export type ServerProcessResourceHistoryInput = typeof ServerProcessResourceHistoryInput.Type;
388
389export const ServerProcessResourceHistoryBucket = Schema.Struct({
390 startedAt: Schema.DateTimeUtc,
391 endedAt: Schema.DateTimeUtc,
392 avgCpuPercent: Schema.Number,
393 maxCpuPercent: Schema.Number,
394 maxRssBytes: NonNegativeInt,
395 maxProcessCount: NonNegativeInt,
396});
397export type ServerProcessResourceHistoryBucket = typeof ServerProcessResourceHistoryBucket.Type;
398
399export const ServerProcessResourceHistorySummary = Schema.Struct({
400 processKey: TrimmedNonEmptyString,
401 pid: PositiveInt,
402 ppid: NonNegativeInt,
403 command: TrimmedNonEmptyString,
404 depth: NonNegativeInt,
405 isServerRoot: Schema.Boolean,
406 firstSeenAt: Schema.DateTimeUtc,
407 lastSeenAt: Schema.DateTimeUtc,
408 currentCpuPercent: Schema.Number,
409 avgCpuPercent: Schema.Number,
410 maxCpuPercent: Schema.Number,
411 cpuSecondsApprox: Schema.Number,
412 currentRssBytes: NonNegativeInt,
413 maxRssBytes: NonNegativeInt,
414 sampleCount: NonNegativeInt,
415});
416export type ServerProcessResourceHistorySummary = typeof ServerProcessResourceHistorySummary.Type;
417
418export const ServerProcessResourceHistoryFailureTag = Schema.Literals([
419 "ProcessDiagnosticsQueryTimeoutError",
420 "ProcessDiagnosticsQueryFailedError",
421 "ProcessDiagnosticsServerProcessSignalError",
422 "ProcessDiagnosticsNotDescendantError",
423 "ProcessDiagnosticsSignalFailedError",
424]);
425export type ServerProcessResourceHistoryFailureTag =
426 typeof ServerProcessResourceHistoryFailureTag.Type;
427
428export const ServerProcessResourceHistoryResult = Schema.Struct({
429 readAt: Schema.DateTimeUtc,
430 windowMs: NonNegativeInt,
431 bucketMs: NonNegativeInt,
432 sampleIntervalMs: NonNegativeInt,
433 retainedSampleCount: NonNegativeInt,
434 totalCpuSecondsApprox: Schema.Number,
435 buckets: Schema.Array(ServerProcessResourceHistoryBucket),
436 topProcesses: Schema.Array(ServerProcessResourceHistorySummary),
437 error: Schema.Option(
438 Schema.Struct({
439 failureTag: ServerProcessResourceHistoryFailureTag,
440 message: TrimmedNonEmptyString,
441 }),
442 ),
443});
444export type ServerProcessResourceHistoryResult = typeof ServerProcessResourceHistoryResult.Type;
445
446export const ServerSignalProcessInput = Schema.Struct({
447 pid: PositiveInt,
448 startTimeMs: NonNegativeInt,
449 signal: ServerProcessSignal,
450});
451export type ServerSignalProcessInput = typeof ServerSignalProcessInput.Type;
452
453export const ServerSignalProcessResult = Schema.Struct({
454 pid: PositiveInt,
455 signal: ServerProcessSignal,
456 signaled: Schema.Boolean,
457 message: Schema.Option(TrimmedNonEmptyString),
458});
459export type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;
460
461/**
462 * A palette the environment's machine publishes for T3 Code to follow, read
463 * from a theme file next to the rest of the environment's state. Two seed
464 * colors rather than a full palette: clients derive the remaining roles with
465 * the same generator the guided theme editor uses, so a desktop theme carries
466 * over as a coherent T3 Code palette instead of a foreign one.
467 */
468export const EnvironmentThemeColor = Schema.String.check(
469 Schema.isPattern(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/),
470);
471export type EnvironmentThemeColor = typeof EnvironmentThemeColor.Type;
472
473/**
474 * Matches the client-side theme id rule, so a published id is selectable.
475 * The appearance keywords are excluded outright: a published `dark.json`
476 * would otherwise capture every client whose stored preference is the stock
477 * `"dark"`, retinting people who never chose it.
478 */
479export const EnvironmentThemeId = Schema.String.check(
480 Schema.isPattern(/^(?!(?:system|light|dark)$)[a-z0-9](?:[a-z0-9-]{0,47})$/),
481);
482export type EnvironmentThemeId = typeof EnvironmentThemeId.Type;
483
484/**
485 * Role colors as published. Values are any CSS color the client's theme
486 * parser accepts (exported theme files use oklch), canonicalized client-side;
487 * roles a build does not know are dropped there, so a machine may publish
488 * roles a newer client added without breaking an older one. Keys must still
489 * be role-shaped and values color-sized, so the record stays open to future
490 * vocabulary without being an arbitrary-payload channel.
491 */
492const EnvironmentThemeColors = Schema.Record(
493 Schema.String.check(Schema.isPattern(/^[a-zA-Z][a-zA-Z0-9]{0,63}$/)),
494 TrimmedNonEmptyString.check(Schema.isMaxLength(64)),
495);
496
497const environmentThemeFields = {
498 /**
499 * Standard exported theme files (the Download button's output) carry
500 * `version: 1`; the seeded short form a desktop generates has no version.
501 */
502 version: Schema.optional(Schema.Literal(1)),
503 /** Shown on the theme card, e.g. the desktop theme's own name. */
504 name: TrimmedNonEmptyString.check(Schema.isMaxLength(48)),
505 appearance: Schema.Literals(["light", "dark"]),
506 /**
507 * Seed colors. When present, clients derive the full palette from them with
508 * the guided theme editor's generator and layer `colors` on top; when
509 * absent, `colors` is the palette, as in an exported theme file.
510 */
511 canvas: Schema.optional(EnvironmentThemeColor),
512 accent: Schema.optional(EnvironmentThemeColor),
513 colors: Schema.optional(EnvironmentThemeColors),
514 /** The other appearance's palette, as exported theme files carry it. */
515 variants: Schema.optional(
516 Schema.Struct({
517 light: Schema.optional(EnvironmentThemeColors),
518 dark: Schema.optional(EnvironmentThemeColors),
519 }),
520 ),
521};
522
523/** One published theme file. The id is the filename, not part of the content,
524 * so a file cannot claim another file's identity; an embedded `id` is ignored. */
525export const EnvironmentThemeFile = Schema.Struct(environmentThemeFields);
526export type EnvironmentThemeFile = typeof EnvironmentThemeFile.Type;
527
528export const EnvironmentTheme = Schema.Struct({
529 /** The publishing filename without its extension, stable across recolors. */
530 id: EnvironmentThemeId,
531 ...environmentThemeFields,
532});
533export type EnvironmentTheme = typeof EnvironmentTheme.Type;
534
535/**
536 * Whether a theme file carries anything to render. A file with neither seeds
537 * nor colors would show as the stock palette wearing a name, which reads as a
538 * bug rather than a theme — the CLI and the server watcher both reject it,
539 * through this one predicate so they cannot drift.
540 */
541export function environmentThemeFileHasColors(file: EnvironmentThemeFile): boolean {
542 return (
543 (file.canvas !== undefined && file.accent !== undefined) ||
544 (file.colors !== undefined && Object.keys(file.colors).length > 0)
545 );
546}
547
548export const ServerConfig = Schema.Struct({
549 environment: ExecutionEnvironmentDescriptor,
550 auth: ServerAuthDescriptor,
551 cwd: TrimmedNonEmptyString,
552 keybindingsConfigPath: TrimmedNonEmptyString,
553 keybindings: ResolvedKeybindingsConfig,
554 issues: ServerConfigIssues,
555 providers: ServerProviders,
556 // Editor ids grow over time; drop ones this build does not know rather than
557 // failing the whole config decode.
558 availableEditors: ForwardCompatibleArray(EditorId),
559 /**
560 * SSH hosts this environment advertises for remote open-in-editor links.
561 * Absent on servers that predate the feature; empty when the machine has no
562 * sshd or no advertisable name.
563 */
564 remoteOpenTargets: Schema.optionalKey(ForwardCompatibleArray(RemoteOpenTarget)),
565 observability: ServerObservability,
566 settings: ServerSettings,
567 /** Whether shell subscriptions can emit an opt-in catch-up completion marker. */
568 shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
569 /** Whether shell.openInEditor honors `LaunchEditorInput.reveal` for the
570 file-manager editor. */
571 shellRevealInFileManager: Schema.optionalKey(Schema.Boolean),
572 /** File-manager wording clients should use for reveal actions. */
573 shellRevealInFileManagerKind: Schema.optionalKey(FileManagerRevealKind),
574 /** Whether thread subscriptions can emit an opt-in catch-up completion marker. */
575 threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
576 /**
577 * Whether thread detail reads accept a turn window (`turnLimit`/
578 * `beforeCursor`) and return `page` metadata. Clients must not send window
579 * fields to servers that don't advertise this.
580 */
581 threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),
582 /**
583 * Palettes published by this environment's machine. Never sent in a config
584 * snapshot: the theme stream emits the current set before any change, so a
585 * snapshot carrying it too would hand every subscriber the same array twice
586 * per connect. Clients populate this by projecting `environmentThemesUpdated`,
587 * and it stays absent for subscribers that did not opt in.
588 */
589 environmentThemes: Schema.optional(Schema.Array(EnvironmentTheme)),
590 /**
591 * Quota reported by configured `usageLimitSources`. Like themes, never in
592 * a snapshot: the source stream emits the current set on subscribe, and it
593 * stays absent for subscribers that did not opt in.
594 */
595 usageLimitSources: Schema.optional(UsageLimitSourceSnapshots),
596});
597export type ServerConfig = typeof ServerConfig.Type;
598
599/**
600 * The machine an environment should be drawn as: the user's pick, else what
601 * the server detected, else a generic server. A null config (not connected
602 * yet, or an older server) resolves to the same generic so rows never
603 * flicker between glyphs.
604 */
605export function resolveEnvironmentMachineKind(
606 config: Pick<ServerConfig, "environment" | "settings"> | null,
607): EnvironmentMachineKind {
608 return config?.settings.environmentIcon ?? config?.environment.platform.machine ?? "server";
609}
610
611const ServerUpsertKeybindingReplaceTarget = Schema.Struct({
612 key: KeybindingValue,
613 command: KeybindingCommand,
614 when: Schema.optional(KeybindingWhen),
615});
616
617export const ServerUpsertKeybindingInput = Schema.Struct({
618 key: KeybindingValue,
619 command: KeybindingCommand,
620 when: Schema.optional(KeybindingWhen),
621 replace: Schema.optional(ServerUpsertKeybindingReplaceTarget),
622});
623export type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;
624
625export const ServerRemoveKeybindingInput = ServerUpsertKeybindingReplaceTarget;
626export type ServerRemoveKeybindingInput = typeof ServerRemoveKeybindingInput.Type;
627
628export const ServerUpsertKeybindingResult = Schema.Struct({
629 keybindings: ResolvedKeybindingsConfig,
630 issues: ServerConfigIssues,
631});
632export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.Type;
633
634export const ServerRemoveKeybindingResult = ServerUpsertKeybindingResult;
635export type ServerRemoveKeybindingResult = typeof ServerRemoveKeybindingResult.Type;
636
637export const ServerConfigUpdatedPayload = Schema.Struct({
638 issues: ServerConfigIssues,
639 providers: ServerProviders,
640 settings: Schema.optional(ServerSettings),
641});
642export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
643
644export const ServerConfigKeybindingsUpdatedPayload = Schema.Struct({
645 keybindings: ResolvedKeybindingsConfig,
646 issues: ServerConfigIssues,
647});
648export type ServerConfigKeybindingsUpdatedPayload =
649 typeof ServerConfigKeybindingsUpdatedPayload.Type;
650
651export const ServerConfigProviderStatusesPayload = Schema.Struct({
652 providers: ServerProviders,
653});
654export type ServerConfigProviderStatusesPayload = typeof ServerConfigProviderStatusesPayload.Type;
655
656export const ServerConfigSettingsUpdatedPayload = Schema.Struct({
657 settings: ServerSettings,
658});
659export type ServerConfigSettingsUpdatedPayload = typeof ServerConfigSettingsUpdatedPayload.Type;
660
661export const ServerConfigStreamSnapshotEvent = Schema.Struct({
662 version: Schema.Literal(1),
663 type: Schema.Literal("snapshot"),
664 config: ServerConfig,
665});
666export type ServerConfigStreamSnapshotEvent = typeof ServerConfigStreamSnapshotEvent.Type;
667
668export const ServerConfigStreamKeybindingsUpdatedEvent = Schema.Struct({
669 version: Schema.Literal(1),
670 type: Schema.Literal("keybindingsUpdated"),
671 payload: ServerConfigKeybindingsUpdatedPayload,
672});
673export type ServerConfigStreamKeybindingsUpdatedEvent =
674 typeof ServerConfigStreamKeybindingsUpdatedEvent.Type;
675
676export const ServerConfigStreamProviderStatusesEvent = Schema.Struct({
677 version: Schema.Literal(1),
678 type: Schema.Literal("providerStatuses"),
679 payload: ServerConfigProviderStatusesPayload,
680});
681export type ServerConfigStreamProviderStatusesEvent =
682 typeof ServerConfigStreamProviderStatusesEvent.Type;
683
684export const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({
685 version: Schema.Literal(1),
686 type: Schema.Literal("settingsUpdated"),
687 payload: ServerConfigSettingsUpdatedPayload,
688});
689export type ServerConfigStreamSettingsUpdatedEvent =
690 typeof ServerConfigStreamSettingsUpdatedEvent.Type;
691
692export const ServerConfigEnvironmentThemesUpdatedPayload = Schema.Struct({
693 /** The full published set; empty once the machine publishes none. */
694 themes: Schema.Array(EnvironmentTheme),
695});
696export type ServerConfigEnvironmentThemesUpdatedPayload =
697 typeof ServerConfigEnvironmentThemesUpdatedPayload.Type;
698
699export const ServerConfigStreamEnvironmentThemesUpdatedEvent = Schema.Struct({
700 version: Schema.Literal(1),
701 type: Schema.Literal("environmentThemesUpdated"),
702 payload: ServerConfigEnvironmentThemesUpdatedPayload,
703});
704export type ServerConfigStreamEnvironmentThemesUpdatedEvent =
705 typeof ServerConfigStreamEnvironmentThemesUpdatedEvent.Type;
706
707export const ServerConfigUsageLimitSourcesUpdatedPayload = Schema.Struct({
708 /** The full set; empty once no source is configured. */
709 sources: UsageLimitSourceSnapshots,
710});
711export type ServerConfigUsageLimitSourcesUpdatedPayload =
712 typeof ServerConfigUsageLimitSourcesUpdatedPayload.Type;
713
714export const ServerConfigStreamUsageLimitSourcesUpdatedEvent = Schema.Struct({
715 version: Schema.Literal(1),
716 type: Schema.Literal("usageLimitSourcesUpdated"),
717 payload: ServerConfigUsageLimitSourcesUpdatedPayload,
718});
719export type ServerConfigStreamUsageLimitSourcesUpdatedEvent =
720 typeof ServerConfigStreamUsageLimitSourcesUpdatedEvent.Type;
721
722export const ServerConfigStreamEvent = Schema.Union([
723 ServerConfigStreamSnapshotEvent,
724 ServerConfigStreamKeybindingsUpdatedEvent,
725 ServerConfigStreamProviderStatusesEvent,
726 ServerConfigStreamSettingsUpdatedEvent,
727 ServerConfigStreamEnvironmentThemesUpdatedEvent,
728 ServerConfigStreamUsageLimitSourcesUpdatedEvent,
729]);
730export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;
731
732/** Terminal selection recorded by the service launcher for one update. */
733export const ServerSelfUpdateOutcome = Schema.Struct({
734 id: TrimmedNonEmptyString,
735 fromVersion: TrimmedNonEmptyString,
736 targetVersion: TrimmedNonEmptyString,
737 status: Schema.Literals(["committed", "rolled-back", "failed"]),
738 reason: Schema.optionalKey(TrimmedNonEmptyString),
739});
740export type ServerSelfUpdateOutcome = typeof ServerSelfUpdateOutcome.Type;
741
742export const ServerLifecycleReadyPayload = Schema.Struct({
743 at: IsoDateTime,
744 environment: ExecutionEnvironmentDescriptor,
745 /** Present when this process resumed a launcher-managed update. */
746 updateOutcome: Schema.optionalKey(ServerSelfUpdateOutcome),
747});
748export type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type;
749
750export const ServerLifecycleWelcomePayload = Schema.Struct({
751 environment: ExecutionEnvironmentDescriptor,
752 cwd: TrimmedNonEmptyString,
753 projectName: TrimmedNonEmptyString,
754 bootstrapStatus: Schema.optional(Schema.Literals(["pending", "complete"])),
755 bootstrapProjectId: Schema.optional(ProjectId),
756 bootstrapThreadId: Schema.optional(ThreadId),
757 bootstrapProjectCreated: Schema.optional(Schema.Boolean),
758 bootstrapThreadCreated: Schema.optional(Schema.Boolean),
759});
760export type ServerLifecycleWelcomePayload = typeof ServerLifecycleWelcomePayload.Type;
761
762export const ServerLifecycleStreamWelcomeEvent = Schema.Struct({
763 version: Schema.Literal(1),
764 sequence: NonNegativeInt,
765 type: Schema.Literal("welcome"),
766 payload: ServerLifecycleWelcomePayload,
767});
768export type ServerLifecycleStreamWelcomeEvent = typeof ServerLifecycleStreamWelcomeEvent.Type;
769
770export const ServerLifecycleStreamReadyEvent = Schema.Struct({
771 version: Schema.Literal(1),
772 sequence: NonNegativeInt,
773 type: Schema.Literal("ready"),
774 payload: ServerLifecycleReadyPayload,
775});
776export type ServerLifecycleStreamReadyEvent = typeof ServerLifecycleStreamReadyEvent.Type;
777
778export const ServerLifecycleStreamEvent = Schema.Union([
779 ServerLifecycleStreamWelcomeEvent,
780 ServerLifecycleStreamReadyEvent,
781]);
782export type ServerLifecycleStreamEvent = typeof ServerLifecycleStreamEvent.Type;
783
784export const ServerProviderUpdatedPayload = Schema.Struct({
785 providers: ServerProviders,
786});
787export type ServerProviderUpdatedPayload = typeof ServerProviderUpdatedPayload.Type;
788
789export const ServerProviderUpdateInput = Schema.Struct({
790 provider: ProviderDriverKind,
791 instanceId: Schema.optionalKey(ProviderInstanceId),
792});
793export type ServerProviderUpdateInput = typeof ServerProviderUpdateInput.Type;
794
795export class ServerProviderUpdateError extends Schema.TaggedError<ServerProviderUpdateError>()(
796 "ServerProviderUpdateError",
797 {
798 provider: ProviderDriverKind,
799 reason: TrimmedNonEmptyString,
800 cause: Schema.optional(Schema.Defect()),
801 },
802) {
803 override get message(): string {
804 return `Provider update failed for ${this.provider}: ${this.reason}`;
805 }
806}
807
808export const ServerSelfUpdateInput = Schema.Struct({
809 /** Exact npm version of the `t3` package to install (never a dist-tag, so
810 the server and the acknowledging client agree on what was requested). */
811 targetVersion: TrimmedNonEmptyString,
812 /** Opt-in recovery for provider turns that are running when the server
813 hands off to its replacement. Missing and false keep restart behavior
814 conservative under version skew. */
815 continueRunningThreads: Schema.optionalKey(Schema.Boolean),
816});
817export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
818
819/** Acknowledgement that the update artifact is installed and the server is
820 about to restart into it — the connection will drop moments later. */
821export const ServerSelfUpdateResult = Schema.Struct({
822 targetVersion: TrimmedNonEmptyString,
823 method: ServerSelfUpdateMethod,
824 /** Launcher-generated correlation ID. Absent when talking to older servers. */
825 updateId: Schema.optionalKey(TrimmedNonEmptyString),
826 /** Desktop preparation token. Present only for the desktop-app method. */
827 desktopUpdateToken: Schema.optionalKey(TrimmedNonEmptyString),
828});
829export type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;
830
831export const DesktopUpdateCommitInput = Schema.Struct({
832 requestId: TrimmedNonEmptyString,
833});
834export type DesktopUpdateCommitInput = typeof DesktopUpdateCommitInput.Type;
835
836export const ServerSelfUpdateProgressStage = Schema.Literals(["downloading", "installing"]);
837export type ServerSelfUpdateProgressStage = typeof ServerSelfUpdateProgressStage.Type;
838
839export const ServerSelfUpdateProgressEvent = Schema.Union([
840 Schema.Struct({
841 type: Schema.Literal("progress"),
842 stage: ServerSelfUpdateProgressStage,
843 }),
844 Schema.Struct({
845 type: Schema.Literal("complete"),
846 result: ServerSelfUpdateResult,
847 }),
848]);
849export type ServerSelfUpdateProgressEvent = typeof ServerSelfUpdateProgressEvent.Type;
850
851export class ServerSelfUpdateError extends Schema.TaggedError<ServerSelfUpdateError>()(
852 "ServerSelfUpdateError",
853 {
854 reason: TrimmedNonEmptyString,
855 cause: Schema.optional(Schema.Defect()),
856 },
857) {
858 override get message(): string {
859 return `Server update failed: ${this.reason}`;
860 }
861}