@moxt-ai/mobius 0.0.142 → 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 (46) 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 +339 -315
  13. package/dist/cli.js.map +4 -4
  14. package/dist/daemon-active-turn.d.ts +2 -0
  15. package/dist/daemon-active-turn.d.ts.map +1 -1
  16. package/dist/daemon-active-turn.js +80 -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/index.js +338 -314
  24. package/dist/index.js.map +4 -4
  25. package/dist/native-sessions/live-history-page.d.ts.map +1 -1
  26. package/dist/native-sessions/live-history-page.js +40 -24
  27. package/dist/native-sessions/live-history-page.js.map +1 -1
  28. package/dist/relay-connection/coalescing-agent-event-publisher.d.ts +32 -0
  29. package/dist/relay-connection/coalescing-agent-event-publisher.d.ts.map +1 -0
  30. package/dist/relay-connection/coalescing-agent-event-publisher.js +116 -0
  31. package/dist/relay-connection/coalescing-agent-event-publisher.js.map +1 -0
  32. package/dist/runtime.js +338 -314
  33. package/dist/runtime.js.map +4 -4
  34. package/package.json +1 -1
  35. package/dist/relay-connection/coalescing-activity-publisher.d.ts +0 -10
  36. package/dist/relay-connection/coalescing-activity-publisher.d.ts.map +0 -1
  37. package/dist/relay-connection/coalescing-activity-publisher.js +0 -54
  38. package/dist/relay-connection/coalescing-activity-publisher.js.map +0 -1
  39. package/dist/relay-connection/coalescing-narration-publisher.d.ts +0 -31
  40. package/dist/relay-connection/coalescing-narration-publisher.d.ts.map +0 -1
  41. package/dist/relay-connection/coalescing-narration-publisher.js +0 -61
  42. package/dist/relay-connection/coalescing-narration-publisher.js.map +0 -1
  43. package/dist/relay-connection/coalescing-text-publisher.d.ts +0 -26
  44. package/dist/relay-connection/coalescing-text-publisher.d.ts.map +0 -1
  45. package/dist/relay-connection/coalescing-text-publisher.js +0 -57
  46. 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,18 +37946,26 @@ 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;
37897
37970
  matchesInteraction = (interactionId, sessionId) => this.command.sessionId === sessionId && this.#interaction?.interactionId === interactionId;
37898
37971
  requestCancellation = () => {
@@ -40202,6 +40275,34 @@ function liveHistoryCoveredTurnRanges(history) {
40202
40275
  function historyMessageCharacters(message) {
40203
40276
  return message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0);
40204
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
+ }
40205
40306
  function paginateAcpSessionHistory(history, sessionId, cursor, limit) {
40206
40307
  if (history.status === "unavailable") {
40207
40308
  if (cursor !== null) {
@@ -40232,30 +40333,19 @@ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limi
40232
40333
  if (activeTurn === null || cursor !== null) {
40233
40334
  return paginateAcpSessionHistory(history, sessionId, cursor, limit);
40234
40335
  }
40235
- const activeMessageOverhead = 4;
40236
- const activeStructuredCharacters = JSON.stringify(activeTurn.activities).length + JSON.stringify(activeTurn.content).length;
40237
- const maximumActiveTextLength = Math.max(
40238
- 0,
40239
- SESSION_HISTORY_CHARACTER_LIMIT - activeTurn.prompt.length - activeStructuredCharacters - activeMessageOverhead
40240
- );
40241
- const activeText = activeTurn.text.slice(-maximumActiveTextLength);
40242
- const completeActiveMessages = [
40243
- { role: "user", text: activeTurn.prompt },
40244
- {
40245
- activities: activeTurn.activities,
40246
- content: activeTurn.content,
40247
- role: "assistant",
40248
- text: activeText
40249
- }
40250
- ];
40251
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
+ );
40252
40342
  return {
40253
40343
  coveredCommandIds: [],
40254
40344
  coveredMessageIds: [],
40255
- messages: completeActiveMessages,
40345
+ messages: [{ role: "user", text: activeTurn.prompt }, ...bounded3.messages],
40256
40346
  nextCursor: null,
40257
40347
  status: "available",
40258
- truncated: activeTurn.truncated || activeText.length !== activeTurn.text.length
40348
+ truncated: activeTurn.truncated || bounded3.truncated
40259
40349
  };
40260
40350
  }
40261
40351
  const activeUserIndex = history.coveredCommandIds.includes(activeTurn.commandId) ? history.messages.findLastIndex((message) => message.role === "user") : -1;
@@ -40270,9 +40360,18 @@ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limi
40270
40360
  };
40271
40361
  }
