@moxt-ai/mobius 0.0.155 → 0.0.157

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 (75) hide show
  1. package/dist/acp/agent-query-processes.d.ts +2 -1
  2. package/dist/acp/agent-query-processes.d.ts.map +1 -1
  3. package/dist/acp/agent-query-processes.js +7 -1
  4. package/dist/acp/agent-query-processes.js.map +1 -1
  5. package/dist/acp/agent-runtime-manager.d.ts +4 -2
  6. package/dist/acp/agent-runtime-manager.d.ts.map +1 -1
  7. package/dist/acp/agent-runtime-manager.js +19 -0
  8. package/dist/acp/agent-runtime-manager.js.map +1 -1
  9. package/dist/acp/agent-session.d.ts +2 -1
  10. package/dist/acp/agent-session.d.ts.map +1 -1
  11. package/dist/acp/agent-session.js +30 -3
  12. package/dist/acp/agent-session.js.map +1 -1
  13. package/dist/acp/session-contracts.d.ts +9 -1
  14. package/dist/acp/session-contracts.d.ts.map +1 -1
  15. package/dist/acp/session-contracts.js +1 -0
  16. package/dist/acp/session-contracts.js.map +1 -1
  17. package/dist/acp/session-history.d.ts +3 -2
  18. package/dist/acp/session-history.d.ts.map +1 -1
  19. package/dist/acp/session-history.js +17 -1
  20. package/dist/acp/session-history.js.map +1 -1
  21. package/dist/acp/session-store.d.ts +13 -0
  22. package/dist/acp/session-store.d.ts.map +1 -1
  23. package/dist/acp/session-store.js +65 -3
  24. package/dist/acp/session-store.js.map +1 -1
  25. package/dist/cli.js +1171 -105
  26. package/dist/cli.js.map +4 -4
  27. package/dist/daemon-command-handler.d.ts +3 -1
  28. package/dist/daemon-command-handler.d.ts.map +1 -1
  29. package/dist/daemon-command-handler.js +13 -4
  30. package/dist/daemon-command-handler.js.map +1 -1
  31. package/dist/daemon-history-commands.d.ts +2 -1
  32. package/dist/daemon-history-commands.d.ts.map +1 -1
  33. package/dist/daemon-history-commands.js +55 -1
  34. package/dist/daemon-history-commands.js.map +1 -1
  35. package/dist/daemon-observers.d.ts +3 -2
  36. package/dist/daemon-observers.d.ts.map +1 -1
  37. package/dist/daemon-observers.js +23 -1
  38. package/dist/daemon-observers.js.map +1 -1
  39. package/dist/daemon-prompt-executor.d.ts +3 -1
  40. package/dist/daemon-prompt-executor.d.ts.map +1 -1
  41. package/dist/daemon-prompt-executor.js +9 -3
  42. package/dist/daemon-prompt-executor.js.map +1 -1
  43. package/dist/daemon-turn-registry.d.ts +13 -13
  44. package/dist/generated/acp-session-store-migrations.d.ts +3 -0
  45. package/dist/generated/acp-session-store-migrations.d.ts.map +1 -1
  46. package/dist/generated/acp-session-store-migrations.js +5 -1
  47. package/dist/generated/acp-session-store-migrations.js.map +1 -1
  48. package/dist/index.js +1154 -88
  49. package/dist/index.js.map +4 -4
  50. package/dist/relay-connection/run-relay-connection.d.ts +3 -1
  51. package/dist/relay-connection/run-relay-connection.d.ts.map +1 -1
  52. package/dist/relay-connection/run-relay-connection.js +2 -1
  53. package/dist/relay-connection/run-relay-connection.js.map +1 -1
  54. package/dist/relay-connection/session-event-publisher.d.ts +2 -1
  55. package/dist/relay-connection/session-event-publisher.d.ts.map +1 -1
  56. package/dist/relay-connection/session-event-publisher.js +18 -1
  57. package/dist/relay-connection/session-event-publisher.js.map +1 -1
  58. package/dist/run-daemon.d.ts.map +1 -1
  59. package/dist/run-daemon.js +4 -1
  60. package/dist/run-daemon.js.map +1 -1
  61. package/dist/runtime.js +1150 -84
  62. package/dist/runtime.js.map +4 -4
  63. package/dist/schema/acp-session-store/index.d.ts +1 -0
  64. package/dist/schema/acp-session-store/index.d.ts.map +1 -1
  65. package/dist/schema/acp-session-store/index.js +1 -0
  66. package/dist/schema/acp-session-store/index.js.map +1 -1
  67. package/dist/schema/acp-session-store/session-event-v2.d.ts +82 -0
  68. package/dist/schema/acp-session-store/session-event-v2.d.ts.map +1 -0
  69. package/dist/schema/acp-session-store/session-event-v2.js +11 -0
  70. package/dist/schema/acp-session-store/session-event-v2.js.map +1 -0
  71. package/dist/session-event-log-v2.d.ts +15 -0
  72. package/dist/session-event-log-v2.d.ts.map +1 -0
  73. package/dist/session-event-log-v2.js +257 -0
  74. package/dist/session-event-log-v2.js.map +1 -0
  75. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -2340,11 +2340,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
2340
2340
  };
2341
2341
  this._checkNumberOfArguments();
2342
2342
  const processedArgs = [];
