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

server.ts

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