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

server.ts

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