2343
- this.registeredArguments.forEach((declaredArg, index) => {
2343
+ this.registeredArguments.forEach((declaredArg, index2) => {
2344
2344
  let value = declaredArg.defaultValue;
2345
2345
  if (declaredArg.variadic) {
2346
- if (index < this.args.length) {
2347
- value = this.args.slice(index);
2346
+ if (index2 < this.args.length) {
2347
+ value = this.args.slice(index2);
2348
2348
  if (declaredArg.parseArg) {
2349
2349
  value = value.reduce((processed, v) => {
2350
2350
  return myParseArg(declaredArg, v, processed);
@@ -2353,13 +2353,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
2353
2353
  } else if (value === void 0) {
2354
2354
  value = [];
2355
2355
  }
2356
- } else if (index < this.args.length) {
2357
- value = this.args[index];
2356
+ } else if (index2 < this.args.length) {
2357
+ value = this.args[index2];
2358
2358
  if (declaredArg.parseArg) {
2359
2359
  value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2360
2360
  }
2361
2361
  }
2362
- processedArgs[index] = value;
2362
+ processedArgs[index2] = value;
2363
2363
  });
2364
2364
  this.processedArgs = processedArgs;
2365
2365
  }
@@ -2653,10 +2653,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2653
2653
  }
2654
2654
  }
2655
2655
  if (/^--[^=]+=/.test(arg)) {
2656
- const index = arg.indexOf("=");
2657
- const option = this._findOption(arg.slice(0, index));
2656
+ const index2 = arg.indexOf("=");
2657
+ const option = this._findOption(arg.slice(0, index2));
2658
2658
  if (option && (option.required || option.optional)) {
2659
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
2659
+ this.emit(`option:${option.name()}`, arg.slice(index2 + 1));
2660
2660
  continue;
2661
2661
  }
2662
2662
  }
@@ -3381,7 +3381,7 @@ var program = new Command();
3381
3381
  // package.json
3382
3382
  var package_default = {
3383
3383
  name: "@moxt-ai/mobius",
3384
- version: "0.0.155",
3384
+ version: "0.0.157",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -8316,11 +8316,11 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
8316
8316
  return payload;
8317
8317
  };
8318
8318
  });
8319
- function handleArrayResult(result, final, index) {
8319
+ function handleArrayResult(result, final, index2) {
8320
8320
  if (result.issues.length) {
8321
- final.issues.push(...prefixIssues(index, result.issues));
8321
+ final.issues.push(...prefixIssues(index2, result.issues));
8322
8322
  }
8323
- final.value[index] = result.value;
8323
+ final.value[index2] = result.value;
8324
8324
  }
8325
8325
  var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
8326
8326
  $ZodType.init(inst, def);
@@ -8931,14 +8931,14 @@ function mergeValues(a, b) {
8931
8931
  return { valid: false, mergeErrorPath: [] };
8932
8932
  }
8933
8933
  const newArray = [];
8934
- for (let index = 0; index < a.length; index++) {
8935
- const itemA = a[index];
8936
- const itemB = b[index];
8934
+ for (let index2 = 0; index2 < a.length; index2++) {
8935
+ const itemA = a[index2];
8936
+ const itemB = b[index2];
8937
8937
  const sharedValue = mergeValues(itemA, itemB);
8938
8938
  if (!sharedValue.valid) {
8939
8939
  return {
8940
8940
  valid: false,
8941
- mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
8941
+ mergeErrorPath: [index2, ...sharedValue.mergeErrorPath]
8942
8942
  };
8943
8943
  }
8944
8944
  newArray.push(sharedValue.data);
@@ -9089,11 +9089,11 @@ function getTupleOptStart(items, key) {
9089
9089
  }
9090
9090
  return 0;
9091
9091
  }
9092
- function handleTupleResult(result, final, index) {
9092
+ function handleTupleResult(result, final, index2) {
9093
9093
  if (result.issues.length) {
9094
- final.issues.push(...prefixIssues(index, result.issues));
9094
+ final.issues.push(...prefixIssues(index2, result.issues));
9095
9095
  }
9096
- final.value[index] = result.value;
9096
+ final.value[index2] = result.value;
9097
9097
  }
9098
9098
  function handleTupleResults(itemResults, final, items, input2, optoutStart) {
9099
9099
  for (let i = 0; i < items.length; i++) {
@@ -23774,7 +23774,7 @@ function detectVersion(schema, defaultTarget) {
23774
23774
  return defaultTarget ?? "draft-2020-12";
23775
23775
  }
23776
23776
  function applyMinItems(items, minItems) {
23777
- return items.map((item, index) => index < minItems ? item : item.optional());
23777
+ return items.map((item, index2) => index2 < minItems ? item : item.optional());
23778
23778
  }
23779
23779
  function decodeJSONPointerSegment(segment) {
23780
23780
  return segment.replace(/~1/g, "/").replace(/~0/g, "~");
@@ -27822,9 +27822,9 @@ function comparePrerelease(left, right) {
27822
27822
  if (left.length === 0 || right.length === 0) {
27823
27823
  return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
27824
27824
  }
27825
- for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
27826
- const leftPart = left[index];
27827
- const rightPart = right[index];
27825
+ for (let index2 = 0; index2 < Math.max(left.length, right.length); index2 += 1) {
27826
+ const leftPart = left[index2];
27827
+ const rightPart = right[index2];
27828
27828
  if (leftPart === void 0 || rightPart === void 0) {
27829
27829
  return leftPart === rightPart ? 0 : leftPart === void 0 ? -1 : 1;
27830
27830
  }
@@ -27849,8 +27849,8 @@ function compareAgentVersions(left, right) {
27849
27849
  if (parsedLeft === null || parsedRight === null) {
27850
27850
  return null;
27851
27851
  }
27852
- for (let index = 0; index < Math.max(parsedLeft.core.length, parsedRight.core.length); index += 1) {
27853
- const difference = (parsedLeft.core[index] ?? 0) - (parsedRight.core[index] ?? 0);
27852
+ for (let index2 = 0; index2 < Math.max(parsedLeft.core.length, parsedRight.core.length); index2 += 1) {
27853
+ const difference = (parsedLeft.core[index2] ?? 0) - (parsedRight.core[index2] ?? 0);
27854
27854
  if (difference !== 0) {
27855
27855
  return Math.sign(difference);
27856
27856
  }
@@ -28597,12 +28597,12 @@ var DEFAULT_AGENT_EXECUTION_CONFIGURATION = Object.freeze({
28597
28597
  });
28598
28598
  var sessionConfigurationSelectionsSchema = external_exports.array(sessionConfigurationSelectionSchema).max(100).superRefine((selections, context) => {
28599
28599
  const identifiers = /* @__PURE__ */ new Set();
28600
- for (const [index, selection] of selections.entries()) {
28600
+ for (const [index2, selection] of selections.entries()) {
28601
28601
  if (identifiers.has(selection.configId)) {
28602
28602
  context.addIssue({
28603
28603
  code: "custom",
28604
28604
  message: "Session configuration identifiers must be unique",
28605
- path: [index, "configId"]
28605
+ path: [index2, "configId"]
28606
28606
  });
28607
28607
  }
28608
28608
  identifiers.add(selection.configId);
@@ -29804,6 +29804,443 @@ var encodeNativeSessionResult = (value) => JSON.stringify(nativeSessionResultSch
29804
29804
  var decodeNativeSessionCancel = (encoded) => decode4(nativeSessionCancelSchema, encoded);
29805
29805
  var encodeNativeSessionCancel = (value) => JSON.stringify(nativeSessionCancelSchema.parse(value));
29806
29806
 
29807
+ // ../protocol/src/session-event-log-v2.ts
29808
+ var MAX_EVENT_COUNT = 1e4;
29809
+ var MAX_COLLECTION_SIZE = 1e3;
29810
+ var MAX_CONTENT_LENGTH = 1e6;
29811
+ var MAX_JSON_DEPTH = 16;
29812
+ var MAX_JSON_KEYS = 1e3;
29813
+ var SESSION_EVENT_V2_KIND = "session.event.v2";
29814
+ var boundedString = external_exports.string().max(MAX_CONTENT_LENGTH);
29815
+ var shortString = external_exports.string().max(2048);
29816
+ function boundedJsonIssue(value, depth = 0) {
29817
+ if (depth > MAX_JSON_DEPTH) {
29818
+ return "JSON nesting exceeds the maximum depth";
29819
+ }
29820
+ if (typeof value === "string") {
29821
+ return value.length <= MAX_CONTENT_LENGTH ? null : "JSON string exceeds the maximum length";
29822
+ }
29823
+ if (typeof value === "number") {
29824
+ return Number.isFinite(value) ? null : "JSON number must be finite";
29825
+ }
29826
+ if (typeof value === "boolean" || value === null) {
29827
+ return null;
29828
+ }
29829
+ if (Array.isArray(value)) {
29830
+ if (value.length > MAX_COLLECTION_SIZE) {
29831
+ return "JSON array exceeds the maximum length";
29832
+ }
29833
+ for (const item of value) {
29834
+ const issue2 = boundedJsonIssue(item, depth + 1);
29835
+ if (issue2 !== null) {
29836
+ return issue2;
29837
+ }
29838
+ }
29839
+ return null;
29840
+ }
29841
+ if (typeof value === "object" && value !== void 0) {
29842
+ const entries = Object.entries(value);
29843
+ if (entries.length > MAX_JSON_KEYS) {
29844
+ return "JSON object exceeds the maximum key count";
29845
+ }
29846
+ for (const [key, item] of entries) {
29847
+ if (key.length > 255) {
29848
+ return "JSON key exceeds the maximum length";
29849
+ }
29850
+ const issue2 = boundedJsonIssue(item, depth + 1);
29851
+ if (issue2 !== null) {
29852
+ return issue2;
29853
+ }
29854
+ }
29855
+ return null;
29856
+ }
29857
+ return "Value is not bounded JSON";
29858
+ }
29859
+ var boundedJsonSchema = external_exports.unknown().superRefine((value, context) => {
29860
+ const issue2 = boundedJsonIssue(value);
29861
+ if (issue2 !== null) {
29862
+ context.addIssue({ code: "custom", message: issue2 });
29863
+ }
29864
+ });
29865
+ var metadataSchema = external_exports.record(external_exports.string().max(255), boundedJsonSchema).readonly();
29866
+ var optionalMetadata = metadataSchema.nullable().optional();
29867
+ var annotationsSchema = external_exports.strictObject({
29868
+ _meta: optionalMetadata,
29869
+ audience: external_exports.array(external_exports.enum(["assistant", "user"])).max(2).readonly().nullable().optional(),
29870
+ lastModified: shortString.nullable().optional(),
29871
+ priority: external_exports.number().finite().nullable().optional()
29872
+ }).readonly();
29873
+ var contentFields = { _meta: optionalMetadata, annotations: annotationsSchema.nullable().optional() };
29874
+ var textContentSchema = external_exports.strictObject({ ...contentFields, text: boundedString, type: external_exports.literal("text") }).readonly();
29875
+ var imageContentSchema = external_exports.strictObject({
29876
+ ...contentFields,
29877
+ data: boundedString,
29878
+ mimeType: shortString,
29879
+ type: external_exports.literal("image"),
29880
+ uri: boundedString.nullable().optional()
29881
+ }).readonly();
29882
+ var audioContentSchema = external_exports.strictObject({ ...contentFields, data: boundedString, mimeType: shortString, type: external_exports.literal("audio") }).readonly();
29883
+ var resourceLinkSchema = external_exports.strictObject({
29884
+ ...contentFields,
29885
+ description: boundedString.nullable().optional(),
29886
+ mimeType: shortString.nullable().optional(),
29887
+ name: shortString,
29888
+ size: external_exports.number().int().nonnegative().safe().nullable().optional(),
29889
+ title: shortString.nullable().optional(),
29890
+ type: external_exports.literal("resource_link"),
29891
+ uri: boundedString
29892
+ }).readonly();
29893
+ var textResourceSchema = external_exports.strictObject({
29894
+ _meta: optionalMetadata,
29895
+ mimeType: shortString.nullable().optional(),
29896
+ text: boundedString,
29897
+ uri: boundedString
29898
+ }).readonly();
29899
+ var blobResourceSchema = external_exports.strictObject({
29900
+ _meta: optionalMetadata,
29901
+ blob: boundedString,
29902
+ mimeType: shortString.nullable().optional(),
29903
+ uri: boundedString
29904
+ }).readonly();
29905
+ var embeddedResourceSchema = external_exports.strictObject({
29906
+ ...contentFields,
29907
+ resource: external_exports.union([textResourceSchema, blobResourceSchema]),
29908
+ type: external_exports.literal("resource")
29909
+ }).readonly();
29910
+ var contentBlockV2Schema = external_exports.discriminatedUnion("type", [
29911
+ textContentSchema,
29912
+ imageContentSchema,
29913
+ audioContentSchema,
29914
+ resourceLinkSchema,
29915
+ embeddedResourceSchema
29916
+ ]);
29917
+ var toolCallContentSchema = external_exports.discriminatedUnion("type", [
29918
+ external_exports.strictObject({ _meta: optionalMetadata, content: contentBlockV2Schema, type: external_exports.literal("content") }).readonly(),
29919
+ external_exports.strictObject({
29920
+ _meta: optionalMetadata,
29921
+ newText: boundedString,
29922
+ oldText: boundedString.nullable().optional(),
29923
+ path: boundedString,
29924
+ type: external_exports.literal("diff")
29925
+ }).readonly(),
29926
+ external_exports.strictObject({ _meta: optionalMetadata, terminalId: shortString, type: external_exports.literal("terminal") }).readonly()
29927
+ ]);
29928
+ var toolCallLocationSchema = external_exports.strictObject({
29929
+ _meta: optionalMetadata,
29930
+ line: external_exports.number().int().nonnegative().safe().nullable().optional(),
29931
+ path: boundedString
29932
+ }).readonly();
29933
+ var toolKindSchema = external_exports.enum([
29934
+ "read",
29935
+ "edit",
29936
+ "delete",
29937
+ "move",
29938
+ "search",
29939
+ "execute",
29940
+ "think",
29941
+ "fetch",
29942
+ "switch_mode",
29943
+ "other"
29944
+ ]);
29945
+ var toolStatusSchema = external_exports.enum(["pending", "in_progress", "completed", "failed"]);
29946
+ var toolPatchFields = {
29947
+ _meta: optionalMetadata,
29948
+ content: external_exports.array(toolCallContentSchema).max(MAX_COLLECTION_SIZE).readonly().nullable().optional(),
29949
+ kind: toolKindSchema.nullable().optional(),
29950
+ locations: external_exports.array(toolCallLocationSchema).max(MAX_COLLECTION_SIZE).readonly().nullable().optional(),
29951
+ name: shortString.nullable().optional(),
29952
+ rawInput: boundedJsonSchema.optional(),
29953
+ rawOutput: boundedJsonSchema.optional(),
29954
+ status: toolStatusSchema.nullable().optional(),
29955
+ title: boundedString.nullable().optional()
29956
+ };
29957
+ var planEntrySchema = external_exports.strictObject({
29958
+ _meta: optionalMetadata,
29959
+ content: boundedString,
29960
+ priority: external_exports.enum(["high", "medium", "low"]),
29961
+ status: external_exports.enum(["pending", "in_progress", "completed"])
29962
+ }).readonly();
29963
+ var planContentSchema = external_exports.discriminatedUnion("type", [
29964
+ external_exports.strictObject({
29965
+ _meta: optionalMetadata,
29966
+ entries: external_exports.array(planEntrySchema).max(MAX_COLLECTION_SIZE).readonly(),
29967
+ planId: shortString,
29968
+ type: external_exports.literal("items")
29969
+ }).readonly(),
29970
+ external_exports.strictObject({ _meta: optionalMetadata, planId: shortString, type: external_exports.literal("file"), uri: boundedString }).readonly(),
29971
+ external_exports.strictObject({
29972
+ _meta: optionalMetadata,
29973
+ content: boundedString,
29974
+ planId: shortString,
29975
+ type: external_exports.literal("markdown")
29976
+ }).readonly()
29977
+ ]);
29978
+ var commandSchema = external_exports.strictObject({
29979
+ _meta: optionalMetadata,
29980
+ description: boundedString,
29981
+ input: external_exports.strictObject({ _meta: optionalMetadata, hint: boundedString }).readonly().nullable().optional(),
29982
+ name: shortString
29983
+ }).readonly();
29984
+ var configSelectOptionSchema = external_exports.strictObject({
29985
+ _meta: optionalMetadata,
29986
+ description: boundedString.nullable().optional(),
29987
+ name: shortString,
29988
+ value: shortString
29989
+ }).readonly();
29990
+ var configSelectGroupSchema = external_exports.strictObject({
29991
+ _meta: optionalMetadata,
29992
+ group: shortString,
29993
+ name: shortString,
29994
+ options: external_exports.array(configSelectOptionSchema).max(MAX_COLLECTION_SIZE).readonly()
29995
+ }).readonly();
29996
+ var configBaseFields = {
29997
+ _meta: optionalMetadata,
29998
+ category: shortString.nullable().optional(),
29999
+ description: boundedString.nullable().optional(),
30000
+ id: shortString,
30001
+ name: shortString
30002
+ };
30003
+ var sessionConfigOptionSchema2 = external_exports.discriminatedUnion("type", [
30004
+ external_exports.strictObject({
30005
+ ...configBaseFields,
30006
+ currentValue: shortString,
30007
+ options: external_exports.union([
30008
+ external_exports.array(configSelectOptionSchema).max(MAX_COLLECTION_SIZE).readonly(),
30009
+ external_exports.array(configSelectGroupSchema).max(MAX_COLLECTION_SIZE).readonly()
30010
+ ]),
30011
+ type: external_exports.literal("select")
30012
+ }).readonly(),
30013
+ external_exports.strictObject({ ...configBaseFields, currentValue: external_exports.boolean(), type: external_exports.literal("boolean") }).readonly()
30014
+ ]);
30015
+ var contentChunkFields = {
30016
+ _meta: optionalMetadata,
30017
+ content: contentBlockV2Schema,
30018
+ messageId: shortString.nullable().optional()
30019
+ };
30020
+ var acpSessionUpdateV2Schema = external_exports.discriminatedUnion("sessionUpdate", [
30021
+ external_exports.strictObject({ ...contentChunkFields, sessionUpdate: external_exports.literal("user_message_chunk") }).readonly(),
30022
+ external_exports.strictObject({ ...contentChunkFields, sessionUpdate: external_exports.literal("agent_message_chunk") }).readonly(),
30023
+ external_exports.strictObject({ ...contentChunkFields, sessionUpdate: external_exports.literal("agent_thought_chunk") }).readonly(),
30024
+ external_exports.strictObject({
30025
+ _meta: optionalMetadata,
30026
+ content: external_exports.array(toolCallContentSchema).max(MAX_COLLECTION_SIZE).readonly().optional(),
30027
+ kind: toolKindSchema.optional(),
30028
+ locations: external_exports.array(toolCallLocationSchema).max(MAX_COLLECTION_SIZE).readonly().optional(),
30029
+ name: shortString.nullable().optional(),
30030
+ rawInput: boundedJsonSchema.optional(),
30031
+ rawOutput: boundedJsonSchema.optional(),
30032
+ sessionUpdate: external_exports.literal("tool_call"),
30033
+ status: toolStatusSchema.optional(),
30034
+ title: boundedString,
30035
+ toolCallId: shortString
30036
+ }).readonly(),
30037
+ external_exports.strictObject({ ...toolPatchFields, sessionUpdate: external_exports.literal("tool_call_update"), toolCallId: shortString }).readonly(),
30038
+ external_exports.strictObject({
30039
+ _meta: optionalMetadata,
30040
+ entries: external_exports.array(planEntrySchema).max(MAX_COLLECTION_SIZE).readonly(),
30041
+ sessionUpdate: external_exports.literal("plan")
30042
+ }).readonly(),
30043
+ external_exports.strictObject({ _meta: optionalMetadata, plan: planContentSchema, sessionUpdate: external_exports.literal("plan_update") }).readonly(),
30044
+ external_exports.strictObject({ _meta: optionalMetadata, planId: shortString, sessionUpdate: external_exports.literal("plan_removed") }).readonly(),
30045
+ external_exports.strictObject({
30046
+ _meta: optionalMetadata,
30047
+ availableCommands: external_exports.array(commandSchema).max(MAX_COLLECTION_SIZE).readonly(),
30048
+ sessionUpdate: external_exports.literal("available_commands_update")
30049
+ }).readonly(),
30050
+ external_exports.strictObject({
30051
+ _meta: optionalMetadata,
30052
+ currentModeId: shortString,
30053
+ sessionUpdate: external_exports.literal("current_mode_update")
30054
+ }).readonly(),
30055
+ external_exports.strictObject({
30056
+ _meta: optionalMetadata,
30057
+ configOptions: external_exports.array(sessionConfigOptionSchema2).max(MAX_COLLECTION_SIZE).readonly(),
30058
+ sessionUpdate: external_exports.literal("config_option_update")
30059
+ }).readonly(),
30060
+ external_exports.strictObject({
30061
+ _meta: optionalMetadata,
30062
+ sessionUpdate: external_exports.literal("session_info_update"),
30063
+ title: boundedString.nullable().optional(),
30064
+ updatedAt: shortString.nullable().optional()
30065
+ }).readonly(),
30066
+ external_exports.strictObject({
30067
+ _meta: optionalMetadata,
30068
+ cost: external_exports.strictObject({ _meta: optionalMetadata, amount: external_exports.number().finite(), currency: external_exports.string().max(16) }).readonly().nullable().optional(),
30069
+ sessionUpdate: external_exports.literal("usage_update"),
30070
+ size: external_exports.number().int().nonnegative().safe(),
30071
+ used: external_exports.number().int().nonnegative().safe()
30072
+ }).readonly(),
30073
+ external_exports.strictObject({
30074
+ _meta: optionalMetadata,
30075
+ compactionId: shortString,
30076
+ error: boundedString.nullable().optional(),
30077
+ sessionUpdate: external_exports.literal("compaction_update"),
30078
+ status: shortString,
30079
+ summary: external_exports.array(contentBlockV2Schema).max(MAX_COLLECTION_SIZE).readonly().nullable().optional()
30080
+ }).readonly(),
30081
+ external_exports.strictObject({
30082
+ _meta: optionalMetadata,
30083
+ compactionId: shortString,
30084
+ content: contentBlockV2Schema,
30085
+ sessionUpdate: external_exports.literal("compaction_summary_chunk")
30086
+ }).readonly()
30087
+ ]);
30088
+ var lifecycleBase = { commandId: identifierStringSchema };
30089
+ var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
30090
+ external_exports.strictObject({ kind: external_exports.literal("session.queue.changed") }).readonly(),
30091
+ external_exports.strictObject({ event: sessionPermissionRequestedEventSchema, kind: external_exports.literal("session.permission.requested") }).readonly(),
30092
+ external_exports.strictObject({ event: sessionPermissionResolvedEventSchema, kind: external_exports.literal("session.permission.resolved") }).readonly(),
30093
+ external_exports.strictObject({
30094
+ event: sessionElicitationRequestedEventSchema,
30095
+ kind: external_exports.literal("session.elicitation.requested")
30096
+ }).readonly(),
30097
+ external_exports.strictObject({ event: sessionElicitationResolvedEventSchema, kind: external_exports.literal("session.elicitation.resolved") }).readonly(),
30098
+ external_exports.strictObject({
30099
+ ...lifecycleBase,
30100
+ content: external_exports.array(contentBlockV2Schema).min(1).max(100).readonly(),
30101
+ kind: external_exports.literal("prompt.requested")
30102
+ }).readonly(),
30103
+ external_exports.strictObject({ ...lifecycleBase, attemptId: identifierStringSchema, epoch: identifierStringSchema, kind: external_exports.literal("prompt.started") }).readonly(),
30104
+ external_exports.strictObject({ ...lifecycleBase, kind: external_exports.literal("prompt.completed"), stopReason: shortString }).readonly(),
30105
+ external_exports.strictObject({
30106
+ ...lifecycleBase,
30107
+ code: identifierStringSchema,
30108
+ kind: external_exports.literal("prompt.failed-before-start"),
30109
+ message: external_exports.string().min(1).max(500)
30110
+ }).readonly(),
30111
+ external_exports.strictObject({
30112
+ ...lifecycleBase,
30113
+ attemptId: identifierStringSchema,
30114
+ code: identifierStringSchema,
30115
+ kind: external_exports.literal("prompt.failed"),
30116
+ message: external_exports.string().min(1).max(500)
30117
+ }).readonly()
30118
+ ]);
30119
+ var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("type", [
30120
+ external_exports.strictObject({ payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
30121
+ external_exports.strictObject({ payload: lifecycleMetadataV2Schema, type: external_exports.literal("lifecycle-metadata") }).readonly()
30122
+ ]);
30123
+ var positionSchema = external_exports.string().regex(/^(0|[1-9][0-9]*)$/);
30124
+ var provenanceSchema = external_exports.discriminatedUnion("kind", [
30125
+ external_exports.strictObject({ kind: external_exports.literal("original") }).readonly(),
30126
+ external_exports.strictObject({
30127
+ kind: external_exports.literal("imported"),
30128
+ sourceEventId: identifierStringSchema,
30129
+ sourcePosition: positionSchema,
30130
+ sourceSessionId: identifierStringSchema
30131
+ }).readonly(),
30132
+ external_exports.strictObject({
30133
+ kind: external_exports.literal("forked"),
30134
+ sourceEventId: identifierStringSchema,
30135
+ sourcePosition: positionSchema,
30136
+ sourceSessionId: identifierStringSchema
30137
+ }).readonly()
30138
+ ]);
30139
+ var sessionEventFieldsV2 = {
30140
+ eventId: identifierStringSchema,
30141
+ position: positionSchema,
30142
+ provenance: provenanceSchema,
30143
+ recordedAt: external_exports.iso.datetime({ offset: true }),
30144
+ sessionId: identifierStringSchema
30145
+ };
30146
+ var sessionEventV2Schema = external_exports.discriminatedUnion("type", [
30147
+ external_exports.strictObject({ ...sessionEventFieldsV2, payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
30148
+ external_exports.strictObject({
30149
+ ...sessionEventFieldsV2,
30150
+ payload: lifecycleMetadataV2Schema,
30151
+ type: external_exports.literal("lifecycle-metadata")
30152
+ }).readonly()
30153
+ ]);
30154
+ var sessionExportV2Schema = external_exports.strictObject({
30155
+ binding: external_exports.strictObject({
30156
+ bindingId: identifierStringSchema,
30157
+ runtimeId: identifierStringSchema
30158
+ }).readonly(),
30159
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
30160
+ sessionId: identifierStringSchema,
30161
+ truncated: external_exports.boolean()
30162
+ }).readonly().superRefine((session, context) => {
30163
+ let previousPosition = 0n;
30164
+ const eventIds = /* @__PURE__ */ new Set();
30165
+ for (const [index2, event] of session.events.entries()) {
30166
+ if (event.sessionId !== session.sessionId) {
30167
+ context.addIssue({
30168
+ code: "custom",
30169
+ message: "Exported event belongs to a different Session",
30170
+ path: ["events", index2, "sessionId"]
30171
+ });
30172
+ }
30173
+ const position = BigInt(event.position);
30174
+ if (position <= previousPosition) {
30175
+ context.addIssue({
30176
+ code: "custom",
30177
+ message: "Exported events are not in increasing position order",
30178
+ path: ["events", index2, "position"]
30179
+ });
30180
+ }
30181
+ if (eventIds.has(event.eventId)) {
30182
+ context.addIssue({
30183
+ code: "custom",
30184
+ message: "Exported event identities are not unique",
30185
+ path: ["events", index2, "eventId"]
30186
+ });
30187
+ }
30188
+ previousPosition = position;
30189
+ eventIds.add(event.eventId);
30190
+ }
30191
+ });
30192
+ var mobiusSessionExportV2Schema = external_exports.strictObject({
30193
+ formatVersion: external_exports.literal("2"),
30194
+ session: sessionExportV2Schema
30195
+ }).readonly();
30196
+ var sessionEventEnvelopeV2Schema = external_exports.strictObject({ event: sessionEventV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
30197
+ var sessionEventLogPageV2Schema = external_exports.strictObject({
30198
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
30199
+ nextCursor: external_exports.string().min(1).max(512).nullable(),
30200
+ tailCursor: external_exports.string().max(512),
30201
+ truncated: external_exports.boolean(),
30202
+ version: external_exports.literal(2)
30203
+ }).readonly();
30204
+ var nativeEventPageRequestV2Schema = external_exports.strictObject({ cursor: external_exports.string().min(1).max(512).nullable(), eventLimit: external_exports.number().int().min(1).max(1e4) }).readonly();
30205
+ var executingPromptRequestEventLogV2Schema = external_exports.strictObject({
30206
+ attemptId: identifierStringSchema,
30207
+ commandId: identifierStringSchema,
30208
+ epoch: identifierStringSchema,
30209
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
30210
+ tailCursor: external_exports.string().max(512),
30211
+ truncated: external_exports.boolean()
30212
+ }).readonly();
30213
+ var nativeSessionEventsV2Schema = external_exports.strictObject({
30214
+ executingPromptRequest: executingPromptRequestEventLogV2Schema.nullable(),
30215
+ history: sessionEventLogPageV2Schema
30216
+ }).readonly();
30217
+ function inputValue(value) {
30218
+ if (typeof value !== "string") {
30219
+ return value;
30220
+ }
30221
+ try {
30222
+ return JSON.parse(value);
30223
+ } catch (cause) {
30224
+ throw new ProtocolMessageError("Session Event Log V2 message is not valid JSON", { cause });
30225
+ }
30226
+ }
30227
+ function decode5(value, schema) {
30228
+ const result = schema.safeParse(inputValue(value));
30229
+ if (!result.success) {
30230
+ throw new ProtocolMessageError("Session Event Log V2 message does not match its schema", {
30231
+ cause: result.error
30232
+ });
30233
+ }
30234
+ return result.data;
30235
+ }
30236
+ function encode4(value, schema) {
30237
+ return JSON.stringify(decode5(value, schema));
30238
+ }
30239
+ var decodeSessionEventV2 = (value) => decode5(value, sessionEventV2Schema);
30240
+ var decodeSessionEventEnvelopeV2 = (value) => decode5(value, sessionEventEnvelopeV2Schema);
30241
+ var encodeSessionEventEnvelopeV2 = (value) => encode4(value, sessionEventEnvelopeV2Schema);
30242
+ var decodeAcpSessionUpdateV2 = (value) => decode5(value, acpSessionUpdateV2Schema);
30243
+
29807
30244
  // ../protocol/src/session-events.ts
29808
30245
  var SESSION_EVENT_KIND = "session.event";
29809
30246
  var SESSION_FORKED_KIND = "session.forked";
@@ -29821,7 +30258,7 @@ var sessionForkedSchema = external_exports.strictObject({
29821
30258
  sourceSessionId: identifierStringSchema,
29822
30259
  throughCommandId: identifierStringSchema
29823
30260
  }).readonly();
29824
- function decode5(encoded, schema) {
30261
+ function decode6(encoded, schema) {
29825
30262
  let value;
29826
30263
  try {
29827
30264
  value = JSON.parse(encoded);
@@ -29836,7 +30273,7 @@ function decode5(encoded, schema) {
29836
30273
  }
29837
30274
  return decoded.data;
29838
30275
  }
29839
- var encode4 = (message, schema) => {
30276
+ var encode5 = (message, schema) => {
29840
30277
  const decoded = schema.safeParse(message);
29841
30278
  if (!decoded.success) {
29842
30279
  throw new ProtocolMessageError("Message does not match its schema", {
@@ -29845,15 +30282,15 @@ var encode4 = (message, schema) => {
29845
30282
  }
29846
30283
  return JSON.stringify(decoded.data);
29847
30284
  };
29848
- var decodeSessionEventEnvelope = (encoded) => decode5(encoded, sessionEventEnvelopeSchema);
29849
- var encodeSessionEventEnvelope = (message) => encode4(message, sessionEventEnvelopeSchema);
30285
+ var decodeSessionEventEnvelope = (encoded) => decode6(encoded, sessionEventEnvelopeSchema);
30286
+ var encodeSessionEventEnvelope = (message) => encode5(message, sessionEventEnvelopeSchema);
29850
30287
  function decodeRecordedSessionEvent(encoded) {
29851
30288
  const kind = decodeMessageKind(encoded);
29852
30289
  switch (kind) {
29853
30290
  case SESSION_QUEUE_CHANGED_KIND:
29854
- return decode5(encoded, sessionQueueChangedSchema);
30291
+ return decode6(encoded, sessionQueueChangedSchema);
29855
30292
  case SESSION_FORKED_KIND:
29856
- return decode5(encoded, sessionForkedSchema);
30293
+ return decode6(encoded, sessionForkedSchema);
29857
30294
  case AGENT_ACTIVITY_KIND:
29858
30295
  return decodeAgentActivityEvent(encoded);
29859
30296
  case AGENT_ACTIVITY_NARRATION_KIND:
@@ -29897,6 +30334,8 @@ var SESSION_LIVE_HISTORY_LOAD_KIND = "session.live-history.load";
29897
30334
  var SESSION_LIVE_HISTORY_LOADED_KIND = "session.live-history.loaded";
29898
30335
  var SESSION_LIVE_HISTORY_PAGE_LOAD_KIND = "session.live-history.page.load";
29899
30336
  var SESSION_LIVE_HISTORY_PAGE_LOADED_KIND = "session.live-history.page.loaded";
30337
+ var SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND = "session.live-history.v2.page.load";
30338
+ var SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND = "session.live-history.v2.page.loaded";
29900
30339
  var directoryIdentifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
29901
30340
  var sessionLiveHistoryLoadSchema = external_exports.strictObject({
29902
30341
  additionalDirectoryIds: external_exports.array(directoryIdentifier).max(16).readonly(),
@@ -29930,7 +30369,24 @@ var sessionLiveHistoryPageLoadedSchema = external_exports.strictObject({
29930
30369
  requestId: identifierStringSchema,
29931
30370
  sessionId: identifierStringSchema
29932
30371
  }).readonly();
29933
- function decode6(schema, encoded) {
30372
+ var sessionLiveHistoryV2PageLoadSchema = external_exports.strictObject({
30373
+ additionalDirectoryIds: external_exports.array(directoryIdentifier).max(16).readonly(),
30374
+ agentId: identifierStringSchema,
30375
+ bindingId: identifierStringSchema,
30376
+ cursor: external_exports.string().min(1).max(512).nullable(),
30377
+ directoryId: directoryIdentifier,
30378
+ kind: external_exports.literal(SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND),
30379
+ eventLimit: external_exports.number().int().min(1).max(1e4),
30380
+ requestId: identifierStringSchema,
30381
+ sessionId: identifierStringSchema
30382
+ }).readonly();
30383
+ var sessionLiveHistoryV2PageLoadedSchema = external_exports.strictObject({
30384
+ events: nativeSessionEventsV2Schema,
30385
+ kind: external_exports.literal(SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND),
30386
+ requestId: identifierStringSchema,
30387
+ sessionId: identifierStringSchema
30388
+ }).readonly();
30389
+ function decode7(schema, encoded) {
29934
30390
  try {
29935
30391
  const value = JSON.parse(encoded);
29936
30392
  return schema.parse(value);
@@ -29938,14 +30394,18 @@ function decode6(schema, encoded) {
29938
30394
  throw new ProtocolMessageError("Invalid live Session history message", { cause });
29939
30395
  }
29940
30396
  }
29941
- var decodeSessionLiveHistoryLoad = (encoded) => decode6(sessionLiveHistoryLoadSchema, encoded);
29942
- var decodeSessionLiveHistoryLoaded = (encoded) => decode6(sessionLiveHistoryLoadedSchema, encoded);
30397
+ var decodeSessionLiveHistoryLoad = (encoded) => decode7(sessionLiveHistoryLoadSchema, encoded);
30398
+ var decodeSessionLiveHistoryLoaded = (encoded) => decode7(sessionLiveHistoryLoadedSchema, encoded);
29943
30399
  var encodeSessionLiveHistoryLoad = (value) => JSON.stringify(sessionLiveHistoryLoadSchema.parse(value));
29944
30400
  var encodeSessionLiveHistoryLoaded = (value) => JSON.stringify(sessionLiveHistoryLoadedSchema.parse(value));
29945
- var decodeSessionLiveHistoryPageLoad = (encoded) => decode6(sessionLiveHistoryPageLoadSchema, encoded);
29946
- var decodeSessionLiveHistoryPageLoaded = (encoded) => decode6(sessionLiveHistoryPageLoadedSchema, encoded);
30401
+ var decodeSessionLiveHistoryPageLoad = (encoded) => decode7(sessionLiveHistoryPageLoadSchema, encoded);
30402
+ var decodeSessionLiveHistoryPageLoaded = (encoded) => decode7(sessionLiveHistoryPageLoadedSchema, encoded);
29947
30403
  var encodeSessionLiveHistoryPageLoad = (value) => JSON.stringify(sessionLiveHistoryPageLoadSchema.parse(value));
29948
30404
  var encodeSessionLiveHistoryPageLoaded = (value) => JSON.stringify(sessionLiveHistoryPageLoadedSchema.parse(value));
30405
+ var decodeSessionLiveHistoryV2PageLoad = (encoded) => decode7(sessionLiveHistoryV2PageLoadSchema, encoded);
30406
+ var decodeSessionLiveHistoryV2PageLoaded = (encoded) => decode7(sessionLiveHistoryV2PageLoadedSchema, encoded);
30407
+ var encodeSessionLiveHistoryV2PageLoad = (value) => JSON.stringify(sessionLiveHistoryV2PageLoadSchema.parse(value));
30408
+ var encodeSessionLiveHistoryV2PageLoaded = (value) => JSON.stringify(sessionLiveHistoryV2PageLoadedSchema.parse(value));
29949
30409
 
29950
30410
  // ../protocol/src/daemon-transport.ts
29951
30411
  function defineMessageSignature(kind, encoder, decoder) {
@@ -30030,6 +30490,11 @@ var serviceToDaemonSignatures = {
30030
30490
  encodeSessionLiveHistoryPageLoad,
30031
30491
  decodeSessionLiveHistoryPageLoad
30032
30492
  ),
30493
+ [SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND]: defineMessageSignature(
30494
+ SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND,
30495
+ encodeSessionLiveHistoryV2PageLoad,
30496
+ decodeSessionLiveHistoryV2PageLoad
30497
+ ),
30033
30498
  [SESSION_PERMISSION_RESPOND_KIND]: defineMessageSignature(
30034
30499
  SESSION_PERMISSION_RESPOND_KIND,
30035
30500
  encodeSessionPermissionRespondCommand,
@@ -30145,6 +30610,11 @@ var daemonToServiceSignatures = {
30145
30610
  encodeSessionEventEnvelope,
30146
30611
  decodeSessionEventEnvelope
30147
30612
  ),
30613
+ [SESSION_EVENT_V2_KIND]: defineMessageSignature(
30614
+ SESSION_EVENT_V2_KIND,
30615
+ encodeSessionEventEnvelopeV2,
30616
+ decodeSessionEventEnvelopeV2
30617
+ ),
30148
30618
  [SESSION_OPERATION_FAILED_KIND]: defineMessageSignature(
30149
30619
  SESSION_OPERATION_FAILED_KIND,
30150
30620
  encodeSessionOperationFailedEvent,
@@ -30160,6 +30630,11 @@ var daemonToServiceSignatures = {
30160
30630
  encodeSessionLiveHistoryPageLoaded,
30161
30631
  decodeSessionLiveHistoryPageLoaded
30162
30632
  ),
30633
+ [SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND]: defineMessageSignature(
30634
+ SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND,
30635
+ encodeSessionLiveHistoryV2PageLoaded,
30636
+ decodeSessionLiveHistoryV2PageLoaded
30637
+ ),
30163
30638
  [SESSION_READY_KIND]: defineMessageSignature(SESSION_READY_KIND, encodeSessionReadyEvent, decodeSessionReadyEvent),
30164
30639
  [WORKSPACE_ENTRIES_KIND]: defineMessageSignature(
30165
30640
  WORKSPACE_ENTRIES_KIND,
@@ -30244,7 +30719,7 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
30244
30719
 
30245
30720
  // src/daemon-manager.ts
30246
30721
  import { spawn as spawn6 } from "node:child_process";
30247
- import { createHash as createHash7, randomBytes } from "node:crypto";
30722
+ import { createHash as createHash8, randomBytes } from "node:crypto";
30248
30723
  import { readFile as readFile3, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
30249
30724
  import { createConnection, createServer } from "node:net";
30250
30725
  import { tmpdir } from "node:os";
@@ -30579,16 +31054,16 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
30579
31054
  };
30580
31055
  #readConnectionForChannel = async (channelId, signal) => {
30581
31056
  const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
30582
- const index = decodeChannelIndex(
31057
+ const index2 = decodeChannelIndex(
30583
31058
  await readJsonFile(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
30584
31059
  );
30585
- if (index.applicationId !== this.applicationId || index.installationId !== this.installationId || index.channelId !== normalizedChannelId) {
31060
+ if (index2.applicationId !== this.applicationId || index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
30586
31061
  throw new RuntimeInstallationStoreError(
30587
31062
  "connection_owner_mismatch",
30588
31063
  "The saved Runtime connection belongs to another installation"
30589
31064
  );
30590
31065
  }
30591
- return await this.readConnection(index.connectionId, signal);
31066
+ return await this.readConnection(index2.connectionId, signal);
30592
31067
  };
30593
31068
  saveConnection = async (input2, signal) => {
30594
31069
  const stored = new VerifiedRuntimeConnection(
@@ -30783,16 +31258,16 @@ function hasExactKeys2(value, expectedKeys) {
30783
31258
  }
30784
31259
  function readSingleOption(arguments_, option) {
30785
31260
  const values = [];
30786
- for (let index = 0; index < arguments_.length; index += 1) {
30787
- if (arguments_[index] !== option) {
31261
+ for (let index2 = 0; index2 < arguments_.length; index2 += 1) {
31262
+ if (arguments_[index2] !== option) {
30788
31263
  continue;
30789
31264
  }
30790
- const value = arguments_[index + 1];
31265
+ const value = arguments_[index2 + 1];
30791
31266
  if (value === void 0 || value.startsWith("--")) {
30792
31267
  throw new PairingClientError("invalid_arguments", `${option} requires a value`);
30793
31268
  }
30794
31269
  values.push(value);
30795
- index += 1;
31270
+ index2 += 1;
30796
31271
  }
30797
31272
  if (values.length !== 1) {
30798
31273
  throw new PairingClientError("invalid_arguments", `${option} must be provided exactly once`);
@@ -30800,8 +31275,8 @@ function readSingleOption(arguments_, option) {
30800
31275
  return values[0] ?? "";
30801
31276
  }
30802
31277
  function assertKnownArguments(arguments_) {
30803
- for (let index = 0; index < arguments_.length; index += 2) {
30804
- const option = arguments_[index];
31278
+ for (let index2 = 0; index2 < arguments_.length; index2 += 2) {
31279
+ const option = arguments_[index2];
30805
31280
  if (option !== "--url" && option !== "--code" && option !== "--pairing" && option !== "--workspace") {
30806
31281
  throw new PairingClientError("invalid_arguments", `Unknown pairing option: ${option ?? "missing option"}`);
30807
31282
  }
@@ -31078,7 +31553,7 @@ var AuditStore = class {
31078
31553
  };
31079
31554
 
31080
31555
  // src/run-daemon.ts
31081
- import { createHash as createHash6, randomUUID as randomUUID7 } from "node:crypto";
31556
+ import { createHash as createHash7, randomUUID as randomUUID7 } from "node:crypto";
31082
31557
  import { join as join18 } from "node:path";
31083
31558
  import { styleText } from "node:util";
31084
31559
 
@@ -31201,7 +31676,7 @@ function startsWith(bytes, signature, offset = 0) {
31201
31676
  if (bytes.byteLength < offset + signature.byteLength) {
31202
31677
  return false;
31203
31678
  }
31204
- return signature.every((value, index) => bytes[offset + index] === value);
31679
+ return signature.every((value, index2) => bytes[offset + index2] === value);
31205
31680
  }
31206
31681
  function sniffRasterMime(bytes) {
31207
31682
  if (startsWith(bytes, PNG_SIGNATURE)) {
@@ -31329,7 +31804,7 @@ function startsWith2(bytes, signature, offset = 0) {
31329
31804
  if (bytes.byteLength < offset + signature.byteLength) {
31330
31805
  return false;
31331
31806
  }
31332
- return signature.every((value, index) => bytes[offset + index] === value);
31807
+ return signature.every((value, index2) => bytes[offset + index2] === value);
31333
31808
  }
31334
31809
  function sniffVideoMime(bytes) {
31335
31810
  if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
@@ -31458,10 +31933,10 @@ async function replaceImageMarkers(text2, replace) {
31458
31933
  let cursor = 0;
31459
31934
  let rewritten = "";
31460
31935
  for (const match of matches) {
31461
- const index = match.index ?? 0;
31462
- rewritten += text2.slice(cursor, index);
31936
+ const index2 = match.index ?? 0;
31937
+ rewritten += text2.slice(cursor, index2);
31463
31938
  rewritten += await replace(match[1] ?? "");
31464
- cursor = index + match[0].length;
31939
+ cursor = index2 + match[0].length;
31465
31940
  }
31466
31941
  return `${rewritten}${text2.slice(cursor)}`;
31467
31942
  }
@@ -32627,6 +33102,7 @@ function sessionConfigProtocolForAgent(_agentId) {
32627
33102
 
32628
33103
  // src/acp/session-contracts.ts
32629
33104
  var NullAcpSessionObserver = class {
33105
+ onAcpUpdate = (_sessionId, _update) => Promise.resolve();
32630
33106
  onCommands = () => Promise.resolve();
32631
33107
  onConfig = () => Promise.resolve();
32632
33108
  onContent = () => Promise.resolve();
@@ -32694,6 +33170,7 @@ function historyContentCharacters(messages) {
32694
33170
  var AcpHistoryReplay = class {
32695
33171
  #activities = /* @__PURE__ */ new Map();
32696
33172
  #messages = [];
33173
+ #updates = [];
32697
33174
  #turnActivityIds = /* @__PURE__ */ new Set();
32698
33175
  #activityTracker = new AcpActivityTracker(
32699
33176
  async (activity2) => {
@@ -32715,7 +33192,8 @@ var AcpHistoryReplay = class {
32715
33192
  #firstMessageIndex = 0;
32716
33193
  #characters = 0;
32717
33194
  #truncated = false;
32718
- record = async (update) => {
33195
+ record = async (update, rawUpdate) => {
33196
+ this.#updates.push(rawUpdate);
32719
33197
  if (update.sessionUpdate === "agent_thought_chunk") {
32720
33198
  if (update.content.type === "text") {
32721
33199
  await this.#activityTracker.recordNarrative(
@@ -32796,6 +33274,20 @@ var AcpHistoryReplay = class {
32796
33274
  this.#lastMessageId = id;
32797
33275
  this.trimMessages();
32798
33276
  };
33277
+ eventPage = (eventLimit, cursor) => {
33278
+ const parsedCursor = cursor === null ? this.#updates.length : Number(cursor);
33279
+ if (!Number.isSafeInteger(parsedCursor) || parsedCursor < 0 || parsedCursor > this.#updates.length) {
33280
+ throw new Error("The native event cursor is invalid");
33281
+ }
33282
+ const endUpdate = parsedCursor;
33283
+ const startUpdate = Math.max(0, endUpdate - eventLimit);
33284
+ return {
33285
+ nextCursor: startUpdate === 0 ? null : startUpdate.toString(),
33286
+ startPosition: startUpdate + 1,
33287
+ truncated: startUpdate > 0,
33288
+ updates: this.#updates.slice(startUpdate, endUpdate)
33289
+ };
33290
+ };
32799
33291
  snapshot = async () => {
32800
33292
  await this.#activityTracker.finish();
32801
33293
  const messages = this.#messages.slice(this.#firstMessageIndex).map((message) => {
@@ -34783,8 +35275,8 @@ function haveSameKeys(left, right) {
34783
35275
  if (leftKeys.length !== rightKeys.length) {
34784
35276
  return false;
34785
35277
  }
34786
- for (const [index, key] of leftKeys.entries()) {
34787
- if (key !== rightKeys[index]) {
35278
+ for (const [index2, key] of leftKeys.entries()) {
35279
+ if (key !== rightKeys[index2]) {
34788
35280
  return false;
34789
35281
  }
34790
35282
  }
@@ -35972,6 +36464,55 @@ var sqliteTable = (name, columns, extraConfig) => {
35972
36464
  return sqliteTableBase(name, columns, extraConfig);
35973
36465
  };
35974
36466
 
36467
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6.13_better-sqlite3@12.4.1/node_modules/drizzle-orm/sqlite-core/indexes.js
36468
+ var IndexBuilderOn = class {
36469
+ constructor(name, unique) {
36470
+ this.name = name;
36471
+ this.unique = unique;
36472
+ }
36473
+ static [entityKind] = "SQLiteIndexBuilderOn";
36474
+ on(...columns) {
36475
+ return new IndexBuilder(this.name, columns, this.unique);
36476
+ }
36477
+ };
36478
+ var IndexBuilder = class {
36479
+ static [entityKind] = "SQLiteIndexBuilder";
36480
+ /** @internal */
36481
+ config;
36482
+ constructor(name, columns, unique) {
36483
+ this.config = {
36484
+ name,
36485
+ columns,
36486
+ unique,
36487
+ where: void 0
36488
+ };
36489
+ }
36490
+ /**
36491
+ * Condition for partial index.
36492
+ */
36493
+ where(condition) {
36494
+ this.config.where = condition;
36495
+ return this;
36496
+ }
36497
+ /** @internal */
36498
+ build(table) {
36499
+ return new Index(this.config, table);
36500
+ }
36501
+ };
36502
+ var Index = class {
36503
+ static [entityKind] = "SQLiteIndex";
36504
+ config;
36505
+ constructor(config2, table) {
36506
+ this.config = { ...config2, table };
36507
+ }
36508
+ };
36509
+ function index(name) {
36510
+ return new IndexBuilderOn(name, false);
36511
+ }
36512
+ function uniqueIndex(name) {
36513
+ return new IndexBuilderOn(name, true);
36514
+ }
36515
+
35975
36516
  // ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260918.1_@types+better-sqlite3@7.6.13_better-sqlite3@12.4.1/node_modules/drizzle-orm/sqlite-core/utils.js
35976
36517
  function extractUsedTable(table) {
35977
36518
  if (is(table, SQLiteTable)) {
@@ -36320,8 +36861,8 @@ var SQLiteDialect = class {
36320
36861
  }
36321
36862
  const joinsArray = [];
36322
36863
  if (joins) {
36323
- for (const [index, joinMeta] of joins.entries()) {
36324
- if (index === 0) {
36864
+ for (const [index2, joinMeta] of joins.entries()) {
36865
+ if (index2 === 0) {
36325
36866
  joinsArray.push(sql` `);
36326
36867
  }
36327
36868
  const table = joinMeta.table;
@@ -36341,7 +36882,7 @@ var SQLiteDialect = class {
36341
36882
  sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`
36342
36883
  );
36343
36884
  }
36344
- if (index < joins.length - 1) {
36885
+ if (index2 < joins.length - 1) {
36345
36886
  joinsArray.push(sql` `);
36346
36887
  }
36347
36888
  }
@@ -36354,9 +36895,9 @@ var SQLiteDialect = class {
36354
36895
  buildOrderBy(orderBy) {
36355
36896
  const orderByList = [];
36356
36897
  if (orderBy) {
36357
- for (const [index, orderByValue] of orderBy.entries()) {
36898
+ for (const [index2, orderByValue] of orderBy.entries()) {
36358
36899
  orderByList.push(orderByValue);
36359
- if (index < orderBy.length - 1) {
36900
+ if (index2 < orderBy.length - 1) {
36360
36901
  orderByList.push(sql`, `);
36361
36902
  }
36362
36903
  }
@@ -36409,9 +36950,9 @@ var SQLiteDialect = class {
36409
36950
  const havingSql = having ? sql` having ${having}` : void 0;
36410
36951
  const groupByList = [];
36411
36952
  if (groupBy) {
36412
- for (const [index, groupByValue] of groupBy.entries()) {
36953
+ for (const [index2, groupByValue] of groupBy.entries()) {
36413
36954
  groupByList.push(groupByValue);
36414
- if (index < groupBy.length - 1) {
36955
+ if (index2 < groupBy.length - 1) {
36415
36956
  groupByList.push(sql`, `);
36416
36957
  }
36417
36958
  }
@@ -38825,6 +39366,10 @@ var acpSessionStoreMigrations = [
38825
39366
  {
38826
39367
  "name": "0001_regular_ultimates.sql",
38827
39368
  "sql": "ALTER TABLE `acp_session` ADD `last_terminal_command_id` text;"
39369
+ },
39370
+ {
39371
+ "name": "0002_equal_black_queen.sql",
39372
+ "sql": "CREATE TABLE `session_event_v2` (\n `event_id` text PRIMARY KEY NOT NULL,\n `event_json` text NOT NULL,\n `position` integer NOT NULL,\n `session_id` text NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `session_event_v2_session_position_unique` ON `session_event_v2` (`session_id`,`position`);--> statement-breakpoint\nCREATE INDEX `session_event_v2_session_position_index` ON `session_event_v2` (`session_id`,`position`);"
38828
39373
  }
38829
39374
  ];
38830
39375
 
@@ -38832,7 +39377,8 @@ var acpSessionStoreMigrations = [
38832
39377
  var acp_session_store_exports = {};
38833
39378
  __export(acp_session_store_exports, {
38834
39379
  acpSession: () => acpSession,
38835
- deletedAcpSession: () => deletedAcpSession
39380
+ deletedAcpSession: () => deletedAcpSession,
39381
+ sessionEventV2: () => sessionEventV2
38836
39382
  });
38837
39383
 
38838
39384
  // src/schema/acp-session-store/acp-session.ts
@@ -38853,6 +39399,21 @@ var deletedAcpSession = sqliteTable("deleted_acp_session", {
38853
39399
  sessionId: text("session_id").primaryKey()
38854
39400
  });
38855
39401
 
39402
+ // src/schema/acp-session-store/session-event-v2.ts
39403
+ var sessionEventV2 = sqliteTable(
39404
+ "session_event_v2",
39405
+ {
39406
+ eventId: text("event_id").primaryKey(),
39407
+ eventJson: text("event_json").notNull(),
39408
+ position: integer2("position").notNull(),
39409
+ sessionId: text("session_id").notNull()
39410
+ },
39411
+ (table) => [
39412
+ uniqueIndex("session_event_v2_session_position_unique").on(table.sessionId, table.position),
39413
+ index("session_event_v2_session_position_index").on(table.sessionId, table.position)
39414
+ ]
39415
+ );
39416
+
38856
39417
  // src/acp/session-store.ts
38857
39418
  var AcpStoredSession = class {
38858
39419
  additionalDirectories;
@@ -38895,9 +39456,21 @@ var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
38895
39456
  var MemoryAcpSessionStore = class {
38896
39457
  #sessions = /* @__PURE__ */ new Map();
38897
39458
  #deleted = /* @__PURE__ */ new Set();
39459
+ #eventsV2 = /* @__PURE__ */ new Map();
39460
+ appendExecutingPromptEventV2 = (event) => {
39461
+ const events = this.#eventsV2.get(event.sessionId);
39462
+ if (events === void 0) {
39463
+ throw new Error("The executing prompt event log has not started");
39464
+ }
39465
+ events.push(event);
39466
+ };
39467
+ clearExecutingPromptEventsV2 = (sessionId) => {
39468
+ this.#eventsV2.delete(sessionId);
39469
+ };
38898
39470
  close = () => {
38899
39471
  this.#sessions.clear();
38900
39472
  this.#deleted.clear();
39473
+ this.#eventsV2.clear();
38901
39474
  };
38902
39475
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
38903
39476
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
@@ -38908,6 +39481,7 @@ var MemoryAcpSessionStore = class {
38908
39481
  for (const id of ids) {
38909
39482
  this.#sessions.delete(id);
38910
39483
  this.#deleted.add(id);
39484
+ this.#eventsV2.delete(id);
38911
39485
  }
38912
39486
  return ids;
38913
39487
  };
@@ -38920,6 +39494,13 @@ var MemoryAcpSessionStore = class {
38920
39494
  };
38921
39495
  remove = (sessionId) => {
38922
39496
  this.#sessions.delete(sessionId);
39497
+ this.#eventsV2.delete(sessionId);
39498
+ };
39499
+ readExecutingPromptEventsV2 = (sessionId) => [
39500
+ ...this.#eventsV2.get(sessionId) ?? []
39501
+ ];
39502
+ startExecutingPromptEventsV2 = (sessionId, events) => {
39503
+ this.#eventsV2.set(sessionId, [...events]);
38923
39504
  };
38924
39505
  write = (session) => {
38925
39506
  this.#sessions.set(session.sessionId, session);
@@ -38969,15 +39550,15 @@ var SqliteAcpSessionStore = class {
38969
39550
  this.#sqliteDatabase.close();
38970
39551
  throw new Error("The ACP Session database was created by a newer Mobius version");
38971
39552
  }
38972
- for (let index = version3; index < acpSessionStoreMigrations.length; index += 1) {
38973
- const migration = acpSessionStoreMigrations[index];
39553
+ for (let index2 = version3; index2 < acpSessionStoreMigrations.length; index2 += 1) {
39554
+ const migration = acpSessionStoreMigrations[index2];
38974
39555
  if (migration === void 0) {
38975
39556
  throw new Error("The ACP Session migration is unavailable");
38976
39557
  }
38977
39558
  this.#sqliteDatabase.exec("BEGIN IMMEDIATE");
38978
39559
  try {
38979
39560
  this.#sqliteDatabase.exec(migration.sql);
38980
- this.#sqliteDatabase.pragma(`user_version = ${index + 1}`);
39561
+ this.#sqliteDatabase.pragma(`user_version = ${index2 + 1}`);
38981
39562
  this.#sqliteDatabase.exec("COMMIT");
38982
39563
  } catch (error62) {
38983
39564
  this.#sqliteDatabase.exec("ROLLBACK");
@@ -38988,6 +39569,30 @@ var SqliteAcpSessionStore = class {
38988
39569
  close = () => {
38989
39570
  this.#sqliteDatabase.close();
38990
39571
  };
39572
+ appendExecutingPromptEventV2 = (event) => {
39573
+ this.#database.insert(sessionEventV2).values({
39574
+ eventId: event.eventId,
39575
+ eventJson: JSON.stringify(event),
39576
+ position: Number(event.position),
39577
+ sessionId: event.sessionId
39578
+ }).run();
39579
+ };
39580
+ clearExecutingPromptEventsV2 = (sessionId) => {
39581
+ this.#database.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
39582
+ };
39583
+ startExecutingPromptEventsV2 = (sessionId, events) => {
39584
+ this.#database.transaction((transaction) => {
39585
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
39586
+ for (const event of events) {
39587
+ transaction.insert(sessionEventV2).values({
39588
+ eventId: event.eventId,
39589
+ eventJson: JSON.stringify(event),
39590
+ position: Number(event.position),
39591
+ sessionId: event.sessionId
39592
+ }).run();
39593
+ }
39594
+ });
39595
+ };
38991
39596
  findNative = (agentId, nativeSessionId) => this.#database.select().from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map(decodeStoredSession);
38992
39597
  list = () => this.#database.select().from(acpSession).orderBy(desc(acpSession.updatedAt)).all().map(decodeStoredSession);
38993
39598
  markDeleted = (agentId, nativeSessionId) => {
@@ -38996,6 +39601,7 @@ var SqliteAcpSessionStore = class {
38996
39601
  transaction.delete(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).run();
38997
39602
  for (const id of ids) {
38998
39603
  transaction.insert(deletedAcpSession).values({ sessionId: id }).onConflictDoNothing().run();
39604
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, id)).run();
38999
39605
  }
39000
39606
  });
39001
39607
  return ids;
@@ -39009,8 +39615,12 @@ var SqliteAcpSessionStore = class {
39009
39615
  const row = this.#database.select().from(acpSession).where(eq(acpSession.sessionId, sessionId)).get();
39010
39616
  return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeStoredSession(row));
39011
39617
  };
39618
+ readExecutingPromptEventsV2 = (sessionId) => this.#database.select({ eventJson: sessionEventV2.eventJson }).from(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).orderBy(asc(sessionEventV2.position)).all().map((row) => decodeSessionEventV2(row.eventJson));
39012
39619
  remove = (sessionId) => {
39013
- this.#database.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
39620
+ this.#database.transaction((transaction) => {
39621
+ transaction.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
39622
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
39623
+ });
39014
39624
  };
39015
39625
  write = (session) => {
39016
39626
  const value = {
@@ -39043,7 +39653,7 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
39043
39653
  }
39044
39654
  };
39045
39655
  function arraysEqual(left, right) {
39046
- return left.length === right.length && left.every((value, index) => value === right[index]);
39656
+ return left.length === right.length && left.every((value, index2) => value === right[index2]);
39047
39657
  }
39048
39658
  function recordsEqual(left, right) {
39049
39659
  const leftEntries = Object.entries(left);
@@ -39190,6 +39800,17 @@ var AgentSession = class _AgentSession {
39190
39800
  const loaded = await this.#loadSession(signal, "ACP agent exited while loading history");
39191
39801
  return await embedLocalHistoryImages(await loaded.history.snapshot(), signal);
39192
39802
  };
39803
+ loadHistoryEventsV2 = async (eventLimit, cursor, signal) => {
39804
+ if (!this.#capabilities.loadSession) {
39805
+ throw new AcpExecutionError(
39806
+ "This Agent restores context but does not provide message history.",
39807
+ {},
39808
+ "native_history_unsupported"
39809
+ );
39810
+ }
39811
+ const loaded = await this.#loadSession(signal, "ACP agent exited while loading history");
39812
+ return loaded.history.eventPage(eventLimit, cursor);
39813
+ };
39193
39814
  async #loadSession(signal, exitMessage) {
39194
39815
  if (this.#sessionLoad.kind === "loaded") {
39195
39816
  return this.#sessionLoad;
@@ -39672,6 +40293,19 @@ var AgentSession = class _AgentSession {
39672
40293
  if (this.#turn.running) {
39673
40294
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
39674
40295
  }
40296
+ switch (this.#sessionLoad.kind) {
40297
+ case "not-requested":
40298
+ break;
40299
+ case "loaded":
40300
+ this.#sessionLoad = { kind: "not-requested" };
40301
+ break;
40302
+ case "capturing":
40303
+ throw new AcpExecutionError("Session history is still loading", {}, "session_busy");
40304
+ default: {
40305
+ const unexpected = this.#sessionLoad;
40306
+ throw new Error(`Unexpected Session load state: ${JSON.stringify(unexpected)}`);
40307
+ }
40308
+ }
39675
40309
  const prompt = this.buildPrompt(options);
39676
40310
  if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
39677
40311
  this.#sessionTitle = truncate(options.prompt, 500);
@@ -39836,8 +40470,14 @@ var AgentSession = class _AgentSession {
39836
40470
  #processUpdate = async (notification) => {
39837
40471
  this.assertNativeSession(notification.sessionId);
39838
40472
  const update = notification.update;
39839
- if (this.#sessionLoad.kind !== "not-requested") {
39840
- await this.#sessionLoad.history.record(update);
40473
+ const rawUpdate = decodeAcpSessionUpdateV2(JSON.stringify(update));
40474
+ if (this.#sessionLoad.kind === "capturing") {
40475
+ await this.#sessionLoad.history.record(update, rawUpdate);
40476
+ } else {
40477
+ const onAcpUpdate = this.#getObserver().onAcpUpdate;
40478
+ if (onAcpUpdate !== void 0) {
40479
+ await onAcpUpdate(this.#mobiusSessionId, rawUpdate);
40480
+ }
39841
40481
  }
39842
40482
  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")) {
39843
40483
  return;
@@ -40219,6 +40859,21 @@ var AgentQueryProcesses = class {
40219
40859
  async (runtime) => await runtime.closeProcess()
40220
40860
  );
40221
40861
  };
40862
+ previewEventsV2 = async (options, nativeSessionId, eventLimit, cursor) => {
40863
+ return await this.#processes.runTransient(
40864
+ options.signal,
40865
+ async () => await AgentSession.startNativeSessionBrowser(
40866
+ options,
40867
+ () => this.#observer,
40868
+ new MemoryAcpSessionStore()
40869
+ ),
40870
+ async (runtime) => {
40871
+ runtime.selectNativeSession(nativeSessionId);
40872
+ return await runtime.loadHistoryEventsV2(eventLimit, cursor, options.signal);
40873
+ },
40874
+ async (runtime) => await runtime.closeProcess()
40875
+ );
40876
+ };
40222
40877
  close = async () => {
40223
40878
  await Promise.all(
40224
40879
  this.#processesByQuery.entries().map(async ([id, runtime]) => await this.retire(id, runtime))
@@ -40288,9 +40943,9 @@ var AcpProcessCapacityLock = class {
40288
40943
  return await waiter.completion.promise;
40289
40944
  } finally {
40290
40945
  signal.removeEventListener("abort", waiter.cancel);
40291
- const index = this.#waiters.indexOf(waiter);
40292
- if (index >= 0) {
40293
- this.#waiters.splice(index, 1);
40946
+ const index2 = this.#waiters.indexOf(waiter);
40947
+ if (index2 >= 0) {
40948
+ this.#waiters.splice(index2, 1);
40294
40949
  }
40295
40950
  }
40296
40951
  };
@@ -40920,6 +41575,22 @@ var AgentRuntimeManager = class {
40920
41575
  this.#nativeOperations.delete(key);
40921
41576
  }
40922
41577
  });
41578
+ previewNativeSessionEventsV2 = async (options, nativeSessionId, eventLimit, cursor) => this.#operations.run(options, async (options2) => {
41579
+ const key = `${options2.agent.id}:${nativeSessionId}`;
41580
+ if (this.#nativeOperations.has(key)) {
41581
+ throw new AcpExecutionError(
41582
+ "Wait for the native session's running operation to finish",
41583
+ {},
41584
+ "session_busy"
41585
+ );
41586
+ }
41587
+ this.#nativeOperations.add(key);
41588
+ try {
41589
+ return await this.#queryProcesses.previewEventsV2(options2, nativeSessionId, eventLimit, cursor);
41590
+ } finally {
41591
+ this.#nativeOperations.delete(key);
41592
+ }
41593
+ });
40923
41594
  loadSessionHistory = async (options) => this.#operations.run(options, async (options2) => {
40924
41595
  return await this.#executionProcesses.use(options2.sessionId, async () => {
40925
41596
  const runtime = await this.ensureSession(options2);
@@ -40937,6 +41608,12 @@ var AgentRuntimeManager = class {
40937
41608
  return await runtime.loadHistory(options2.signal);
40938
41609
  });
40939
41610
  });
41611
+ loadSessionEventsV2 = async (options, eventLimit, cursor) => this.#operations.run(options, async (options2) => {
41612
+ return await this.#executionProcesses.use(options2.sessionId, async () => {
41613
+ const runtime = await this.ensureSession(options2);
41614
+ return await runtime.loadHistoryEventsV2(eventLimit, cursor, options2.signal);
41615
+ });
41616
+ });
40940
41617
  openNativeSession = async (options, origin) => this.#operations.run(options, async (options2) => {
40941
41618
  const key = `${options2.agent.id}:${origin.nativeSessionId}`;
40942
41619
  if (this.#nativeOperations.has(key)) {
@@ -42139,9 +42816,15 @@ function reportOperationFailure(socket, requestId, sessionId, error62, runtimeTi
42139
42816
  // src/daemon-observers.ts
42140
42817
  var DaemonAcpObserver = class {
42141
42818
  #record;
42142
- constructor(record2) {
42819
+ #recordV2;
42820
+ constructor(record2, recordV2 = () => void 0) {
42143
42821
  this.#record = record2;
42822
+ this.#recordV2 = recordV2;
42144
42823
  }
42824
+ onAcpUpdate = (sessionId, update) => {
42825
+ this.#recordV2(sessionId, { payload: update, type: "acp" });
42826
+ return Promise.resolve();
42827
+ };
42145
42828
  onCommands = (event) => {
42146
42829
  this.#record(event.sessionId, event);
42147
42830
  return Promise.resolve();
@@ -42156,10 +42839,18 @@ var DaemonAcpObserver = class {
42156
42839
  };
42157
42840
  onElicitation = (event) => {
42158
42841
  this.#record(event.sessionId, event);
42842
+ this.#recordV2(event.sessionId, {
42843
+ payload: { event, kind: "session.elicitation.requested" },
42844
+ type: "lifecycle-metadata"
42845
+ });
42159
42846
  return Promise.resolve();
42160
42847
  };
42161
42848
  onElicitationResolved = (event) => {
42162
42849
  this.#record(event.sessionId, event);
42850
+ this.#recordV2(event.sessionId, {
42851
+ payload: { event, kind: "session.elicitation.resolved" },
42852
+ type: "lifecycle-metadata"
42853
+ });
42163
42854
  return Promise.resolve();
42164
42855
  };
42165
42856
  onInfo = (event) => {
@@ -42168,10 +42859,18 @@ var DaemonAcpObserver = class {
42168
42859
  };
42169
42860
  onPermission = (event) => {
42170
42861
  this.#record(event.sessionId, event);
42862
+ this.#recordV2(event.sessionId, {
42863
+ payload: { event, kind: "session.permission.requested" },
42864
+ type: "lifecycle-metadata"
42865
+ });
42171
42866
  return Promise.resolve();
42172
42867
  };
42173
42868
  onPermissionResolved = (event) => {
42174
42869
  this.#record(event.sessionId, event);
42870
+ this.#recordV2(event.sessionId, {
42871
+ payload: { event, kind: "session.permission.resolved" },
42872
+ type: "lifecycle-metadata"
42873
+ });
42175
42874
  return Promise.resolve();
42176
42875
  };
42177
42876
  onUsage = (event) => {
@@ -42278,8 +42977,8 @@ var ACTIVE_TURN_TEXT_CHUNK_LIMIT = Math.floor(SESSION_HISTORY_CHARACTER_LIMIT /
42278
42977
  function boundedRecoveryMessages(messages) {
42279
42978
  const selected = [];
42280
42979
  let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT;
42281
- for (let index = messages.length - 1; index >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index -= 1) {
42282
- const message = messages[index];
42980
+ for (let index2 = messages.length - 1; index2 >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index2 -= 1) {
42981
+ const message = messages[index2];
42283
42982
  if (message === void 0) {
42284
42983
  break;
42285
42984
  }
@@ -42420,7 +43119,7 @@ var ActiveDaemonTurn = class {
42420
43119
  ];
42421
43120
  } else {
42422
43121
  this.#timeline = this.#timeline.map(
42423
- (entry, index) => index === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
43122
+ (entry, index2) => index2 === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
42424
43123
  );
42425
43124
  }
42426
43125
  } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
@@ -43431,7 +44130,7 @@ async function readAcpHistory(sessions, directories, bindingId, options, nativeS
43431
44130
  async (directory) => await directories.identify(bindingId, directory, options.signal)
43432
44131
  )
43433
44132
  );
43434
- if (primary.path !== options.cwd || additional.length !== options.additionalDirectories.length || additional.some((directory, index) => directory.path !== options.additionalDirectories[index])) {
44133
+ if (primary.path !== options.cwd || additional.length !== options.additionalDirectories.length || additional.some((directory, index2) => directory.path !== options.additionalDirectories[index2])) {
43435
44134
  throw new AcpExecutionError(
43436
44135
  "The native Session belongs to another workspace.",
43437
44136
  {},
@@ -43564,7 +44263,7 @@ var NativeSessionService = class {
43564
44263
  "native_session_not_found"
43565
44264
  );
43566
44265
  }
43567
- if (source.agentId !== command.agentId || source.cwd !== cwd || source.additionalDirectories.length !== additionalDirectories.length || source.additionalDirectories.some((path3, index) => path3 !== additionalDirectories[index])) {
44266
+ if (source.agentId !== command.agentId || source.cwd !== cwd || source.additionalDirectories.length !== additionalDirectories.length || source.additionalDirectories.some((path3, index2) => path3 !== additionalDirectories[index2])) {
43568
44267
  throw new AcpExecutionError(
43569
44268
  "The source conversation execution target does not match the fork request",
43570
44269
  {},
@@ -43585,8 +44284,8 @@ var NativeSessionService = class {
43585
44284
  signal.throwIfAborted();
43586
44285
  const directory = await this.#directories.list(this.#config.bindingId, command.directoryId, signal);
43587
44286
  const ready2 = {
43588
- additionalDirectories: additionalDirectories.map((path3, index) => ({
43589
- directoryId: command.additionalDirectoryIds[index] ?? command.directoryId,
44287
+ additionalDirectories: additionalDirectories.map((path3, index2) => ({
44288
+ directoryId: command.additionalDirectoryIds[index2] ?? command.directoryId,
43590
44289
  name: basename5(path3) || path3
43591
44290
  })),
43592
44291
  agentId: command.agentId,
@@ -43918,7 +44617,7 @@ var NativeSessionService = class {
43918
44617
  resolveTarget = async (command, options, selected) => {
43919
44618
  let cursor = null;
43920
44619
  const visited = /* @__PURE__ */ new Set();
43921
- for (let index = 0; index < 100; index += 1) {
44620
+ for (let index2 = 0; index2 < 100; index2 += 1) {
43922
44621
  const page = await this.#sessions.listNativeSessions(options, cursor);
43923
44622
  const info = page.sessions.find((entry) => entry.sessionId === selected.nativeSessionId);
43924
44623
  if (info !== void 0) {
@@ -43926,7 +44625,7 @@ var NativeSessionService = class {
43926
44625
  if (target === null) {
43927
44626
  throw new LocalAuthorizationError("The selected native session is not authorized");
43928
44627
  }
43929
- if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path3, index2) => path3 !== selected.additionalDirectories[index2])) {
44628
+ if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path3, index3) => path3 !== selected.additionalDirectories[index3])) {
43930
44629
  throw new AcpExecutionError(
43931
44630
  "This session's directory changed. Refresh the list before continuing.",
43932
44631
  {},
@@ -45014,6 +45713,9 @@ async function streamLocalFile(command, send2, signal, workingDirectory) {
45014
45713
  });
45015
45714
  }
45016
45715
 
45716
+ // src/daemon-history-commands.ts
45717
+ import { createHash as createHash6 } from "node:crypto";
45718
+
45017
45719
  // src/authorization/resolve-session-directories.ts
45018
45720
  import { basename as basename7 } from "node:path";
45019
45721
  var ResolvedSessionDirectories = class {
@@ -45113,8 +45815,8 @@ function selectMessagesBefore(messages, endIndex, messageLimit, characterLimit)
45113
45815
  const selected = [];
45114
45816
  let remainingCharacters = characterLimit;
45115
45817
  let startIndex = endIndex;
45116
- for (let index = endIndex - 1; index >= 0 && selected.length < messageLimit; index -= 1) {
45117
- const message = messages[index];
45818
+ for (let index2 = endIndex - 1; index2 >= 0 && selected.length < messageLimit; index2 -= 1) {
45819
+ const message = messages[index2];
45118
45820
  if (message === void 0) {
45119
45821
  break;
45120
45822
  }
@@ -45124,7 +45826,7 @@ function selectMessagesBefore(messages, endIndex, messageLimit, characterLimit)
45124
45826
  }
45125
45827
  selected.unshift(message);
45126
45828
  remainingCharacters -= characters;
45127
- startIndex = index;
45829
+ startIndex = index2;
45128
45830
  }
45129
45831
  if (selected.length === 0 && endIndex > 0) {
45130
45832
  throw new AcpExecutionError(
@@ -45404,6 +46106,70 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
45404
46106
  });
45405
46107
  }
45406
46108
  }
46109
+ function replayEvent(sessionId, position, update) {
46110
+ const encoded = JSON.stringify(update);
46111
+ const eventId = `native-${createHash6("sha256").update(sessionId).update(":").update(position.toString()).update(":").update(encoded).digest("hex")}`;
46112
+ return {
46113
+ eventId,
46114
+ payload: update,
46115
+ position: position.toString(),
46116
+ provenance: { kind: "original" },
46117
+ recordedAt: "1970-01-01T00:00:00.000Z",
46118
+ sessionId,
46119
+ type: "acp"
46120
+ };
46121
+ }
46122
+ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, sessions, executingPromptRequest, signal) {
46123
+ try {
46124
+ const resolved = await resolveSessionDirectories(
46125
+ directories,
46126
+ config2.bindingId,
46127
+ command.directoryId,
46128
+ command.additionalDirectoryIds,
46129
+ signal
46130
+ );
46131
+ const replay = await sessions.loadSessionEventsV2(
46132
+ {
46133
+ additionalDirectories: resolved.additionalDirectories,
46134
+ agent: config2.catalog.find(command.agentId),
46135
+ cwd: resolved.cwd,
46136
+ sessionId: command.sessionId,
46137
+ signal
46138
+ },
46139
+ command.eventLimit,
46140
+ command.cursor
46141
+ );
46142
+ signal.throwIfAborted();
46143
+ const events = replay.updates.map(
46144
+ (update, index2) => replayEvent(command.sessionId, replay.startPosition + index2, update)
46145
+ );
46146
+ const tailCursor = events.at(-1)?.eventId ?? "";
46147
+ audit.record({
46148
+ commandId: command.requestId,
46149
+ event: "session_event_log_v2_loaded",
46150
+ sessionId: command.sessionId
46151
+ });
46152
+ send(socket, {
46153
+ events: {
46154
+ executingPromptRequest: executingPromptRequest(command.sessionId),
46155
+ history: {
46156
+ events,
46157
+ nextCursor: replay.nextCursor,
46158
+ tailCursor,
46159
+ truncated: replay.truncated,
46160
+ version: 2
46161
+ }
46162
+ },
46163
+ kind: "session.live-history.v2.page.loaded",
46164
+ requestId: command.requestId,
46165
+ sessionId: command.sessionId
46166
+ });
46167
+ } catch (error62) {
46168
+ if (!signal.aborted) {
46169
+ reportOperationFailure(socket, command.requestId, command.sessionId, error62);
46170
+ }
46171
+ }
46172
+ }
45407
46173
 
45408
46174
  // src/acp/session-config/apply-session-configuration.ts
45409
46175
  import { randomUUID as randomUUID5 } from "node:crypto";
@@ -45718,6 +46484,7 @@ function daemonActivity(command, activity2) {
45718
46484
  async function executePrompt({
45719
46485
  operations,
45720
46486
  publisher,
46487
+ eventLogV2,
45721
46488
  command,
45722
46489
  config: config2,
45723
46490
  directories,
@@ -45822,6 +46589,7 @@ async function executePrompt({
45822
46589
  }
45823
46590
  }
45824
46591
  const stream = activateAttempt();
46592
+ eventLogV2.started(command.sessionId, command.commandId, attemptId, stream.epoch);
45825
46593
  if (!prepared.prompted) {
45826
46594
  const listing = await directories.list(config2.bindingId, command.directoryId, signal);
45827
46595
  publisher.publish(command.sessionId, {
@@ -45891,6 +46659,7 @@ async function executePrompt({
45891
46659
  sessionId: command.sessionId,
45892
46660
  stopReason
45893
46661
  });
46662
+ eventLogV2.completed(command.sessionId, command.commandId, stopReason);
45894
46663
  operations.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
45895
46664
  audit.record({
45896
46665
  commandId: command.commandId,
@@ -45906,6 +46675,7 @@ async function executePrompt({
45906
46675
  sessionId: command.sessionId,
45907
46676
  stopReason: "cancelled"
45908
46677
  });
46678
+ eventLogV2.completed(command.sessionId, command.commandId, "cancelled");
45909
46679
  operations.transitionExecution(command.commandId, "cancelled");
45910
46680
  audit.record({
45911
46681
  commandId: command.commandId,
@@ -45920,12 +46690,10 @@ async function executePrompt({
45920
46690
  sessionId: command.sessionId
45921
46691
  });
45922
46692
  const code = operationErrorCode(error62);
45923
- reportFailure(
45924
- publisher,
45925
- command,
45926
- code === "session_operation_failed" ? "agent_execution_failed" : code,
45927
- code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62)
45928
- );
46693
+ const failureCode = code === "session_operation_failed" ? "agent_execution_failed" : code;
46694
+ const failureMessage = code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62);
46695
+ eventLogV2.failed(command.sessionId, command.commandId, failureCode, failureMessage);
46696
+ reportFailure(publisher, command, failureCode, failureMessage);
45929
46697
  operations.transitionExecution(command.commandId, "failed");
45930
46698
  console.error("Mobius daemon command failed", error62);
45931
46699
  }
@@ -46208,6 +46976,7 @@ function createDaemonCommandHandler({
46208
46976
  nativeSessions,
46209
46977
  operations,
46210
46978
  publisher,
46979
+ eventLogV2,
46211
46980
  activeTurns,
46212
46981
  diagnostics,
46213
46982
  socket,
@@ -46235,7 +47004,10 @@ function createDaemonCommandHandler({
46235
47004
  timer,
46236
47005
  resolveEnvironment: resolveAgentCatalogEnvironment
46237
47006
  });
46238
- const queueChanged = (sessionId) => publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
47007
+ const queueChanged = (sessionId) => {
47008
+ publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
47009
+ eventLogV2.queueChanged(sessionId);
47010
+ };
46239
47011
  const activeTurnRecovery = (sessionId) => activeTurns.recovery((command) => command.sessionId === sessionId);
46240
47012
  const nativeRequestHandler = createNativeSessionRequestHandler({
46241
47013
  audit,
@@ -46277,6 +47049,19 @@ function createDaemonCommandHandler({
46277
47049
  );
46278
47050
  return;
46279
47051
  }
47052
+ if (kind === SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND) {
47053
+ void executeSessionLiveHistoryV2PageLoad(
47054
+ socket,
47055
+ message,
47056
+ config2,
47057
+ directories,
47058
+ audit,
47059
+ sessions,
47060
+ eventLogV2.executingPromptRequest,
47061
+ signal
47062
+ );
47063
+ return;
47064
+ }
46280
47065
  if (kind === NATIVE_SESSION_CANCEL_KIND) {
46281
47066
  nativeRequestHandler.cancel(message);
46282
47067
  return;
@@ -46462,9 +47247,11 @@ function createDaemonCommandHandler({
46462
47247
  return;
46463
47248
  }
46464
47249
  const turn = activeTurns.start(command, receipt.attemptId);
47250
+ eventLogV2.requested(command);
46465
47251
  void executePrompt({
46466
47252
  operations,
46467
47253
  publisher,
47254
+ eventLogV2,
46468
47255
  command,
46469
47256
  config: config2,
46470
47257
  directories,
@@ -46754,6 +47541,7 @@ async function runRelayConnection({
46754
47541
  nativeSessions,
46755
47542
  operations,
46756
47543
  publisher,
47544
+ eventLogV2,
46757
47545
  activeTurns,
46758
47546
  connectionEpoch,
46759
47547
  diagnostics,
@@ -46776,6 +47564,7 @@ async function runRelayConnection({
46776
47564
  nativeSessions,
46777
47565
  operations,
46778
47566
  publisher,
47567
+ eventLogV2,
46779
47568
  activeTurns,
46780
47569
  diagnostics,
46781
47570
  socket,
@@ -46955,6 +47744,21 @@ var DaemonSessionEventPublisher = class {
46955
47744
  this.publish(sessionId, event);
46956
47745
  }
46957
47746
  };
47747
+ publishV2 = (event) => {
47748
+ const socket = this.#socket;
47749
+ if (socket === null || socket.readyState !== WebSocket9.OPEN) {
47750
+ return;
47751
+ }
47752
+ const encoded = encodeDaemonToServiceMessage({ event, kind: SESSION_EVENT_V2_KIND });
47753
+ if (socket.bufferedAmount + Buffer.byteLength(encoded, "utf8") > MAX_BUFFERED_BYTES) {
47754
+ socket.close(1013, "Live event transport overloaded");
47755
+ return;
47756
+ }
47757
+ try {
47758
+ socket.send(encoded);
47759
+ } catch {
47760
+ }
47761
+ };
46958
47762
  };
46959
47763
 
46960
47764
  // src/relay-connection/timer.ts
@@ -46966,6 +47770,266 @@ var SystemDaemonTimer = class {
46966
47770
  };
46967
47771
  var systemDaemonTimer = new SystemDaemonTimer();
46968
47772
 
47773
+ // src/session-event-log-v2.ts
47774
+ var EXECUTING_PROMPT_EVENT_LIMIT = 1e4;
47775
+ function eventArray(tail) {
47776
+ const reversed = [];
47777
+ let node2 = tail;
47778
+ while (node2 !== null) {
47779
+ reversed.push(node2.event);
47780
+ node2 = node2.previous;
47781
+ }
47782
+ return reversed.reverse();
47783
+ }
47784
+ function promptContent(command) {
47785
+ const content = [];
47786
+ if (command.prompt.length > 0) {
47787
+ content.push({ text: command.prompt, type: "text" });
47788
+ }
47789
+ for (const image of command.images) {
47790
+ content.push({
47791
+ _meta: { mobius: { name: image.name } },
47792
+ data: image.data,
47793
+ mimeType: image.mimeType,
47794
+ type: "image"
47795
+ });
47796
+ }
47797
+ for (const resource of command.resources) {
47798
+ content.push(
47799
+ resource.type === "embedded" ? {
47800
+ resource: { mimeType: resource.mimeType, text: resource.text, uri: resource.uri },
47801
+ type: "resource"
47802
+ } : { mimeType: resource.mimeType, name: resource.name, type: "resource_link", uri: resource.uri }
47803
+ );
47804
+ }
47805
+ return content;
47806
+ }
47807
+ var DaemonSessionEventLogV2 = class {
47808
+ #positions = /* @__PURE__ */ new Map();
47809
+ #requests = /* @__PURE__ */ new Map();
47810
+ #loadedRequestSessions = /* @__PURE__ */ new Set();
47811
+ #publisher;
47812
+ #store;
47813
+ constructor(publisher, store) {
47814
+ this.#publisher = publisher;
47815
+ this.#store = store;
47816
+ }
47817
+ #loadStoredEvents = (sessionId) => {
47818
+ const stored = this.#store.readExecutingPromptEventsV2(sessionId);
47819
+ const lastPosition = stored.at(-1)?.position;
47820
+ if (lastPosition !== void 0) {
47821
+ this.#positions.set(sessionId, Number(lastPosition));
47822
+ }
47823
+ return stored;
47824
+ };
47825
+ #loadRequests = (sessionId) => {
47826
+ if (this.#loadedRequestSessions.has(sessionId)) {
47827
+ return;
47828
+ }
47829
+ for (const event of this.#loadStoredEvents(sessionId)) {
47830
+ if (event.type === "acp") {
47831
+ const executing = [...this.#requests.values()].find(
47832
+ (request) => request.sessionId === sessionId && request.kind === "executing"
47833
+ );
47834
+ if (executing !== void 0) {
47835
+ this.#requests.set(executing.commandId, {
47836
+ ...executing,
47837
+ eventTail: { event, previous: executing.eventTail }
47838
+ });
47839
+ }
47840
+ continue;
47841
+ }
47842
+ const payload = event.payload;
47843
+ if (payload.kind === "prompt.requested") {
47844
+ this.#requests.set(payload.commandId, {
47845
+ commandId: payload.commandId,
47846
+ eventTail: { event, previous: null },
47847
+ kind: "requested",
47848
+ sessionId
47849
+ });
47850
+ continue;
47851
+ }
47852
+ if ("event" in payload) {
47853
+ const executing = [...this.#requests.values()].find(
47854
+ (request) => request.sessionId === sessionId && request.kind === "executing"
47855
+ );
47856
+ if (executing !== void 0) {
47857
+ this.#requests.set(executing.commandId, {
47858
+ ...executing,
47859
+ eventTail: { event, previous: executing.eventTail }
47860
+ });
47861
+ }
47862
+ continue;
47863
+ }
47864
+ if (!("commandId" in payload)) {
47865
+ continue;
47866
+ }
47867
+ const state = this.#requests.get(payload.commandId);
47868
+ if (state === void 0) {
47869
+ continue;
47870
+ }
47871
+ if (payload.kind === "prompt.started") {
47872
+ this.#requests.set(payload.commandId, {
47873
+ attemptId: payload.attemptId,
47874
+ commandId: payload.commandId,
47875
+ epoch: payload.epoch,
47876
+ eventTail: { event, previous: state.eventTail },
47877
+ kind: "executing",
47878
+ sessionId
47879
+ });
47880
+ } else if (payload.kind === "prompt.completed" || payload.kind === "prompt.failed" || payload.kind === "prompt.failed-before-start") {
47881
+ this.#requests.delete(payload.commandId);
47882
+ }
47883
+ }
47884
+ this.#loadedRequestSessions.add(sessionId);
47885
+ };
47886
+ #append = (sessionId, payload) => {
47887
+ this.#loadRequests(sessionId);
47888
+ const position = (this.#positions.get(sessionId) ?? 0) + 1;
47889
+ const event = {
47890
+ eventId: `event-${crypto.randomUUID()}`,
47891
+ ...payload,
47892
+ position: position.toString(),
47893
+ provenance: { kind: "original" },
47894
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
47895
+ sessionId
47896
+ };
47897
+ this.#positions.set(sessionId, position);
47898
+ this.#publisher.publishV2(event);
47899
+ return event;
47900
+ };
47901
+ requested = (command) => {
47902
+ const content = promptContent(command);
47903
+ const event = this.#append(command.sessionId, {
47904
+ payload: { commandId: command.commandId, content, kind: "prompt.requested" },
47905
+ type: "lifecycle-metadata"
47906
+ });
47907
+ let eventTail = { event, previous: null };
47908
+ for (const block of content) {
47909
+ const userMessageEvent = this.#append(command.sessionId, {
47910
+ payload: {
47911
+ content: block,
47912
+ messageId: command.commandId,
47913
+ sessionUpdate: "user_message_chunk"
47914
+ },
47915
+ type: "acp"
47916
+ });
47917
+ eventTail = { event: userMessageEvent, previous: eventTail };
47918
+ }
47919
+ this.#requests.set(command.commandId, {
47920
+ commandId: command.commandId,
47921
+ eventTail,
47922
+ kind: "requested",
47923
+ sessionId: command.sessionId
47924
+ });
47925
+ };
47926
+ started = (sessionId, commandId, attemptId, epoch) => {
47927
+ this.#loadRequests(sessionId);
47928
+ const request = this.#requests.get(commandId);
47929
+ if (request?.sessionId !== sessionId) {
47930
+ return;
47931
+ }
47932
+ const event = this.#append(sessionId, {
47933
+ payload: { attemptId, commandId, epoch, kind: "prompt.started" },
47934
+ type: "lifecycle-metadata"
47935
+ });
47936
+ this.#requests.set(commandId, {
47937
+ attemptId,
47938
+ commandId,
47939
+ epoch,
47940
+ eventTail: { event, previous: request.eventTail },
47941
+ kind: "executing",
47942
+ sessionId
47943
+ });
47944
+ this.#store.startExecutingPromptEventsV2(sessionId, eventArray({ event, previous: request.eventTail }));
47945
+ };
47946
+ record = (sessionId, payload) => {
47947
+ this.#loadRequests(sessionId);
47948
+ const event = this.#append(sessionId, payload);
47949
+ this.#appendToExecutingRequest(sessionId, event);
47950
+ };
47951
+ #appendToExecutingRequest = (sessionId, event) => {
47952
+ const executing = [...this.#requests.values()].find(
47953
+ (request) => request.sessionId === sessionId && request.kind === "executing"
47954
+ );
47955
+ if (executing !== void 0) {
47956
+ this.#requests.set(executing.commandId, {
47957
+ ...executing,
47958
+ eventTail: { event, previous: executing.eventTail }
47959
+ });
47960
+ this.#store.appendExecutingPromptEventV2(event);
47961
+ }
47962
+ };
47963
+ queueChanged = (sessionId) => {
47964
+ const event = this.#append(sessionId, {
47965
+ payload: { kind: "session.queue.changed" },
47966
+ type: "lifecycle-metadata"
47967
+ });
47968
+ this.#appendToExecutingRequest(sessionId, event);
47969
+ };
47970
+ completed = (sessionId, commandId, stopReason) => {
47971
+ this.#loadRequests(sessionId);
47972
+ const request = this.#requests.get(commandId);
47973
+ const event = this.#append(sessionId, {
47974
+ payload: { commandId, kind: "prompt.completed", stopReason },
47975
+ type: "lifecycle-metadata"
47976
+ });
47977
+ this.#requests.delete(commandId);
47978
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
47979
+ this.#store.clearExecutingPromptEventsV2(sessionId);
47980
+ } else {
47981
+ this.#appendToExecutingRequest(sessionId, event);
47982
+ }
47983
+ };
47984
+ failed = (sessionId, commandId, code, message) => {
47985
+ this.#loadRequests(sessionId);
47986
+ const request = this.#requests.get(commandId);
47987
+ let event;
47988
+ if (request?.kind === "executing" && request.commandId === commandId) {
47989
+ event = this.#append(sessionId, {
47990
+ payload: {
47991
+ attemptId: request.attemptId,
47992
+ code,
47993
+ commandId,
47994
+ kind: "prompt.failed",
47995
+ message
47996
+ },
47997
+ type: "lifecycle-metadata"
47998
+ });
47999
+ } else {
48000
+ event = this.#append(sessionId, {
48001
+ payload: { code, commandId, kind: "prompt.failed-before-start", message },
48002
+ type: "lifecycle-metadata"
48003
+ });
48004
+ }
48005
+ this.#requests.delete(commandId);
48006
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
48007
+ this.#store.clearExecutingPromptEventsV2(sessionId);
48008
+ } else {
48009
+ this.#appendToExecutingRequest(sessionId, event);
48010
+ }
48011
+ };
48012
+ executingPromptRequest = (sessionId) => {
48013
+ this.#loadRequests(sessionId);
48014
+ const request = [...this.#requests.values()].find(
48015
+ (candidate) => candidate.sessionId === sessionId && candidate.kind === "executing"
48016
+ );
48017
+ if (request?.kind !== "executing") {
48018
+ return null;
48019
+ }
48020
+ const requestEvents = eventArray(request.eventTail);
48021
+ const events = requestEvents.slice(-EXECUTING_PROMPT_EVENT_LIMIT);
48022
+ return {
48023
+ attemptId: request.attemptId,
48024
+ commandId: request.commandId,
48025
+ epoch: request.epoch,
48026
+ events,
48027
+ tailCursor: events.at(-1)?.eventId ?? "",
48028
+ truncated: events.length < requestEvents.length
48029
+ };
48030
+ };
48031
+ };
48032
+
46969
48033
  // src/run-daemon.ts
46970
48034
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
46971
48035
  function waitForRelayRetry(signal, timer) {
@@ -47033,16 +48097,17 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
47033
48097
  stateDirectory
47034
48098
  });
47035
48099
  const sessionStore = new SqliteAcpSessionStore(
47036
- join18(stateDirectory, "sessions", `${createHash6("sha256").update(config2.channelId).digest("hex")}.sqlite`)
48100
+ join18(stateDirectory, "sessions", `${createHash7("sha256").update(config2.channelId).digest("hex")}.sqlite`)
47037
48101
  );
47038
48102
  const operations = new DaemonOperationState();
47039
48103
  const publisher = new DaemonSessionEventPublisher();
48104
+ const eventLogV2 = new DaemonSessionEventLogV2(publisher, sessionStore);
47040
48105
  const activeTurns = new DaemonTurnRegistry(operations);
47041
48106
  const recordSessionEvent = (sessionId, event) => {
47042
48107
  publisher.publish(sessionId, activeTurns.recordEvent(event));
47043
48108
  };
47044
48109
  const agentRuntime = new AgentRuntimeManager(
47045
- new DaemonAcpObserver(recordSessionEvent),
48110
+ new DaemonAcpObserver(recordSessionEvent, eventLogV2.record),
47046
48111
  sessionStore,
47047
48112
  {
47048
48113
  read: async (options2, nativeSessionId, nativeTurn) => options2.agent.id === "codex" ? (await readCodexFullHistory(
@@ -47080,7 +48145,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
47080
48145
  options2.signal
47081
48146
  );
47082
48147
  return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
47083
- (directory, index) => directory === options2.additionalDirectories[index]
48148
+ (directory, index2) => directory === options2.additionalDirectories[index2]
47084
48149
  );
47085
48150
  });
47086
48151
  }
@@ -47166,6 +48231,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
47166
48231
  nativeSessions,
47167
48232
  operations,
47168
48233
  publisher,
48234
+ eventLogV2,
47169
48235
  activeTurns,
47170
48236
  connectionEpoch,
47171
48237
  diagnostics,
@@ -47318,7 +48384,7 @@ function isRecord11(value) {
47318
48384
  return typeof value === "object" && value !== null && !Array.isArray(value);
47319
48385
  }
47320
48386
  function controlSocketPath(stateDirectory) {
47321
- const installationHash = createHash7("sha256").update(stateDirectory).digest("hex").slice(0, 32);
48387
+ const installationHash = createHash8("sha256").update(stateDirectory).digest("hex").slice(0, 32);
47322
48388
  return process.platform === "win32" ? `\\\\.\\pipe\\mobius-${installationHash}` : join19(tmpdir(), `mobius-${installationHash}.sock`);
47323
48389
  }
47324
48390
  function controlTokenPath(stateDirectory) {
@@ -47549,12 +48615,12 @@ var RuntimeSupervisor = class {
47549
48615
  }
47550
48616
  };
47551
48617
  function pairingIdentifier(arguments_) {
47552
- const indexes = arguments_.flatMap((argument, index2) => argument === "--pairing" ? [index2] : []);
48618
+ const indexes = arguments_.flatMap((argument, index3) => argument === "--pairing" ? [index3] : []);
47553
48619
  if (indexes.length !== 1) {
47554
48620
  return null;
47555
48621
  }
47556
- const index = indexes[0];
47557
- return index === void 0 ? null : arguments_[index + 1] ?? null;
48622
+ const index2 = indexes[0];
48623
+ return index2 === void 0 ? null : arguments_[index2 + 1] ?? null;
47558
48624
  }
47559
48625
  async function waitForReady(active, signal) {
47560
48626
  if (active.status === "online") {
@@ -47849,9 +48915,9 @@ function formatPairTable(pairs) {
47849
48915
  const headers = ["connection_id", "app_id", "runtime_id", "workspace", "status"];
47850
48916
  const rows = pairs.map((pair) => [pair.connectionId, pair.appId, pair.runtimeId, pair.workspace, pair.status]);
47851
48917
  const widths = headers.map(
47852
- (header, index) => Math.max(header.length, ...rows.map((row) => row[index]?.length ?? 0))
48918
+ (header, index2) => Math.max(header.length, ...rows.map((row) => row[index2]?.length ?? 0))
47853
48919
  );
47854
- const line = (row) => `| ${row.map((value, index) => value.padEnd(widths[index] ?? value.length)).join(" | ")} |`;
48920
+ const line = (row) => `| ${row.map((value, index2) => value.padEnd(widths[index2] ?? value.length)).join(" | ")} |`;
47855
48921
  const divider = `|-${widths.map((width) => "-".repeat(width)).join("-|-")}-|`;
47856
48922
  return `${line(headers)}
47857
48923
  ${divider}