@agentrq/acp-gateway 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +59 -169
  2. package/dist/__tests__/agentInfo.test.js +2 -31
  3. package/dist/__tests__/agentInfo.test.js.map +1 -1
  4. package/dist/__tests__/concurrency.test.js +1 -74
  5. package/dist/__tests__/concurrency.test.js.map +1 -1
  6. package/dist/__tests__/index.test.js +190 -2672
  7. package/dist/__tests__/index.test.js.map +1 -1
  8. package/dist/__tests__/localClient.test.js +100 -0
  9. package/dist/__tests__/localClient.test.js.map +1 -0
  10. package/dist/__tests__/log.test.js +1 -42
  11. package/dist/__tests__/log.test.js.map +1 -1
  12. package/dist/__tests__/mcpServers.test.js +62 -0
  13. package/dist/__tests__/mcpServers.test.js.map +1 -0
  14. package/dist/__tests__/models.test.js +2 -18
  15. package/dist/__tests__/models.test.js.map +1 -1
  16. package/dist/__tests__/native.test.js +294 -29
  17. package/dist/__tests__/native.test.js.map +1 -1
  18. package/dist/__tests__/nativeFrames.test.js +132 -4
  19. package/dist/__tests__/nativeFrames.test.js.map +1 -1
  20. package/dist/__tests__/nativeHeaders.test.js +34 -0
  21. package/dist/__tests__/nativeHeaders.test.js.map +1 -1
  22. package/dist/agentInfo.js +0 -31
  23. package/dist/agentInfo.js.map +1 -1
  24. package/dist/concurrency.js +6 -64
  25. package/dist/concurrency.js.map +1 -1
  26. package/dist/index.js +114 -1729
  27. package/dist/index.js.map +1 -1
  28. package/dist/localClient.js +91 -0
  29. package/dist/localClient.js.map +1 -0
  30. package/dist/log.js +0 -22
  31. package/dist/log.js.map +1 -1
  32. package/dist/mcpServers.js +60 -0
  33. package/dist/mcpServers.js.map +1 -0
  34. package/dist/models.js +0 -10
  35. package/dist/models.js.map +1 -1
  36. package/dist/native.js +243 -30
  37. package/dist/native.js.map +1 -1
  38. package/dist/nativeFrames.js +114 -12
  39. package/dist/nativeFrames.js.map +1 -1
  40. package/package.json +6 -8
  41. package/dist/__tests__/acpClient.test.js +0 -2346
  42. package/dist/__tests__/acpClient.test.js.map +0 -1
  43. package/dist/__tests__/collections.test.js +0 -116
  44. package/dist/__tests__/collections.test.js.map +0 -1
  45. package/dist/__tests__/commands.test.js +0 -92
  46. package/dist/__tests__/commands.test.js.map +0 -1
  47. package/dist/__tests__/mcpClient.test.js +0 -558
  48. package/dist/__tests__/mcpClient.test.js.map +0 -1
  49. package/dist/__tests__/taskIdentity.test.js +0 -63
  50. package/dist/__tests__/taskIdentity.test.js.map +0 -1
  51. package/dist/__tests__/telemetry.test.js +0 -151
  52. package/dist/__tests__/telemetry.test.js.map +0 -1
  53. package/dist/acpClient.js +0 -1112
  54. package/dist/acpClient.js.map +0 -1
  55. package/dist/collections.js +0 -105
  56. package/dist/collections.js.map +0 -1
  57. package/dist/commands.js +0 -60
  58. package/dist/commands.js.map +0 -1
  59. package/dist/mcpClient.js +0 -361
  60. package/dist/mcpClient.js.map +0 -1
  61. package/dist/taskIdentity.js +0 -41
  62. package/dist/taskIdentity.js.map +0 -1
  63. package/dist/telemetry.js +0 -106
  64. package/dist/telemetry.js.map +0 -1
