@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 969 lines 36.6 KB
Raw
1 import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe";
2 import {
3 AcpRegistryListProvidersResult,
4 AcpRegistryOperationError,
5 AcpRegistryListSessionsResult,
6 AcpRegistryProbeResult,
7 type AcpRegistryProbeAuthMethod,
8 type AcpRegistryProbeModel,
9 type AcpRegistryUrlAuthAction,
10 type ProviderInstanceId,
11 type ServerProviderSkill,
12 type ServerProviderSlashCommand,
13 } from "@t3tools/contracts";
14 import { AcpRegistrySettings } from "../settings.ts";
15 import * as SecureRandom from "effect/crypto/SecureRandom";
16 import * as Deferred from "effect/Deferred";
17 import * as Duration from "effect/Duration";
18 import * as Effect from "effect/Effect";
19 import * as FileSystem from "effect/FileSystem";
20 import * as Layer from "effect/Layer";
21 import * as Option from "effect/Option";
22 import * as Path from "effect/Path";
23 import * as Ref from "effect/Ref";
24 import * as Result from "effect/Result";
25 import * as Schema from "effect/Schema";
26 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
27 import type * as EffectAcpErrors from "effect-acp/errors";
28 import type * as EffectAcpSchema from "effect-acp/compat";
29
30 import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
31 import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
32 import {
33 findModelConfigOption,
34 parseSessionModeState,
35 } from "@t3tools/provider-acp/server/runtimeModel";
36 import {
37 acpProviderOptionDescriptors,
38 flattenSelectChoices,
39 isAcpThoughtLevelOption,
40 } from "@t3tools/provider-acp/server/sessionConfig";
41 import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
42 import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
43
44 const MAX_AUTH_METHODS = 32;
45 const MAX_MODELS = 256;
46 const MAX_ID_LENGTH = 128;
47 const MAX_NAME_LENGTH = 160;
48 const MAX_DESCRIPTION_LENGTH = 1_024;
49 const MAX_COMMAND_LINE_LENGTH = 2_048;
50 const PROBE_TIMEOUT_MS = 60_000;
51 const COMMAND_ADVERTISEMENT_GRACE = "500 millis";
52 // Agents that fetch their catalog after session setup (Qoder CLI, OpenCode)
53 // settle it in seconds, not milliseconds; commands arrive much sooner.
54 const MODEL_ADVERTISEMENT_GRACE = "5 seconds";
55 const PROBE_SESSION_DELETE_TIMEOUT = "5 seconds";
56 const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
57
58 const boundedText = (value: string, maximumLength: number): string =>
59 value.trim().slice(0, maximumLength);
60
61 const boundedOpaqueValue = (value: string, maximumLength: number): string | undefined =>
62 value.length > 0 && value === value.trim() && value.length <= maximumLength ? value : undefined;
63
64 /**
65 * The session's reasoning option with the levels a model advertises in `_meta`, in the
66 * shape Grok uses. Null when the model has none, undefined when it says nothing.
67 */
68 function advertisedReasoningEffort(
69 option: EffectAcpSchema.SessionConfigOption | undefined,
70 meta: Readonly<Record<string, unknown>> | null | undefined,
71 ): AcpRegistryProbeModel["reasoningEffort"] {
72 if (option?.type !== "select" || meta == null) return undefined;
73 if (meta.supportsReasoningEffort === false) return null;
74 if (!Array.isArray(meta.reasoningEfforts)) return undefined;
75 const options = meta.reasoningEfforts.flatMap((level: unknown) =>
76 typeof level === "object" &&
77 level !== null &&
78 "value" in level &&
79 typeof level.value === "string"
80 ? [
81 {
82 value: level.value,
83 name: "label" in level && typeof level.label === "string" ? level.label : level.value,
84 },
85 ]
86 : [],
87 );
88 const currentValue = typeof meta.reasoningEffort === "string" ? meta.reasoningEffort : "";
89 return (
90 acpProviderOptionDescriptors({
91 configOptions: [{ ...option, options, currentValue }],
92 modeState: undefined,
93 })[0] ?? null
94 );
95 }
96
97 export function normalizeAcpRegistryWebUrl(value: string): string | undefined {
98 if (value.length > 2_048 || !URL.canParse(value)) return undefined;
99 const url = new URL(value);
100 return url.protocol === "https:" || url.protocol === "http:" ? url.href : undefined;
101 }
102
103 function normalizedModel(id: string, candidate: AcpRegistryProbeModel): AcpRegistryProbeModel {
104 return {
105 id,
106 name: boundedText(candidate.name, MAX_NAME_LENGTH) || id,
107 description:
108 candidate.description === null
109 ? null
110 : boundedText(candidate.description, MAX_DESCRIPTION_LENGTH) || null,
111 };
112 }
113
114 function normalizeModels(
115 candidates: ReadonlyArray<AcpRegistryProbeModel>,
116 currentModelId: string | null,
117 ): ReadonlyArray<AcpRegistryProbeModel> {
118 const seen = new Set<string>();
119 const models: Array<AcpRegistryProbeModel> = [];
120 for (const candidate of candidates) {
121 if (models.length === MAX_MODELS) break;
122 const id = boundedOpaqueValue(candidate.id, MAX_ID_LENGTH);
123 if (id === undefined || seen.has(id)) continue;
124 seen.add(id);
125 models.push(normalizedModel(id, candidate));
126 }
127 // Keep the running model visible even when its advertised position exceeds the cap.
128 if (currentModelId !== null && models.length === MAX_MODELS && !seen.has(currentModelId)) {
129 const current = candidates.find((candidate) => candidate.id === currentModelId);
130 if (current !== undefined) {
131 models[MAX_MODELS - 1] = normalizedModel(currentModelId, current);
132 }
133 }
134 return models;
135 }
136
137 export interface AcpRegistryAuthSpawnContext {
138 readonly command: string;
139 readonly args: ReadonlyArray<string>;
140 }
141
142 const SHELL_SAFE_TOKEN = /^[A-Za-z0-9_@%+=:,./-]+$/u;
143
144 function shellDisplayToken(token: string): string {
145 return SHELL_SAFE_TOKEN.test(token) ? token : `'${token.replaceAll("'", `'\\''`)}'`;
146 }
147
148 function terminalAuthCommand(
149 method: Extract<EffectAcpSchema.AuthMethod, { readonly type: "terminal" }>,
150 spawn: AcpRegistryAuthSpawnContext,
151 ): string | undefined {
152 const environmentPrefix = Object.entries(method.env ?? {}).map(
153 ([name, value]) => `${name}=${shellDisplayToken(value)}`,
154 );
155 const command = [spawn.command, ...spawn.args, ...(method.args ?? [])].map(shellDisplayToken);
156 const displayCommand = [...environmentPrefix, ...command].join(" ");
157 return displayCommand.length <= MAX_COMMAND_LINE_LENGTH ? displayCommand : undefined;
158 }
159
160 export function normalizeAcpRegistryAuthMethods(
161 methods: ReadonlyArray<EffectAcpSchema.AuthMethod> | undefined,
162 spawn?: AcpRegistryAuthSpawnContext,
163 ): ReadonlyArray<AcpRegistryProbeAuthMethod> {
164 const normalized: Array<AcpRegistryProbeAuthMethod> = [];
165 for (const method of methods ?? []) {
166 const id = boundedOpaqueValue(method.id, MAX_ID_LENGTH);
167 if (id === undefined) continue;
168 const type = method.type ?? "agent";
169 const envVarNames =
170 type === "env_var" && "vars" in method
171 ? method.vars
172 .flatMap((variable) => {
173 const name = boundedOpaqueValue(variable.name, MAX_ID_LENGTH);
174 return name === undefined ? [] : [name];
175 })
176 .slice(0, 16)
177 : [];
178 const command =
179 spawn !== undefined && "type" in method && method.type === "terminal"
180 ? terminalAuthCommand(method, spawn)
181 : undefined;
182 const link =
183 type === "env_var" && "link" in method && method.link
184 ? normalizeAcpRegistryWebUrl(method.link)
185 : undefined;
186 normalized.push({
187 id,
188 name: boundedText(method.name, MAX_NAME_LENGTH) || id,
189 description:
190 method.description == null
191 ? null
192 : boundedText(method.description, MAX_DESCRIPTION_LENGTH) || null,
193 type,
194 ...(command === undefined ? {} : { command }),
195 ...(envVarNames.length > 0 ? { envVarNames } : {}),
196 ...(link === undefined ? {} : { link }),
197 });
198 if (normalized.length === MAX_AUTH_METHODS) break;
199 }
200 return normalized;
201 }
202
203 export interface AcpRegistryAvailableCommands {
204 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
205 readonly skills: ReadonlyArray<ServerProviderSkill>;
206 }
207
208 export interface AcpRegistryLiveConfiguration {
209 readonly models: ReadonlyArray<AcpRegistryProbeModel>;
210 readonly currentModelId: string | null;
211 readonly configOptions: AcpRegistryProbeResult["configOptions"];
212 readonly modelOptionIds?: NonNullable<AcpRegistryProbeResult["modelOptionIds"]>;
213 // A single model from an explicit select is the agent's deliberate catalog
214 // (e.g. an entitlement change), not a cold-start placeholder.
215 readonly modelsFromModelSelect?: boolean;
216 }
217
218 export function normalizeAcpRegistryLiveConfiguration(
219 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
220 modeState?: Parameters<typeof acpProviderOptionDescriptors>[0]["modeState"],
221 modelState?: EffectAcpSchema.SessionModelState | null,
222 ): AcpRegistryLiveConfiguration {
223 const modelOption = findModelConfigOption(configOptions);
224 const currentModelId =
225 modelOption?.type === "select" ? modelOption.currentValue : modelState?.currentModelId;
226 const candidates =
227 modelOption === undefined
228 ? (modelState?.availableModels ?? []).map((model) => ({
229 id: model.modelId,
230 name: model.name,
231 description: model.description ?? null,
232 }))
233 : flattenSelectChoices(modelOption.options).map((model) => ({
234 id: model.value,
235 name: model.name,
236 description: model.description ?? null,
237 }));
238 const boundedCurrentModelId =
239 currentModelId === undefined
240 ? null
241 : (boundedOpaqueValue(currentModelId, MAX_ID_LENGTH) ?? null);
242 const effortOption =
243 configOptions.find((option) => option.category === "thought_level") ??
244 configOptions.find(isAcpThoughtLevelOption);
245 const models = normalizeModels(candidates, boundedCurrentModelId).map((model) => {
246 const reasoningEffort = advertisedReasoningEffort(
247 effortOption,
248 modelState?.availableModels.find((info) => info.modelId === model.id)?._meta,
249 );
250 return reasoningEffort === undefined ? model : { ...model, reasoningEffort };
251 });
252 const descriptors = acpProviderOptionDescriptors({ configOptions, modeState });
253 const modelOptionIds = new Set(
254 configOptions
255 .filter((option) => isAcpThoughtLevelOption(option) || option.category === "model_config")
256 .map((option) => option.id),
257 );
258 return {
259 models,
260 currentModelId: models.some((model) => model.id === boundedCurrentModelId)
261 ? boundedCurrentModelId
262 : null,
263 configOptions: descriptors,
264 modelOptionIds: descriptors
265 .filter((descriptor) => modelOptionIds.has(descriptor.id))
266 .map((descriptor) => descriptor.id),
267 modelsFromModelSelect: modelOption !== undefined,
268 };
269 }
270
271 const emptyAcpRegistryAvailableCommands = (): AcpRegistryAvailableCommands => ({
272 slashCommands: [],
273 skills: [],
274 });
275
276 export function acpRegistryAdvertisesModelCatalog(
277 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
278 modelState?: EffectAcpSchema.SessionModelState | null,
279 ): boolean {
280 const modelOption = findModelConfigOption(configOptions);
281 return (
282 (modelOption !== undefined && flattenSelectChoices(modelOption.options).length > 1) ||
283 (modelState?.availableModels?.length ?? 0) > 1
284 );
285 }
286
287 export function normalizeAcpRegistryCommands(
288 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
289 ): AcpRegistryAvailableCommands {
290 const seen = new Set<string>();
291 const slashCommands: Array<ServerProviderSlashCommand> = [];
292 const skills: Array<ServerProviderSkill> = [];
293 for (const command of commands) {
294 const name = boundedOpaqueValue(command.name, MAX_ID_LENGTH);
295 if (name === undefined) continue;
296 const key = name.toLowerCase();
297 if (seen.has(key)) continue;
298 seen.add(key);
299 const description = boundedText(command.description, MAX_DESCRIPTION_LENGTH);
300 const hint = command.input ? boundedText(command.input.hint, MAX_DESCRIPTION_LENGTH) : "";
301 if (name.startsWith("$")) {
302 const skillName = boundedOpaqueValue(name.slice(1), MAX_ID_LENGTH);
303 if (skillName === undefined) continue;
304 skills.push({
305 name: skillName,
306 ...(description ? { description } : {}),
307 path: `acp://skill/${encodeURIComponent(skillName)}`,
308 scope: "agent",
309 enabled: true,
310 });
311 } else {
312 slashCommands.push({
313 name,
314 ...(description ? { description } : {}),
315 ...(hint ? { input: { hint } } : {}),
316 });
317 }
318 }
319 return { slashCommands, skills };
320 }
321
322 export function acpRegistryProbeResult(
323 instanceId: ProviderInstanceId,
324 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
325 icon: string | null = null,
326 spawn?: AcpRegistryAuthSpawnContext,
327 liveConfiguration?: AcpRegistryLiveConfiguration,
328 ): AcpRegistryProbeResult {
329 const configuration =
330 liveConfiguration ??
331 normalizeAcpRegistryLiveConfiguration(
332 started.sessionSetupResult.configOptions ?? [],
333 parseSessionModeState(started.sessionSetupResult),
334 started.sessionSetupResult.models,
335 );
336 return AcpRegistryProbeResult.make({
337 instanceId,
338 ready: true,
339 icon,
340 ...(started.initializeResult.agentInfo?.version?.trim()
341 ? { agentVersion: boundedText(started.initializeResult.agentInfo.version, MAX_ID_LENGTH) }
342 : {}),
343 authMethods: normalizeAcpRegistryAuthMethods(started.initializeResult.authMethods, spawn),
344 sessionManagement: {
345 canList: started.initializeResult.agentCapabilities?.sessionCapabilities?.list != null,
346 canLoad: started.initializeResult.agentCapabilities?.loadSession === true,
347 canResume: started.initializeResult.agentCapabilities?.sessionCapabilities?.resume != null,
348 canLogout: started.initializeResult.agentCapabilities?.auth?.logout != null,
349 canDelete: started.initializeResult.agentCapabilities?.sessionCapabilities?.delete != null,
350 canConfigureProviders: started.initializeResult.agentCapabilities?.providers != null,
351 },
352 ...configuration,
353 });
354 }
355
356 export function acpRegistryProbeFailure(
357 error: EffectAcpErrors.AcpError,
358 authMethods: ReadonlyArray<AcpRegistryProbeAuthMethod> = [],
359 authAction?: AcpRegistryUrlAuthAction,
360 ): AcpRegistryOperationError {
361 const detail = error._tag === "AcpTransportError" && error.detail ? error.detail : error.message;
362 const authenticationFailed =
363 (error._tag === "AcpRequestError" && error.code === -32000) ||
364 /\b(?:authenticat(?:e|ed|es|ing|ion)|credentials?|log(?:[\s-]+)?in)\b/iu.test(detail);
365 return new AcpRegistryOperationError({
366 reason: authenticationFailed ? "authentication_failed" : "probe_failed",
367 message: authenticationFailed
368 ? "The ACP agent could not complete authentication."
369 : "The ACP agent could not create a test session.",
370 cause: error,
371 ...(authMethods.length > 0 ? { authMethods } : {}),
372 ...(authAction === undefined ? {} : { authAction }),
373 });
374 }
375
376 export interface AcpRegistryConfigurationProbeInput {
377 readonly instanceId: ProviderInstanceId;
378 readonly settings: AcpRegistrySettings;
379 readonly cwd: string;
380 readonly environment: NodeJS.ProcessEnv;
381 }
382
383 type AcpRegistryManagementInput = AcpRegistryConfigurationProbeInput;
384
385 export interface AcpRegistryConfigurationProbeResult {
386 readonly probe: AcpRegistryProbeResult;
387 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
388 readonly skills: ReadonlyArray<ServerProviderSkill>;
389 }
390
391 export type AcpRegistryConfigurationProbe<Requirements = never> = (
392 input: AcpRegistryConfigurationProbeInput,
393 ) => Effect.Effect<AcpRegistryConfigurationProbeResult, AcpRegistryOperationError, Requirements>;
394
395 const isolateDeepSeekProbeHistory = Effect.fn("AcpRegistryProbe.isolateDeepSeekProbeHistory")(
396 function* (commandPath: string, spawn: AcpSessionRuntime.AcpSpawnInput) {
397 const executable = (commandPath || spawn.command).split(/[\\/]/u).at(-1) ?? "";
398 if (!/^dsh(?:\.cmd|\.exe)?$/iu.test(executable)) return spawn;
399
400 const argumentSeparator = spawn.args.indexOf("--");
401 const launcherArgs =
402 argumentSeparator === -1 ? spawn.args : spawn.args.slice(0, argumentSeparator);
403 const usesAcpProfile =
404 launcherArgs[0] === "acp" ||
405 launcherArgs.includes("--profile=acp") ||
406 launcherArgs.some((arg, index) => arg === "--profile" && launcherArgs[index + 1] === "acp");
407 if (!usesAcpProfile) return spawn;
408
409 // DeepSeek persists session/new before any prompt and does not advertise session/delete.
410 const fs = yield* FileSystem.FileSystem;
411 const path = yield* Path.Path;
412 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-dsh-acp-probe-" });
413 const patchPath = path.join(directory, "probe.json");
414 const patch = yield* encodeJson([
415 { id: "session-persistence-jsonl", config: { root: path.join(directory, "sessions") } },
416 { id: "session-projection-cache", disabled: true },
417 ]);
418 yield* fs.writeFileString(patchPath, patch);
419 return {
420 ...spawn,
421 args: [...launcherArgs, "--patch", patchPath, ...spawn.args.slice(launcherArgs.length)],
422 };
423 },
424 );
425
426 export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeConfiguration")(
427 function* (
428 input: AcpRegistryConfigurationProbeInput,
429 ): Effect.fn.Return<
430 AcpRegistryConfigurationProbeResult,
431 AcpRegistryOperationError,
432 | AcpRegistrySupport.AcpRegistryCatalog
433 | ChildProcessSpawner.ChildProcessSpawner
434 | FileSystem.FileSystem
435 | Path.Path
436 | SecureRandom.SecureRandom
437 > {
438 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
439 const probeTimeoutMs = resolveProviderProbeTimeoutMs(
440 "acp_registry",
441 PROBE_TIMEOUT_MS,
442 input.environment,
443 );
444 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
445 const random = yield* SecureRandom.SecureRandom;
446 const pty = yield* Effect.serviceOption(PtyAdapter.PtyAdapter);
447
448 const result = yield* Effect.gen(function* () {
449 // Resolution may install packages; bound it by the probe deadline.
450 const resolved = yield* catalog
451 .resolve(input.settings, input.cwd, input.environment)
452 .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError));
453 const spawn = yield* isolateDeepSeekProbeHistory(
454 input.settings.commandPath,
455 resolved.spawn,
456 ).pipe(
457 Effect.mapError(
458 (cause) =>
459 new AcpRegistryOperationError({
460 reason: "probe_failed",
461 message: "Could not prepare temporary history for the DeepSeek Harness probe.",
462 cause,
463 }),
464 ),
465 );
466 const authMethodsRef = yield* Ref.make<ReadonlyArray<AcpRegistryProbeAuthMethod>>([]);
467 const authActionRef = yield* Ref.make<AcpRegistryUrlAuthAction | undefined>(undefined);
468 const runtimeCoordinator = yield* Effect.serviceOption(
469 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
470 );
471 const runtimeContext = yield* Layer.build(
472 AcpSessionRuntime.layer({
473 spawn,
474 cwd: input.cwd,
475 clientCapabilities: {
476 auth: { terminal: Option.isSome(pty) },
477 elicitation: { url: {} },
478 fs: { readTextFile: false, writeTextFile: false },
479 terminal: false,
480 },
481 clientInfo: { name: "t3-code-provider-test", version: "0.0.0" },
482 authenticateOnAuthRequired: false,
483 onInitialized: (initializeResult) =>
484 Ref.set(
485 authMethodsRef,
486 normalizeAcpRegistryAuthMethods(initializeResult.authMethods, {
487 command: resolved.spawn.command,
488 args: resolved.spawn.args,
489 }),
490 ),
491 ...(input.settings.authMethodId ? { authMethodId: input.settings.authMethodId } : {}),
492 }).pipe(
493 Layer.provide(
494 Layer.mergeAll(
495 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
496 Layer.succeed(SecureRandom.SecureRandom, random),
497 ),
498 ),
499 ),
500 );
501 const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
502 Effect.provide(runtimeContext),
503 );
504 const commandsRef = yield* Ref.make<AcpRegistryAvailableCommands>(
505 emptyAcpRegistryAvailableCommands(),
506 );
507 const commandsAdvertised = yield* Deferred.make<void>();
508 const configOptionsRef = yield* Ref.make<
509 ReadonlyArray<EffectAcpSchema.SessionConfigOption> | undefined
510 >(undefined);
511 const modelsAdvertised = yield* Deferred.make<void>();
512 yield* runtime.handleElicitation((request) =>
513 Effect.gen(function* () {
514 if (
515 request.mode !== "url" ||
516 !("url" in request) ||
517 !("elicitationId" in request) ||
518 typeof request.url !== "string" ||
519 typeof request.elicitationId !== "string"
520 ) {
521 return { action: "decline" } as const;
522 }
523 const url = normalizeAcpRegistryWebUrl(request.url);
524 const elicitationId = boundedOpaqueValue(request.elicitationId, MAX_ID_LENGTH);
525 if (url === undefined || elicitationId === undefined) {
526 return { action: "decline" } as const;
527 }
528 const action: AcpRegistryUrlAuthAction = {
529 elicitationId,
530 url,
531 message: boundedText(request.message, MAX_DESCRIPTION_LENGTH),
532 };
533 yield* Ref.set(authActionRef, action);
534 const accepted = yield* Option.match(runtimeCoordinator, {
535 onNone: () => Effect.succeed(false),
536 onSome: (coordinator) => coordinator.requestUrlAuthentication(input.instanceId, action),
537 });
538 return accepted ? ({ action: "accept" } as const) : ({ action: "decline" } as const);
539 }),
540 );
541 yield* runtime.handleSessionUpdate((notification) => {
542 const update = notification.update;
543 if (update.sessionUpdate === "available_commands_update") {
544 return Ref.set(commandsRef, normalizeAcpRegistryCommands(update.availableCommands)).pipe(
545 Effect.andThen(Deferred.succeed(commandsAdvertised, undefined)),
546 Effect.asVoid,
547 );
548 }
549 if (update.sessionUpdate === "config_option_update") {
550 const hasAdvertisedModels = acpRegistryAdvertisesModelCatalog(update.configOptions);
551 return Ref.set(configOptionsRef, update.configOptions).pipe(
552 Effect.andThen(
553 hasAdvertisedModels
554 ? Deferred.succeed(modelsAdvertised, undefined).pipe(Effect.asVoid)
555 : Effect.void,
556 ),
557 );
558 }
559 return Effect.void;
560 });
561 const startResult = yield* Effect.result(runtime.start());
562 if (Result.isFailure(startResult)) {
563 return yield* acpRegistryProbeFailure(
564 startResult.failure,
565 yield* Ref.get(authMethodsRef),
566 yield* Ref.get(authActionRef),
567 );
568 }
569 const started = startResult.success;
570 // Agents that persist sessions (OpenCode) would otherwise keep one empty session per probe.
571 // The runtime only sends session/delete when the agent advertises it.
572 yield* Effect.addFinalizer(() =>
573 runtime
574 .deleteSession(started.sessionId)
575 .pipe(Effect.timeoutOption(PROBE_SESSION_DELETE_TIMEOUT), Effect.ignore),
576 );
577 const hasInitialModels = acpRegistryAdvertisesModelCatalog(
578 started.sessionSetupResult.configOptions,
579 started.sessionSetupResult.models,
580 );
581
582 yield* Effect.all(
583 [
584 hasInitialModels
585 ? Effect.void
586 : Deferred.await(modelsAdvertised).pipe(
587 Effect.timeoutOption(MODEL_ADVERTISEMENT_GRACE),
588 ),
589 Deferred.await(commandsAdvertised).pipe(
590 Effect.timeoutOption(COMMAND_ADVERTISEMENT_GRACE),
591 ),
592 ],
593 { concurrency: "unbounded" },
594 );
595
596 // config_option_update replaces the full option set, so an empty notice is authoritative.
597 const liveConfiguration = normalizeAcpRegistryLiveConfiguration(
598 (yield* Ref.get(configOptionsRef)) ?? (yield* runtime.getConfigOptions),
599 (yield* runtime.getModeState) ?? parseSessionModeState(started.sessionSetupResult),
600 started.sessionSetupResult.models,
601 );
602
603 return {
604 resolved,
605 started,
606 commands: yield* Ref.get(commandsRef),
607 liveConfiguration,
608 };
609 }).pipe(
610 Effect.scoped,
611 Effect.timeoutOrElse({
612 duration: probeTimeoutMs,
613 orElse: () =>
614 Effect.fail(
615 new AcpRegistryOperationError({
616 reason: "probe_failed",
617 message: `The ACP agent did not resolve and create a test session within ${probeTimeoutMs / 1_000} seconds. Package installation or agent startup may be slow; this check retries on the next provider refresh.`,
618 }),
619 ),
620 }),
621 Effect.mapError((error) =>
622 error._tag === "AcpRegistryOperationError" ? error : acpRegistryProbeFailure(error),
623 ),
624 );
625 return {
626 probe: acpRegistryProbeResult(
627 input.instanceId,
628 result.started,
629 result.resolved.agent?.icon ?? null,
630 {
631 command: result.resolved.spawn.command,
632 args: result.resolved.spawn.args,
633 },
634 result.liveConfiguration,
635 ),
636 slashCommands: result.commands.slashCommands,
637 skills: result.commands.skills,
638 };
639 },
640 );
641
642 const MANAGEMENT_TIMEOUT = Duration.seconds(60);
643
644 const makeAcpRegistryManagementRuntime = Effect.fn("AcpRegistryProbe.makeManagementRuntime")(
645 function* (input: AcpRegistryManagementInput) {
646 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
647 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
648 const random = yield* SecureRandom.SecureRandom;
649 const runtimeCoordinator = yield* Effect.serviceOption(
650 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
651 );
652 const resolved = yield* catalog
653 .resolve(input.settings, input.cwd, input.environment)
654 .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError));
655 const runtimeContext = yield* Layer.build(
656 AcpSessionRuntime.layer({
657 spawn: resolved.spawn,
658 cwd: input.cwd,
659 clientCapabilities: {
660 auth: { terminal: false },
661 elicitation: { url: {} },
662 fs: { readTextFile: false, writeTextFile: false },
663 terminal: false,
664 },
665 clientInfo: { name: "t3-code-session-manager", version: "0.0.0" },
666 authenticateOnAuthRequired: false,
667 ...(input.settings.authMethodId ? { authMethodId: input.settings.authMethodId } : {}),
668 }).pipe(
669 Layer.provide(
670 Layer.mergeAll(
671 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
672 Layer.succeed(SecureRandom.SecureRandom, random),
673 ),
674 ),
675 ),
676 );
677 const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
678 Effect.provide(runtimeContext),
679 );
680 yield* runtime.handleElicitation((request) =>
681 Effect.gen(function* () {
682 if (
683 request.mode !== "url" ||
684 !("url" in request) ||
685 !("elicitationId" in request) ||
686 typeof request.url !== "string" ||
687 typeof request.elicitationId !== "string"
688 ) {
689 return { action: "decline" } as const;
690 }
691 const url = normalizeAcpRegistryWebUrl(request.url);
692 const elicitationId = boundedOpaqueValue(request.elicitationId, MAX_ID_LENGTH);
693 if (url === undefined || elicitationId === undefined) {
694 return { action: "decline" } as const;
695 }
696 const action: AcpRegistryUrlAuthAction = {
697 elicitationId,
698 url,
699 message: boundedText(request.message, MAX_DESCRIPTION_LENGTH),
700 };
701 const accepted = yield* Option.match(runtimeCoordinator, {
702 onNone: () => Effect.succeed(false),
703 onSome: (coordinator) => coordinator.requestUrlAuthentication(input.instanceId, action),
704 });
705 return accepted ? ({ action: "accept" } as const) : ({ action: "decline" } as const);
706 }),
707 );
708 return runtime;
709 },
710 );
711
712 function managementFailure(
713 operation:
714 | "list"
715 | "delete"
716 | "providers_list"
717 | "providers_set"
718 | "providers_disable"
719 | "logout",
720 error: EffectAcpErrors.AcpError | AcpRegistryOperationError,
721 ): AcpRegistryOperationError {
722 if (error._tag === "AcpRegistryOperationError") return error;
723 if (error._tag === "AcpRequestError" && error.code === -32601) {
724 if (operation === "list") {
725 return new AcpRegistryOperationError({
726 reason: "session_list_unsupported",
727 message: "The ACP agent does not advertise session listing.",
728 cause: error,
729 });
730 }
731 if (operation === "delete") {
732 return new AcpRegistryOperationError({
733 reason: "session_delete_unsupported",
734 message: "The ACP agent does not advertise session deletion.",
735 cause: error,
736 });
737 }
738 if (operation.startsWith("providers_")) {
739 return new AcpRegistryOperationError({
740 reason: "providers_unsupported",
741 message: "The ACP agent does not advertise provider configuration.",
742 cause: error,
743 });
744 }
745 return new AcpRegistryOperationError({
746 reason: "logout_unsupported",
747 message: "The ACP agent does not advertise logout.",
748 cause: error,
749 });
750 }
751 const classified = acpRegistryProbeFailure(error);
752 if (classified.reason === "authentication_failed") return classified;
753 const failure =
754 operation === "delete"
755 ? { reason: "session_delete_failed" as const, message: "Could not delete the ACP session." }
756 : operation === "providers_list"
757 ? { reason: "providers_list_failed" as const, message: "Could not list ACP providers." }
758 : operation === "providers_set" || operation === "providers_disable"
759 ? {
760 reason: "provider_configuration_failed" as const,
761 message: "Could not update the ACP provider configuration.",
762 }
763 : undefined;
764 return failure === undefined
765 ? classified
766 : new AcpRegistryOperationError({ ...failure, cause: error });
767 }
768
769 export const listAcpRegistrySessions = Effect.fn("AcpRegistryProbe.listSessions")(
770 function* (input: AcpRegistryManagementInput & { readonly cursor?: string }) {
771 const runtime = yield* makeAcpRegistryManagementRuntime(input);
772 const initialized = yield* runtime.initialize();
773 const listed = yield* runtime.listSessions(input.cursor);
774 const sessions = listed.sessions.slice(0, 256).flatMap((session) => {
775 const sessionId = boundedOpaqueValue(session.sessionId, 1_024);
776 const cwd = boundedOpaqueValue(session.cwd, 4_096);
777 if (sessionId === undefined || cwd === undefined) return [];
778 return [
779 {
780 sessionId,
781 cwd,
782 additionalDirectories: (session.additionalDirectories ?? [])
783 .flatMap((directory) => {
784 const normalized = boundedOpaqueValue(directory, 4_096);
785 return normalized === undefined ? [] : [normalized];
786 })
787 .slice(0, 32),
788 title:
789 session.title === undefined || session.title === null
790 ? null
791 : boundedText(session.title, 1_024) || null,
792 updatedAt:
793 session.updatedAt === undefined || session.updatedAt === null
794 ? null
795 : boundedText(session.updatedAt, 128) || null,
796 importedThreadId: null,
797 },
798 ];
799 });
800 return AcpRegistryListSessionsResult.make({
801 sessions,
802 nextCursor:
803 listed.nextCursor === undefined || listed.nextCursor === null
804 ? null
805 : boundedText(listed.nextCursor, 2_048) || null,
806 canLoad: initialized.agentCapabilities?.loadSession === true,
807 canResume: initialized.agentCapabilities?.sessionCapabilities?.resume != null,
808 canDelete: initialized.agentCapabilities?.sessionCapabilities?.delete != null,
809 });
810 },
811 (effect) =>
812 effect.pipe(
813 Effect.scoped,
814 Effect.timeoutOrElse({
815 duration: MANAGEMENT_TIMEOUT,
816 orElse: () =>
817 Effect.fail(
818 new AcpRegistryOperationError({
819 reason: "probe_failed",
820 message: "The ACP session list request timed out.",
821 }),
822 ),
823 }),
824 Effect.mapError((error) => managementFailure("list", error)),
825 ),
826 );
827
828 export const deleteAcpRegistrySession = Effect.fn("AcpRegistryProbe.deleteSession")(
829 function* (input: AcpRegistryManagementInput & { readonly sessionId: string }) {
830 const runtime = yield* makeAcpRegistryManagementRuntime(input);
831 yield* runtime.deleteSession(input.sessionId);
832 },
833 (effect) =>
834 effect.pipe(
835 Effect.scoped,
836 Effect.timeoutOrElse({
837 duration: MANAGEMENT_TIMEOUT,
838 orElse: () =>
839 Effect.fail(
840 new AcpRegistryOperationError({
841 reason: "session_delete_failed",
842 message: "The ACP session delete request timed out.",
843 }),
844 ),
845 }),
846 Effect.mapError((error) => managementFailure("delete", error)),
847 ),
848 );
849
850 export const listAcpRegistryProviders = Effect.fn("AcpRegistryProbe.listProviders")(
851 function* (input: AcpRegistryManagementInput) {
852 const runtime = yield* makeAcpRegistryManagementRuntime(input);
853 const listed = yield* runtime.listProviders;
854 return AcpRegistryListProvidersResult.make({
855 providers: listed.providers.slice(0, 64).flatMap((provider) => {
856 const providerId = boundedOpaqueValue(provider.providerId, 256);
857 if (providerId === undefined) return [];
858 const supported = provider.supported
859 .flatMap((protocol) => {
860 const value = boundedOpaqueValue(protocol, 64);
861 return value === undefined ? [] : [value];
862 })
863 .slice(0, 16);
864 const current = provider.current;
865 const currentApiType =
866 current == null ? undefined : boundedOpaqueValue(current.apiType, 64);
867 const currentBaseUrl =
868 current == null ? undefined : normalizeAcpRegistryWebUrl(current.baseUrl);
869 return [
870 {
871 providerId,
872 supported,
873 required: provider.required,
874 current:
875 currentApiType === undefined || currentBaseUrl === undefined
876 ? null
877 : { apiType: currentApiType, baseUrl: currentBaseUrl },
878 },
879 ];
880 }),
881 });
882 },
883 (effect) =>
884 effect.pipe(
885 Effect.scoped,
886 Effect.timeoutOrElse({
887 duration: MANAGEMENT_TIMEOUT,
888 orElse: () =>
889 Effect.fail(
890 new AcpRegistryOperationError({
891 reason: "providers_list_failed",
892 message: "The ACP provider list request timed out.",
893 }),
894 ),
895 }),
896 Effect.mapError((error) => managementFailure("providers_list", error)),
897 ),
898 );
899
900 export const setAcpRegistryProvider = Effect.fn("AcpRegistryProbe.setProvider")(
901 function* (input: AcpRegistryManagementInput & EffectAcpSchema.SetProviderRequest) {
902 const runtime = yield* makeAcpRegistryManagementRuntime(input);
903 yield* runtime.setProvider({
904 providerId: input.providerId,
905 apiType: input.apiType,
906 baseUrl: input.baseUrl,
907 ...(input.headers === undefined ? {} : { headers: input.headers }),
908 });
909 },
910 (effect) =>
911 effect.pipe(
912 Effect.scoped,
913 Effect.timeoutOrElse({
914 duration: MANAGEMENT_TIMEOUT,
915 orElse: () =>
916 Effect.fail(
917 new AcpRegistryOperationError({
918 reason: "provider_configuration_failed",
919 message: "The ACP provider configuration request timed out.",
920 }),
921 ),
922 }),
923 Effect.mapError((error) => managementFailure("providers_set", error)),
924 ),
925 );
926
927 export const disableAcpRegistryProvider = Effect.fn("AcpRegistryProbe.disableProvider")(
928 function* (input: AcpRegistryManagementInput & { readonly providerId: string }) {
929 const runtime = yield* makeAcpRegistryManagementRuntime(input);
930 yield* runtime.disableProvider(input.providerId);
931 },
932 (effect) =>
933 effect.pipe(
934 Effect.scoped,
935 Effect.timeoutOrElse({
936 duration: MANAGEMENT_TIMEOUT,
937 orElse: () =>
938 Effect.fail(
939 new AcpRegistryOperationError({
940 reason: "provider_configuration_failed",
941 message: "The ACP provider disable request timed out.",
942 }),
943 ),
944 }),
945 Effect.mapError((error) => managementFailure("providers_disable", error)),
946 ),
947 );
948
949 export const logoutAcpRegistry = Effect.fn("AcpRegistryProbe.logout")(
950 function* (input: AcpRegistryManagementInput) {
951 const runtime = yield* makeAcpRegistryManagementRuntime(input);
952 yield* runtime.logout;
953 },
954 (effect) =>
955 effect.pipe(
956 Effect.scoped,
957 Effect.timeoutOrElse({
958 duration: MANAGEMENT_TIMEOUT,
959 orElse: () =>
960 Effect.fail(
961 new AcpRegistryOperationError({
962 reason: "probe_failed",
963 message: "The ACP logout request timed out.",
964 }),
965 ),
966 }),
967 Effect.mapError((error) => managementFailure("logout", error)),
968 ),
969 );