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

server.ts

903 lines35.9 KB

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