40272
40362
  const latestNativeMessage = history.messages.at(-1);
40273
- 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
+ ];
40274
40373
  let historicalMessageCount = 0;
40275
- 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);
40276
40375
  const historicalMessageLimit = Math.max(0, limit - activeMessages.length);
40277
40376
  for (let index = history.messages.length - 1; index >= 0 && historicalMessageCount < historicalMessageLimit; index -= 1) {
40278
40377
  const message = history.messages[index];
@@ -40297,7 +40396,7 @@ function paginateLiveSessionHistory(history, activeTurn, sessionId, cursor, limi
40297
40396
  return {
40298
40397
  ...page,
40299
40398
  messages: [...page.messages, ...activeMessages],
40300
- truncated: page.truncated || activeTurn.truncated || activeText.length !== activeTurn.text.length
40399
+ truncated: page.truncated || activeTurn.truncated || bounded2.truncated
40301
40400
  };
40302
40401
  }
40303
40402
  function mergeLiveSessionHistory(history, activeTurn, sessionId) {
@@ -40607,167 +40706,113 @@ function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selecti
40607
40706
  `);
40608
40707
  }
40609
40708
 
40610
- // src/relay-connection/coalescing-activity-publisher.ts
40611
- var AGENT_ACTIVITY_COALESCING_MILLISECONDS = 100;
40612
- var CoalescingDaemonActivityPublisher = class {
40613
- #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 = [];
40614
40714
  #publish;
40615
40715
  #publishedActivityIds = /* @__PURE__ */ new Set();
40616
- #scheduled = /* @__PURE__ */ new Map();
40716
+ #scheduled = null;
40617
40717
  #timer;
40618
40718
  constructor(timer, publish) {
40619
40719
  this.#publish = publish;
40620
40720
  this.#timer = timer;
40621
40721
  }
40622
- flush = () => {
40623
- const activities = [...this.#pending.values()].sort((left, right) => left.sequence - right.sequence);
40624
- for (const task of this.#scheduled.values()) {
40625
- task.cancel();
40626
- }
40627
- this.#pending.clear();
40628
- this.#scheduled.clear();
40629
- for (const activity2 of activities) {
40630
- this.#publish(activity2);
40631
- }
40632
- };
40633
- record = (activity2) => {
40634
- if (activity2.status !== "pending" && activity2.status !== "running") {
40635
- this.#discardPending(activity2.activityId);
40636
- this.#publishedActivityIds.add(activity2.activityId);
40637
- this.#publish(activity2);
40638
- return Promise.resolve();
40639
- }
40640
- if (!this.#publishedActivityIds.has(activity2.activityId)) {
40641
- this.#publishedActivityIds.add(activity2.activityId);
40642
- this.#publish(activity2);
40643
- return Promise.resolve();
40644
- }
40645
- this.#pending.set(activity2.activityId, activity2);
40646
- if (!this.#scheduled.has(activity2.activityId)) {
40647
- this.#scheduled.set(
40648
- activity2.activityId,
40649
- this.#timer.schedule(
40650
- () => this.#flushActivity(activity2.activityId),
40651
- AGENT_ACTIVITY_COALESCING_MILLISECONDS
40652
- )
40653
- );
40654
- }
40655
- return Promise.resolve();
40656
- };
40657
- #discardPending = (activityId) => {
40658
- this.#scheduled.get(activityId)?.cancel();
40659
- this.#scheduled.delete(activityId);
40660
- this.#pending.delete(activityId);
40661
- };
40662
- #flushActivity = (activityId) => {
40663
- const activity2 = this.#pending.get(activityId);
40664
- this.#discardPending(activityId);
40665
- if (activity2 !== void 0) {
40666
- this.#publish(activity2);
40667
- }
40668
- };
40669
- };
40670
-
40671
- // src/relay-connection/coalescing-narration-publisher.ts
40672
- var CoalescingNarrationPublisher = class {
40673
- #coalescingMilliseconds;
40674
- #maximumTextLength;
40675
- #publish;
40676
- #timer;
40677
- #pending = /* @__PURE__ */ new Map();
40678
- #scheduled = null;
40679
- constructor(timer, publish, coalescingMilliseconds, maximumTextLength) {
40680
- this.#publish = publish;
40681
- this.#timer = timer;
40682
- this.#coalescingMilliseconds = coalescingMilliseconds;
40683
- this.#maximumTextLength = maximumTextLength;
40684
- }
40685
- /** Emit every buffered increment now, cancelling the pending flush. */
40686
40722
  flush = () => {
40687
40723
  this.#scheduled?.cancel();
40688
40724
  this.#scheduled = null;
40689
- const increments = [...this.#pending.entries()].map(
40690
- ([activityId, pending]) => ({
40691
- activityId,
40692
- activityType: pending.activityType,
40693
- sequence: pending.sequence,
40694
- text: pending.text
40695
- })
40696
- );
40697
- this.#pending.clear();
40698
- for (const increment of increments) {
40699
- this.#publish(increment);
40725
+ const entries = this.#entries;
40726
+ this.#entries = [];
40727
+ for (const entry of entries) {
40728
+ this.#publish(entry);
40700
40729
  }
40701
40730
  };
40702
- /**
40703
- * Buffer an increment, emitting the buffered text when it would exceed the
40704
- * protocol's per-event text limit so no event is rejected by the codec.
40705
- */
40706
- record = (increment) => {
40707
- if (increment.text.length === 0) {
40708
- return;
40709
- }
40710
- const previous = this.#pending.get(increment.activityId);
40711
- 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") {
40712
40737
  this.flush();
40738
+ } else {
40739
+ this.schedule();
40713
40740
  }
40714
- const current = this.#pending.get(increment.activityId);
40715
- this.#pending.set(increment.activityId, {
40716
- activityType: increment.activityType,
40717
- sequence: increment.sequence,
40718
- text: `${current?.text ?? ""}${increment.text}`
40719
- });
40720
- this.#scheduled ??= this.#timer.schedule(this.flush, this.#coalescingMilliseconds);
40741
+ return Promise.resolve();
40721
40742
  };
40722
- };
40723
-
40724
- // src/relay-connection/coalescing-text-publisher.ts
40725
- var CoalescingTextPublisher = class {
40726
- #coalescingMilliseconds;
40727
- #maximumTextLength;
40728
- #publish;
40729
- #timer;
40730
- #messageId = "";
40731
- #scheduled = null;
40732
- #text = "";
40733
- constructor(timer, publish, coalescingMilliseconds, maximumTextLength) {
40734
- this.#publish = publish;
40735
- this.#timer = timer;
40736
- this.#coalescingMilliseconds = coalescingMilliseconds;
40737
- this.#maximumTextLength = maximumTextLength;
40738
- }
40739
- /** Emit any buffered text now, cancelling the pending flush. */
40740
- flush = () => {
40741
- this.#scheduled?.cancel();
40742
- this.#scheduled = null;
40743
- const messageId = this.#messageId;
40744
- const text2 = this.#text;
40745
- this.#messageId = "";
40746
- this.#text = "";
40747
- if (text2.length > 0) {
40748
- 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);
40749
40775
  }
40776
+ this.schedule();
40777
+ return Promise.resolve();
40750
40778
  };
40751
- /**
40752
- * Buffer a chunk, emitting the buffered text when the message changes or the
40753
- * buffer would exceed the protocol's per-event text limit.
40754
- */
40755
- record = (messageId, text2) => {
40779
+ recordText = (text2, messageId) => {
40756
40780
  if (text2.length === 0) {
40757
- return;
40781
+ return Promise.resolve();
40758
40782
  }
40759
- if (this.#text.length > 0 && (this.#messageId !== messageId || this.#text.length + text2.length > this.#maximumTextLength)) {
40760
- 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);
40761
40806
  }
40762
- this.#messageId = messageId;
40763
- this.#text = `${this.#text}${text2}`;
40764
- this.#scheduled ??= this.#timer.schedule(this.flush, this.#coalescingMilliseconds);
40807
+ this.schedule();
40808
+ return Promise.resolve();
40765
40809
  };
40810
+ schedule() {
40811
+ this.#scheduled ??= this.#timer.schedule(this.flush, AGENT_EVENT_COALESCING_MILLISECONDS);
40812
+ }
40766
40813
  };
40767
40814
 
40768
40815
  // src/daemon-prompt-executor.ts
40769
- var AGENT_TEXT_COALESCING_MILLISECONDS = 100;
40770
- var AGENT_TEXT_MAXIMUM_LENGTH = 1e5;
40771
40816
  function daemonActivity(command, activity2) {
40772
40817
  return {
40773
40818
  activityId: activity2.activityId,
@@ -40803,41 +40848,30 @@ async function executePrompt({
40803
40848
  recordLiveEvent,
40804
40849
  cancellationRequested
40805
40850
  }) {
40806
- const narration = new CoalescingNarrationPublisher(
40807
- timer,
40808
- (increment) => {
40809
- const event = {
40810
- activityId: increment.activityId,
40811
- 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,
40812
40863
  commandId: command.commandId,
40813
40864
  kind: AGENT_ACTIVITY_NARRATION_KIND,
40814
- sequence: increment.sequence,
40865
+ sequence: event.increment.sequence,
40815
40866
  sessionId: command.sessionId,
40816
- text: increment.text
40867
+ text: event.increment.text
40817
40868
  };
40818
- publisher.publish(command.sessionId, recordLiveEvent(event));
40819
- },
40820
- AGENT_ACTIVITY_COALESCING_MILLISECONDS,
40821
- AGENT_TEXT_MAXIMUM_LENGTH
40822
- );
40823
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity2) => {
40824
- if (activity2.status !== "pending" && activity2.status !== "running") {
40825
- narration.flush();
40869
+ publisher.publish(command.sessionId, recordLiveEvent(recorded));
40870
+ return;
40826
40871
  }
40827
- const event = daemonActivity(command, activity2);
40828
- publisher.publish(command.sessionId, recordLiveEvent(event));
40872
+ const activity2 = daemonActivity(command, event.activity);
40873
+ publisher.publish(command.sessionId, recordLiveEvent(activity2));
40829
40874
  });
40830
- const text2 = new CoalescingTextPublisher(
40831
- timer,
40832
- (messageId, delta) => {
40833
- publisher.publish(
40834
- command.sessionId,
40835
- recordLiveEvent({ kind: AGENT_MESSAGE_DELTA_KIND, messageId, text: delta })
40836
- );
40837
- },
40838
- AGENT_TEXT_COALESCING_MILLISECONDS,
40839
- AGENT_TEXT_MAXIMUM_LENGTH
40840
- );
40841
40875
  try {
40842
40876
  const resolved = await resolveSessionDirectories(
40843
40877
  directories,
@@ -40926,15 +40960,9 @@ async function executePrompt({
40926
40960
  cwd: resolved.cwd,
40927
40961
  disposition: availability.disposition,
40928
40962
  images: attachments.images,
40929
- onActivity: activities.record,
40930
- onNarration: (increment) => {
40931
- narration.record(increment);
40932
- return Promise.resolve();
40933
- },
40934
- onText: (delta, messageId) => {
40935
- text2.record(messageId, delta);
40936
- return Promise.resolve();
40937
- },
40963
+ onActivity: events.recordActivity,
40964
+ onNarration: events.recordNarration,
40965
+ onText: events.recordText,
40938
40966
  prompt: command.prompt,
40939
40967
  resources: attachments.resources,
40940
40968
  sessionId: command.sessionId,
@@ -40943,9 +40971,7 @@ async function executePrompt({
40943
40971
  });
40944
40972
  stopReason = result.stopReason;
40945
40973
  }
40946
- text2.flush();
40947
- narration.flush();
40948
- activities.flush();
40974
+ events.flush();
40949
40975
  publisher.publish(command.sessionId, {
40950
40976
  commandId: command.commandId,
40951
40977
  kind: SESSION_COMPLETED_KIND,
@@ -40959,9 +40985,7 @@ async function executePrompt({
40959
40985
  sessionId: command.sessionId
40960
40986
  });
40961
40987
  } catch (error62) {
40962
- text2.flush();
40963
- narration.flush();
40964
- activities.flush();
40988
+ events.flush();
40965
40989
  if (signal.aborted && cancellationRequested()) {
40966
40990
  publisher.publish(command.sessionId, {
40967
40991
  commandId: command.commandId,