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

AcpRegistryProbe.ts

775 lines29.2 KB

1import {
2 AcpRegistryListProvidersResult,
3 AcpRegistryOperationError,
4 AcpRegistryListSessionsResult,
5 AcpRegistryProbeResult,
6 AcpRegistrySettings,
7 type AcpRegistryProbeAuthMethod,
8 type AcpRegistryProbeModel,
9 type AcpRegistryUrlAuthAction,
10 type ProviderInstanceId,
11 type ServerProviderSkill,
12 type ServerProviderSlashCommand,
13} from "@t3tools/contracts";
14import * as Crypto from "effect/Crypto";
15import * as Deferred from "effect/Deferred";
16import * as Duration from "effect/Duration";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Ref from "effect/Ref";
21import * as Result from "effect/Result";
22import { ChildProcessSpawner } from "effect/unstable/process";
23import type * as EffectAcpErrors from "effect-acp/errors";
24import type * as EffectAcpSchema from "effect-acp/compat";
25​
26import { AcpRegistryCatalog, toAcpRegistryOperationError } from "./AcpRegistrySupport.ts";
27import { parseSessionModeState } from "./AcpRuntimeModel.ts";
28import { acpProviderOptionDescriptors } from "./AcpSessionConfig.ts";
29import { AcpRegistryRuntimeCoordinator } from "./AcpRegistryRuntimeCoordinator.ts";
30import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
31​
32const MAX_AUTH_METHODS = 32;
33const MAX_MODELS = 256;
34const MAX_ID_LENGTH = 128;
35const MAX_NAME_LENGTH = 160;
36const MAX_DESCRIPTION_LENGTH = 1_024;
37const MAX_COMMANDS = 128;
38const MAX_COMMAND_LINE_LENGTH = 2_048;
39// Covers a cold package command launch and ACP initialization after registry
40// preparation globally installs the exact package.
41const PROBE_TIMEOUT_SECONDS = 60;
42const PROBE_TIMEOUT = `${PROBE_TIMEOUT_SECONDS} seconds`;
43const COMMAND_ADVERTISEMENT_GRACE = "500 millis";
44​
45const boundedText = (value: string, maximumLength: number): string =>
46 value.trim().slice(0, maximumLength);
47​
48const boundedOpaqueValue = (value: string, maximumLength: number): string | undefined =>
49 value.length > 0 && value === value.trim() && value.length <= maximumLength ? value : undefined;
50​
51export function normalizeAcpRegistryWebUrl(value: string): string | undefined {
52 if (value.length > 2_048 || !URL.canParse(value)) return undefined;
53 const url = new URL(value);
54 return url.protocol === "https:" || url.protocol === "http:" ? url.href : undefined;
56​
57function modelConfigOptions(
58 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
59): ReadonlyArray<EffectAcpSchema.SessionConfigSelectOption> {
60 return (configOptions ?? []).flatMap((option) => {
61 if (option.category !== "model" || option.type !== "select") return [];
62 return option.options.flatMap((candidate) =>
63 "value" in candidate ? [candidate] : candidate.options,
64 );
65 });
67​
68function normalizeModels(
69 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
70): ReadonlyArray<AcpRegistryProbeModel> {
71 // Model discovery is the model config option's base models; ACP has no
72 // other portable model inventory.
73 const candidates = modelConfigOptions(configOptions).map((model) => ({
74 id: model.value,
75 name: model.name,
76 description: model.description ?? null,
77 }));
78 const seen = new Set<string>();
79 const models: Array<AcpRegistryProbeModel> = [];
80 for (const candidate of candidates) {
81 const id = boundedOpaqueValue(candidate.id, MAX_ID_LENGTH);
82 if (id === undefined || seen.has(id)) continue;
83 seen.add(id);
84 models.push({
85 id,
86 name: boundedText(candidate.name, MAX_NAME_LENGTH) || id,
87 description:
88 candidate.description === null
89 ? null
90 : boundedText(candidate.description, MAX_DESCRIPTION_LENGTH) || null,
91 });
92 if (models.length === MAX_MODELS) break;
93 }
94 return models;
96​
97/** Agent spawn recipe used to compose runnable terminal-auth command lines. */
98export interface AcpRegistryAuthSpawnContext {
99 readonly command: string;
100 readonly args: ReadonlyArray<string>;
102​
103const SHELL_SAFE_TOKEN = /^[A-Za-z0-9_@%+=:,./-]+$/u;
104​
105function shellDisplayToken(token: string): string {
106 return SHELL_SAFE_TOKEN.test(token) ? token : `'${token.replaceAll("'", `'\\''`)}'`;
108​
109function terminalAuthCommand(
110 method: Extract<EffectAcpSchema.AuthMethod, { readonly type: "terminal" }>,
111 spawn: AcpRegistryAuthSpawnContext,
112): string | undefined {
113 const environmentPrefix = Object.entries(method.env ?? {}).map(
114 ([name, value]) => `${name}=${shellDisplayToken(value)}`,
115 );
116 const command = [spawn.command, ...spawn.args, ...(method.args ?? [])].map(shellDisplayToken);
117 const displayCommand = [...environmentPrefix, ...command].join(" ");
118 return displayCommand.length <= MAX_COMMAND_LINE_LENGTH ? displayCommand : undefined;
120​
121export function normalizeAcpRegistryAuthMethods(
122 methods: ReadonlyArray<EffectAcpSchema.AuthMethod> | undefined,
123 spawn?: AcpRegistryAuthSpawnContext,
124): ReadonlyArray<AcpRegistryProbeAuthMethod> {
125 const normalized: Array<AcpRegistryProbeAuthMethod> = [];
126 for (const method of methods ?? []) {
127 const id = boundedOpaqueValue(method.id, MAX_ID_LENGTH);
128 if (id === undefined) continue;
129 const type = "type" in method ? method.type : "agent";
130 const envVarNames =
131 type === "env_var" && "vars" in method
132 ? method.vars
133 .flatMap((variable) => {
134 const name = boundedOpaqueValue(variable.name, MAX_ID_LENGTH);
135 return name === undefined ? [] : [name];
136 })
137 .slice(0, 16)
138 : [];
139 const command =
140 spawn !== undefined && "type" in method && method.type === "terminal"
141 ? terminalAuthCommand(method, spawn)
142 : undefined;
143 const link =
144 type === "env_var" && "link" in method && method.link
145 ? normalizeAcpRegistryWebUrl(method.link)
146 : undefined;
147 normalized.push({
148 id,
149 name: boundedText(method.name, MAX_NAME_LENGTH) || id,
150 description:
151 method.description == null
152 ? null
153 : boundedText(method.description, MAX_DESCRIPTION_LENGTH) || null,
154 type,
155 ...(command === undefined ? {} : { command }),
156 ...(envVarNames.length > 0 ? { envVarNames } : {}),
157 ...(link === undefined ? {} : { link }),
158 });
159 if (normalized.length === MAX_AUTH_METHODS) break;
160 }
161 return normalized;
163​
164export interface AcpRegistryAvailableCommands {
165 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
166 readonly skills: ReadonlyArray<ServerProviderSkill>;
168​
169export interface AcpRegistryLiveConfiguration {
170 readonly models: ReadonlyArray<AcpRegistryProbeModel>;
171 readonly currentModelId: string | null;
172 readonly configOptions: AcpRegistryProbeResult["configOptions"];
174​
175/** Normalizes volatile session configuration using the same bounds as discovery probes. */
176export function normalizeAcpRegistryLiveConfiguration(
177 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
178 modeState?: Parameters<typeof acpProviderOptionDescriptors>[0]["modeState"],
179): AcpRegistryLiveConfiguration {
180 const modelOption = configOptions.find(
181 (option) => option.category === "model" && option.type === "select",
182 );
183 const boundedCurrentModelId =
184 modelOption?.type === "select"
185 ? (boundedOpaqueValue(modelOption.currentValue, MAX_ID_LENGTH) ?? null)
186 : null;
187 const models = normalizeModels(configOptions);
188 return {
189 models,
190 currentModelId: models.some((model) => model.id === boundedCurrentModelId)
191 ? boundedCurrentModelId
192 : null,
193 configOptions: acpProviderOptionDescriptors({ configOptions, modeState }),
194 };
196​
197const emptyAcpRegistryAvailableCommands = (): AcpRegistryAvailableCommands => ({
198 slashCommands: [],
199 skills: [],
200});
201​
202/** Splits the latest ACP command advertisement into T3's `/` and `$` menus. */
203export function normalizeAcpRegistryCommands(
204 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
205): AcpRegistryAvailableCommands {
206 const seen = new Set<string>();
207 const slashCommands: Array<ServerProviderSlashCommand> = [];
208 const skills: Array<ServerProviderSkill> = [];
209 let accepted = 0;
210 for (const command of commands) {
211 const name = boundedOpaqueValue(command.name, MAX_ID_LENGTH);
212 if (name === undefined) continue;
213 const key = name.toLowerCase();
214 if (seen.has(key)) continue;
215 seen.add(key);
216 const description = boundedText(command.description, MAX_DESCRIPTION_LENGTH);
217 const hint = command.input ? boundedText(command.input.hint, MAX_DESCRIPTION_LENGTH) : "";
218 if (name.startsWith("$")) {
219 const skillName = boundedOpaqueValue(name.slice(1), MAX_ID_LENGTH);
220 if (skillName === undefined) continue;
221 skills.push({
222 name: skillName,
223 ...(description ? { description } : {}),
224 path: `acp://skill/${encodeURIComponent(skillName)}`,
225 scope: "agent",
226 enabled: true,
227 });
228 } else {
229 slashCommands.push({
230 name,
231 ...(description ? { description } : {}),
232 ...(hint ? { input: { hint } } : {}),
233 });
234 }
235 accepted += 1;
236 if (accepted === MAX_COMMANDS) break;
237 }
238 return { slashCommands, skills };
240​
241/** Builds the bounded wire result from a successfully created disposable ACP session. */
242export function acpRegistryProbeResult(
243 instanceId: ProviderInstanceId,
244 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
245 icon: string | null = null,
246 spawn?: AcpRegistryAuthSpawnContext,
247): AcpRegistryProbeResult {
248 const liveConfiguration = normalizeAcpRegistryLiveConfiguration(
249 started.sessionSetupResult.configOptions ?? [],
250 parseSessionModeState(started.sessionSetupResult),
251 );
252 return AcpRegistryProbeResult.make({
253 instanceId,
254 ready: true,
255 icon,
256 authMethods: normalizeAcpRegistryAuthMethods(started.initializeResult.authMethods, spawn),
257 sessionManagement: {
258 canList: started.initializeResult.agentCapabilities?.sessionCapabilities?.list != null,
259 canLoad: started.initializeResult.agentCapabilities?.loadSession === true,
260 canResume: started.initializeResult.agentCapabilities?.sessionCapabilities?.resume != null,
261 canLogout: started.initializeResult.agentCapabilities?.auth?.logout != null,
262 canDelete: started.initializeResult.agentCapabilities?.sessionCapabilities?.delete != null,
263 canConfigureProviders: started.initializeResult.agentCapabilities?.providers != null,
264 },
265 ...liveConfiguration,
266 });
268​
269export function acpRegistryProbeFailure(
270 error: EffectAcpErrors.AcpError,
271 authMethods: ReadonlyArray<AcpRegistryProbeAuthMethod> = [],
272 authAction?: AcpRegistryUrlAuthAction,
273): AcpRegistryOperationError {
274 const detail = error._tag === "AcpTransportError" && error.detail ? error.detail : error.message;
275 const authenticationFailed =
276 (error._tag === "AcpRequestError" && error.code === -32000) ||
277 /\b(?:authenticat(?:e|ed|es|ing|ion)|credentials?|log(?:[\s-]+)?in)\b/iu.test(detail);
278 return new AcpRegistryOperationError({
279 reason: authenticationFailed ? "authentication_failed" : "probe_failed",
280 message: authenticationFailed
281 ? "The ACP agent could not complete authentication."
282 : "The ACP agent could not create a test session.",
283 cause: error,
284 ...(authMethods.length > 0 ? { authMethods } : {}),
285 ...(authAction === undefined ? {} : { authAction }),
286 });
288​
289export interface AcpRegistryConfigurationProbeInput {
290 readonly instanceId: ProviderInstanceId;
291 readonly settings: AcpRegistrySettings;
292 readonly cwd: string;
293 readonly environment: NodeJS.ProcessEnv;
295​
296type AcpRegistryManagementInput = AcpRegistryConfigurationProbeInput;
297​
298export interface AcpRegistryConfigurationProbeResult {
299 readonly probe: AcpRegistryProbeResult;
300 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
301 readonly skills: ReadonlyArray<ServerProviderSkill>;
303​
304export type AcpRegistryConfigurationProbe<Requirements = never> = (
305 input: AcpRegistryConfigurationProbeInput,
306) => Effect.Effect<AcpRegistryConfigurationProbeResult, AcpRegistryOperationError, Requirements>;
307​
308/** Starts and immediately disposes an ACP session for one already-decoded configuration. */
309export const probeAcpRegistryConfiguration = Effect.fn("AcpRegistryProbe.probeConfiguration")(
310 function* (
311 input: AcpRegistryConfigurationProbeInput,
312 ): Effect.fn.Return<
313 AcpRegistryConfigurationProbeResult,
314 AcpRegistryOperationError,
315 AcpRegistryCatalog | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
316 > {
317 const catalog = yield* AcpRegistryCatalog;
318 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
319 const crypto = yield* Crypto.Crypto;
320​
321 const result = yield* Effect.gen(function* () {
322 // Resolution may install a missing registry package. Keep it inside the
323 // probe deadline so a provider refresh cannot inherit the installer's
324 // much longer timeout.
325 const resolved = yield* catalog
326 .resolve(input.settings, input.cwd, input.environment)
327 .pipe(Effect.mapError(toAcpRegistryOperationError));
328 const authMethodsRef = yield* Ref.make<ReadonlyArray<AcpRegistryProbeAuthMethod>>([]);
329 const authActionRef = yield* Ref.make<AcpRegistryUrlAuthAction | undefined>(undefined);
330 const runtimeCoordinator = yield* Effect.serviceOption(AcpRegistryRuntimeCoordinator);
331 const runtimeContext = yield* Layer.build(
332 AcpSessionRuntime.layer({
333 spawn: resolved.spawn,
334 cwd: input.cwd,
335 clientCapabilities: {
336 auth: { terminal: false },
337 elicitation: { url: {} },
338 fs: { readTextFile: false, writeTextFile: false },
339 terminal: false,
340 },
341 clientInfo: { name: "t3-code-provider-test", version: "0.0.0" },
342 authenticateOnAuthRequired: false,
343 onInitialized: (initializeResult) =>
344 Ref.set(
345 authMethodsRef,
346 normalizeAcpRegistryAuthMethods(initializeResult.authMethods, {
347 command: resolved.spawn.command,
348 args: resolved.spawn.args,
349 }),
350 ),
351 ...(input.settings.authMethodId ? { authMethodId: input.settings.authMethodId } : {}),
352 }).pipe(
353 Layer.provide(
354 Layer.mergeAll(
355 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
356 Layer.succeed(Crypto.Crypto, crypto),
357 ),
358 ),
359 ),
360 );
361 const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
362 Effect.provide(runtimeContext),
363 );
364 const commandsRef = yield* Ref.make<AcpRegistryAvailableCommands>(
365 emptyAcpRegistryAvailableCommands(),
366 );
367 const commandsAdvertised = yield* Deferred.make<void>();
368 yield* runtime.handleElicitation((request) =>
369 Effect.gen(function* () {
370 if (
371 request.mode !== "url" ||
372 !("url" in request) ||
373 !("elicitationId" in request) ||
374 typeof request.url !== "string" ||
375 typeof request.elicitationId !== "string"
376 ) {
377 return { action: "decline" } as const;
378 }
379 const url = normalizeAcpRegistryWebUrl(request.url);
380 const elicitationId = boundedOpaqueValue(request.elicitationId, MAX_ID_LENGTH);
381 if (url === undefined || elicitationId === undefined) {
382 return { action: "decline" } as const;
383 }
384 const action: AcpRegistryUrlAuthAction = {
385 elicitationId,
386 url,
387 message: boundedText(request.message, MAX_DESCRIPTION_LENGTH),
388 };
389 yield* Ref.set(authActionRef, action);
390 const accepted = yield* Option.match(runtimeCoordinator, {
391 onNone: () => Effect.succeed(false),
392 onSome: (coordinator) => coordinator.requestUrlAuthentication(input.instanceId, action),
393 });
394 return accepted ? ({ action: "accept" } as const) : ({ action: "decline" } as const);
395 }),
396 );
397 yield* runtime.handleSessionUpdate((notification) => {
398 const update = notification.update;
399 return update.sessionUpdate === "available_commands_update"
400 ? Ref.set(commandsRef, normalizeAcpRegistryCommands(update.availableCommands)).pipe(
401 Effect.andThen(Deferred.succeed(commandsAdvertised, undefined)),
402 Effect.asVoid,
403 )
404 : Effect.void;
405 });
406 const startResult = yield* Effect.result(runtime.start());
407 if (Result.isFailure(startResult)) {
408 return yield* acpRegistryProbeFailure(
409 startResult.failure,
410 yield* Ref.get(authMethodsRef),
411 yield* Ref.get(authActionRef),
412 );
413 }
414 const started = startResult.success;
415 yield* Deferred.await(commandsAdvertised).pipe(
416 Effect.timeoutOption(COMMAND_ADVERTISEMENT_GRACE),
417 );
418 return { resolved, started, commands: yield* Ref.get(commandsRef) };
419 }).pipe(
420 Effect.scoped,
421 Effect.timeoutOrElse({
422 duration: PROBE_TIMEOUT,
423 orElse: () =>
424 Effect.fail(
425 new AcpRegistryOperationError({
426 reason: "probe_failed",
427 message: `The ACP agent did not resolve and create a test session within ${PROBE_TIMEOUT_SECONDS} seconds. Package installation or agent startup may be slow; this check retries on the next provider refresh.`,
428 }),
429 ),
430 }),
431 Effect.mapError((error) =>
432 error._tag === "AcpRegistryOperationError" ? error : acpRegistryProbeFailure(error),
433 ),
434 );
435 return {
436 probe: acpRegistryProbeResult(
437 input.instanceId,
438 result.started,
439 result.resolved.agent.icon ?? null,
440 {
441 command: result.resolved.spawn.command,
442 args: result.resolved.spawn.args,
443 },
444 ),
445 slashCommands: result.commands.slashCommands,
446 skills: result.commands.skills,
447 };
448 },
449);
450​
451const MANAGEMENT_TIMEOUT = Duration.seconds(60);
452​
453const makeAcpRegistryManagementRuntime = Effect.fn("AcpRegistryProbe.makeManagementRuntime")(
454 function* (input: AcpRegistryManagementInput) {
455 const catalog = yield* AcpRegistryCatalog;
456 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
457 const crypto = yield* Crypto.Crypto;
458 const runtimeCoordinator = yield* Effect.serviceOption(AcpRegistryRuntimeCoordinator);
459 const resolved = yield* catalog
460 .resolve(input.settings, input.cwd, input.environment)
461 .pipe(Effect.mapError(toAcpRegistryOperationError));
462 const runtimeContext = yield* Layer.build(
463 AcpSessionRuntime.layer({
464 spawn: resolved.spawn,
465 cwd: input.cwd,
466 clientCapabilities: {
467 auth: { terminal: false },
468 elicitation: { url: {} },
469 fs: { readTextFile: false, writeTextFile: false },
470 terminal: false,
471 },
472 clientInfo: { name: "t3-code-session-manager", version: "0.0.0" },
473 ...(input.settings.authMethodId ? { authMethodId: input.settings.authMethodId } : {}),
474 }).pipe(
475 Layer.provide(
476 Layer.mergeAll(
477 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
478 Layer.succeed(Crypto.Crypto, crypto),
479 ),
480 ),
481 ),
482 );
483 const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
484 Effect.provide(runtimeContext),
485 );
486 yield* runtime.handleElicitation((request) =>
487 Effect.gen(function* () {
488 if (
489 request.mode !== "url" ||
490 !("url" in request) ||
491 !("elicitationId" in request) ||
492 typeof request.url !== "string" ||
493 typeof request.elicitationId !== "string"
494 ) {
495 return { action: "decline" } as const;
496 }
497 const url = normalizeAcpRegistryWebUrl(request.url);
498 const elicitationId = boundedOpaqueValue(request.elicitationId, MAX_ID_LENGTH);
499 if (url === undefined || elicitationId === undefined) {
500 return { action: "decline" } as const;
501 }
502 const action: AcpRegistryUrlAuthAction = {
503 elicitationId,
504 url,
505 message: boundedText(request.message, MAX_DESCRIPTION_LENGTH),
506 };
507 const accepted = yield* Option.match(runtimeCoordinator, {
508 onNone: () => Effect.succeed(false),
509 onSome: (coordinator) => coordinator.requestUrlAuthentication(input.instanceId, action),
510 });
511 return accepted ? ({ action: "accept" } as const) : ({ action: "decline" } as const);
512 }),
513 );
514 return runtime;
515 },
516);
517​
518function managementFailure(
519 operation:
520 | "list"
521 | "delete"
522 | "providers_list"
523 | "providers_set"
524 | "providers_disable"
525 | "logout",
526 error: EffectAcpErrors.AcpError | AcpRegistryOperationError,
527): AcpRegistryOperationError {
528 if (error._tag === "AcpRegistryOperationError") return error;
529 if (error._tag === "AcpRequestError" && error.code === -32601) {
530 if (operation === "list") {
531 return new AcpRegistryOperationError({
532 reason: "session_list_unsupported",
533 message: "The ACP agent does not advertise session listing.",
534 cause: error,
535 });
536 }
537 if (operation === "delete") {
538 return new AcpRegistryOperationError({
539 reason: "session_delete_unsupported",
540 message: "The ACP agent does not advertise session deletion.",
541 cause: error,
542 });
543 }
544 if (operation.startsWith("providers_")) {
545 return new AcpRegistryOperationError({
546 reason: "providers_unsupported",
547 message: "The ACP agent does not advertise provider configuration.",
548 cause: error,
549 });
550 }
551 return new AcpRegistryOperationError({
552 reason: "logout_unsupported",
553 message: "The ACP agent does not advertise logout.",
554 cause: error,
555 });
556 }
557 const classified = acpRegistryProbeFailure(error);
558 if (classified.reason === "authentication_failed") return classified;
559 const failure =
560 operation === "delete"
561 ? { reason: "session_delete_failed" as const, message: "Could not delete the ACP session." }
562 : operation === "providers_list"
563 ? { reason: "providers_list_failed" as const, message: "Could not list ACP providers." }
564 : operation === "providers_set" || operation === "providers_disable"
565 ? {
566 reason: "provider_configuration_failed" as const,
567 message: "Could not update the ACP provider configuration.",
568 }
569 : undefined;
570 return failure === undefined
571 ? classified
572 : new AcpRegistryOperationError({ ...failure, cause: error });
574​
575export const listAcpRegistrySessions = Effect.fn("AcpRegistryProbe.listSessions")(
576 function* (input: AcpRegistryManagementInput & { readonly cursor?: string }) {
577 const runtime = yield* makeAcpRegistryManagementRuntime(input);
578 const initialized = yield* runtime.initialize();
579 const listed = yield* runtime.listSessions(input.cursor);
580 const sessions = listed.sessions.slice(0, 256).flatMap((session) => {
581 const sessionId = boundedOpaqueValue(session.sessionId, 1_024);
582 const cwd = boundedOpaqueValue(session.cwd, 4_096);
583 if (sessionId === undefined || cwd === undefined) return [];
584 return [
585 {
586 sessionId,
587 cwd,
588 additionalDirectories: (session.additionalDirectories ?? [])
589 .flatMap((directory) => {
590 const normalized = boundedOpaqueValue(directory, 4_096);
591 return normalized === undefined ? [] : [normalized];
592 })
593 .slice(0, 32),
594 title:
595 session.title === undefined || session.title === null
596 ? null
597 : boundedText(session.title, 1_024) || null,
598 updatedAt:
599 session.updatedAt === undefined || session.updatedAt === null
600 ? null
601 : boundedText(session.updatedAt, 128) || null,
602 importedThreadId: null,
603 },
604 ];
605 });
606 return AcpRegistryListSessionsResult.make({
607 sessions,
608 nextCursor:
609 listed.nextCursor === undefined || listed.nextCursor === null
610 ? null
611 : boundedText(listed.nextCursor, 2_048) || null,
612 canLoad: initialized.agentCapabilities?.loadSession === true,
613 canResume: initialized.agentCapabilities?.sessionCapabilities?.resume != null,
614 canDelete: initialized.agentCapabilities?.sessionCapabilities?.delete != null,
615 });
616 },
617 (effect) =>
618 effect.pipe(
619 Effect.scoped,
620 Effect.timeoutOrElse({
621 duration: MANAGEMENT_TIMEOUT,
622 orElse: () =>
623 Effect.fail(
624 new AcpRegistryOperationError({
625 reason: "probe_failed",
626 message: "The ACP session list request timed out.",
627 }),
628 ),
629 }),
630 Effect.mapError((error) => managementFailure("list", error)),
631 ),
632);
633​
634export const deleteAcpRegistrySession = Effect.fn("AcpRegistryProbe.deleteSession")(
635 function* (input: AcpRegistryManagementInput & { readonly sessionId: string }) {
636 const runtime = yield* makeAcpRegistryManagementRuntime(input);
637 yield* runtime.deleteSession(input.sessionId);
638 },
639 (effect) =>
640 effect.pipe(
641 Effect.scoped,
642 Effect.timeoutOrElse({
643 duration: MANAGEMENT_TIMEOUT,
644 orElse: () =>
645 Effect.fail(
646 new AcpRegistryOperationError({
647 reason: "session_delete_failed",
648 message: "The ACP session delete request timed out.",
649 }),
650 ),
651 }),
652 Effect.mapError((error) => managementFailure("delete", error)),
653 ),
654);
655​
656export const listAcpRegistryProviders = Effect.fn("AcpRegistryProbe.listProviders")(
657 function* (input: AcpRegistryManagementInput) {
658 const runtime = yield* makeAcpRegistryManagementRuntime(input);
659 const listed = yield* runtime.listProviders;
660 return AcpRegistryListProvidersResult.make({
661 providers: listed.providers.slice(0, 64).flatMap((provider) => {
662 const providerId = boundedOpaqueValue(provider.providerId, 256);
663 if (providerId === undefined) return [];
664 const supported = provider.supported
665 .flatMap((protocol) => {
666 const value = boundedOpaqueValue(protocol, 64);
667 return value === undefined ? [] : [value];
668 })
669 .slice(0, 16);
670 const current = provider.current;
671 const currentApiType =
672 current == null ? undefined : boundedOpaqueValue(current.apiType, 64);
673 const currentBaseUrl =
674 current == null ? undefined : normalizeAcpRegistryWebUrl(current.baseUrl);
675 return [
676 {
677 providerId,
678 supported,
679 required: provider.required,
680 current:
681 currentApiType === undefined || currentBaseUrl === undefined
682 ? null
683 : { apiType: currentApiType, baseUrl: currentBaseUrl },
684 },
685 ];
686 }),
687 });
688 },
689 (effect) =>
690 effect.pipe(
691 Effect.scoped,
692 Effect.timeoutOrElse({
693 duration: MANAGEMENT_TIMEOUT,
694 orElse: () =>
695 Effect.fail(
696 new AcpRegistryOperationError({
697 reason: "providers_list_failed",
698 message: "The ACP provider list request timed out.",
699 }),
700 ),
701 }),
702 Effect.mapError((error) => managementFailure("providers_list", error)),
703 ),
704);
705​
706export const setAcpRegistryProvider = Effect.fn("AcpRegistryProbe.setProvider")(
707 function* (input: AcpRegistryManagementInput & EffectAcpSchema.SetProviderRequest) {
708 const runtime = yield* makeAcpRegistryManagementRuntime(input);
709 yield* runtime.setProvider({
710 providerId: input.providerId,
711 apiType: input.apiType,
712 baseUrl: input.baseUrl,
713 ...(input.headers === undefined ? {} : { headers: input.headers }),
714 });
715 },
716 (effect) =>
717 effect.pipe(
718 Effect.scoped,
719 Effect.timeoutOrElse({
720 duration: MANAGEMENT_TIMEOUT,
721 orElse: () =>
722 Effect.fail(
723 new AcpRegistryOperationError({
724 reason: "provider_configuration_failed",
725 message: "The ACP provider configuration request timed out.",
726 }),
727 ),
728 }),
729 Effect.mapError((error) => managementFailure("providers_set", error)),
730 ),
731);
732​
733export const disableAcpRegistryProvider = Effect.fn("AcpRegistryProbe.disableProvider")(
734 function* (input: AcpRegistryManagementInput & { readonly providerId: string }) {
735 const runtime = yield* makeAcpRegistryManagementRuntime(input);
736 yield* runtime.disableProvider(input.providerId);
737 },
738 (effect) =>
739 effect.pipe(
740 Effect.scoped,
741 Effect.timeoutOrElse({
742 duration: MANAGEMENT_TIMEOUT,
743 orElse: () =>
744 Effect.fail(
745 new AcpRegistryOperationError({
746 reason: "provider_configuration_failed",
747 message: "The ACP provider disable request timed out.",
748 }),
749 ),
750 }),
751 Effect.mapError((error) => managementFailure("providers_disable", error)),
752 ),
753);
754​
755export const logoutAcpRegistry = Effect.fn("AcpRegistryProbe.logout")(
756 function* (input: AcpRegistryManagementInput) {
757 const runtime = yield* makeAcpRegistryManagementRuntime(input);
758 yield* runtime.logout;
759 },
760 (effect) =>
761 effect.pipe(
762 Effect.scoped,
763 Effect.timeoutOrElse({
764 duration: MANAGEMENT_TIMEOUT,
765 orElse: () =>
766 Effect.fail(
767 new AcpRegistryOperationError({
768 reason: "probe_failed",
769 message: "The ACP logout request timed out.",
770 }),
771 ),
772 }),
773 Effect.mapError((error) => managementFailure("logout", error)),
774 ),
775);