Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server.ts

914 lines36.5 KB

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