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