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