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

server.ts

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