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