@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/index.js CHANGED
@@ -3380,11 +3380,11 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
3380
3380
  return payload;
3381
3381
  };
3382
3382
  });
3383
- function handleArrayResult(result, final, index) {
3383
+ function handleArrayResult(result, final, index2) {
3384
3384
  if (result.issues.length) {
3385
- final.issues.push(...prefixIssues(index, result.issues));
3385
+ final.issues.push(...prefixIssues(index2, result.issues));
3386
3386
  }
3387
- final.value[index] = result.value;
3387
+ final.value[index2] = result.value;
3388
3388
  }
3389
3389
  var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
3390
3390
  $ZodType.init(inst, def);
@@ -3995,14 +3995,14 @@ function mergeValues(a, b) {
3995
3995
  return { valid: false, mergeErrorPath: [] };
3996
3996
  }
3997
3997
  const newArray = [];
3998
- for (let index = 0; index < a.length; index++) {
3999
- const itemA = a[index];
4000
- const itemB = b[index];
3998
+ for (let index2 = 0; index2 < a.length; index2++) {
3999
+ const itemA = a[index2];
4000
+ const itemB = b[index2];
4001
4001
  const sharedValue = mergeValues(itemA, itemB);
4002
4002
  if (!sharedValue.valid) {
4003
4003
  return {
4004
4004
  valid: false,
4005
- mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
4005
+ mergeErrorPath: [index2, ...sharedValue.mergeErrorPath]
4006
4006
  };
4007
4007
  }
4008
4008
  newArray.push(sharedValue.data);
@@ -4153,11 +4153,11 @@ function getTupleOptStart(items, key) {
4153
4153
  }
4154
4154
  return 0;
4155
4155
  }
4156
- function handleTupleResult(result, final, index) {
4156
+ function handleTupleResult(result, final, index2) {
4157
4157
  if (result.issues.length) {
4158
- final.issues.push(...prefixIssues(index, result.issues));
4158
+ final.issues.push(...prefixIssues(index2, result.issues));
4159
4159
  }
4160
- final.value[index] = result.value;
4160
+ final.value[index2] = result.value;
4161
4161
  }
4162
4162
  function handleTupleResults(itemResults, final, items, input2, optoutStart) {
4163
4163
  for (let i = 0; i < items.length; i++) {
@@ -18838,7 +18838,7 @@ function detectVersion(schema, defaultTarget) {
18838
18838
  return defaultTarget ?? "draft-2020-12";
18839
18839
  }
18840
18840
  function applyMinItems(items, minItems) {
18841
- return items.map((item, index) => index < minItems ? item : item.optional());
18841
+ return items.map((item, index2) => index2 < minItems ? item : item.optional());
18842
18842
  }
18843
18843
  function decodeJSONPointerSegment(segment) {
18844
18844
  return segment.replace(/~1/g, "/").replace(/~0/g, "~");
@@ -20026,12 +20026,12 @@ var DEFAULT_AGENT_EXECUTION_CONFIGURATION = Object.freeze({
20026
20026
  });
20027
20027
  var sessionConfigurationSelectionsSchema = external_exports.array(sessionConfigurationSelectionSchema).max(100).superRefine((selections, context) => {
20028
20028
  const identifiers = /* @__PURE__ */ new Set();
20029
- for (const [index, selection] of selections.entries()) {
20029
+ for (const [index2, selection] of selections.entries()) {
20030
20030
  if (identifiers.has(selection.configId)) {
20031
20031
  context.addIssue({
20032
20032
  code: "custom",
20033
20033
  message: "Session configuration identifiers must be unique",
20034
- path: [index, "configId"]
20034
+ path: [index2, "configId"]
20035
20035
  });
20036
20036
  }
20037
20037
  identifiers.add(selection.configId);
@@ -21233,6 +21233,443 @@ var encodeNativeSessionResult = (value) => JSON.stringify(nativeSessionResultSch
21233
21233
  var decodeNativeSessionCancel = (encoded) => decode4(nativeSessionCancelSchema, encoded);
21234
21234
  var encodeNativeSessionCancel = (value) => JSON.stringify(nativeSessionCancelSchema.parse(value));
21235
21235
 
21236
+ // ../protocol/src/session-event-log-v2.ts
21237
+ var MAX_EVENT_COUNT = 1e4;
21238
+ var MAX_COLLECTION_SIZE = 1e3;
21239
+ var MAX_CONTENT_LENGTH = 1e6;
21240
+ var MAX_JSON_DEPTH = 16;
21241
+ var MAX_JSON_KEYS = 1e3;
21242
+ var SESSION_EVENT_V2_KIND = "session.event.v2";
21243
+ var boundedString = external_exports.string().max(MAX_CONTENT_LENGTH);
21244
+ var shortString = external_exports.string().max(2048);
21245
+ function boundedJsonIssue(value, depth = 0) {
21246
+ if (depth > MAX_JSON_DEPTH) {
21247
+ return "JSON nesting exceeds the maximum depth";
21248
+ }
21249
+ if (typeof value === "string") {
21250
+ return value.length <= MAX_CONTENT_LENGTH ? null : "JSON string exceeds the maximum length";
21251
+ }
21252
+ if (typeof value === "number") {
21253
+ return Number.isFinite(value) ? null : "JSON number must be finite";
21254
+ }
21255
+ if (typeof value === "boolean" || value === null) {
21256
+ return null;
21257
+ }
21258
+ if (Array.isArray(value)) {
21259
+ if (value.length > MAX_COLLECTION_SIZE) {
21260
+ return "JSON array exceeds the maximum length";
21261
+ }
21262
+ for (const item of value) {
21263
+ const issue2 = boundedJsonIssue(item, depth + 1);
21264
+ if (issue2 !== null) {
21265
+ return issue2;
21266
+ }
21267
+ }
21268
+ return null;
21269
+ }
21270
+ if (typeof value === "object" && value !== void 0) {
21271
+ const entries = Object.entries(value);
21272
+ if (entries.length > MAX_JSON_KEYS) {
21273
+ return "JSON object exceeds the maximum key count";
21274
+ }
21275
+ for (const [key, item] of entries) {
21276
+ if (key.length > 255) {
21277
+ return "JSON key exceeds the maximum length";
21278
+ }
21279
+ const issue2 = boundedJsonIssue(item, depth + 1);
21280
+ if (issue2 !== null) {
21281
+ return issue2;
21282
+ }
21283
+ }
21284
+ return null;
21285
+ }
21286
+ return "Value is not bounded JSON";
21287
+ }
21288
+ var boundedJsonSchema = external_exports.unknown().superRefine((value, context) => {
21289
+ const issue2 = boundedJsonIssue(value);
21290
+ if (issue2 !== null) {
21291
+ context.addIssue({ code: "custom", message: issue2 });
21292
+ }
21293
+ });
21294
+ var metadataSchema = external_exports.record(external_exports.string().max(255), boundedJsonSchema).readonly();
21295
+ var optionalMetadata = metadataSchema.nullable().optional();
21296
+ var annotationsSchema = external_exports.strictObject({
21297
+ _meta: optionalMetadata,
21298
+ audience: external_exports.array(external_exports.enum(["assistant", "user"])).max(2).readonly().nullable().optional(),
21299
+ lastModified: shortString.nullable().optional(),
21300
+ priority: external_exports.number().finite().nullable().optional()
21301
+ }).readonly();
21302
+ var contentFields = { _meta: optionalMetadata, annotations: annotationsSchema.nullable().optional() };
21303
+ var textContentSchema = external_exports.strictObject({ ...contentFields, text: boundedString, type: external_exports.literal("text") }).readonly();
21304
+ var imageContentSchema = external_exports.strictObject({
21305
+ ...contentFields,
21306
+ data: boundedString,
21307
+ mimeType: shortString,
21308
+ type: external_exports.literal("image"),
21309
+ uri: boundedString.nullable().optional()
21310
+ }).readonly();
21311
+ var audioContentSchema = external_exports.strictObject({ ...contentFields, data: boundedString, mimeType: shortString, type: external_exports.literal("audio") }).readonly();
21312
+ var resourceLinkSchema = external_exports.strictObject({
21313
+ ...contentFields,
21314
+ description: boundedString.nullable().optional(),
21315
+ mimeType: shortString.nullable().optional(),
21316
+ name: shortString,
21317
+ size: external_exports.number().int().nonnegative().safe().nullable().optional(),
21318
+ title: shortString.nullable().optional(),
21319
+ type: external_exports.literal("resource_link"),
21320
+ uri: boundedString
21321
+ }).readonly();
21322
+ var textResourceSchema = external_exports.strictObject({
21323
+ _meta: optionalMetadata,
21324
+ mimeType: shortString.nullable().optional(),
21325
+ text: boundedString,
21326
+ uri: boundedString
21327
+ }).readonly();
21328
+ var blobResourceSchema = external_exports.strictObject({
21329
+ _meta: optionalMetadata,
21330
+ blob: boundedString,
21331
+ mimeType: shortString.nullable().optional(),
21332
+ uri: boundedString
21333
+ }).readonly();
21334
+ var embeddedResourceSchema = external_exports.strictObject({
21335
+ ...contentFields,
21336
+ resource: external_exports.union([textResourceSchema, blobResourceSchema]),
21337
+ type: external_exports.literal("resource")
21338
+ }).readonly();
21339
+ var contentBlockV2Schema = external_exports.discriminatedUnion("type", [
21340
+ textContentSchema,
21341
+ imageContentSchema,
21342
+ audioContentSchema,
21343
+ resourceLinkSchema,
21344
+ embeddedResourceSchema
21345
+ ]);
21346
+ var toolCallContentSchema = external_exports.discriminatedUnion("type", [
21347
+ external_exports.strictObject({ _meta: optionalMetadata, content: contentBlockV2Schema, type: external_exports.literal("content") }).readonly(),
21348
+ external_exports.strictObject({
21349
+ _meta: optionalMetadata,
21350
+ newText: boundedString,
21351
+ oldText: boundedString.nullable().optional(),
21352
+ path: boundedString,
21353
+ type: external_exports.literal("diff")
21354
+ }).readonly(),
21355
+ external_exports.strictObject({ _meta: optionalMetadata, terminalId: shortString, type: external_exports.literal("terminal") }).readonly()
21356
+ ]);
21357
+ var toolCallLocationSchema = external_exports.strictObject({
21358
+ _meta: optionalMetadata,
21359
+ line: external_exports.number().int().nonnegative().safe().nullable().optional(),
21360
+ path: boundedString
21361
+ }).readonly();
21362
+ var toolKindSchema = external_exports.enum([
21363
+ "read",
21364
+ "edit",
21365
+ "delete",
21366
+ "move",
21367
+ "search",
21368
+ "execute",
21369
+ "think",
21370
+ "fetch",
21371
+ "switch_mode",
21372
+ "other"
21373
+ ]);
21374
+ var toolStatusSchema = external_exports.enum(["pending", "in_progress", "completed", "failed"]);
21375
+ var toolPatchFields = {
21376
+ _meta: optionalMetadata,
21377
+ content: external_exports.array(toolCallContentSchema).max(MAX_COLLECTION_SIZE).readonly().nullable().optional(),
21378
+ kind: toolKindSchema.nullable().optional(),
21379
+ locations: external_exports.array(toolCallLocationSchema).max(MAX_COLLECTION_SIZE).readonly().nullable().optional(),
21380
+ name: shortString.nullable().optional(),
21381
+ rawInput: boundedJsonSchema.optional(),
21382
+ rawOutput: boundedJsonSchema.optional(),
21383
+ status: toolStatusSchema.nullable().optional(),
21384
+ title: boundedString.nullable().optional()
21385
+ };
21386
+ var planEntrySchema = external_exports.strictObject({
21387
+ _meta: optionalMetadata,
21388
+ content: boundedString,
21389
+ priority: external_exports.enum(["high", "medium", "low"]),
21390
+ status: external_exports.enum(["pending", "in_progress", "completed"])
21391
+ }).readonly();
21392
+ var planContentSchema = external_exports.discriminatedUnion("type", [
21393
+ external_exports.strictObject({
21394
+ _meta: optionalMetadata,
21395
+ entries: external_exports.array(planEntrySchema).max(MAX_COLLECTION_SIZE).readonly(),
21396
+ planId: shortString,
21397
+ type: external_exports.literal("items")
21398
+ }).readonly(),
21399
+ external_exports.strictObject({ _meta: optionalMetadata, planId: shortString, type: external_exports.literal("file"), uri: boundedString }).readonly(),
21400
+ external_exports.strictObject({
21401
+ _meta: optionalMetadata,
21402
+ content: boundedString,
21403
+ planId: shortString,
21404
+ type: external_exports.literal("markdown")
21405
+ }).readonly()
21406
+ ]);
21407
+ var commandSchema = external_exports.strictObject({
21408
+ _meta: optionalMetadata,
21409
+ description: boundedString,
21410
+ input: external_exports.strictObject({ _meta: optionalMetadata, hint: boundedString }).readonly().nullable().optional(),
21411
+ name: shortString
21412
+ }).readonly();
21413
+ var configSelectOptionSchema = external_exports.strictObject({
21414
+ _meta: optionalMetadata,
21415
+ description: boundedString.nullable().optional(),
21416
+ name: shortString,
21417
+ value: shortString
21418
+ }).readonly();
21419
+ var configSelectGroupSchema = external_exports.strictObject({
21420
+ _meta: optionalMetadata,
21421
+ group: shortString,
21422
+ name: shortString,
21423
+ options: external_exports.array(configSelectOptionSchema).max(MAX_COLLECTION_SIZE).readonly()
21424
+ }).readonly();
21425
+ var configBaseFields = {
21426
+ _meta: optionalMetadata,
21427
+ category: shortString.nullable().optional(),
21428
+ description: boundedString.nullable().optional(),
21429
+ id: shortString,
21430
+ name: shortString
21431
+ };
21432
+ var sessionConfigOptionSchema2 = external_exports.discriminatedUnion("type", [
21433
+ external_exports.strictObject({
21434
+ ...configBaseFields,
21435
+ currentValue: shortString,
21436
+ options: external_exports.union([
21437
+ external_exports.array(configSelectOptionSchema).max(MAX_COLLECTION_SIZE).readonly(),
21438
+ external_exports.array(configSelectGroupSchema).max(MAX_COLLECTION_SIZE).readonly()
21439
+ ]),
21440
+ type: external_exports.literal("select")
21441
+ }).readonly(),
21442
+ external_exports.strictObject({ ...configBaseFields, currentValue: external_exports.boolean(), type: external_exports.literal("boolean") }).readonly()
21443
+ ]);
21444
+ var contentChunkFields = {
21445
+ _meta: optionalMetadata,
21446
+ content: contentBlockV2Schema,
21447
+ messageId: shortString.nullable().optional()
21448
+ };
21449
+ var acpSessionUpdateV2Schema = external_exports.discriminatedUnion("sessionUpdate", [
21450
+ external_exports.strictObject({ ...contentChunkFields, sessionUpdate: external_exports.literal("user_message_chunk") }).readonly(),
21451
+ external_exports.strictObject({ ...contentChunkFields, sessionUpdate: external_exports.literal("agent_message_chunk") }).readonly(),
21452
+ external_exports.strictObject({ ...contentChunkFields, sessionUpdate: external_exports.literal("agent_thought_chunk") }).readonly(),
21453
+ external_exports.strictObject({
21454
+ _meta: optionalMetadata,
21455
+ content: external_exports.array(toolCallContentSchema).max(MAX_COLLECTION_SIZE).readonly().optional(),
21456
+ kind: toolKindSchema.optional(),
21457
+ locations: external_exports.array(toolCallLocationSchema).max(MAX_COLLECTION_SIZE).readonly().optional(),
21458
+ name: shortString.nullable().optional(),
21459
+ rawInput: boundedJsonSchema.optional(),
21460
+ rawOutput: boundedJsonSchema.optional(),
21461
+ sessionUpdate: external_exports.literal("tool_call"),
21462
+ status: toolStatusSchema.optional(),
21463
+ title: boundedString,
21464
+ toolCallId: shortString
21465
+ }).readonly(),
21466
+ external_exports.strictObject({ ...toolPatchFields, sessionUpdate: external_exports.literal("tool_call_update"), toolCallId: shortString }).readonly(),
21467
+ external_exports.strictObject({
21468
+ _meta: optionalMetadata,
21469
+ entries: external_exports.array(planEntrySchema).max(MAX_COLLECTION_SIZE).readonly(),
21470
+ sessionUpdate: external_exports.literal("plan")
21471
+ }).readonly(),
21472
+ external_exports.strictObject({ _meta: optionalMetadata, plan: planContentSchema, sessionUpdate: external_exports.literal("plan_update") }).readonly(),
21473
+ external_exports.strictObject({ _meta: optionalMetadata, planId: shortString, sessionUpdate: external_exports.literal("plan_removed") }).readonly(),
21474
+ external_exports.strictObject({
21475
+ _meta: optionalMetadata,
21476
+ availableCommands: external_exports.array(commandSchema).max(MAX_COLLECTION_SIZE).readonly(),
21477
+ sessionUpdate: external_exports.literal("available_commands_update")
21478
+ }).readonly(),
21479
+ external_exports.strictObject({
21480
+ _meta: optionalMetadata,
21481
+ currentModeId: shortString,
21482
+ sessionUpdate: external_exports.literal("current_mode_update")
21483
+ }).readonly(),
21484
+ external_exports.strictObject({
21485
+ _meta: optionalMetadata,
21486
+ configOptions: external_exports.array(sessionConfigOptionSchema2).max(MAX_COLLECTION_SIZE).readonly(),
21487
+ sessionUpdate: external_exports.literal("config_option_update")
21488
+ }).readonly(),
21489
+ external_exports.strictObject({
21490
+ _meta: optionalMetadata,
21491
+ sessionUpdate: external_exports.literal("session_info_update"),
21492
+ title: boundedString.nullable().optional(),
21493
+ updatedAt: shortString.nullable().optional()
21494
+ }).readonly(),
21495
+ external_exports.strictObject({
21496
+ _meta: optionalMetadata,
21497
+ cost: external_exports.strictObject({ _meta: optionalMetadata, amount: external_exports.number().finite(), currency: external_exports.string().max(16) }).readonly().nullable().optional(),
21498
+ sessionUpdate: external_exports.literal("usage_update"),
21499
+ size: external_exports.number().int().nonnegative().safe(),
21500
+ used: external_exports.number().int().nonnegative().safe()
21501
+ }).readonly(),
21502
+ external_exports.strictObject({
21503
+ _meta: optionalMetadata,
21504
+ compactionId: shortString,
21505
+ error: boundedString.nullable().optional(),
21506
+ sessionUpdate: external_exports.literal("compaction_update"),
21507
+ status: shortString,
21508
+ summary: external_exports.array(contentBlockV2Schema).max(MAX_COLLECTION_SIZE).readonly().nullable().optional()
21509
+ }).readonly(),
21510
+ external_exports.strictObject({
21511
+ _meta: optionalMetadata,
21512
+ compactionId: shortString,
21513
+ content: contentBlockV2Schema,
21514
+ sessionUpdate: external_exports.literal("compaction_summary_chunk")
21515
+ }).readonly()
21516
+ ]);
21517
+ var lifecycleBase = { commandId: identifierStringSchema };
21518
+ var lifecycleMetadataV2Schema = external_exports.discriminatedUnion("kind", [
21519
+ external_exports.strictObject({ kind: external_exports.literal("session.queue.changed") }).readonly(),
21520
+ external_exports.strictObject({ event: sessionPermissionRequestedEventSchema, kind: external_exports.literal("session.permission.requested") }).readonly(),
21521
+ external_exports.strictObject({ event: sessionPermissionResolvedEventSchema, kind: external_exports.literal("session.permission.resolved") }).readonly(),
21522
+ external_exports.strictObject({
21523
+ event: sessionElicitationRequestedEventSchema,
21524
+ kind: external_exports.literal("session.elicitation.requested")
21525
+ }).readonly(),
21526
+ external_exports.strictObject({ event: sessionElicitationResolvedEventSchema, kind: external_exports.literal("session.elicitation.resolved") }).readonly(),
21527
+ external_exports.strictObject({
21528
+ ...lifecycleBase,
21529
+ content: external_exports.array(contentBlockV2Schema).min(1).max(100).readonly(),
21530
+ kind: external_exports.literal("prompt.requested")
21531
+ }).readonly(),
21532
+ external_exports.strictObject({ ...lifecycleBase, attemptId: identifierStringSchema, epoch: identifierStringSchema, kind: external_exports.literal("prompt.started") }).readonly(),
21533
+ external_exports.strictObject({ ...lifecycleBase, kind: external_exports.literal("prompt.completed"), stopReason: shortString }).readonly(),
21534
+ external_exports.strictObject({
21535
+ ...lifecycleBase,
21536
+ code: identifierStringSchema,
21537
+ kind: external_exports.literal("prompt.failed-before-start"),
21538
+ message: external_exports.string().min(1).max(500)
21539
+ }).readonly(),
21540
+ external_exports.strictObject({
21541
+ ...lifecycleBase,
21542
+ attemptId: identifierStringSchema,
21543
+ code: identifierStringSchema,
21544
+ kind: external_exports.literal("prompt.failed"),
21545
+ message: external_exports.string().min(1).max(500)
21546
+ }).readonly()
21547
+ ]);
21548
+ var sessionEventPayloadV2Schema = external_exports.discriminatedUnion("type", [
21549
+ external_exports.strictObject({ payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
21550
+ external_exports.strictObject({ payload: lifecycleMetadataV2Schema, type: external_exports.literal("lifecycle-metadata") }).readonly()
21551
+ ]);
21552
+ var positionSchema = external_exports.string().regex(/^(0|[1-9][0-9]*)$/);
21553
+ var provenanceSchema = external_exports.discriminatedUnion("kind", [
21554
+ external_exports.strictObject({ kind: external_exports.literal("original") }).readonly(),
21555
+ external_exports.strictObject({
21556
+ kind: external_exports.literal("imported"),
21557
+ sourceEventId: identifierStringSchema,
21558
+ sourcePosition: positionSchema,
21559
+ sourceSessionId: identifierStringSchema
21560
+ }).readonly(),
21561
+ external_exports.strictObject({
21562
+ kind: external_exports.literal("forked"),
21563
+ sourceEventId: identifierStringSchema,
21564
+ sourcePosition: positionSchema,
21565
+ sourceSessionId: identifierStringSchema
21566
+ }).readonly()
21567
+ ]);
21568
+ var sessionEventFieldsV2 = {
21569
+ eventId: identifierStringSchema,
21570
+ position: positionSchema,
21571
+ provenance: provenanceSchema,
21572
+ recordedAt: external_exports.iso.datetime({ offset: true }),
21573
+ sessionId: identifierStringSchema
21574
+ };
21575
+ var sessionEventV2Schema = external_exports.discriminatedUnion("type", [
21576
+ external_exports.strictObject({ ...sessionEventFieldsV2, payload: acpSessionUpdateV2Schema, type: external_exports.literal("acp") }).readonly(),
21577
+ external_exports.strictObject({
21578
+ ...sessionEventFieldsV2,
21579
+ payload: lifecycleMetadataV2Schema,
21580
+ type: external_exports.literal("lifecycle-metadata")
21581
+ }).readonly()
21582
+ ]);
21583
+ var sessionExportV2Schema = external_exports.strictObject({
21584
+ binding: external_exports.strictObject({
21585
+ bindingId: identifierStringSchema,
21586
+ runtimeId: identifierStringSchema
21587
+ }).readonly(),
21588
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
21589
+ sessionId: identifierStringSchema,
21590
+ truncated: external_exports.boolean()
21591
+ }).readonly().superRefine((session, context) => {
21592
+ let previousPosition = 0n;
21593
+ const eventIds = /* @__PURE__ */ new Set();
21594
+ for (const [index2, event] of session.events.entries()) {
21595
+ if (event.sessionId !== session.sessionId) {
21596
+ context.addIssue({
21597
+ code: "custom",
21598
+ message: "Exported event belongs to a different Session",
21599
+ path: ["events", index2, "sessionId"]
21600
+ });
21601
+ }
21602
+ const position = BigInt(event.position);
21603
+ if (position <= previousPosition) {
21604
+ context.addIssue({
21605
+ code: "custom",
21606
+ message: "Exported events are not in increasing position order",
21607
+ path: ["events", index2, "position"]
21608
+ });
21609
+ }
21610
+ if (eventIds.has(event.eventId)) {
21611
+ context.addIssue({
21612
+ code: "custom",
21613
+ message: "Exported event identities are not unique",
21614
+ path: ["events", index2, "eventId"]
21615
+ });
21616
+ }
21617
+ previousPosition = position;
21618
+ eventIds.add(event.eventId);
21619
+ }
21620
+ });
21621
+ var mobiusSessionExportV2Schema = external_exports.strictObject({
21622
+ formatVersion: external_exports.literal("2"),
21623
+ session: sessionExportV2Schema
21624
+ }).readonly();
21625
+ var sessionEventEnvelopeV2Schema = external_exports.strictObject({ event: sessionEventV2Schema, kind: external_exports.literal(SESSION_EVENT_V2_KIND) }).readonly();
21626
+ var sessionEventLogPageV2Schema = external_exports.strictObject({
21627
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
21628
+ nextCursor: external_exports.string().min(1).max(512).nullable(),
21629
+ tailCursor: external_exports.string().max(512),
21630
+ truncated: external_exports.boolean(),
21631
+ version: external_exports.literal(2)
21632
+ }).readonly();
21633
+ var nativeEventPageRequestV2Schema = external_exports.strictObject({ cursor: external_exports.string().min(1).max(512).nullable(), eventLimit: external_exports.number().int().min(1).max(1e4) }).readonly();
21634
+ var executingPromptRequestEventLogV2Schema = external_exports.strictObject({
21635
+ attemptId: identifierStringSchema,
21636
+ commandId: identifierStringSchema,
21637
+ epoch: identifierStringSchema,
21638
+ events: external_exports.array(sessionEventV2Schema).max(MAX_EVENT_COUNT).readonly(),
21639
+ tailCursor: external_exports.string().max(512),
21640
+ truncated: external_exports.boolean()
21641
+ }).readonly();
21642
+ var nativeSessionEventsV2Schema = external_exports.strictObject({
21643
+ executingPromptRequest: executingPromptRequestEventLogV2Schema.nullable(),
21644
+ history: sessionEventLogPageV2Schema
21645
+ }).readonly();
21646
+ function inputValue(value) {
21647
+ if (typeof value !== "string") {
21648
+ return value;
21649
+ }
21650
+ try {
21651
+ return JSON.parse(value);
21652
+ } catch (cause) {
21653
+ throw new ProtocolMessageError("Session Event Log V2 message is not valid JSON", { cause });
21654
+ }
21655
+ }
21656
+ function decode5(value, schema) {
21657
+ const result = schema.safeParse(inputValue(value));
21658
+ if (!result.success) {
21659
+ throw new ProtocolMessageError("Session Event Log V2 message does not match its schema", {
21660
+ cause: result.error
21661
+ });
21662
+ }
21663
+ return result.data;
21664
+ }
21665
+ function encode4(value, schema) {
21666
+ return JSON.stringify(decode5(value, schema));
21667
+ }
21668
+ var decodeSessionEventV2 = (value) => decode5(value, sessionEventV2Schema);
21669
+ var decodeSessionEventEnvelopeV2 = (value) => decode5(value, sessionEventEnvelopeV2Schema);
21670
+ var encodeSessionEventEnvelopeV2 = (value) => encode4(value, sessionEventEnvelopeV2Schema);
21671
+ var decodeAcpSessionUpdateV2 = (value) => decode5(value, acpSessionUpdateV2Schema);
21672
+
21236
21673
  // ../protocol/src/session-events.ts
21237
21674
  var SESSION_EVENT_KIND = "session.event";
21238
21675
  var SESSION_FORKED_KIND = "session.forked";
@@ -21250,7 +21687,7 @@ var sessionForkedSchema = external_exports.strictObject({
21250
21687
  sourceSessionId: identifierStringSchema,
21251
21688
  throughCommandId: identifierStringSchema
21252
21689
  }).readonly();
21253
- function decode5(encoded, schema) {
21690
+ function decode6(encoded, schema) {
21254
21691
  let value;
21255
21692
  try {
21256
21693
  value = JSON.parse(encoded);
@@ -21265,7 +21702,7 @@ function decode5(encoded, schema) {
21265
21702
  }
21266
21703
  return decoded.data;
21267
21704
  }
21268
- var encode4 = (message, schema) => {
21705
+ var encode5 = (message, schema) => {
21269
21706
  const decoded = schema.safeParse(message);
21270
21707
  if (!decoded.success) {
21271
21708
  throw new ProtocolMessageError("Message does not match its schema", {
@@ -21274,15 +21711,15 @@ var encode4 = (message, schema) => {
21274
21711
  }
21275
21712
  return JSON.stringify(decoded.data);
21276
21713
  };
21277
- var decodeSessionEventEnvelope = (encoded) => decode5(encoded, sessionEventEnvelopeSchema);
21278
- var encodeSessionEventEnvelope = (message) => encode4(message, sessionEventEnvelopeSchema);
21714
+ var decodeSessionEventEnvelope = (encoded) => decode6(encoded, sessionEventEnvelopeSchema);
21715
+ var encodeSessionEventEnvelope = (message) => encode5(message, sessionEventEnvelopeSchema);
21279
21716
  function decodeRecordedSessionEvent(encoded) {
21280
21717
  const kind = decodeMessageKind(encoded);
21281
21718
  switch (kind) {
21282
21719
  case SESSION_QUEUE_CHANGED_KIND:
21283
- return decode5(encoded, sessionQueueChangedSchema);
21720
+ return decode6(encoded, sessionQueueChangedSchema);
21284
21721
  case SESSION_FORKED_KIND:
21285
- return decode5(encoded, sessionForkedSchema);
21722
+ return decode6(encoded, sessionForkedSchema);
21286
21723
  case AGENT_ACTIVITY_KIND:
21287
21724
  return decodeAgentActivityEvent(encoded);
21288
21725
  case AGENT_ACTIVITY_NARRATION_KIND:
@@ -21326,6 +21763,8 @@ var SESSION_LIVE_HISTORY_LOAD_KIND = "session.live-history.load";
21326
21763
  var SESSION_LIVE_HISTORY_LOADED_KIND = "session.live-history.loaded";
21327
21764
  var SESSION_LIVE_HISTORY_PAGE_LOAD_KIND = "session.live-history.page.load";
21328
21765
  var SESSION_LIVE_HISTORY_PAGE_LOADED_KIND = "session.live-history.page.loaded";
21766
+ var SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND = "session.live-history.v2.page.load";
21767
+ var SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND = "session.live-history.v2.page.loaded";
21329
21768
  var directoryIdentifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
21330
21769
  var sessionLiveHistoryLoadSchema = external_exports.strictObject({
21331
21770
  additionalDirectoryIds: external_exports.array(directoryIdentifier).max(16).readonly(),
@@ -21359,7 +21798,24 @@ var sessionLiveHistoryPageLoadedSchema = external_exports.strictObject({
21359
21798
  requestId: identifierStringSchema,
21360
21799
  sessionId: identifierStringSchema
21361
21800
  }).readonly();
21362
- function decode6(schema, encoded) {
21801
+ var sessionLiveHistoryV2PageLoadSchema = external_exports.strictObject({
21802
+ additionalDirectoryIds: external_exports.array(directoryIdentifier).max(16).readonly(),
21803
+ agentId: identifierStringSchema,
21804
+ bindingId: identifierStringSchema,
21805
+ cursor: external_exports.string().min(1).max(512).nullable(),
21806
+ directoryId: directoryIdentifier,
21807
+ kind: external_exports.literal(SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND),
21808
+ eventLimit: external_exports.number().int().min(1).max(1e4),
21809
+ requestId: identifierStringSchema,
21810
+ sessionId: identifierStringSchema
21811
+ }).readonly();
21812
+ var sessionLiveHistoryV2PageLoadedSchema = external_exports.strictObject({
21813
+ events: nativeSessionEventsV2Schema,
21814
+ kind: external_exports.literal(SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND),
21815
+ requestId: identifierStringSchema,
21816
+ sessionId: identifierStringSchema
21817
+ }).readonly();
21818
+ function decode7(schema, encoded) {
21363
21819
  try {
21364
21820
  const value = JSON.parse(encoded);
21365
21821
  return schema.parse(value);
@@ -21367,14 +21823,18 @@ function decode6(schema, encoded) {
21367
21823
  throw new ProtocolMessageError("Invalid live Session history message", { cause });
21368
21824
  }
21369
21825
  }
21370
- var decodeSessionLiveHistoryLoad = (encoded) => decode6(sessionLiveHistoryLoadSchema, encoded);
21371
- var decodeSessionLiveHistoryLoaded = (encoded) => decode6(sessionLiveHistoryLoadedSchema, encoded);
21826
+ var decodeSessionLiveHistoryLoad = (encoded) => decode7(sessionLiveHistoryLoadSchema, encoded);
21827
+ var decodeSessionLiveHistoryLoaded = (encoded) => decode7(sessionLiveHistoryLoadedSchema, encoded);
21372
21828
  var encodeSessionLiveHistoryLoad = (value) => JSON.stringify(sessionLiveHistoryLoadSchema.parse(value));
21373
21829
  var encodeSessionLiveHistoryLoaded = (value) => JSON.stringify(sessionLiveHistoryLoadedSchema.parse(value));
21374
- var decodeSessionLiveHistoryPageLoad = (encoded) => decode6(sessionLiveHistoryPageLoadSchema, encoded);
21375
- var decodeSessionLiveHistoryPageLoaded = (encoded) => decode6(sessionLiveHistoryPageLoadedSchema, encoded);
21830
+ var decodeSessionLiveHistoryPageLoad = (encoded) => decode7(sessionLiveHistoryPageLoadSchema, encoded);
21831
+ var decodeSessionLiveHistoryPageLoaded = (encoded) => decode7(sessionLiveHistoryPageLoadedSchema, encoded);
21376
21832
  var encodeSessionLiveHistoryPageLoad = (value) => JSON.stringify(sessionLiveHistoryPageLoadSchema.parse(value));
21377
21833
  var encodeSessionLiveHistoryPageLoaded = (value) => JSON.stringify(sessionLiveHistoryPageLoadedSchema.parse(value));
21834
+ var decodeSessionLiveHistoryV2PageLoad = (encoded) => decode7(sessionLiveHistoryV2PageLoadSchema, encoded);
21835
+ var decodeSessionLiveHistoryV2PageLoaded = (encoded) => decode7(sessionLiveHistoryV2PageLoadedSchema, encoded);
21836
+ var encodeSessionLiveHistoryV2PageLoad = (value) => JSON.stringify(sessionLiveHistoryV2PageLoadSchema.parse(value));
21837
+ var encodeSessionLiveHistoryV2PageLoaded = (value) => JSON.stringify(sessionLiveHistoryV2PageLoadedSchema.parse(value));
21378
21838
 
21379
21839
  // ../protocol/src/daemon-transport.ts
21380
21840
  function defineMessageSignature(kind, encoder, decoder) {
@@ -21459,6 +21919,11 @@ var serviceToDaemonSignatures = {
21459
21919
  encodeSessionLiveHistoryPageLoad,
21460
21920
  decodeSessionLiveHistoryPageLoad
21461
21921
  ),
21922
+ [SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND]: defineMessageSignature(
21923
+ SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND,
21924
+ encodeSessionLiveHistoryV2PageLoad,
21925
+ decodeSessionLiveHistoryV2PageLoad
21926
+ ),
21462
21927
  [SESSION_PERMISSION_RESPOND_KIND]: defineMessageSignature(
21463
21928
  SESSION_PERMISSION_RESPOND_KIND,
21464
21929
  encodeSessionPermissionRespondCommand,
@@ -21574,6 +22039,11 @@ var daemonToServiceSignatures = {
21574
22039
  encodeSessionEventEnvelope,
21575
22040
  decodeSessionEventEnvelope
21576
22041
  ),
22042
+ [SESSION_EVENT_V2_KIND]: defineMessageSignature(
22043
+ SESSION_EVENT_V2_KIND,
22044
+ encodeSessionEventEnvelopeV2,
22045
+ decodeSessionEventEnvelopeV2
22046
+ ),
21577
22047
  [SESSION_OPERATION_FAILED_KIND]: defineMessageSignature(
21578
22048
  SESSION_OPERATION_FAILED_KIND,
21579
22049
  encodeSessionOperationFailedEvent,
@@ -21589,6 +22059,11 @@ var daemonToServiceSignatures = {
21589
22059
  encodeSessionLiveHistoryPageLoaded,
21590
22060
  decodeSessionLiveHistoryPageLoaded
21591
22061
  ),
22062
+ [SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND]: defineMessageSignature(
22063
+ SESSION_LIVE_HISTORY_V2_PAGE_LOADED_KIND,
22064
+ encodeSessionLiveHistoryV2PageLoaded,
22065
+ decodeSessionLiveHistoryV2PageLoaded
22066
+ ),
21592
22067
  [SESSION_READY_KIND]: defineMessageSignature(SESSION_READY_KIND, encodeSessionReadyEvent, decodeSessionReadyEvent),
21593
22068
  [WORKSPACE_ENTRIES_KIND]: defineMessageSignature(
21594
22069
  WORKSPACE_ENTRIES_KIND,
@@ -22578,7 +23053,7 @@ function startsWith(bytes, signature, offset = 0) {
22578
23053
  if (bytes.byteLength < offset + signature.byteLength) {
22579
23054
  return false;
22580
23055
  }
22581
- return signature.every((value, index) => bytes[offset + index] === value);
23056
+ return signature.every((value, index2) => bytes[offset + index2] === value);
22582
23057
  }
22583
23058
  function sniffRasterMime(bytes) {
22584
23059
  if (startsWith(bytes, PNG_SIGNATURE)) {
@@ -22706,7 +23181,7 @@ function startsWith2(bytes, signature, offset = 0) {
22706
23181
  if (bytes.byteLength < offset + signature.byteLength) {
22707
23182
  return false;
22708
23183
  }
22709
- return signature.every((value, index) => bytes[offset + index] === value);
23184
+ return signature.every((value, index2) => bytes[offset + index2] === value);
22710
23185
  }
22711
23186
  function sniffVideoMime(bytes) {
22712
23187
  if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
@@ -22835,10 +23310,10 @@ async function replaceImageMarkers(text2, replace) {
22835
23310
  let cursor = 0;
22836
23311
  let rewritten = "";
22837
23312
  for (const match of matches) {
22838
- const index = match.index ?? 0;
22839
- rewritten += text2.slice(cursor, index);
23313
+ const index2 = match.index ?? 0;
23314
+ rewritten += text2.slice(cursor, index2);
22840
23315
  rewritten += await replace(match[1] ?? "");
22841
- cursor = index + match[0].length;
23316
+ cursor = index2 + match[0].length;
22842
23317
  }
22843
23318
  return `${rewritten}${text2.slice(cursor)}`;
22844
23319
  }
@@ -24031,6 +24506,7 @@ function sessionConfigProtocolForAgent(_agentId) {
24031
24506
 
24032
24507
  // src/acp/session-contracts.ts
24033
24508
  var NullAcpSessionObserver = class {
24509
+ onAcpUpdate = (_sessionId, _update) => Promise.resolve();
24034
24510
  onCommands = () => Promise.resolve();
24035
24511
  onConfig = () => Promise.resolve();
24036
24512
  onContent = () => Promise.resolve();
@@ -24155,6 +24631,7 @@ function historyContentCharacters(messages) {
24155
24631
  var AcpHistoryReplay = class {
24156
24632
  #activities = /* @__PURE__ */ new Map();
24157
24633
  #messages = [];
24634
+ #updates = [];
24158
24635
  #turnActivityIds = /* @__PURE__ */ new Set();
24159
24636
  #activityTracker = new AcpActivityTracker(
24160
24637
  async (activity2) => {
@@ -24176,7 +24653,8 @@ var AcpHistoryReplay = class {
24176
24653
  #firstMessageIndex = 0;
24177
24654
  #characters = 0;
24178
24655
  #truncated = false;
24179
- record = async (update) => {
24656
+ record = async (update, rawUpdate) => {
24657
+ this.#updates.push(rawUpdate);
24180
24658
  if (update.sessionUpdate === "agent_thought_chunk") {
24181
24659
  if (update.content.type === "text") {
24182
24660
  await this.#activityTracker.recordNarrative(
@@ -24257,6 +24735,20 @@ var AcpHistoryReplay = class {
24257
24735
  this.#lastMessageId = id;
24258
24736
  this.trimMessages();
24259
24737
  };
24738
+ eventPage = (eventLimit, cursor) => {
24739
+ const parsedCursor = cursor === null ? this.#updates.length : Number(cursor);
24740
+ if (!Number.isSafeInteger(parsedCursor) || parsedCursor < 0 || parsedCursor > this.#updates.length) {
24741
+ throw new Error("The native event cursor is invalid");
24742
+ }
24743
+ const endUpdate = parsedCursor;
24744
+ const startUpdate = Math.max(0, endUpdate - eventLimit);
24745
+ return {
24746
+ nextCursor: startUpdate === 0 ? null : startUpdate.toString(),
24747
+ startPosition: startUpdate + 1,
24748
+ truncated: startUpdate > 0,
24749
+ updates: this.#updates.slice(startUpdate, endUpdate)
24750
+ };
24751
+ };
24260
24752
  snapshot = async () => {
24261
24753
  await this.#activityTracker.finish();
24262
24754
  const messages = this.#messages.slice(this.#firstMessageIndex).map((message) => {
@@ -26244,8 +26736,8 @@ function haveSameKeys(left, right) {
26244
26736
  if (leftKeys.length !== rightKeys.length) {
26245
26737
  return false;
26246
26738
  }
26247
- for (const [index, key] of leftKeys.entries()) {
26248
- if (key !== rightKeys[index]) {
26739
+ for (const [index2, key] of leftKeys.entries()) {
26740
+ if (key !== rightKeys[index2]) {
26249
26741
  return false;
26250
26742
  }
26251
26743
  }
@@ -27433,6 +27925,55 @@ var sqliteTable = (name, columns, extraConfig) => {
27433
27925
  return sqliteTableBase(name, columns, extraConfig);
27434
27926
  };
27435
27927
 
27928
+ // ../../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
27929
+ var IndexBuilderOn = class {
27930
+ constructor(name, unique) {
27931
+ this.name = name;
27932
+ this.unique = unique;
27933
+ }
27934
+ static [entityKind] = "SQLiteIndexBuilderOn";
27935
+ on(...columns) {
27936
+ return new IndexBuilder(this.name, columns, this.unique);
27937
+ }
27938
+ };
27939
+ var IndexBuilder = class {
27940
+ static [entityKind] = "SQLiteIndexBuilder";
27941
+ /** @internal */
27942
+ config;
27943
+ constructor(name, columns, unique) {
27944
+ this.config = {
27945
+ name,
27946
+ columns,
27947
+ unique,
27948
+ where: void 0
27949
+ };
27950
+ }
27951
+ /**
27952
+ * Condition for partial index.
27953
+ */
27954
+ where(condition) {
27955
+ this.config.where = condition;
27956
+ return this;
27957
+ }
27958
+ /** @internal */
27959
+ build(table) {
27960
+ return new Index(this.config, table);
27961
+ }
27962
+ };
27963
+ var Index = class {
27964
+ static [entityKind] = "SQLiteIndex";
27965
+ config;
27966
+ constructor(config2, table) {
27967
+ this.config = { ...config2, table };
27968
+ }
27969
+ };
27970
+ function index(name) {
27971
+ return new IndexBuilderOn(name, false);
27972
+ }
27973
+ function uniqueIndex(name) {
27974
+ return new IndexBuilderOn(name, true);
27975
+ }
27976
+
27436
27977
  // ../../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
27437
27978
  function extractUsedTable(table) {
27438
27979
  if (is(table, SQLiteTable)) {
@@ -27781,8 +28322,8 @@ var SQLiteDialect = class {
27781
28322
  }
27782
28323
  const joinsArray = [];
27783
28324
  if (joins) {
27784
- for (const [index, joinMeta] of joins.entries()) {
27785
- if (index === 0) {
28325
+ for (const [index2, joinMeta] of joins.entries()) {
28326
+ if (index2 === 0) {
27786
28327
  joinsArray.push(sql` `);
27787
28328
  }
27788
28329
  const table = joinMeta.table;
@@ -27802,7 +28343,7 @@ var SQLiteDialect = class {
27802
28343
  sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`
27803
28344
  );
27804
28345
  }
27805
- if (index < joins.length - 1) {
28346
+ if (index2 < joins.length - 1) {
27806
28347
  joinsArray.push(sql` `);
27807
28348
  }
27808
28349
  }
@@ -27815,9 +28356,9 @@ var SQLiteDialect = class {
27815
28356
  buildOrderBy(orderBy) {
27816
28357
  const orderByList = [];
27817
28358
  if (orderBy) {
27818
- for (const [index, orderByValue] of orderBy.entries()) {
28359
+ for (const [index2, orderByValue] of orderBy.entries()) {
27819
28360
  orderByList.push(orderByValue);
27820
- if (index < orderBy.length - 1) {
28361
+ if (index2 < orderBy.length - 1) {
27821
28362
  orderByList.push(sql`, `);
27822
28363
  }
27823
28364
  }
@@ -27870,9 +28411,9 @@ var SQLiteDialect = class {
27870
28411
  const havingSql = having ? sql` having ${having}` : void 0;
27871
28412
  const groupByList = [];
27872
28413
  if (groupBy) {
27873
- for (const [index, groupByValue] of groupBy.entries()) {
28414
+ for (const [index2, groupByValue] of groupBy.entries()) {
27874
28415
  groupByList.push(groupByValue);
27875
- if (index < groupBy.length - 1) {
28416
+ if (index2 < groupBy.length - 1) {
27876
28417
  groupByList.push(sql`, `);
27877
28418
  }
27878
28419
  }
@@ -30286,6 +30827,10 @@ var acpSessionStoreMigrations = [
30286
30827
  {
30287
30828
  "name": "0001_regular_ultimates.sql",
30288
30829
  "sql": "ALTER TABLE `acp_session` ADD `last_terminal_command_id` text;"
30830
+ },
30831
+ {
30832
+ "name": "0002_equal_black_queen.sql",
30833
+ "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`);"
30289
30834
  }
30290
30835
  ];
30291
30836
 
@@ -30293,7 +30838,8 @@ var acpSessionStoreMigrations = [
30293
30838
  var acp_session_store_exports = {};
30294
30839
  __export(acp_session_store_exports, {
30295
30840
  acpSession: () => acpSession,
30296
- deletedAcpSession: () => deletedAcpSession
30841
+ deletedAcpSession: () => deletedAcpSession,
30842
+ sessionEventV2: () => sessionEventV2
30297
30843
  });
30298
30844
 
30299
30845
  // src/schema/acp-session-store/acp-session.ts
@@ -30314,6 +30860,21 @@ var deletedAcpSession = sqliteTable("deleted_acp_session", {
30314
30860
  sessionId: text("session_id").primaryKey()
30315
30861
  });
30316
30862
 
30863
+ // src/schema/acp-session-store/session-event-v2.ts
30864
+ var sessionEventV2 = sqliteTable(
30865
+ "session_event_v2",
30866
+ {
30867
+ eventId: text("event_id").primaryKey(),
30868
+ eventJson: text("event_json").notNull(),
30869
+ position: integer2("position").notNull(),
30870
+ sessionId: text("session_id").notNull()
30871
+ },
30872
+ (table) => [
30873
+ uniqueIndex("session_event_v2_session_position_unique").on(table.sessionId, table.position),
30874
+ index("session_event_v2_session_position_index").on(table.sessionId, table.position)
30875
+ ]
30876
+ );
30877
+
30317
30878
  // src/acp/session-store.ts
30318
30879
  var AcpStoredSession = class {
30319
30880
  additionalDirectories;
@@ -30356,9 +30917,21 @@ var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
30356
30917
  var MemoryAcpSessionStore = class {
30357
30918
  #sessions = /* @__PURE__ */ new Map();
30358
30919
  #deleted = /* @__PURE__ */ new Set();
30920
+ #eventsV2 = /* @__PURE__ */ new Map();
30921
+ appendExecutingPromptEventV2 = (event) => {
30922
+ const events = this.#eventsV2.get(event.sessionId);
30923
+ if (events === void 0) {
30924
+ throw new Error("The executing prompt event log has not started");
30925
+ }
30926
+ events.push(event);
30927
+ };
30928
+ clearExecutingPromptEventsV2 = (sessionId) => {
30929
+ this.#eventsV2.delete(sessionId);
30930
+ };
30359
30931
  close = () => {
30360
30932
  this.#sessions.clear();
30361
30933
  this.#deleted.clear();
30934
+ this.#eventsV2.clear();
30362
30935
  };
30363
30936
  findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
30364
30937
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
@@ -30369,6 +30942,7 @@ var MemoryAcpSessionStore = class {
30369
30942
  for (const id of ids) {
30370
30943
  this.#sessions.delete(id);
30371
30944
  this.#deleted.add(id);
30945
+ this.#eventsV2.delete(id);
30372
30946
  }
30373
30947
  return ids;
30374
30948
  };
@@ -30381,6 +30955,13 @@ var MemoryAcpSessionStore = class {
30381
30955
  };
30382
30956
  remove = (sessionId) => {
30383
30957
  this.#sessions.delete(sessionId);
30958
+ this.#eventsV2.delete(sessionId);
30959
+ };
30960
+ readExecutingPromptEventsV2 = (sessionId) => [
30961
+ ...this.#eventsV2.get(sessionId) ?? []
30962
+ ];
30963
+ startExecutingPromptEventsV2 = (sessionId, events) => {
30964
+ this.#eventsV2.set(sessionId, [...events]);
30384
30965
  };
30385
30966
  write = (session) => {
30386
30967
  this.#sessions.set(session.sessionId, session);
@@ -30430,15 +31011,15 @@ var SqliteAcpSessionStore = class {
30430
31011
  this.#sqliteDatabase.close();
30431
31012
  throw new Error("The ACP Session database was created by a newer Mobius version");
30432
31013
  }
30433
- for (let index = version3; index < acpSessionStoreMigrations.length; index += 1) {
30434
- const migration = acpSessionStoreMigrations[index];
31014
+ for (let index2 = version3; index2 < acpSessionStoreMigrations.length; index2 += 1) {
31015
+ const migration = acpSessionStoreMigrations[index2];
30435
31016
  if (migration === void 0) {
30436
31017
  throw new Error("The ACP Session migration is unavailable");
30437
31018
  }
30438
31019
  this.#sqliteDatabase.exec("BEGIN IMMEDIATE");
30439
31020
  try {
30440
31021
  this.#sqliteDatabase.exec(migration.sql);
30441
- this.#sqliteDatabase.pragma(`user_version = ${index + 1}`);
31022
+ this.#sqliteDatabase.pragma(`user_version = ${index2 + 1}`);
30442
31023
  this.#sqliteDatabase.exec("COMMIT");
30443
31024
  } catch (error62) {
30444
31025
  this.#sqliteDatabase.exec("ROLLBACK");
@@ -30449,6 +31030,30 @@ var SqliteAcpSessionStore = class {
30449
31030
  close = () => {
30450
31031
  this.#sqliteDatabase.close();
30451
31032
  };
31033
+ appendExecutingPromptEventV2 = (event) => {
31034
+ this.#database.insert(sessionEventV2).values({
31035
+ eventId: event.eventId,
31036
+ eventJson: JSON.stringify(event),
31037
+ position: Number(event.position),
31038
+ sessionId: event.sessionId
31039
+ }).run();
31040
+ };
31041
+ clearExecutingPromptEventsV2 = (sessionId) => {
31042
+ this.#database.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
31043
+ };
31044
+ startExecutingPromptEventsV2 = (sessionId, events) => {
31045
+ this.#database.transaction((transaction) => {
31046
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
31047
+ for (const event of events) {
31048
+ transaction.insert(sessionEventV2).values({
31049
+ eventId: event.eventId,
31050
+ eventJson: JSON.stringify(event),
31051
+ position: Number(event.position),
31052
+ sessionId: event.sessionId
31053
+ }).run();
31054
+ }
31055
+ });
31056
+ };
30452
31057
  findNative = (agentId, nativeSessionId) => this.#database.select().from(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).all().map(decodeStoredSession);
30453
31058
  list = () => this.#database.select().from(acpSession).orderBy(desc(acpSession.updatedAt)).all().map(decodeStoredSession);
30454
31059
  markDeleted = (agentId, nativeSessionId) => {
@@ -30457,6 +31062,7 @@ var SqliteAcpSessionStore = class {
30457
31062
  transaction.delete(acpSession).where(and(eq(acpSession.agentId, agentId), eq(acpSession.nativeSessionId, nativeSessionId))).run();
30458
31063
  for (const id of ids) {
30459
31064
  transaction.insert(deletedAcpSession).values({ sessionId: id }).onConflictDoNothing().run();
31065
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, id)).run();
30460
31066
  }
30461
31067
  });
30462
31068
  return ids;
@@ -30470,8 +31076,12 @@ var SqliteAcpSessionStore = class {
30470
31076
  const row = this.#database.select().from(acpSession).where(eq(acpSession.sessionId, sessionId)).get();
30471
31077
  return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeStoredSession(row));
30472
31078
  };
31079
+ 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));
30473
31080
  remove = (sessionId) => {
30474
- this.#database.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
31081
+ this.#database.transaction((transaction) => {
31082
+ transaction.delete(acpSession).where(eq(acpSession.sessionId, sessionId)).run();
31083
+ transaction.delete(sessionEventV2).where(eq(sessionEventV2.sessionId, sessionId)).run();
31084
+ });
30475
31085
  };
30476
31086
  write = (session) => {
30477
31087
  const value = {
@@ -30504,7 +31114,7 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
30504
31114
  }
30505
31115
  };
30506
31116
  function arraysEqual(left, right) {
30507
- return left.length === right.length && left.every((value, index) => value === right[index]);
31117
+ return left.length === right.length && left.every((value, index2) => value === right[index2]);
30508
31118
  }
30509
31119
  function recordsEqual(left, right) {
30510
31120
  const leftEntries = Object.entries(left);
@@ -30651,6 +31261,17 @@ var AgentSession = class _AgentSession {
30651
31261
  const loaded = await this.#loadSession(signal, "ACP agent exited while loading history");
30652
31262
  return await embedLocalHistoryImages(await loaded.history.snapshot(), signal);
30653
31263
  };
31264
+ loadHistoryEventsV2 = async (eventLimit, cursor, signal) => {
31265
+ if (!this.#capabilities.loadSession) {
31266
+ throw new AcpExecutionError(
31267
+ "This Agent restores context but does not provide message history.",
31268
+ {},
31269
+ "native_history_unsupported"
31270
+ );
31271
+ }
31272
+ const loaded = await this.#loadSession(signal, "ACP agent exited while loading history");
31273
+ return loaded.history.eventPage(eventLimit, cursor);
31274
+ };
30654
31275
  async #loadSession(signal, exitMessage) {
30655
31276
  if (this.#sessionLoad.kind === "loaded") {
30656
31277
  return this.#sessionLoad;
@@ -31133,6 +31754,19 @@ var AgentSession = class _AgentSession {
31133
31754
  if (this.#turn.running) {
31134
31755
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
31135
31756
  }
31757
+ switch (this.#sessionLoad.kind) {
31758
+ case "not-requested":
31759
+ break;
31760
+ case "loaded":
31761
+ this.#sessionLoad = { kind: "not-requested" };
31762
+ break;
31763
+ case "capturing":
31764
+ throw new AcpExecutionError("Session history is still loading", {}, "session_busy");
31765
+ default: {
31766
+ const unexpected = this.#sessionLoad;
31767
+ throw new Error(`Unexpected Session load state: ${JSON.stringify(unexpected)}`);
31768
+ }
31769
+ }
31136
31770
  const prompt = this.buildPrompt(options);
31137
31771
  if (this.#sessionTitle === null || this.#sessionTitle.length === 0) {
31138
31772
  this.#sessionTitle = truncate2(options.prompt, 500);
@@ -31297,8 +31931,14 @@ var AgentSession = class _AgentSession {
31297
31931
  #processUpdate = async (notification) => {
31298
31932
  this.assertNativeSession(notification.sessionId);
31299
31933
  const update = notification.update;
31300
- if (this.#sessionLoad.kind !== "not-requested") {
31301
- await this.#sessionLoad.history.record(update);
31934
+ const rawUpdate = decodeAcpSessionUpdateV2(JSON.stringify(update));
31935
+ if (this.#sessionLoad.kind === "capturing") {
31936
+ await this.#sessionLoad.history.record(update, rawUpdate);
31937
+ } else {
31938
+ const onAcpUpdate = this.#getObserver().onAcpUpdate;
31939
+ if (onAcpUpdate !== void 0) {
31940
+ await onAcpUpdate(this.#mobiusSessionId, rawUpdate);
31941
+ }
31302
31942
  }
31303
31943
  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")) {
31304
31944
  return;
@@ -31680,6 +32320,21 @@ var AgentQueryProcesses = class {
31680
32320
  async (runtime) => await runtime.closeProcess()
31681
32321
  );
31682
32322
  };
32323
+ previewEventsV2 = async (options, nativeSessionId, eventLimit, cursor) => {
32324
+ return await this.#processes.runTransient(
32325
+ options.signal,
32326
+ async () => await AgentSession.startNativeSessionBrowser(
32327
+ options,
32328
+ () => this.#observer,
32329
+ new MemoryAcpSessionStore()
32330
+ ),
32331
+ async (runtime) => {
32332
+ runtime.selectNativeSession(nativeSessionId);
32333
+ return await runtime.loadHistoryEventsV2(eventLimit, cursor, options.signal);
32334
+ },
32335
+ async (runtime) => await runtime.closeProcess()
32336
+ );
32337
+ };
31683
32338
  close = async () => {
31684
32339
  await Promise.all(
31685
32340
  this.#processesByQuery.entries().map(async ([id, runtime]) => await this.retire(id, runtime))
@@ -31749,9 +32404,9 @@ var AcpProcessCapacityLock = class {
31749
32404
  return await waiter.completion.promise;
31750
32405
  } finally {
31751
32406
  signal.removeEventListener("abort", waiter.cancel);
31752
- const index = this.#waiters.indexOf(waiter);
31753
- if (index >= 0) {
31754
- this.#waiters.splice(index, 1);
32407
+ const index2 = this.#waiters.indexOf(waiter);
32408
+ if (index2 >= 0) {
32409
+ this.#waiters.splice(index2, 1);
31755
32410
  }
31756
32411
  }
31757
32412
  };
@@ -32381,6 +33036,22 @@ var AgentRuntimeManager = class {
32381
33036
  this.#nativeOperations.delete(key);
32382
33037
  }
32383
33038
  });
33039
+ previewNativeSessionEventsV2 = async (options, nativeSessionId, eventLimit, cursor) => this.#operations.run(options, async (options2) => {
33040
+ const key = `${options2.agent.id}:${nativeSessionId}`;
33041
+ if (this.#nativeOperations.has(key)) {
33042
+ throw new AcpExecutionError(
33043
+ "Wait for the native session's running operation to finish",
33044
+ {},
33045
+ "session_busy"
33046
+ );
33047
+ }
33048
+ this.#nativeOperations.add(key);
33049
+ try {
33050
+ return await this.#queryProcesses.previewEventsV2(options2, nativeSessionId, eventLimit, cursor);
33051
+ } finally {
33052
+ this.#nativeOperations.delete(key);
33053
+ }
33054
+ });
32384
33055
  loadSessionHistory = async (options) => this.#operations.run(options, async (options2) => {
32385
33056
  return await this.#executionProcesses.use(options2.sessionId, async () => {
32386
33057
  const runtime = await this.ensureSession(options2);
@@ -32398,6 +33069,12 @@ var AgentRuntimeManager = class {
32398
33069
  return await runtime.loadHistory(options2.signal);
32399
33070
  });
32400
33071
  });
33072
+ loadSessionEventsV2 = async (options, eventLimit, cursor) => this.#operations.run(options, async (options2) => {
33073
+ return await this.#executionProcesses.use(options2.sessionId, async () => {
33074
+ const runtime = await this.ensureSession(options2);
33075
+ return await runtime.loadHistoryEventsV2(eventLimit, cursor, options2.signal);
33076
+ });
33077
+ });
32401
33078
  openNativeSession = async (options, origin) => this.#operations.run(options, async (options2) => {
32402
33079
  const key = `${options2.agent.id}:${origin.nativeSessionId}`;
32403
33080
  if (this.#nativeOperations.has(key)) {
@@ -36300,9 +36977,9 @@ function comparePrerelease(left, right) {
36300
36977
  if (left.length === 0 || right.length === 0) {
36301
36978
  return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
36302
36979
  }
36303
- for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
36304
- const leftPart = left[index];
36305
- const rightPart = right[index];
36980
+ for (let index2 = 0; index2 < Math.max(left.length, right.length); index2 += 1) {
36981
+ const leftPart = left[index2];
36982
+ const rightPart = right[index2];
36306
36983
  if (leftPart === void 0 || rightPart === void 0) {
36307
36984
  return leftPart === rightPart ? 0 : leftPart === void 0 ? -1 : 1;
36308
36985
  }
@@ -36327,8 +37004,8 @@ function compareAgentVersions(left, right) {
36327
37004
  if (parsedLeft === null || parsedRight === null) {
36328
37005
  return null;
36329
37006
  }
36330
- for (let index = 0; index < Math.max(parsedLeft.core.length, parsedRight.core.length); index += 1) {
36331
- const difference = (parsedLeft.core[index] ?? 0) - (parsedRight.core[index] ?? 0);
37007
+ for (let index2 = 0; index2 < Math.max(parsedLeft.core.length, parsedRight.core.length); index2 += 1) {
37008
+ const difference = (parsedLeft.core[index2] ?? 0) - (parsedRight.core[index2] ?? 0);
36332
37009
  if (difference !== 0) {
36333
37010
  return Math.sign(difference);
36334
37011
  }
@@ -37071,16 +37748,16 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
37071
37748
  };
37072
37749
  #readConnectionForChannel = async (channelId, signal) => {
37073
37750
  const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
37074
- const index = decodeChannelIndex(
37751
+ const index2 = decodeChannelIndex(
37075
37752
  await readJsonFile(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
37076
37753
  );
37077
- if (index.applicationId !== this.applicationId || index.installationId !== this.installationId || index.channelId !== normalizedChannelId) {
37754
+ if (index2.applicationId !== this.applicationId || index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
37078
37755
  throw new RuntimeInstallationStoreError(
37079
37756
  "connection_owner_mismatch",
37080
37757
  "The saved Runtime connection belongs to another installation"
37081
37758
  );
37082
37759
  }
37083
- return await this.readConnection(index.connectionId, signal);
37760
+ return await this.readConnection(index2.connectionId, signal);
37084
37761
  };
37085
37762
  saveConnection = async (input2, signal) => {
37086
37763
  const stored = new VerifiedRuntimeConnection(
@@ -37275,16 +37952,16 @@ function hasExactKeys2(value, expectedKeys) {
37275
37952
  }
37276
37953
  function readSingleOption(arguments_, option) {
37277
37954
  const values = [];
37278
- for (let index = 0; index < arguments_.length; index += 1) {
37279
- if (arguments_[index] !== option) {
37955
+ for (let index2 = 0; index2 < arguments_.length; index2 += 1) {
37956
+ if (arguments_[index2] !== option) {
37280
37957
  continue;
37281
37958
  }
37282
- const value = arguments_[index + 1];
37959
+ const value = arguments_[index2 + 1];
37283
37960
  if (value === void 0 || value.startsWith("--")) {
37284
37961
  throw new PairingClientError("invalid_arguments", `${option} requires a value`);
37285
37962
  }
37286
37963
  values.push(value);
37287
- index += 1;
37964
+ index2 += 1;
37288
37965
  }
37289
37966
  if (values.length !== 1) {
37290
37967
  throw new PairingClientError("invalid_arguments", `${option} must be provided exactly once`);
@@ -37292,8 +37969,8 @@ function readSingleOption(arguments_, option) {
37292
37969
  return values[0] ?? "";
37293
37970
  }
37294
37971
  function assertKnownArguments(arguments_) {
37295
- for (let index = 0; index < arguments_.length; index += 2) {
37296
- const option = arguments_[index];
37972
+ for (let index2 = 0; index2 < arguments_.length; index2 += 2) {
37973
+ const option = arguments_[index2];
37297
37974
  if (option !== "--url" && option !== "--code" && option !== "--pairing" && option !== "--workspace") {
37298
37975
  throw new PairingClientError("invalid_arguments", `Unknown pairing option: ${option ?? "missing option"}`);
37299
37976
  }
@@ -37584,7 +38261,7 @@ function isRuntimeRelayRevocation(closeCode, closeReason) {
37584
38261
  }
37585
38262
 
37586
38263
  // src/run-daemon.ts
37587
- import { createHash as createHash6, randomUUID as randomUUID7 } from "node:crypto";
38264
+ import { createHash as createHash7, randomUUID as randomUUID7 } from "node:crypto";
37588
38265
  import { join as join18 } from "node:path";
37589
38266
  import { styleText } from "node:util";
37590
38267
 
@@ -38656,9 +39333,15 @@ function reportOperationFailure(socket, requestId, sessionId, error62, runtimeTi
38656
39333
  // src/daemon-observers.ts
38657
39334
  var DaemonAcpObserver = class {
38658
39335
  #record;
38659
- constructor(record2) {
39336
+ #recordV2;
39337
+ constructor(record2, recordV2 = () => void 0) {
38660
39338
  this.#record = record2;
39339
+ this.#recordV2 = recordV2;
38661
39340
  }
39341
+ onAcpUpdate = (sessionId, update) => {
39342
+ this.#recordV2(sessionId, { payload: update, type: "acp" });
39343
+ return Promise.resolve();
39344
+ };
38662
39345
  onCommands = (event) => {
38663
39346
  this.#record(event.sessionId, event);
38664
39347
  return Promise.resolve();
@@ -38673,10 +39356,18 @@ var DaemonAcpObserver = class {
38673
39356
  };
38674
39357
  onElicitation = (event) => {
38675
39358
  this.#record(event.sessionId, event);
39359
+ this.#recordV2(event.sessionId, {
39360
+ payload: { event, kind: "session.elicitation.requested" },
39361
+ type: "lifecycle-metadata"
39362
+ });
38676
39363
  return Promise.resolve();
38677
39364
  };
38678
39365
  onElicitationResolved = (event) => {
38679
39366
  this.#record(event.sessionId, event);
39367
+ this.#recordV2(event.sessionId, {
39368
+ payload: { event, kind: "session.elicitation.resolved" },
39369
+ type: "lifecycle-metadata"
39370
+ });
38680
39371
  return Promise.resolve();
38681
39372
  };
38682
39373
  onInfo = (event) => {
@@ -38685,10 +39376,18 @@ var DaemonAcpObserver = class {
38685
39376
  };
38686
39377
  onPermission = (event) => {
38687
39378
  this.#record(event.sessionId, event);
39379
+ this.#recordV2(event.sessionId, {
39380
+ payload: { event, kind: "session.permission.requested" },
39381
+ type: "lifecycle-metadata"
39382
+ });
38688
39383
  return Promise.resolve();
38689
39384
  };
38690
39385
  onPermissionResolved = (event) => {
38691
39386
  this.#record(event.sessionId, event);
39387
+ this.#recordV2(event.sessionId, {
39388
+ payload: { event, kind: "session.permission.resolved" },
39389
+ type: "lifecycle-metadata"
39390
+ });
38692
39391
  return Promise.resolve();
38693
39392
  };
38694
39393
  onUsage = (event) => {
@@ -38795,8 +39494,8 @@ var ACTIVE_TURN_TEXT_CHUNK_LIMIT = Math.floor(SESSION_HISTORY_CHARACTER_LIMIT /
38795
39494
  function boundedRecoveryMessages(messages) {
38796
39495
  const selected = [];
38797
39496
  let remainingCharacters = SESSION_HISTORY_CHARACTER_LIMIT;
38798
- for (let index = messages.length - 1; index >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index -= 1) {
38799
- const message = messages[index];
39497
+ for (let index2 = messages.length - 1; index2 >= 0 && selected.length < SESSION_HISTORY_MESSAGE_LIMIT; index2 -= 1) {
39498
+ const message = messages[index2];
38800
39499
  if (message === void 0) {
38801
39500
  break;
38802
39501
  }
@@ -38937,7 +39636,7 @@ var ActiveDaemonTurn = class {
38937
39636
  ];
38938
39637
  } else {
38939
39638
  this.#timeline = this.#timeline.map(
38940
- (entry, index) => index === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
39639
+ (entry, index2) => index2 === target && entry.kind === "message" ? { ...entry, content: new Map([...entry.content, [event.contentId, event.content]]) } : entry
38941
39640
  );
38942
39641
  }
38943
39642
  } else if (event.kind === SESSION_PERMISSION_REQUESTED_KIND || event.kind === SESSION_ELICITATION_REQUESTED_KIND) {
@@ -39948,7 +40647,7 @@ async function readAcpHistory(sessions, directories, bindingId, options, nativeS
39948
40647
  async (directory) => await directories.identify(bindingId, directory, options.signal)
39949
40648
  )
39950
40649
  );
39951
- if (primary.path !== options.cwd || additional.length !== options.additionalDirectories.length || additional.some((directory, index) => directory.path !== options.additionalDirectories[index])) {
40650
+ if (primary.path !== options.cwd || additional.length !== options.additionalDirectories.length || additional.some((directory, index2) => directory.path !== options.additionalDirectories[index2])) {
39952
40651
  throw new AcpExecutionError(
39953
40652
  "The native Session belongs to another workspace.",
39954
40653
  {},
@@ -40081,7 +40780,7 @@ var NativeSessionService = class {
40081
40780
  "native_session_not_found"
40082
40781
  );
40083
40782
  }
40084
- if (source.agentId !== command.agentId || source.cwd !== cwd || source.additionalDirectories.length !== additionalDirectories.length || source.additionalDirectories.some((path2, index) => path2 !== additionalDirectories[index])) {
40783
+ if (source.agentId !== command.agentId || source.cwd !== cwd || source.additionalDirectories.length !== additionalDirectories.length || source.additionalDirectories.some((path2, index2) => path2 !== additionalDirectories[index2])) {
40085
40784
  throw new AcpExecutionError(
40086
40785
  "The source conversation execution target does not match the fork request",
40087
40786
  {},
@@ -40102,8 +40801,8 @@ var NativeSessionService = class {
40102
40801
  signal.throwIfAborted();
40103
40802
  const directory = await this.#directories.list(this.#config.bindingId, command.directoryId, signal);
40104
40803
  const ready2 = {
40105
- additionalDirectories: additionalDirectories.map((path2, index) => ({
40106
- directoryId: command.additionalDirectoryIds[index] ?? command.directoryId,
40804
+ additionalDirectories: additionalDirectories.map((path2, index2) => ({
40805
+ directoryId: command.additionalDirectoryIds[index2] ?? command.directoryId,
40107
40806
  name: basename5(path2) || path2
40108
40807
  })),
40109
40808
  agentId: command.agentId,
@@ -40435,7 +41134,7 @@ var NativeSessionService = class {
40435
41134
  resolveTarget = async (command, options, selected) => {
40436
41135
  let cursor = null;
40437
41136
  const visited = /* @__PURE__ */ new Set();
40438
- for (let index = 0; index < 100; index += 1) {
41137
+ for (let index2 = 0; index2 < 100; index2 += 1) {
40439
41138
  const page = await this.#sessions.listNativeSessions(options, cursor);
40440
41139
  const info = page.sessions.find((entry) => entry.sessionId === selected.nativeSessionId);
40441
41140
  if (info !== void 0) {
@@ -40443,7 +41142,7 @@ var NativeSessionService = class {
40443
41142
  if (target === null) {
40444
41143
  throw new LocalAuthorizationError("The selected native session is not authorized");
40445
41144
  }
40446
- if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path2, index2) => path2 !== selected.additionalDirectories[index2])) {
41145
+ if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path2, index3) => path2 !== selected.additionalDirectories[index3])) {
40447
41146
  throw new AcpExecutionError(
40448
41147
  "This session's directory changed. Refresh the list before continuing.",
40449
41148
  {},
@@ -41531,6 +42230,9 @@ async function streamLocalFile(command, send2, signal, workingDirectory) {
41531
42230
  });
41532
42231
  }
41533
42232
 
42233
+ // src/daemon-history-commands.ts
42234
+ import { createHash as createHash6 } from "node:crypto";
42235
+
41534
42236
  // src/authorization/resolve-session-directories.ts
41535
42237
  import { basename as basename7 } from "node:path";
41536
42238
  var ResolvedSessionDirectories = class {
@@ -41630,8 +42332,8 @@ function selectMessagesBefore(messages, endIndex, messageLimit, characterLimit)
41630
42332
  const selected = [];
41631
42333
  let remainingCharacters = characterLimit;
41632
42334
  let startIndex = endIndex;
41633
- for (let index = endIndex - 1; index >= 0 && selected.length < messageLimit; index -= 1) {
41634
- const message = messages[index];
42335
+ for (let index2 = endIndex - 1; index2 >= 0 && selected.length < messageLimit; index2 -= 1) {
42336
+ const message = messages[index2];
41635
42337
  if (message === void 0) {
41636
42338
  break;
41637
42339
  }
@@ -41641,7 +42343,7 @@ function selectMessagesBefore(messages, endIndex, messageLimit, characterLimit)
41641
42343
  }
41642
42344
  selected.unshift(message);
41643
42345
  remainingCharacters -= characters;
41644
- startIndex = index;
42346
+ startIndex = index2;
41645
42347
  }
41646
42348
  if (selected.length === 0 && endIndex > 0) {
41647
42349
  throw new AcpExecutionError(
@@ -41921,6 +42623,70 @@ async function executeSessionLiveHistoryPageLoad(socket, command, config2, direc
41921
42623
  });
41922
42624
  }
41923
42625
  }
42626
+ function replayEvent(sessionId, position, update) {
42627
+ const encoded = JSON.stringify(update);
42628
+ const eventId = `native-${createHash6("sha256").update(sessionId).update(":").update(position.toString()).update(":").update(encoded).digest("hex")}`;
42629
+ return {
42630
+ eventId,
42631
+ payload: update,
42632
+ position: position.toString(),
42633
+ provenance: { kind: "original" },
42634
+ recordedAt: "1970-01-01T00:00:00.000Z",
42635
+ sessionId,
42636
+ type: "acp"
42637
+ };
42638
+ }
42639
+ async function executeSessionLiveHistoryV2PageLoad(socket, command, config2, directories, audit, sessions, executingPromptRequest, signal) {
42640
+ try {
42641
+ const resolved = await resolveSessionDirectories(
42642
+ directories,
42643
+ config2.bindingId,
42644
+ command.directoryId,
42645
+ command.additionalDirectoryIds,
42646
+ signal
42647
+ );
42648
+ const replay = await sessions.loadSessionEventsV2(
42649
+ {
42650
+ additionalDirectories: resolved.additionalDirectories,
42651
+ agent: config2.catalog.find(command.agentId),
42652
+ cwd: resolved.cwd,
42653
+ sessionId: command.sessionId,
42654
+ signal
42655
+ },
42656
+ command.eventLimit,
42657
+ command.cursor
42658
+ );
42659
+ signal.throwIfAborted();
42660
+ const events = replay.updates.map(
42661
+ (update, index2) => replayEvent(command.sessionId, replay.startPosition + index2, update)
42662
+ );
42663
+ const tailCursor = events.at(-1)?.eventId ?? "";
42664
+ audit.record({
42665
+ commandId: command.requestId,
42666
+ event: "session_event_log_v2_loaded",
42667
+ sessionId: command.sessionId
42668
+ });
42669
+ send(socket, {
42670
+ events: {
42671
+ executingPromptRequest: executingPromptRequest(command.sessionId),
42672
+ history: {
42673
+ events,
42674
+ nextCursor: replay.nextCursor,
42675
+ tailCursor,
42676
+ truncated: replay.truncated,
42677
+ version: 2
42678
+ }
42679
+ },
42680
+ kind: "session.live-history.v2.page.loaded",
42681
+ requestId: command.requestId,
42682
+ sessionId: command.sessionId
42683
+ });
42684
+ } catch (error62) {
42685
+ if (!signal.aborted) {
42686
+ reportOperationFailure(socket, command.requestId, command.sessionId, error62);
42687
+ }
42688
+ }
42689
+ }
41924
42690
 
41925
42691
  // src/acp/session-config/apply-session-configuration.ts
41926
42692
  import { randomUUID as randomUUID5 } from "node:crypto";
@@ -42235,6 +43001,7 @@ function daemonActivity(command, activity2) {
42235
43001
  async function executePrompt({
42236
43002
  operations,
42237
43003
  publisher,
43004
+ eventLogV2,
42238
43005
  command,
42239
43006
  config: config2,
42240
43007
  directories,
@@ -42339,6 +43106,7 @@ async function executePrompt({
42339
43106
  }
42340
43107
  }
42341
43108
  const stream = activateAttempt();
43109
+ eventLogV2.started(command.sessionId, command.commandId, attemptId, stream.epoch);
42342
43110
  if (!prepared.prompted) {
42343
43111
  const listing = await directories.list(config2.bindingId, command.directoryId, signal);
42344
43112
  publisher.publish(command.sessionId, {
@@ -42408,6 +43176,7 @@ async function executePrompt({
42408
43176
  sessionId: command.sessionId,
42409
43177
  stopReason
42410
43178
  });
43179
+ eventLogV2.completed(command.sessionId, command.commandId, stopReason);
42411
43180
  operations.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
42412
43181
  audit.record({
42413
43182
  commandId: command.commandId,
@@ -42423,6 +43192,7 @@ async function executePrompt({
42423
43192
  sessionId: command.sessionId,
42424
43193
  stopReason: "cancelled"
42425
43194
  });
43195
+ eventLogV2.completed(command.sessionId, command.commandId, "cancelled");
42426
43196
  operations.transitionExecution(command.commandId, "cancelled");
42427
43197
  audit.record({
42428
43198
  commandId: command.commandId,
@@ -42437,12 +43207,10 @@ async function executePrompt({
42437
43207
  sessionId: command.sessionId
42438
43208
  });
42439
43209
  const code = operationErrorCode(error62);
42440
- reportFailure(
42441
- publisher,
42442
- command,
42443
- code === "session_operation_failed" ? "agent_execution_failed" : code,
42444
- code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62)
42445
- );
43210
+ const failureCode = code === "session_operation_failed" ? "agent_execution_failed" : code;
43211
+ const failureMessage = code === "session_operation_failed" ? "The local agent could not complete the request" : operationErrorMessage(error62);
43212
+ eventLogV2.failed(command.sessionId, command.commandId, failureCode, failureMessage);
43213
+ reportFailure(publisher, command, failureCode, failureMessage);
42446
43214
  operations.transitionExecution(command.commandId, "failed");
42447
43215
  console.error("Mobius daemon command failed", error62);
42448
43216
  }
@@ -42725,6 +43493,7 @@ function createDaemonCommandHandler({
42725
43493
  nativeSessions,
42726
43494
  operations,
42727
43495
  publisher,
43496
+ eventLogV2,
42728
43497
  activeTurns,
42729
43498
  diagnostics,
42730
43499
  socket,
@@ -42752,7 +43521,10 @@ function createDaemonCommandHandler({
42752
43521
  timer,
42753
43522
  resolveEnvironment: resolveAgentCatalogEnvironment
42754
43523
  });
42755
- const queueChanged = (sessionId) => publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
43524
+ const queueChanged = (sessionId) => {
43525
+ publisher.publish(sessionId, { kind: "session.queue.changed", sessionId });
43526
+ eventLogV2.queueChanged(sessionId);
43527
+ };
42756
43528
  const activeTurnRecovery = (sessionId) => activeTurns.recovery((command) => command.sessionId === sessionId);
42757
43529
  const nativeRequestHandler = createNativeSessionRequestHandler({
42758
43530
  audit,
@@ -42794,6 +43566,19 @@ function createDaemonCommandHandler({
42794
43566
  );
42795
43567
  return;
42796
43568
  }
43569
+ if (kind === SESSION_LIVE_HISTORY_V2_PAGE_LOAD_KIND) {
43570
+ void executeSessionLiveHistoryV2PageLoad(
43571
+ socket,
43572
+ message,
43573
+ config2,
43574
+ directories,
43575
+ audit,
43576
+ sessions,
43577
+ eventLogV2.executingPromptRequest,
43578
+ signal
43579
+ );
43580
+ return;
43581
+ }
42797
43582
  if (kind === NATIVE_SESSION_CANCEL_KIND) {
42798
43583
  nativeRequestHandler.cancel(message);
42799
43584
  return;
@@ -42979,9 +43764,11 @@ function createDaemonCommandHandler({
42979
43764
  return;
42980
43765
  }
42981
43766
  const turn = activeTurns.start(command, receipt.attemptId);
43767
+ eventLogV2.requested(command);
42982
43768
  void executePrompt({
42983
43769
  operations,
42984
43770
  publisher,
43771
+ eventLogV2,
42985
43772
  command,
42986
43773
  config: config2,
42987
43774
  directories,
@@ -43251,6 +44038,7 @@ async function runRelayConnection({
43251
44038
  nativeSessions,
43252
44039
  operations,
43253
44040
  publisher,
44041
+ eventLogV2,
43254
44042
  activeTurns,
43255
44043
  connectionEpoch,
43256
44044
  diagnostics,
@@ -43273,6 +44061,7 @@ async function runRelayConnection({
43273
44061
  nativeSessions,
43274
44062
  operations,
43275
44063
  publisher,
44064
+ eventLogV2,
43276
44065
  activeTurns,
43277
44066
  diagnostics,
43278
44067
  socket,
@@ -43452,6 +44241,21 @@ var DaemonSessionEventPublisher = class {
43452
44241
  this.publish(sessionId, event);
43453
44242
  }
43454
44243
  };
44244
+ publishV2 = (event) => {
44245
+ const socket = this.#socket;
44246
+ if (socket === null || socket.readyState !== WebSocket9.OPEN) {
44247
+ return;
44248
+ }
44249
+ const encoded = encodeDaemonToServiceMessage({ event, kind: SESSION_EVENT_V2_KIND });
44250
+ if (socket.bufferedAmount + Buffer.byteLength(encoded, "utf8") > MAX_BUFFERED_BYTES) {
44251
+ socket.close(1013, "Live event transport overloaded");
44252
+ return;
44253
+ }
44254
+ try {
44255
+ socket.send(encoded);
44256
+ } catch {
44257
+ }
44258
+ };
43455
44259
  };
43456
44260
 
43457
44261
  // src/relay-connection/timer.ts
@@ -43463,6 +44267,266 @@ var SystemDaemonTimer = class {
43463
44267
  };
43464
44268
  var systemDaemonTimer = new SystemDaemonTimer();
43465
44269
 
44270
+ // src/session-event-log-v2.ts
44271
+ var EXECUTING_PROMPT_EVENT_LIMIT = 1e4;
44272
+ function eventArray(tail) {
44273
+ const reversed = [];
44274
+ let node2 = tail;
44275
+ while (node2 !== null) {
44276
+ reversed.push(node2.event);
44277
+ node2 = node2.previous;
44278
+ }
44279
+ return reversed.reverse();
44280
+ }
44281
+ function promptContent(command) {
44282
+ const content = [];
44283
+ if (command.prompt.length > 0) {
44284
+ content.push({ text: command.prompt, type: "text" });
44285
+ }
44286
+ for (const image of command.images) {
44287
+ content.push({
44288
+ _meta: { mobius: { name: image.name } },
44289
+ data: image.data,
44290
+ mimeType: image.mimeType,
44291
+ type: "image"
44292
+ });
44293
+ }
44294
+ for (const resource of command.resources) {
44295
+ content.push(
44296
+ resource.type === "embedded" ? {
44297
+ resource: { mimeType: resource.mimeType, text: resource.text, uri: resource.uri },
44298
+ type: "resource"
44299
+ } : { mimeType: resource.mimeType, name: resource.name, type: "resource_link", uri: resource.uri }
44300
+ );
44301
+ }
44302
+ return content;
44303
+ }
44304
+ var DaemonSessionEventLogV2 = class {
44305
+ #positions = /* @__PURE__ */ new Map();
44306
+ #requests = /* @__PURE__ */ new Map();
44307
+ #loadedRequestSessions = /* @__PURE__ */ new Set();
44308
+ #publisher;
44309
+ #store;
44310
+ constructor(publisher, store) {
44311
+ this.#publisher = publisher;
44312
+ this.#store = store;
44313
+ }
44314
+ #loadStoredEvents = (sessionId) => {
44315
+ const stored = this.#store.readExecutingPromptEventsV2(sessionId);
44316
+ const lastPosition = stored.at(-1)?.position;
44317
+ if (lastPosition !== void 0) {
44318
+ this.#positions.set(sessionId, Number(lastPosition));
44319
+ }
44320
+ return stored;
44321
+ };
44322
+ #loadRequests = (sessionId) => {
44323
+ if (this.#loadedRequestSessions.has(sessionId)) {
44324
+ return;
44325
+ }
44326
+ for (const event of this.#loadStoredEvents(sessionId)) {
44327
+ if (event.type === "acp") {
44328
+ const executing = [...this.#requests.values()].find(
44329
+ (request) => request.sessionId === sessionId && request.kind === "executing"
44330
+ );
44331
+ if (executing !== void 0) {
44332
+ this.#requests.set(executing.commandId, {
44333
+ ...executing,
44334
+ eventTail: { event, previous: executing.eventTail }
44335
+ });
44336
+ }
44337
+ continue;
44338
+ }
44339
+ const payload = event.payload;
44340
+ if (payload.kind === "prompt.requested") {
44341
+ this.#requests.set(payload.commandId, {
44342
+ commandId: payload.commandId,
44343
+ eventTail: { event, previous: null },
44344
+ kind: "requested",
44345
+ sessionId
44346
+ });
44347
+ continue;
44348
+ }
44349
+ if ("event" in payload) {
44350
+ const executing = [...this.#requests.values()].find(
44351
+ (request) => request.sessionId === sessionId && request.kind === "executing"
44352
+ );
44353
+ if (executing !== void 0) {
44354
+ this.#requests.set(executing.commandId, {
44355
+ ...executing,
44356
+ eventTail: { event, previous: executing.eventTail }
44357
+ });
44358
+ }
44359
+ continue;
44360
+ }
44361
+ if (!("commandId" in payload)) {
44362
+ continue;
44363
+ }
44364
+ const state = this.#requests.get(payload.commandId);
44365
+ if (state === void 0) {
44366
+ continue;
44367
+ }
44368
+ if (payload.kind === "prompt.started") {
44369
+ this.#requests.set(payload.commandId, {
44370
+ attemptId: payload.attemptId,
44371
+ commandId: payload.commandId,
44372
+ epoch: payload.epoch,
44373
+ eventTail: { event, previous: state.eventTail },
44374
+ kind: "executing",
44375
+ sessionId
44376
+ });
44377
+ } else if (payload.kind === "prompt.completed" || payload.kind === "prompt.failed" || payload.kind === "prompt.failed-before-start") {
44378
+ this.#requests.delete(payload.commandId);
44379
+ }
44380
+ }
44381
+ this.#loadedRequestSessions.add(sessionId);
44382
+ };
44383
+ #append = (sessionId, payload) => {
44384
+ this.#loadRequests(sessionId);
44385
+ const position = (this.#positions.get(sessionId) ?? 0) + 1;
44386
+ const event = {
44387
+ eventId: `event-${crypto.randomUUID()}`,
44388
+ ...payload,
44389
+ position: position.toString(),
44390
+ provenance: { kind: "original" },
44391
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
44392
+ sessionId
44393
+ };
44394
+ this.#positions.set(sessionId, position);
44395
+ this.#publisher.publishV2(event);
44396
+ return event;
44397
+ };
44398
+ requested = (command) => {
44399
+ const content = promptContent(command);
44400
+ const event = this.#append(command.sessionId, {
44401
+ payload: { commandId: command.commandId, content, kind: "prompt.requested" },
44402
+ type: "lifecycle-metadata"
44403
+ });
44404
+ let eventTail = { event, previous: null };
44405
+ for (const block of content) {
44406
+ const userMessageEvent = this.#append(command.sessionId, {
44407
+ payload: {
44408
+ content: block,
44409
+ messageId: command.commandId,
44410
+ sessionUpdate: "user_message_chunk"
44411
+ },
44412
+ type: "acp"
44413
+ });
44414
+ eventTail = { event: userMessageEvent, previous: eventTail };
44415
+ }
44416
+ this.#requests.set(command.commandId, {
44417
+ commandId: command.commandId,
44418
+ eventTail,
44419
+ kind: "requested",
44420
+ sessionId: command.sessionId
44421
+ });
44422
+ };
44423
+ started = (sessionId, commandId, attemptId, epoch) => {
44424
+ this.#loadRequests(sessionId);
44425
+ const request = this.#requests.get(commandId);
44426
+ if (request?.sessionId !== sessionId) {
44427
+ return;
44428
+ }
44429
+ const event = this.#append(sessionId, {
44430
+ payload: { attemptId, commandId, epoch, kind: "prompt.started" },
44431
+ type: "lifecycle-metadata"
44432
+ });
44433
+ this.#requests.set(commandId, {
44434
+ attemptId,
44435
+ commandId,
44436
+ epoch,
44437
+ eventTail: { event, previous: request.eventTail },
44438
+ kind: "executing",
44439
+ sessionId
44440
+ });
44441
+ this.#store.startExecutingPromptEventsV2(sessionId, eventArray({ event, previous: request.eventTail }));
44442
+ };
44443
+ record = (sessionId, payload) => {
44444
+ this.#loadRequests(sessionId);
44445
+ const event = this.#append(sessionId, payload);
44446
+ this.#appendToExecutingRequest(sessionId, event);
44447
+ };
44448
+ #appendToExecutingRequest = (sessionId, event) => {
44449
+ const executing = [...this.#requests.values()].find(
44450
+ (request) => request.sessionId === sessionId && request.kind === "executing"
44451
+ );
44452
+ if (executing !== void 0) {
44453
+ this.#requests.set(executing.commandId, {
44454
+ ...executing,
44455
+ eventTail: { event, previous: executing.eventTail }
44456
+ });
44457
+ this.#store.appendExecutingPromptEventV2(event);
44458
+ }
44459
+ };
44460
+ queueChanged = (sessionId) => {
44461
+ const event = this.#append(sessionId, {
44462
+ payload: { kind: "session.queue.changed" },
44463
+ type: "lifecycle-metadata"
44464
+ });
44465
+ this.#appendToExecutingRequest(sessionId, event);
44466
+ };
44467
+ completed = (sessionId, commandId, stopReason) => {
44468
+ this.#loadRequests(sessionId);
44469
+ const request = this.#requests.get(commandId);
44470
+ const event = this.#append(sessionId, {
44471
+ payload: { commandId, kind: "prompt.completed", stopReason },
44472
+ type: "lifecycle-metadata"
44473
+ });
44474
+ this.#requests.delete(commandId);
44475
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
44476
+ this.#store.clearExecutingPromptEventsV2(sessionId);
44477
+ } else {
44478
+ this.#appendToExecutingRequest(sessionId, event);
44479
+ }
44480
+ };
44481
+ failed = (sessionId, commandId, code, message) => {
44482
+ this.#loadRequests(sessionId);
44483
+ const request = this.#requests.get(commandId);
44484
+ let event;
44485
+ if (request?.kind === "executing" && request.commandId === commandId) {
44486
+ event = this.#append(sessionId, {
44487
+ payload: {
44488
+ attemptId: request.attemptId,
44489
+ code,
44490
+ commandId,
44491
+ kind: "prompt.failed",
44492
+ message
44493
+ },
44494
+ type: "lifecycle-metadata"
44495
+ });
44496
+ } else {
44497
+ event = this.#append(sessionId, {
44498
+ payload: { code, commandId, kind: "prompt.failed-before-start", message },
44499
+ type: "lifecycle-metadata"
44500
+ });
44501
+ }
44502
+ this.#requests.delete(commandId);
44503
+ if (request?.kind === "executing" && request.sessionId === sessionId) {
44504
+ this.#store.clearExecutingPromptEventsV2(sessionId);
44505
+ } else {
44506
+ this.#appendToExecutingRequest(sessionId, event);
44507
+ }
44508
+ };
44509
+ executingPromptRequest = (sessionId) => {
44510
+ this.#loadRequests(sessionId);
44511
+ const request = [...this.#requests.values()].find(
44512
+ (candidate) => candidate.sessionId === sessionId && candidate.kind === "executing"
44513
+ );
44514
+ if (request?.kind !== "executing") {
44515
+ return null;
44516
+ }
44517
+ const requestEvents = eventArray(request.eventTail);
44518
+ const events = requestEvents.slice(-EXECUTING_PROMPT_EVENT_LIMIT);
44519
+ return {
44520
+ attemptId: request.attemptId,
44521
+ commandId: request.commandId,
44522
+ epoch: request.epoch,
44523
+ events,
44524
+ tailCursor: events.at(-1)?.eventId ?? "",
44525
+ truncated: events.length < requestEvents.length
44526
+ };
44527
+ };
44528
+ };
44529
+
43466
44530
  // src/run-daemon.ts
43467
44531
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
43468
44532
  function waitForRelayRetry(signal, timer) {
@@ -43530,16 +44594,17 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43530
44594
  stateDirectory
43531
44595
  });
43532
44596
  const sessionStore = new SqliteAcpSessionStore(
43533
- join18(stateDirectory, "sessions", `${createHash6("sha256").update(config2.channelId).digest("hex")}.sqlite`)
44597
+ join18(stateDirectory, "sessions", `${createHash7("sha256").update(config2.channelId).digest("hex")}.sqlite`)
43534
44598
  );
43535
44599
  const operations = new DaemonOperationState();
43536
44600
  const publisher = new DaemonSessionEventPublisher();
44601
+ const eventLogV2 = new DaemonSessionEventLogV2(publisher, sessionStore);
43537
44602
  const activeTurns = new DaemonTurnRegistry(operations);
43538
44603
  const recordSessionEvent = (sessionId, event) => {
43539
44604
  publisher.publish(sessionId, activeTurns.recordEvent(event));
43540
44605
  };
43541
44606
  const agentRuntime = new AgentRuntimeManager(
43542
- new DaemonAcpObserver(recordSessionEvent),
44607
+ new DaemonAcpObserver(recordSessionEvent, eventLogV2.record),
43543
44608
  sessionStore,
43544
44609
  {
43545
44610
  read: async (options2, nativeSessionId, nativeTurn) => options2.agent.id === "codex" ? (await readCodexFullHistory(
@@ -43577,7 +44642,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43577
44642
  options2.signal
43578
44643
  );
43579
44644
  return cwd === options2.cwd && additionalDirectories.length === options2.additionalDirectories.length && additionalDirectories.every(
43580
- (directory, index) => directory === options2.additionalDirectories[index]
44645
+ (directory, index2) => directory === options2.additionalDirectories[index2]
43581
44646
  );
43582
44647
  });
43583
44648
  }
@@ -43663,6 +44728,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43663
44728
  nativeSessions,
43664
44729
  operations,
43665
44730
  publisher,
44731
+ eventLogV2,
43666
44732
  activeTurns,
43667
44733
  connectionEpoch,
43668
44734
  diagnostics,