package/dist/acpClient.js DELETED
@@ -1,1112 +0,0 @@
1
- /**
2
- * acpClient.ts
3
- *
4
- * Implements the ACP Client interface for the agentrq workspace.
5
- * Routes permission requests to the MCP server.
6
- */
7
- import { callTaskAction } from "./mcpClient.js";
8
- import { TELEMETRY_NOTIFICATION_METHOD, formatPlan, formatUsage, planFromEntries, planTelemetryData, usageTelemetryData, } from "./telemetry.js";
9
- import { extractModels } from "./models.js";
10
- import { COMMANDS_NOTIFICATION_METHOD, normalizeCommands, } from "./commands.js";
11
- import { sendAgentIdentity } from "./agentInfo.js";
12
- import * as fs from "node:fs/promises";
13
- import * as path from "node:path";
14
- import { debug, isVerbose } from "./log.js";
15
- import { BoundedMap } from "./collections.js";
16
- /**
17
- * Identifies a tool call routed through an agentrq MCP server named after a
18
- * bare workspace id.
19
- *
20
- * Matched anywhere in a title, which is looser than the checks below — but it
21
- * is the rule every existing deployment already relies on, so it stays exactly
22
- * as generous as it was.
23
- */
24
- const AGENTRQ_TOOL_PATTERN = /agentrq-[a-zA-Z0-9]{11}/;
25
- /**
26
- * An MCP server belonging to agentrq: a bare workspace id today, a slug
27
- * tomorrow, so anything starting `agentrq` counts.
28
- *
29
- * Being generous about the name is safe because the name alone never grants
30
- * auto-approval — the tool it is calling has to be one the workspace itself
31
- * advertises.
32
- */
33
- const AGENTRQ_SERVER = /^agentrq(?:[.\-_][A-Za-z0-9.\-_]*)?$/i;
34
- /**
35
- * The tools agentrq's workspace server is known to advertise, used only when
36
- * the server has not managed to say for itself.
37
- *
38
- * Not the mechanism — `MCPBridge.getAdvertisedTools` is — just a floor, so a
39
- * `tools/list` that failed does not turn every workspace call into a question
40
- * for the human.
41
- */
42
- const KNOWN_WORKSPACE_TOOLS = new Set([
43
- "task",
44
- "memory",
45
- "skills",
46
- "workspace",
47
- "siteTools",
48
- "pano",
49
- "help",
50
- // What those replaced, still advertised by older servers.
51
- "reply",
52
- "createTask",
53
- "getTask",
54
- "updateTaskStatus",
55
- "getWorkspace",
56
- "publishEvent",
57
- "getAttachment",
58
- "elicit",
59
- "loadMemory",
60
- "saveMemory",
61
- "deleteMemory",
62
- ]);
63
- /**
64
- * The server and tool an MCP tool-call title names, if it names one.
65
- *
66
- * Agents each spell this their own way — `mcp__server__tool`,
67
- * `mcp.server.tool`, `tool (server MCP Server)` — but all of them put the two
68
- * names in fixed positions. Reading the positions, rather than searching the
69
- * whole title, is what stops a path under a directory of the same name (or an
70
- * argument echoed into the title) from reading as a call to that server.
71
- */
72
- function mcpCallFromTitle(title) {
73
- // `saveMemory (agentrq-workspace MCP Server)`
74
- const attributed = /^\s*([A-Za-z0-9_]+)\s*\(\s*([^()\s]+)\s+MCP\b/i.exec(title);
75
- if (attributed)
76
- return { server: attributed[2], tool: attributed[1] };
77
- // `mcp__agentrq-workspace__saveMemory`, `mcp.agentrq-workspace.saveMemory`
78
- const qualified = /^\s*mcp(__|[.\-])(.+?)\1([A-Za-z0-9_]+)\s*$/i.exec(title);
79
- if (qualified)
80
- return { server: qualified[2], tool: qualified[3] };
81
- return undefined;
82
- }
83
- /**
84
- * The task and text of a workspace reply the agent sent itself, if this
85
- * workspace tool call was one.
86
- *
87
- * A reply comes in three shapes: the old `reply {chatId, text}`,
88
- * `task {action: "reply", payload: {taskId, text}}`, and the flat
89
- * `task {action: "reply", taskId, text}` the workspace also accepts.
90
- */
91
- function agentReplyFromCall(title, rawInput) {
92
- if (rawInput == null || typeof rawInput !== "object")
93
- return undefined;
94
- const tool = mcpCallFromTitle(title)?.tool ?? title.trim().split(/[\s(]/)[0];
95
- const input = rawInput;
96
- if (/(^|[._-])reply$/.test(tool) && typeof input.chatId === "string") {
97
- return { taskId: input.chatId, text: input.text ?? "" };
98
- }
99
- if (/(^|[._-])task$/.test(tool) && input.action === "reply") {
100
- const args = input.payload != null && typeof input.payload === "object" ? input.payload : input;
101
- if (typeof args.taskId === "string")
102
- return { taskId: args.taskId, text: args.text ?? "" };
103
- }
104
- return undefined;
105
- }
106
- /** A title that is nothing but a name: no arguments, no attribution, no path. */
107
- const BARE_TITLE = /^[A-Za-z0-9._-]+$/;
108
- /** Where one name could end and the next begin, longest separator first. */
109
- const NAME_SEPARATOR = /__|[._-]/g;
110
- /**
111
- * Every way a bare `server<sep>tool` title could divide into its two names.
112
- *
113
- * Some agents drop the `mcp` prefix entirely and announce the call as
114
- * `agentrq-workspace_updateTaskStatus`. That leaves nothing to anchor on: the
115
- * separator is also a character both names are free to contain, so where the
116
- * server ends cannot be read off the title alone.
117
- *
118
- * So this does not try to decide. It offers every division, and the caller
119
- * accepts one only if *both* halves check out — a server it recognises and a
120
- * tool that server advertises. Two independent confirmations are what make a
121
- * guessed split safe: `write_file` offers `write`/`file`, and no workspace
122
- * answers to that.
123
- */
124
- function bareCallCandidates(title) {
125
- const trimmed = title.trim();
126
- if (!BARE_TITLE.test(trimmed))
127
- return [];
128
- const candidates = [];
129
- NAME_SEPARATOR.lastIndex = 0;
130
- for (let match = NAME_SEPARATOR.exec(trimmed); match !== null; match = NAME_SEPARATOR.exec(trimmed)) {
131
- const server = trimmed.slice(0, match.index);
132
- const tool = trimmed.slice(match.index + match[0].length);
133
- if (server && tool)
134
- candidates.push({ server, tool });
135
- }
136
- return candidates;
137
- }
138
- /** How long to wait for `session/cancel` before settling permissions regardless. */
139
- const CANCEL_SESSION_TIMEOUT_MS = 5000;
140
- /**
141
- * What a turn ending in anything but `end_turn` means, in the human's terms.
142
- *
143
- * Without this the workspace sees the agent's partial answer and nothing else,
144
- * so a refused or truncated turn is indistinguishable from a finished one.
145
- */
146
- /**
147
- * How long a tool call waits for a human before the turn is given up on.
148
- *
149
- * Humans are slow — this is not a network timeout — but it must exist: a wait
150
- * with no end holds a task-queue slot for the life of the process, and at low
151
- * concurrency one unanswered approval is enough to stop the workspace.
152
- */
153
- export const DEFAULT_PERMISSION_TIMEOUT_MS = 30 * 60 * 1000;
154
- /**
155
- * The last model list reported for each session.
156
- *
157
- * Kept so a runtime selection that fails can put back what was true. The
158
- * workspace marks a chosen model pending and waits for a models notification to
159
- * confirm it, so a set that throws would otherwise leave the picker showing a
160
- * model the agent never adopted, with nothing ever arriving to correct it.
161
- *
162
- * Deliberately module-level rather than a field. A set can arrive for a session
163
- * whose agent has already exited, and the client instance that served it went
164
- * with the process — an instance field would take the only record of what that
165
- * session was on with it, leaving the one case that most needs answering unable
166
- * to be answered. Session ids are unique, so nothing collides here.
167
- * Bounded because every session the gateway ever opened would otherwise stay
168
- * here; one evicted is answered as if nothing had been reported for it yet.
169
- *
170
- * Written in sendModelsToWorkspace because that is the single point every report
171
- * leaves through, which is what keeps this current without a second place to
172
- * remember to update.
173
- */
174
- const lastModels = new BoundedMap(256);
175
- /** What was last reported for a session, from anywhere, including after it ends. */
176
- export function lastModelsForSession(sessionId) {
177
- return lastModels.get(sessionId);
178
- }
179
- /**
180
- * Sends a session's model list to the workspace.
181
- *
182
- * Standalone, like sendAgentIdentity, because the caller that needs it most has
183
- * no client left to call a method on: a set_model for a session that has ended
184
- * still has to be answered, and only the bridge survives that.
185
- *
186
- * Never throws: this is an interface update, and a workspace that cannot take it
187
- * right now must not cost the agent anything.
188
- */
189
- export async function sendModelsNotification(bridge, sessionId, modelsResult, taskId) {
190
- lastModels.set(sessionId, modelsResult);
191
- const serializedModels = modelsResult.models.map((m) => {
192
- const isCurrent = m.current ?? false;
193
- return {
194
- ...m,
195
- id: m.id,
196
- model_id: m.model_id ?? m.id,
197
- modelId: m.modelId ?? m.id,
198
- value: m.value ?? m.id,
199
- name: m.name,
200
- label: m.label ?? m.name,
201
- title: m.title ?? m.name,
202
- description: m.description,
203
- current: isCurrent,
204
- is_current: m.is_current ?? isCurrent,
205
- isCurrent: m.isCurrent ?? isCurrent,
206
- };
207
- });
208
- const payload = {
209
- // No task required. The workspace keys this to the MCP connection it
210
- // arrived on and ignores the task id, so refusing to send without one only
211
- // kept a workspace ignorant of its agent until somebody gave it work —
212
- // which is exactly when a human is looking at it.
213
- task_id: taskId ?? "",
214
- taskId: taskId ?? "",
215
- session_id: sessionId,
216
- sessionId: sessionId,
217
- config_id: modelsResult.configId,
218
- configId: modelsResult.configId,
219
- current_model: modelsResult.currentModelId,
220
- currentModel: modelsResult.currentModelId,
221
- current_model_id: modelsResult.currentModelId,
222
- currentModelId: modelsResult.currentModelId,
223
- models: serializedModels,
224
- available_models: serializedModels,
225
- availableModels: serializedModels,
226
- // This gateway acts on a set_model notification, and says so.
227
- //
228
- // The workspace cannot infer it: every gateway ever published reports its
229
- // models, and the ones before this release ignore being told to change
230
- // one. Nor can it be read off the client name, which is "acp-gateway"
231
- // either way — the question is about the version, not the identity. So
232
- // the capability is declared here, absence means no, and older gateways
233
- // stay read-only without knowing this field exists.
234
- can_set: true,
235
- canSet: true,
236
- };
237
- try {
238
- await bridge.sendNotification("notifications/claude/channel/models", payload);
239
- debug(`[acp] Shared ${modelsResult.models.length} supported model(s) with workspace (current: ${modelsResult.currentModelId ?? "none"})`);
240
- }
241
- catch (err) {
242
- console.error(`[acp] Failed to send models notification for session ${sessionId}:`, err);
243
- }
244
- }
245
- const STOP_REASON_NOTES = {
246
- refusal: "⚠️ The agent refused to continue this turn.",
247
- max_tokens: "⚠️ The agent stopped mid-turn: it ran out of output tokens.",
248
- max_turn_requests: "⚠️ The agent stopped mid-turn: it reached its limit on model requests for a single turn.",
249
- cancelled: "⚠️ The turn was cancelled before the agent finished.",
250
- };
251
- /** A line/limit bound the caller left out, or sent as something unusable. */
252
- function lineBound(value) {
253
- return typeof value === "number" && Number.isFinite(value)
254
- ? Math.trunc(value)
255
- : undefined;
256
- }
257
- /**
258
- * The window of `content` an ACP `fs/read_text_file` request asked for.
259
- *
260
- * `line` is a 1-based start line and `limit` a maximum line count; either may
261
- * be absent, in which case the window runs from the start of the file, or to
262
- * its end. Lines keep the newline they had in the file, so the result is
263
- * always an exact substring — reading a whole file returns it byte for byte.
264
- *
265
- * A `line` past the end of the file yields an empty window rather than an
266
- * error: the agent asked what is there, and the answer is nothing.
267
- */
268
- function sliceLines(content, line, limit) {
269
- const startLine = lineBound(line);
270
- const maxLines = lineBound(limit);
271
- if (startLine === undefined && maxLines === undefined)
272
- return content;
273
- let start = 0;
274
- for (let i = 1; i < (startLine ?? 1); i++) {
275
- const lineEnd = content.indexOf("\n", start);
276
- if (lineEnd === -1)
277
- return "";
278
- start = lineEnd + 1;
279
- }
280
- if (maxLines === undefined)
281
- return content.slice(start);
282
- if (maxLines <= 0)
283
- return "";
284
- let end = start;
285
- for (let i = 0; i < maxLines; i++) {
286
- const lineEnd = content.indexOf("\n", end);
287
- if (lineEnd === -1)
288
- return content.slice(start);
289
- end = lineEnd + 1;
290
- }
291
- return content.slice(start, end);
292
- }
293
- /**
294
- * Renders a url-mode elicitation for someone reading a terminal.
295
- *
296
- * The URL goes on a line of its own: an agent's `message` carries the part
297
- * only a human can supply — codex-acp puts the one-time device code there —
298
- * and says nothing about where to type it, so a log of the message alone
299
- * leaves the reader with a code and nowhere to use it.
300
- */
301
- export function formatUrlElicitation(message, url) {
302
- return `\n[auth] ${message}\n[auth] Open this URL to continue:\n\n ${url}\n`;
303
- }
304
- export class AgentRQACPClient {
305
- mcpBridge;
306
- getTaskIdForSession;
307
- replyBuffers = new BoundedMap(256);
308
- // sessionId → reasoning accumulated since the last boundary. Thought tokens
309
- // stream one at a time and are deliberately kept out of replyBuffers: they
310
- // are not the answer, and folding them in would both corrupt the reply and
311
- // break the dedup against the agent's own `reply` tool call.
312
- thoughtBuffers = new BoundedMap(256);
313
- // sessionId → the most recent usage snapshot. Only the last one is worth
314
- // reporting: each supersedes the one before it.
315
- latestUsage = new BoundedMap(256);
316
- // Telemetry sends, run one after another so the workspace sees them in the
317
- // order the agent produced them, and off the ACP stream's critical path so a
318
- // slow or unreachable workspace never stalls the agent mid-turn.
319
- telemetryChain = Promise.resolve();
320
- // taskId → text the agent replied to the workspace itself (for dedup in flushReply)
321
- agentReplies = new BoundedMap(200);
322
- // toolCallId → details seen on session updates. A `tool_call` update always
323
- // carries a title, but the permission request for that same call may omit it
324
- // (ACP marks it optional there, and codex-acp sends it bare), which would
325
- // otherwise leave us unable to tell an agentrq MCP call from anything else.
326
- toolCallDetails = new BoundedMap(512);
327
- // request_id → the tool call waiting on a human. One shared verdict listener
328
- // serves them all: a listener per request was only ever removed on a matching
329
- // verdict, so every unanswered request leaked one for the life of the process.
330
- pendingPermissions = new Map();
331
- // elicitationId → the terminal prompt still waiting on a human. Kept so an
332
- // `elicitation/complete` can close a prompt whose answer the agent has
333
- // stopped waiting for — a browser login that finished on its own, say.
334
- pendingUrlElicitations = new Map();
335
- permissionTimeoutMs;
336
- promptUrlElicitation;
337
- cancelSession;
338
- onModeChanged;
339
- // The name the workspace server is configured under. Fixed for the life of
340
- // the bridge, so it is read once.
341
- workspaceServer;
342
- constructor(mcpBridge, getTaskIdForSession = () => undefined, options = {}) {
343
- this.mcpBridge = mcpBridge;
344
- this.getTaskIdForSession = getTaskIdForSession;
345
- this.workspaceServer = this.mcpBridge.getServerName?.();
346
- this.permissionTimeoutMs = options.permissionTimeoutMs ?? DEFAULT_PERMISSION_TIMEOUT_MS;
347
- this.promptUrlElicitation = options.promptUrlElicitation;
348
- this.mcpBridge.on("verdict", this.onVerdict);
349
- this.mcpBridge.on("reconnected", this.onWorkspaceReconnected);
350
- }
351
- /**
352
- * Supplies what to do when the agent changes its own session mode.
353
- *
354
- * The gateway pins a mode that routes approvals to the human at session
355
- * creation, but agents may switch modes on their own — and back into one
356
- * that approves on the user's behalf.
357
- */
358
- setModeChangeHandler(handler) {
359
- this.onModeChanged = handler;
360
- }
361
- /**
362
- * Cleans up event listeners registered on mcpBridge and aborts/cancels any
363
- * pending elicitation or permission promises.
364
- */
365
- dispose() {
366
- const bridge = this.mcpBridge;
367
- bridge.off?.("verdict", this.onVerdict);
368
- bridge.off?.("reconnected", this.onWorkspaceReconnected);
369
- this.cancelPendingPermissions("client disposed");
370
- for (const controller of this.pendingUrlElicitations.values()) {
371
- controller.abort();
372
- }
373
- this.pendingUrlElicitations.clear();
374
- this.replyBuffers.clear();
375
- this.thoughtBuffers.clear();
376
- this.latestUsage.clear();
377
- this.agentReplies.clear();
378
- this.toolCallDetails.clear();
379
- }
380
- /** How many tool calls are waiting on a human right now. */
381
- get pendingPermissionCount() {
382
- return this.pendingPermissions.size;
383
- }
384
- /**
385
- * Supplies the way to stop a turn, which only exists once the agent
386
- * connection has been built around this client.
387
- */
388
- setSessionCanceller(cancel) {
389
- this.cancelSession = cancel;
390
- }
391
- /**
392
- * Answers every waiting tool call with `cancelled`.
393
- *
394
- * Used when the agent is gone: nothing will ever act on those answers, but
395
- * the promises must settle or their task-queue slots are held forever.
396
- */
397
- cancelPendingPermissions(reason, sessionId) {
398
- if (this.pendingPermissions.size === 0)
399
- return;
400
- const toCancel = sessionId
401
- ? [...this.pendingPermissions.values()].filter((p) => p.sessionId === sessionId)
402
- : [...this.pendingPermissions.values()];
403
- if (toCancel.length === 0)
404
- return;
405
- debug(`[acp] Cancelling ${toCancel.length} waiting permission request(s): ${reason}`);
406
- for (const pending of toCancel) {
407
- pending.settle({ outcome: "cancelled" });
408
- }
409
- }
410
- /**
411
- * Re-sends everything still waiting, after the workspace connection was
412
- * re-established on a new session.
413
- *
414
- * A verdict is routed back to the session its request arrived on, so a
415
- * request that was in flight across a reconnect can never be answered. The
416
- * request id stays the same, which is what lets the workspace recognise this
417
- * as the same pending decision rather than a new one to ask about again.
418
- */
419
- onWorkspaceReconnected = () => {
420
- if (this.pendingPermissions.size === 0)
421
- return;
422
- debug(`[acp] Workspace reconnected — re-sending ${this.pendingPermissions.size} ` +
423
- `permission request(s) that would otherwise never be answered`);
424
- for (const pending of this.pendingPermissions.values()) {
425
- void this.mcpBridge
426
- .sendNotification("notifications/claude/channel/permission_request", pending.payload)
427
- .catch((err) => {
428
- console.error(`[acp] Failed to re-send permission request ${pending.payload.request_id}:`, err);
429
- });
430
- }
431
- };
432
- /** Delivers a verdict to whichever tool call is waiting on it, if any. */
433
- onVerdict = (data) => {
434
- const pending = this.pendingPermissions.get(data.requestId);
435
- if (!pending) {
436
- debug(`[acp] Verdict for ${data.requestId} arrived with nothing waiting on it`);
437
- return;
438
- }
439
- console.error(`✅ Permission verdict received: ${data.behavior}`);
440
- pending.settle(this.outcomeForVerdict(pending.options, data.behavior));
441
- };
442
- /** Stops the agent's current turn and cancels any pending permissions for the session. */
443
- async cancelTurn(sessionId) {
444
- if (!sessionId)
445
- return;
446
- try {
447
- // Cancel before answering: the spec treats `cancelled` as the answer a
448
- // client gives *because* it cancelled the turn, so settling first would
449
- // leave the agent free to carry on and ask again. The wait is bounded and
450
- // the settle happens either way — an agent wedged on its stdin must not
451
- // hold waiting permissions, and their task-queue slots, open forever.
452
- if (this.cancelSession) {
453
- let timer;
454
- try {
455
- await Promise.race([
456
- Promise.resolve(this.cancelSession(sessionId)),
457
- new Promise((resolve) => {
458
- timer = setTimeout(() => {
459
- console.error(`[acp] session/cancel for ${sessionId} did not complete in ` +
460
- `${CANCEL_SESSION_TIMEOUT_MS}ms — settling permissions anyway`);
461
- resolve();
462
- }, CANCEL_SESSION_TIMEOUT_MS);
463
- }),
464
- ]);
465
- }
466
- finally {
467
- if (timer)
468
- clearTimeout(timer);
469
- }
470
- }
471
- }
472
- catch (err) {
473
- console.error(`[acp] Failed to cancel turn for session ${sessionId}:`, err);
474
- }
475
- finally {
476
- this.cancelPendingPermissions("task cancelled", sessionId);
477
- }
478
- }
479
- /**
480
- * Ends the turn: everything the agent produced besides its answer goes out
481
- * around the answer itself.
482
- *
483
- * The reasoning that led to the answer has to precede it, and the token and
484
- * cost counters read as a footer, so they follow.
485
- */
486
- async flushReply(sessionId) {
487
- await this.flushThought(sessionId);
488
- await this.deliverReply(sessionId);
489
- await this.flushUsage(sessionId);
490
- }
491
- /**
492
- * Queues whatever reasoning has accumulated for sending, and waits for the
493
- * telemetry queue to drain.
494
- *
495
- * Taking the buffer here rather than inside the queued send is what keeps a
496
- * reasoning block whole: anything the agent thinks after this point belongs
497
- * to the next block.
498
- */
499
- async flushThought(sessionId) {
500
- this.queueThoughtFlush(sessionId);
501
- await this.telemetryChain;
502
- }
503
- /**
504
- * Closes off the current reasoning block, if there is one.
505
- *
506
- * Called wherever the agent stops thinking and does something else — starts
507
- * answering, calls a tool, revises its plan — so a block of reasoning
508
- * reaches the human while it still explains what is about to happen, rather
509
- * than arriving in one lump at the end of the turn.
510
- */
511
- queueThoughtFlush(sessionId) {
512
- const thought = this.thoughtBuffers.get(sessionId);
513
- if (!thought?.trim())
514
- return;
515
- this.thoughtBuffers.delete(sessionId);
516
- this.queueTelemetry(() => this.sendTelemetry(sessionId, "thought", thought, {}));
517
- }
518
- /** Reports the last usage snapshot of the turn, if the agent sent any. */
519
- async flushUsage(sessionId) {
520
- const usage = this.latestUsage.get(sessionId);
521
- this.latestUsage.delete(sessionId);
522
- if (!usage)
523
- return;
524
- await this.sendTelemetry(sessionId, "usage", formatUsage(usage), usageTelemetryData(usage));
525
- }
526
- /** Reports a plan the agent has just published or revised. */
527
- queuePlan(sessionId, plan) {
528
- this.queueThoughtFlush(sessionId);
529
- this.queueTelemetry(() => this.sendTelemetry(sessionId, "plan", formatPlan(plan), planTelemetryData(plan)));
530
- }
531
- /** Adds a send to the tail of the telemetry queue. */
532
- queueTelemetry(send) {
533
- this.telemetryChain = this.telemetryChain
534
- .catch(() => { })
535
- .then(send)
536
- .catch((err) => {
537
- console.error(`[acp] Telemetry send failed:`, err);
538
- });
539
- }
540
- /**
541
- * Forwards one piece of telemetry to the workspace.
542
- *
543
- * Never throws: telemetry is not the answer, so a workspace that cannot take
544
- * it right now must not cost the agent its turn.
545
- */
546
- async sendTelemetry(sessionId, kind, text, data) {
547
- const taskId = this.getTaskIdForSession(sessionId);
548
- if (!taskId) {
549
- debug(`[acp] No task ID for session ${sessionId}, dropping ${kind} telemetry`);
550
- return;
551
- }
552
- const payload = {
553
- task_id: taskId,
554
- session_id: sessionId,
555
- kind,
556
- text,
557
- data,
558
- };
559
- try {
560
- await this.mcpBridge.sendNotification(TELEMETRY_NOTIFICATION_METHOD, payload);
561
- }
562
- catch (err) {
563
- console.error(`[acp] Failed to send ${kind} telemetry for session ${sessionId}:`, err);
564
- }
565
- }
566
- async deliverReply(sessionId) {
567
- const text = this.replyBuffers.get(sessionId) ?? "";
568
- this.replyBuffers.delete(sessionId);
569
- if (!text.trim())
570
- return;
571
- const taskId = this.getTaskIdForSession(sessionId);
572
- if (!taskId) {
573
- debug(`[acp] No task ID for session ${sessionId}, skipping reply`);
574
- return;
575
- }
576
- const agentReplyText = this.agentReplies.get(taskId);
577
- this.agentReplies.delete(taskId);
578
- if (agentReplyText !== undefined && agentReplyText === text) {
579
- debug(`[acp] Skipping reply to task ${taskId} — agent already sent identical reply`);
580
- return;
581
- }
582
- try {
583
- await callTaskAction(this.mcpBridge, "reply", { taskId, text });
584
- debug(`[acp] Forwarded agent reply to task ${taskId}`);
585
- }
586
- catch (err) {
587
- console.error(`[acp] Failed to forward reply to task ${taskId}:`, err);
588
- }
589
- }
590
- /**
591
- * Tells the workspace when a turn ended for any reason other than the agent
592
- * finishing what it was asked. Call after flushReply, so the note follows
593
- * whatever the agent did manage to say.
594
- */
595
- async reportStopReason(sessionId, stopReason) {
596
- if (stopReason === "end_turn")
597
- return;
598
- const taskId = this.getTaskIdForSession(sessionId);
599
- if (!taskId) {
600
- debug(`[acp] No task ID for session ${sessionId}, not reporting "${stopReason}"`);
601
- return;
602
- }
603
- const text = STOP_REASON_NOTES[stopReason] ??
604
- `⚠️ The agent stopped for a reason this gateway does not recognise: ${stopReason}.`;
605
- try {
606
- await callTaskAction(this.mcpBridge, "reply", { taskId, text });
607
- debug(`[acp] Reported stop reason "${stopReason}" to task ${taskId}`);
608
- }
609
- catch (err) {
610
- console.error(`[acp] Failed to report stop reason to task ${taskId}:`, err);
611
- }
612
- }
613
- async requestPermission(params) {
614
- const toolCallId = params.toolCall.toolCallId;
615
- // Fall back to what the earlier session update reported for this same tool
616
- // call: the permission request itself may carry no title or input.
617
- const remembered = this.toolCallDetails.get(toolCallId);
618
- this.toolCallDetails.delete(toolCallId);
619
- const toolTitle = params.toolCall.title ?? remembered?.title ?? "Unknown Tool";
620
- const rawInput = params.toolCall.rawInput ?? remembered?.rawInput;
621
- // Auto-allow the tool calls the workspace itself is serving.
622
- if (this.isWorkspaceToolCall(toolTitle)) {
623
- debug(`\n🔓 ACP Auto-allowing tool call: ${toolTitle} (ID: ${toolCallId})`);
624
- const option = params.options.find(o => o.kind.startsWith("allow") ||
625
- o.name.toLowerCase().includes("allow") ||
626
- o.name.toLowerCase().includes("yes") ||
627
- o.name.toLowerCase().includes("approve"));
628
- const optionId = option?.optionId ?? params.options[0].optionId;
629
- return {
630
- outcome: {
631
- outcome: "selected",
632
- optionId: optionId,
633
- },
634
- };
635
- }
636
- console.error(`\n🔐 ACP Permission requested: ${toolTitle} (ID: ${toolCallId})`);
637
- const sessionId = params.sessionId;
638
- // agentrq keys its own bookkeeping on the request id alone, across the whole
639
- // workspace. Tool call ids are only unique within a session, and agents
640
- // commonly number them from one, so two tasks running at once could
641
- // otherwise have a verdict land on the wrong tool call.
642
- const requestId = sessionId ? `${sessionId}:${toolCallId}` : toolCallId;
643
- const taskId = sessionId ? this.getTaskIdForSession(sessionId) : undefined;
644
- const payload = {
645
- request_id: requestId,
646
- task_id: taskId,
647
- tool_name: toolTitle,
648
- description: toolTitle,
649
- input_preview: JSON.stringify(rawInput ?? {}),
650
- };
651
- debug(`[acp] Bridge Session ID: ${this.mcpBridge.getSessionId() ?? "unknown"}`);
652
- debug(`[acp] Sending permission request notification:`, JSON.stringify(payload, null, 2));
653
- // 1. Forward the permission request to the MCP server as a notification.
654
- // If the MCP transport is down (e.g. network outage), sendNotification
655
- // rejects. Swallow it here so the rejection doesn't bubble up as an
656
- // unhandled promise rejection and crash the process — instead cancel
657
- // this permission request and let the transport reconnect in the
658
- // background. The agent receives a clean "cancelled" outcome.
659
- try {
660
- await this.mcpBridge.sendNotification("notifications/claude/channel/permission_request", payload);
661
- }
662
- catch (err) {
663
- console.error(`[acp] Failed to forward permission request ${requestId} (cancelling):`, err);
664
- return { outcome: { outcome: "cancelled" } };
665
- }
666
- // 2. Wait for the verdict from the MCP server — but not forever.
667
- console.error(`⌛ Waiting for human approval in the agentrq dashboard...`);
668
- return new Promise((resolve) => {
669
- const timer = this.permissionTimeoutMs > 0
670
- ? setTimeout(() => {
671
- console.error(`[acp] ⌛ No verdict for ${requestId} after ` +
672
- `${Math.round(this.permissionTimeoutMs / 60000)} min — cancelling the turn.`);
673
- // Cancel as well as answering: the spec treats `cancelled` as the
674
- // answer a client gives *because* it cancelled the turn. Answering
675
- // alone would leave the agent free to carry on and ask again.
676
- void this.cancelTurn(sessionId);
677
- settle({ outcome: "cancelled" });
678
- }, this.permissionTimeoutMs)
679
- : undefined;
680
- let settled = false;
681
- const settle = (outcome) => {
682
- if (settled)
683
- return;
684
- settled = true;
685
- if (timer)
686
- clearTimeout(timer);
687
- this.pendingPermissions.delete(requestId);
688
- debug(`[acp] Selected permission option: ${"optionId" in outcome ? outcome.optionId : "cancelled"}`);
689
- resolve({ outcome });
690
- };
691
- this.pendingPermissions.set(requestId, {
692
- payload,
693
- sessionId,
694
- options: params.options,
695
- settle,
696
- });
697
- });
698
- }
699
- /**
700
- * Turns a workspace verdict into one of the options the agent offered.
701
- *
702
- * A verdict from agentrq covers exactly one tool call. Never select a
703
- * "persistent" option (ACP's "allow_always"/"reject_always" kinds, or an
704
- * equivalent "remember"/"don't ask again" option by name) — picking one would
705
- * make the *spawned agent* remember the decision and stop sending
706
- * requestPermission for matching future tool calls, so those calls would
707
- * never reach agentrq again. Every subsequent call must still be forwarded
708
- * and re-approved there.
709
- */
710
- outcomeForVerdict(options, behavior) {
711
- const isPersistent = (o) => /always|remember|don'?t ask/i.test(o.kind) || /always|remember|don'?t ask/i.test(o.name);
712
- const onceOptions = options.filter(o => !isPersistent(o));
713
- // Map "allow"/"deny" to the correct ACP option. Per the ACP spec,
714
- // PermissionOptionKind is one of "allow_once" | "allow_always" |
715
- // "reject_once" | "reject_always" — there is no "deny_*" kind, so a
716
- // deny verdict must match on "reject" to find a spec-compliant option.
717
- const isAllow = behavior === "allow";
718
- const option = onceOptions.find(o => {
719
- const name = o.name.toLowerCase();
720
- return isAllow
721
- ? o.kind.startsWith("allow") || name.includes("allow") || name.includes("yes") || name.includes("approve")
722
- : o.kind.startsWith("reject") || name.includes("deny") || name.includes("reject") || name.includes("no");
723
- });
724
- if (option)
725
- return { outcome: "selected", optionId: option.optionId };
726
- // Falling back to onceOptions[0] unconditionally is unsafe for a deny
727
- // verdict: ACP conventionally lists allow options first, so an unmatched
728
- // deny could silently resolve to an allow option and approve a tool call
729
- // the human explicitly denied. Only ever fall back to a non-persistent
730
- // option that is not itself an allow-kind; if no safe option exists at all
731
- // (e.g. only "always" options were offered), cancel instead of guessing.
732
- if (isAllow) {
733
- return onceOptions[0]
734
- ? { outcome: "selected", optionId: onceOptions[0].optionId }
735
- : { outcome: "cancelled" };
736
- }
737
- const safeFallback = onceOptions.find(o => !o.kind.startsWith("allow"));
738
- return safeFallback
739
- ? { outcome: "selected", optionId: safeFallback.optionId }
740
- : { outcome: "cancelled" };
741
- }
742
- /**
743
- * Whether a tool call is one the workspace itself is serving.
744
- *
745
- * These need no human approval — the workspace is where the approval would
746
- * be asked, and a call it is serving is already the human's own bookkeeping
747
- * (reporting a reply, moving a task on, reading or writing the workspace's
748
- * memory). Forwarding them would ask the human to approve the very act of
749
- * being asked.
750
- */
751
- isWorkspaceToolCall(title) {
752
- if (AGENTRQ_TOOL_PATTERN.test(title))
753
- return true;
754
- // A title that names its two halves outright is read as it is written.
755
- const call = mcpCallFromTitle(title);
756
- if (call)
757
- return this.isWorkspaceCall(call);
758
- // Otherwise it may be a bare `server_tool`, which only divides one way
759
- // that survives both checks — if it divides at all.
760
- return bareCallCandidates(title).some((candidate) => this.isWorkspaceCall(candidate));
761
- }
762
- /** Whether a server and tool, once separated, are this workspace's own. */
763
- isWorkspaceCall(call) {
764
- // The server has to be agentrq's — either the one this gateway is bridged
765
- // to, or any other agentrq-named one, since the workspace is free to
766
- // rename what it hands out.
767
- const isOurs = call.server.toLowerCase() === this.workspaceServer?.toLowerCase() ||
768
- AGENTRQ_SERVER.test(call.server);
769
- if (!isOurs)
770
- return false;
771
- // And the tool has to be one the workspace actually offers. Without this a
772
- // server named to look like agentrq's would have its whole surface
773
- // approved on the human's behalf.
774
- const advertised = this.mcpBridge.getAdvertisedTools?.() ?? KNOWN_WORKSPACE_TOOLS;
775
- return advertised.has(call.tool);
776
- }
777
- /**
778
- * Records what a tool call is, keyed by its id, so that a permission request
779
- * arriving without a title or input can still be identified. ACP requires a
780
- * title on the `tool_call` session update but leaves it optional on the
781
- * permission request for that same call — codex-acp sends the request bare,
782
- * which previously surfaced agentrq's own MCP calls to the human as
783
- * "Unknown Tool" instead of being auto-allowed.
784
- */
785
- rememberToolCall(update) {
786
- const id = update.toolCallId;
787
- if (!id)
788
- return;
789
- // A finished call will never ask for permission, so drop what we kept
790
- // rather than growing the map for the lifetime of the session.
791
- if (update.status === "completed" || update.status === "failed") {
792
- this.toolCallDetails.delete(id);
793
- return;
794
- }
795
- const previous = this.toolCallDetails.get(id);
796
- const title = update.title ?? previous?.title;
797
- const rawInput = update.rawInput ?? previous?.rawInput;
798
- if (title === undefined && rawInput === undefined)
799
- return;
800
- this.toolCallDetails.set(id, { title, rawInput });
801
- }
802
- async sessionUpdate(params) {
803
- const update = params.update;
804
- switch (update.sessionUpdate) {
805
- case "agent_message_chunk":
806
- if (update.content.type === "text") {
807
- // The agent has stopped thinking and started answering.
808
- this.queueThoughtFlush(params.sessionId);
809
- if (isVerbose())
810
- process.stdout.write(update.content.text);
811
- const sid = params.sessionId;
812
- this.replyBuffers.set(sid, (this.replyBuffers.get(sid) ?? "") + update.content.text);
813
- }
814
- break;
815
- case "agent_thought_chunk":
816
- if (update.content.type === "text") {
817
- const sid = params.sessionId;
818
- this.thoughtBuffers.set(sid, (this.thoughtBuffers.get(sid) ?? "") + update.content.text);
819
- }
820
- break;
821
- case "plan":
822
- this.queuePlan(params.sessionId, planFromEntries(update.entries));
823
- break;
824
- case "plan_update":
825
- this.queuePlan(params.sessionId, update.plan);
826
- break;
827
- case "plan_removed":
828
- this.queueThoughtFlush(params.sessionId);
829
- this.queueTelemetry(() => this.sendTelemetry(params.sessionId, "plan", "Plan withdrawn.", {
830
- planId: update.planId,
831
- removed: true,
832
- }));
833
- break;
834
- case "usage_update":
835
- // Each snapshot supersedes the last; only the final one is reported,
836
- // at the end of the turn.
837
- this.latestUsage.set(params.sessionId, update);
838
- break;
839
- case "current_mode_update":
840
- debug(`[acp] Agent switched session mode to "${update.currentModeId}"`);
841
- await this.onModeChanged?.(params.sessionId, update.currentModeId);
842
- break;
843
- case "config_option_update":
844
- this.handleConfigOptionUpdate(params.sessionId, update.configOptions);
845
- break;
846
- case "available_commands_update":
847
- await this.sendCommandsToWorkspace(params.sessionId, normalizeCommands(update.availableCommands));
848
- break;
849
- case "tool_call_update":
850
- this.rememberToolCall(update);
851
- break;
852
- case "tool_call": {
853
- // Reasoning that explains a tool call belongs in front of it.
854
- this.queueThoughtFlush(params.sessionId);
855
- this.rememberToolCall(update);
856
- if (update.title && this.isWorkspaceToolCall(update.title)) {
857
- // Track completed reply calls so flushReply can skip exact duplicates
858
- if (update.status === "completed") {
859
- const reply = agentReplyFromCall(update.title, update.rawInput);
860
- if (reply)
861
- this.agentReplies.set(reply.taskId, reply.text);
862
- }
863
- break;
864
- }
865
- debug(`\n🔧 [ACP Agent] Tool call: ${update.title} (${update.status})`);
866
- break;
867
- }
868
- default:
869
- break;
870
- }
871
- }
872
- /** What was last reported for a session, for putting back after a failed set. */
873
- lastModelsFor(sessionId) {
874
- return lastModelsForSession(sessionId);
875
- }
876
- handleConfigOptionUpdate(sessionId, configOptions) {
877
- try {
878
- const modelsResult = extractModels(configOptions);
879
- if (!modelsResult)
880
- return;
881
- void this.sendModelsToWorkspace(sessionId, modelsResult);
882
- }
883
- catch (err) {
884
- console.error(`[acp] Failed to process config_option_update for session ${sessionId}:`, err);
885
- }
886
- }
887
- async sendModelsToWorkspace(sessionId, modelsResult) {
888
- await sendModelsNotification(this.mcpBridge, sessionId, modelsResult, this.getTaskIdForSession(sessionId));
889
- }
890
- /**
891
- * Tells the workspace which slash commands the agent is currently offering.
892
- *
893
- * An empty list is sent rather than skipped: it is how an agent withdraws its
894
- * commands, and a workspace that only ever hears about additions would go on
895
- * offering a menu of commands the agent has stopped accepting.
896
- *
897
- * Never throws, for the same reason telemetry does not — the commands are a
898
- * convenience for the human, and a workspace that cannot take them right now
899
- * must not cost the agent its turn.
900
- */
901
- async sendCommandsToWorkspace(sessionId, commands) {
902
- // No task required, for the reason sendModelsToWorkspace records.
903
- const payload = {
904
- task_id: this.getTaskIdForSession(sessionId) ?? "",
905
- session_id: sessionId,
906
- commands,
907
- };
908
- try {
909
- await this.mcpBridge.sendNotification(COMMANDS_NOTIFICATION_METHOD, payload);
910
- debug(`[acp] Shared ${commands.length} slash command(s) with workspace`);
911
- }
912
- catch (err) {
913
- console.error(`[acp] Failed to send commands notification for session ${sessionId}:`, err);
914
- }
915
- }
916
- /**
917
- * Tells the workspace which agent is behind this gateway.
918
- *
919
- * Without it the workspace can only name its MCP client, which for anything
920
- * reached through here is "acp-gateway" — the bridge rather than the agent.
921
- * The agent said who it was during its own handshake; this passes that on,
922
- * replacing whatever the gateway guessed from how it was launched.
923
- *
924
- * Sent once per session, since an agent cannot become a different agent
925
- * mid-session.
926
- */
927
- async sendAgentToWorkspace(sessionId, identity) {
928
- await sendAgentIdentity(this.mcpBridge, identity, {
929
- taskId: this.getTaskIdForSession(sessionId),
930
- sessionId,
931
- });
932
- }
933
- /**
934
- * Handles the agent's elicitation/create requests by delegating to
935
- * AgentRQ's `elicit` MCP tool, which blocks in the chat until the human
936
- * answers (or times out). AgentRQ's tool already waits for the human to
937
- * confirm in url mode too — collapsing ACP's "accept now, complete
938
- * later" url flow into a single round trip — so the response here already
939
- * reflects completion; see completeElicitation below.
940
- */
941
- async createElicitation(params) {
942
- const sessionId = "sessionId" in params ? params.sessionId : undefined;
943
- let taskId = sessionId ? this.getTaskIdForSession(sessionId) : undefined;
944
- // Logged before anything is routed anywhere, and whatever happens next:
945
- // wherever the question ends up being answered, the URL is the one thing
946
- // the human needs and the one thing nothing else prints.
947
- if (params.mode === "url") {
948
- const { url } = params;
949
- console.error(formatUrlElicitation(params.message, url));
950
- // A url elicitation with no task behind it is a login the human asked
951
- // for at this terminal — `--login` reaches here before any session
952
- // exists. Ask them where they are standing, rather than opening a task
953
- // in a workspace panel they are not watching and timing out.
954
- if (!taskId && this.promptUrlElicitation) {
955
- return await this.askUrlOnTerminal(params);
956
- }
957
- }
958
- if (!taskId) {
959
- // Request-scoped elicitations (e.g. during an auth/config phase before
960
- // any session exists) have no task to attach to, but the workspace's elicit action
961
- // requires one — create one for the human to answer instead of
962
- // cancelling outright.
963
- taskId = await this.createTaskForElicitation(params.message);
964
- if (!taskId) {
965
- console.error(`[acp] Elicitation request has no associated task and task creation failed, cancelling`);
966
- return { action: "cancel" };
967
- }
968
- }
969
- const toolArgs = {
970
- taskId,
971
- message: params.message,
972
- mode: params.mode,
973
- };
974
- if (params.mode === "form") {
975
- toolArgs.requestedSchema = params.requestedSchema;
976
- }
977
- else if (params.mode === "url") {
978
- toolArgs.url = params.url;
979
- }
980
- else {
981
- console.error(`[acp] Unsupported elicitation mode "${params.mode}", cancelling`);
982
- return { action: "cancel" };
983
- }
984
- console.error(`[acp] Elicitation requested (mode=${params.mode}): ${params.message}`);
985
- try {
986
- const result = await callTaskAction(this.mcpBridge, "elicit", toolArgs);
987
- const contentBlock = result.content;
988
- const text = contentBlock?.[0]?.text;
989
- if (!text) {
990
- console.error(`[acp] Elicit tool returned no content, cancelling`);
991
- return { action: "cancel" };
992
- }
993
- if (result.isError) {
994
- console.error(`[acp] Elicit tool call failed: ${text}`);
995
- return { action: "cancel" };
996
- }
997
- const parsed = JSON.parse(text);
998
- if (parsed.action === "accept") {
999
- return { action: "accept", content: parsed.content };
1000
- }
1001
- if (parsed.action === "decline") {
1002
- return { action: "decline" };
1003
- }
1004
- return { action: "cancel" };
1005
- }
1006
- catch (err) {
1007
- console.error(`[acp] Failed to process elicitation request:`, err);
1008
- return { action: "cancel" };
1009
- }
1010
- }
1011
- /**
1012
- * Creates a new AgentRQ task for a session-less elicitation and marks it
1013
- * ongoing, so the elicit call has somewhere to post the question and
1014
- * the human sees it show up as an active task rather than a stray message.
1015
- * Returns the new task's base62 ID, or undefined if creation failed.
1016
- */
1017
- async createTaskForElicitation(message) {
1018
- try {
1019
- const created = await callTaskAction(this.mcpBridge, "create", {
1020
- title: message.length > 80 ? `${message.slice(0, 77)}...` : message,
1021
- body: message,
1022
- assignee: "human",
1023
- });
1024
- const text = created.content?.[0]?.text;
1025
- const taskId = text?.match(/id=(\S+)/)?.[1];
1026
- if (!taskId) {
1027
- console.error(`[acp] Could not parse task ID from createTask response: ${text ?? "<empty>"}`);
1028
- return undefined;
1029
- }
1030
- await callTaskAction(this.mcpBridge, "updateStatus", { taskId, status: "ongoing" });
1031
- return taskId;
1032
- }
1033
- catch (err) {
1034
- console.error(`[acp] Failed to create task for elicitation:`, err);
1035
- return undefined;
1036
- }
1037
- }
1038
- /**
1039
- * Called when the agent reports a url-mode elicitation as complete.
1040
- * AgentRQ's elicit action already blocks until the human confirms, so our
1041
- * createElicitation response has already reflected completion by the time
1042
- * this notification (if any) arrives — matching the spec's requirement
1043
- * that clients ignore completion notices for elicitations they don't
1044
- * still consider pending.
1045
- */
1046
- async completeElicitation(params) {
1047
- const waiting = this.pendingUrlElicitations.get(params.elicitationId);
1048
- if (!waiting)
1049
- return;
1050
- console.error(`[auth] The agent reports this login as finished.`);
1051
- waiting.abort();
1052
- }
1053
- /**
1054
- * Puts a url-mode elicitation to the human at this terminal.
1055
- *
1056
- * Registered by `elicitationId` for the length of the wait so that
1057
- * completeElicitation can close the prompt: the agent may resolve the login
1058
- * by itself — codex-acp races the browser against our answer — and without
1059
- * this the human would be left staring at a prompt nobody reads.
1060
- */
1061
- async askUrlOnTerminal(params) {
1062
- const controller = new AbortController();
1063
- const id = params.elicitationId;
1064
- if (id)
1065
- this.pendingUrlElicitations.set(id, controller);
1066
- try {
1067
- return await this.promptUrlElicitation({
1068
- message: params.message,
1069
- url: params.url,
1070
- signal: controller.signal,
1071
- });
1072
- }
1073
- catch (err) {
1074
- console.error(`[auth] Could not ask about the login at this terminal:`, err);
1075
- return { action: "cancel" };
1076
- }
1077
- finally {
1078
- if (id)
1079
- this.pendingUrlElicitations.delete(id);
1080
- }
1081
- }
1082
- async writeTextFile(params) {
1083
- const filePath = path.resolve(process.cwd(), params.path);
1084
- debug(`[acp] Writing file: ${params.path}`);
1085
- try {
1086
- await fs.mkdir(path.dirname(filePath), { recursive: true });
1087
- await fs.writeFile(filePath, params.content, "utf8");
1088
- debug(`[acp] File written successfully: ${params.path}`);
1089
- return {};
1090
- }
1091
- catch (err) {
1092
- console.error(`[acp] Error writing file ${params.path}:`, err.message);
1093
- throw err;
1094
- }
1095
- }
1096
- async readTextFile(params) {
1097
- const filePath = path.resolve(process.cwd(), params.path);
1098
- const window = params.line != null || params.limit != null
1099
- ? ` (from line ${params.line ?? 1}${params.limit != null ? `, ${params.limit} lines` : ""})`
1100
- : "";
1101
- debug(`[acp] Reading file: ${params.path}${window}`);
1102
- try {
1103
- const content = await fs.readFile(filePath, "utf8");
1104
- return { content: sliceLines(content, params.line, params.limit) };
1105
- }
1106
- catch (err) {
1107
- console.error(`[acp] Error reading file ${params.path}:`, err.message);
1108
- throw err;
1109
- }
1110
- }
1111
- }
1112
- //# sourceMappingURL=acpClient.js.map