@moxt-ai/mobius 0.0.128 → 0.0.130

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 (36) hide show
  1. package/dist/acp/activity-content.d.ts +29 -0
  2. package/dist/acp/activity-content.d.ts.map +1 -0
  3. package/dist/acp/activity-content.js +301 -0
  4. package/dist/acp/activity-content.js.map +1 -0
  5. package/dist/acp/activity.d.ts +3 -9
  6. package/dist/acp/activity.d.ts.map +1 -1
  7. package/dist/acp/activity.js +2 -300
  8. package/dist/acp/activity.js.map +1 -1
  9. package/dist/acp/agent-session.d.ts +0 -4
  10. package/dist/acp/agent-session.d.ts.map +1 -1
  11. package/dist/acp/agent-session.js +6 -37
  12. package/dist/acp/agent-session.js.map +1 -1
  13. package/dist/acp/{session-state.d.ts → agent-turn.d.ts} +5 -22
  14. package/dist/acp/agent-turn.d.ts.map +1 -0
  15. package/dist/acp/agent-turn.js +51 -0
  16. package/dist/acp/agent-turn.js.map +1 -0
  17. package/dist/acp/pending-interactions.d.ts +22 -0
  18. package/dist/acp/pending-interactions.d.ts.map +1 -0
  19. package/dist/acp/{session-state.js → pending-interactions.js} +1 -23
  20. package/dist/acp/pending-interactions.js.map +1 -0
  21. package/dist/acp/session-history.d.ts.map +1 -1
  22. package/dist/acp/session-history.js +2 -1
  23. package/dist/acp/session-history.js.map +1 -1
  24. package/dist/acp/session-interactions.d.ts.map +1 -1
  25. package/dist/acp/session-interactions.js +1 -1
  26. package/dist/acp/session-interactions.js.map +1 -1
  27. package/dist/cli.js +312 -312
  28. package/dist/cli.js.map +4 -4
  29. package/dist/daemon-turn-registry.d.ts +13 -13
  30. package/dist/index.js +398 -398
  31. package/dist/index.js.map +4 -4
  32. package/dist/runtime.js +384 -384
  33. package/dist/runtime.js.map +4 -4
  34. package/package.json +1 -1
  35. package/dist/acp/session-state.d.ts.map +0 -1
  36. package/dist/acp/session-state.js.map +0 -1
package/dist/index.js CHANGED
@@ -22781,73 +22781,11 @@ async function replaceImageMarkers(text2, replace) {
22781
22781
  return `${rewritten}${text2.slice(cursor)}`;
22782
22782
  }
22783
22783
 
22784
- // src/acp/activity.ts
22784
+ // src/acp/activity-content.ts
22785
22785
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
22786
- var AcpActivityNarration = class {
22787
- activityId;
22788
- activityType;
22789
- sequence;
22790
- text;
22791
- constructor(activityId, activityType, sequence, text2) {
22792
- this.activityId = activityId;
22793
- this.activityType = activityType;
22794
- this.sequence = sequence;
22795
- this.text = text2;
22796
- }
22797
- };
22798
22786
  function isRecord3(value) {
22799
22787
  return typeof value === "object" && value !== null && !Array.isArray(value);
22800
22788
  }
22801
- var AcpActivity = class _AcpActivity {
22802
- activityId;
22803
- activityType;
22804
- input;
22805
- locations;
22806
- name;
22807
- output;
22808
- sequence;
22809
- status;
22810
- title;
22811
- toolKind;
22812
- content;
22813
- detail;
22814
- constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(content, input2, output2)) {
22815
- this.activityId = activityId;
22816
- this.activityType = activityType;
22817
- this.input = input2;
22818
- this.locations = locations;
22819
- this.name = name;
22820
- this.output = output2;
22821
- this.sequence = sequence;
22822
- this.status = status;
22823
- this.title = title2;
22824
- this.toolKind = toolKind;
22825
- this.content = content;
22826
- this.detail = detail;
22827
- }
22828
- complete = () => (this.activityType === "progress" || this.activityType === "reasoning") && (this.status === "pending" || this.status === "running") ? new _AcpActivity(
22829
- this.activityId,
22830
- this.activityType,
22831
- this.input,
22832
- this.locations,
22833
- this.name,
22834
- this.output,
22835
- this.sequence,
22836
- "completed",
22837
- this.title,
22838
- this.toolKind,
22839
- this.content,
22840
- this.detail
22841
- ) : this;
22842
- };
22843
- var ActivityIdentity = class {
22844
- id;
22845
- sequence;
22846
- constructor(id, sequence) {
22847
- this.id = id;
22848
- this.sequence = sequence;
22849
- }
22850
- };
22851
22789
  function truncate(value, maximumLength) {
22852
22790
  if (value.length <= maximumLength) {
22853
22791
  return value;
@@ -23124,6 +23062,282 @@ function contentPhase(content) {
23124
23062
  function isProgressMessage(content) {
23125
23063
  return contentPhase(content) === "commentary";
23126
23064
  }
23065
+
23066
+ // src/acp/agent-connection.ts
23067
+ import { spawn as spawn2 } from "node:child_process";
23068
+ import { ndJsonStream, RequestError } from "@agentclientprotocol/sdk";
23069
+
23070
+ // src/acp/in-process/acp-endpoint.ts
23071
+ function acpEndpointTerminationError(termination) {
23072
+ switch (termination.kind) {
23073
+ case "failed":
23074
+ return termination.error;
23075
+ case "closed":
23076
+ return new AcpExecutionError("The ACP endpoint is closed", {}, "acp_endpoint_closed");
23077
+ default: {
23078
+ const unreachable2 = termination;
23079
+ return unreachable2;
23080
+ }
23081
+ }
23082
+ }
23083
+
23084
+ // src/acp/value-utils.ts
23085
+ function truncate2(value, maximumLength) {
23086
+ return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
23087
+ }
23088
+ function isRecord4(value) {
23089
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23090
+ }
23091
+ function readString2(value, fallback = "") {
23092
+ return typeof value === "string" ? value : fallback;
23093
+ }
23094
+
23095
+ // src/acp/agent-connection.ts
23096
+ function readableWebStream(input2) {
23097
+ let streamOpen = true;
23098
+ return new ReadableStream({
23099
+ start(controller) {
23100
+ input2.on("data", (chunk) => {
23101
+ if (!streamOpen) {
23102
+ return;
23103
+ }
23104
+ if (chunk instanceof Uint8Array) {
23105
+ controller.enqueue(new Uint8Array(chunk));
23106
+ return;
23107
+ }
23108
+ streamOpen = false;
23109
+ controller.error(new Error("ACP process produced a non-binary chunk"));
23110
+ });
23111
+ input2.once("end", () => {
23112
+ if (!streamOpen) {
23113
+ return;
23114
+ }
23115
+ streamOpen = false;
23116
+ controller.close();
23117
+ });
23118
+ input2.once("error", (error62) => {
23119
+ if (!streamOpen) {
23120
+ return;
23121
+ }
23122
+ streamOpen = false;
23123
+ controller.error(error62);
23124
+ });
23125
+ },
23126
+ cancel() {
23127
+ streamOpen = false;
23128
+ }
23129
+ });
23130
+ }
23131
+ function createWritableAcpStream(output2) {
23132
+ let outputFailure;
23133
+ const pendingWriteFailures = /* @__PURE__ */ new Set();
23134
+ const fail = (error62) => {
23135
+ outputFailure = error62;
23136
+ for (const reject of pendingWriteFailures) {
23137
+ reject(error62);
23138
+ }
23139
+ pendingWriteFailures.clear();
23140
+ };
23141
+ output2.on("error", fail);
23142
+ output2.once("close", () => {
23143
+ if (outputFailure === void 0) {
23144
+ fail(new Error("ACP process input closed"));
23145
+ }
23146
+ });
23147
+ return new WritableStream({
23148
+ write(chunk) {
23149
+ if (outputFailure !== void 0) {
23150
+ return Promise.reject(outputFailure);
23151
+ }
23152
+ return new Promise((resolve9, reject) => {
23153
+ pendingWriteFailures.add(reject);
23154
+ output2.write(chunk, (error62) => {
23155
+ pendingWriteFailures.delete(reject);
23156
+ if (error62) {
23157
+ outputFailure = error62;
23158
+ reject(error62);
23159
+ return;
23160
+ }
23161
+ if (outputFailure !== void 0) {
23162
+ reject(outputFailure);
23163
+ return;
23164
+ }
23165
+ resolve9();
23166
+ });
23167
+ });
23168
+ }
23169
+ });
23170
+ }
23171
+ var AgentConnection = class {
23172
+ connection;
23173
+ termination;
23174
+ #process;
23175
+ constructor(agent, cwd, client2) {
23176
+ if (agent.kind === "in-process-acp") {
23177
+ const inProcess = agent.createEndpoint({
23178
+ command: agent.command,
23179
+ cwd,
23180
+ environment: agent.environment
23181
+ });
23182
+ this.#process = { kind: "in-process", endpoint: inProcess };
23183
+ this.termination = inProcess.terminated;
23184
+ this.connection = createAcpClient(client2).connect(inProcess.app());
23185
+ return;
23186
+ }
23187
+ const child = spawn2(agent.adapterPath, [...agent.arguments], {
23188
+ cwd,
23189
+ detached: process.platform !== "win32",
23190
+ env: { ...process.env, ...agent.environment },
23191
+ shell: false,
23192
+ stdio: ["pipe", "pipe", "pipe"]
23193
+ });
23194
+ this.#process = { kind: "child", child };
23195
+ const stdin = child.stdin;
23196
+ const stdout = child.stdout;
23197
+ const stderr = child.stderr;
23198
+ if (stdin === null || stdout === null || stderr === null) {
23199
+ child.kill("SIGKILL");
23200
+ throw new AcpExecutionError("ACP process streams are unavailable");
23201
+ }
23202
+ stderr.setEncoding("utf8");
23203
+ stderr.on("data", (chunk) => {
23204
+ process.stderr.write(`[${agent.id}-acp] ${chunk}`);
23205
+ });
23206
+ this.termination = new Promise((resolve9) => {
23207
+ child.once("error", (cause) => {
23208
+ resolve9({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
23209
+ });
23210
+ child.once("exit", (code, signal) => {
23211
+ resolve9({
23212
+ kind: "failed",
23213
+ error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } })
23214
+ });
23215
+ });
23216
+ });
23217
+ const stream = ndJsonStream(createWritableAcpStream(stdin), readableWebStream(stdout));
23218
+ this.connection = createAcpClient(client2).connect(stream);
23219
+ }
23220
+ get inProcessAgent() {
23221
+ return this.#process.kind === "in-process" ? this.#process.endpoint : null;
23222
+ }
23223
+ captureProcessTree = async () => this.#process.kind === "child" ? await captureProcessTree(this.#process.child) : [];
23224
+ closeProcess = async (capturedProcesses = []) => {
23225
+ try {
23226
+ if (this.#process.kind === "in-process") {
23227
+ await this.#process.endpoint.close();
23228
+ return;
23229
+ }
23230
+ await stopProcessTree(this.#process.child, capturedProcesses);
23231
+ } finally {
23232
+ this.connection.close();
23233
+ }
23234
+ };
23235
+ race = async (operation, exitMessage, signal) => {
23236
+ signal.throwIfAborted();
23237
+ let removeAbortListener = () => {
23238
+ };
23239
+ const aborted2 = new Promise((_resolve, reject) => {
23240
+ const rejectAbort = () => {
23241
+ reject(signal.reason ?? new Error("ACP request was cancelled"));
23242
+ };
23243
+ signal.addEventListener("abort", rejectAbort, { once: true });
23244
+ removeAbortListener = () => {
23245
+ signal.removeEventListener("abort", rejectAbort);
23246
+ };
23247
+ });
23248
+ try {
23249
+ try {
23250
+ return await Promise.race([
23251
+ operation,
23252
+ this.termination.then((termination) => {
23253
+ const cause = acpEndpointTerminationError(termination);
23254
+ throw new AcpExecutionError(exitMessage, { cause }, cause.code);
23255
+ }),
23256
+ aborted2
23257
+ ]);
23258
+ } catch (error62) {
23259
+ signal.throwIfAborted();
23260
+ if (error62 instanceof RequestError && error62.code === -32e3) {
23261
+ throw new AcpExecutionError(
23262
+ "Agent authentication is required",
23263
+ { cause: error62 },
23264
+ "authentication_required"
23265
+ );
23266
+ }
23267
+ if (error62 instanceof RequestError) {
23268
+ throw new AcpExecutionError(truncate2(error62.message, 500), { cause: error62 }, "acp_agent_error");
23269
+ }
23270
+ throw error62;
23271
+ }
23272
+ } finally {
23273
+ removeAbortListener();
23274
+ }
23275
+ };
23276
+ };
23277
+
23278
+ // src/acp/activity.ts
23279
+ var AcpActivityNarration = class {
23280
+ activityId;
23281
+ activityType;
23282
+ sequence;
23283
+ text;
23284
+ constructor(activityId, activityType, sequence, text2) {
23285
+ this.activityId = activityId;
23286
+ this.activityType = activityType;
23287
+ this.sequence = sequence;
23288
+ this.text = text2;
23289
+ }
23290
+ };
23291
+ var AcpActivity = class _AcpActivity {
23292
+ activityId;
23293
+ activityType;
23294
+ input;
23295
+ locations;
23296
+ name;
23297
+ output;
23298
+ sequence;
23299
+ status;
23300
+ title;
23301
+ toolKind;
23302
+ content;
23303
+ detail;
23304
+ constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(content, input2, output2)) {
23305
+ this.activityId = activityId;
23306
+ this.activityType = activityType;
23307
+ this.input = input2;
23308
+ this.locations = locations;
23309
+ this.name = name;
23310
+ this.output = output2;
23311
+ this.sequence = sequence;
23312
+ this.status = status;
23313
+ this.title = title2;
23314
+ this.toolKind = toolKind;
23315
+ this.content = content;
23316
+ this.detail = detail;
23317
+ }
23318
+ complete = () => (this.activityType === "progress" || this.activityType === "reasoning") && (this.status === "pending" || this.status === "running") ? new _AcpActivity(
23319
+ this.activityId,
23320
+ this.activityType,
23321
+ this.input,
23322
+ this.locations,
23323
+ this.name,
23324
+ this.output,
23325
+ this.sequence,
23326
+ "completed",
23327
+ this.title,
23328
+ this.toolKind,
23329
+ this.content,
23330
+ this.detail
23331
+ ) : this;
23332
+ };
23333
+ var ActivityIdentity = class {
23334
+ id;
23335
+ sequence;
23336
+ constructor(id, sequence) {
23337
+ this.id = id;
23338
+ this.sequence = sequence;
23339
+ }
23340
+ };
23127
23341
  var AcpActivityTracker = class {
23128
23342
  #activities = /* @__PURE__ */ new Map();
23129
23343
  #identities = /* @__PURE__ */ new Map();
@@ -23300,293 +23514,134 @@ var AcpActivityTracker = class {
23300
23514
  await this.finishNarrative();
23301
23515
  for (const key of this.#narrations.keys()) {
23302
23516
  await this.#completeNarrative(key);
23303
- }
23304
- const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
23305
- for (const [key, activity2] of entries) {
23306
- const completed = activity2.complete();
23307
- if (completed !== activity2) {
23308
- await this.#record(key, completed);
23309
- }
23310
- }
23311
- };
23312
- // Materialize a streamed narration as one completed snapshot activity. The
23313
- // incremental events carried the text; this final event gives consumers the
23314
- // whole narration with its terminal status, as a single bounded item.
23315
- #completeNarrative = async (key) => {
23316
- const narration = this.#narrations.get(key);
23317
- if (narration === void 0) {
23318
- return;
23319
- }
23320
- this.#narrations.delete(key);
23321
- const previous = this.#activities.get(key);
23322
- const detail = narration.truncated ? {
23323
- capturedBytes: encodedByteLength({ content: [], input: "", output: narration.output }),
23324
- kind: "truncated",
23325
- originalBytes: narration.originalBytes
23326
- } : captureActivityDetail([], "", narration.output);
23327
- await this.#record(
23328
- key,
23329
- new AcpActivity(
23330
- narration.activityId,
23331
- narration.activityType,
23332
- "",
23333
- [],
23334
- "",
23335
- truncate(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
23336
- narration.sequence,
23337
- "completed",
23338
- narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
23339
- narration.activityType === "reasoning" ? "think" : "",
23340
- previous?.content ?? [],
23341
- detail
23342
- )
23343
- );
23344
- };
23345
- #identity = (key) => {
23346
- const existing = this.#identities.get(key);
23347
- if (existing !== void 0) {
23348
- return existing;
23349
- }
23350
- const identity2 = new ActivityIdentity(`activity-${crypto.randomUUID()}`, this.#nextSequence);
23351
- this.#nextSequence += 1;
23352
- this.#identities.set(key, identity2);
23353
- return identity2;
23354
- };
23355
- #record = async (key, activity2) => {
23356
- this.#activities.set(key, activity2);
23357
- await this.#onActivity(activity2);
23358
- };
23359
- #recordPlanEntries = async (key, entries) => {
23360
- const identity2 = this.#identity(key);
23361
- await this.#record(
23362
- key,
23363
- new AcpActivity(
23364
- identity2.id,
23365
- "plan",
23366
- "",
23367
- [],
23368
- "",
23369
- formatPlanEntries(entries),
23370
- identity2.sequence,
23371
- planStatus(entries),
23372
- "Plan",
23373
- ""
23374
- )
23375
- );
23376
- };
23377
- };
23378
-
23379
- // src/acp/agent-connection.ts
23380
- import { spawn as spawn2 } from "node:child_process";
23381
- import { ndJsonStream, RequestError } from "@agentclientprotocol/sdk";
23382
-
23383
- // src/acp/in-process/acp-endpoint.ts
23384
- function acpEndpointTerminationError(termination) {
23385
- switch (termination.kind) {
23386
- case "failed":
23387
- return termination.error;
23388
- case "closed":
23389
- return new AcpExecutionError("The ACP endpoint is closed", {}, "acp_endpoint_closed");
23390
- default: {
23391
- const unreachable2 = termination;
23392
- return unreachable2;
23393
- }
23394
- }
23395
- }
23396
-
23397
- // src/acp/value-utils.ts
23398
- function truncate2(value, maximumLength) {
23399
- return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
23400
- }
23401
- function isRecord4(value) {
23402
- return typeof value === "object" && value !== null && !Array.isArray(value);
23403
- }
23404
- function readString2(value, fallback = "") {
23405
- return typeof value === "string" ? value : fallback;
23406
- }
23407
-
23408
- // src/acp/agent-connection.ts
23409
- function readableWebStream(input2) {
23410
- let streamOpen = true;
23411
- return new ReadableStream({
23412
- start(controller) {
23413
- input2.on("data", (chunk) => {
23414
- if (!streamOpen) {
23415
- return;
23416
- }
23417
- if (chunk instanceof Uint8Array) {
23418
- controller.enqueue(new Uint8Array(chunk));
23419
- return;
23420
- }
23421
- streamOpen = false;
23422
- controller.error(new Error("ACP process produced a non-binary chunk"));
23423
- });
23424
- input2.once("end", () => {
23425
- if (!streamOpen) {
23426
- return;
23427
- }
23428
- streamOpen = false;
23429
- controller.close();
23430
- });
23431
- input2.once("error", (error62) => {
23432
- if (!streamOpen) {
23433
- return;
23434
- }
23435
- streamOpen = false;
23436
- controller.error(error62);
23437
- });
23438
- },
23439
- cancel() {
23440
- streamOpen = false;
23441
- }
23442
- });
23443
- }
23444
- function createWritableAcpStream(output2) {
23445
- let outputFailure;
23446
- const pendingWriteFailures = /* @__PURE__ */ new Set();
23447
- const fail = (error62) => {
23448
- outputFailure = error62;
23449
- for (const reject of pendingWriteFailures) {
23450
- reject(error62);
23451
- }
23452
- pendingWriteFailures.clear();
23453
- };
23454
- output2.on("error", fail);
23455
- output2.once("close", () => {
23456
- if (outputFailure === void 0) {
23457
- fail(new Error("ACP process input closed"));
23458
- }
23459
- });
23460
- return new WritableStream({
23461
- write(chunk) {
23462
- if (outputFailure !== void 0) {
23463
- return Promise.reject(outputFailure);
23517
+ }
23518
+ const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
23519
+ for (const [key, activity2] of entries) {
23520
+ const completed = activity2.complete();
23521
+ if (completed !== activity2) {
23522
+ await this.#record(key, completed);
23464
23523
  }
23465
- return new Promise((resolve9, reject) => {
23466
- pendingWriteFailures.add(reject);
23467
- output2.write(chunk, (error62) => {
23468
- pendingWriteFailures.delete(reject);
23469
- if (error62) {
23470
- outputFailure = error62;
23471
- reject(error62);
23472
- return;
23473
- }
23474
- if (outputFailure !== void 0) {
23475
- reject(outputFailure);
23476
- return;
23477
- }
23478
- resolve9();
23479
- });
23480
- });
23481
23524
  }
23482
- });
23483
- }
23484
- var AgentConnection = class {
23485
- connection;
23486
- termination;
23487
- #process;
23488
- constructor(agent, cwd, client2) {
23489
- if (agent.kind === "in-process-acp") {
23490
- const inProcess = agent.createEndpoint({
23491
- command: agent.command,
23492
- cwd,
23493
- environment: agent.environment
23494
- });
23495
- this.#process = { kind: "in-process", endpoint: inProcess };
23496
- this.termination = inProcess.terminated;
23497
- this.connection = createAcpClient(client2).connect(inProcess.app());
23525
+ };
23526
+ // Materialize a streamed narration as one completed snapshot activity. The
23527
+ // incremental events carried the text; this final event gives consumers the
23528
+ // whole narration with its terminal status, as a single bounded item.
23529
+ #completeNarrative = async (key) => {
23530
+ const narration = this.#narrations.get(key);
23531
+ if (narration === void 0) {
23498
23532
  return;
23499
23533
  }
23500
- const child = spawn2(agent.adapterPath, [...agent.arguments], {
23501
- cwd,
23502
- detached: process.platform !== "win32",
23503
- env: { ...process.env, ...agent.environment },
23504
- shell: false,
23505
- stdio: ["pipe", "pipe", "pipe"]
23506
- });
23507
- this.#process = { kind: "child", child };
23508
- const stdin = child.stdin;
23509
- const stdout = child.stdout;
23510
- const stderr = child.stderr;
23511
- if (stdin === null || stdout === null || stderr === null) {
23512
- child.kill("SIGKILL");
23513
- throw new AcpExecutionError("ACP process streams are unavailable");
23534
+ this.#narrations.delete(key);
23535
+ const previous = this.#activities.get(key);
23536
+ const detail = narration.truncated ? {
23537
+ capturedBytes: encodedByteLength({ content: [], input: "", output: narration.output }),
23538
+ kind: "truncated",
23539
+ originalBytes: narration.originalBytes
23540
+ } : captureActivityDetail([], "", narration.output);
23541
+ await this.#record(
23542
+ key,
23543
+ new AcpActivity(
23544
+ narration.activityId,
23545
+ narration.activityType,
23546
+ "",
23547
+ [],
23548
+ "",
23549
+ truncate(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
23550
+ narration.sequence,
23551
+ "completed",
23552
+ narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
23553
+ narration.activityType === "reasoning" ? "think" : "",
23554
+ previous?.content ?? [],
23555
+ detail
23556
+ )
23557
+ );
23558
+ };
23559
+ #identity = (key) => {
23560
+ const existing = this.#identities.get(key);
23561
+ if (existing !== void 0) {
23562
+ return existing;
23514
23563
  }
23515
- stderr.setEncoding("utf8");
23516
- stderr.on("data", (chunk) => {
23517
- process.stderr.write(`[${agent.id}-acp] ${chunk}`);
23518
- });
23519
- this.termination = new Promise((resolve9) => {
23520
- child.once("error", (cause) => {
23521
- resolve9({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
23522
- });
23523
- child.once("exit", (code, signal) => {
23524
- resolve9({
23525
- kind: "failed",
23526
- error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } })
23527
- });
23528
- });
23529
- });
23530
- const stream = ndJsonStream(createWritableAcpStream(stdin), readableWebStream(stdout));
23531
- this.connection = createAcpClient(client2).connect(stream);
23532
- }
23533
- get inProcessAgent() {
23534
- return this.#process.kind === "in-process" ? this.#process.endpoint : null;
23535
- }
23536
- captureProcessTree = async () => this.#process.kind === "child" ? await captureProcessTree(this.#process.child) : [];
23537
- closeProcess = async (capturedProcesses = []) => {
23538
- try {
23539
- if (this.#process.kind === "in-process") {
23540
- await this.#process.endpoint.close();
23541
- return;
23564
+ const identity2 = new ActivityIdentity(`activity-${crypto.randomUUID()}`, this.#nextSequence);
23565
+ this.#nextSequence += 1;
23566
+ this.#identities.set(key, identity2);
23567
+ return identity2;
23568
+ };
23569
+ #record = async (key, activity2) => {
23570
+ this.#activities.set(key, activity2);
23571
+ await this.#onActivity(activity2);
23572
+ };
23573
+ #recordPlanEntries = async (key, entries) => {
23574
+ const identity2 = this.#identity(key);
23575
+ await this.#record(
23576
+ key,
23577
+ new AcpActivity(
23578
+ identity2.id,
23579
+ "plan",
23580
+ "",
23581
+ [],
23582
+ "",
23583
+ formatPlanEntries(entries),
23584
+ identity2.sequence,
23585
+ planStatus(entries),
23586
+ "Plan",
23587
+ ""
23588
+ )
23589
+ );
23590
+ };
23591
+ };
23592
+
23593
+ // src/acp/agent-turn.ts
23594
+ var SESSION_CONTROL_COMMAND_ID = "session-control";
23595
+ var AcpTurnState = class {
23596
+ #bufferedText = [];
23597
+ bufferText = (text2, messageId) => {
23598
+ const previous = this.#bufferedText.at(-1);
23599
+ if (previous?.messageId === messageId) {
23600
+ previous.chunks.push(text2);
23601
+ } else {
23602
+ this.#bufferedText.push({ chunks: [text2], messageId });
23603
+ }
23604
+ };
23605
+ flushText = async () => {
23606
+ const buffered = this.#bufferedText;
23607
+ this.#bufferedText = [];
23608
+ for (const message of buffered) {
23609
+ for (const chunk of message.chunks) {
23610
+ await this.onText(chunk, message.messageId);
23542
23611
  }
23543
- await stopProcessTree(this.#process.child, capturedProcesses);
23544
- } finally {
23545
- this.connection.close();
23546
23612
  }
23547
23613
  };
23548
- race = async (operation, exitMessage, signal) => {
23549
- signal.throwIfAborted();
23550
- let removeAbortListener = () => {
23551
- };
23552
- const aborted2 = new Promise((_resolve, reject) => {
23553
- const rejectAbort = () => {
23554
- reject(signal.reason ?? new Error("ACP request was cancelled"));
23555
- };
23556
- signal.addEventListener("abort", rejectAbort, { once: true });
23557
- removeAbortListener = () => {
23558
- signal.removeEventListener("abort", rejectAbort);
23559
- };
23560
- });
23561
- try {
23562
- try {
23563
- return await Promise.race([
23564
- operation,
23565
- this.termination.then((termination) => {
23566
- const cause = acpEndpointTerminationError(termination);
23567
- throw new AcpExecutionError(exitMessage, { cause }, cause.code);
23568
- }),
23569
- aborted2
23570
- ]);
23571
- } catch (error62) {
23572
- signal.throwIfAborted();
23573
- if (error62 instanceof RequestError && error62.code === -32e3) {
23574
- throw new AcpExecutionError(
23575
- "Agent authentication is required",
23576
- { cause: error62 },
23577
- "authentication_required"
23578
- );
23579
- }
23580
- if (error62 instanceof RequestError) {
23581
- throw new AcpExecutionError(truncate2(error62.message, 500), { cause: error62 }, "acp_agent_error");
23582
- }
23583
- throw error62;
23614
+ recordTextAsProgress = async () => {
23615
+ const buffered = this.#bufferedText;
23616
+ this.#bufferedText = [];
23617
+ for (const message of buffered) {
23618
+ for (const chunk of message.chunks) {
23619
+ await this.activities.recordNarrative("progress", message.messageId, chunk);
23584
23620
  }
23585
- } finally {
23586
- removeAbortListener();
23587
23621
  }
23588
23622
  };
23589
23623
  };
23624
+ var IdleAcpTurn = class extends AcpTurnState {
23625
+ commandId = SESSION_CONTROL_COMMAND_ID;
23626
+ running = false;
23627
+ activities = new AcpActivityTracker(
23628
+ () => Promise.resolve(),
23629
+ () => Promise.resolve()
23630
+ );
23631
+ onText = () => Promise.resolve();
23632
+ };
23633
+ var RunningAcpTurn = class extends AcpTurnState {
23634
+ commandId;
23635
+ running = true;
23636
+ activities;
23637
+ onText;
23638
+ constructor(commandId, onActivity, onNarration, onText, prepareContent) {
23639
+ super();
23640
+ this.commandId = commandId;
23641
+ this.activities = new AcpActivityTracker(onActivity, onNarration ?? (() => Promise.resolve()), prepareContent);
23642
+ this.onText = onText;
23643
+ }
23644
+ };
23590
23645
 
23591
23646
  // src/acp/native-session.ts
23592
23647
  var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
@@ -24343,31 +24398,7 @@ function validateElicitationContent(encoded, requestedSchema) {
24343
24398
  return validated;
24344
24399
  }
24345
24400
 
24346
- // src/acp/session-state.ts
24347
- var SESSION_CONTROL_COMMAND_ID = "session-control";
24348
- var AcpTurnState = class {
24349
- };
24350
- var IdleAcpTurn = class extends AcpTurnState {
24351
- commandId = SESSION_CONTROL_COMMAND_ID;
24352
- running = false;
24353
- activities = new AcpActivityTracker(
24354
- () => Promise.resolve(),
24355
- () => Promise.resolve()
24356
- );
24357
- onText = () => Promise.resolve();
24358
- };
24359
- var RunningAcpTurn = class extends AcpTurnState {
24360
- commandId;
24361
- running = true;
24362
- activities;
24363
- onText;
24364
- constructor(commandId, onActivity, onNarration, onText, prepareContent) {
24365
- super();
24366
- this.commandId = commandId;
24367
- this.activities = new AcpActivityTracker(onActivity, onNarration ?? (() => Promise.resolve()), prepareContent);
24368
- this.onText = onText;
24369
- }
24370
- };
24401
+ // src/acp/pending-interactions.ts
24371
24402
  var PendingPermission = class {
24372
24403
  completion = Promise.withResolvers();
24373
24404
  interactionId;
@@ -30318,7 +30349,6 @@ var AgentSession = class _AgentSession {
30318
30349
  #verifiedAgentVersion;
30319
30350
  #agentName = "";
30320
30351
  #agentVersion = "";
30321
- #bufferedAgentText = [];
30322
30352
  #capabilities = unsupportedSessionCapabilities();
30323
30353
  #commands = [];
30324
30354
  #configRevision = 0;
@@ -30464,35 +30494,6 @@ var AgentSession = class _AgentSession {
30464
30494
  this.#replay = { kind: "idle" };
30465
30495
  }
30466
30496
  };
30467
- emitAgentMessage = async (chunks, messageId) => {
30468
- for (const chunk of chunks) {
30469
- await this.#turn.onText(chunk, messageId);
30470
- }
30471
- };
30472
- bufferAgentText = async (text2, messageId) => {
30473
- const previous = this.#bufferedAgentText.at(-1);
30474
- if (previous?.messageId === messageId) {
30475
- previous.chunks.push(text2);
30476
- return;
30477
- }
30478
- this.#bufferedAgentText.push({ chunks: [text2], messageId });
30479
- };
30480
- flushAgentText = async () => {
30481
- const buffered = this.#bufferedAgentText;
30482
- this.#bufferedAgentText = [];
30483
- for (const message of buffered) {
30484
- await this.emitAgentMessage(message.chunks, message.messageId);
30485
- }
30486
- };
30487
- recordBufferedAgentTextAsProgress = async () => {
30488
- const buffered = this.#bufferedAgentText;
30489
- this.#bufferedAgentText = [];
30490
- for (const message of buffered) {
30491
- for (const chunk of message.chunks) {
30492
- await this.#turn.activities.recordNarrative("progress", message.messageId, chunk);
30493
- }
30494
- }
30495
- };
30496
30497
  prepareAgentContent = async (content) => {
30497
30498
  if (content.type === "image" && content.uri.length > 0) {
30498
30499
  const signal = AbortSignal.timeout(2e4);
@@ -30990,7 +30991,7 @@ var AgentSession = class _AgentSession {
30990
30991
  options.signal
30991
30992
  );
30992
30993
  await this.#updates.drained();
30993
- await this.flushAgentText();
30994
+ await this.#turn.flushText();
30994
30995
  await running.activities.finish();
30995
30996
  let result;
30996
30997
  try {
@@ -31022,7 +31023,6 @@ var AgentSession = class _AgentSession {
31022
31023
  cause: error62
31023
31024
  });
31024
31025
  } finally {
31025
- this.#bufferedAgentText = [];
31026
31026
  this.#turn = new IdleAcpTurn();
31027
31027
  }
31028
31028
  };
@@ -31113,11 +31113,11 @@ var AgentSession = class _AgentSession {
31113
31113
  );
31114
31114
  } else {
31115
31115
  await this.#turn.activities.finishNarrative();
31116
- await this.bufferAgentText(update.content.text, truncate2(update.messageId ?? "", 255));
31116
+ this.#turn.bufferText(update.content.text, truncate2(update.messageId ?? "", 255));
31117
31117
  }
31118
31118
  } else {
31119
31119
  await this.#turn.activities.finishNarrative();
31120
- await this.flushAgentText();
31120
+ await this.#turn.flushText();
31121
31121
  await this.emitAgentContent(
31122
31122
  normalizeContentBlock(update.content),
31123
31123
  truncate2(update.messageId ?? "", 255)
@@ -31136,7 +31136,7 @@ var AgentSession = class _AgentSession {
31136
31136
  return;
31137
31137
  }
31138
31138
  if (update.sessionUpdate === "tool_call") {
31139
- await this.recordBufferedAgentTextAsProgress();
31139
+ await this.#turn.recordTextAsProgress();
31140
31140
  await this.#turn.activities.recordToolCall(update);
31141
31141
  return;
31142
31142
  }