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

server.ts

895 lines34.0 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​
49const ServerConfigIssues = ForwardCompatibleArray(ServerConfigIssue);
50​
51export const ServerProviderState = Schema.Literals(["ready", "warning", "error", "disabled"]);
52export type ServerProviderState = typeof ServerProviderState.Type;
53​
54export const ServerProviderAuthStatus = Schema.Literals([
55 "authenticated",
56 "unauthenticated",
57 "unknown",
58]);
59export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
60​
61export const ServerProviderAuth = Schema.Struct({
62 status: ServerProviderAuthStatus,
63 type: Schema.optional(TrimmedNonEmptyString),
64 label: Schema.optional(TrimmedNonEmptyString),
65 email: Schema.optional(TrimmedNonEmptyString),
66 action: Schema.optional(AcpRegistryUrlAuthAction),
67 canLogout: Schema.optional(Schema.Boolean),
68 subscriptionSharing: Schema.optional(Schema.Boolean),
69 profileId: Schema.optional(TrimmedNonEmptyString),
70 workspaceId: Schema.optional(TrimmedNonEmptyString),
71});
72export type ServerProviderAuth = typeof ServerProviderAuth.Type;
73​
74export const ServerProviderModel = Schema.Struct({
75 slug: TrimmedNonEmptyString,
76 name: TrimmedNonEmptyString,
77 shortName: Schema.optional(TrimmedNonEmptyString),
78 subProvider: Schema.optional(TrimmedNonEmptyString),
79 aliases: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
80 badge: Schema.optional(Schema.Literal("new")),
81 isCustom: Schema.Boolean,
82 isDefault: Schema.optional(Schema.Boolean),
83 isLegacy: Schema.optional(Schema.Boolean),
84 capabilities: Schema.NullOr(ModelCapabilities),
85});
86export type ServerProviderModel = typeof ServerProviderModel.Type;
87​
88export const ServerProviderUpdateRequiredModel = Schema.Struct({
89 slug: TrimmedNonEmptyString,
90 name: TrimmedNonEmptyString,
91 badge: Schema.optional(Schema.Literal("new")),
92 minVersion: TrimmedNonEmptyString,
93});
94export type ServerProviderUpdateRequiredModel = typeof ServerProviderUpdateRequiredModel.Type;
95​
96export const ServerProviderSlashCommandInput = Schema.Struct({
97 hint: TrimmedNonEmptyString,
98});
99export type ServerProviderSlashCommandInput = typeof ServerProviderSlashCommandInput.Type;
100​
101export const ServerProviderSlashCommand = Schema.Struct({
102 name: TrimmedNonEmptyString,
103 description: Schema.optional(TrimmedNonEmptyString),
104 input: Schema.optional(ServerProviderSlashCommandInput),
105});
106export type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type;
107​
108export const ServerProviderSkill = Schema.Struct({
109 name: TrimmedNonEmptyString,
110 description: Schema.optional(TrimmedNonEmptyString),
111 path: TrimmedNonEmptyString,
112 scope: Schema.optional(TrimmedNonEmptyString),
113 enabled: Schema.Boolean,
114 displayName: Schema.optional(TrimmedNonEmptyString),
115 shortDescription: Schema.optional(TrimmedNonEmptyString),
116 /**
117 * The skill is hidden from the agent's own skill tool, so only the user can
118 * start it — Claude Code's `disable-model-invocation`. Composers must offer
119 * it as a slash command; naming it in prose does nothing.
120 */
121 userInvocationOnly: Schema.optional(Schema.Boolean),
122 /**
123 * The mirror of {@link ServerProviderSkill.userInvocationOnly}: Claude Code's
124 * `user-invocable: false` keeps the skill out of its own slash commands, so
125 * only the agent can start it. Composers must not offer it under `/`.
126 */
127 userInvocable: Schema.optional(Schema.Boolean),
128});
129export type ServerProviderSkill = typeof ServerProviderSkill.Type;
130​
131export const ServerProviderWorkspaceSnapshot = Schema.Struct({
132 cwd: TrimmedNonEmptyString,
133 checkedAt: IsoDateTime,
134 slashCommands: Schema.Array(ServerProviderSlashCommand),
135 slashCommandsPending: Schema.optional(Schema.Boolean),
136 skills: Schema.Array(ServerProviderSkill),
137});
138export type ServerProviderWorkspaceSnapshot = typeof ServerProviderWorkspaceSnapshot.Type;
139​
140export const PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS = 5 * 60_000;
141​
142export function isProviderWorkspaceSnapshotCurrent(
143 snapshot: Pick<ServerProviderWorkspaceSnapshot, "checkedAt">,
144 nowMs: number,
145): boolean {
146 return nowMs - Date.parse(snapshot.checkedAt) < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS;
148​
149/**
150 * Snapshots with `availability: "unavailable"` MUST set
151 * `installed: false` and `enabled: false`; the runtime refuses turn
152 * starts against them with a structured error.
153 */
154export const ServerProviderAvailability = Schema.Literals(["available", "unavailable"]);
155export type ServerProviderAvailability = typeof ServerProviderAvailability.Type;
156​
157export const ServerProviderContinuation = Schema.Struct({
158 groupKey: TrimmedNonEmptyString,
159});
160export type ServerProviderContinuation = typeof ServerProviderContinuation.Type;
161​
162export const ServerProviderCompatibilityStatus = Schema.Literals([
163 "unknown",
164 "supported",
165 "graceful",
166 "unsupported",
167 "broken",
168]);
169export const ServerProviderCompatibilityAdvisory = Schema.Struct({
170 status: ServerProviderCompatibilityStatus,
171 latestVersionStatus: Schema.optionalKey(ServerProviderCompatibilityStatus),
172 message: Schema.NullOr(TrimmedNonEmptyString),
173 recommendedVersion: Schema.NullOr(TrimmedNonEmptyString),
174 recommendedRange: Schema.NullOr(TrimmedNonEmptyString),
175});
176export type ServerProviderCompatibilityAdvisory = typeof ServerProviderCompatibilityAdvisory.Type;
177​
178export const ServerProviderVersionAdvisoryStatus = Schema.Literals([
179 "unknown",
180 "current",
181 "behind_latest",
182]);
183export type ServerProviderVersionAdvisoryStatus = typeof ServerProviderVersionAdvisoryStatus.Type;
184​
185export const ServerProviderVersionAdvisory = Schema.Struct({
186 status: ServerProviderVersionAdvisoryStatus,
187 currentVersion: Schema.NullOr(TrimmedNonEmptyString),
188 latestVersion: Schema.NullOr(TrimmedNonEmptyString),
189 updateCommand: Schema.NullOr(TrimmedNonEmptyString),
190 canUpdate: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
191 canInstallVersion: Schema.optionalKey(Schema.Boolean),
192 checkedAt: Schema.NullOr(IsoDateTime),
193 message: Schema.NullOr(TrimmedNonEmptyString),
194});
195export type ServerProviderVersionAdvisory = typeof ServerProviderVersionAdvisory.Type;
196​
197export const ServerProviderUpdateStatus = Schema.Literals([
198 "idle",
199 "queued",
200 "running",
201 "succeeded",
202 "failed",
203 "unchanged",
204]);
205export type ServerProviderUpdateStatus = typeof ServerProviderUpdateStatus.Type;
206​
207export const ServerProviderUpdateState = Schema.Struct({
208 status: ServerProviderUpdateStatus,
209 startedAt: Schema.NullOr(IsoDateTime),
210 finishedAt: Schema.NullOr(IsoDateTime),
211 message: Schema.NullOr(TrimmedNonEmptyString),
212 output: Schema.NullOr(Schema.String.check(Schema.isMaxLength(10_000))),
213});
214export type ServerProviderUpdateState = typeof ServerProviderUpdateState.Type;
215​
216export const ServerProvider = Schema.Struct({
217 // Routing key for the configured instance this snapshot represents. This
218 // is the only stable identity consumers may use for provider routing.
219 instanceId: ProviderInstanceId,
220 driver: ProviderDriverKind,
221 displayName: Schema.optional(TrimmedNonEmptyString),
222 accentColor: Schema.optional(TrimmedNonEmptyString),
223 // Optional visual identity supplied by the owning provider driver. Clients
224 // must still validate remote URLs against that driver's trusted origin.
225 iconUrl: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(2_048))),
226 badgeLabel: Schema.optional(TrimmedNonEmptyString),
227 continuation: Schema.optional(ServerProviderContinuation),
228 showInteractionModeToggle: Schema.optional(Schema.Boolean),
229 reportsContextWindow: Schema.optional(Schema.Boolean),
230 supportedRuntimeModes: Schema.optional(ForwardCompatibleArray(RuntimeMode)),
231 requiresNewThreadForModelChange: Schema.optional(Schema.Boolean),
232 supportsConversationRollback: Schema.optional(Schema.Boolean),
233 supportsTextGeneration: Schema.optional(Schema.Boolean),
234 setup: Schema.optional(
235 Schema.Struct({
236 canAuthenticate: Schema.Boolean,
237 canInstall: Schema.Boolean,
238 documentationUrl: Schema.optionalKey(TrimmedNonEmptyString.check(Schema.isMaxLength(2_048))),
239 }),
240 ),
241 nativeSessions: Schema.optional(
242 Schema.Struct({
243 canList: Schema.Boolean,
244 canLoad: Schema.Boolean,
245 canResume: Schema.Boolean,
246 canDelete: Schema.optional(Schema.Boolean),
247 }),
248 ),
249 configurableProviders: Schema.optional(Schema.Boolean),
250 runtimePaths: Schema.optionalKey(
251 Schema.Struct({
252 homePath: TrimmedNonEmptyString,
253 shadowHomePath: Schema.NullOr(TrimmedNonEmptyString),
254 }),
255 ),
256 enabled: Schema.Boolean,
257 installed: Schema.Boolean,
258 version: Schema.NullOr(TrimmedNonEmptyString),
259 status: ServerProviderState,
260 auth: ServerProviderAuth,
261 checkedAt: IsoDateTime,
262 message: Schema.optional(TrimmedNonEmptyString),
263 availability: Schema.optional(ServerProviderAvailability),
264 unavailableReason: Schema.optional(TrimmedNonEmptyString),
265 models: Schema.Array(ServerProviderModel),
266 // Kept apart from `models` so clients that predate it never offer them.
267 updateRequiredModels: Schema.optionalKey(Schema.Array(ServerProviderUpdateRequiredModel)),
268 slashCommands: Schema.Array(ServerProviderSlashCommand).pipe(
269 Schema.withDecodingDefault(Effect.succeed([])),
270 ),
271 skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
272 workspaceSnapshots: Schema.optionalKey(Schema.Array(ServerProviderWorkspaceSnapshot)),
273 usageLimits: Schema.optional(ServerProviderUsageLimits),
274 versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory),
275 compatibilityAdvisory: Schema.optionalKey(ServerProviderCompatibilityAdvisory),
276 updateState: Schema.optionalKey(ServerProviderUpdateState),
277});
278export type ServerProvider = typeof ServerProvider.Type;
279​
280export const ServerProviders = ForwardCompatibleArray(ServerProvider);
281export type ServerProviders = typeof ServerProviders.Type;
282​
283export const isProviderAvailable = (snapshot: ServerProvider): boolean =>
284 snapshot.availability !== "unavailable";
285​
286/**
287 * Treat an absent `supportsTextGeneration` as supported so legacy
288 * producers, which all support application text generation, keep working
289 * without resending the field.
290 */
291export const isProviderTextGenerationCapable = (snapshot: ServerProvider): boolean =>
292 snapshot.supportsTextGeneration !== false;
293​
294export const ServerObservability = Schema.Struct({
295 logsDirectoryPath: TrimmedNonEmptyString,
296 localTracingEnabled: Schema.Boolean,
297 otlpTracesUrl: Schema.optional(TrimmedNonEmptyString),
298 otlpTracesEnabled: Schema.Boolean,
299 otlpMetricsUrl: Schema.optional(TrimmedNonEmptyString),
300 otlpMetricsEnabled: Schema.Boolean,
301 otlpLogsUrl: Schema.optional(TrimmedNonEmptyString),
302 otlpLogsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
303});
304export type ServerObservability = typeof ServerObservability.Type;
305​
306export const OtlpSignal = Schema.Literals(["traces", "metrics", "logs"]);
307export type OtlpSignal = typeof OtlpSignal.Type;
308​
309export const OtlpEndpointCheckInput = Schema.Struct({
310 signal: OtlpSignal,
311 url: TrimmedNonEmptyString.check(Schema.isPattern(/^https?:\/\/./i)),
312});
313export type OtlpEndpointCheckInput = typeof OtlpEndpointCheckInput.Type;
314​
315export const OtlpEndpointCheckResult = Schema.Union([
316 Schema.TaggedStruct("Accepted", { latencyMs: Schema.Number }),
317 Schema.TaggedStruct("Rejected", { status: Schema.Number }),
318 Schema.TaggedStruct("Unreachable", { timedOut: Schema.Boolean }),
319]);
320export type OtlpEndpointCheckResult = typeof OtlpEndpointCheckResult.Type;
321​
322export const ServerTraceDiagnosticsErrorKind = Schema.Literals([
323 "trace-file-not-found",
324 "trace-file-read-failed",
325]);
326export type ServerTraceDiagnosticsErrorKind = typeof ServerTraceDiagnosticsErrorKind.Type;
327​
328export const ServerTraceDiagnosticsSpanSummary = Schema.Struct({
329 name: TrimmedNonEmptyString,
330 count: NonNegativeInt,
331 failureCount: NonNegativeInt,
332 totalDurationMs: Schema.Number,
333 averageDurationMs: Schema.Number,
334 maxDurationMs: Schema.Number,
335});
336export type ServerTraceDiagnosticsSpanSummary = typeof ServerTraceDiagnosticsSpanSummary.Type;
337​
338export const ServerTraceDiagnosticsFailureSummary = Schema.Struct({
339 name: TrimmedNonEmptyString,
340 cause: TrimmedNonEmptyString,
341 count: NonNegativeInt,
342 lastSeenAt: Schema.DateTimeUtc,
343 traceId: TrimmedNonEmptyString,
344 spanId: TrimmedNonEmptyString,
345});
346export type ServerTraceDiagnosticsFailureSummary = typeof ServerTraceDiagnosticsFailureSummary.Type;
347​
348export const ServerTraceDiagnosticsRecentFailure = Schema.Struct({
349 name: TrimmedNonEmptyString,
350 cause: TrimmedNonEmptyString,
351 durationMs: Schema.Number,
352 endedAt: Schema.DateTimeUtc,
353 traceId: TrimmedNonEmptyString,
354 spanId: TrimmedNonEmptyString,
355});
356export type ServerTraceDiagnosticsRecentFailure = typeof ServerTraceDiagnosticsRecentFailure.Type;
357​
358export const ServerTraceDiagnosticsSpanOccurrence = Schema.Struct({
359 name: TrimmedNonEmptyString,
360 durationMs: Schema.Number,
361 endedAt: Schema.DateTimeUtc,
362 traceId: TrimmedNonEmptyString,
363 spanId: TrimmedNonEmptyString,
364});
365export type ServerTraceDiagnosticsSpanOccurrence = typeof ServerTraceDiagnosticsSpanOccurrence.Type;
366​
367export const ServerTraceDiagnosticsLogEvent = Schema.Struct({
368 spanName: TrimmedNonEmptyString,
369 level: TrimmedNonEmptyString,
370 message: TrimmedNonEmptyString,
371 seenAt: Schema.DateTimeUtc,
372 traceId: TrimmedNonEmptyString,
373 spanId: TrimmedNonEmptyString,
374});
375export type ServerTraceDiagnosticsLogEvent = typeof ServerTraceDiagnosticsLogEvent.Type;
376​
377export const ServerTraceDiagnosticsResult = Schema.Struct({
378 traceFilePath: TrimmedNonEmptyString,
379 scannedFilePaths: Schema.Array(TrimmedNonEmptyString),
380 readAt: Schema.DateTimeUtc,
381 recordCount: NonNegativeInt,
382 parseErrorCount: NonNegativeInt,
383 firstSpanAt: Schema.Option(Schema.DateTimeUtc),
384 lastSpanAt: Schema.Option(Schema.DateTimeUtc),
385 failureCount: NonNegativeInt,
386 interruptionCount: NonNegativeInt,
387 slowSpanThresholdMs: NonNegativeInt,
388 slowSpanCount: NonNegativeInt,
389 logLevelCounts: Schema.Record(TrimmedNonEmptyString, NonNegativeInt),
390 topSpansByCount: Schema.Array(ServerTraceDiagnosticsSpanSummary),
391 slowestSpans: Schema.Array(ServerTraceDiagnosticsSpanOccurrence),
392 commonFailures: Schema.Array(ServerTraceDiagnosticsFailureSummary),
393 latestFailures: Schema.Array(ServerTraceDiagnosticsRecentFailure),
394 latestWarningAndErrorLogs: Schema.Array(ServerTraceDiagnosticsLogEvent),
395 partialFailure: Schema.Option(Schema.Boolean),
396 error: Schema.Option(
397 Schema.Struct({
398 kind: ServerTraceDiagnosticsErrorKind,
399 message: TrimmedNonEmptyString,
400 }),
401 ),
402});
403export type ServerTraceDiagnosticsResult = typeof ServerTraceDiagnosticsResult.Type;
404​
405export const ServerProcessSignal = Schema.Literals(["SIGINT", "SIGKILL"]);
406export type ServerProcessSignal = typeof ServerProcessSignal.Type;
407​
408export const ServerProcessDiagnosticsEntry = Schema.Struct({
409 pid: PositiveInt,
410 startTimeMs: NonNegativeInt,
411 ppid: NonNegativeInt,
412 pgid: Schema.Option(Schema.Int),
413 status: TrimmedNonEmptyString,
414 cpuPercent: Schema.Number,
415 rssBytes: NonNegativeInt,
416 elapsed: TrimmedNonEmptyString,
417 command: TrimmedNonEmptyString,
418 depth: NonNegativeInt,
419 childPids: Schema.Array(PositiveInt),
420});
421export type ServerProcessDiagnosticsEntry = typeof ServerProcessDiagnosticsEntry.Type;
422​
423export const ServerProcessDiagnosticsResult = Schema.Struct({
424 serverPid: PositiveInt,
425 readAt: Schema.DateTimeUtc,
426 processCount: NonNegativeInt,
427 totalRssBytes: NonNegativeInt,
428 totalCpuPercent: Schema.Number,
429 processes: Schema.Array(ServerProcessDiagnosticsEntry),
430 error: Schema.Option(
431 Schema.Struct({
432 message: TrimmedNonEmptyString,
433 }),
434 ),
435});
436export type ServerProcessDiagnosticsResult = typeof ServerProcessDiagnosticsResult.Type;
437​
438export const ServerProcessResourceHistoryInput = Schema.Struct({
439 windowMs: NonNegativeInt,
440 bucketMs: NonNegativeInt,
441});
442export type ServerProcessResourceHistoryInput = typeof ServerProcessResourceHistoryInput.Type;
443​
444export const ServerProcessResourceHistoryBucket = Schema.Struct({
445 startedAt: Schema.DateTimeUtc,
446 endedAt: Schema.DateTimeUtc,
447 avgCpuPercent: Schema.Number,
448 maxCpuPercent: Schema.Number,
449 maxRssBytes: NonNegativeInt,
450 maxProcessCount: NonNegativeInt,
451});
452export type ServerProcessResourceHistoryBucket = typeof ServerProcessResourceHistoryBucket.Type;
453​
454export const ServerProcessResourceHistorySummary = Schema.Struct({
455 processKey: TrimmedNonEmptyString,
456 pid: PositiveInt,
457 ppid: NonNegativeInt,
458 command: TrimmedNonEmptyString,
459 depth: NonNegativeInt,
460 isServerRoot: Schema.Boolean,
461 firstSeenAt: Schema.DateTimeUtc,
462 lastSeenAt: Schema.DateTimeUtc,
463 currentCpuPercent: Schema.Number,
464 avgCpuPercent: Schema.Number,
465 maxCpuPercent: Schema.Number,
466 cpuSecondsApprox: Schema.Number,
467 currentRssBytes: NonNegativeInt,
468 maxRssBytes: NonNegativeInt,
469 sampleCount: NonNegativeInt,
470});
471export type ServerProcessResourceHistorySummary = typeof ServerProcessResourceHistorySummary.Type;
472​
473export const ServerProcessResourceHistoryFailureTag = Schema.Literals([
474 "ProcessDiagnosticsQueryTimeoutError",
475 "ProcessDiagnosticsQueryFailedError",
476 "ProcessDiagnosticsServerProcessSignalError",
477 "ProcessDiagnosticsNotDescendantError",
478 "ProcessDiagnosticsSignalFailedError",
479]);
480export type ServerProcessResourceHistoryFailureTag =
481 typeof ServerProcessResourceHistoryFailureTag.Type;
482​
483export const ServerProcessResourceHistoryResult = Schema.Struct({
484 readAt: Schema.DateTimeUtc,
485 windowMs: NonNegativeInt,
486 bucketMs: NonNegativeInt,
487 sampleIntervalMs: NonNegativeInt,
488 retainedSampleCount: NonNegativeInt,
489 totalCpuSecondsApprox: Schema.Number,
490 buckets: Schema.Array(ServerProcessResourceHistoryBucket),
491 topProcesses: Schema.Array(ServerProcessResourceHistorySummary),
492 error: Schema.Option(
493 Schema.Struct({
494 failureTag: ServerProcessResourceHistoryFailureTag,
495 message: TrimmedNonEmptyString,
496 }),
497 ),
498});
499export type ServerProcessResourceHistoryResult = typeof ServerProcessResourceHistoryResult.Type;
500​
501export const ServerSignalProcessInput = Schema.Struct({
502 pid: PositiveInt,
503 startTimeMs: NonNegativeInt,
504 signal: ServerProcessSignal,
505});
506export type ServerSignalProcessInput = typeof ServerSignalProcessInput.Type;
507​
508export const ServerSignalProcessResult = Schema.Struct({
509 pid: PositiveInt,
510 signal: ServerProcessSignal,
511 signaled: Schema.Boolean,
512 message: Schema.Option(TrimmedNonEmptyString),
513});
514export type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;
515​
516export const EnvironmentThemeColor = Schema.String.check(
517 Schema.isPattern(/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/),
518);
519export type EnvironmentThemeColor = typeof EnvironmentThemeColor.Type;
520​
521/**
522 * The appearance keywords are excluded outright: a published `dark.json`
523 * would otherwise capture every client whose stored preference is the stock
524 * `"dark"`, retinting people who never chose it.
525 */
526export const EnvironmentThemeId = Schema.String.check(
527 Schema.isPattern(/^(?!(?:system|light|dark)$)[a-z0-9](?:[a-z0-9-]{0,47})$/),
528);
529export type EnvironmentThemeId = typeof EnvironmentThemeId.Type;
530​
531const EnvironmentThemeColors = Schema.Record(
532 Schema.String.check(Schema.isPattern(/^[a-zA-Z][a-zA-Z0-9]{0,63}$/)),
533 TrimmedNonEmptyString.check(Schema.isMaxLength(64)),
534);
535​
536const environmentThemeFields = {
537 version: Schema.optional(Schema.Literal(1)),
538 name: TrimmedNonEmptyString.check(Schema.isMaxLength(48)),
539 appearance: Schema.Literals(["light", "dark"]),
540 /**
541 * When present, clients derive the full palette from them with the guided
542 * theme editor's generator and layer `colors` on top; when absent, `colors`
543 * is the palette, as in an exported theme file.
544 */
545 canvas: Schema.optional(EnvironmentThemeColor),
546 accent: Schema.optional(EnvironmentThemeColor),
547 colors: Schema.optional(EnvironmentThemeColors),
548 variants: Schema.optional(
549 Schema.Struct({
550 light: Schema.optional(EnvironmentThemeColors),
551 dark: Schema.optional(EnvironmentThemeColors),
552 }),
553 ),
554};
555​
556export const EnvironmentThemeFile = Schema.Struct(environmentThemeFields);
557export type EnvironmentThemeFile = typeof EnvironmentThemeFile.Type;
558​
559export const EnvironmentTheme = Schema.Struct({
560 id: EnvironmentThemeId,
561 ...environmentThemeFields,
562});
563export type EnvironmentTheme = typeof EnvironmentTheme.Type;
564​
565export function environmentThemeFileHasColors(file: EnvironmentThemeFile): boolean {
566 return (
567 (file.canvas !== undefined && file.accent !== undefined) ||
568 (file.colors !== undefined && Object.keys(file.colors).length > 0)
569 );
571​
572/**
573 * "tailnet" when the address is on this machine's Tailscale interface, "lan"
574 * for any other private address, including other VPNs in 100.64.0.0/10.
575 */
576export const ServerDirectEndpointKind = Schema.Literals(["lan", "tailnet"]);
577export type ServerDirectEndpointKind = typeof ServerDirectEndpointKind.Type;
578​
579export const ServerDirectEndpoint = Schema.Struct({
580 kind: ServerDirectEndpointKind,
581 httpBaseUrl: TrimmedNonEmptyString,
582});
583export type ServerDirectEndpoint = typeof ServerDirectEndpoint.Type;
584​
585export const ServerConfig = Schema.Struct({
586 environment: ExecutionEnvironmentDescriptor,
587 auth: ServerAuthDescriptor,
588 cwd: TrimmedNonEmptyString,
589 keybindingsConfigPath: TrimmedNonEmptyString,
590 keybindings: ResolvedKeybindingsConfig,
591 issues: ServerConfigIssues,
592 providers: ServerProviders,
593 availableEditors: ForwardCompatibleArray(EditorId),
594 remoteOpenTargets: Schema.optionalKey(ForwardCompatibleArray(RemoteOpenTarget)),
595 /**
596 * Hints only: the client checks each address answers as this environment
597 * before using it.
598 */
599 directEndpoints: Schema.optionalKey(ForwardCompatibleArray(ServerDirectEndpoint)),
600 observability: ServerObservability,
601 settings: ServerSettings,
602 shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
603 shellRevealInFileManager: Schema.optionalKey(Schema.Boolean),
604 shellRevealInFileManagerKind: Schema.optionalKey(FileManagerRevealKind),
605 threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
606 /**
607 * Clients must not send window fields to servers that don't advertise this.
608 */
609 threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),
610 reasoningMessages: Schema.optionalKey(Schema.Boolean),
611 threadFind: Schema.optionalKey(Schema.Boolean),
612 threadFindProgressive: Schema.optionalKey(Schema.Boolean),
613 scratchWorkspaceRoot: Schema.optionalKey(TrimmedNonEmptyString),
614 newProjectsRoot: Schema.optionalKey(TrimmedNonEmptyString),
615 /**
616 * Never sent in a config snapshot: the theme stream emits the current set
617 * before any change, so a snapshot carrying it too would hand every
618 * subscriber the same array twice per connect.
619 */
620 environmentThemes: Schema.optional(Schema.Array(EnvironmentTheme)),
621 /**
622 * Like themes, never in a snapshot: the source stream emits the current set
623 * on subscribe, and it stays absent for subscribers that did not opt in.
624 */
625 usageLimitSources: Schema.optional(UsageLimitSourceSnapshots),
626});
627export type ServerConfig = typeof ServerConfig.Type;
628​
629export function resolveEnvironmentMachineKind(
630 config: {
631 readonly environment: Pick<ExecutionEnvironmentDescriptor, "platform">;
632 readonly settings?: Pick<ServerSettings, "environmentIcon">;
633 } | null,
634): EnvironmentMachineKind {
635 return config?.settings?.environmentIcon ?? config?.environment.platform.machine ?? "server";
637​
638const ServerUpsertKeybindingReplaceTarget = Schema.Struct({
639 key: KeybindingValue,
640 command: KeybindingCommand,
641 when: Schema.optional(KeybindingWhen),
642});
643​
644export const ServerUpsertKeybindingInput = Schema.Struct({
645 key: KeybindingValue,
646 command: KeybindingCommand,
647 when: Schema.optional(KeybindingWhen),
648 replace: Schema.optional(ServerUpsertKeybindingReplaceTarget),
649});
650export type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;
651​
652export const ServerRemoveKeybindingInput = ServerUpsertKeybindingReplaceTarget;
653export type ServerRemoveKeybindingInput = typeof ServerRemoveKeybindingInput.Type;
654​
655export const ServerUpsertKeybindingResult = Schema.Struct({
656 keybindings: ResolvedKeybindingsConfig,
657 issues: ServerConfigIssues,
658});
659export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.Type;
660​
661export const ServerRemoveKeybindingResult = ServerUpsertKeybindingResult;
662export type ServerRemoveKeybindingResult = typeof ServerRemoveKeybindingResult.Type;
663​
664export const ServerConfigUpdatedPayload = Schema.Struct({
665 issues: ServerConfigIssues,
666 providers: ServerProviders,
667 settings: Schema.optional(ServerSettings),
668});
669export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
670​
671export const ServerConfigKeybindingsUpdatedPayload = Schema.Struct({
672 keybindings: ResolvedKeybindingsConfig,
673 issues: ServerConfigIssues,
674});
675export type ServerConfigKeybindingsUpdatedPayload =
676 typeof ServerConfigKeybindingsUpdatedPayload.Type;
677​
678export const ServerConfigProviderStatusesPayload = Schema.Struct({
679 providers: ServerProviders,
680});
681export type ServerConfigProviderStatusesPayload = typeof ServerConfigProviderStatusesPayload.Type;
682​
683export const ServerConfigSettingsUpdatedPayload = Schema.Struct({
684 settings: ServerSettings,
685});
686export type ServerConfigSettingsUpdatedPayload = typeof ServerConfigSettingsUpdatedPayload.Type;
687​
688export const ServerConfigStreamSnapshotEvent = Schema.Struct({
689 version: Schema.Literal(1),
690 type: Schema.Literal("snapshot"),
691 config: ServerConfig,
692});
693export type ServerConfigStreamSnapshotEvent = typeof ServerConfigStreamSnapshotEvent.Type;
694​
695export const ServerConfigStreamKeybindingsUpdatedEvent = Schema.Struct({
696 version: Schema.Literal(1),
697 type: Schema.Literal("keybindingsUpdated"),
698 payload: ServerConfigKeybindingsUpdatedPayload,
699});
700export type ServerConfigStreamKeybindingsUpdatedEvent =
701 typeof ServerConfigStreamKeybindingsUpdatedEvent.Type;
702​
703export const ServerConfigStreamProviderStatusesEvent = Schema.Struct({
704 version: Schema.Literal(1),
705 type: Schema.Literal("providerStatuses"),
706 payload: ServerConfigProviderStatusesPayload,
707});
708export type ServerConfigStreamProviderStatusesEvent =
709 typeof ServerConfigStreamProviderStatusesEvent.Type;
710​
711export const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({
712 version: Schema.Literal(1),
713 type: Schema.Literal("settingsUpdated"),
714 payload: ServerConfigSettingsUpdatedPayload,
715});
716export type ServerConfigStreamSettingsUpdatedEvent =
717 typeof ServerConfigStreamSettingsUpdatedEvent.Type;
718​
719export const ServerConfigEnvironmentThemesUpdatedPayload = Schema.Struct({
720 themes: Schema.Array(EnvironmentTheme),
721});
722export type ServerConfigEnvironmentThemesUpdatedPayload =
723 typeof ServerConfigEnvironmentThemesUpdatedPayload.Type;
724​
725export const ServerConfigStreamEnvironmentThemesUpdatedEvent = Schema.Struct({
726 version: Schema.Literal(1),
727 type: Schema.Literal("environmentThemesUpdated"),
728 payload: ServerConfigEnvironmentThemesUpdatedPayload,
729});
730export type ServerConfigStreamEnvironmentThemesUpdatedEvent =
731 typeof ServerConfigStreamEnvironmentThemesUpdatedEvent.Type;
732​
733export const ServerConfigUsageLimitSourcesUpdatedPayload = Schema.Struct({
734 sources: UsageLimitSourceSnapshots,
735});
736export type ServerConfigUsageLimitSourcesUpdatedPayload =
737 typeof ServerConfigUsageLimitSourcesUpdatedPayload.Type;
738​
739export const ServerConfigStreamUsageLimitSourcesUpdatedEvent = Schema.Struct({
740 version: Schema.Literal(1),
741 type: Schema.Literal("usageLimitSourcesUpdated"),
742 payload: ServerConfigUsageLimitSourcesUpdatedPayload,
743});
744export type ServerConfigStreamUsageLimitSourcesUpdatedEvent =
745 typeof ServerConfigStreamUsageLimitSourcesUpdatedEvent.Type;
746​
747export const ServerConfigStreamEvent = Schema.Union([
748 ServerConfigStreamSnapshotEvent,
749 ServerConfigStreamKeybindingsUpdatedEvent,
750 ServerConfigStreamProviderStatusesEvent,
751 ServerConfigStreamSettingsUpdatedEvent,
752 ServerConfigStreamEnvironmentThemesUpdatedEvent,
753 ServerConfigStreamUsageLimitSourcesUpdatedEvent,
754]);
755export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;
756​
757export const ServerSelfUpdateOutcome = Schema.Struct({
758 id: TrimmedNonEmptyString,
759 fromVersion: TrimmedNonEmptyString,
760 targetVersion: TrimmedNonEmptyString,
761 status: Schema.Literals(["committed", "rolled-back", "failed"]),
762 reason: Schema.optionalKey(TrimmedNonEmptyString),
763});
764export type ServerSelfUpdateOutcome = typeof ServerSelfUpdateOutcome.Type;
765​
766export const ServerLifecycleReadyPayload = Schema.Struct({
767 at: IsoDateTime,
768 environment: ExecutionEnvironmentDescriptor,
769 updateOutcome: Schema.optionalKey(ServerSelfUpdateOutcome),
770});
771export type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type;
772​
773export const ServerLifecycleWelcomePayload = Schema.Struct({
774 environment: ExecutionEnvironmentDescriptor,
775 cwd: TrimmedNonEmptyString,
776 projectName: TrimmedNonEmptyString,
777 bootstrapStatus: Schema.optional(Schema.Literals(["pending", "complete"])),
778 bootstrapProjectId: Schema.optional(ProjectId),
779 bootstrapThreadId: Schema.optional(ThreadId),
780 bootstrapProjectCreated: Schema.optional(Schema.Boolean),
781 bootstrapThreadCreated: Schema.optional(Schema.Boolean),
782});
783export type ServerLifecycleWelcomePayload = typeof ServerLifecycleWelcomePayload.Type;
784​
785export const ServerLifecycleLegacyThreadMigrationPayload = Schema.Struct({
786 status: Schema.Union([Schema.Literal("running"), Schema.Literal("complete")]),
787 totalThreadCount: NonNegativeInt,
788});
789export type ServerLifecycleLegacyThreadMigrationPayload =
790 typeof ServerLifecycleLegacyThreadMigrationPayload.Type;
791​
792export const ServerLifecycleStreamWelcomeEvent = Schema.Struct({
793 version: Schema.Literal(1),
794 sequence: NonNegativeInt,
795 type: Schema.Literal("welcome"),
796 payload: ServerLifecycleWelcomePayload,
797});
798export type ServerLifecycleStreamWelcomeEvent = typeof ServerLifecycleStreamWelcomeEvent.Type;
799​
800export const ServerLifecycleStreamReadyEvent = Schema.Struct({
801 version: Schema.Literal(1),
802 sequence: NonNegativeInt,
803 type: Schema.Literal("ready"),
804 payload: ServerLifecycleReadyPayload,
805});
806export type ServerLifecycleStreamReadyEvent = typeof ServerLifecycleStreamReadyEvent.Type;
807​
808export const ServerLifecycleStreamLegacyThreadMigrationEvent = Schema.Struct({
809 version: Schema.Literal(1),
810 sequence: NonNegativeInt,
811 type: Schema.Literal("legacyThreadMigration"),
812 payload: ServerLifecycleLegacyThreadMigrationPayload,
813});
814export type ServerLifecycleStreamLegacyThreadMigrationEvent =
815 typeof ServerLifecycleStreamLegacyThreadMigrationEvent.Type;
816​
817export const ServerLifecycleStreamEvent = Schema.Union([
818 ServerLifecycleStreamWelcomeEvent,
819 ServerLifecycleStreamReadyEvent,
820 ServerLifecycleStreamLegacyThreadMigrationEvent,
821]);
822export type ServerLifecycleStreamEvent = typeof ServerLifecycleStreamEvent.Type;
823​
824export const ServerProviderUpdatedPayload = Schema.Struct({
825 providers: ServerProviders,
826});
827export type ServerProviderUpdatedPayload = typeof ServerProviderUpdatedPayload.Type;
828​
829export const ServerProviderUpdateInput = Schema.Struct({
830 provider: ProviderDriverKind,
831 targetVersion: Schema.optionalKey(TrimmedNonEmptyString),
832 instanceId: Schema.optionalKey(ProviderInstanceId),
833});
834export type ServerProviderUpdateInput = typeof ServerProviderUpdateInput.Type;
835​
836export class ServerProviderUpdateError extends Schema.TaggedError<ServerProviderUpdateError>()(
837 "ServerProviderUpdateError",
838 {
839 provider: ProviderDriverKind,
840 reason: TrimmedNonEmptyString,
841 cause: Schema.optional(Schema.Defect()),
842 },
843) {
844 override get message(): string {
845 return `Provider update failed for ${this.provider}: ${this.reason}`;
846 }
848​
849export const ServerSelfUpdateInput = Schema.Struct({
850 /** Exact npm version of the `t3` package to install (never a dist-tag, so
851 the server and the acknowledging client agree on what was requested). */
852 targetVersion: TrimmedNonEmptyString,
853 continueRunningThreads: Schema.optionalKey(Schema.Boolean),
854});
855export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
856​
857export const ServerSelfUpdateResult = Schema.Struct({
858 targetVersion: TrimmedNonEmptyString,
859 method: ServerSelfUpdateMethod,
860 updateId: Schema.optionalKey(TrimmedNonEmptyString),
861 desktopUpdateToken: Schema.optionalKey(TrimmedNonEmptyString),
862});
863export type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;
864​
865export const DesktopUpdateCommitInput = Schema.Struct({
866 requestId: TrimmedNonEmptyString,
867});
868export type DesktopUpdateCommitInput = typeof DesktopUpdateCommitInput.Type;
869​
870export const ServerSelfUpdateProgressStage = Schema.Literals(["downloading", "installing"]);
871export type ServerSelfUpdateProgressStage = typeof ServerSelfUpdateProgressStage.Type;
872​
873export const ServerSelfUpdateProgressEvent = Schema.Union([
874 Schema.Struct({
875 type: Schema.Literal("progress"),
876 stage: ServerSelfUpdateProgressStage,
877 }),
878 Schema.Struct({
879 type: Schema.Literal("complete"),
880 result: ServerSelfUpdateResult,
881 }),
882]);
883export type ServerSelfUpdateProgressEvent = typeof ServerSelfUpdateProgressEvent.Type;
884​
885export class ServerSelfUpdateError extends Schema.TaggedError<ServerSelfUpdateError>()(
886 "ServerSelfUpdateError",
887 {
888 reason: TrimmedNonEmptyString,
889 cause: Schema.optional(Schema.Defect()),
890 },
891) {
892 override get message(): string {
893 return `Server update failed: ${this.reason}`;
894 }