@moxt-ai/mobius 0.0.141 → 0.0.143

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 (48) hide show
  1. package/dist/acp/agent-query-processes.js +2 -2
  2. package/dist/acp/agent-query-processes.js.map +1 -1
  3. package/dist/acp/agent-runtime-manager.js +4 -4
  4. package/dist/acp/agent-runtime-manager.js.map +1 -1
  5. package/dist/acp/agent-session.d.ts.map +1 -1
  6. package/dist/acp/agent-session.js +37 -34
  7. package/dist/acp/agent-session.js.map +1 -1
  8. package/dist/acp/runtime-operations.d.ts +2 -2
  9. package/dist/acp/runtime-operations.d.ts.map +1 -1
  10. package/dist/acp/runtime-operations.js +2 -2
  11. package/dist/acp/runtime-operations.js.map +1 -1
  12. package/dist/cli.js +347 -315
  13. package/dist/cli.js.map +4 -4
  14. package/dist/daemon-active-turn.d.ts +3 -0
  15. package/dist/daemon-active-turn.d.ts.map +1 -1
  16. package/dist/daemon-active-turn.js +81 -6
  17. package/dist/daemon-active-turn.js.map +1 -1
  18. package/dist/daemon-prompt-executor.d.ts.map +1 -1
  19. package/dist/daemon-prompt-executor.js +25 -41
  20. package/dist/daemon-prompt-executor.js.map +1 -1
  21. package/dist/daemon-turn-registry.d.ts +48 -0
  22. package/dist/daemon-turn-registry.d.ts.map +1 -1
  23. package/dist/daemon-turn-registry.js +8 -1
  24. package/dist/daemon-turn-registry.js.map +1 -1
  25. package/dist/index.js +346 -314
  26. package/dist/index.js.map +4 -4
  27. package/dist/native-sessions/live-history-page.d.ts.map +1 -1
  28. package/dist/native-sessions/live-history-page.js +40 -24
  29. package/dist/native-sessions/live-history-page.js.map +1 -1
  30. package/dist/relay-connection/coalescing-agent-event-publisher.d.ts +32 -0
  31. package/dist/relay-connection/coalescing-agent-event-publisher.d.ts.map +1 -0
  32. package/dist/relay-connection/coalescing-agent-event-publisher.js +116 -0
  33. package/dist/relay-connection/coalescing-agent-event-publisher.js.map +1 -0
  34. package/dist/runtime.js +346 -314
  35. package/dist/runtime.js.map +4 -4
  36. package/package.json +1 -1
  37. package/dist/relay-connection/coalescing-activity-publisher.d.ts +0 -10
  38. package/dist/relay-connection/coalescing-activity-publisher.d.ts.map +0 -1
  39. package/dist/relay-connection/coalescing-activity-publisher.js +0 -54
  40. package/dist/relay-connection/coalescing-activity-publisher.js.map +0 -1
  41. package/dist/relay-connection/coalescing-narration-publisher.d.ts +0 -31
  42. package/dist/relay-connection/coalescing-narration-publisher.d.ts.map +0 -1
  43. package/dist/relay-connection/coalescing-narration-publisher.js +0 -61
  44. package/dist/relay-connection/coalescing-narration-publisher.js.map +0 -1
  45. package/dist/relay-connection/coalescing-text-publisher.d.ts +0 -26
  46. package/dist/relay-connection/coalescing-text-publisher.d.ts.map +0 -1
  47. package/dist/relay-connection/coalescing-text-publisher.js +0 -57
  48. package/dist/relay-connection/coalescing-text-publisher.js.map +0 -1
package/dist/runtime.js CHANGED
@@ -20929,7 +20929,7 @@ var userHistoryMessage = external_exports.strictObject({
20929
20929
  text: external_exports.string().max(SESSION_HISTORY_CHARACTER_LIMIT),
20930
20930
  images: external_exports.array(historyImage).max(8).readonly().optional()
20931
20931
  }).readonly();
