@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/runtime.js CHANGED
@@ -3354,11 +3354,11 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
3354
3354
  return payload;
3355
3355
  };
3356
3356
  });
3357
- function handleArrayResult(result, final, index) {
3357
+ function handleArrayResult(result, final, index2) {
3358
3358
  if (result.issues.length) {
3359
- final.issues.push(...prefixIssues(index, result.issues));
3359
+ final.issues.push(...prefixIssues(index2, result.issues));
3360
3360
  }
3361
- final.value[index] = result.value;
3361
+ final.value[index2] = result.value;
3362
3362
  }
3363
3363
  var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
3364
3364
  $ZodType.init(inst, def);
@@ -3969,14 +3969,14 @@ function mergeValues(a, b) {
3969
3969
  return { valid: false, mergeErrorPath: [] };
3970
3970
  }
3971
3971
  const newArray = [];
3972
- for (let index = 0; index < a.length; index++) {
3973
- const itemA = a[index];
3974
- const itemB = b[index];
3972
+ for (let index2 = 0; index2 < a.length; index2++) {
3973
+ const itemA = a[index2];
3974
+ const itemB = b[index2];
3975
3975
  const sharedValue = mergeValues(itemA, itemB);
3976
3976
  if (!sharedValue.valid) {
3977
3977
  return {
3978
3978
  valid: false,
3979
- mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
3979
+ mergeErrorPath: [index2, ...sharedValue.mergeErrorPath]
3980
3980
  };
3981
3981
  }
3982
3982
  newArray.push(sharedValue.data);
@@ -4127,11 +4127,11 @@ function getTupleOptStart(items, key) {
4127
4127
  }
4128
4128
  return 0;
4129
4129
  }
4130
- function handleTupleResult(result, final, index) {
4130
+ function handleTupleResult(result, final, index2) {
4131
4131
  if (result.issues.length) {
4132
- final.issues.push(...prefixIssues(index, result.issues));
4132
+ final.issues.push(...prefixIssues(index2, result.issues));
4133
4133
  }
4134
- final.value[index] = result.value;
4134
+ final.value[index2] = result.value;
4135
4135
  }
4136
4136
  function handleTupleResults(itemResults, final, items, input2, optoutStart) {
4137
4137
  for (let i = 0; i < items.length; i++) {
@@ -18812,7 +18812,7 @@ function detectVersion(schema, defaultTarget) {
18812
18812
  return defaultTarget ?? "draft-2020-12";
18813
18813
  }
18814
18814
  function applyMinItems(items, minItems) {
18815
- return items.map((item, index) => index < minItems ? item : item.optional());
18815
+ return items.map((item, index2) => index2 < minItems ? item : item.optional());
18816
18816
  }
18817
18817
  function decodeJSONPointerSegment(segment) {
18818
18818
  return segment.replace(/~1/g, "/").replace(/~0/g, "~");
@@ -20000,12 +20000,12 @@ var DEFAULT_AGENT_EXECUTION_CONFIGURATION = Object.freeze({
20000
20000
  });
20001
20001
  var sessionConfigurationSelectionsSchema = external_exports.array(sessionConfigurationSelectionSchema).max(100).superRefine((selections, context) => {
20002
20002
  const identifiers = /* @__PURE__ */ new Set();
20003
- for (const [index, selection] of selections.entries()) {
20003
+ for (const [index2, selection] of selections.entries()) {
20004
20004
  if (identifiers.has(selection.configId)) {
20005
20005
  context.addIssue({
20006
20006
  code: "custom",
20007
20007
  message: "Session configuration identifiers must be unique",
20008
- path: [index, "configId"]
20008
+ path: [index2, "configId"]
20009
20009
  });
20010
20010
  }
20011
20011
  identifiers.add(selection.configId);
@@ -21207,6 +21207,443 @@ var encodeNativeSessionResult = (value) => JSON.stringify(nativeSessionResultSch
21207
21207
  var decodeNativeSessionCancel = (encoded) => decode4(nativeSessionCancelSchema, encoded);
21208
21208
  var encodeNativeSessionCancel = (value) => JSON.stringify(nativeSessionCancelSchema.parse(value));
21209
21209
 
21210
+ // ../protocol/src/session-event-log-v2.ts
21211
+ var MAX_EVENT_COUNT = 1e4;
21212
+ var MAX_COLLECTION_SIZE = 1e3;
21213
+ var MAX_CONTENT_LENGTH = 1e6;
21214
+ var MAX_JSON_DEPTH = 16;
21215
+ var MAX_JSON_KEYS = 1e3;
21216
+ var SESSION_EVENT_V2_KIND = "session.event.v2";
21217
+ var boundedString = external_exports.string().max(MAX_CONTENT_LENGTH);
21218
+ var shortString = external_exports.string().max(2048);
21219
+ function boundedJsonIssue(value, depth = 0) {
21220
+ if (depth > MAX_JSON_DEPTH) {
21221
+ return "JSON nesting exceeds the maximum depth";
21222
+ }
21223
+ if (typeof value === "string") {
21224
+ return value.length <= MAX_CONTENT_LENGTH ? null : "JSON string exceeds the maximum length";
21225
+ }
21226
+ if (typeof value === "number") {
21227
+ return Number.isFinite(value) ? null : "JSON number must be finite";
21228
+ }
21229
+ if (typeof value === "boolean" || value === null) {
21230
+ return null;
21231
+ }
21232
+ if (Array.isArray(value)) {
21233
+ if (value.length > MAX_COLLECTION_SIZE) {
21234
+ return "JSON array exceeds the maximum length";
21235
+ }
21236
+ for (const item of value) {
21237
+ const issue2 = boundedJsonIssue(item, depth + 1);
21238
+ if (issue2 !== null) {
21239
+ return issue2;
21240
+ }
21241
+ }
21242
+ return null;
21243
+ }
21244
+ if (typeof value === "object" && value !== void 0) {
21245
+ const entries = Object.entries(value);
21246
+ if (entries.length > MAX_JSON_KEYS) {
21247
+ return "JSON object exceeds the maximum key count";
21248
+ }
21249
+ for (const [key, item] of entries) {
21250
+ if (key.length > 255) {
21251
+ return "JSON key exceeds the maximum length";
21252
+ }
21253
+ const issue2 = boundedJsonIssue(item, depth + 1);
21254
+ if (issue2 !== null) {
21255
+ return issue2;
21256
+ }
21257
+ }
21258
+ return null;
21259
+ }
21260
+ return "Value is not bounded JSON";
21261
+ }
21262
+ var boundedJsonSchema = external_exports.unknown().superRefine((value, context) => {
21263
+ const issue2 = boundedJsonIssue(value);
21264
+ if (issue2 !== null) {
21265
+ context.addIssue({ code: "custom", message: issue2 });
21266
+ }
21267
+ });
21268
+ var metadataSchema = external_exports.record(external_exports.string().max(255), boundedJsonSchema).readonly();
21269
+ var optionalMetadata = metadataSchema.nullable().optional();
21270
+ var annotationsSchema = external_exports.strictObject({
21271
+ _meta: optionalMetadata,
21272
+ audience: external_exports.array(external_exports.enum(["assistant", "user"])).max(2).readonly().nullable().optional(),
21273
+ lastModified: shortString.nullable().optional(),
21274
+ priority: external_exports.number().finite().nullable().optional()
21275
+ }).readonly();
21276
+ var contentFields = { _meta: optionalMetadata, annotations: annotationsSchema.nullable().optional() };
21277
+ var textContentSchema = external_exports.strictObject({ ...contentFields, text: boundedString, type: external_exports.literal("text") }).readonly();
21278
+ var imageContentSchema = external_exports.strictObject({
21279
+ ...contentFields,
21280
+ data: boundedString,
21281
+ mimeType: shortString,
21282
+ type: external_exports.literal("image"),
21283
+ uri: boundedString.nullable().optional()
21284
+ }).readonly();
21285
+ var audioContentSchema = external_exports.strictObject({ ...contentFields, data: boundedString, mimeType: shortString, type: external_exports.literal("audio") }).readonly();
21286
+ var resourceLinkSchema = external_exports.strictObject({
21287
+ ...contentFields,
21288
+ description: boundedString.nullable().optional(),
21289
+ mimeType: shortString.nullable().optional(),
21290
+ name: shortString,
21291
+ size: external_exports.number().int().nonnegative().safe().nullable().optional(),
21292
+ title: shortString.nullable().optional(),
21293
+ type: external_exports.literal("resource_link"),
21294
+ uri: boundedString
21295
+ }).readonly();
21296
+ var textResourceSchema = external_exports.strictObject({
21297
+ _meta: optionalMetadata,
21298
+ mimeType: shortString.nullable().optional(),
21299
+ text: boundedString,
21300
+ uri: boundedString
21301
+ }).readonly();
21302
+ var blobResourceSchema = external_exports.strictObject({
21303
+ _meta: optionalMetadata,
21304
+ blob: boundedString,
21305
+ mimeType: shortString.nullable().optional(),
21306
+ uri: boundedString
21307
+ }).readonly();
21308
+ var embeddedResourceSchema = external_exports.strictObject({
21309
+ ...contentFields,
21310
+ resource: external_exports.union([textResourceSchema, blobResourceSchema]),
21311
+ type: external_exports.literal("resource")
21312
+ }).readonly();
21313
+ var contentBlockV2Schema = external_exports.discriminatedUnion("type", [
21314
+ textContentSchema,
21315
+ imageContentSchema,
21316
+ audioContentSchema,
21317
+ resourceLinkSchema,
21318
+ embeddedResourceSchema
21319
+ ]);
21320
+ var toolCallContentSchema = external_exports.discriminatedUnion("type", [
21321
+ external_exports.strictObject({ _meta: optionalMetadata, content: contentBlockV2Schema, type: external_exports.literal("content") }).readonly(),
21322
+ external_exports.strictObject({
21323
+ _meta: optionalMetadata,
21324
+ newText: boundedString,
21325
+ oldText: boundedString.nullable().optional(),
21326
+ path: boundedString,
21327
+ type: external_exports.literal("diff")
21328
+ }).readonly(),
21329
+ external_exports.strictObject({ _meta: optionalMetadata, terminalId: shortString, type: external_exports.literal("terminal") }).readonly()
21330
+ ]);
21331
+ var toolCallLocationSchema = external_exports.strictObject({
21332
+ _meta: optionalMetadata,
21333
+ line: external_exports.number().int().nonnegative().safe().nullable().optional(),
21334
+ path: boundedString
21335
+ }).readonly();
21336
+ var toolKindSchema = external_exports.enum([
21337
+ "read",
21338
+ "edit",
21339
+ "delete",
21340
+ "move",
21341
+ "search",
21342
+ "execute",
21343
+ "think",
21344
+ "fetch",
21345
+ "switch_mode",
21346
+ "other"
21347
+ ]);
21348
+ var toolStatusSchema = external_exports.enum(["pending", "in_progress", "completed", "failed"]);
21349
+ var toolPatchFields = {
21350
+ _meta: optionalMetadata,
21351
+ content: external_exports.array(toolCallContentSchema).max(MAX_COLLECTION_SIZE).readonly().nullable().optional(),
21352
+ kind: toolKindSchema.nullable().optional(),
21353
+ locations: external_exports.array(toolCallLocationSchema).max(MAX_COLLECTION_SIZE).readonly().nullable().optional(),
21354
+ name: shortString.nullable().optional(),
21355
+ rawInput: boundedJsonSchema.optional(),
21356
+ rawOutput: boundedJsonSchema.optional(),
21357
+ status: toolStatusSchema.nullable().optional(),
21358
+ title: boundedString.nullable().optional()
21359
+ };
21360
+ var planEntrySchema = external_exports.strictObject({
21361
+ _meta: optionalMetadata,
21362
+ content: boundedString,
21363
+ priority: external_exports.enum(["high", "medium", "low"]),
21364
+ status: external_exports.enum(["pending", "in_progress", "completed"])
21365
+ }).readonly();
21366
+ var planContentSchema = external_exports.discriminatedUnion("type", [
21367
+ external_exports.strictObject({
21368
+ _meta: optionalMetadata,
21369
+ entries: external_exports.array(planEntrySchema).max(MAX_COLLECTION_SIZE).readonly(),
21370
+ planId: shortString,
21371
+ type: external_exports.literal("items")
21372
+ }).readonly(),
21373
+ external_exports.strictObject({ _meta: optionalMetadata, planId: shortString, type: external_exports.literal("file"), uri: boundedString }).readonly(),
21374
+ external_exports.strictObject({
21375
+ _meta: optionalMetadata,
21376
+ content: boundedString,
21377
+ planId: shortString,
21378
+ type: external_exports.literal("markdown")
21379
+ }).readonly()
21380
+ ]);
21381
+ var commandSchema = external_exports.strictObject({
21382
+ _meta: optionalMetadata,
21383
+ description: boundedString,
21384
+ input: external_exports.strictObject({ _meta: optionalMetadata, hint: boundedString }).readonly().nullable().optional(),
21385
+ name: shortString
21386
+ }).readonly();
21387
+ var configSelectOptionSchema = external_exports.strictObject({
21388
+ _meta: optionalMetadata,
21389
+ description: boundedString.nullable().optional(),
21390
+ name: shortString,
21391
+ value: shortString
21392
+ }).readonly();
21393
+ var configSelectGroupSchema = external_exports.strictObject({
21394
+ _meta: optionalMetadata,
21395
+ group: shortString,
21396
+ name: shortString,
21397
+ options: external_exports.array(configSelectOptionSchema).max(MAX_COLLECTION_SIZE).readonly()
21398
+ }).readonly();
21399
+ var configBaseFields = {
21400
+ _meta: optionalMetadata,
21401
+ category: shortString.nullable().optional(),
21402
+ description: boundedString.nullable().optional(),
21403
+ id: shortString,
21404
+ name: shortString
21405
+ };
21406
+ var sessionConfigOptionSchema2 = external_exports.discriminatedUnion("type", [
21407
+ external_exports.strictObject({
21408
+ ...configBaseFields,
21409
+ currentValue: shortString,
21410
+ options: external_exports.union([
21411
+ external_exports.array(configSelectOptionSchema).max(MAX_COLLECTION_SIZE).readonly(),
21412
+ external_exports.array(configSelectGroupSchema).max(MAX_COLLECTION_SIZE).readonly()
21413
+ ]),
21414
+ type: external_exports.literal("select")
21415
+ }).readonly(),
21416
+ external_exports.strictObject({ ...configBaseFields, currentValue: external_exports.boolean(), type: external_exports.literal("boolean") }).readonly()
21417
+ ]);
21418
+ var contentChunkFields = {
21419
+ _meta: optionalMetadata,
21420
+ content: contentBlockV2Schema,
21421
+ messageId: shortString.nullable().optional()
21422
+ };
21423
+ var acpSessionUpdateV2Schema = external_exports.discriminatedUnion("sessionUpdate", [
21424
+ external_exports.strictObject({ ...contentChunkFields, sessionUpdate: external_exports.literal("user_message_chunk") }).readonly(),
21425
+ external_exports.strictObject({ ...contentChunkFields, sessionUpdate: external_exports.literal("agent_message_chunk") }).readonly(),
21426
+ external_exports.strictObject({ ...contentChunkFields, sessionUpdate: external_exports.literal("agent_thought_chunk") }).readonly(),
21427
+ external_exports.strictObject({
21428
+ _meta: optionalMetadata,
21429
+ content: external_exports.array(toolCallContentSchema).max(MAX_COLLECTION_SIZE).readonly().optional(),
21430
+ kind: toolKindSchema.optional(),
21431
+ locations: external_exports.array(toolCallLocationSchema).max(MAX_COLLECTION_SIZE).readonly().optional(),
21432
+ name: shortString.nullable().optional(),
21433
+ rawInput: boundedJsonSchema.optional(),
21434
+ rawOutput: boundedJsonSchema.optional(),
21435
+ sessionUpdate: external_exports.literal("tool_call"),
21436
+ status: toolStatusSchema.optional(),
21437
+ title: boundedString,
21438
+ toolCallId: shortString
21439
+ }).readonly(),
21440
+ external_exports.strictObject({ ...toolPatchFields, sessionUpdate: external_exports.literal("tool_call_update"), toolCallId: shortString }).readonly(),
21441
+ external_exports.strictObject({
21442
+ _meta: optionalMetadata,
21443
+ entries: external_exports.array(planEntrySchema).max(MAX_COLLECTION_SIZE).readonly(),
21444
+ sessionUpdate: external_exports.literal("plan")
21445
+ }).readonly(),
21446
+ external_exports.strictObject({ _meta: optionalMetadata, plan: planContentSchema, sessionUpdate: external_exports.literal("plan_update") }).readonly(),
21447
+ external_exports.strictObject({ _meta: optionalMetadata, planId: shortString, sessionUpdate: external_exports.literal("plan_removed") }).readonly(),
21448
+ external_exports.strictObject({
21449
+ _meta: optionalMetadata,
21450
+ availableCommands: external_exports.array(commandSchema).max(MAX_COLLECTION_SIZE).readonly(),
21451
+ sessionUpdate: external_exports.literal("available_commands_update")
21452
+ }).readonly(),
21453
+ external_exports.strictObject({
21454
+ _meta: optionalMetadata,
21455
+ currentModeId: shortString,
21456
+ sessionUpdate: external_exports.literal("current_mode_update")
21457
+ }).readonly(),
21458
+ external_exports.strictObject({
21459
+ _meta: optionalMetadata,
21460
+ configOptions: external_exports.array(sessionConfigOptionSchema2).max(MAX_COLLECTION_SIZE).readonly(),
21461
+ sessionUpdate: external_exports.literal("config_option_update")
21462
+ }).readonly(),
21463
+ external_exports.strictObject({
21464
+ _meta: optionalMetadata,
21465
+ sessionUpdate: external_exports.literal("session_info_update"),
21466
+ title: boundedString.nullable().optional(),
21467
+ updatedAt: shortString.nullable().optional()
21468
+ }).readonly(),
21469
+ external_exports.strictObject({
21470
+ _meta: optionalMetadata,
21471
+ cost: external_exports.strictObject({ _meta: optionalMetadata, amount: external_exports.number().finite(), currency: external_exports.string().max(16) }).readonly().nullable().optional(),
21472
+ sessionUpdate: external_exports.literal("usage_update"),
21473
+ size: external_exports.number().int().nonnegative().safe(),
21474
+ used: external_exports.number().int().nonnegative().safe()
21475
+ }).readonly(),
21476
+ external_exports.strictObject({
21477
+ _meta: optionalMetadata,
21478
+ compactionId: shortString,
21479
+ error: boundedString.nullable().optional(),
21480
+ sessionUpdate: external_exports.literal("compaction_update"),
21481
+ status: shortString,
21482
+ summary: external_exports.array(contentBlockV2Schema).max(MAX_COLLECTION_SIZE).readonly().nullable().optional()
21483
+ }).readonly(),
21484
+ external_exports.strictObject({
21485
+ _meta: optionalMetadata,
21486
+ compactionId: shortString,
21487
+ content: contentBlockV2Schema,
21488
+ sessionUpdate: external_exports.literal("compaction_summary_chunk")
21489
+ }).readonly()
21490
+ ]);
21491
+ var lifecycleBase = { commandId: identifierStringSchema };
21492
+ var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
21493
+ external_exports.strictObject({ kind: external_exports.literal("session.queue.changed") }).readonly(),
21494
+ external_exports.strictObject({ event: sessionPermissionRequestedEventSchema, kind: external_exports.literal("session.permission.requested") }).readonly(),
21495
+ external_exports.strictObject({ event: sessionPermissionResolvedEventSchema, kind: external_exports.literal("session.permission.resolved") }).readonly(),
21496
+ external_exports.strictObject({
21497
+ event: sessionElicitationRequestedEventSchema,
21498
+ kind: external_exports.literal("session.elicitation.requested")
21499
+ }).readonly(),
21500
+ external_exports.strictObject({ event: sessionElicitationResolvedEventSchema, kind: external_exports.literal("session.elicitation.resolved") }).readonly(),
21501
+ external_exports.strictObject({
21502
+ ...lifecycleBase,
21503
+ content: external_exports.array(contentBlockV2Schema).min(1).max(100).readonly(),
21504
+ kind: external_exports.literal("prompt.requested")
21505
+ }).readonly(),
21506
+ external_exports.strictObject({ ...lifecycleBase, attemptId: identifierStringSchema, epoch: identifierStringSchema, kind: external_exports.literal("prompt.started") }).readonly(),
21507
+ external_exports.strictObject({ ...lifecycleBase, kind: external_exports.literal("prompt.completed"), stopReason: shortString }).readonly(),
21508
+ external_exports.strictObject({
21509
+ ...lifecycleBase,
21510
+ code: identifierStringSchema,
21511
+ kind: external_exports.literal("prompt.failed-before-start"),
21512
+ message: external_exports.string().min(1).max(500)
21513
+ }).readonly(),
21514
+ external_exports.strictObject({
21515
+ ...lifecycleBase,
21516
+ attemptId: identifierStringSchema,
21517
+ code: identifierStringSchema,
21518
+ kind: external_exports.literal("prompt.failed"),
21519
+ message: external_exports.string().min(1).max(500)
21520
+ }).readonly()
21521
+ ]);
21522
+ var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("type", [
21523
+ external_exports.strictObject({ payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
21524
+ external_exports.strictObject({ payload: lifecycleMetadataV2Schema, type: external_exports.literal("lifecycle-metadata") }).readonly()
21525
+ ]);
21526
+ var positionSchema = external_exports.string().regex(/^(0|[1-9][0-9]*)$/);
21527
+ var provenanceSchema = external_exports.discriminatedUnion("kind", [
21528
+ external_exports.strictObject({ kind: external_exports.literal("original") }).readonly(),
21529
+ external_exports.strictObject({
21530
+ kind: external_exports.literal("imported"),
21531
+ sourceEventId: identifierStringSchema,
21532
+ sourcePosition: positionSchema,
21533
+ sourceSessionId: identifierStringSchema
21534
+ }).readonly(),
21535
+ external_exports.strictObject({
21536
+ kind: external_exports.literal("forked"),
21537
+ sourceEventId: identifierStringSchema,
21538
+ sourcePosition: positionSchema,
21539
+ sourceSessionId: identifierStringSchema
21540
+ }).readonly()
21541
+ ]);
21542
+ var sessionEventFieldsV2 = {
21543
+ eventId: identifierStringSchema,
21544
+ position: positionSchema,
21545
+ provenance: provenanceSchema,
21546
+ recordedAt: external_exports.iso.datetime({ offset: true }),
21547
+ sessionId: identifierStringSchema
21548
+ };
21549
+ var sessionEventV2Schema = external_exports.discriminatedUnion("type", [
21550
+ external_exports.strictObject({ ...sessionEventFieldsV2, payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
21551
+ external_exports.strictObject({
21552
+ ...sessionEventFieldsV2,
21553
+ payload: lifecycleMetadataV2Schema,
21554
+ type: external_exports.literal("lifecycle-metadata")
21555
+ }).readonly()
21556
+ ]);
21557
+ var sessionExportV2Schema = external_exports.strictObject({
21558
+ binding: external_exports.strictObject({
21559
+ bindingId: identifierStringSchema,
21560
+ runtimeId: identifierStringSchema
21561
+ }).readonly(),
21562
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
21563
+ sessionId: identifierStringSchema,
21564
+ truncated: external_exports.boolean()
21565
+ }).readonly().superRefine((session, context) => {
21566
+ let previousPosition = 0n;
21567
+ const eventIds = /* @__PURE__ */ new Set();
21568
+ for (const [index2, event] of session.events.entries()) {
21569
+ if (event.sessionId !== session.sessionId) {
21570
+ context.addIssue({
21571
+ code: "custom",
21572
+ message: "Exported event belongs to a different Session",
21573
+ path: ["events", index2, "sessionId"]
21574
+ });
21575
+ }
21576
+ const position = BigInt(event.position);
21577
+ if (position <= previousPosition) {
21578
+ context.addIssue({
21579
+ code: "custom",
21580
+ message: "Exported events are not in increasing position order",
21581
+ path: ["events", index2, "position"]
21582
+ });
21583
+ }
21584
+ if (eventIds.has(event.eventId)) {
21585
+ context.addIssue({
21586
+ code: "custom",
21587
+ message: "Exported event identities are not unique",
21588
+ path: ["events", index2, "eventId"]
21589
+ });
21590
+ }
21591
+ previousPosition = position;
21592
+ eventIds.add(event.eventId);
21593
+ }
21594
+ });
21595
+ var mobiusSessionExportV2Schema = external_exports.strictObject({
21596
+ formatVersion: external_exports.literal("2"),
21597
+ session: sessionExportV2Schema
21598
+ }).readonly();
21599
+ var sessionEventEnvelopeV2Schema = external_exports.strictObject({ event: sessionEventV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
21600
+ var sessionEventLogPageV2Schema = external_exports.strictObject({
21601
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
21602
+ nextCursor: external_exports.string().min(1).max(512).nullable(),
21603
+ tailCursor: external_exports.string().max(512),
21604
+ truncated: external_exports.boolean(),
21605
+ version: external_exports.literal(2)
21606
+ }).readonly();
21607
+ var nativeEventPageRequestV2Schema = external_exports.strictObject({ cursor: external_exports.string().min(1).max(512).nullable(), eventLimit: external_exports.number().int().min(1).max(1e4) }).readonly();
21608
+ var executingPromptRequestEventLogV2Schema = external_exports.strictObject({
21609
+ attemptId: identifierStringSchema,
21610
+ commandId: identifierStringSchema,
21611
+ epoch: identifierStringSchema,
21612
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
21613
+ tailCursor: external_exports.string().max(512),
21614
+ truncated: external_exports.boolean()
21615
+ }).readonly();
21616
+ var nativeSessionEventsV2Schema = external_exports.strictObject({
21617
+ executingPromptRequest: executingPromptRequestEventLogV2Schema.nullable(),
21618
+ history: sessionEventLogPageV2Schema
21619
+ }).readonly();
21620
+ function inputValue(value) {
21621
+ if (typeof value !== "string") {
21622
+ return value;
21623
+ }
21624
+ try {
21625
+ return JSON.parse(value);
21626
+ } catch (cause) {
21627
+ throw new ProtocolMessageError("Session Event Log V2 message is not valid JSON", { cause });
21628
+ }
21629
+ }
21630
+ function decode5(value, schema) {
21631
+ const result = schema.safeParse(inputValue(value));
21632
+ if (!result.success) {
21633
+ throw new ProtocolMessageError("Session Event Log V2 message does not match its schema", {
21634
+ cause: result.error
21635
+ });
21636
+ }
21637
+ return result.data;
21638
+ }
21639
+ function encode4(value, schema) {
21640
+ return JSON.stringify(decode5(value, schema));
21641
+ }
21642
+ var decodeSessionEventV2 = (value) => decode5(value, sessionEventV2Schema);
21643
+ var decodeSessionEventEnvelopeV2 = (value) => decode5(value, sessionEventEnvelopeV2Schema);
21644
+ var encodeSessionEventEnvelopeV2 = (value) => encode4(value, sessionEventEnvelopeV2Schema);
21645
+ var decodeAcpSessionUpdateV2 = (value) => decode5(value, acpSessionUpdateV2Schema);
21646
+
21210
21647
  // ../protocol/src/session-events.ts
21211
21648
  var SESSION_EVENT_KIND = "session.event";
21212
21649
  var SESSION_FORKED_KIND = "session.forked";
@@ -21224,7 +21661,7 @@ var sessionForkedSchema = external_exports.strictObject({
21224
21661
  sourceSessionId: identifierStringSchema,
21225
21662
  throughCommandId: identifierStringSchema
21226
21663
  }).readonly();
21227
- function decode5(encoded, schema) {
21664
+ function decode6(encoded, schema) {
21228
21665
  let value;
21229
21666
  try {
21230
21667
  value = JSON.parse(encoded);
@@ -21239,7 +21676,7 @@ function decode5(encoded, schema) {
21239
21676
  }
21240
21677
  return decoded.data;
21241
21678
  }
21242
- var encode4 = (message, schema) => {
21679
+ var encode5 = (message, schema) => {
21243
21680
  const decoded = schema.safeParse(message);
21244
21681
  if (!decoded.success) {
21245
21682
  throw new ProtocolMessageError("Message does not match its schema", {
@@ -21248,15 +21685,15 @@ var encode4 = (message, schema) => {
21248
21685
  }
21249
21686
  return JSON.stringify(decoded.data);
21250
21687
  };
21251
- var decodeSessionEventEnvelope = (encoded) => decode5(encoded, sessionEventEnvelopeSchema);
21252
- var encodeSessionEventEnvelope = (message) => encode4(message, sessionEventEnvelopeSchema);
21688
+ var decodeSessionEventEnvelope = (encoded) => decode6(encoded, sessionEventEnvelopeSchema);
21689
+ var encodeSessionEventEnvelope = (message) => encode5(message, sessionEventEnvelopeSchema);
21253
21690
  function decodeRecordedSessionEvent(encoded) {
21254
21691
  const kind = decodeMessageKind(encoded);
21255
21692
  switch (kind) {
21256
21693
  case SESSION_QUEUE_CHANGED_KIND:
21257
- return decode5(encoded, sessionQueueChangedSchema);
21694
+ return decode6(encoded, sessionQueueChangedSchema);
21258
21695
  case SESSION_FORKED_KIND:
21259
- return decode5(encoded, sessionForkedSchema);
21696
+ return decode6(encoded, sessionForkedSchema);
21260
21697
  case AGENT_ACTIVITY_KIND:
21261
21698
  return decodeAgentActivityEvent(encoded);
21262
21699
  case AGENT_ACTIVITY_NARRATION_KIND:
@@ -21300,6 +21737,8 @@ var SESSION_LIVE_HISTORY_LOAD_KIND = "session.live-history.load";
21300
21737
  var SESSION_LIVE_HISTORY_LOADED_KIND = "session.live-history.loaded";
21301
21738
  var SESSION_LIVE_HISTORY_PAGE_LOAD_KIND = "session.live-history.page.load";
21302
21739
  var SESSION_LIVE_HISTORY_PAGE_LOADED_KIND = "session.live-history.page.loaded";
21740
+ var SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND = "session.live-history.v2.page.load";
21741
+ var SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND = "session.live-history.v2.page.loaded";
21303
21742
  var directoryIdentifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
21304
21743
  var sessionLiveHistoryLoadSchema = external_exports.strictObject({
21305
21744
  additionalDirectoryIds: external_exports.array(directoryIdentifier).max(16).readonly(),
@@ -21333,7 +21772,24 @@ var sessionLiveHistoryPageLoadedSchema = external_exports.strictObject({
21333
21772
  requestId: identifierStringSchema,
21334
21773
  sessionId: identifierStringSchema
21335
21774
  }).readonly();
21336
- function decode6(schema, encoded) {
21775
+ var sessionLiveHistoryV2PageLoadSchema = external_exports.strictObject({
21776
+ additionalDirectoryIds: external_exports.array(directoryIdentifier).max(16).readonly(),
21777
+ agentId: identifierStringSchema,
21778
+ bindingId: identifierStringSchema,
21779
+ cursor: external_exports.string().min(1).max(512).nullable(),
21780
+ directoryId: directoryIdentifier,
21781
+ kind: external_exports.literal(SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND),
21782
+ eventLimit: external_exports.number().int().min(1).max(1e4),
21783
+ requestId: identifierStringSchema,
21784
+ sessionId: identifierStringSchema
21785
+ }).readonly();
21786
+ var sessionLiveHistoryV2PageLoadedSchema = external_exports.strictObject({
21787
+ events: nativeSessionEventsV2Schema,
21788
+ kind: external_exports.literal(SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND),
21789
+ requestId: identifierStringSchema,
21790
+ sessionId: identifierStringSchema
21791
+ }).readonly();
21792
+ function decode7(schema, encoded) {
21337
21793
  try {
21338
21794
  const value = JSON.parse(encoded);
21339
21795
  return schema.parse(value);
@@ -21341,14 +21797,18 @@ function decode6(schema, encoded) {
21341
21797
  throw new ProtocolMessageError("Invalid live Session history message", { cause });
21342
21798
  }
21343
21799
  }
21344
- var decodeSessionLiveHistoryLoad = (encoded) => decode6(sessionLiveHistoryLoadSchema, encoded);
21345
- var decodeSessionLiveHistoryLoaded = (encoded) => decode6(sessionLiveHistoryLoadedSchema, encoded);
21800
+ var decodeSessionLiveHistoryLoad = (encoded) => decode7(sessionLiveHistoryLoadSchema, encoded);
21801
+ var decodeSessionLiveHistoryLoaded = (encoded) => decode7(sessionLiveHistoryLoadedSchema, encoded);
21346
21802
  var encodeSessionLiveHistoryLoad = (value) => JSON.stringify(sessionLiveHistoryLoadSchema.parse(value));
21347
21803
  var encodeSessionLiveHistoryLoaded = (value) => JSON.stringify(sessionLiveHistoryLoadedSchema.parse(value));
21348
- var decodeSessionLiveHistoryPageLoad = (encoded) => decode6(sessionLiveHistoryPageLoadSchema, encoded);
21349
- var decodeSessionLiveHistoryPageLoaded = (encoded) => decode6(sessionLiveHistoryPageLoadedSchema, encoded);
21804
+ var decodeSessionLiveHistoryPageLoad = (encoded) => decode7(sessionLiveHistoryPageLoadSchema, encoded);
21805
+ var decodeSessionLiveHistoryPageLoaded = (encoded) => decode7(sessionLiveHistoryPageLoadedSchema, encoded);
21350
21806
  var encodeSessionLiveHistoryPageLoad = (value) => JSON.stringify(sessionLiveHistoryPageLoadSchema.parse(value));
21351
21807
  var encodeSessionLiveHistoryPageLoaded = (value) => JSON.stringify(sessionLiveHistoryPageLoadedSchema.parse(value));
21808
+ var decodeSessionLiveHistoryV2PageLoad = (encoded) => decode7(sessionLiveHistoryV2PageLoadSchema, encoded);
21809
+ var decodeSessionLiveHistoryV2PageLoaded = (encoded) => decode7(sessionLiveHistoryV2PageLoadedSchema, encoded);
21810
+ var encodeSessionLiveHistoryV2PageLoad = (value) => JSON.stringify(sessionLiveHistoryV2PageLoadSchema.parse(value));
21811
+ var encodeSessionLiveHistoryV2PageLoaded = (value) => JSON.stringify(sessionLiveHistoryV2PageLoadedSchema.parse(value));
21352
21812
 
21353
21813
  // ../protocol/src/daemon-transport.ts
21354
21814
  function defineMessageSignature(kind, encoder, decoder) {
@@ -21433,6 +21893,11 @@ var serviceToDaemonSignatures = {
21433
21893
  encodeSessionLiveHistoryPageLoad,
21434
21894
  decodeSessionLiveHistoryPageLoad
21435
21895
  ),
21896
+ [SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND]: defineMessageSignature(
21897
+ SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND,
21898
+ encodeSessionLiveHistoryV2PageLoad,
21899
+ decodeSessionLiveHistoryV2PageLoad
21900
+ ),
21436
21901
  [SESSION_PERMISSION_RESPOND_KIND]: defineMessageSignature(
21437
21902
  SESSION_PERMISSION_RESPOND_KIND,
21438
21903
  encodeSessionPermissionRespondCommand,
@@ -21548,6 +22013,11 @@ var daemonToServiceSignatures = {
21548
22013
  encodeSessionEventEnvelope,
21549
22014
  decodeSessionEventEnvelope
21550
22015
  ),
22016
+ [SESSION_EVENT_V2_KIND]: defineMessageSignature(
22017
+ SESSION_EVENT_V2_KIND,
22018
+ encodeSessionEventEnvelopeV2,
22019
+ decodeSessionEventEnvelopeV2
22020
+ ),
21551
22021
  [SESSION_OPERATION_FAILED_KIND]: defineMessageSignature(
21552
22022
  SESSION_OPERATION_FAILED_KIND,
21553
22023
  encodeSessionOperationFailedEvent,
@@ -21563,6 +22033,11 @@ var daemonToServiceSignatures = {
21563
22033
  encodeSessionLiveHistoryPageLoaded,
21564
22034
  decodeSessionLiveHistoryPageLoaded
21565
22035
  ),
22036
+ [SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND]: defineMessageSignature(
22037
+ SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND,
22038
+ encodeSessionLiveHistoryV2PageLoaded,
22039
+ decodeSessionLiveHistoryV2PageLoaded
22040
+ ),
21566
22041
  [SESSION_READY_KIND]: defineMessageSignature(SESSION_READY_KIND, encodeSessionReadyEvent, decodeSessionReadyEvent),
21567
22042
  [WORKSPACE_ENTRIES_KIND]: defineMessageSignature(
21568
22043
  WORKSPACE_ENTRIES_KIND,
@@ -26202,9 +26677,9 @@ function comparePrerelease(left, right) {
26202
26677
  if (left.length === 0 || right.length === 0) {
26203
26678
  return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
26204
26679
  }
26205
- for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
26206
- const leftPart = left[index];
26207
- const rightPart = right[index];
26680
+ for (let index2 = 0; index2 < Math.max(left.length, right.length); index2 += 1) {
26681
+ const leftPart = left[index2];
26682
+ const rightPart = right[index2];
26208
26683
  if (leftPart === void 0 || rightPart === void 0) {
26209
26684
  return leftPart === rightPart ? 0 : leftPart === void 0 ? -1 : 1;
26210
26685
  }
@@ -26229,8 +26704,8 @@ function compareAgentVersions(left, right) {
26229
26704
  if (parsedLeft === null || parsedRight === null) {
26230
26705
  return null;
26231
26706
  }
26232
- for (let index = 0; index < Math.max(parsedLeft.core.length, parsedRight.core.length); index += 1) {
26233
- const difference = (parsedLeft.core[index] ?? 0) - (parsedRight.core[index] ?? 0);
26707
+ for (let index2 = 0; index2 < Math.max(parsedLeft.core.length, parsedRight.core.length); index2 += 1) {
26708
+ const difference = (parsedLeft.core[index2] ?? 0) - (parsedRight.core[index2] ?? 0);
26234
26709
  if (difference !== 0) {
26235
26710
  return Math.sign(difference);
26236
26711
  }
@@ -26717,7 +27192,7 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
26717
27192
  }
26718
27193
 
26719
27194
  // src/run-daemon.ts
26720
- import { createHash as createHash5, randomUUID as randomUUID6 } from "node:crypto";
27195
+ import { createHash as createHash6, randomUUID as randomUUID6 } from "node:crypto";
26721
27196
  import { join as join17 } from "node:path";
26722
27197
  import { styleText } from "node:util";
26723
27198
 
@@ -26840,7 +27315,7 @@ function startsWith(bytes, signature, offset = 0) {
26840
27315
  if (bytes.byteLength < offset + signature.byteLength) {
26841
27316
  return false;
26842
27317
  }
26843
- return signature.every((value, index) => bytes[offset + index] === value);
27318
+ return signature.every((value, index2) => bytes[offset + index2] === value);
26844
27319
  }
26845
27320
  function sniffRasterMime(bytes) {
26846
27321
  if (startsWith(bytes, PNG_SIGNATURE)) {
@@ -26968,7 +27443,7 @@ function startsWith2(bytes, signature, offset = 0) {
26968
27443
  if (bytes.byteLength < offset + signature.byteLength) {
26969
27444
  return false;
26970
27445
  }
26971
- return signature.every((value, index) => bytes[offset + index] === value);
27446
+ return signature.every((value, index2) => bytes[offset + index2] === value);
26972
27447
  }
26973
27448
  function sniffVideoMime(bytes) {
26974
27449
  if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
@@ -27097,10 +27572,10 @@ async function replaceImageMarkers(text2, replace) {
27097
27572
  let cursor = 0;
27098
27573
  let rewritten = "";
27099
27574
  for (const match of matches) {
27100
- const index = match.index ?? 0;
27101
- rewritten += text2.slice(cursor, index);
27575
+ const index2 = match.index ?? 0;
27576
+ rewritten += text2.slice(cursor, index2);
27102
27577
  rewritten += await replace(match[1] ?? "");
27103
- cursor = index + match[0].length;
27578
+ cursor = index2 + match[0].length;
27104
27579
  }
27105
27580
  return `${rewritten}${text2.slice(cursor)}`;
27106
27581
  }
@@ -28266,6 +28741,7 @@ function sessionConfigProtocolForAgent(_agentId) {
28266
28741
 
28267
28742
  // src/acp/session-contracts.ts
28268
28743
  var NullAcpSessionObserver = class {
28744
+ onAcpUpdate = (_sessionId, _update) => Promise.resolve();
28269
28745
  onCommands = () => Promise.resolve();
28270
28746
  onConfig = () => Promise.resolve();
28271
28747
  onContent = () => Promise.resolve();
@@ -28333,6 +28809,7 @@ function historyContentCharacters(messages) {
28333
28809
  var AcpHistoryReplay = class {
28334
28810
  #activities = /* @__PURE__ */ new Map();
28335
28811
  #messages = [];
28812
+ #updates = [];
28336
28813
  #turnActivityIds = /* @__PURE__ */ new Set();
28337
28814
  #activityTracker = new AcpActivityTracker(
28338
28815
  async (activity2) => {
@@ -28354,7 +28831,8 @@ var AcpHistoryReplay = class {
28354
28831
  #firstMessageIndex = 0;
28355
28832
  #characters = 0;
28356
28833
  #truncated = false;
28357
- record = async (update) => {
28834
+ record = async (update, rawUpdate) => {
28835
+ this.#updates.push(rawUpdate);
28358
28836
  if (update.sessionUpdate === "agent_thought_chunk") {
28359
28837
  if (update.content.type === "text") {
28360
28838
  await this.#activityTracker.recordNarrative(
@@ -28435,6 +28913,20 @@ var AcpHistoryReplay = class {
28435
28913
  this.#lastMessageId = id;
28436
28914
  this.trimMessages();
28437
28915
  };
28916
+ eventPage = (eventLimit, cursor) => {
28917
+ const parsedCursor = cursor === null ? this.#updates.length : Number(cursor);
28918
+ if (!Number.isSafeInteger(parsedCursor) || parsedCursor < 0 || parsedCursor > this.#updates.length) {
28919
+ throw new Error("The native event cursor is invalid");
28920
+ }
28921
+ const endUpdate = parsedCursor;
28922
+ const startUpdate = Math.max(0, endUpdate - eventLimit);
28923
+ return {
28924
+ nextCursor: startUpdate === 0 ? null : startUpdate.toString(),
28925
+ startPosition: startUpdate + 1,
28926
+ truncated: startUpdate > 0,
28927
+ updates: this.#updates.slice(startUpdate, endUpdate)
28928
+ };
28929
+ };
28438
28930
  snapshot = async () => {
28439
28931
  await this.#activityTracker.finish();
28440
28932
  const messages = this.#messages.slice(this.#firstMessageIndex).map((message) => {
@@ -30422,8 +30914,8 @@ function haveSameKeys(left, right) {
30422
30914
  if (leftKeys.length !== rightKeys.length) {
30423
30915
  return false;
30424
30916
  }
30425
- for (const [index, key] of leftKeys.entries()) {
30426
- if (key !== rightKeys[index]) {
30917
+ for (const [index2, key] of leftKeys.entries()) {
30918
+ if (key !== rightKeys[index2]) {
30427
30919
  return false;
30428
30920
  }
30429
30921
  }
@@ -31611,6 +32103,55 @@ var sqliteTable = (name, columns, extraConfig) => {
31611
32103
  return sqliteTableBase(name, columns, extraConfig);
31612
32104
  };
31613
32105
 
32106
+ // ../../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
32107
+ var IndexBuilderOn = class {
32108
+ constructor(name, unique) {
32109
+ this.name = name;
32110
+ this.unique = unique;
32111
+ }
32112
+ static [entityKind] = "SQLiteIndexBuilderOn";
32113
+ on(...columns) {
32114
+ return new IndexBuilder(this.name, columns, this.unique);
32115
+ }
32116
+ };
32117
+ var IndexBuilder = class {
32118
+ static [entityKind] = "SQLiteIndexBuilder";
32119
+ /** @internal */
32120
+ config;
32121
+ constructor(name, columns, unique) {
32122
+ this.config = {
32123
+ name,
32124
+ columns,
32125
+ unique,
32126
+ where: void 0
32127
+ };
32128
+ }
32129
+ /**
32130
+ * Condition for partial index.
32131
+ */
32132
+ where(condition) {
32133
+ this.config.where = condition;
32134
+ return this;
32135
+ }
32136
+ /** @internal */
32137
+ build(table) {
32138
+ return new Index(this.config, table);
32139
+ }
32140
+ };
32141
+ var Index = class {
32142
+ static [entityKind] = "SQLiteIndex";
32143
+ config;
32144
+ constructor(config2, table) {
32145
+ this.config = { ...config2, table };
32146
+ }
32147
+ };
32148
+ function index(name) {
32149
+ return new IndexBuilderOn(name, false);
32150
+ }
32151
+ function uniqueIndex(name) {
32152
+ return new IndexBuilderOn(name, true);
32153
+ }
32154
+
31614
32155
  // ../../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
31615
32156
  function extractUsedTable(table) {
31616
32157
  if (is(table, SQLiteTable)) {
@@ -31959,8 +32500,8 @@ var SQLiteDialect = class {
31959
32500
  }
31960
32501
  const joinsArray = [];
31961
32502
  if (joins) {
31962
- for (const [index, joinMeta] of joins.entries()) {
31963
- if (index === 0) {
32503
+ for (const [index2, joinMeta] of joins.entries()) {
32504
+ if (index2 === 0) {
31964
32505
  joinsArray.push(sql` `);
31965
32506
  }
31966
32507
  const table = joinMeta.table;
@@ -31980,7 +32521,7 @@ var SQLiteDialect = class {
31980
32521
  sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`
31981
32522
  );
31982
32523
  }
31983
- if (index < joins.length - 1) {
32524
+ if (index2 < joins.length - 1) {
31984
32525
  joinsArray.push(sql` `);
31985
32526
  }
31986
32527
  }
@@ -31993,9 +32534,9 @@ var SQLiteDialect = class {
31993
32534
  buildOrderBy(orderBy) {
31994
32535
  const orderByList = [];
31995
32536
  if (orderBy) {
31996
- for (const [index, orderByValue] of orderBy.entries()) {
32537
+ for (const [index2, orderByValue] of orderBy.entries()) {
31997
32538
  orderByList.push(orderByValue);
31998
- if (index < orderBy.length - 1) {
32539
+ if (index2 < orderBy.length - 1) {
31999
32540
  orderByList.push(sql`, `);
32000
32541
  }
32001
32542
  }
@@ -32048,9 +32589,9 @@ var SQLiteDialect = class {
32048
32589
  const havingSql = having ? sql` having ${having}` : void 0;
32049
32590
  const groupByList = [];
32050
32591
  if (groupBy) {
32051
- for (const [index, groupByValue] of groupBy.entries()) {
32592
+ for (const [index2, groupByValue] of groupBy.entries()) {
32052
32593
  groupByList.push(groupByValue);
32053
- if (index < groupBy.length - 1) {
32594
+ if (index2 < groupBy.length - 1) {
32054
32595
  groupByList.push(sql`, `);
32055
32596
  }
32056
32597
  }
@@ -34464,6 +35005,10 @@ var acpSessionStoreMigrations = [
34464
35005
  {
34465
35006
  "name": "0001_regular_ultimates.sql",
34466
35007
  "sql": "ALTER TABLE `acp_session` ADD `last_terminal_command_id` text;"
35008
+ },
35009
+ {
35010
+ "name": "0002_equal_black_queen.sql",
35011
+ "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`);"
34467
35012
  }
34468
35013
  ];
34469
35014
 
@@ -34471,7 +35016,8 @@ var acpSessionStoreMigrations = [
34471
35016
  var acp_session_store_exports = {};
34472
35017
  __export(acp_session_store_exports, {
34473
35018
  acpSession: () => acpSession,
34474
- deletedAcpSession: () => deletedAcpSession
35019
+ deletedAcpSession: () => deletedAcpSession,
35020
+ sessionEventV2: () => sessionEventV2
34475
35021
  });
34476
35022
 
34477
35023
  // src/schema/acp-session-store/acp-session.ts
@@ -34492,6 +35038,21 @@ var deletedAcpSession = sqliteTable("deleted_acp_session", {
34492
35038
  sessionId: text("session_id").primaryKey()
34493
35039
  });
34494
35040
 
35041
+ // src/schema/acp-session-store/session-event-v2.ts
35042
+ var sessionEventV2 = sqliteTable(
35043
+ "session_event_v2",
35044
+ {
35045
+ eventId: text("event_id").primaryKey(),
35046
+ eventJson: text("event_json").notNull(),
35047
+ position: integer2("position").notNull(),
35048
+ sessionId: text("session_id").notNull()
35049
+ },
35050
+ (table) => [
35051
+ uniqueIndex("session_event_v2_session_position_unique").on(table.sessionId, table.position),
35052
+ index("session_event_v2_session_position_index").on(table.sessionId, table.position)
35053
+ ]
35054
+ );
35055
+
34495
35056
  // src/acp/session-store.ts
34496
35057
  var AcpStoredSession = class {
34497
35058
  additionalDirectories;
@@ -34534,9 +35095,21 @@ var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
34534
35095
  var MemoryAcpSessionStore = class {
34535
35096
  #sessions = /* @__PURE__ */ new Map();
34536
35097
  #deleted = /* @__PURE__ */ new Set();
35098
+ #eventsV2 = /* @__PURE__ */ new Map();
35099
+ appendExecutingPromptEventV2 = (event) => {
35100
+ const events = this.#eventsV2.get(event.sessionId);
35101
+ if (events === void 0) {
35102
+ throw new Error("The executing prompt event log has not started");
35103
+ }
35104
+ events.push(event);
35105
+ };
35106
+ clearExecutingPromptEventsV2 = (sessionId) => {
35107
+ this.#eventsV2.delete(sessionId);
35108
+ };
34537
35109
  close = () => {
34538
35110
  this.#sessions.clear();
34539
35111
  this.#deleted.clear();
35112
+ this.#eventsV2.clear();
34540
35113
  };
34541
35114
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
34542
35115
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
@@ -34547,6 +35120,7 @@ var MemoryAcpSessionStore = class {
34547
35120
  for (const id of ids) {
34548
35121
  this.#sessions.delete(id);
34549
35122
  this.#deleted.add(id);
35123
+ this.#eventsV2.delete(id);
34550
35124
  }
34551
35125
  return ids;
34552
35126
  };
@@ -34559,6 +35133,13 @@ var MemoryAcpSessionStore = class {
34559
35133
  };
34560
35134
  remove = (sessionId) => {
34561
35135
  this.#sessions.delete(sessionId);
35136
+ this.#eventsV2.delete(sessionId);
35137
+ };
35138
+ readExecutingPromptEventsV2 = (sessionId) => [
35139
+ ...this.#eventsV2.get(sessionId) ?? []
35140
+ ];
35141
+ startExecutingPromptEventsV2 = (sessionId, events) => {
35142
+ this.#eventsV2.set(sessionId, [...events]);
34562
35143
  };
34563
35144
  write = (session) => {
34564
35145
  this.#sessions.set(session.sessionId, session);
@@ -34608,15 +35189,15 @@ var SqliteAcpSessionStore = class {
34608
35189
  this.#sqliteDatabase.close();
34609
35190
  throw new Error("The ACP Session database was created by a newer Mobius version");
34610
35191
  }
34611
- for (let index = version3; index < acpSessionStoreMigrations.length; index += 1) {
34612
- const migration = acpSessionStoreMigrations[index];
35192
+ for (let index2 = version3; index2 < acpSessionStoreMigrations.length; index2 += 1) {
35193
+ const migration = acpSessionStoreMigrations[index2];
34613
35194
  if (migration === void 0) {
34614
35195
  throw new Error("The ACP Session migration is unavailable");
34615
35196
  }
34616
35197
  this.#sqliteDatabase.exec("BEGIN IMMEDIATE");
34617
35198
  try {
34618
35199
  this.#sqliteDatabase.exec(migration.sql);
34619
- this.#sqliteDatabase.pragma(`user_version = ${index + 1}`);
35200
+ this.#sqliteDatabase.pragma(`user_version = ${index2 + 1}`);
34620
35201
  this.#sqliteDatabase.exec("COMMIT");
34621
35202
  } catch (error62) {
34622
35203
  this.#sqliteDatabase.exec("ROLLBACK");
@@ -34627,6 +35208,30 @@ var SqliteAcpSessionStore = class {
34627
35208
  close = () => {
34628
35209
  this.#sqliteDatabase.close();
34629
35210
  };
35211
+ appendExecutingPromptEventV2 = (event) => {
35212
+ this.#database.insert(sessionEventV2).values({
35213
+ eventId: event.eventId,
35214
+ eventJson: JSON.stringify(event),
35215
+ position: Number(event.position),
35216
+ sessionId: event.sessionId
35217
+ }).run();
35218
+ };
35219
+ clearExecutingPromptEventsV2 = (sessionId) => {
35220
+ this.#database.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
35221
+ };
35222
+ startExecutingPromptEventsV2 = (sessionId, events) => {
35223
+ this.#database.transaction((transaction) => {
35224
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
35225
+ for (const event of events) {
35226
+ transaction.insert(sessionEventV2).values({
35227
+ eventId: event.eventId,
35228
+ eventJson: JSON.stringify(event),
35229
+ position: Number(event.position),
35230
+ sessionId: event.sessionId
35231
+ }).run();
35232
+ }
35233
+ });
35234
+ };
34630
35235
  findNative = (agentId, nativeSessionId) => this.#database.select().from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map(decodeStoredSession);
34631
35236
  list = () => this.#database.select().from(acpSession).orderBy(desc(acpSession.updatedAt)).all().map(decodeStoredSession);
34632
35237
  markDeleted = (agentId, nativeSessionId) => {
@@ -34635,6 +35240,7 @@ var SqliteAcpSessionStore = class {
34635
35240
  transaction.delete(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).run();
34636
35241
  for (const id of ids) {
34637
35242
  transaction.insert(deletedAcpSession).values({ sessionId: id }).onConflictDoNothing().run();
35243
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, id)).run();
34638
35244
  }
34639
35245
  });
34640
35246
  return ids;
@@ -34648,8 +35254,12 @@ var SqliteAcpSessionStore = class {
34648
35254
  const row = this.#database.select().from(acpSession).where(eq(acpSession.sessionId, sessionId)).get();
34649
35255
  return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeStoredSession(row));
34650
35256
  };
35257
+ 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));
34651
35258
  remove = (sessionId) => {
34652
- this.#database.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
35259
+ this.#database.transaction((transaction) => {
35260
+ transaction.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
35261
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
35262
+ });
34653
35263
  };
34654
35264
  write = (session) => {
34655
35265
  const value = {
@@ -34682,7 +35292,7 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
34682
35292
  }
34683
35293
  };
34684
35294
  function arraysEqual(left, right) {
34685
- return left.length === right.length && left.every((value, index) => value === right[index]);
35295
+ return left.length === right.length && left.every((value, index2) => value === right[index2]);
34686
35296
  }
34687
35297
  function recordsEqual(left, right) {
34688
35298
  const leftEntries = Object.entries(left);
@@ -34829,6 +35439,17 @@ var AgentSession = class _AgentSession {
34829
35439
  const loaded = await this.#loadSession(signal, "ACP agent exited while loading history");
34830
35440
  return await embedLocalHistoryImages(await loaded.history.snapshot(), signal);
34831
35441
  };
35442
+ loadHistoryEventsV2 = async (eventLimit, cursor, signal) => {
35443
+ if (!this.#capabilities.loadSession) {
35444
+ throw new AcpExecutionError(
35445
+ "This Agent restores context but does not provide message history.",
35446
+ {},
35447
+ "native_history_unsupported"
35448
+ );
35449
+ }
35450
+ const loaded = await this.#loadSession(signal, "ACP agent exited while loading history");
35451
+ return loaded.history.eventPage(eventLimit, cursor);
35452
+ };
34832
35453
  async #loadSession(signal, exitMessage) {
34833
35454
  if (this.#sessionLoad.kind === "loaded") {
34834
35455
  return this.#sessionLoad;
@@ -35311,6 +35932,19 @@ var AgentSession = class _AgentSession {
35311
35932
  if (this.#turn.running) {
35312
35933
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
35313
35934
  }
35935
+ switch (this.#sessionLoad.kind) {
35936
+ case "not-requested":
35937
+ break;
35938
+ case "loaded":
35939
+ this.#sessionLoad = { kind: "not-requested" };
35940
+ break;
35941
+ case "capturing":
35942
+ throw new AcpExecutionError("Session history is still loading", {}, "session_busy");
35943
+ default: {
35944
+ const unexpected = this.#sessionLoad;
35945
+ throw new Error(`Unexpected Session load state: ${JSON.stringify(unexpected)}`);
35946
+ }
35947
+ }
35314
35948
  const prompt = this.buildPrompt(options);
35315
35949
  if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
35316
35950
  this.#sessionTitle = truncate(options.prompt, 500);
@@ -35475,8 +36109,14 @@ var AgentSession = class _AgentSession {
35475
36109
  #processUpdate = async (notification) => {
35476
36110
  this.assertNativeSession(notification.sessionId);
35477
36111
  const update = notification.update;
35478
- if (this.#sessionLoad.kind !== "not-requested") {
35479
- await this.#sessionLoad.history.record(update);
36112
+ const rawUpdate = decodeAcpSessionUpdateV2(JSON.stringify(update));
36113
+ if (this.#sessionLoad.kind === "capturing") {
36114
+ await this.#sessionLoad.history.record(update, rawUpdate);
36115
+ } else {
36116
+ const onAcpUpdate = this.#getObserver().onAcpUpdate;
36117
+ if (onAcpUpdate !== void 0) {
36118
+ await onAcpUpdate(this.#mobiusSessionId, rawUpdate);
36119
+ }
35480
36120
  }
35481
36121
  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")) {
35482
36122
  return;
@@ -35858,6 +36498,21 @@ var AgentQueryProcesses = class {
35858
36498
  async (runtime) => await runtime.closeProcess()
35859
36499
  );
35860
36500
  };
36501
+ previewEventsV2 = async (options, nativeSessionId, eventLimit, cursor) => {
36502
+ return await this.#processes.runTransient(
36503
+ options.signal,
36504
+ async () => await AgentSession.startNativeSessionBrowser(
36505
+ options,
36506
+ () => this.#observer,
36507
+ new MemoryAcpSessionStore()
36508
+ ),
36509
+ async (runtime) => {
36510
+ runtime.selectNativeSession(nativeSessionId);
36511
+ return await runtime.loadHistoryEventsV2(eventLimit, cursor, options.signal);
36512
+ },
36513
+ async (runtime) => await runtime.closeProcess()
36514
+ );
36515
+ };
35861
36516
  close = async () => {
35862
36517
  await Promise.all(
35863
36518
  this.#processesByQuery.entries().map(async ([id, runtime]) => await this.retire(id, runtime))
@@ -35927,9 +36582,9 @@ var AcpProcessCapacityLock = class {
35927
36582
  return await waiter.completion.promise;
35928
36583
  } finally {
35929
36584
  signal.removeEventListener("abort", waiter.cancel);
35930
- const index = this.#waiters.indexOf(waiter);
35931
- if (index >= 0) {
35932
- this.#waiters.splice(index, 1);
36585
+ const index2 = this.#waiters.indexOf(waiter);
36586
+ if (index2 >= 0) {
36587
+ this.#waiters.splice(index2, 1);
35933
36588
  }
35934
36589
  }
35935
36590
  };
@@ -36559,6 +37214,22 @@ var AgentRuntimeManager = class {
36559
37214
  this.#nativeOperations.delete(key);
36560
37215
  }
36561
37216
  });
37217
+ previewNativeSessionEventsV2 = async (options, nativeSessionId, eventLimit, cursor) => this.#operations.run(options, async (options2) => {
37218
+ const key = `${options2.agent.id}:${nativeSessionId}`;
37219
+ if (this.#nativeOperations.has(key)) {
37220
+ throw new AcpExecutionError(
37221
+ "Wait for the native session's running operation to finish",
37222
+ {},
37223
+ "session_busy"
37224
+ );
37225
+ }
37226
+ this.#nativeOperations.add(key);
37227
+ try {
37228
+ return await this.#queryProcesses.previewEventsV2(options2, nativeSessionId, eventLimit, cursor);
37229
+ } finally {
37230
+ this.#nativeOperations.delete(key);
37231
+ }
37232
+ });
36562
37233
  loadSessionHistory = async (options) => this.#operations.run(options, async (options2) => {
36563
37234
  return await this.#executionProcesses.use(options2.sessionId, async () => {
36564
37235
  const runtime = await this.ensureSession(options2);
@@ -36576,6 +37247,12 @@ var AgentRuntimeManager = class {
36576
37247
  return await runtime.loadHistory(options2.signal);
36577
37248
  });
36578
37249
  });
37250
+ loadSessionEventsV2 = async (options, eventLimit, cursor) => this.#operations.run(options, async (options2) => {
37251
+ return await this.#executionProcesses.use(options2.sessionId, async () => {
37252
+ const runtime = await this.ensureSession(options2);
37253
+ return await runtime.loadHistoryEventsV2(eventLimit, cursor, options2.signal);
37254
+ });
37255
+ });
36579
37256
  openNativeSession = async (options, origin) => this.#operations.run(options, async (options2) => {
36580
37257
  const key = `${options2.agent.id}:${origin.nativeSessionId}`;
36581
37258
  if (this.#nativeOperations.has(key)) {
@@ -37778,9 +38455,15 @@ function reportOperationFailure(socket, requestId, sessionId, error62, runtimeTi
37778
38455
  // src/daemon-observers.ts
37779
38456
  var DaemonAcpObserver = class {
37780
38457
  #record;
37781
- constructor(record2) {
38458
+ #recordV2;
38459
+ constructor(record2, recordV2 = () => void 0) {
37782
38460
  this.#record = record2;
38461
+ this.#recordV2 = recordV2;
37783
38462
  }
38463
+ onAcpUpdate = (sessionId, update) => {
38464
+ this.#recordV2(sessionId, { payload: update, type: "acp" });
38465
+ return Promise.resolve();
38466
+ };
37784
38467
  onCommands = (event) => {
37785
38468
  this.#record(event.sessionId, event);
37786
38469
  return Promise.resolve();
@@ -37795,10 +38478,18 @@ var DaemonAcpObserver = class {
37795
38478
  };
37796
38479
  onElicitation = (event) => {
37797
38480
  this.#record(event.sessionId, event);
38481
+ this.#recordV2(event.sessionId, {
38482
+ payload: { event, kind: "session.elicitation.requested" },
38483
+ type: "lifecycle-metadata"
38484
+ });
37798
38485
  return Promise.resolve();
37799
38486
  };
37800
38487
  onElicitationResolved = (event) => {
37801
38488
  this.#record(event.sessionId, event);
38489
+ this.#recordV2(event.sessionId, {
38490
+ payload: { event, kind: "session.elicitation.resolved" },
38491
+ type: "lifecycle-metadata"
38492
+ });
37802
38493
  return Promise.resolve();
37803
38494
  };
37804
38495
  onInfo = (event) => {
@@ -37807,10 +38498,18 @@ var DaemonAcpObserver = class {
37807
38498
  };
37808
38499
  onPermission = (event) => {
37809
38500
  this.#record(event.sessionId, event);
38501
+ this.#recordV2(event.sessionId, {
38502
+ payload: { event, kind: "session.permission.requested" },
38503
+ type: "lifecycle-metadata"
38504
+ });
37810
38505
  return Promise.resolve();
37811
38506
  };
37812
38507
  onPermissionResolved = (event) => {
37813
38508
  this.#record(event.sessionId, event);
38509
+ this.#recordV2(event.sessionId, {
38510
+ payload: { event, kind: "session.permission.resolved" },
38511
+ type: "lifecycle-metadata"
38512
+ });
37814
38513
  return Promise.resolve();
37815
38514
  };
37816
38515
  onUsage = (event) => {
@@ -37917,8 +38616,8 @@ var ACTIVE_TURN_TEXT_CHUNK_LIMIT = Math.floor(SESSION_HISTORY_CHARACTER_LIMIT /
37917
38616
  function boundedRecoveryMessages(messages) {
37918
38617
  const selected = [];
37919
38618
  let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT;
37920
- for (let index = messages.length - 1; index >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index -= 1) {
37921
- const message = messages[index];
38619
+ for (let index2 = messages.length - 1; index2 >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index2 -= 1) {
38620
+ const message = messages[index2];
37922
38621
  if (message === void 0) {
37923
38622
  break;
37924
38623
  }
@@ -38059,7 +38758,7 @@ var ActiveDaemonTurn = class {
38059
38758
  ];
38060
38759
  } else {
38061
38760
  this.#timeline = this.#timeline.map(
38062
- (entry, index) => index === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
38761
+ (entry, index2) => index2 === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
38063
38762
  );
38064
38763
  }
38065
38764
  } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
@@ -39070,7 +39769,7 @@ async function readAcpHistory(sessions, directories, bindingId, options, nativeS
39070
39769
  async (directory) => await directories.identify(bindingId, directory, options.signal)
39071
39770
  )
39072
39771
  );
39073
- if (primary.path !== options.cwd || additional.length !== options.additionalDirectories.length || additional.some((directory, index) => directory.path !== options.additionalDirectories[index])) {
39772
+ if (primary.path !== options.cwd || additional.length !== options.additionalDirectories.length || additional.some((directory, index2) => directory.path !== options.additionalDirectories[index2])) {
39074
39773
  throw new AcpExecutionError(
39075
39774
  "The native Session belongs to another workspace.",
39076
39775
  {},
@@ -39203,7 +39902,7 @@ var NativeSessionService = class {
39203
39902
  "native_session_not_found"
39204
39903
  );
39205
39904
  }
39206
- if (source.agentId !== command.agentId || source.cwd !== cwd || source.additionalDirectories.length !== additionalDirectories.length || source.additionalDirectories.some((path2, index) => path2 !== additionalDirectories[index])) {
39905
+ if (source.agentId !== command.agentId || source.cwd !== cwd || source.additionalDirectories.length !== additionalDirectories.length || source.additionalDirectories.some((path2, index2) => path2 !== additionalDirectories[index2])) {
39207
39906
  throw new AcpExecutionError(
39208
39907
  "The source conversation execution target does not match the fork request",
39209
39908
  {},
@@ -39224,8 +39923,8 @@ var NativeSessionService = class {
39224
39923
  signal.throwIfAborted();
39225
39924
  const directory = await this.#directories.list(this.#config.bindingId, command.directoryId, signal);
39226
39925
  const ready2 = {
39227
- additionalDirectories: additionalDirectories.map((path2, index) => ({
39228
- directoryId: command.additionalDirectoryIds[index] ?? command.directoryId,
39926
+ additionalDirectories: additionalDirectories.map((path2, index2) => ({
39927
+ directoryId: command.additionalDirectoryIds[index2] ?? command.directoryId,
39229
39928
  name: basename4(path2) || path2
39230
39929
  })),
39231
39930
  agentId: command.agentId,
@@ -39557,7 +40256,7 @@ var NativeSessionService = class {
39557
40256
  resolveTarget = async (command, options, selected) => {
39558
40257
  let cursor = null;
39559
40258
  const visited = /* @__PURE__ */ new Set();
39560
- for (let index = 0; index < 100; index += 1) {
40259
+ for (let index2 = 0; index2 < 100; index2 += 1) {
39561
40260
  const page = await this.#sessions.listNativeSessions(options, cursor);
39562
40261
  const info = page.sessions.find((entry) => entry.sessionId === selected.nativeSessionId);
39563
40262
  if (info !== void 0) {
@@ -39565,7 +40264,7 @@ var NativeSessionService = class {
39565
40264
  if (target === null) {
39566
40265
  throw new LocalAuthorizationError("The selected native session is not authorized");
39567
40266
  }
39568
- if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path2, index2) => path2 !== selected.additionalDirectories[index2])) {
40267
+ if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path2, index3) => path2 !== selected.additionalDirectories[index3])) {
39569
40268
  throw new AcpExecutionError(
39570
40269
  "This session's directory changed. Refresh the list before continuing.",
39571
40270
  {},
@@ -40653,6 +41352,9 @@ async function streamLocalFile(command, send2, signal, workingDirectory) {
40653
41352
  });
40654
41353
  }
40655
41354
 
41355
+ // src/daemon-history-commands.ts
41356
+ import { createHash as createHash5 } from "node:crypto";
41357
+
40656
41358
  // src/authorization/resolve-session-directories.ts
40657
41359
  import { basename as basename6 } from "node:path";
40658
41360
  var ResolvedSessionDirectories = class {
@@ -40752,8 +41454,8 @@ function selectMessagesBefore(messages, endIndex, messageLimit, characterLimit)
40752
41454
  const selected = [];
40753
41455
  let remainingCharacters = characterLimit;
40754
41456
  let startIndex = endIndex;
40755
- for (let index = endIndex - 1; index >= 0 && selected.length < messageLimit; index -= 1) {
40756
- const message = messages[index];
41457
+ for (let index2 = endIndex - 1; index2 >= 0 && selected.length < messageLimit; index2 -= 1) {
41458
+ const message = messages[index2];
40757
41459
  if (message === void 0) {
40758
41460
  break;
40759
41461
  }
@@ -40763,7 +41465,7 @@ function selectMessagesBefore(messages, endIndex, messageLimit, characterLimit)
40763
41465
  }
40764
41466
  selected.unshift(message);
40765
41467
  remainingCharacters -= characters;
40766
- startIndex = index;
41468
+ startIndex = index2;
40767
41469
  }
40768
41470
  if (selected.length === 0 && endIndex > 0) {
40769
41471
  throw new AcpExecutionError(
@@ -41043,6 +41745,70 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
41043
41745
  });
41044
41746
  }
41045
41747
  }
41748
+ function replayEvent(sessionId, position, update) {
41749
+ const encoded = JSON.stringify(update);
41750
+ const eventId = `native-${createHash5("sha256").update(sessionId).update(":").update(position.toString()).update(":").update(encoded).digest("hex")}`;
41751
+ return {
41752
+ eventId,
41753
+ payload: update,
41754
+ position: position.toString(),
41755
+ provenance: { kind: "original" },
41756
+ recordedAt: "1970-01-01T00:00:00.000Z",
41757
+ sessionId,
41758
+ type: "acp"
41759
+ };
41760
+ }
41761
+ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, sessions, executingPromptRequest, signal) {
41762
+ try {
41763
+ const resolved = await resolveSessionDirectories(
41764
+ directories,
41765
+ config2.bindingId,
41766
+ command.directoryId,
41767
+ command.additionalDirectoryIds,
41768
+ signal
41769
+ );
41770
+ const replay = await sessions.loadSessionEventsV2(
41771
+ {
41772
+ additionalDirectories: resolved.additionalDirectories,
41773
+ agent: config2.catalog.find(command.agentId),
41774
+ cwd: resolved.cwd,
41775
+ sessionId: command.sessionId,
41776
+ signal
41777
+ },
41778
+ command.eventLimit,
41779
+ command.cursor
41780
+ );
41781
+ signal.throwIfAborted();
41782
+ const events = replay.updates.map(
41783
+ (update, index2) => replayEvent(command.sessionId, replay.startPosition + index2, update)
41784
+ );
41785
+ const tailCursor = events.at(-1)?.eventId ?? "";
41786
+ audit.record({
41787
+ commandId: command.requestId,
41788
+ event: "session_event_log_v2_loaded",
41789
+ sessionId: command.sessionId
41790
+ });
41791
+ send(socket, {
41792
+ events: {
41793
+ executingPromptRequest: executingPromptRequest(command.sessionId),
41794
+ history: {
41795
+ events,
41796
+ nextCursor: replay.nextCursor,
41797
+ tailCursor,
41798
+ truncated: replay.truncated,
41799
+ version: 2
41800
+ }
41801
+ },
41802
+ kind: "session.live-history.v2.page.loaded",
41803
+ requestId: command.requestId,
41804
+ sessionId: command.sessionId
41805
+ });
41806
+ } catch (error62) {
41807
+ if (!signal.aborted) {
41808
+ reportOperationFailure(socket, command.requestId, command.sessionId, error62);
41809
+ }
41810
+ }
41811
+ }
41046
41812
 
41047
41813
  // src/acp/session-config/apply-session-configuration.ts
41048
41814
  import { randomUUID as randomUUID4 } from "node:crypto";
@@ -41357,6 +42123,7 @@ function daemonActivity(command, activity2) {
41357
42123
  async function executePrompt({
41358
42124
  operations,
41359
42125
  publisher,
42126
+ eventLogV2,
41360
42127
  command,
41361
42128
  config: config2,
41362
42129
  directories,
@@ -41461,6 +42228,7 @@ async function executePrompt({
41461
42228
  }
41462
42229
  }
41463
42230
  const stream = activateAttempt();
42231
+ eventLogV2.started(command.sessionId, command.commandId, attemptId, stream.epoch);
41464
42232
  if (!prepared.prompted) {
41465
42233
  const listing = await directories.list(config2.bindingId, command.directoryId, signal);
41466
42234
  publisher.publish(command.sessionId, {
@@ -41530,6 +42298,7 @@ async function executePrompt({
41530
42298
  sessionId: command.sessionId,
41531
42299
  stopReason
41532
42300
  });
42301
+ eventLogV2.completed(command.sessionId, command.commandId, stopReason);
41533
42302
  operations.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
41534
42303
  audit.record({
41535
42304
  commandId: command.commandId,
@@ -41545,6 +42314,7 @@ async function executePrompt({
41545
42314
  sessionId: command.sessionId,
41546
42315
  stopReason: "cancelled"
41547
42316
  });
42317
+ eventLogV2.completed(command.sessionId, command.commandId, "cancelled");
41548
42318
  operations.transitionExecution(command.commandId, "cancelled");
41549
42319
  audit.record({
41550
42320
  commandId: command.commandId,
@@ -41559,12 +42329,10 @@ async function executePrompt({
41559
42329
  sessionId: command.sessionId
41560
42330
  });
41561
42331
  const code = operationErrorCode(error62);
41562
- reportFailure(
41563
- publisher,
41564
- command,
41565
- code === "session_operation_failed" ? "agent_execution_failed" : code,
41566
- code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62)
41567
- );
42332
+ const failureCode = code === "session_operation_failed" ? "agent_execution_failed" : code;
42333
+ const failureMessage = code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62);
42334
+ eventLogV2.failed(command.sessionId, command.commandId, failureCode, failureMessage);
42335
+ reportFailure(publisher, command, failureCode, failureMessage);
41568
42336
  operations.transitionExecution(command.commandId, "failed");
41569
42337
  console.error("Mobius daemon command failed", error62);
41570
42338
  }
@@ -41847,6 +42615,7 @@ function createDaemonCommandHandler({
41847
42615
  nativeSessions,
41848
42616
  operations,
41849
42617
  publisher,
42618
+ eventLogV2,
41850
42619
  activeTurns,
41851
42620
  diagnostics,
41852
42621
  socket,
@@ -41874,7 +42643,10 @@ function createDaemonCommandHandler({
41874
42643
  timer,
41875
42644
  resolveEnvironment: resolveAgentCatalogEnvironment
41876
42645
  });
41877
- const queueChanged = (sessionId) => publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
42646
+ const queueChanged = (sessionId) => {
42647
+ publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
42648
+ eventLogV2.queueChanged(sessionId);
42649
+ };
41878
42650
  const activeTurnRecovery = (sessionId) => activeTurns.recovery((command) => command.sessionId === sessionId);
41879
42651
  const nativeRequestHandler = createNativeSessionRequestHandler({
41880
42652
  audit,
@@ -41916,6 +42688,19 @@ function createDaemonCommandHandler({
41916
42688
  );
41917
42689
  return;
41918
42690
  }
42691
+ if (kind === SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND) {
42692
+ void executeSessionLiveHistoryV2PageLoad(
42693
+ socket,
42694
+ message,
42695
+ config2,
42696
+ directories,
42697
+ audit,
42698
+ sessions,
42699
+ eventLogV2.executingPromptRequest,
42700
+ signal
42701
+ );
42702
+ return;
42703
+ }
41919
42704
  if (kind === NATIVE_SESSION_CANCEL_KIND) {
41920
42705
  nativeRequestHandler.cancel(message);
41921
42706
  return;
@@ -42101,9 +42886,11 @@ function createDaemonCommandHandler({
42101
42886
  return;
42102
42887
  }
42103
42888
  const turn = activeTurns.start(command, receipt.attemptId);
42889
+ eventLogV2.requested(command);
42104
42890
  void executePrompt({
42105
42891
  operations,
42106
42892
  publisher,
42893
+ eventLogV2,
42107
42894
  command,
42108
42895
  config: config2,
42109
42896
  directories,
@@ -42393,6 +43180,7 @@ async function runRelayConnection({
42393
43180
  nativeSessions,
42394
43181
  operations,
42395
43182
  publisher,
43183
+ eventLogV2,
42396
43184
  activeTurns,
42397
43185
  connectionEpoch,
42398
43186
  diagnostics,
@@ -42415,6 +43203,7 @@ async function runRelayConnection({
42415
43203
  nativeSessions,
42416
43204
  operations,
42417
43205
  publisher,
43206
+ eventLogV2,
42418
43207
  activeTurns,
42419
43208
  diagnostics,
42420
43209
  socket,
@@ -42594,6 +43383,21 @@ var DaemonSessionEventPublisher = class {
42594
43383
  this.publish(sessionId, event);
42595
43384
  }
42596
43385
  };
43386
+ publishV2 = (event) => {
43387
+ const socket = this.#socket;
43388
+ if (socket === null || socket.readyState !== WebSocket9.OPEN) {
43389
+ return;
43390
+ }
43391
+ const encoded = encodeDaemonToServiceMessage({ event, kind: SESSION_EVENT_V2_KIND });
43392
+ if (socket.bufferedAmount + Buffer.byteLength(encoded, "utf8") > MAX_BUFFERED_BYTES) {
43393
+ socket.close(1013, "Live event transport overloaded");
43394
+ return;
43395
+ }
43396
+ try {
43397
+ socket.send(encoded);
43398
+ } catch {
43399
+ }
43400
+ };
42597
43401
  };
42598
43402
 
42599
43403
  // src/relay-connection/timer.ts
@@ -42605,6 +43409,266 @@ var SystemDaemonTimer = class {
42605
43409
  };
42606
43410
  var systemDaemonTimer = new SystemDaemonTimer();
42607
43411
 
43412
+ // src/session-event-log-v2.ts
43413
+ var EXECUTING_PROMPT_EVENT_LIMIT = 1e4;
43414
+ function eventArray(tail) {
43415
+ const reversed = [];
43416
+ let node2 = tail;
43417
+ while (node2 !== null) {
43418
+ reversed.push(node2.event);
43419
+ node2 = node2.previous;
43420
+ }
43421
+ return reversed.reverse();
43422
+ }
43423
+ function promptContent(command) {
43424
+ const content = [];
43425
+ if (command.prompt.length > 0) {
43426
+ content.push({ text: command.prompt, type: "text" });
43427
+ }
43428
+ for (const image of command.images) {
43429
+ content.push({
43430
+ _meta: { mobius: { name: image.name } },
43431
+ data: image.data,
43432
+ mimeType: image.mimeType,
43433
+ type: "image"
43434
+ });
43435
+ }
43436
+ for (const resource of command.resources) {
43437
+ content.push(
43438
+ resource.type === "embedded" ? {
43439
+ resource: { mimeType: resource.mimeType, text: resource.text, uri: resource.uri },
43440
+ type: "resource"
43441
+ } : { mimeType: resource.mimeType, name: resource.name, type: "resource_link", uri: resource.uri }
43442
+ );
43443
+ }
43444
+ return content;
43445
+ }
43446
+ var DaemonSessionEventLogV2 = class {
43447
+ #positions = /* @__PURE__ */ new Map();
43448
+ #requests = /* @__PURE__ */ new Map();
43449
+ #loadedRequestSessions = /* @__PURE__ */ new Set();
43450
+ #publisher;
43451
+ #store;
43452
+ constructor(publisher, store) {
43453
+ this.#publisher = publisher;
43454
+ this.#store = store;
43455
+ }
43456
+ #loadStoredEvents = (sessionId) => {
43457
+ const stored = this.#store.readExecutingPromptEventsV2(sessionId);
43458
+ const lastPosition = stored.at(-1)?.position;
43459
+ if (lastPosition !== void 0) {
43460
+ this.#positions.set(sessionId, Number(lastPosition));
43461
+ }
43462
+ return stored;
43463
+ };
43464
+ #loadRequests = (sessionId) => {
43465
+ if (this.#loadedRequestSessions.has(sessionId)) {
43466
+ return;
43467
+ }
43468
+ for (const event of this.#loadStoredEvents(sessionId)) {
43469
+ if (event.type === "acp") {
43470
+ const executing = [...this.#requests.values()].find(
43471
+ (request) => request.sessionId === sessionId && request.kind === "executing"
43472
+ );
43473
+ if (executing !== void 0) {
43474
+ this.#requests.set(executing.commandId, {
43475
+ ...executing,
43476
+ eventTail: { event, previous: executing.eventTail }
43477
+ });
43478
+ }
43479
+ continue;
43480
+ }
43481
+ const payload = event.payload;
43482
+ if (payload.kind === "prompt.requested") {
43483
+ this.#requests.set(payload.commandId, {
43484
+ commandId: payload.commandId,
43485
+ eventTail: { event, previous: null },
43486
+ kind: "requested",
43487
+ sessionId
43488
+ });
43489
+ continue;
43490
+ }
43491
+ if ("event" in payload) {
43492
+ const executing = [...this.#requests.values()].find(
43493
+ (request) => request.sessionId === sessionId && request.kind === "executing"
43494
+ );
43495
+ if (executing !== void 0) {
43496
+ this.#requests.set(executing.commandId, {
43497
+ ...executing,
43498
+ eventTail: { event, previous: executing.eventTail }
43499
+ });
43500
+ }
43501
+ continue;
43502
+ }
43503
+ if (!("commandId" in payload)) {
43504
+ continue;
43505
+ }
43506
+ const state = this.#requests.get(payload.commandId);
43507
+ if (state === void 0) {
43508
+ continue;
43509
+ }
43510
+ if (payload.kind === "prompt.started") {
43511
+ this.#requests.set(payload.commandId, {
43512
+ attemptId: payload.attemptId,
43513
+ commandId: payload.commandId,
43514
+ epoch: payload.epoch,
43515
+ eventTail: { event, previous: state.eventTail },
43516
+ kind: "executing",
43517
+ sessionId
43518
+ });
43519
+ } else if (payload.kind === "prompt.completed" || payload.kind === "prompt.failed" || payload.kind === "prompt.failed-before-start") {
43520
+ this.#requests.delete(payload.commandId);
43521
+ }
43522
+ }
43523
+ this.#loadedRequestSessions.add(sessionId);
43524
+ };
43525
+ #append = (sessionId, payload) => {
43526
+ this.#loadRequests(sessionId);
43527
+ const position = (this.#positions.get(sessionId) ?? 0) + 1;
43528
+ const event = {
43529
+ eventId: `event-${crypto.randomUUID()}`,
43530
+ ...payload,
43531
+ position: position.toString(),
43532
+ provenance: { kind: "original" },
43533
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
43534
+ sessionId
43535
+ };
43536
+ this.#positions.set(sessionId, position);
43537
+ this.#publisher.publishV2(event);
43538
+ return event;
43539
+ };
43540
+ requested = (command) => {
43541
+ const content = promptContent(command);
43542
+ const event = this.#append(command.sessionId, {
43543
+ payload: { commandId: command.commandId, content, kind: "prompt.requested" },
43544
+ type: "lifecycle-metadata"
43545
+ });
43546
+ let eventTail = { event, previous: null };
43547
+ for (const block of content) {
43548
+ const userMessageEvent = this.#append(command.sessionId, {
43549
+ payload: {
43550
+ content: block,
43551
+ messageId: command.commandId,
43552
+ sessionUpdate: "user_message_chunk"
43553
+ },
43554
+ type: "acp"
43555
+ });
43556
+ eventTail = { event: userMessageEvent, previous: eventTail };
43557
+ }
43558
+ this.#requests.set(command.commandId, {
43559
+ commandId: command.commandId,
43560
+ eventTail,
43561
+ kind: "requested",
43562
+ sessionId: command.sessionId
43563
+ });
43564
+ };
43565
+ started = (sessionId, commandId, attemptId, epoch) => {
43566
+ this.#loadRequests(sessionId);
43567
+ const request = this.#requests.get(commandId);
43568
+ if (request?.sessionId !== sessionId) {
43569
+ return;
43570
+ }
43571
+ const event = this.#append(sessionId, {
43572
+ payload: { attemptId, commandId, epoch, kind: "prompt.started" },
43573
+ type: "lifecycle-metadata"
43574
+ });
43575
+ this.#requests.set(commandId, {
43576
+ attemptId,
43577
+ commandId,
43578
+ epoch,
43579
+ eventTail: { event, previous: request.eventTail },
43580
+ kind: "executing",
43581
+ sessionId
43582
+ });
43583
+ this.#store.startExecutingPromptEventsV2(sessionId, eventArray({ event, previous: request.eventTail }));
43584
+ };
43585
+ record = (sessionId, payload) => {
43586
+ this.#loadRequests(sessionId);
43587
+ const event = this.#append(sessionId, payload);
43588
+ this.#appendToExecutingRequest(sessionId, event);
43589
+ };
43590
+ #appendToExecutingRequest = (sessionId, event) => {
43591
+ const executing = [...this.#requests.values()].find(
43592
+ (request) => request.sessionId === sessionId && request.kind === "executing"
43593
+ );
43594
+ if (executing !== void 0) {
43595
+ this.#requests.set(executing.commandId, {
43596
+ ...executing,
43597
+ eventTail: { event, previous: executing.eventTail }
43598
+ });
43599
+ this.#store.appendExecutingPromptEventV2(event);
43600
+ }
43601
+ };
43602
+ queueChanged = (sessionId) => {
43603
+ const event = this.#append(sessionId, {
43604
+ payload: { kind: "session.queue.changed" },
43605
+ type: "lifecycle-metadata"
43606
+ });
43607
+ this.#appendToExecutingRequest(sessionId, event);
43608
+ };
43609
+ completed = (sessionId, commandId, stopReason) => {
43610
+ this.#loadRequests(sessionId);
43611
+ const request = this.#requests.get(commandId);
43612
+ const event = this.#append(sessionId, {
43613
+ payload: { commandId, kind: "prompt.completed", stopReason },
43614
+ type: "lifecycle-metadata"
43615
+ });
43616
+ this.#requests.delete(commandId);
43617
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
43618
+ this.#store.clearExecutingPromptEventsV2(sessionId);
43619
+ } else {
43620
+ this.#appendToExecutingRequest(sessionId, event);
43621
+ }
43622
+ };
43623
+ failed = (sessionId, commandId, code, message) => {
43624
+ this.#loadRequests(sessionId);
43625
+ const request = this.#requests.get(commandId);
43626
+ let event;
43627
+ if (request?.kind === "executing" && request.commandId === commandId) {
43628
+ event = this.#append(sessionId, {
43629
+ payload: {
43630
+ attemptId: request.attemptId,
43631
+ code,
43632
+ commandId,
43633
+ kind: "prompt.failed",
43634
+ message
43635
+ },
43636
+ type: "lifecycle-metadata"
43637
+ });
43638
+ } else {
43639
+ event = this.#append(sessionId, {
43640
+ payload: { code, commandId, kind: "prompt.failed-before-start", message },
43641
+ type: "lifecycle-metadata"
43642
+ });
43643
+ }
43644
+ this.#requests.delete(commandId);
43645
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
43646
+ this.#store.clearExecutingPromptEventsV2(sessionId);
43647
+ } else {
43648
+ this.#appendToExecutingRequest(sessionId, event);
43649
+ }
43650
+ };
43651
+ executingPromptRequest = (sessionId) => {
43652
+ this.#loadRequests(sessionId);
43653
+ const request = [...this.#requests.values()].find(
43654
+ (candidate) => candidate.sessionId === sessionId && candidate.kind === "executing"
43655
+ );
43656
+ if (request?.kind !== "executing") {
43657
+ return null;
43658
+ }
43659
+ const requestEvents = eventArray(request.eventTail);
43660
+ const events = requestEvents.slice(-EXECUTING_PROMPT_EVENT_LIMIT);
43661
+ return {
43662
+ attemptId: request.attemptId,
43663
+ commandId: request.commandId,
43664
+ epoch: request.epoch,
43665
+ events,
43666
+ tailCursor: events.at(-1)?.eventId ?? "",
43667
+ truncated: events.length < requestEvents.length
43668
+ };
43669
+ };
43670
+ };
43671
+
42608
43672
  // src/run-daemon.ts
42609
43673
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
42610
43674
  function waitForRelayRetry(signal, timer) {
@@ -42672,16 +43736,17 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42672
43736
  stateDirectory
42673
43737
  });
42674
43738
  const sessionStore = new SqliteAcpSessionStore(
42675
- join17(stateDirectory, "sessions", `${createHash5("sha256").update(config2.channelId).digest("hex")}.sqlite`)
43739
+ join17(stateDirectory, "sessions", `${createHash6("sha256").update(config2.channelId).digest("hex")}.sqlite`)
42676
43740
  );
42677
43741
  const operations = new DaemonOperationState();
42678
43742
  const publisher = new DaemonSessionEventPublisher();
43743
+ const eventLogV2 = new DaemonSessionEventLogV2(publisher, sessionStore);
42679
43744
  const activeTurns = new DaemonTurnRegistry(operations);
42680
43745
  const recordSessionEvent = (sessionId, event) => {
42681
43746
  publisher.publish(sessionId, activeTurns.recordEvent(event));
42682
43747
  };
42683
43748
  const agentRuntime = new AgentRuntimeManager(
42684
- new DaemonAcpObserver(recordSessionEvent),
43749
+ new DaemonAcpObserver(recordSessionEvent, eventLogV2.record),
42685
43750
  sessionStore,
42686
43751
  {
42687
43752
  read: async (options2, nativeSessionId, nativeTurn) => options2.agent.id === "codex" ? (await readCodexFullHistory(
@@ -42719,7 +43784,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42719
43784
  options2.signal
42720
43785
  );
42721
43786
  return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
42722
- (directory, index) => directory === options2.additionalDirectories[index]
43787
+ (directory, index2) => directory === options2.additionalDirectories[index2]
42723
43788
  );
42724
43789
  });
42725
43790
  }
@@ -42805,6 +43870,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42805
43870
  nativeSessions,
42806
43871
  operations,
42807
43872
  publisher,
43873
+ eventLogV2,
42808
43874
  activeTurns,
42809
43875
  connectionEpoch,
42810
43876
  diagnostics,
@@ -42867,7 +43933,7 @@ import { basename as basename7, resolve as resolve7 } from "node:path";
42867
43933
  import { fetch as fetch4 } from "undici";
42868
43934
 
42869
43935
  // src/storage/runtime-installation-store.ts
42870
- import { createHash as createHash6, randomUUID as randomUUID7 } from "node:crypto";
43936
+ import { createHash as createHash7, randomUUID as randomUUID7 } from "node:crypto";
42871
43937
  import { mkdir as mkdir4, open as open5, readdir as readdir3, rename as rename3, unlink, writeFile as writeFile3 } from "node:fs/promises";
42872
43938
  import { dirname as dirname5, join as join18, resolve as resolve6 } from "node:path";
42873
43939
  var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
@@ -43003,7 +44069,7 @@ function installationId() {
43003
44069
  return `min_${randomUUID7().replaceAll("-", "")}`;
43004
44070
  }
43005
44071
  function channelIndexFileName(channelId) {
43006
- return `mci_${createHash6("sha256").update(channelId).digest("hex")}.json`;
44072
+ return `mci_${createHash7("sha256").update(channelId).digest("hex")}.json`;
43007
44073
  }
43008
44074
  function decodeInstallationPointer(value) {
43009
44075
  if (!isRecord9(value) || !hasExactKeys(value, INSTALLATION_POINTER_KEYS) || value["version"] !== 1) {
@@ -43189,16 +44255,16 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
43189
44255
  };
43190
44256
  #readConnectionForChannel = async (channelId, signal) => {
43191
44257
  const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
43192
- const index = decodeChannelIndex(
44258
+ const index2 = decodeChannelIndex(
43193
44259
  await readJsonFile(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
43194
44260
  );
43195
- if (index.applicationId !== this.applicationId || index.installationId !== this.installationId || index.channelId !== normalizedChannelId) {
44261
+ if (index2.applicationId !== this.applicationId || index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
43196
44262
  throw new RuntimeInstallationStoreError(
43197
44263
  "connection_owner_mismatch",
43198
44264
  "The saved Runtime connection belongs to another installation"
43199
44265
  );
43200
44266
  }
43201
- return await this.readConnection(index.connectionId, signal);
44267
+ return await this.readConnection(index2.connectionId, signal);
43202
44268
  };
43203
44269
  saveConnection = async (input2, signal) => {
43204
44270
  const stored = new VerifiedRuntimeConnection(