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 * Folder that holds projects started from just a name. Present only on
648 * servers that answer projects.createNew.
649 */
650 newProjectsRoot: Schema.optionalKey(TrimmedNonEmptyString),
651 /**
652 * Palettes published by this environment's machine. Never sent in a config
653 * snapshot: the theme stream emits the current set before any change, so a
654 * snapshot carrying it too would hand every subscriber the same array twice
655 * per connect. Clients populate this by projecting `environmentThemesUpdated`,
656 * and it stays absent for subscribers that did not opt in.
657 */
658 environmentThemes: Schema.optional(Schema.Array(EnvironmentTheme)),
659 /**
660 * Quota reported by configured `usageLimitSources`. Like themes, never in
661 * a snapshot: the source stream emits the current set on subscribe, and it
662 * stays absent for subscribers that did not opt in.
663 */
664 usageLimitSources: Schema.optional(UsageLimitSourceSnapshots),
665});
666export type ServerConfig = typeof ServerConfig.Type;
667
668/**
669 * The machine an environment should be drawn as: the user's pick, else what
670 * the server detected, else a generic server. Settings only exist once
671 * connected; a descriptor alone (relay discovery, before any connection)
672 * still yields the detected kind. A null config (nothing known yet, or an
673 * older server) resolves to the same generic so rows never flicker between
674 * glyphs.
675 */
676export function resolveEnvironmentMachineKind(
677 config: {
678 readonly environment: Pick<ExecutionEnvironmentDescriptor, "platform">;
679 readonly settings?: Pick<ServerSettings, "environmentIcon">;
680 } | null,
681): EnvironmentMachineKind {
682 return config?.settings?.environmentIcon ?? config?.environment.platform.machine ?? "server";
683}
684
685const ServerUpsertKeybindingReplaceTarget = Schema.Struct({
686 key: KeybindingValue,
687 command: KeybindingCommand,
688 when: Schema.optional(KeybindingWhen),
689});
690
691export const ServerUpsertKeybindingInput = Schema.Struct({
692 key: KeybindingValue,
693 command: KeybindingCommand,
694 when: Schema.optional(KeybindingWhen),
695 replace: Schema.optional(ServerUpsertKeybindingReplaceTarget),
696});
697export type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;
698
699export const ServerRemoveKeybindingInput = ServerUpsertKeybindingReplaceTarget;
700export type ServerRemoveKeybindingInput = typeof ServerRemoveKeybindingInput.Type;
701
702export const ServerUpsertKeybindingResult = Schema.Struct({
703 keybindings: ResolvedKeybindingsConfig,
704 issues: ServerConfigIssues,
705});
706export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.Type;
707
708export const ServerRemoveKeybindingResult = ServerUpsertKeybindingResult;
709export type ServerRemoveKeybindingResult = typeof ServerRemoveKeybindingResult.Type;
710
711export const ServerConfigUpdatedPayload = Schema.Struct({
712 issues: ServerConfigIssues,
713 providers: ServerProviders,
714 settings: Schema.optional(ServerSettings),
715});
716export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
717
718export const ServerConfigKeybindingsUpdatedPayload = Schema.Struct({
719 keybindings: ResolvedKeybindingsConfig,
720 issues: ServerConfigIssues,
721});
722export type ServerConfigKeybindingsUpdatedPayload =
723 typeof ServerConfigKeybindingsUpdatedPayload.Type;
724
725export const ServerConfigProviderStatusesPayload = Schema.Struct({
726 providers: ServerProviders,
727});
728export type ServerConfigProviderStatusesPayload = typeof ServerConfigProviderStatusesPayload.Type;
729
730export const ServerConfigSettingsUpdatedPayload = Schema.Struct({
731 settings: ServerSettings,
732});
733export type ServerConfigSettingsUpdatedPayload = typeof ServerConfigSettingsUpdatedPayload.Type;
734
735export const ServerConfigStreamSnapshotEvent = Schema.Struct({
736 version: Schema.Literal(1),
737 type: Schema.Literal("snapshot"),
738 config: ServerConfig,
739});
740export type ServerConfigStreamSnapshotEvent = typeof ServerConfigStreamSnapshotEvent.Type;
741
742export const ServerConfigStreamKeybindingsUpdatedEvent = Schema.Struct({
743 version: Schema.Literal(1),
744 type: Schema.Literal("keybindingsUpdated"),
745 payload: ServerConfigKeybindingsUpdatedPayload,
746});
747export type ServerConfigStreamKeybindingsUpdatedEvent =
748 typeof ServerConfigStreamKeybindingsUpdatedEvent.Type;
749
750export const ServerConfigStreamProviderStatusesEvent = Schema.Struct({
751 version: Schema.Literal(1),
752 type: Schema.Literal("providerStatuses"),
753 payload: ServerConfigProviderStatusesPayload,
754});
755export type ServerConfigStreamProviderStatusesEvent =
756 typeof ServerConfigStreamProviderStatusesEvent.Type;
757
758export const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({
759 version: Schema.Literal(1),
760 type: Schema.Literal("settingsUpdated"),
761 payload: ServerConfigSettingsUpdatedPayload,
762});
763export type ServerConfigStreamSettingsUpdatedEvent =
764 typeof ServerConfigStreamSettingsUpdatedEvent.Type;
765
766export const ServerConfigEnvironmentThemesUpdatedPayload = Schema.Struct({
767 /** The full published set; empty once the machine publishes none. */
768 themes: Schema.Array(EnvironmentTheme),
769});
770export type ServerConfigEnvironmentThemesUpdatedPayload =
771 typeof ServerConfigEnvironmentThemesUpdatedPayload.Type;
772
773export const ServerConfigStreamEnvironmentThemesUpdatedEvent = Schema.Struct({
774 version: Schema.Literal(1),
775 type: Schema.Literal("environmentThemesUpdated"),
776 payload: ServerConfigEnvironmentThemesUpdatedPayload,
777});
778export type ServerConfigStreamEnvironmentThemesUpdatedEvent =
779 typeof ServerConfigStreamEnvironmentThemesUpdatedEvent.Type;
780
781export const ServerConfigUsageLimitSourcesUpdatedPayload = Schema.Struct({
782 /** The full set; empty once no source is configured. */
783 sources: UsageLimitSourceSnapshots,
784});
785export type ServerConfigUsageLimitSourcesUpdatedPayload =
786 typeof ServerConfigUsageLimitSourcesUpdatedPayload.Type;
787
788export const ServerConfigStreamUsageLimitSourcesUpdatedEvent = Schema.Struct({
789 version: Schema.Literal(1),
790 type: Schema.Literal("usageLimitSourcesUpdated"),
791 payload: ServerConfigUsageLimitSourcesUpdatedPayload,
792});
793export type ServerConfigStreamUsageLimitSourcesUpdatedEvent =
794 typeof ServerConfigStreamUsageLimitSourcesUpdatedEvent.Type;
795
796export const ServerConfigStreamEvent = Schema.Union([
797 ServerConfigStreamSnapshotEvent,
798 ServerConfigStreamKeybindingsUpdatedEvent,
799 ServerConfigStreamProviderStatusesEvent,
800 ServerConfigStreamSettingsUpdatedEvent,
801 ServerConfigStreamEnvironmentThemesUpdatedEvent,
802 ServerConfigStreamUsageLimitSourcesUpdatedEvent,
803]);
804export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;
805
806/** Terminal selection recorded by the service launcher for one update. */
807export const ServerSelfUpdateOutcome = Schema.Struct({
808 id: TrimmedNonEmptyString,
809 fromVersion: TrimmedNonEmptyString,
810 targetVersion: TrimmedNonEmptyString,
811 status: Schema.Literals(["committed", "rolled-back", "failed"]),
812 reason: Schema.optionalKey(TrimmedNonEmptyString),
813});
814export type ServerSelfUpdateOutcome = typeof ServerSelfUpdateOutcome.Type;
815
816export const ServerLifecycleReadyPayload = Schema.Struct({
817 at: IsoDateTime,
818 environment: ExecutionEnvironmentDescriptor,
819 /** Present when this process resumed a launcher-managed update. */
820 updateOutcome: Schema.optionalKey(ServerSelfUpdateOutcome),
821});
822export type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type;
823
824export const ServerLifecycleWelcomePayload = Schema.Struct({
825 environment: ExecutionEnvironmentDescriptor,
826 cwd: TrimmedNonEmptyString,
827 projectName: TrimmedNonEmptyString,
828 bootstrapStatus: Schema.optional(Schema.Literals(["pending", "complete"])),
829 bootstrapProjectId: Schema.optional(ProjectId),
830 bootstrapThreadId: Schema.optional(ThreadId),
831 bootstrapProjectCreated: Schema.optional(Schema.Boolean),
832 bootstrapThreadCreated: Schema.optional(Schema.Boolean),
833});
834export type ServerLifecycleWelcomePayload = typeof ServerLifecycleWelcomePayload.Type;
835
836export const ServerLifecycleLegacyThreadMigrationPayload = Schema.Struct({
837 status: Schema.Union([Schema.Literal("running"), Schema.Literal("complete")]),
838 totalThreadCount: NonNegativeInt,
839});
840export type ServerLifecycleLegacyThreadMigrationPayload =
841 typeof ServerLifecycleLegacyThreadMigrationPayload.Type;
842
843export const ServerLifecycleStreamWelcomeEvent = Schema.Struct({
844 version: Schema.Literal(1),
845 sequence: NonNegativeInt,
846 type: Schema.Literal("welcome"),
847 payload: ServerLifecycleWelcomePayload,
848});
849export type ServerLifecycleStreamWelcomeEvent = typeof ServerLifecycleStreamWelcomeEvent.Type;
850
851export const ServerLifecycleStreamReadyEvent = Schema.Struct({
852 version: Schema.Literal(1),
853 sequence: NonNegativeInt,
854 type: Schema.Literal("ready"),
855 payload: ServerLifecycleReadyPayload,
856});
857export type ServerLifecycleStreamReadyEvent = typeof ServerLifecycleStreamReadyEvent.Type;
858
859export const ServerLifecycleStreamLegacyThreadMigrationEvent = Schema.Struct({
860 version: Schema.Literal(1),
861 sequence: NonNegativeInt,
862 type: Schema.Literal("legacyThreadMigration"),
863 payload: ServerLifecycleLegacyThreadMigrationPayload,
864});
865export type ServerLifecycleStreamLegacyThreadMigrationEvent =
866 typeof ServerLifecycleStreamLegacyThreadMigrationEvent.Type;
867
868export const ServerLifecycleStreamEvent = Schema.Union([
869 ServerLifecycleStreamWelcomeEvent,
870 ServerLifecycleStreamReadyEvent,
871 ServerLifecycleStreamLegacyThreadMigrationEvent,
872]);
873export type ServerLifecycleStreamEvent = typeof ServerLifecycleStreamEvent.Type;
874
875export const ServerProviderUpdatedPayload = Schema.Struct({
876 providers: ServerProviders,
877});
878export type ServerProviderUpdatedPayload = typeof ServerProviderUpdatedPayload.Type;
879
880export const ServerProviderUpdateInput = Schema.Struct({
881 provider: ProviderDriverKind,
882 targetVersion: Schema.optionalKey(TrimmedNonEmptyString),
883 instanceId: Schema.optionalKey(ProviderInstanceId),
884});
885export type ServerProviderUpdateInput = typeof ServerProviderUpdateInput.Type;
886
887export class ServerProviderUpdateError extends Schema.TaggedError<ServerProviderUpdateError>()(
888 "ServerProviderUpdateError",
889 {
890 provider: ProviderDriverKind,
891 reason: TrimmedNonEmptyString,
892 cause: Schema.optional(Schema.Defect()),
893 },
894) {
895 override get message(): string {
896 return `Provider update failed for ${this.provider}: ${this.reason}`;
897 }
898}
899
900export const ServerSelfUpdateInput = Schema.Struct({
901 /** Exact npm version of the `t3` package to install (never a dist-tag, so
902 the server and the acknowledging client agree on what was requested). */
903 targetVersion: TrimmedNonEmptyString,
904 /** Opt-in recovery for provider turns that are running when the server
905 hands off to its replacement. Missing and false keep restart behavior
906 conservative under version skew. */
907 continueRunningThreads: Schema.optionalKey(Schema.Boolean),
908});
909export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
910
911/** Acknowledgement that the update artifact is installed and the server is
912 about to restart into it — the connection will drop moments later. */
913export const ServerSelfUpdateResult = Schema.Struct({
914 targetVersion: TrimmedNonEmptyString,
915 method: ServerSelfUpdateMethod,
916 /** Launcher-generated correlation ID. Absent when talking to older servers. */
917 updateId: Schema.optionalKey(TrimmedNonEmptyString),
918 /** Desktop preparation token. Present only for the desktop-app method. */
919 desktopUpdateToken: Schema.optionalKey(TrimmedNonEmptyString),
920});
921export type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;
922
923export const DesktopUpdateCommitInput = Schema.Struct({
924 requestId: TrimmedNonEmptyString,
925});
926export type DesktopUpdateCommitInput = typeof DesktopUpdateCommitInput.Type;
927
928export const ServerSelfUpdateProgressStage = Schema.Literals(["downloading", "installing"]);
929export type ServerSelfUpdateProgressStage = typeof ServerSelfUpdateProgressStage.Type;
930
931export const ServerSelfUpdateProgressEvent = Schema.Union([
932 Schema.Struct({
933 type: Schema.Literal("progress"),
934 stage: ServerSelfUpdateProgressStage,
935 }),
936 Schema.Struct({
937 type: Schema.Literal("complete"),
938 result: ServerSelfUpdateResult,
939 }),
940]);
941export type ServerSelfUpdateProgressEvent = typeof ServerSelfUpdateProgressEvent.Type;
942
943export class ServerSelfUpdateError extends Schema.TaggedError<ServerSelfUpdateError>()(
944 "ServerSelfUpdateError",
945 {
946 reason: TrimmedNonEmptyString,
947 cause: Schema.optional(Schema.Defect()),
948 },
949) {
950 override get message(): string {
951 return `Server update failed: ${this.reason}`;
952 }
953}