20932
- var assistantHistoryMessage = external_exports.strictObject({
20932
+ var assistantHistoryMessageSchema = external_exports.strictObject({
20933
20933
  activities: external_exports.array(nativeMessageActivitySchema).max(100).readonly().default([]),
20934
20934
  content: external_exports.array(displayContentSchema).max(100).readonly().default([]),
20935
20935
  role: external_exports.literal("assistant"),
@@ -20938,7 +20938,7 @@ var assistantHistoryMessage = external_exports.strictObject({
20938
20938
  text: external_exports.string().max(SESSION_HISTORY_CHARACTER_LIMIT),
20939
20939
  images: external_exports.array(historyImage).max(8).readonly().optional()
20940
20940
  }).readonly();
20941
- var historyMessage = external_exports.discriminatedUnion("role", [userHistoryMessage, assistantHistoryMessage]);
20941
+ var historyMessage = external_exports.discriminatedUnion("role", [userHistoryMessage, assistantHistoryMessageSchema]);
20942
20942
  var availableSessionHistoryObjectSchema = external_exports.strictObject({
20943
20943
  status: external_exports.literal("available"),
20944
20944
  messages: external_exports.array(historyMessage).max(SESSION_HISTORY_MESSAGE_LIMIT).readonly(),
@@ -21009,6 +21009,7 @@ var activeTurnSnapshotSchema = external_exports.strictObject({
21009
21009
  truncated: external_exports.boolean(),
21010
21010
  epoch: identifierStringSchema,
21011
21011
  interaction: external_exports.discriminatedUnion("kind", [sessionPermissionRequestedEventSchema, sessionElicitationRequestedEventSchema]).nullable(),
21012
+ messages: external_exports.array(assistantHistoryMessageSchema).max(SESSION_HISTORY_MESSAGE_LIMIT).readonly(),
21012
21013
  sequence: external_exports.number().int().nonnegative(),
21013
21014
  state: external_exports.literal("running")
21014
21015
  }).readonly();
@@ -27921,6 +27922,48 @@ var AgentUpdateStream = class {
27921
27922
  };
27922
27923
  };
27923
27924
 
27925
+ // src/acp/runtime-operations.ts
27926
+ var RuntimeOperations = class {
27927
+ #shutdown = new AbortController();
27928
+ #pending = /* @__PURE__ */ new Set();
27929
+ #closing = null;
27930
+ run = async (options, operation) => {
27931
+ const signal = AbortSignal.any([options.signal, this.#shutdown.signal]);
27932
+ signal.throwIfAborted();
27933
+ const pending = Promise.resolve().then(() => operation({ ...options, signal }));
27934
+ this.#pending.add(pending);
27935
+ try {
27936
+ const result = await pending;
27937
+ signal.throwIfAborted();
27938
+ return result;
27939
+ } finally {
27940
+ this.#pending.delete(pending);
27941
+ }
27942
+ };
27943
+ close = (release) => {
27944
+ if (this.#closing !== null) {
27945
+ return this.#closing;
27946
+ }
27947
+ this.#shutdown.abort();
27948
+ this.#closing = (async () => {
27949
+ await Promise.allSettled([...this.#pending]);
27950
+ await release();
27951
+ })();
27952
+ return this.#closing;
27953
+ };
27954
+ };
27955
+ async function waitForSharedOperation(pending, signal) {
27956
+ signal.throwIfAborted();
27957
+ const cancelled = Promise.withResolvers();
27958
+ const abort = () => cancelled.reject(signal.reason);
27959
+ signal.addEventListener("abort", abort, { once: true });
27960
+ try {
27961
+ return await Promise.race([pending, cancelled.promise]);
27962
+ } finally {
27963
+ signal.removeEventListener("abort", abort);
27964
+ }
27965
+ }
27966
+
27924
27967
  // src/acp/session-config/session-config-protocol.ts
27925
27968
  import { methods as methods7 } from "@agentclientprotocol/sdk";
27926
27969
  var MAXIMUM_CONFIG_OPTIONS = 100;
@@ -34560,9 +34603,7 @@ var AgentSession = class _AgentSession {
34560
34603
  #configOptions = [];
34561
34604
  #prompted = false;
34562
34605
  #nativePrompt = null;
34563
- #replay = {
34564
- kind: "idle"
34565
- };
34606
+ #sessionLoad = { kind: "not-requested" };
34566
34607
  #restored = false;
34567
34608
  #sessionTitle = null;
34568
34609
  #sessionUpdatedAt = "";
@@ -34675,30 +34716,46 @@ var AgentSession = class _AgentSession {
34675
34716
  }
34676
34717
  };
34677
34718
  }
34678
- const history = new AcpHistoryReplay();
34679
- this.#replay = { kind: "capture", history };
34680
- try {
34681
- await this.race(
34682
- this.#connection.connection.agent.request(
34683
- methods8.agent.session.load,
34684
- {
34685
- additionalDirectories: [...this.#additionalDirectories],
34686
- cwd: this.#cwd,
34687
- mcpServers: [],
34688
- sessionId: this.#updates.sessionId()
34689
- },
34690
- { cancellationSignal: signal }
34691
- ),
34692
- "ACP agent exited while loading history",
34693
- signal
34694
- );
34695
- await this.#updates.drained();
34696
- signal.throwIfAborted();
34697
- return await embedLocalHistoryImages(await history.snapshot(), signal);
34698
- } finally {
34699
- this.#replay = { kind: "idle" };
34700
- }
34719
+ const loaded = await this.#loadSession(signal, "ACP agent exited while loading history");
34720
+ return await embedLocalHistoryImages(await loaded.history.snapshot(), signal);
34701
34721
  };
34722
+ async #loadSession(signal, exitMessage) {
34723
+ if (this.#sessionLoad.kind === "loaded") {
34724
+ return this.#sessionLoad;
34725
+ }
34726
+ if (this.#sessionLoad.kind === "capturing") {
34727
+ return await waitForSharedOperation(this.#sessionLoad.completion, signal);
34728
+ }
34729
+ const history = new AcpHistoryReplay();
34730
+ const completion = Promise.resolve().then(async () => {
34731
+ try {
34732
+ const response = await this.race(
34733
+ this.#connection.connection.agent.request(
34734
+ methods8.agent.session.load,
34735
+ {
34736
+ additionalDirectories: [...this.#additionalDirectories],
34737
+ cwd: this.#cwd,
34738
+ mcpServers: [],
34739
+ sessionId: this.#updates.sessionId()
34740
+ },
34741
+ { cancellationSignal: signal }
34742
+ ),
34743
+ exitMessage,
34744
+ signal
34745
+ );
34746
+ await this.#updates.drained();
34747
+ signal.throwIfAborted();
34748
+ const loaded = { history, kind: "loaded", response };
34749
+ this.#sessionLoad = loaded;
34750
+ return loaded;
34751
+ } catch (cause) {
34752
+ this.#sessionLoad = { kind: "not-requested" };
34753
+ throw cause;
34754
+ }
34755
+ });
34756
+ this.#sessionLoad = { completion, history, kind: "capturing" };
34757
+ return await completion;
34758
+ }
34702
34759
  prepareAgentContent = async (content) => {
34703
34760
  if (content.type === "image" && content.uri.length > 0) {
34704
34761
  const signal = AbortSignal.timeout(2e4);
@@ -34901,29 +34958,10 @@ var AgentSession = class _AgentSession {
34901
34958
  )
34902
34959
  );
34903
34960
  } else if (this.#capabilities.loadSession) {
34904
- this.#replay = { kind: "discard" };
34905
- try {
34906
- lifecycleResponse = await this.#metrics.measure(
34907
- "session-load",
34908
- async () => await this.race(
34909
- this.#connection.connection.agent.request(
34910
- methods8.agent.session.load,
34911
- {
34912
- additionalDirectories: [...this.#additionalDirectories],
34913
- cwd: this.#cwd,
34914
- mcpServers: [],
34915
- sessionId: this.#updates.sessionId()
34916
- },
34917
- { cancellationSignal: signal }
34918
- ),
34919
- "ACP agent exited while loading a session",
34920
- signal
34921
- )
34922
- );
34923
- } finally {
34924
- await this.#updates.drained();
34925
- this.#replay = { kind: "idle" };
34926
- }
34961
+ lifecycleResponse = await this.#metrics.measure(
34962
+ "session-load",
34963
+ async () => (await this.#loadSession(signal, "ACP agent exited while loading a session")).response
34964
+ );
34927
34965
  } else {
34928
34966
  throw new AcpExecutionError(
34929
34967
  "The ACP agent cannot restore its persisted session",
@@ -35308,10 +35346,10 @@ var AgentSession = class _AgentSession {
35308
35346
  #processUpdate = async (notification) => {
35309
35347
  this.assertNativeSession(notification.sessionId);
35310
35348
  const update = notification.update;
35311
- if (this.#replay.kind === "capture") {
35312
- await this.#replay.history.record(update);
35349
+ if (this.#sessionLoad.kind !== "not-requested") {
35350
+ await this.#sessionLoad.history.record(update);
35313
35351
  }
35314
- if (this.#replay.kind !== "idle" && (update.sessionUpdate === "user_message_chunk" || update.sessionUpdate === "agent_message_chunk" || update.sessionUpdate === "agent_thought_chunk" || update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update" || update.sessionUpdate === "plan" || update.sessionUpdate === "plan_update" || update.sessionUpdate === "plan_removed")) {
35352
+ if (this.#sessionLoad.kind === "capturing" && (update.sessionUpdate === "user_message_chunk" || update.sessionUpdate === "agent_message_chunk" || update.sessionUpdate === "agent_thought_chunk" || update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update" || update.sessionUpdate === "plan" || update.sessionUpdate === "plan_update" || update.sessionUpdate === "plan_removed")) {
35315
35353
  return;
35316
35354
  }
35317
35355
  if (update.sessionUpdate === "agent_message_chunk") {
@@ -35581,48 +35619,6 @@ var RetainedAgentProcesses = class {
35581
35619
  };
35582
35620
  };
35583
35621
 
35584
- // src/acp/runtime-operations.ts
35585
- var RuntimeOperations = class {
35586
- #shutdown = new AbortController();
35587
- #pending = /* @__PURE__ */ new Set();
35588
- #closing = null;
35589
- run = async (options, operation) => {
35590
- const signal = AbortSignal.any([options.signal, this.#shutdown.signal]);
35591
- signal.throwIfAborted();
35592
- const pending = Promise.resolve().then(() => operation({ ...options, signal }));
35593
- this.#pending.add(pending);
35594
- try {
35595
- const result = await pending;
35596
- signal.throwIfAborted();
35597
- return result;
35598
- } finally {
35599
- this.#pending.delete(pending);
35600
- }
35601
- };
35602
- close = (release) => {
35603
- if (this.#closing !== null) {
35604
- return this.#closing;
35605
- }
35606
- this.#shutdown.abort();
35607
- this.#closing = (async () => {
35608
- await Promise.allSettled([...this.#pending]);
35609
- await release();
35610
- })();
35611
- return this.#closing;
35612
- };
35613
- };
35614
- async function waitForPreparation(pending, signal) {
35615
- signal.throwIfAborted();
35616
- const cancelled = Promise.withResolvers();
35617
- const abort = () => cancelled.reject(signal.reason);
35618
- signal.addEventListener("abort", abort, { once: true });
35619
- try {
35620
- return await Promise.race([pending, cancelled.promise]);
35621
- } finally {
35622
- signal.removeEventListener("abort", abort);
35623
- }
35624
- }
35625
-
35626
35622
  // src/acp/agent-query-processes.ts
35627
35623
  var AgentQueryProcesses = class {
35628
35624
  #processesByQuery;
@@ -35669,7 +35665,7 @@ var AgentQueryProcesses = class {
35669
35665
  prepare = async (options) => {
35670
35666
  const pending = this.#processesByQuery.pending(options.sessionId);
35671
35667
  if (pending !== void 0) {
35672
- const runtime2 = await waitForPreparation(pending, options.signal);
35668
+ const runtime2 = await waitForSharedOperation(pending, options.signal);
35673
35669
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35674
35670
  this.#processesByQuery.touch(options.sessionId, runtime2);
35675
35671
  return runtime2.prepared();
@@ -36087,7 +36083,7 @@ var AgentRuntimeManager = class {
36087
36083
  if (pending !== void 0) {
36088
36084
  const runtime2 = await metrics.measure(
36089
36085
  "session-preparation-wait",
36090
- async () => await waitForPreparation(pending, options2.signal)
36086
+ async () => await waitForSharedOperation(pending, options2.signal)
36091
36087
  );
36092
36088
  if (runtime2.belongsTo(options2.agent.id, options2.cwd, options2.additionalDirectories)) {
36093
36089
  this.#executionProcesses.touch(options2.sessionId, runtime2);
@@ -36177,7 +36173,7 @@ var AgentRuntimeManager = class {
36177
36173
  prepareExecutionSession = async (options) => this.#operations.run(options, async (options2) => {
36178
36174
  const pending = this.#executionProcesses.pending(options2.sessionId);
36179
36175
  if (pending !== void 0) {
36180
- await waitForPreparation(pending, options2.signal);
36176
+ await waitForSharedOperation(pending, options2.signal);
36181
36177
  return await this.prepareExecutionSession(options2);
36182
36178
  }
36183
36179
  const existing = this.#executionProcesses.get(options2.sessionId);
@@ -36231,7 +36227,7 @@ var AgentRuntimeManager = class {
36231
36227
  }
36232
36228
  const pending = this.#executionProcesses.pending(options2.sessionId);
36233
36229
  if (pending !== void 0) {
36234
- await waitForPreparation(pending, options2.signal);
36230
+ await waitForSharedOperation(pending, options2.signal);
36235
36231
  }
36236
36232
  if (this.#executions.command(options2.sessionId) !== options2.targetCommandId) {
36237
36233
  throw new AcpExecutionError("The target turn is no longer active", {}, "steering_target_unavailable");
@@ -37784,6 +37780,7 @@ var ActiveDaemonTurn = class {
37784
37780
  #text = "";
37785
37781
  #activities = /* @__PURE__ */ new Map();
37786
37782
  #content = /* @__PURE__ */ new Map();
37783
+ #timeline = [];
37787
37784
  #sequence = 0;
37788
37785
  #interaction = null;
37789
37786
  #epoch = decodeIdentifier(randomUUID());
@@ -37827,12 +37824,16 @@ var ActiveDaemonTurn = class {
37827
37824
  recordEvent = (event) => {
37828
37825
  if (event.kind === AGENT_MESSAGE_DELTA_KIND) {
37829
37826
  this.#text += event.text;
37827
+ this.appendMessageText(event.messageId, event.text);
37830
37828
  return this.updated();
37831
37829
  }
37832
37830
  if (event.sessionId !== this.command.sessionId || "commandId" in event && event.commandId !== this.command.commandId) {
37833
37831
  return event;
37834
37832
  }
37835
37833
  if (event.kind === AGENT_ACTIVITY_KIND) {
37834
+ if (!this.#activities.has(event.activityId)) {
37835
+ this.#timeline = [...this.#timeline, { activityId: event.activityId, kind: "activity" }];
37836
+ }
37836
37837
  this.#activities.set(event.activityId, {
37837
37838
  activityId: event.activityId,
37838
37839
  activityType: event.activityType,
@@ -37848,6 +37849,9 @@ var ActiveDaemonTurn = class {
37848
37849
  });
37849
37850
  } else if (event.kind === AGENT_ACTIVITY_NARRATION_KIND) {
37850
37851
  const previous = this.#activities.get(event.activityId);
37852
+ if (previous === void 0) {
37853
+ this.#timeline = [...this.#timeline, { activityId: event.activityId, kind: "activity" }];
37854
+ }
37851
37855
  this.#activities.set(event.activityId, {
37852
37856
  activityId: event.activityId,
37853
37857
  activityType: event.activityType,
@@ -37863,6 +37867,24 @@ var ActiveDaemonTurn = class {
37863
37867
  });
37864
37868
  } else if (event.kind === AGENT_CONTENT_KIND) {
37865
37869
  this.#content.set(event.contentId, event.content);
37870
+ const target = this.#timeline.findLastIndex(
37871
+ (entry) => entry.kind === "message" && entry.messageId === event.messageId
37872
+ );
37873
+ if (target < 0) {
37874
+ this.#timeline = [
37875
+ ...this.#timeline,
37876
+ {
37877
+ content: /* @__PURE__ */ new Map([[event.contentId, event.content]]),
37878
+ kind: "message",
37879
+ messageId: event.messageId,
37880
+ text: ""
37881
+ }
37882
+ ];
37883
+ } else {
37884
+ this.#timeline = this.#timeline.map(
37885
+ (entry, index) => index === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
37886
+ );
37887
+ }
37866
37888
  } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
37867
37889
  this.#interaction = event;
37868
37890
  } else if ((event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) && this.#interaction?.interactionId === event.interactionId) {
@@ -37873,6 +37895,49 @@ var ActiveDaemonTurn = class {
37873
37895
  }
37874
37896
  return event;
37875
37897
  };
37898
+ appendMessageText(messageId, text2) {
37899
+ let remaining = text2;
37900
+ while (remaining.length > 0) {
37901
+ const latest = this.#timeline.at(-1);
37902
+ if (latest?.kind === "message" && latest.messageId === messageId) {
37903
+ const available = SESSION_HISTORY_CHARACTER_LIMIT - latest.text.length;
37904
+ if (available > 0) {
37905
+ this.#timeline = [
37906
+ ...this.#timeline.slice(0, -1),
37907
+ { ...latest, text: `${latest.text}${remaining.slice(0, available)}` }
37908
+ ];
37909
+ remaining = remaining.slice(available);
37910
+ continue;
37911
+ }
37912
+ }
37913
+ this.#timeline = [
37914
+ ...this.#timeline,
37915
+ {
37916
+ content: /* @__PURE__ */ new Map(),
37917
+ kind: "message",
37918
+ messageId,
37919
+ text: remaining.slice(0, SESSION_HISTORY_CHARACTER_LIMIT)
37920
+ }
37921
+ ];
37922
+ remaining = remaining.slice(SESSION_HISTORY_CHARACTER_LIMIT);
37923
+ }
37924
+ }
37925
+ timelineMessages() {
37926
+ return this.#timeline.flatMap((entry) => {
37927
+ if (entry.kind === "message") {
37928
+ return [
37929
+ {
37930
+ activities: [],
37931
+ content: [...entry.content.values()],
37932
+ role: "assistant",
37933
+ text: entry.text
37934
+ }
37935
+ ];
37936
+ }
37937
+ const activity2 = this.#activities.get(entry.activityId);
37938
+ return activity2 === void 0 ? [] : [{ activities: [activity2], content: [], role: "assistant", text: "" }];
37939
+ });
37940
+ }
37876
37941
  updated = () => {
37877
37942
  this.#sequence += 1;
37878
37943
  const turn = this.snapshot();
@@ -37881,19 +37946,28 @@ var ActiveDaemonTurn = class {
37881
37946
  }
37882
37947
  return { kind: "session.turn.updated", sessionId: this.command.sessionId, turn };
37883
37948
  };
37884
- snapshot = () => this.#dispatch.kind === "running" ? {
37885
- activities: [...this.#activities.values()].sort((left, right) => left.sequence - right.sequence),
37886
- commandId: decodeIdentifier(this.command.commandId),
37887
- content: [...this.#content.values()],
37888
- prompt: this.command.prompt,
37889
- text: this.#text,
37890
- truncated: false,
37891
- epoch: this.#epoch,
37892
- interaction: this.#interaction,
37893
- sequence: this.#sequence,
37894
- state: "running"
37895
- } : null;
37949
+ snapshot = () => {
37950
+ if (this.#dispatch.kind !== "running") {
37951
+ return null;
37952
+ }
37953
+ const completeMessages = this.timelineMessages();
37954
+ const messages = completeMessages.slice(-SESSION_HISTORY_MESSAGE_LIMIT);
37955
+ return {
37956
+ activities: [...this.#activities.values()].sort((left, right) => left.sequence - right.sequence),
37957
+ commandId: decodeIdentifier(this.command.commandId),
37958
+ content: [...this.#content.values()],
37959
+ prompt: this.command.prompt,
37960
+ text: this.#text,
37961
+ truncated: messages.length !== completeMessages.length,
37962
+ epoch: this.#epoch,
37963
+ interaction: this.#interaction,
37964
+ messages,
37965
+ sequence: this.#sequence,
37966
+ state: "running"
37967
+ };
37968
+ };
37896
37969
  matches = (cancellation) => cancellation.commandId === this.command.commandId && cancellation.sessionId === this.command.sessionId;
37970
+ matchesInteraction = (interactionId, sessionId) => this.command.sessionId === sessionId && this.#interaction?.interactionId === interactionId;
37897
37971
  requestCancellation = () => {
37898
37972
  if (this.#cancellationRequested) {
37899
37973
  return "already-requested";
@@ -37962,6 +38036,13 @@ var DaemonTurnRegistry = class {
37962
38036
  return turn.recordEvent(event);
37963
38037
  }
37964
38038
  }
38039
+ if (event.kind === SESSION_PERMISSION_RESOLVED_KIND || event.kind === SESSION_ELICITATION_RESOLVED_KIND) {
38040
+ for (const turn of this.#turns.values()) {
38041
+ if (turn.matchesInteraction(event.interactionId, event.sessionId)) {
38042
+ return turn.recordEvent(event);
38043
+ }
38044
+ }
38045
+ }
37965
38046
  return event;
37966
38047
  };
37967
38048
  executionSnapshot = async (matches) => {
@@ -40194,6 +40275,34 @@ function liveHistoryCoveredTurnRanges(history) {
40194
40275
  function historyMessageCharacters(message) {
40195
40276
  return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
40196
40277
  }
40278
+ function boundedActiveMessages(messages, messageLimit, characterLimit) {
40279
+ const selected = [];
40280
+ let remainingCharacters = characterLimit;
40281
+ for (let index = messages.length - 1; index >= 0 && selected.length < messageLimit; index -= 1) {
40282
+ const message = messages[index];
40283
+ if (message === void 0) {
40284
+ break;
40285
+ }
40286
+ const characters = historyMessageCharacters(message);
40287
+ if (characters <= remainingCharacters) {
40288
+ selected.unshift(message);
40289
+ remainingCharacters -= characters;
40290
+ continue;
40291
+ }
40292
+ const structuredCharacters = characters - message.text.length;
40293
+ if (selected.length === 0 && structuredCharacters <= remainingCharacters) {
40294
+ const textCharacters = remainingCharacters - structuredCharacters;
40295
+ selected.unshift({ ...message, text: textCharacters === 0 ? "" : message.text.slice(-textCharacters) });
40296
+ remainingCharacters = 0;
40297
+ }
40298
+ break;
40299
+ }
40300
+ return {
40301
+ characters: characterLimit - remainingCharacters,
40302
+ messages: selected,
40303
+ truncated: selected.length !== messages.length
40304
+ };
40305
+ }
40197
40306
  function paginateAcpSessionHistory(history, sessionId, cursor, limit) {
40198
40307
  if (history.status === "unavailable") {
40199
40308
  if (cursor !== null) {
@@ -40224,30 +40333,19 @@ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limi
40224
40333
  if (activeTurn === null || cursor !== null) {
40225
40334
  return paginateAcpSessionHistory(history, sessionId, cursor, limit);
40226
40335
  }
40227
- const activeMessageOverhead = 4;
40228
- const activeStructuredCharacters = JSON.stringify(activeTurn.activities).length + JSON.stringify(activeTurn.content).length;
40229
- const maximumActiveTextLength = Math.max(
40230
- 0,
40231
- SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length - activeStructuredCharacters - activeMessageOverhead
40232
- );
40233
- const activeText = activeTurn.text.slice(-maximumActiveTextLength);
40234
- const completeActiveMessages = [
40235
- { role: "user", text: activeTurn.prompt },
40236
- {
40237
- activities: activeTurn.activities,
40238
- content: activeTurn.content,
40239
- role: "assistant",
40240
- text: activeText
40241
- }
40242
- ];
40243
40336
  if (history.status === "unavailable") {
40337
+ const bounded3 = boundedActiveMessages(
40338
+ activeTurn.messages,
40339
+ Math.max(0, limit - 1),
40340
+ Math.max(0, SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length)
40341
+ );
40244
40342
  return {
40245
40343
  coveredCommandIds: [],
40246
40344
  coveredMessageIds: [],
40247
- messages: completeActiveMessages,
40345
+ messages: [{ role: "user", text: activeTurn.prompt }, ...bounded3.messages],
40248
40346
  nextCursor: null,
40249
40347
  status: "available",
40250
- truncated: activeTurn.truncated || activeText.length !== activeTurn.text.length
40348
+ truncated: activeTurn.truncated || bounded3.truncated
40251
40349
  };
40252
40350
  }
40253
40351
  const activeUserIndex = history.coveredCommandIds.includes(activeTurn.commandId) ? history.messages.findLastIndex((message) => message.role === "user") : -1;
@@ -40262,9 +40360,18 @@ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limi
40262
40360
  };
40263
40361
  }
40264
40362
  const latestNativeMessage = history.messages.at(-1);
40265
- const activeMessages = activeUserIndex >= 0 || latestNativeMessage?.role === "user" && latestNativeMessage.text === activeTurn.prompt ? completeActiveMessages.slice(1) : completeActiveMessages;
40363
+ const includeActivePrompt = activeUserIndex < 0 && !(latestNativeMessage?.role === "user" && latestNativeMessage.text === activeTurn.prompt);
40364
+ const bounded2 = boundedActiveMessages(
40365
+ activeTurn.messages,
40366
+ Math.max(0, limit - (includeActivePrompt ? 1 : 0)),
40367
+ Math.max(0, SESSION_HISTORY_CHARACTER_LIMIT - (includeActivePrompt ? activeTurn.prompt.length : 0))
40368
+ );
40369
+ const activeMessages = [
40370
+ ...includeActivePrompt ? [{ role: "user", text: activeTurn.prompt }] : [],
40371
+ ...bounded2.messages
40372
+ ];
40266
40373
  let historicalMessageCount = 0;
40267
- let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT - activeText.length - activeMessageOverhead - activeStructuredCharacters - (activeMessages.length === completeActiveMessages.length ? activeTurn.prompt.length : 0);
40374
+ let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT - bounded2.characters - (includeActivePrompt ? activeTurn.prompt.length : 0);
40268
40375
  const historicalMessageLimit = Math.max(0, limit - activeMessages.length);
40269
40376
  for (let index = history.messages.length - 1; index >= 0 && historicalMessageCount < historicalMessageLimit; index -= 1) {
40270
40377
  const message = history.messages[index];
@@ -40289,7 +40396,7 @@ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limi
40289
40396
  return {
40290
40397
  ...page,
40291
40398
  messages: [...page.messages, ...activeMessages],
40292
- truncated: page.truncated || activeTurn.truncated || activeText.length !== activeTurn.text.length
40399
+ truncated: page.truncated || activeTurn.truncated || bounded2.truncated
40293
40400
  };
40294
40401
  }
40295
40402
  function mergeLiveSessionHistory(history, activeTurn, sessionId) {
@@ -40599,167 +40706,113 @@ function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selecti
40599
40706
  `);
40600
40707
  }
40601
40708
 
40602
- // src/relay-connection/coalescing-activity-publisher.ts
40603
- var AGENT_ACTIVITY_COALESCING_MILLISECONDS = 100;
40604
- var CoalescingDaemonActivityPublisher = class {
40605
- #pending = /* @__PURE__ */ new Map();
40709
+ // src/relay-connection/coalescing-agent-event-publisher.ts
40710
+ var AGENT_EVENT_COALESCING_MILLISECONDS = 100;
40711
+ var AGENT_EVENT_TEXT_MAXIMUM_LENGTH = 1e5;
40712
+ var CoalescingAgentEventPublisher = class {
40713
+ #entries = [];
40606
40714
  #publish;
40607
40715
  #publishedActivityIds = /* @__PURE__ */ new Set();
40608
- #scheduled = /* @__PURE__ */ new Map();
40716
+ #scheduled = null;
40609
40717
  #timer;
40610
40718
  constructor(timer, publish) {
40611
40719
  this.#publish = publish;
40612
40720
  this.#timer = timer;
40613
40721
  }
40614
- flush = () => {
40615
- const activities = [...this.#pending.values()].sort((left, right) => left.sequence - right.sequence);
40616
- for (const task of this.#scheduled.values()) {
40617
- task.cancel();
40618
- }
40619
- this.#pending.clear();
40620
- this.#scheduled.clear();
40621
- for (const activity2 of activities) {
40622
- this.#publish(activity2);
40623
- }
40624
- };
40625
- record = (activity2) => {
40626
- if (activity2.status !== "pending" && activity2.status !== "running") {
40627
- this.#discardPending(activity2.activityId);
40628
- this.#publishedActivityIds.add(activity2.activityId);
40629
- this.#publish(activity2);
40630
- return Promise.resolve();
40631
- }
40632
- if (!this.#publishedActivityIds.has(activity2.activityId)) {
40633
- this.#publishedActivityIds.add(activity2.activityId);
40634
- this.#publish(activity2);
40635
- return Promise.resolve();
40636
- }
40637
- this.#pending.set(activity2.activityId, activity2);
40638
- if (!this.#scheduled.has(activity2.activityId)) {
40639
- this.#scheduled.set(
40640
- activity2.activityId,
40641
- this.#timer.schedule(
40642
- () => this.#flushActivity(activity2.activityId),
40643
- AGENT_ACTIVITY_COALESCING_MILLISECONDS
40644
- )
40645
- );
40646
- }
40647
- return Promise.resolve();
40648
- };
40649
- #discardPending = (activityId) => {
40650
- this.#scheduled.get(activityId)?.cancel();
40651
- this.#scheduled.delete(activityId);
40652
- this.#pending.delete(activityId);
40653
- };
40654
- #flushActivity = (activityId) => {
40655
- const activity2 = this.#pending.get(activityId);
40656
- this.#discardPending(activityId);
40657
- if (activity2 !== void 0) {
40658
- this.#publish(activity2);
40659
- }
40660
- };
40661
- };
40662
-
40663
- // src/relay-connection/coalescing-narration-publisher.ts
40664
- var CoalescingNarrationPublisher = class {
40665
- #coalescingMilliseconds;
40666
- #maximumTextLength;
40667
- #publish;
40668
- #timer;
40669
- #pending = /* @__PURE__ */ new Map();
40670
- #scheduled = null;
40671
- constructor(timer, publish, coalescingMilliseconds, maximumTextLength) {
40672
- this.#publish = publish;
40673
- this.#timer = timer;
40674
- this.#coalescingMilliseconds = coalescingMilliseconds;
40675
- this.#maximumTextLength = maximumTextLength;
40676
- }
40677
- /** Emit every buffered increment now, cancelling the pending flush. */
40678
40722
  flush = () => {
40679
40723
  this.#scheduled?.cancel();
40680
40724
  this.#scheduled = null;
40681
- const increments = [...this.#pending.entries()].map(
40682
- ([activityId, pending]) => ({
40683
- activityId,
40684
- activityType: pending.activityType,
40685
- sequence: pending.sequence,
40686
- text: pending.text
40687
- })
40688
- );
40689
- this.#pending.clear();
40690
- for (const increment of increments) {
40691
- this.#publish(increment);
40725
+ const entries = this.#entries;
40726
+ this.#entries = [];
40727
+ for (const entry of entries) {
40728
+ this.#publish(entry);
40692
40729
  }
40693
40730
  };
40694
- /**
40695
- * Buffer an increment, emitting the buffered text when it would exceed the
40696
- * protocol's per-event text limit so no event is rejected by the codec.
40697
- */
40698
- record = (increment) => {
40699
- if (increment.text.length === 0) {
40700
- return;
40701
- }
40702
- const previous = this.#pending.get(increment.activityId);
40703
- if (previous !== void 0 && previous.text.length + increment.text.length > this.#maximumTextLength) {
40731
+ recordActivity = (activity2) => {
40732
+ const latest = this.#entries.at(-1);
40733
+ this.#entries = latest?.kind === "activity" && latest.activity.activityId === activity2.activityId ? [...this.#entries.slice(0, -1), { activity: activity2, kind: "activity" }] : [...this.#entries, { activity: activity2, kind: "activity" }];
40734
+ const first = !this.#publishedActivityIds.has(activity2.activityId);
40735
+ this.#publishedActivityIds.add(activity2.activityId);
40736
+ if (first || activity2.status !== "pending" && activity2.status !== "running") {
40704
40737
  this.flush();
40738
+ } else {
40739
+ this.schedule();
40705
40740
  }
40706
- const current = this.#pending.get(increment.activityId);
40707
- this.#pending.set(increment.activityId, {
40708
- activityType: increment.activityType,
40709
- sequence: increment.sequence,
40710
- text: `${current?.text ?? ""}${increment.text}`
40711
- });
40712
- this.#scheduled ??= this.#timer.schedule(this.flush, this.#coalescingMilliseconds);
40741
+ return Promise.resolve();
40713
40742
  };
40714
- };
40715
-
40716
- // src/relay-connection/coalescing-text-publisher.ts
40717
- var CoalescingTextPublisher = class {
40718
- #coalescingMilliseconds;
40719
- #maximumTextLength;
40720
- #publish;
40721
- #timer;
40722
- #messageId = "";
40723
- #scheduled = null;
40724
- #text = "";
40725
- constructor(timer, publish, coalescingMilliseconds, maximumTextLength) {
40726
- this.#publish = publish;
40727
- this.#timer = timer;
40728
- this.#coalescingMilliseconds = coalescingMilliseconds;
40729
- this.#maximumTextLength = maximumTextLength;
40730
- }
40731
- /** Emit any buffered text now, cancelling the pending flush. */
40732
- flush = () => {
40733
- this.#scheduled?.cancel();
40734
- this.#scheduled = null;
40735
- const messageId = this.#messageId;
40736
- const text2 = this.#text;
40737
- this.#messageId = "";
40738
- this.#text = "";
40739
- if (text2.length > 0) {
40740
- this.#publish(messageId, text2);
40743
+ recordNarration = (increment) => {
40744
+ if (increment.text.length === 0) {
40745
+ return Promise.resolve();
40746
+ }
40747
+ let remaining = increment.text;
40748
+ while (remaining.length > 0) {
40749
+ const latest = this.#entries.at(-1);
40750
+ if (latest?.kind === "narration" && latest.increment.activityId === increment.activityId) {
40751
+ const available = AGENT_EVENT_TEXT_MAXIMUM_LENGTH - latest.increment.text.length;
40752
+ if (available > 0) {
40753
+ this.#entries = [
40754
+ ...this.#entries.slice(0, -1),
40755
+ {
40756
+ increment: {
40757
+ ...increment,
40758
+ text: `${latest.increment.text}${remaining.slice(0, available)}`
40759
+ },
40760
+ kind: "narration"
40761
+ }
40762
+ ];
40763
+ remaining = remaining.slice(available);
40764
+ continue;
40765
+ }
40766
+ }
40767
+ this.#entries = [
40768
+ ...this.#entries,
40769
+ {
40770
+ increment: { ...increment, text: remaining.slice(0, AGENT_EVENT_TEXT_MAXIMUM_LENGTH) },
40771
+ kind: "narration"
40772
+ }
40773
+ ];
40774
+ remaining = remaining.slice(AGENT_EVENT_TEXT_MAXIMUM_LENGTH);
40741
40775
  }
40776
+ this.schedule();
40777
+ return Promise.resolve();
40742
40778
  };
40743
- /**
40744
- * Buffer a chunk, emitting the buffered text when the message changes or the
40745
- * buffer would exceed the protocol's per-event text limit.
40746
- */
40747
- record = (messageId, text2) => {
40779
+ recordText = (text2, messageId) => {
40748
40780
  if (text2.length === 0) {
40749
- return;
40781
+ return Promise.resolve();
40750
40782
  }
40751
- if (this.#text.length > 0 && (this.#messageId !== messageId || this.#text.length + text2.length > this.#maximumTextLength)) {
40752
- this.flush();
40783
+ let remaining = text2;
40784
+ while (remaining.length > 0) {
40785
+ const latest = this.#entries.at(-1);
40786
+ if (latest?.kind === "text" && latest.messageId === messageId) {
40787
+ const available = AGENT_EVENT_TEXT_MAXIMUM_LENGTH - latest.text.length;
40788
+ if (available > 0) {
40789
+ this.#entries = [
40790
+ ...this.#entries.slice(0, -1),
40791
+ { ...latest, text: `${latest.text}${remaining.slice(0, available)}` }
40792
+ ];
40793
+ remaining = remaining.slice(available);
40794
+ continue;
40795
+ }
40796
+ }
40797
+ this.#entries = [
40798
+ ...this.#entries,
40799
+ {
40800
+ kind: "text",
40801
+ messageId,
40802
+ text: remaining.slice(0, AGENT_EVENT_TEXT_MAXIMUM_LENGTH)
40803
+ }
40804
+ ];
40805
+ remaining = remaining.slice(AGENT_EVENT_TEXT_MAXIMUM_LENGTH);
40753
40806
  }
40754
- this.#messageId = messageId;
40755
- this.#text = `${this.#text}${text2}`;
40756
- this.#scheduled ??= this.#timer.schedule(this.flush, this.#coalescingMilliseconds);
40807
+ this.schedule();
40808
+ return Promise.resolve();
40757
40809
  };
40810
+ schedule() {
40811
+ this.#scheduled ??= this.#timer.schedule(this.flush, AGENT_EVENT_COALESCING_MILLISECONDS);
40812
+ }
40758
40813
  };
40759
40814
 
40760
40815
  // src/daemon-prompt-executor.ts
40761
- var AGENT_TEXT_COALESCING_MILLISECONDS = 100;
40762
- var AGENT_TEXT_MAXIMUM_LENGTH = 1e5;
40763
40816
  function daemonActivity(command, activity2) {
40764
40817
  return {
40765
40818
  activityId: activity2.activityId,
@@ -40795,41 +40848,30 @@ async function executePrompt({
40795
40848
  recordLiveEvent,
40796
40849
  cancellationRequested
40797
40850
  }) {
40798
- const narration = new CoalescingNarrationPublisher(
40799
- timer,
40800
- (increment) => {
40801
- const event = {
40802
- activityId: increment.activityId,
40803
- activityType: increment.activityType,
40851
+ const events = new CoalescingAgentEventPublisher(timer, (event) => {
40852
+ if (event.kind === "text") {
40853
+ publisher.publish(
40854
+ command.sessionId,
40855
+ recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId: event.messageId, text: event.text })
40856
+ );
40857
+ return;
40858
+ }
40859
+ if (event.kind === "narration") {
40860
+ const recorded = {
40861
+ activityId: event.increment.activityId,
40862
+ activityType: event.increment.activityType,
40804
40863
  commandId: command.commandId,
40805
40864
  kind: AGENT_ACTIVITY_NARRATION_KIND,
40806
- sequence: increment.sequence,
40865
+ sequence: event.increment.sequence,
40807
40866
  sessionId: command.sessionId,
40808
- text: increment.text
40867
+ text: event.increment.text
40809
40868
  };
40810
- publisher.publish(command.sessionId, recordLiveEvent(event));
40811
- },
40812
- AGENT_ACTIVITY_COALESCING_MILLISECONDS,
40813
- AGENT_TEXT_MAXIMUM_LENGTH
40814
- );
40815
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
40816
- if (activity2.status !== "pending" && activity2.status !== "running") {
40817
- narration.flush();
40869
+ publisher.publish(command.sessionId, recordLiveEvent(recorded));
40870
+ return;
40818
40871
  }
40819
- const event = daemonActivity(command, activity2);
40820
- publisher.publish(command.sessionId, recordLiveEvent(event));
40872
+ const activity2 = daemonActivity(command, event.activity);
40873
+ publisher.publish(command.sessionId, recordLiveEvent(activity2));
40821
40874
  });
40822
- const text2 = new CoalescingTextPublisher(
40823
- timer,
40824
- (messageId, delta) => {
40825
- publisher.publish(
40826
- command.sessionId,
40827
- recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
40828
- );
40829
- },
40830
- AGENT_TEXT_COALESCING_MILLISECONDS,
40831
- AGENT_TEXT_MAXIMUM_LENGTH
40832
- );
40833
40875
  try {
40834
40876
  const resolved = await resolveSessionDirectories(
40835
40877
  directories,
@@ -40918,15 +40960,9 @@ async function executePrompt({
40918
40960
  cwd: resolved.cwd,
40919
40961
  disposition: availability.disposition,
40920
40962
  images: attachments.images,
40921
- onActivity: activities.record,
40922
- onNarration: (increment) => {
40923
- narration.record(increment);
40924
- return Promise.resolve();
40925
- },
40926
- onText: (delta, messageId) => {
40927
- text2.record(messageId, delta);
40928
- return Promise.resolve();
40929
- },
40963
+ onActivity: events.recordActivity,
40964
+ onNarration: events.recordNarration,
40965
+ onText: events.recordText,
40930
40966
  prompt: command.prompt,
40931
40967
  resources: attachments.resources,
40932
40968
  sessionId: command.sessionId,
@@ -40935,9 +40971,7 @@ async function executePrompt({
40935
40971
  });
40936
40972
  stopReason = result.stopReason;
40937
40973
  }
40938
- text2.flush();
40939
- narration.flush();
40940
- activities.flush();
40974
+ events.flush();
40941
40975
  publisher.publish(command.sessionId, {
40942
40976
  commandId: command.commandId,
40943
40977
  kind: SESSION_COMPLETED_KIND,
@@ -40951,9 +40985,7 @@ async function executePrompt({
40951
40985
  sessionId: command.sessionId
40952
40986
  });
40953
40987
  } catch (error62) {
40954
- text2.flush();
40955
- narration.flush();
40956
- activities.flush();
40988
+ events.flush();
40957
40989
  if (signal.aborted && cancellationRequested()) {
40958
40990
  publisher.publish(command.sessionId, {
40959
40991
  commandId: command.commandId,