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

probe.ts

787 lines29.3 KB

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