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

server.ts

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