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

server.ts

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