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