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

server.ts

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