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

AcpRegistryProbe.ts

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