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