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

server.ts

880 lines34.9 KB

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