GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — oh-my-pi/packages/coding-agent/src/modes/acp/acp-agent.ts at v18.12.6 · can1357/oh-my-pi Expand file tree/ Copy pathacp-agent.tsMore file actions 3249 lines (3084 loc) · 117 KB / Copy pathacp-agent.tsFile metadata and controls3249 lines (3084 loc) · 117 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 import * as fs from "node:fs/promises"; import * as path from "node:path"; import { AgentBusyError, type AgentToolResult } from "@oh-my-pi/pi-agent-core"; import type { AssistantMessage, Model } from "@oh-my-pi/pi-ai"; import { getBlobsDir, isEnoent, logger, type postmortem, VERSION } from "@oh-my-pi/pi-utils"; import { type Agent, type AgentSideConnection, type AuthenticateRequest, type AuthenticateResponse, type AuthMethod, type AvailableCommand, type ClientCapabilities, type CloseSessionRequest, type CloseSessionResponse, type CreateElicitationResponse, type ElicitationContentValue, type ElicitationPropertySchema, type ForkSessionRequest, type ForkSessionResponse, type InitializeRequest, type InitializeResponse, type ListSessionsRequest, type ListSessionsResponse, type LoadSessionRequest, type LoadSessionResponse, type McpServer, type NewSessionRequest, type NewSessionResponse, PROTOCOL_VERSION, type PromptRequest, type PromptResponse, RequestError, type ResumeSessionRequest, type ResumeSessionResponse, type SessionConfigOption, type SessionInfo, type SessionModeState, type SessionNotification, type SessionUpdate, type SetSessionConfigOptionRequest, type SetSessionConfigOptionResponse, type SetSessionModeRequest, type SetSessionModeResponse, type Usage, } from "@oh-my-pi/pi-utils/acp"; import { disableProvider, enableProvider } from "../../capability"; import { Settings } from "../../config/settings"; import { clearPluginRootsAndCaches, resolveActiveProjectRegistryPath } from "../../discovery/helpers"; import { type ExtensionUIContext, type ExtensionUIDialogOptions, getExtensionUISelectOptionLabel, timedOutAskDialogResult, } from "../../extensibility/extensions"; import { runExtensionCompact } from "../../extensibility/extensions/compact-handler"; import { getSessionSlashCommands } from "../../extensibility/extensions/get-commands-handler"; import { buildSkillPromptMessage, parseSkillInvocation } from "../../extensibility/skills"; import { MCPManager } from "../../mcp/manager"; import { reconnectMcpManagerServer } from "../../mcp/oauth-reauth"; import type { MCPServerConfig } from "../../mcp/types"; import { loadAllExtensions } from "../../modes/components/extensions/state-manager"; import { theme } from "@oh-my-pi/pi-tui/theme"; import { normalizePlanTitle, type PlanApprovalDetails, resolveApprovedPlan } from "../../plan-mode/approved-plan"; import { autosaveApprovedPlan } from "../../plan-mode/plan-autosave"; import type { AgentSession, AgentSessionEvent } from "../../session/agent-session"; import { BlobStore, resolveImageDataSync } from "../../session/blob-store"; import { isSilentAbort, SKILL_PROMPT_MESSAGE_TYPE, USER_INTERRUPT_LABEL } from "../../session/messages"; import type { UsageStatistics } from "../../session/session-entries"; import type { SessionInfo as StoredSessionInfo } from "../../session/session-listing"; import { SessionManager } from "../../session/session-manager"; import { executeAcpBuiltinSlashCommand } from "../../slash-commands/acp-builtins"; import { buildAvailableSlashCommands, toAcpAvailableCommands } from "../../slash-commands/available-commands"; import { DEFAULT_STT_MODEL_KEY, STT_MODELS } from "../../stt/models"; import { refreshAgentDiscovery } from "../../task"; import { AUTO_THINKING, parseConfiguredThinkingLevel } from "@oh-my-pi/pi-tui/thinking"; import { OTHER_OPTION } from "../../tools/ask"; import { resolvePlanFilePath } from "../../plan-mode/plan-files"; import { ToolError } from "@oh-my-pi/pi-tui/tools/tool-errors"; import { DEFAULT_TTS_SPEED, DEFAULT_TTS_VOICE, TTS_LOCAL_MODELS, TTS_LOCAL_VOICE_OPTIONS, TTS_SPEED_MAX, TTS_SPEED_MIN, TTS_SPEED_OPTIONS, } from "../../tts/models"; import { canonicalizeMessage } from "@oh-my-pi/pi-tui/chat/thinking-display"; import { createAcpClientBridge } from "./acp-client-bridge"; import { extractAssistantMessageText, mapAgentSessionEventToAcpSessionUpdates, normalizeReplayToolArguments, } from "./acp-event-mapper"; import { ACP_TERMINAL_AUTH_FLAG } from "./terminal-auth"; import { cfgDisabledExtensions } from "../../extensibility/settings"; import { cfgPlanEnabled } from "../../plan-mode/settings"; const ACP_DEFAULT_MODE_ID = "default"; const ACP_PLAN_MODE_ID = "plan"; const DEFAULT_PLAN_FILE_URL = "local://PLAN.md"; const APPROVE_OPTION = "Approve and execute"; const REFINE_OPTION = "Refine plan"; const MODE_CONFIG_ID = "mode"; const MODEL_CONFIG_ID = "model"; const THINKING_CONFIG_ID = "thinking"; const THINKING_OFF = "off"; const SESSION_PAGE_SIZE = 50; const SPEECH_MODELS_LIST_METHOD = "speech.models.list"; /** * `_session/steering` — the steering extension method from claude-agent-acp / * codex-acp (spec proposal: ACP `session/inject`, * agentclientprotocol/agent-client-protocol#1261, still open). Advertised via * top-level `_meta.steering.supported` in the `initialize` response; params * carry `{ sessionId, prompt: ContentBlock[] }`. The omp extension * `_meta.steering.queue: "followUp"` routes to the native follow-up queue * instead of the steering queue. Idle sessions are never consumed or started: * the response is always `promptRequired`, so the host submits the prompt * itself and keeps owning the turn. */ const SESSION_STEERING_METHOD = "_session/steering"; /** * Delay between `session/new` (or `session/load` / `session/resume` / * `unstable_session/fork`) returning and the agent firing the first * notifications against the new session id. Mitigates Zed's * `Received session notification for unknown session` race — see * `#scheduleBootstrapUpdates`. Exported so the ACP test harness can * wait past this guard without hard-coding the literal. */ export const ACP_BOOTSTRAP_RACE_GUARD_MS = 50; const ACP_CANCEL_CLEANUP_TIMEOUT_MS = 5_000; const ACP_ASYNC_DELIVERY_DRAIN_TIMEOUT_MS = 250; const ACP_ASYNC_DELIVERY_DRAIN_MAX_PASSES = 3; type AgentImageContent = { type: "image"; data: string; mimeType: string; }; type PromptQueueState = { promise: Promise<void>; release: (() => void) | undefined; }; /** * Cancellation carrier for a client prompt accepted on the wire whose turn has * not started yet — still queued behind another prompt, or inside the dispatch * window before its `PromptTurnState` slot exists. `session/request_cancel` * marks every live carrier so a stop can never race past a prompt that is * about to stream; the queue callback consumes the mark when the slot is * created and resolves the wire response `cancelled` without starting the run. */ type PromptDispatchCancellation = { cancelled: boolean }; type PromptLifecycleError = Error & { readonly code: "ACP_SESSION_CLOSED" }; type PromptTurnState = { abortController: AbortController; cancelRequested: boolean; settled: boolean; /** * Delivery of streamed assistant `error` chunks this turn (the mapper * surfaces them as `agent_message_chunk`s). Resolves `true` once at least * one error chunk reached the client — the `agent_end` error fallback in * {@link AcpAgent##flushUnreportedTurnError} awaits it and stays silent on * success, so a fallback racing an in-flight delivery can neither duplicate * the error nor drop it when delivery fails. */ errorTextDelivery: Promise<boolean> | undefined; /** * `abort()` is in-flight (or its bounded-timeout race). `undefined` while the turn is * running normally and after cleanup completes. The turn occupies `record.promptTurn` * for as long as either `!settled` or `cleanup` is set — that combined window is the * "turn in flight" predicate (`isPromptTurnInFlight`) every consumer gates on. */ cleanup: Promise<void> | undefined; usageBaseline: UsageStatistics; unsubscribe: (() => void) | undefined; resolve: (value: PromptResponse) => void; reject: (reason?: unknown) => void; promise: Promise<PromptResponse>; }; /** * A turn is "in flight" from the moment `prompt()` reserves the slot until `settled` is * true AND any cancel cleanup has completed. Fork/queue/event gating all depend on this * combined window — a settled-but-still-aborting turn is not safe to fork from, queue * onto, or forward late events for. */ function isPromptTurnInFlight(turn: PromptTurnState | undefined): turn is PromptTurnState { return turn !== undefined && (!turn.settled || turn.cleanup !== undefined); } /** * `_session/steering` prompt param: the same `ContentBlock[]` shape as * `session/prompt`. Blocks are validated here rather than trusted, because * `#convertPromptBlocks` dereferences their fields (`block.text`, image * `data`/`mimeType`, `block.resource`) — a null block would surface as a * TypeError (generic internal error) and an image without `data` would queue * an image with undefined fields. A bare string is accepted defensively for * slightly off-spec clients. */ function toSteeringPromptBlocks(prompt: unknown): PromptRequest["prompt"] { if (typeof prompt === "string") { return [{ type: "text", text: prompt }]; } if (!Array.isArray(prompt)) { throw RequestError.invalidParams({ method: SESSION_STEERING_METHOD }, "prompt must be content blocks"); } for (const block of prompt) { if (typeof block !== "object" || block === null || Array.isArray(block)) { throw RequestError.invalidParams({ method: SESSION_STEERING_METHOD }, "prompt blocks must be objects"); } const record = block as Record<string, unknown>; if (typeof record.type !== "string") { throw RequestError.invalidParams({ method: SESSION_STEERING_METHOD }, "prompt block requires a string type"); } // Own-key lookup: inherited names (`constructor`, `toString`, …) would // index inherited prototype values, and the `for…of` below would then // throw a TypeError that surfaces as a generic -32603 internal error. if (!Object.hasOwn(STEERING_BLOCK_STRING_FIELDS, record.type)) { throw RequestError.invalidParams( { method: SESSION_STEERING_METHOD }, `unsupported prompt block type: ${record.type}`, ); } const required = STEERING_BLOCK_STRING_FIELDS[record.type]; for (const field of required) { if (typeof record[field] !== "string") { throw RequestError.invalidParams( { method: SESSION_STEERING_METHOD }, `prompt block ${record.type} requires string ${field}`, ); } } if (record.type === "resource") { const resource = record.resource; if ( typeof resource !== "object" || resource === null || typeof (resource as Record<string, unknown>).uri !== "string" ) { throw RequestError.invalidParams( { method: SESSION_STEERING_METHOD }, "resource block requires a resource object with a string uri", ); } const resourceFields = resource as Record<string, unknown>; // `#convertPromptBlocks` selects the text arm whenever the key // exists and the image arm only for a string blob: require the // arm that would be selected to be a string, so a mixed shape // (e.g. a string blob plus a non-string text) cannot pass here // and then silently replace the image with the raw field value // in model input. A resource with neither arm keeps the same // rejection as before. if (Object.hasOwn(resourceFields, "text")) { if (typeof resourceFields.text !== "string") { throw RequestError.invalidParams( { method: SESSION_STEERING_METHOD }, "resource block with a text arm requires string text", ); } } else if (Object.hasOwn(resourceFields, "blob")) { if (typeof resourceFields.blob !== "string") { throw RequestError.invalidParams( { method: SESSION_STEERING_METHOD }, "resource block with a blob arm requires string blob", ); } } else { throw RequestError.invalidParams( { method: SESSION_STEERING_METHOD }, "resource block requires string text or string blob", ); } // The embedded-resource schema types `mimeType` as an optional // string (never null): reject a present non-string value instead // of letting it slip into the converter's image arm. if (Object.hasOwn(resourceFields, "mimeType") && typeof resourceFields.mimeType !== "string") { throw RequestError.invalidParams( { method: SESSION_STEERING_METHOD }, "resource block mimeType must be a string when present", ); } } if (record.type === "resource_link") { for (const field of ["title", "name", "mimeType", "description"] as const) { // `null` is a legal value (the ACP schema types these // `string | null`): treat it exactly like an absent field — // the converter's `title ?? name ?? uri` fallback already // does. if (record[field] !== undefined && record[field] !== null && typeof record[field] !== "string") { throw RequestError.invalidParams( { method: SESSION_STEERING_METHOD }, `resource_link ${field} must be a string or null when present`, ); } } if (record.size !== undefined && record.size !== null && typeof record.size !== "number") { throw RequestError.invalidParams( { method: SESSION_STEERING_METHOD }, "resource_link size must be a number or null when present", ); } } } return prompt as PromptRequest["prompt"]; } /** Required top-level string fields per accepted prompt block type. */ const STEERING_BLOCK_STRING_FIELDS: Record<string, string[]> = { text: ["text"], image: ["data", "mimeType"], audio: ["data", "mimeType"], resource_link: ["uri"], resource: [], }; /** * `_meta.steering.queue` of a `_session/steering` request — the omp-specific * opt-in routing the message to the native follow-up queue instead of the * steering queue. Everything else (including `idleBehavior`) is unused: idle * sessions always answer `promptRequired`, so the host keeps owning the turn. */ function steeringQueueFromMeta(meta: unknown): "steering" | "followUp" { if (typeof meta === "object" && meta !== null) { const steering = (meta as Record<string, unknown>).steering; if (typeof steering === "object" && steering !== null) { return (steering as Record<string, unknown>).queue === "followUp" ? "followUp" : "steering"; } } return "steering"; } type ManagedSessionRecord = { session: AgentSession; setToolUIContext: ((uiContext: ExtensionUIContext, hasUI: boolean) => void) | undefined; mcpManager: MCPManager | undefined; // Ordered queue of MCP tool refreshes for this record. Rebuilt per // `#configureMcpServers` call; drained on reconfigure so a stale in-flight // refresh can never land after a newer configuration's tools. mcpRefreshChain: Promise<void> | undefined; // MCP startup failures recorded during `#registerPreparedSession` (before // the newSession/loadSession response has told the client the session id). // Drained by `#emitBootstrapUpdates` behind the bootstrap race guard so // clients (Zed) cannot drop them as notifications for an unknown session. // `oauthCapable` marks http/sse servers, the only ones `/mcp reauth` can repair. pendingMcpStartupChunks: Array<{ name: string; message: string; oauthCapable: boolean }>; promptTurn: PromptTurnState | undefined; promptQueue: PromptQueueState; // Cancellation carriers for client prompts accepted on the wire whose // turn slot does not exist yet (queued behind another prompt or still // inside the dispatch window). Marked by cancel(); consumed at slot // creation so a stop never leaves a prompt streaming behind the client's back. pendingPromptDispatches: Array<PromptDispatchCancellation>; liveMessageId: string | undefined; liveMessageProgress: { textEmitted: boolean; thoughtEmitted: boolean } | undefined; toolArgsById: Map<string, unknown>; extensionsConfigured: boolean; // Installed inside `#scheduleBootstrapUpdates` (post-race-guard); released // in `#disposeSessionRecord`. Lives independent of any prompt turn. lifetimeUnsubscribe: (() => void) | undefined; closedError: PromptLifecycleError | undefined; promptEventHandlers: Set<Promise<void>>; extensionUserMessageTasks: Set<Promise<void>>; }; type ReplayableMessage = { role: string; content?: unknown; errorMessage?: string; toolCallId?: string; toolName?: string; details?: unknown; isError?: boolean; }; type ReplayableToolItem = { type?: unknown; id?: unknown; name?: unknown; arguments?: unknown; input?: unknown; }; type MCPConfigMap = { [name: string]: MCPServerConfig; }; type MCPSource = { provider: string; providerName: string; path: string; level: "project"; }; type MCPSourceMap = { [name: string]: MCPSource; }; type AcpSessionHandle = { session: AgentSession; setToolUIContext: (uiContext: ExtensionUIContext, hasUI: boolean) => void; }; type CreateAcpSession = ( cwd: string, options?: { interactivePrompts?: boolean }, ) => Promise<AgentSession | AcpSessionHandle>; function normalizeCreatedAcpSession(created: AgentSession | AcpSessionHandle): { session: AgentSession; setToolUIContext: AcpSessionHandle["setToolUIContext"] | undefined; } { return "session" in created ? created : { session: created, setToolUIContext: undefined }; } type AcpSpeechOption = { value: string; label: string; description?: string; }; type AcpSpeechVoiceOption = { value: string; label: string; }; type AcpSpeechTtsModelOption = AcpSpeechOption & { voices: AcpSpeechVoiceOption[]; }; function buildAcpSpeechModelsCatalog(): Record<string, unknown> { const localSelector = (modelId: string) => `local/${modelId}`; const defaultSpeechModel = localSelector(TTS_LOCAL_MODELS[0].key); const defaultDictationModel = localSelector(DEFAULT_STT_MODEL_KEY); const voices = TTS_LOCAL_VOICE_OPTIONS.map(({ value, label }) => ({ value, label })); // Speed settings are numeric, so presets are advertised as numbers clients can write back as-is. const speeds = TTS_SPEED_OPTIONS.map(({ value, label }) => ({ value: Number(value), label })); return { settings: { speechToTextModel: "modelRoles.dictation", textToSpeechModel: "modelRoles.speech", textToSpeechVoice: "tts.localVoice", speechVoice: "speech.voice", textToSpeechSpeed: "tts.localSpeed", speechSpeed: "speech.speed", }, defaults: { speechToTextModel: defaultDictationModel, textToSpeechModel: defaultSpeechModel, voice: DEFAULT_TTS_VOICE, speed: DEFAULT_TTS_SPEED, }, speechToText: { setting: "modelRoles.dictation", defaultValue: defaultDictationModel, models: STT_MODELS.map(({ key, label, description }) => ({ value: localSelector(key), label, description, })), }, textToSpeech: { modelSetting: "modelRoles.speech", voiceSetting: "tts.localVoice", speechVoiceSetting: "speech.voice", speedSetting: "tts.localSpeed", speechSpeedSetting: "speech.speed", defaultModel: defaultSpeechModel, defaultVoice: DEFAULT_TTS_VOICE, defaultSpeed: DEFAULT_TTS_SPEED, speedRange: { min: TTS_SPEED_MIN, max: TTS_SPEED_MAX }, models: TTS_LOCAL_MODELS.map(({ key, label, description, voices: modelVoices }): AcpSpeechTtsModelOption => ({ value: localSelector(key), label, description, voices: modelVoices.map(({ id, label: voiceLabel }) => ({ value: id, label: voiceLabel })), })), voices, speeds, }, }; } /** * Bridge an ExtensionUIContext form to ACP `unstable_createElicitation`. * * `dialogOptions.signal` short-circuits the elicitation if it is already * aborted and races the in-flight request against the abort event. The SDK * exposes no `cancel_elicitation` surface for form-mode elicitations * (`unstable_completeElicitation` is URL-mode only), so the ACP request itself * keeps running on the client side until the user dismisses it — but * resolving the local promise unblocks the caller (matches the RPC mode * pattern in `requestRpcEditor`). The abort listener is removed once the * elicitation settles so that callers which reuse the same signal across many * elicitations don't accumulate listeners and trip Node's `MaxListeners` * warning. * * `dialogOptions.timeout` mirrors `RpcExtensionUIContext.#createDialogPromise`: * when the timer fires before the client responds, `onTimeout` is invoked and * the caller's promise resolves to the stub fallback. Late SDK responses that * arrive after abort/timeout — both rejections and successful `accept`s — * are dropped silently (no `logger.warn`) to keep operator logs clean. */ async function elicitFormFromAcpClient( connection: AgentSideConnection, sessionId: string, method: string, message: string, properties: Record<string, ElicitationPropertySchema>, required: string[] | undefined, dialogOptions: ExtensionUIDialogOptions | undefined, ): Promise<Record<string, ElicitationContentValue> | undefined> { const signal = dialogOptions?.signal; if (signal?.aborted) { return undefined; } const { promise, resolve } = Promise.withResolvers<CreateElicitationResponse | undefined>(); let settled = false; let timeoutId: NodeJS.Timeout | undefined; const finish = (value: CreateElicitationResponse | undefined) => { if (settled) return; settled = true; clearTimeout(timeoutId); signal?.removeEventListener("abort", onAbort); resolve(value); }; const onAbort = () => finish(undefined); signal?.addEventListener("abort", onAbort, { once: true }); if (dialogOptions?.timeout !== undefined) { timeoutId = setTimeout(() => { if (settled) return; try { dialogOptions.onTimeout?.(); } catch (error) { // A throwing `onTimeout` must not leave the elicitation promise // pending — settle it via `finish` below regardless. logger.warn("ACP elicitation onTimeout threw", { sessionId, method, error }); } finish(undefined); }, dialogOptions.timeout); // A long pending timeout alone shouldn't keep the event loop alive when // the rest of the agent has shut down — matches `job-manager.ts` / // `executor.ts` timer hygiene. Connection + session lifetimes keep the // loop alive on the happy path. timeoutId.unref(); } connection .unstable_createElicitation({ mode: "form", sessionId, message, requestedSchema: { type: "object", properties, required, }, }) .then(finish, error => { // Caller may already have moved on via abort/timeout; suppress noise. if (settled) return; logger.warn("ACP elicitation failed", { sessionId, method, error }); finish(undefined); }); const response = await promise; if (!isAcceptedElicitation(response) || !response.content) { return undefined; } return response.content; } async function elicitFromAcpClient( connection: AgentSideConnection, sessionId: string, method: "select" | "confirm" | "input" | "editor", message: string, property: ElicitationPropertySchema, dialogOptions: ExtensionUIDialogOptions | undefined, ): Promise<ElicitationContentValue | undefined> { const content = await elicitFormFromAcpClient( connection, sessionId, method, message, { value: property }, ["value"], dialogOptions, ); return content?.value; } /** Narrows a `CreateElicitationResponse` to the accepted-with-content branch; the SDK's `action: string` catch-all arm otherwise defeats literal narrowing on `action !== "accept"`. */ function isAcceptedElicitation( response: CreateElicitationResponse | undefined, ): response is Extract<CreateElicitationResponse, { action: "accept" }> { return response?.action === "accept"; } /** * Build an {@link ExtensionUIContext} that translates skill/extension UI * requests into ACP elicitations against `connection` for the session * returned by `getSessionId()`. The id is read lazily at each elicitation * because `AgentSession.sessionId` is a getter over `sessionManager` state * that mutates when an extension command calls `ctx.newSession` / * `ctx.switchSession` — snapshotting it once at factory time would route * later elicitations to the pre-switch id. Live reads keep the bridge * symmetric with every other `sessionUpdate` call in this file * (`record.session.sessionId` is always evaluated at emit time). * * The non-elicitation surface (custom components, theming, terminal * input) remains stubbed — ACP clients render those themselves or not * at all. Capability gating respects the client's `initialize` * advertisement. */ export function createAcpExtensionUiContext( connection: AgentSideConnection, getSessionId: () => string, clientCapabilities: ClientCapabilities | undefined, ): ExtensionUIContext { const supportsForm = clientCapabilities?.elicitation?.form != null; return { supportsEditor: false, select: async (title, options, dialogOptions) => { if (!supportsForm) return undefined; const value = await elicitFromAcpClient( connection, getSessionId(), "select", title, { type: "string", enum: options.map(getExtensionUISelectOptionLabel) }, dialogOptions, ); return typeof value === "string" ? value : undefined; }, confirm: async (title, message, dialogOptions) => { if (!supportsForm) return false; const value = await elicitFromAcpClient( connection, getSessionId(), "confirm", message.trim().length > 0 ? `${title}\n\n${message}` : title, { type: "boolean" }, dialogOptions, ); return typeof value === "boolean" ? value : false; }, input: async (title, placeholder, dialogOptions) => { if (!supportsForm) return undefined; const value = await elicitFromAcpClient( connection, getSessionId(), "input", title, // ACP's `StringPropertySchema` has no `placeholder` field, so we // surface the placeholder text as `description` — the closest // semantic field a client can render alongside the input. // Empty / whitespace-only placeholders are treated as absent. { type: "string", ...(placeholder?.trim() ? { description: placeholder } : {}) }, dialogOptions, ); return typeof value === "string" ? value : undefined; }, askDialog: async (questions, dialogOptions) => { if (!supportsForm) return undefined; const properties: Record<string, ElicitationPropertySchema> = {}; for (const [index, question] of questions.entries()) { const key = `q${index}`; const entries = question.options.map(option => ({ const: option.label, title: option.label, ...(option.description?.trim() ? { description: option.description.trim() } : {}), })); const description = question.header?.trim(); if (entries.length > 0) { if (question.multi === true) { properties[key] = { type: "array", title: question.question, ...(description ? { description } : {}), items: { anyOf: entries }, }; } else { const recommended = question.recommended; properties[key] = { type: "string", title: question.question, ...(description ? { description } : {}), oneOf: entries, ...(recommended !== undefined && recommended >= 0 && recommended < question.options.length ? { default: question.options[recommended].label } : {}), }; } } properties[`${key}__other`] = { type: "string", title: OTHER_OPTION }; } let timedOut = false; const content = await elicitFormFromAcpClient( connection, getSessionId(), "askDialog", questions.length === 1 ? questions[0].question : `Answer ${questions.length} questions`, properties, undefined, { ...dialogOptions, onTimeout: () => { timedOut = true; dialogOptions?.onTimeout?.(); }, }, ); if (timedOut) return timedOutAskDialogResult(questions); if (!content) return undefined; return { kind: "submit", results: questions.map((question, index) => { const key = `q${index}`; const otherKey = `${key}__other`; const labels = question.options.map(option => option.label); const otherValue = content[otherKey]; const customInput = typeof otherValue === "string" && otherValue.trim() ? otherValue.trim() : undefined; const value = content[key]; const selectedOptions = question.multi === true ? Array.isArray(value) ? value.filter(candidate => typeof candidate === "string" && labels.includes(candidate)) : [] : customInput === undefined && typeof value === "string" && labels.includes(value) ? [value] : []; return { id: question.id, question: question.question, options: labels, multi: question.multi ?? false, selectedOptions, customInput, }; }), }; }, notify: (message, type) => { logger.debug("ACP extension notification", { message, type }); }, onTerminalInput: () => () => {}, setStatus: () => {}, setWorkingMessage: () => {}, setWidget: () => {}, setFooter: () => {}, setHeader: () => {}, setTitle: () => {}, custom: async () => undefined as never, pasteToEditor: () => {}, setEditorText: () => {}, getEditorText: () => "", editor: async (title, prefill, dialogOptions) => { if (!supportsForm) return undefined; const value = await elicitFromAcpClient( connection, getSessionId(), "editor", title, { type: "string", ...(prefill ? { default: prefill } : {}) }, dialogOptions, ); return typeof value === "string" ? value : undefined; }, addAutocompleteProvider: () => {}, setEditorComponent: () => {}, getEditorComponent: () => undefined, get theme() { return theme; }, getAllThemes: async () => [], getTheme: async () => undefined, setTheme: async () => ({ success: false, error: "Theme changes are unavailable in ACP mode" }), getToolsExpanded: () => false, setToolsExpanded: () => {}, }; } export class AcpAgent implements Agent { #connection: AgentSideConnection; #initialSession: AgentSession | undefined; #createSession: CreateAcpSession; #sessions = new Map<string, ManagedSessionRecord>(); #disposePromise: Promise<void> | undefined; #cleanupRegistered = false; #clientCapabilities: ClientCapabilities | undefined; #cancelCleanupTimeoutMs = ACP_CANCEL_CLEANUP_TIMEOUT_MS; #blobs = new BlobStore(getBlobsDir()); constructor(connection: AgentSideConnection, createSession: CreateAcpSession, initialSession?: AgentSession) { this.#connection = connection; this.#initialSession = initialSession; this.#createSession = createSession; } setCancelCleanupTimeoutForTesting(timeoutMs: number): void { this.#cancelCleanupTimeoutMs = Math.max(1, timeoutMs); } async initialize(params: InitializeRequest): Promise<InitializeResponse> { this.#registerConnectionCleanup(); this.#clientCapabilities = params.clientCapabilities; const authMethods: AuthMethod[] = [ { id: "agent", name: "Use existing local credentials", description: "Authenticate via the provider keys/OAuth state already configured under ~/.omp.", }, ]; if (params.clientCapabilities?.auth?.terminal === true) { authMethods.push({ type: "terminal", id: "terminal", name: "Set up omp in terminal", description: "Launch the omp TUI to add provider keys and select models.", args: [ACP_TERMINAL_AUTH_FLAG], }); } return { protocolVersion: PROTOCOL_VERSION, agentInfo: { name: "omp", title: "omp", version: VERSION, }, authMethods, agentCapabilities: { loadSession: true, mcpCapabilities: { http: true, sse: true, }, promptCapabilities: { embeddedContext: true, image: true, }, sessionCapabilities: { list: {}, fork: {}, resume: {}, close: {}, }, }, // Top-level `_meta` (sibling of `agentCapabilities`) is where // claude-agent-acp and codex-acp advertise steering; clients such as // agent-shell gate `_session/steering` on it. _meta: { steering: { supported: true }, }, }; } async authenticate(params: AuthenticateRequest): Promise<AuthenticateResponse> { // ACP spec: `methodId` must be one of the methods advertised by `initialize`. // Reject anything else so malformed clients fail fast rather than appearing // authenticated and surfacing a downstream model failure later. const supportsTerminalAuth = this.#clientCapabilities?.auth?.terminal === true; const validMethods = supportsTerminalAuth ? ["agent", "terminal"] : ["agent"]; if (!validMethods.includes(params.methodId)) { throw new Error(`Unknown ACP auth method: ${params.methodId}`); } return {}; } async newSession(params: NewSessionRequest): Promise<NewSessionResponse> { this.#assertAbsoluteCwd(params.cwd); const record = await this.#createNewSessionRecord(params.cwd, params.mcpServers); const response: NewSessionResponse = { sessionId: record.session.sessionId, configOptions: this.#buildConfigOptions(record.session), modes: this.#buildModeState(record.session), }; this.#scheduleBootstrapUpdates(record.session.sessionId); return response; } async loadSession(params: LoadSessionRequest): Promise<LoadSessionResponse> { this.#assertAbsoluteCwd(params.cwd); const record = await this.#loadManagedSession(params.sessionId, params.cwd, params.mcpServers); await this.#replaySessionHistory(record); const response: LoadSessionResponse = { configOptions: this.#buildConfigOptions(record.session), modes: this.#buildModeState(record.session), }; this.#scheduleBootstrapUpdates(record.session.sessionId); return response; } async listSessions(params: ListSessionsRequest): Promise<ListSessionsResponse> { if (params.cwd) { this.#assertAbsoluteCwd(params.cwd); } for (const record of this.#sessions.values()) { await record.session.sessionManager.flush(); } const sessions = await this.#listStoredSessions(params.cwd ?? undefined); const offset = this.#parseCursor(params.cursor ?? undefined); const paged = sessions.slice(offset, offset + SESSION_PAGE_SIZE); const nextOffset = offset + paged.length; return { sessions: paged.map(session => this.#toSessionInfo(session)), nextCursor: nextOffset < sessions.length ? String(nextOffset) : undefined, }; } async resumeSession(params: ResumeSessionRequest): Promise<ResumeSessionResponse> { this.#assertAbsoluteCwd(params.cwd); const record = await this.#resumeManagedSession(params.sessionId, params.cwd, params.mcpServers ?? []); const response: ResumeSessionResponse = { configOptions: this.#buildConfigOptions(record.session), modes: this.#buildModeState(record.session), }; this.#scheduleBootstrapUpdates(record.session.sessionId); return response; } async unstable_forkSession(params: ForkSessionRequest): Promise<ForkSessionResponse> { this.#assertAbsoluteCwd(params.cwd); const record = await this.#forkManagedSession(params); const response: ForkSessionResponse = { sessionId: record.session.sessionId, configOptions: this.#buildConfigOptions(record.session), modes: this.#buildModeState(record.session), }; this.#scheduleBootstrapUpdates(record.session.sessionId); return response; } async closeSession(params: CloseSessionRequest): Promise<CloseSessionResponse> { const record = this.#sessions.get(params.sessionId); if (!record) { return {}; } await this.#closeManagedSession(params.sessionId, record); return {}; } async setSessionMode(params: SetSessionModeRequest): Promise<SetSessionModeResponse> { const record = this.#getSessionRecord(params.sessionId); this.#applyModeChange(record.session, params.modeId); await this.#connection.sessionUpdate({ sessionId: record.session.sessionId, update: this.#buildCurrentModeUpdate(record.session), }); await this.#pushConfigOptionUpdate(record); return {}; } async setSessionConfigOption(params: SetSessionConfigOptionRequest): Promise<SetSessionConfigOptionResponse> { const record = this.#getSessionRecord(params.sessionId); if (typeof params.value === "boolean") { throw new Error(`Unsupported boolean ACP config option: ${params.configId}`); } switch (params.configId) { case MODE_CONFIG_ID: this.#applyModeChange(record.session, params.value); break; case MODEL_CONFIG_ID: await this.#setModelById(record.session, params.value); break; case THINKING_CONFIG_ID: this.#setThinkingLevelById(record.session, params.value); break; default: throw new Error(`Unknown ACP config option: ${params.configId}`); } // When mode is changed via the generic config-option API, mirror the // `current_mode_update` notification that `setSessionMode` emits so // ACP clients tracking session-mode state see a consistent transition. if (params.configId === MODE_CONFIG_ID) { await this.#connection.sessionUpdate({ sessionId: record.session.sessionId, update: this.#buildCurrentModeUpdate(record.session), }); } // For `model`/`thinking`, `#setModelById`/`#setThinkingLevelById` change // the session model/thinking level through AgentSession, which now emits // a lifetime event (`model_changed`/`thinking_level_changed`) that // `#handleLifetimeEvent` turns into a push once the subscription is // installed. Only push here when that subscription is not yet // installed, so pre-bootstrap callers still see the change without a // post-bootstrap duplicate. const handledBySubscription = (params.configId === THINKING_CONFIG_ID || params.configId === MODEL_CONFIG_ID) && record.lifetimeUnsubscribe !== undefined; if (!handledBySubscription) { await this.#pushConfigOptionUpdate(record); } return { configOptions: this.#buildConfigOptions(record.session) }; |
| You are visitor 01402911 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |