@moxt-ai/mobius 0.0.128 → 0.0.129

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.
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,791 +23062,855 @@ function contentPhase(content) {
23124
23062
  function isProgressMessage(content) {
23125
23063
  return contentPhase(content) === "commentary";
23126
23064
  }
23127
- var AcpActivityTracker = class {
23128
- #activities = /* @__PURE__ */ new Map();
23129
- #identities = /* @__PURE__ */ new Map();
23130
- #narrations = /* @__PURE__ */ new Map();
23131
- #onActivity;
23132
- #onNarration;
23133
- #prepareContent;
23134
- #activeNarrativeKey = "";
23135
- #nextSequence = 0;
23136
- constructor(onActivity, onNarration, prepareContent = (content) => Promise.resolve(content)) {
23137
- this.#onActivity = onActivity;
23138
- this.#onNarration = onNarration;
23139
- this.#prepareContent = prepareContent;
23140
- }
23141
- recordNarrative = async (activityType, messageId, text2) => {
23142
- const key = `${activityType}:${messageId}`;
23143
- if (this.#activeNarrativeKey !== key) {
23144
- await this.finishNarrative();
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;
23145
23080
  }
23146
- const identity2 = this.#identity(key);
23147
- const previous = this.#narrations.get(key);
23148
- const previousOutput = previous?.output ?? "";
23149
- const remaining = Math.max(0, AGENT_ACTIVITY_DETAIL_LIMIT - previousOutput.length);
23150
- this.#narrations.set(key, {
23151
- activityId: identity2.id,
23152
- activityType,
23153
- output: `${previousOutput}${text2.slice(0, remaining)}`,
23154
- originalBytes: (previous?.originalBytes ?? 0) + new TextEncoder().encode(text2).byteLength,
23155
- sequence: identity2.sequence,
23156
- truncated: (previous?.truncated ?? false) || text2.length > remaining
23157
- });
23158
- if (previous === void 0) {
23159
- await this.#record(key, this.#narrativeSnapshot(identity2, activityType, "", "running"));
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;
23160
23128
  }
23161
- this.#activeNarrativeKey = key;
23162
- if (text2.length > 0) {
23163
- await this.#onNarration(new AcpActivityNarration(identity2.id, activityType, identity2.sequence, text2));
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);
23164
23138
  }
23139
+ pendingWriteFailures.clear();
23165
23140
  };
23166
- #narrativeSnapshot = (identity2, activityType, output2, status) => new AcpActivity(
23167
- identity2.id,
23168
- activityType,
23169
- "",
23170
- [],
23171
- "",
23172
- truncate(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
23173
- identity2.sequence,
23174
- status,
23175
- activityType === "reasoning" ? "Reasoning" : "Progress update",
23176
- activityType === "reasoning" ? "think" : ""
23177
- );
23178
- recordPlan = async (plan) => {
23179
- await this.finishNarrative();
23180
- await this.#recordPlanEntries("plan:default", plan.entries);
23181
- };
23182
- recordPlanUpdate = async (update) => {
23183
- await this.finishNarrative();
23184
- const plan = update.plan;
23185
- const key = `plan:${plan.planId}`;
23186
- if (plan.type === "items") {
23187
- await this.#recordPlanEntries(key, plan.entries);
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());
23188
23185
  return;
23189
23186
  }
23190
- const identity2 = this.#identity(key);
23191
- const output2 = plan.type === "markdown" ? plan.content : `Plan file: ${plan.uri}`;
23192
- await this.#record(
23193
- key,
23194
- new AcpActivity(
23195
- identity2.id,
23196
- "plan",
23197
- "",
23198
- [],
23199
- "",
23200
- truncate(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
23201
- identity2.sequence,
23202
- "running",
23203
- "Plan",
23204
- ""
23205
- )
23206
- );
23207
- };
23208
- removePlan = async (update) => {
23209
- await this.finishNarrative();
23210
- const key = `plan:${update.planId}`;
23211
- const previous = this.#activities.get(key);
23212
- if (previous !== void 0) {
23213
- await this.#record(
23214
- key,
23215
- new AcpActivity(
23216
- previous.activityId,
23217
- previous.activityType,
23218
- previous.input,
23219
- previous.locations,
23220
- previous.name,
23221
- previous.output,
23222
- previous.sequence,
23223
- "completed",
23224
- previous.title,
23225
- previous.toolKind,
23226
- previous.content,
23227
- previous.detail
23228
- )
23229
- );
23230
- }
23231
- };
23232
- recordToolCall = async (update) => {
23233
- await this.finishNarrative();
23234
- const key = `tool:${update.toolCallId}`;
23235
- const identity2 = this.#identity(key);
23236
- const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
23237
- const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
23238
- const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
23239
- const detailContent = await normalizeToolContent(
23240
- toolContent(update.content, update.rawOutput),
23241
- this.#prepareContent
23242
- );
23243
- await this.#record(
23244
- key,
23245
- new AcpActivity(
23246
- identity2.id,
23247
- "tool",
23248
- update.rawInput === void 0 ? "" : formatUnknown(update.rawInput),
23249
- normalizeLocations(update.locations ?? []),
23250
- truncate(update.name ?? "", 128),
23251
- output2,
23252
- identity2.sequence,
23253
- normalizeToolStatus(update.status ?? "pending", "pending"),
23254
- normalizeTitle(update.title, "Tool call"),
23255
- update.kind ?? "other",
23256
- detailContent.slice(0, 100).map(summarizeDisplayContent),
23257
- captureActivityDetail(detailContent, detailInput, detailOutput)
23258
- )
23259
- );
23260
- };
23261
- recordToolCallUpdate = async (update) => {
23262
- await this.finishNarrative();
23263
- const key = `tool:${update.toolCallId}`;
23264
- const previous = this.#activities.get(key);
23265
- const identity2 = this.#identity(key);
23266
- const previousDetail = recordedDetail(previous);
23267
- const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous?.output ?? "";
23268
- const nextContent = toolContent(update.content, update.rawOutput);
23269
- const content = nextContent.length === 0 ? previous?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
23270
- const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous?.input ?? "" : formatUnknownDetail(update.rawInput);
23271
- const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous?.output ?? "";
23272
- const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous?.content ?? [] : content;
23273
- await this.#record(
23274
- key,
23275
- new AcpActivity(
23276
- identity2.id,
23277
- "tool",
23278
- update.rawInput === void 0 ? previous?.input ?? "" : formatUnknown(update.rawInput),
23279
- update.locations === void 0 || update.locations === null ? previous?.locations ?? [] : normalizeLocations(update.locations),
23280
- update.name === void 0 || update.name === null ? previous?.name ?? "" : truncate(update.name, 128),
23281
- output2,
23282
- identity2.sequence,
23283
- update.status === void 0 || update.status === null ? previous?.status ?? "pending" : normalizeToolStatus(update.status, previous?.status ?? "pending"),
23284
- update.title === void 0 || update.title === null ? previous?.title ?? "Tool call" : normalizeTitle(update.title, "Tool call"),
23285
- update.kind === void 0 || update.kind === null ? previous?.toolKind ?? "other" : update.kind,
23286
- content.slice(0, 100).map(summarizeDisplayContent),
23287
- captureActivityDetail(detailContent, detailInput, detailOutput)
23288
- )
23289
- );
23290
- };
23291
- finishNarrative = async () => {
23292
- const key = this.#activeNarrativeKey;
23293
- if (key.length === 0) {
23294
- return;
23295
- }
23296
- this.#activeNarrativeKey = "";
23297
- await this.#completeNarrative(key);
23298
- };
23299
- finish = async () => {
23300
- await this.finishNarrative();
23301
- for (const key of this.#narrations.keys()) {
23302
- await this.#completeNarrative(key);
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");
23303
23201
  }
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);
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;
23309
23229
  }
23230
+ await stopProcessTree(this.#process.child, capturedProcesses);
23231
+ } finally {
23232
+ this.connection.close();
23310
23233
  }
23311
23234
  };
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;
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();
23349
23274
  }
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
23275
  };
23377
23276
  };
23378
23277
 
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
- }
23278
+ // src/acp/native-session.ts
23279
+ var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
23280
+ var title = external_exports.string().transform((value) => value.slice(0, 500));
23281
+ var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
23282
+ var nativeSessionInfoSchema = external_exports.object({
23283
+ sessionId: nativeSessionIdSchema,
23284
+ cwd: path,
23285
+ additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
23286
+ title: title.nullish(),
23287
+ updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
23288
+ }).readonly();
23289
+ var nativeSessionPageSchema = external_exports.object({
23290
+ sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
23291
+ nextCursor: external_exports.string().min(1).max(4096).nullish()
23292
+ }).readonly();
23293
+
23294
+ // src/acp/agent-update-stream.ts
23295
+ var MAX_PENDING_UPDATES = 100;
23296
+ var MAX_PENDING_BYTES = 1024 * 1024;
23297
+ var AgentUpdateStream = class {
23298
+ #selection = { kind: "awaiting-session", notifications: [], bytes: 0 };
23299
+ #tail = Promise.resolve();
23300
+ #consume;
23301
+ constructor(consume) {
23302
+ this.#consume = consume;
23394
23303
  }
23395
- }
23304
+ sessionId = () => this.#selection.kind === "selected" ? this.#selection.sessionId : "";
23305
+ drained = () => this.#tail;
23306
+ #enqueue = (notification) => {
23307
+ this.#tail = this.#tail.then(async () => await this.#consume(notification));
23308
+ return this.#tail;
23309
+ };
23310
+ receive = (notification) => {
23311
+ const selection = this.#selection;
23312
+ switch (selection.kind) {
23313
+ case "selected":
23314
+ return this.#enqueue(notification);
23315
+ case "awaiting-session": {
23316
+ const bytes = selection.bytes + Buffer.byteLength(JSON.stringify(notification));
23317
+ if (selection.notifications.length >= MAX_PENDING_UPDATES || bytes > MAX_PENDING_BYTES) {
23318
+ return Promise.reject(
23319
+ new AcpExecutionError(
23320
+ "ACP agent sent too many updates before creating its session",
23321
+ {},
23322
+ "agent_update_limit"
23323
+ )
23324
+ );
23325
+ }
23326
+ this.#selection = {
23327
+ kind: "awaiting-session",
23328
+ notifications: [...selection.notifications, notification],
23329
+ bytes
23330
+ };
23331
+ return Promise.resolve();
23332
+ }
23333
+ }
23334
+ };
23335
+ select = (sessionId) => {
23336
+ const selected = nativeSessionIdSchema.parse(sessionId);
23337
+ const selection = this.#selection;
23338
+ switch (selection.kind) {
23339
+ case "selected":
23340
+ if (selection.sessionId !== selected) {
23341
+ throw new AcpExecutionError(
23342
+ "ACP agent attempted to replace the selected session",
23343
+ {},
23344
+ "invalid_agent_session"
23345
+ );
23346
+ }
23347
+ return;
23348
+ case "awaiting-session":
23349
+ this.#selection = { kind: "selected", sessionId: selected };
23350
+ for (const notification of selection.notifications) {
23351
+ void this.#enqueue(notification);
23352
+ }
23353
+ return;
23354
+ }
23355
+ };
23356
+ };
23396
23357
 
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) {
23358
+ // src/acp/session-config/session-config-protocol.ts
23359
+ import { methods as methods2 } from "@agentclientprotocol/sdk";
23360
+ var MAXIMUM_CONFIG_OPTIONS = 100;
23361
+ var SessionConfigProtocolError = class extends Error {
23362
+ code = "invalid_session_configuration_response";
23363
+ constructor(message, options = {}) {
23364
+ super(message, options);
23365
+ this.name = "SessionConfigProtocolError";
23366
+ }
23367
+ };
23368
+ function isRecord5(value) {
23402
23369
  return typeof value === "object" && value !== null && !Array.isArray(value);
23403
23370
  }
23404
- function readString2(value, fallback = "") {
23371
+ function readString3(value, fallback = "") {
23405
23372
  return typeof value === "string" ? value : fallback;
23406
23373
  }
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;
23374
+ function truncate3(value, maximum) {
23375
+ return value.length <= maximum ? value : value.slice(0, maximum);
23376
+ }
23377
+ function readBoolean(value, fallback = false) {
23378
+ return typeof value === "boolean" ? value : fallback;
23379
+ }
23380
+ function normalizeConfigValue(option, groupId = "", groupName = "") {
23381
+ const value = option["value"];
23382
+ if (typeof value !== "string") {
23383
+ return void 0;
23384
+ }
23385
+ return {
23386
+ description: truncate3(readString3(option["description"]), 500),
23387
+ groupId: truncate3(groupId, 128),
23388
+ groupName: truncate3(groupName, 255),
23389
+ name: truncate3(readString3(option["name"], value), 255),
23390
+ value: truncate3(value, 500)
23391
+ };
23392
+ }
23393
+ function normalizeConfigValues(value) {
23394
+ if (!Array.isArray(value)) {
23395
+ return [];
23396
+ }
23397
+ const normalized = [];
23398
+ for (const entry of value) {
23399
+ if (!isRecord5(entry)) {
23400
+ continue;
23401
+ }
23402
+ const groupedOptions = entry["options"];
23403
+ if (Array.isArray(groupedOptions)) {
23404
+ const groupId = readString3(entry["group"]);
23405
+ const groupName = readString3(entry["name"]);
23406
+ for (const groupedOption of groupedOptions) {
23407
+ if (isRecord5(groupedOption)) {
23408
+ const normalizedValue = normalizeConfigValue(groupedOption, groupId, groupName);
23409
+ if (normalizedValue !== void 0) {
23410
+ normalized.push(normalizedValue);
23411
+ }
23416
23412
  }
23417
- if (chunk instanceof Uint8Array) {
23418
- controller.enqueue(new Uint8Array(chunk));
23419
- return;
23413
+ }
23414
+ continue;
23415
+ }
23416
+ const normalizedEntry = normalizeConfigValue(entry);
23417
+ if (normalizedEntry !== void 0) {
23418
+ normalized.push(normalizedEntry);
23419
+ }
23420
+ }
23421
+ return normalized.slice(0, 500);
23422
+ }
23423
+ function normalizeConfigOptions(value, modes) {
23424
+ const normalized = [];
23425
+ if (Array.isArray(value)) {
23426
+ for (const option of value) {
23427
+ if (!isRecord5(option)) {
23428
+ continue;
23429
+ }
23430
+ const id = truncate3(readString3(option["id"]), 128);
23431
+ const name = truncate3(readString3(option["name"], id), 255);
23432
+ const category = truncate3(readString3(option["category"]), 128);
23433
+ if (id.length === 0 || name.length === 0 || category === "_mobius_permission") {
23434
+ continue;
23435
+ }
23436
+ if (option["type"] === "boolean") {
23437
+ normalized.push({
23438
+ booleanValue: readBoolean(option["currentValue"]),
23439
+ category,
23440
+ currentValue: "",
23441
+ description: truncate3(readString3(option["description"]), 500),
23442
+ id,
23443
+ name,
23444
+ type: "boolean",
23445
+ values: []
23446
+ });
23447
+ continue;
23448
+ }
23449
+ if (option["type"] === "select") {
23450
+ const values = normalizeConfigValues(option["options"]);
23451
+ const currentValue = truncate3(readString3(option["currentValue"]), 500);
23452
+ if (values.some((entry) => entry.value === currentValue)) {
23453
+ normalized.push({
23454
+ booleanValue: false,
23455
+ category,
23456
+ currentValue,
23457
+ description: truncate3(readString3(option["description"]), 500),
23458
+ id,
23459
+ name,
23460
+ type: "select",
23461
+ values
23462
+ });
23420
23463
  }
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;
23464
+ }
23465
+ }
23466
+ }
23467
+ if (isRecord5(modes)) {
23468
+ const values = [];
23469
+ const availableModes = modes["availableModes"];
23470
+ if (Array.isArray(availableModes)) {
23471
+ for (const mode of availableModes) {
23472
+ if (!isRecord5(mode)) {
23473
+ continue;
23427
23474
  }
23428
- streamOpen = false;
23429
- controller.close();
23430
- });
23431
- input2.once("error", (error62) => {
23432
- if (!streamOpen) {
23433
- return;
23475
+ const id = truncate3(readString3(mode["id"]), 500);
23476
+ if (id.length === 0) {
23477
+ continue;
23434
23478
  }
23435
- streamOpen = false;
23436
- controller.error(error62);
23479
+ values.push({
23480
+ description: truncate3(readString3(mode["description"]), 500),
23481
+ groupId: "",
23482
+ groupName: "",
23483
+ name: truncate3(readString3(mode["name"], id), 255),
23484
+ value: id
23485
+ });
23486
+ }
23487
+ }
23488
+ const currentValue = truncate3(readString3(modes["currentModeId"]), 500);
23489
+ if (currentValue.length > 0 && values.some((entry) => entry.value === currentValue) && !normalized.some((entry) => entry.category === "mode")) {
23490
+ normalized.unshift({
23491
+ booleanValue: false,
23492
+ category: "mode",
23493
+ currentValue,
23494
+ description: "Agent session mode",
23495
+ id: "mode",
23496
+ name: "Mode",
23497
+ type: "select",
23498
+ values
23437
23499
  });
23438
- },
23439
- cancel() {
23440
- streamOpen = false;
23441
23500
  }
23442
- });
23501
+ }
23502
+ return normalized.slice(0, MAXIMUM_CONFIG_OPTIONS);
23443
23503
  }
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);
23504
+ function normalizeStandardLifecycle(response) {
23505
+ const lifecycle = isRecord5(response) ? response : {};
23506
+ return normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]);
23507
+ }
23508
+ function replaceStandardConfigOptions(current, value) {
23509
+ const next = normalizeConfigOptions(value, void 0);
23510
+ const withMode = next.some((option) => option.category === "mode") ? next : [...current.filter((option) => option.category === "mode"), ...next].slice(0, MAXIMUM_CONFIG_OPTIONS);
23511
+ return withMode;
23512
+ }
23513
+ function updateCurrentValue(current, configId, value) {
23514
+ return current.map((option) => option.id === configId ? { ...option, currentValue: value } : option);
23515
+ }
23516
+ var StandardSessionConfigProtocol = class {
23517
+ configure = async (current, change, nativeSessionId, transport) => {
23518
+ const existing = current.find((option) => option.id === change.configId);
23519
+ if (existing === void 0) {
23520
+ return current;
23451
23521
  }
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"));
23522
+ if (existing.type === "select" && existing.category === "mode") {
23523
+ await transport.request(
23524
+ methods2.agent.session.setMode,
23525
+ { modeId: change.value, sessionId: nativeSessionId },
23526
+ "ACP agent exited while setting the session mode",
23527
+ change.signal
23528
+ );
23529
+ return updateCurrentValue(current, existing.id, change.value);
23458
23530
  }
23459
- });
23460
- return new WritableStream({
23461
- write(chunk) {
23462
- if (outputFailure !== void 0) {
23463
- return Promise.reject(outputFailure);
23464
- }
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
- });
23531
+ const params = existing.type === "boolean" ? {
23532
+ configId: existing.id,
23533
+ sessionId: nativeSessionId,
23534
+ type: "boolean",
23535
+ value: change.booleanValue
23536
+ } : {
23537
+ configId: existing.id,
23538
+ sessionId: nativeSessionId,
23539
+ value: change.value
23540
+ };
23541
+ const response = await transport.request(
23542
+ methods2.agent.session.setConfigOption,
23543
+ params,
23544
+ "ACP agent exited while changing session configuration",
23545
+ change.signal
23546
+ );
23547
+ if (!isRecord5(response) || !Array.isArray(response["configOptions"])) {
23548
+ throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
23481
23549
  }
23482
- });
23550
+ return replaceStandardConfigOptions(current, response["configOptions"]);
23551
+ };
23552
+ normalizeLifecycle = (response) => normalizeStandardLifecycle(response);
23553
+ normalizeUpdate = (current, value) => replaceStandardConfigOptions(current, value);
23554
+ };
23555
+ var standardSessionConfigProtocol = new StandardSessionConfigProtocol();
23556
+
23557
+ // src/acp/session-config/session-config-registry.ts
23558
+ function sessionConfigProtocolForAgent(_agentId) {
23559
+ return standardSessionConfigProtocol;
23483
23560
  }
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());
23498
- return;
23499
- }
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");
23514
- }
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);
23561
+
23562
+ // src/acp/session-contracts.ts
23563
+ var NullAcpSessionObserver = class {
23564
+ onCommands = () => Promise.resolve();
23565
+ onConfig = () => Promise.resolve();
23566
+ onContent = () => Promise.resolve();
23567
+ onElicitation = () => Promise.resolve();
23568
+ onElicitationResolved = () => Promise.resolve();
23569
+ onInfo = () => Promise.resolve();
23570
+ onPermission = () => Promise.resolve();
23571
+ onPermissionResolved = () => Promise.resolve();
23572
+ onUsage = () => Promise.resolve();
23573
+ };
23574
+ var AcpPreparedSession = class {
23575
+ agentName;
23576
+ agentVersion;
23577
+ capabilities;
23578
+ commands;
23579
+ configOptions;
23580
+ restored;
23581
+ constructor(agentName, agentVersion, capabilities, commands, configOptions, restored) {
23582
+ this.agentName = agentName;
23583
+ this.agentVersion = agentVersion;
23584
+ this.capabilities = capabilities;
23585
+ this.commands = commands;
23586
+ this.configOptions = configOptions;
23587
+ this.restored = restored;
23532
23588
  }
23533
- get inProcessAgent() {
23534
- return this.#process.kind === "in-process" ? this.#process.endpoint : null;
23589
+ };
23590
+ var AcpAgentSettingsSnapshot = class {
23591
+ agentName;
23592
+ agentVersion;
23593
+ configOptions;
23594
+ constructor(agentName, agentVersion, configOptions) {
23595
+ this.agentName = agentName;
23596
+ this.agentVersion = agentVersion;
23597
+ this.configOptions = configOptions;
23535
23598
  }
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;
23542
- }
23543
- await stopProcessTree(this.#process.child, capturedProcesses);
23544
- } finally {
23545
- this.connection.close();
23599
+ };
23600
+
23601
+ // src/acp/activity.ts
23602
+ var AcpActivityNarration = class {
23603
+ activityId;
23604
+ activityType;
23605
+ sequence;
23606
+ text;
23607
+ constructor(activityId, activityType, sequence, text2) {
23608
+ this.activityId = activityId;
23609
+ this.activityType = activityType;
23610
+ this.sequence = sequence;
23611
+ this.text = text2;
23612
+ }
23613
+ };
23614
+ var AcpActivity = class _AcpActivity {
23615
+ activityId;
23616
+ activityType;
23617
+ input;
23618
+ locations;
23619
+ name;
23620
+ output;
23621
+ sequence;
23622
+ status;
23623
+ title;
23624
+ toolKind;
23625
+ content;
23626
+ detail;
23627
+ constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(content, input2, output2)) {
23628
+ this.activityId = activityId;
23629
+ this.activityType = activityType;
23630
+ this.input = input2;
23631
+ this.locations = locations;
23632
+ this.name = name;
23633
+ this.output = output2;
23634
+ this.sequence = sequence;
23635
+ this.status = status;
23636
+ this.title = title2;
23637
+ this.toolKind = toolKind;
23638
+ this.content = content;
23639
+ this.detail = detail;
23640
+ }
23641
+ complete = () => (this.activityType === "progress" || this.activityType === "reasoning") && (this.status === "pending" || this.status === "running") ? new _AcpActivity(
23642
+ this.activityId,
23643
+ this.activityType,
23644
+ this.input,
23645
+ this.locations,
23646
+ this.name,
23647
+ this.output,
23648
+ this.sequence,
23649
+ "completed",
23650
+ this.title,
23651
+ this.toolKind,
23652
+ this.content,
23653
+ this.detail
23654
+ ) : this;
23655
+ };
23656
+ var ActivityIdentity = class {
23657
+ id;
23658
+ sequence;
23659
+ constructor(id, sequence) {
23660
+ this.id = id;
23661
+ this.sequence = sequence;
23662
+ }
23663
+ };
23664
+ var AcpActivityTracker = class {
23665
+ #activities = /* @__PURE__ */ new Map();
23666
+ #identities = /* @__PURE__ */ new Map();
23667
+ #narrations = /* @__PURE__ */ new Map();
23668
+ #onActivity;
23669
+ #onNarration;
23670
+ #prepareContent;
23671
+ #activeNarrativeKey = "";
23672
+ #nextSequence = 0;
23673
+ constructor(onActivity, onNarration, prepareContent = (content) => Promise.resolve(content)) {
23674
+ this.#onActivity = onActivity;
23675
+ this.#onNarration = onNarration;
23676
+ this.#prepareContent = prepareContent;
23677
+ }
23678
+ recordNarrative = async (activityType, messageId, text2) => {
23679
+ const key = `${activityType}:${messageId}`;
23680
+ if (this.#activeNarrativeKey !== key) {
23681
+ await this.finishNarrative();
23546
23682
  }
23547
- };
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
- };
23683
+ const identity2 = this.#identity(key);
23684
+ const previous = this.#narrations.get(key);
23685
+ const previousOutput = previous?.output ?? "";
23686
+ const remaining = Math.max(0, AGENT_ACTIVITY_DETAIL_LIMIT - previousOutput.length);
23687
+ this.#narrations.set(key, {
23688
+ activityId: identity2.id,
23689
+ activityType,
23690
+ output: `${previousOutput}${text2.slice(0, remaining)}`,
23691
+ originalBytes: (previous?.originalBytes ?? 0) + new TextEncoder().encode(text2).byteLength,
23692
+ sequence: identity2.sequence,
23693
+ truncated: (previous?.truncated ?? false) || text2.length > remaining
23560
23694
  });
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;
23584
- }
23585
- } finally {
23586
- removeAbortListener();
23695
+ if (previous === void 0) {
23696
+ await this.#record(key, this.#narrativeSnapshot(identity2, activityType, "", "running"));
23697
+ }
23698
+ this.#activeNarrativeKey = key;
23699
+ if (text2.length > 0) {
23700
+ await this.#onNarration(new AcpActivityNarration(identity2.id, activityType, identity2.sequence, text2));
23587
23701
  }
23588
23702
  };
23589
- };
23590
-
23591
- // src/acp/native-session.ts
23592
- var path = external_exports.string().min(1).max(2048).refine((value) => !value.includes("\0"));
23593
- var title = external_exports.string().transform((value) => value.slice(0, 500));
23594
- var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
23595
- var nativeSessionInfoSchema = external_exports.object({
23596
- sessionId: nativeSessionIdSchema,
23597
- cwd: path,
23598
- additionalDirectories: external_exports.array(path).max(16).default([]).readonly(),
23599
- title: title.nullish(),
23600
- updatedAt: external_exports.iso.datetime({ offset: true }).nullish()
23601
- }).readonly();
23602
- var nativeSessionPageSchema = external_exports.object({
23603
- sessions: external_exports.array(nativeSessionInfoSchema).max(500).readonly(),
23604
- nextCursor: external_exports.string().min(1).max(4096).nullish()
23605
- }).readonly();
23606
-
23607
- // src/acp/agent-update-stream.ts
23608
- var MAX_PENDING_UPDATES = 100;
23609
- var MAX_PENDING_BYTES = 1024 * 1024;
23610
- var AgentUpdateStream = class {
23611
- #selection = { kind: "awaiting-session", notifications: [], bytes: 0 };
23612
- #tail = Promise.resolve();
23613
- #consume;
23614
- constructor(consume) {
23615
- this.#consume = consume;
23616
- }
23617
- sessionId = () => this.#selection.kind === "selected" ? this.#selection.sessionId : "";
23618
- drained = () => this.#tail;
23619
- #enqueue = (notification) => {
23620
- this.#tail = this.#tail.then(async () => await this.#consume(notification));
23621
- return this.#tail;
23703
+ #narrativeSnapshot = (identity2, activityType, output2, status) => new AcpActivity(
23704
+ identity2.id,
23705
+ activityType,
23706
+ "",
23707
+ [],
23708
+ "",
23709
+ truncate(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
23710
+ identity2.sequence,
23711
+ status,
23712
+ activityType === "reasoning" ? "Reasoning" : "Progress update",
23713
+ activityType === "reasoning" ? "think" : ""
23714
+ );
23715
+ recordPlan = async (plan) => {
23716
+ await this.finishNarrative();
23717
+ await this.#recordPlanEntries("plan:default", plan.entries);
23622
23718
  };
23623
- receive = (notification) => {
23624
- const selection = this.#selection;
23625
- switch (selection.kind) {
23626
- case "selected":
23627
- return this.#enqueue(notification);
23628
- case "awaiting-session": {
23629
- const bytes = selection.bytes + Buffer.byteLength(JSON.stringify(notification));
23630
- if (selection.notifications.length >= MAX_PENDING_UPDATES || bytes > MAX_PENDING_BYTES) {
23631
- return Promise.reject(
23632
- new AcpExecutionError(
23633
- "ACP agent sent too many updates before creating its session",
23634
- {},
23635
- "agent_update_limit"
23636
- )
23637
- );
23638
- }
23639
- this.#selection = {
23640
- kind: "awaiting-session",
23641
- notifications: [...selection.notifications, notification],
23642
- bytes
23643
- };
23644
- return Promise.resolve();
23645
- }
23719
+ recordPlanUpdate = async (update) => {
23720
+ await this.finishNarrative();
23721
+ const plan = update.plan;
23722
+ const key = `plan:${plan.planId}`;
23723
+ if (plan.type === "items") {
23724
+ await this.#recordPlanEntries(key, plan.entries);
23725
+ return;
23646
23726
  }
23727
+ const identity2 = this.#identity(key);
23728
+ const output2 = plan.type === "markdown" ? plan.content : `Plan file: ${plan.uri}`;
23729
+ await this.#record(
23730
+ key,
23731
+ new AcpActivity(
23732
+ identity2.id,
23733
+ "plan",
23734
+ "",
23735
+ [],
23736
+ "",
23737
+ truncate(output2, AGENT_ACTIVITY_DETAIL_LIMIT),
23738
+ identity2.sequence,
23739
+ "running",
23740
+ "Plan",
23741
+ ""
23742
+ )
23743
+ );
23647
23744
  };
23648
- select = (sessionId) => {
23649
- const selected = nativeSessionIdSchema.parse(sessionId);
23650
- const selection = this.#selection;
23651
- switch (selection.kind) {
23652
- case "selected":
23653
- if (selection.sessionId !== selected) {
23654
- throw new AcpExecutionError(
23655
- "ACP agent attempted to replace the selected session",
23656
- {},
23657
- "invalid_agent_session"
23658
- );
23659
- }
23660
- return;
23661
- case "awaiting-session":
23662
- this.#selection = { kind: "selected", sessionId: selected };
23663
- for (const notification of selection.notifications) {
23664
- void this.#enqueue(notification);
23665
- }
23666
- return;
23745
+ removePlan = async (update) => {
23746
+ await this.finishNarrative();
23747
+ const key = `plan:${update.planId}`;
23748
+ const previous = this.#activities.get(key);
23749
+ if (previous !== void 0) {
23750
+ await this.#record(
23751
+ key,
23752
+ new AcpActivity(
23753
+ previous.activityId,
23754
+ previous.activityType,
23755
+ previous.input,
23756
+ previous.locations,
23757
+ previous.name,
23758
+ previous.output,
23759
+ previous.sequence,
23760
+ "completed",
23761
+ previous.title,
23762
+ previous.toolKind,
23763
+ previous.content,
23764
+ previous.detail
23765
+ )
23766
+ );
23667
23767
  }
23668
23768
  };
23669
- };
23670
-
23671
- // src/acp/session-config/session-config-protocol.ts
23672
- import { methods as methods2 } from "@agentclientprotocol/sdk";
23673
- var MAXIMUM_CONFIG_OPTIONS = 100;
23674
- var SessionConfigProtocolError = class extends Error {
23675
- code = "invalid_session_configuration_response";
23676
- constructor(message, options = {}) {
23677
- super(message, options);
23678
- this.name = "SessionConfigProtocolError";
23679
- }
23680
- };
23681
- function isRecord5(value) {
23682
- return typeof value === "object" && value !== null && !Array.isArray(value);
23683
- }
23684
- function readString3(value, fallback = "") {
23685
- return typeof value === "string" ? value : fallback;
23686
- }
23687
- function truncate3(value, maximum) {
23688
- return value.length <= maximum ? value : value.slice(0, maximum);
23689
- }
23690
- function readBoolean(value, fallback = false) {
23691
- return typeof value === "boolean" ? value : fallback;
23692
- }
23693
- function normalizeConfigValue(option, groupId = "", groupName = "") {
23694
- const value = option["value"];
23695
- if (typeof value !== "string") {
23696
- return void 0;
23697
- }
23698
- return {
23699
- description: truncate3(readString3(option["description"]), 500),
23700
- groupId: truncate3(groupId, 128),
23701
- groupName: truncate3(groupName, 255),
23702
- name: truncate3(readString3(option["name"], value), 255),
23703
- value: truncate3(value, 500)
23769
+ recordToolCall = async (update) => {
23770
+ await this.finishNarrative();
23771
+ const key = `tool:${update.toolCallId}`;
23772
+ const identity2 = this.#identity(key);
23773
+ const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
23774
+ const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
23775
+ const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
23776
+ const detailContent = await normalizeToolContent(
23777
+ toolContent(update.content, update.rawOutput),
23778
+ this.#prepareContent
23779
+ );
23780
+ await this.#record(
23781
+ key,
23782
+ new AcpActivity(
23783
+ identity2.id,
23784
+ "tool",
23785
+ update.rawInput === void 0 ? "" : formatUnknown(update.rawInput),
23786
+ normalizeLocations(update.locations ?? []),
23787
+ truncate(update.name ?? "", 128),
23788
+ output2,
23789
+ identity2.sequence,
23790
+ normalizeToolStatus(update.status ?? "pending", "pending"),
23791
+ normalizeTitle(update.title, "Tool call"),
23792
+ update.kind ?? "other",
23793
+ detailContent.slice(0, 100).map(summarizeDisplayContent),
23794
+ captureActivityDetail(detailContent, detailInput, detailOutput)
23795
+ )
23796
+ );
23704
23797
  };
23705
- }
23706
- function normalizeConfigValues(value) {
23707
- if (!Array.isArray(value)) {
23708
- return [];
23709
- }
23710
- const normalized = [];
23711
- for (const entry of value) {
23712
- if (!isRecord5(entry)) {
23713
- continue;
23714
- }
23715
- const groupedOptions = entry["options"];
23716
- if (Array.isArray(groupedOptions)) {
23717
- const groupId = readString3(entry["group"]);
23718
- const groupName = readString3(entry["name"]);
23719
- for (const groupedOption of groupedOptions) {
23720
- if (isRecord5(groupedOption)) {
23721
- const normalizedValue = normalizeConfigValue(groupedOption, groupId, groupName);
23722
- if (normalizedValue !== void 0) {
23723
- normalized.push(normalizedValue);
23724
- }
23725
- }
23726
- }
23727
- continue;
23728
- }
23729
- const normalizedEntry = normalizeConfigValue(entry);
23730
- if (normalizedEntry !== void 0) {
23731
- normalized.push(normalizedEntry);
23798
+ recordToolCallUpdate = async (update) => {
23799
+ await this.finishNarrative();
23800
+ const key = `tool:${update.toolCallId}`;
23801
+ const previous = this.#activities.get(key);
23802
+ const identity2 = this.#identity(key);
23803
+ const previousDetail = recordedDetail(previous);
23804
+ const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous?.output ?? "";
23805
+ const nextContent = toolContent(update.content, update.rawOutput);
23806
+ const content = nextContent.length === 0 ? previous?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
23807
+ const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous?.input ?? "" : formatUnknownDetail(update.rawInput);
23808
+ const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous?.output ?? "";
23809
+ const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous?.content ?? [] : content;
23810
+ await this.#record(
23811
+ key,
23812
+ new AcpActivity(
23813
+ identity2.id,
23814
+ "tool",
23815
+ update.rawInput === void 0 ? previous?.input ?? "" : formatUnknown(update.rawInput),
23816
+ update.locations === void 0 || update.locations === null ? previous?.locations ?? [] : normalizeLocations(update.locations),
23817
+ update.name === void 0 || update.name === null ? previous?.name ?? "" : truncate(update.name, 128),
23818
+ output2,
23819
+ identity2.sequence,
23820
+ update.status === void 0 || update.status === null ? previous?.status ?? "pending" : normalizeToolStatus(update.status, previous?.status ?? "pending"),
23821
+ update.title === void 0 || update.title === null ? previous?.title ?? "Tool call" : normalizeTitle(update.title, "Tool call"),
23822
+ update.kind === void 0 || update.kind === null ? previous?.toolKind ?? "other" : update.kind,
23823
+ content.slice(0, 100).map(summarizeDisplayContent),
23824
+ captureActivityDetail(detailContent, detailInput, detailOutput)
23825
+ )
23826
+ );
23827
+ };
23828
+ finishNarrative = async () => {
23829
+ const key = this.#activeNarrativeKey;
23830
+ if (key.length === 0) {
23831
+ return;
23732
23832
  }
23733
- }
23734
- return normalized.slice(0, 500);
23735
- }
23736
- function normalizeConfigOptions(value, modes) {
23737
- const normalized = [];
23738
- if (Array.isArray(value)) {
23739
- for (const option of value) {
23740
- if (!isRecord5(option)) {
23741
- continue;
23742
- }
23743
- const id = truncate3(readString3(option["id"]), 128);
23744
- const name = truncate3(readString3(option["name"], id), 255);
23745
- const category = truncate3(readString3(option["category"]), 128);
23746
- if (id.length === 0 || name.length === 0 || category === "_mobius_permission") {
23747
- continue;
23748
- }
23749
- if (option["type"] === "boolean") {
23750
- normalized.push({
23751
- booleanValue: readBoolean(option["currentValue"]),
23752
- category,
23753
- currentValue: "",
23754
- description: truncate3(readString3(option["description"]), 500),
23755
- id,
23756
- name,
23757
- type: "boolean",
23758
- values: []
23759
- });
23760
- continue;
23761
- }
23762
- if (option["type"] === "select") {
23763
- const values = normalizeConfigValues(option["options"]);
23764
- const currentValue = truncate3(readString3(option["currentValue"]), 500);
23765
- if (values.some((entry) => entry.value === currentValue)) {
23766
- normalized.push({
23767
- booleanValue: false,
23768
- category,
23769
- currentValue,
23770
- description: truncate3(readString3(option["description"]), 500),
23771
- id,
23772
- name,
23773
- type: "select",
23774
- values
23775
- });
23776
- }
23777
- }
23833
+ this.#activeNarrativeKey = "";
23834
+ await this.#completeNarrative(key);
23835
+ };
23836
+ finish = async () => {
23837
+ await this.finishNarrative();
23838
+ for (const key of this.#narrations.keys()) {
23839
+ await this.#completeNarrative(key);
23778
23840
  }
23779
- }
23780
- if (isRecord5(modes)) {
23781
- const values = [];
23782
- const availableModes = modes["availableModes"];
23783
- if (Array.isArray(availableModes)) {
23784
- for (const mode of availableModes) {
23785
- if (!isRecord5(mode)) {
23786
- continue;
23787
- }
23788
- const id = truncate3(readString3(mode["id"]), 500);
23789
- if (id.length === 0) {
23790
- continue;
23791
- }
23792
- values.push({
23793
- description: truncate3(readString3(mode["description"]), 500),
23794
- groupId: "",
23795
- groupName: "",
23796
- name: truncate3(readString3(mode["name"], id), 255),
23797
- value: id
23798
- });
23841
+ const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
23842
+ for (const [key, activity2] of entries) {
23843
+ const completed = activity2.complete();
23844
+ if (completed !== activity2) {
23845
+ await this.#record(key, completed);
23799
23846
  }
23800
23847
  }
23801
- const currentValue = truncate3(readString3(modes["currentModeId"]), 500);
23802
- if (currentValue.length > 0 && values.some((entry) => entry.value === currentValue) && !normalized.some((entry) => entry.category === "mode")) {
23803
- normalized.unshift({
23804
- booleanValue: false,
23805
- category: "mode",
23806
- currentValue,
23807
- description: "Agent session mode",
23808
- id: "mode",
23809
- name: "Mode",
23810
- type: "select",
23811
- values
23812
- });
23813
- }
23814
- }
23815
- return normalized.slice(0, MAXIMUM_CONFIG_OPTIONS);
23816
- }
23817
- function normalizeStandardLifecycle(response) {
23818
- const lifecycle = isRecord5(response) ? response : {};
23819
- return normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]);
23820
- }
23821
- function replaceStandardConfigOptions(current, value) {
23822
- const next = normalizeConfigOptions(value, void 0);
23823
- const withMode = next.some((option) => option.category === "mode") ? next : [...current.filter((option) => option.category === "mode"), ...next].slice(0, MAXIMUM_CONFIG_OPTIONS);
23824
- return withMode;
23825
- }
23826
- function updateCurrentValue(current, configId, value) {
23827
- return current.map((option) => option.id === configId ? { ...option, currentValue: value } : option);
23828
- }
23829
- var StandardSessionConfigProtocol = class {
23830
- configure = async (current, change, nativeSessionId, transport) => {
23831
- const existing = current.find((option) => option.id === change.configId);
23832
- if (existing === void 0) {
23833
- return current;
23834
- }
23835
- if (existing.type === "select" && existing.category === "mode") {
23836
- await transport.request(
23837
- methods2.agent.session.setMode,
23838
- { modeId: change.value, sessionId: nativeSessionId },
23839
- "ACP agent exited while setting the session mode",
23840
- change.signal
23841
- );
23842
- return updateCurrentValue(current, existing.id, change.value);
23848
+ };
23849
+ // Materialize a streamed narration as one completed snapshot activity. The
23850
+ // incremental events carried the text; this final event gives consumers the
23851
+ // whole narration with its terminal status, as a single bounded item.
23852
+ #completeNarrative = async (key) => {
23853
+ const narration = this.#narrations.get(key);
23854
+ if (narration === void 0) {
23855
+ return;
23843
23856
  }
23844
- const params = existing.type === "boolean" ? {
23845
- configId: existing.id,
23846
- sessionId: nativeSessionId,
23847
- type: "boolean",
23848
- value: change.booleanValue
23849
- } : {
23850
- configId: existing.id,
23851
- sessionId: nativeSessionId,
23852
- value: change.value
23853
- };
23854
- const response = await transport.request(
23855
- methods2.agent.session.setConfigOption,
23856
- params,
23857
- "ACP agent exited while changing session configuration",
23858
- change.signal
23857
+ this.#narrations.delete(key);
23858
+ const previous = this.#activities.get(key);
23859
+ const detail = narration.truncated ? {
23860
+ capturedBytes: encodedByteLength({ content: [], input: "", output: narration.output }),
23861
+ kind: "truncated",
23862
+ originalBytes: narration.originalBytes
23863
+ } : captureActivityDetail([], "", narration.output);
23864
+ await this.#record(
23865
+ key,
23866
+ new AcpActivity(
23867
+ narration.activityId,
23868
+ narration.activityType,
23869
+ "",
23870
+ [],
23871
+ "",
23872
+ truncate(narration.output, AGENT_ACTIVITY_DETAIL_LIMIT),
23873
+ narration.sequence,
23874
+ "completed",
23875
+ narration.activityType === "reasoning" ? "Reasoning" : "Progress update",
23876
+ narration.activityType === "reasoning" ? "think" : "",
23877
+ previous?.content ?? [],
23878
+ detail
23879
+ )
23859
23880
  );
23860
- if (!isRecord5(response) || !Array.isArray(response["configOptions"])) {
23861
- throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
23881
+ };
23882
+ #identity = (key) => {
23883
+ const existing = this.#identities.get(key);
23884
+ if (existing !== void 0) {
23885
+ return existing;
23862
23886
  }
23863
- return replaceStandardConfigOptions(current, response["configOptions"]);
23887
+ const identity2 = new ActivityIdentity(`activity-${crypto.randomUUID()}`, this.#nextSequence);
23888
+ this.#nextSequence += 1;
23889
+ this.#identities.set(key, identity2);
23890
+ return identity2;
23891
+ };
23892
+ #record = async (key, activity2) => {
23893
+ this.#activities.set(key, activity2);
23894
+ await this.#onActivity(activity2);
23895
+ };
23896
+ #recordPlanEntries = async (key, entries) => {
23897
+ const identity2 = this.#identity(key);
23898
+ await this.#record(
23899
+ key,
23900
+ new AcpActivity(
23901
+ identity2.id,
23902
+ "plan",
23903
+ "",
23904
+ [],
23905
+ "",
23906
+ formatPlanEntries(entries),
23907
+ identity2.sequence,
23908
+ planStatus(entries),
23909
+ "Plan",
23910
+ ""
23911
+ )
23912
+ );
23864
23913
  };
23865
- normalizeLifecycle = (response) => normalizeStandardLifecycle(response);
23866
- normalizeUpdate = (current, value) => replaceStandardConfigOptions(current, value);
23867
- };
23868
- var standardSessionConfigProtocol = new StandardSessionConfigProtocol();
23869
-
23870
- // src/acp/session-config/session-config-registry.ts
23871
- function sessionConfigProtocolForAgent(_agentId) {
23872
- return standardSessionConfigProtocol;
23873
- }
23874
-
23875
- // src/acp/session-contracts.ts
23876
- var NullAcpSessionObserver = class {
23877
- onCommands = () => Promise.resolve();
23878
- onConfig = () => Promise.resolve();
23879
- onContent = () => Promise.resolve();
23880
- onElicitation = () => Promise.resolve();
23881
- onElicitationResolved = () => Promise.resolve();
23882
- onInfo = () => Promise.resolve();
23883
- onPermission = () => Promise.resolve();
23884
- onPermissionResolved = () => Promise.resolve();
23885
- onUsage = () => Promise.resolve();
23886
- };
23887
- var AcpPreparedSession = class {
23888
- agentName;
23889
- agentVersion;
23890
- capabilities;
23891
- commands;
23892
- configOptions;
23893
- restored;
23894
- constructor(agentName, agentVersion, capabilities, commands, configOptions, restored) {
23895
- this.agentName = agentName;
23896
- this.agentVersion = agentVersion;
23897
- this.capabilities = capabilities;
23898
- this.commands = commands;
23899
- this.configOptions = configOptions;
23900
- this.restored = restored;
23901
- }
23902
- };
23903
- var AcpAgentSettingsSnapshot = class {
23904
- agentName;
23905
- agentVersion;
23906
- configOptions;
23907
- constructor(agentName, agentVersion, configOptions) {
23908
- this.agentName = agentName;
23909
- this.agentVersion = agentVersion;
23910
- this.configOptions = configOptions;
23911
- }
23912
23914
  };
23913
23915
 
23914
23916
  // src/acp/session-history.ts