@abelxiaoxing/cadence 2.0.29 → 2.0.31

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.
@@ -4063,7 +4063,7 @@ function decodeCadenceConversation(v) {
4063
4063
  ...degraded ? ["notice"] : []
4064
4064
  ]);
4065
4065
  return {
4066
- id: decodeId(o.id),
4066
+ id: decodeSessionId(o.id),
4067
4067
  revision: integer(o.revision, 0),
4068
4068
  enabled: bool(o.enabled),
4069
4069
  head: nullable(o.head, decodeId),
@@ -4072,9 +4072,72 @@ function decodeCadenceConversation(v) {
4072
4072
  ...degraded ? { notice: text(o.notice, 1024, true) } : {}
4073
4073
  };
4074
4074
  }
4075
+ function decodeSessionId(v) {
4076
+ const s = text(v, 128, true);
4077
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(s))
4078
+ throw new ContractError("invalid");
4079
+ return s;
4080
+ }
4081
+ function decodeEntryId(v) {
4082
+ const s = text(v, 64, true);
4083
+ if (!/^[A-Za-z0-9_-]+$/.test(s))
4084
+ throw new ContractError("invalid");
4085
+ return s;
4086
+ }
4087
+ var TREE_NODES = 1000;
4088
+ var STEP_TEXT_BYTES = 16 * 1024;
4089
+ var TARGET_BYTES = 1024;
4090
+ var STEP_READ = 24;
4091
+ function clipText(value, bytes) {
4092
+ const size = (s) => new TextEncoder().encode(JSON.stringify(s)).length;
4093
+ if (size(value) <= bytes)
4094
+ return value;
4095
+ let low = 0, high = Math.min(value.length, bytes);
4096
+ while (low < high) {
4097
+ const mid = Math.ceil((low + high) / 2);
4098
+ if (size(value.slice(0, mid)) <= bytes)
4099
+ low = mid;
4100
+ else
4101
+ high = mid - 1;
4102
+ }
4103
+ return /[\uD800-\uDBFF]/u.test(value.slice(low - 1, low)) ? value.slice(0, low - 1) : value.slice(0, low);
4104
+ }
4105
+ function toolTarget(args) {
4106
+ let value;
4107
+ try {
4108
+ value = JSON.parse(args);
4109
+ } catch {
4110
+ return "";
4111
+ }
4112
+ if (!value || typeof value !== "object" || Array.isArray(value))
4113
+ return "";
4114
+ const field = (name) => {
4115
+ const v = Object.hasOwn(value, name) ? value[name] : undefined;
4116
+ return typeof v === "string" ? v.trim() : "";
4117
+ };
4118
+ const command = field("command");
4119
+ if (command)
4120
+ return command.split(`
4121
+ `, 1)[0];
4122
+ return [field("pattern"), field("path")].filter(Boolean).join(" ");
4123
+ }
4124
+ function chatStep(item, parts, more = false) {
4125
+ const tool = item.role === "tool";
4126
+ const text2 = tool ? "" : clipText(item.text, STEP_TEXT_BYTES);
4127
+ return {
4128
+ id: item.id,
4129
+ role: item.role,
4130
+ text: text2,
4131
+ clipped: !tool && (more || text2 !== item.text),
4132
+ name: item.name,
4133
+ target: tool ? clipText(toolTarget(item.args), TARGET_BYTES) : "",
4134
+ error: item.error,
4135
+ parts
4136
+ };
4137
+ }
4075
4138
  function decodeChatCursor(value) {
4076
4139
  const o = closed(value, ["id", "updatedAt"]);
4077
- return { id: decodeId(o.id), updatedAt: integer(o.updatedAt, 0) };
4140
+ return { id: decodeSessionId(o.id), updatedAt: integer(o.updatedAt, 0) };
4078
4141
  }
4079
4142
  var statuses = [
4080
4143
  "queued",
@@ -4088,18 +4151,38 @@ var statuses = [
4088
4151
  function decodeWorkbenchRead(v) {
4089
4152
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
4090
4153
  switch (kind) {
4091
- case "conversation-transcript": {
4092
- const o = closed(v, ["kind", "id", "turnId", "page"]);
4154
+ case "conversation-turn": {
4155
+ const o = closed(v, ["kind", "id", "leaf", "ordinal", "before"]);
4093
4156
  return {
4094
4157
  kind,
4095
- id: decodeId(o.id),
4096
- turnId: decodeId(o.turnId),
4097
- page: integer(o.page, 0)
4158
+ id: decodeSessionId(o.id),
4159
+ leaf: nullable(o.leaf, decodeEntryId),
4160
+ ordinal: integer(o.ordinal, 0),
4161
+ before: nullable(o.before, (b) => integer(b, 0))
4162
+ };
4163
+ }
4164
+ case "conversation-step": {
4165
+ const o = closed(v, ["kind", "id", "leaf", "turnId", "step", "part"]);
4166
+ return {
4167
+ kind,
4168
+ id: decodeSessionId(o.id),
4169
+ leaf: nullable(o.leaf, decodeEntryId),
4170
+ turnId: decodeEntryId(o.turnId),
4171
+ step: integer(o.step, 0),
4172
+ part: integer(o.part, 0)
4098
4173
  };
4099
4174
  }
4100
4175
  case "cadence-conversation": {
4101
4176
  const o = closed(v, ["kind", "id"]);
4102
- return { kind, id: decodeId(o.id) };
4177
+ return { kind, id: decodeSessionId(o.id) };
4178
+ }
4179
+ case "conversation-tree": {
4180
+ const o = closed(v, ["kind", "id", "leaf"]);
4181
+ return {
4182
+ kind,
4183
+ id: decodeSessionId(o.id),
4184
+ leaf: nullable(o.leaf, decodeEntryId)
4185
+ };
4103
4186
  }
4104
4187
  case "workflow-history": {
4105
4188
  const continued = Object.hasOwn(v, "scan");
@@ -4123,19 +4206,15 @@ function decodeWorkbenchRead(v) {
4123
4206
  return { kind, id: decodeId(o.id) };
4124
4207
  }
4125
4208
  case "conversations": {
4126
- const after = Object.hasOwn(v, "after"), scan = Object.hasOwn(v, "scan");
4127
- const o = closed(v, [
4128
- "kind",
4129
- ...after ? ["after"] : [],
4130
- ...scan ? ["scan"] : []
4131
- ]);
4209
+ const after = Object.hasOwn(v, "after");
4210
+ const o = closed(v, ["kind", ...after ? ["after"] : []]);
4132
4211
  return {
4133
4212
  kind,
4134
- ...after ? { after: nullable(o.after, decodeChatCursor) } : {},
4135
- ...scan ? { scan: decodeId(o.scan) } : {}
4213
+ ...after ? { after: nullable(o.after, decodeChatCursor) } : {}
4136
4214
  };
4137
4215
  }
4138
4216
  case "conversation-active":
4217
+ case "conversation-legacy":
4139
4218
  case "projects":
4140
4219
  closed(v, ["kind"]);
4141
4220
  return { kind };
@@ -4144,8 +4223,13 @@ function decodeWorkbenchRead(v) {
4144
4223
  return { kind, taskId: decodeId(o.taskId) };
4145
4224
  }
4146
4225
  case "conversation": {
4147
- const o = closed(v, ["kind", "id", "before"]);
4148
- return { kind, id: decodeId(o.id), before: nullable(o.before, decodeId) };
4226
+ const o = closed(v, ["kind", "id", "leaf", "known"]);
4227
+ return {
4228
+ kind,
4229
+ id: decodeSessionId(o.id),
4230
+ leaf: nullable(o.leaf, decodeEntryId),
4231
+ known: nullable(o.known, decodeEntryId)
4232
+ };
4149
4233
  }
4150
4234
  default: {
4151
4235
  const o = closed(v, ["kind", "path"]);
@@ -4174,8 +4258,8 @@ function decodeWorkbenchCommand(v) {
4174
4258
  return {
4175
4259
  kind,
4176
4260
  commandId: decodeId(o2.commandId),
4177
- conversationId: decodeId(o2.conversationId),
4178
- head: nullable(o2.head, decodeId),
4261
+ conversationId: decodeSessionId(o2.conversationId),
4262
+ head: nullable(o2.head, decodeEntryId),
4179
4263
  revision: integer(o2.revision, 0)
4180
4264
  };
4181
4265
  }
@@ -4193,8 +4277,8 @@ function decodeWorkbenchCommand(v) {
4193
4277
  return {
4194
4278
  kind,
4195
4279
  commandId: decodeId(o2.commandId),
4196
- conversationId: decodeId(o2.conversationId),
4197
- head: nullable(o2.head, decodeId),
4280
+ conversationId: decodeSessionId(o2.conversationId),
4281
+ head: nullable(o2.head, decodeEntryId),
4198
4282
  text: text(o2.text, 16384, true),
4199
4283
  model: decodeChoiceVersion(o2.model),
4200
4284
  revision: integer(o2.revision, 0),
@@ -4213,7 +4297,7 @@ function decodeWorkbenchCommand(v) {
4213
4297
  const o2 = closed(v, kind === "cadence-approve" ? [...keys2, "grant"] : keys2);
4214
4298
  const base = {
4215
4299
  commandId: decodeId(o2.commandId),
4216
- conversationId: decodeId(o2.conversationId),
4300
+ conversationId: decodeSessionId(o2.conversationId),
4217
4301
  revision: integer(o2.revision, 0),
4218
4302
  proposalId: decodeId(o2.proposalId),
4219
4303
  digest: decodeHash(o2.digest)
@@ -4241,8 +4325,8 @@ function decodeWorkbenchCommand(v) {
4241
4325
  return {
4242
4326
  kind,
4243
4327
  commandId: decodeId(o2.commandId),
4244
- conversationId: decodeId(o2.conversationId),
4245
- head: nullable(o2.head, decodeId),
4328
+ conversationId: decodeSessionId(o2.conversationId),
4329
+ head: nullable(o2.head, decodeEntryId),
4246
4330
  text: text(o2.text, 16 * 1024, true),
4247
4331
  model: decodeChoiceVersion(o2.model)
4248
4332
  };
@@ -4258,11 +4342,15 @@ function decodeWorkbenchCommand(v) {
4258
4342
  return {
4259
4343
  kind,
4260
4344
  commandId: decodeId(o2.commandId),
4261
- conversationId: decodeId(o2.conversationId),
4345
+ conversationId: decodeSessionId(o2.conversationId),
4262
4346
  turnId: decodeId(o2.turnId),
4263
4347
  epoch: decodeId(o2.epoch)
4264
4348
  };
4265
4349
  }
4350
+ if (kind === "conversation-migrate") {
4351
+ const o2 = closed(v, ["kind", "commandId"]);
4352
+ return { kind, commandId: decodeId(o2.commandId) };
4353
+ }
4266
4354
  const o = closed(v, ["kind", "commandId", "path", "epoch"]);
4267
4355
  return {
4268
4356
  kind: oneOf(o.kind, ["open-project"]),
@@ -4293,48 +4381,125 @@ function decodeChatTurn(v) {
4293
4381
  media: omitted ? bool(omitted.media) : false,
4294
4382
  other: omitted ? bool(omitted.other) : false
4295
4383
  },
4296
- items: list(o.items, 256, (v2) => {
4297
- const i = closed(v2, ["id", "role", "text", "name", "args", "error"]);
4298
- return {
4299
- id: text(i.id, 160, true),
4300
- role: oneOf(i.role, ["user", "assistant", "tool"]),
4301
- text: text(i.text, 256 * 1024),
4302
- name: text(i.name, 128),
4303
- args: text(i.args, 64 * 1024),
4304
- error: bool(i.error)
4305
- };
4306
- })
4384
+ items: list(o.items, 256, decodeChatItem)
4385
+ };
4386
+ }
4387
+ function decodeChatItem(v) {
4388
+ const i = closed(v, ["id", "role", "text", "name", "args", "error"]);
4389
+ return {
4390
+ id: text(i.id, 160, true),
4391
+ role: oneOf(i.role, ["user", "assistant", "tool"]),
4392
+ text: text(i.text, 256 * 1024),
4393
+ name: text(i.name, 128),
4394
+ args: text(i.args, 64 * 1024),
4395
+ error: bool(i.error)
4396
+ };
4397
+ }
4398
+ function decodeChatStep(v) {
4399
+ const o = closed(v, [
4400
+ "id",
4401
+ "role",
4402
+ "text",
4403
+ "clipped",
4404
+ "name",
4405
+ "target",
4406
+ "error",
4407
+ "parts"
4408
+ ]);
4409
+ const step = {
4410
+ id: text(o.id, 160, true),
4411
+ role: oneOf(o.role, ["user", "assistant", "tool"]),
4412
+ text: text(o.text, STEP_TEXT_BYTES),
4413
+ clipped: bool(o.clipped),
4414
+ name: text(o.name, 128),
4415
+ target: text(o.target, TARGET_BYTES),
4416
+ error: bool(o.error),
4417
+ parts: integer(o.parts, 0)
4418
+ };
4419
+ if (step.role === "tool" && (step.text || step.clipped))
4420
+ throw new ContractError("invalid");
4421
+ return step;
4422
+ }
4423
+ function decodeChatTurnHeader(v) {
4424
+ const o = closed(v, [
4425
+ "id",
4426
+ "status",
4427
+ "notice",
4428
+ "omitted",
4429
+ "steps",
4430
+ "stable",
4431
+ "entry",
4432
+ "at"
4433
+ ]);
4434
+ const omitted = closed(o.omitted, ["thinking", "media", "other"]);
4435
+ const steps = integer(o.steps, 0);
4436
+ return {
4437
+ id: decodeEntryId(o.id),
4438
+ entry: nullable(o.entry, decodeEntryId),
4439
+ at: integer(o.at, 0),
4440
+ status: oneOf(o.status, statuses),
4441
+ notice: text(o.notice, 1024),
4442
+ omitted: {
4443
+ thinking: bool(omitted.thinking),
4444
+ media: bool(omitted.media),
4445
+ other: bool(omitted.other)
4446
+ },
4447
+ steps,
4448
+ stable: integer(o.stable, 0, steps)
4307
4449
  };
4308
4450
  }
4309
4451
  function decodeChatSummary(v) {
4310
- const modern = v !== null && typeof v === "object" && Object.hasOwn(v, "cadence");
4452
+ const has = (key) => v !== null && typeof v === "object" && Object.hasOwn(v, key);
4311
4453
  const o = closed(v, [
4312
4454
  "id",
4313
4455
  "title",
4314
- "head",
4456
+ "leaf",
4315
4457
  "status",
4316
4458
  "updatedAt",
4317
- ...modern ? ["cadence"] : []
4459
+ "origin",
4460
+ ...has("cadence") ? ["cadence"] : [],
4461
+ ...has("live") ? ["live"] : []
4318
4462
  ]);
4463
+ const live = has("live") ? closed(o.live, ["commandId", "epoch"]) : null;
4319
4464
  return {
4320
- id: decodeId(o.id),
4465
+ id: decodeSessionId(o.id),
4321
4466
  title: text(o.title, 512, true),
4322
- head: decodeId(o.head),
4467
+ leaf: nullable(o.leaf, decodeEntryId),
4323
4468
  status: oneOf(o.status, statuses),
4324
4469
  updatedAt: integer(o.updatedAt, 0),
4325
- ...modern ? { cadence: bool(o.cadence) } : {}
4470
+ origin: oneOf(o.origin, ["terminal", "webui"]),
4471
+ ...has("cadence") ? { cadence: bool(o.cadence) } : {},
4472
+ ...live ? {
4473
+ live: {
4474
+ commandId: decodeId(live.commandId),
4475
+ epoch: decodeId(live.epoch)
4476
+ }
4477
+ } : {}
4478
+ };
4479
+ }
4480
+ function decodeChatAttempt(v) {
4481
+ const o = closed(v, ["commandId", "text", "status", "notice"]);
4482
+ return {
4483
+ commandId: decodeId(o.commandId),
4484
+ text: text(o.text, 16 * 1024),
4485
+ status: oneOf(o.status, statuses),
4486
+ notice: text(o.notice, 1024)
4487
+ };
4488
+ }
4489
+ function decodeChatTreeNode(v) {
4490
+ const o = closed(v, ["id", "parent", "text", "at", "leaf", "current"]);
4491
+ return {
4492
+ id: decodeEntryId(o.id),
4493
+ parent: nullable(o.parent, decodeEntryId),
4494
+ text: text(o.text, 1024),
4495
+ at: integer(o.at, 0),
4496
+ leaf: decodeEntryId(o.leaf),
4497
+ current: bool(o.current)
4326
4498
  };
4327
4499
  }
4328
4500
  function decodeWorkbenchResult(v) {
4329
4501
  canonicalJson(v, 512 * 1024);
4330
4502
  const k = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
4331
- if (k === "conversation-transcript") {
4332
- const o2 = closed(v, ["kind", "conversationId", "page", "turn"]);
4333
- const turn = decodeChatTurn(o2.turn), page = integer(o2.page, 0);
4334
- if (!turn.transcript || page >= turn.transcript.pages)
4335
- throw new ContractError("invalid");
4336
- return { kind: k, conversationId: decodeId(o2.conversationId), page, turn };
4337
- }
4338
4503
  if (k === "workflow-transcript") {
4339
4504
  const o2 = closed(v, ["kind", "runId", "stepId", "turn"]);
4340
4505
  return {
@@ -4378,7 +4543,7 @@ function decodeWorkbenchResult(v) {
4378
4543
  const l = closed(value, ["runId", "conversationId"]);
4379
4544
  return {
4380
4545
  runId: decodeId(l.runId),
4381
- conversationId: decodeId(l.conversationId)
4546
+ conversationId: decodeSessionId(l.conversationId)
4382
4547
  };
4383
4548
  }) : [];
4384
4549
  if (new Set(links.map((l) => l.runId)).size !== links.length || links.some((l) => !runs.some((r) => r.id === l.runId)))
@@ -4417,15 +4582,7 @@ function decodeWorkbenchResult(v) {
4417
4582
  return {
4418
4583
  kind,
4419
4584
  taskId: decodeId(o2.taskId),
4420
- conversationId: nullable(o2.conversationId, decodeId)
4421
- };
4422
- }
4423
- if (kind === "conversations-progress") {
4424
- const o2 = closed(v, ["kind", "after", "scan"]);
4425
- return {
4426
- kind,
4427
- after: nullable(o2.after, decodeChatCursor),
4428
- scan: decodeId(o2.scan)
4585
+ conversationId: nullable(o2.conversationId, decodeSessionId)
4429
4586
  };
4430
4587
  }
4431
4588
  if (kind === "conversation-active") {
@@ -4433,21 +4590,101 @@ function decodeWorkbenchResult(v) {
4433
4590
  return { kind, entries: list(o2.entries, 8, decodeChatSummary) };
4434
4591
  }
4435
4592
  if (kind === "conversations") {
4436
- const paged = Object.hasOwn(v, "next");
4437
- const o2 = closed(v, ["kind", "entries", ...paged ? ["next"] : []]);
4593
+ const o2 = closed(v, ["kind", "entries", "next"]);
4438
4594
  return {
4439
4595
  kind,
4440
4596
  entries: list(o2.entries, 200, decodeChatSummary),
4441
- ...paged ? { next: nullable(o2.next, decodeChatCursor) } : {}
4597
+ next: nullable(o2.next, decodeChatCursor)
4442
4598
  };
4443
4599
  }
4444
4600
  if (kind === "conversation") {
4445
- const o2 = closed(v, ["kind", "summary", "turns", "before"]);
4601
+ const o2 = closed(v, [
4602
+ "kind",
4603
+ "summary",
4604
+ "leaf",
4605
+ "continues",
4606
+ "turns",
4607
+ "branches",
4608
+ "runs",
4609
+ "attempt"
4610
+ ]);
4611
+ const summary = nullable(o2.summary, decodeChatSummary), turns = integer(o2.turns, 0);
4612
+ if (!summary && turns)
4613
+ throw new ContractError("invalid");
4614
+ return {
4615
+ kind,
4616
+ summary,
4617
+ leaf: nullable(o2.leaf, decodeEntryId),
4618
+ continues: bool(o2.continues),
4619
+ turns,
4620
+ branches: integer(o2.branches, 0),
4621
+ runs: list(o2.runs, 200, decodeId),
4622
+ attempt: nullable(o2.attempt, decodeChatAttempt)
4623
+ };
4624
+ }
4625
+ if (kind === "conversation-tree") {
4626
+ const o2 = closed(v, ["kind", "conversationId", "nodes", "truncated"]);
4627
+ return {
4628
+ kind,
4629
+ conversationId: decodeSessionId(o2.conversationId),
4630
+ nodes: list(o2.nodes, TREE_NODES, decodeChatTreeNode),
4631
+ truncated: bool(o2.truncated)
4632
+ };
4633
+ }
4634
+ if (kind === "conversation-legacy") {
4635
+ const o2 = closed(v, ["kind", "pending"]);
4636
+ return { kind, pending: integer(o2.pending, 0) };
4637
+ }
4638
+ if (kind === "conversation-migrated") {
4639
+ const o2 = closed(v, ["kind", "commandId", "migrated", "skipped"]);
4640
+ return {
4641
+ kind,
4642
+ commandId: decodeId(o2.commandId),
4643
+ migrated: integer(o2.migrated, 0),
4644
+ skipped: integer(o2.skipped, 0)
4645
+ };
4646
+ }
4647
+ if (kind === "conversation-turn") {
4648
+ const o2 = closed(v, [
4649
+ "kind",
4650
+ "conversationId",
4651
+ "leaf",
4652
+ "ordinal",
4653
+ "turn",
4654
+ "start",
4655
+ "steps"
4656
+ ]);
4657
+ const turn = decodeChatTurnHeader(o2.turn), start = integer(o2.start, 0), steps = list(o2.steps, STEP_READ, decodeChatStep);
4658
+ if (start + steps.length > turn.steps)
4659
+ throw new ContractError("invalid");
4660
+ return {
4661
+ kind,
4662
+ conversationId: decodeSessionId(o2.conversationId),
4663
+ leaf: nullable(o2.leaf, decodeEntryId),
4664
+ ordinal: integer(o2.ordinal, 0),
4665
+ turn,
4666
+ start,
4667
+ steps
4668
+ };
4669
+ }
4670
+ if (kind === "conversation-step") {
4671
+ const o2 = closed(v, [
4672
+ "kind",
4673
+ "conversationId",
4674
+ "leaf",
4675
+ "turnId",
4676
+ "step",
4677
+ "part",
4678
+ "item"
4679
+ ]);
4446
4680
  return {
4447
4681
  kind,
4448
- summary: nullable(o2.summary, decodeChatSummary),
4449
- turns: list(o2.turns, 20, decodeChatTurn),
4450
- before: nullable(o2.before, decodeId)
4682
+ conversationId: decodeSessionId(o2.conversationId),
4683
+ leaf: nullable(o2.leaf, decodeEntryId),
4684
+ turnId: decodeEntryId(o2.turnId),
4685
+ step: integer(o2.step, 0),
4686
+ part: integer(o2.part, 0),
4687
+ item: decodeChatItem(o2.item)
4451
4688
  };
4452
4689
  }
4453
4690
  if (kind === "files" || kind === "directories") {
@@ -5080,7 +5317,7 @@ var CONFIG_BYTES = 64 * 1024;
5080
5317
  var TOKEN_BYTES = 1024;
5081
5318
  function accessToken(value) {
5082
5319
  const result = text(value, TOKEN_BYTES, true);
5083
- if (utf8Bytes(result) < 32 || /[\p{Cc}\p{Cf}]/u.test(result))
5320
+ if (/[\p{Cc}\p{Cf}]/u.test(result))
5084
5321
  throw new ContractError("invalid");
5085
5322
  return result;
5086
5323
  }
@@ -5156,7 +5393,7 @@ function decode(source) {
5156
5393
  try {
5157
5394
  return { port: number, token: accessToken(t.value) };
5158
5395
  } catch {
5159
- return unusable(`has ${TOKEN_KEY} on line ${t.line} shorter than 32 characters or with control characters`);
5396
+ return unusable(`has ${TOKEN_KEY} on line ${t.line} that is empty, over ${TOKEN_BYTES} bytes or with control characters`);
5160
5397
  }
5161
5398
  }
5162
5399
  var code = (error) => error?.code ?? "error";
@@ -6441,6 +6678,7 @@ class ServiceCoordination {
6441
6678
  "host-config.json",
6442
6679
  "history-v2",
6443
6680
  "conversations-v1",
6681
+ "conversation-commands-v1",
6444
6682
  "conversation-workflows-v1",
6445
6683
  "workflows-v1"
6446
6684
  ]);
@@ -8600,7 +8838,7 @@ function managementExitCode(result, foreground = false) {
8600
8838
  }
8601
8839
  function serverConfigHint(error) {
8602
8840
  return `Cadence changed nothing: ${error.path} ${error.reason}.
8603
- Fix it and run the command again; the file holds the WebUI port and token as ${PORT_KEY}=<1-65535> and ${TOKEN_KEY}=<at least 32 characters>, one line each.
8841
+ Fix it and run the command again; the file holds the WebUI port and token as ${PORT_KEY}=<1-65535> and ${TOKEN_KEY}=<a non-empty token>, one line each.
8604
8842
  `;
8605
8843
  }
8606
8844
  function registryGuidance(_workspace, stateHome) {
@@ -8852,6 +9090,7 @@ import { createHash as createHash6, randomUUID as randomUUID8 } from "node:crypt
8852
9090
  import {
8853
9091
  createServer
8854
9092
  } from "node:http";
9093
+ import { gzipSync, constants as zlib } from "node:zlib";
8855
9094
  import { WebSocketServer } from "ws";
8856
9095
 
8857
9096
  // src/service/workbench-send-refusal.ts
@@ -8872,12 +9111,24 @@ function fixedHeaders(response) {
8872
9111
  response.setHeader("X-Frame-Options", "DENY");
8873
9112
  response.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self'; style-src-elem 'self'; style-src-attr 'unsafe-inline'; font-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
8874
9113
  }
8875
- function send(response, status, value) {
9114
+ function send(response, status, value, gzip = false) {
8876
9115
  if (response.destroyed || response.writableEnded)
8877
9116
  return;
8878
9117
  response.statusCode = status;
8879
9118
  response.setHeader("Content-Type", "application/json; charset=utf-8");
8880
- response.end(canonicalJson(value, LIMITS.controlBytes));
9119
+ const body = canonicalJson(value, LIMITS.controlBytes);
9120
+ if (gzip && body.length >= 1024) {
9121
+ response.setHeader("Content-Encoding", "gzip");
9122
+ response.end(gzipSync(body, { level: zlib.Z_BEST_SPEED }));
9123
+ } else
9124
+ response.end(body);
9125
+ }
9126
+ function acceptsGzip(header) {
9127
+ return (header ?? "").split(",").some((entry) => {
9128
+ const [name, ...params] = entry.split(";").map((p) => p.trim());
9129
+ const q = params.find((p) => p.toLowerCase().startsWith("q="));
9130
+ return name.toLowerCase() === "gzip" && (!q || Number(q.slice(2)) > 0);
9131
+ });
8881
9132
  }
8882
9133
  function unavailable() {
8883
9134
  throw new ContractError("unavailable");
@@ -9263,7 +9514,10 @@ Content-Length: 0\r
9263
9514
  this.attachment(caller);
9264
9515
  const decoded2 = decodeHttpOutput(route.operation, value);
9265
9516
  const status = value && typeof value === "object" && "kind" in value && value.kind === "error" && "error" in value ? errorStatus(decodePublicError(value.error).code) : 200;
9266
- send(res, status, decoded2);
9517
+ const compressible = route.operation === "workbenchRead";
9518
+ if (compressible)
9519
+ res.setHeader("Vary", "Accept-Encoding");
9520
+ send(res, status, decoded2, compressible && acceptsGzip(boundary.headers.get("accept-encoding")));
9267
9521
  } catch (e) {
9268
9522
  if (createdAttachment)
9269
9523
  this.detach(createdAttachment);
@@ -10333,7 +10587,7 @@ async function createGateway(value, hostUrl, source) {
10333
10587
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
10334
10588
  const web = loadWebAssets(source?.webDirectory);
10335
10589
  const build2 = {
10336
- contractHash: "70b7d387e5677a43ff0a80f82aad39684362496916c796150a4e326cd7756b65",
10590
+ contractHash: "3305384b10bb0c658565426ec2291d0237533cb9ae7aeb1d63f42ac8824b0c82",
10337
10591
  assets: {
10338
10592
  sourceHash: web.manifest.sourceHash,
10339
10593
  contractHash: web.manifest.contractHash,
@@ -10801,6 +11055,7 @@ Content-Length: 0\r
10801
11055
  Origin: b.endpoint
10802
11056
  };
10803
11057
  for (const key of [
11058
+ "accept-encoding",
10804
11059
  "content-type",
10805
11060
  "content-length",
10806
11061
  "x-cadence-build",
@@ -10834,7 +11089,9 @@ Content-Length: 0\r
10834
11089
  res.statusCode = incoming.statusCode ?? 502;
10835
11090
  for (const key of [
10836
11091
  "content-type",
11092
+ "content-encoding",
10837
11093
  "content-disposition",
11094
+ "vary",
10838
11095
  "x-cadence-attachment"
10839
11096
  ]) {
10840
11097
  const value2 = incoming.headers[key];
@@ -11013,8 +11270,8 @@ Content-Length: 0\r
11013
11270
 
11014
11271
  // src/service/host.ts
11015
11272
  import { spawn as spawn5 } from "node:child_process";
11016
- import { lstatSync as lstatSync22, opendirSync as opendirSync15 } from "node:fs";
11017
- import { join as join34 } from "node:path";
11273
+ import { lstatSync as lstatSync23, opendirSync as opendirSync15 } from "node:fs";
11274
+ import { join as join37 } from "node:path";
11018
11275
  import { fileURLToPath as fileURLToPath7 } from "node:url";
11019
11276
 
11020
11277
  // src/agent-registry.ts
@@ -21714,95 +21971,6 @@ import { spawn as spawn3 } from "node:child_process";
21714
21971
  import { join as join26 } from "node:path";
21715
21972
  import { StringDecoder } from "node:string_decoder";
21716
21973
  import { fileURLToPath as fileURLToPath5 } from "node:url";
21717
-
21718
- // src/conversation-context.mjs
21719
- var CONTEXT_BYTES = 2 * 1024 * 1024;
21720
- var CONTEXT_RECORD_BYTES = LIMITS.detailBytes;
21721
- var clean = (s, secrets, max = CONTEXT_RECORD_BYTES) => sanitizeText(text(s, max), secrets);
21722
- function argumentsData(value, secrets) {
21723
- const sanitizer = new DetailSanitizer("canonical-json", secrets);
21724
- const source = sanitizer.write(canonicalJson(value, CONTEXT_RECORD_BYTES)) + sanitizer.end();
21725
- if (sanitizer.limited)
21726
- throw new Error("Unsupported context arguments");
21727
- return parseWireJson(source, CONTEXT_RECORD_BYTES);
21728
- }
21729
- function own2(value, key2) {
21730
- const d = value && typeof value === "object" ? Object.getOwnPropertyDescriptor(value, key2) : undefined;
21731
- if (!d || !("value" in d))
21732
- throw new Error("Invalid usage");
21733
- return d.value;
21734
- }
21735
- function counts(value, keys2) {
21736
- const out = Object.create(null);
21737
- for (const key2 of keys2) {
21738
- const n = own2(value, key2);
21739
- if (typeof n !== "number" || !Number.isFinite(n) || n < 0)
21740
- throw new Error("Invalid usage");
21741
- out[key2] = n;
21742
- }
21743
- return out;
21744
- }
21745
- function conversationMessages(messages, secrets = []) {
21746
- return list(messages, 4096, (message) => {
21747
- if (!message || typeof message !== "object")
21748
- throw new Error("Invalid context");
21749
- const role2 = oneOf(message.role, ["user", "assistant", "toolResult"]);
21750
- const timestamp2 = integer(message.timestamp, 0);
21751
- const content = typeof message.content === "string" ? [{ type: "text", text: clean(message.content, secrets) }] : list(message.content, 256, (block) => {
21752
- if (block.type === "text")
21753
- return { type: "text", text: clean(block.text, secrets) };
21754
- if (role2 === "assistant" && block.type === "toolCall")
21755
- return {
21756
- type: "toolCall",
21757
- id: clean(block.id, secrets, 512),
21758
- name: clean(block.name, secrets, 128),
21759
- arguments: argumentsData(block.arguments, secrets)
21760
- };
21761
- return null;
21762
- }).filter(Boolean);
21763
- if (role2 === "user")
21764
- return { role: role2, timestamp: timestamp2, content };
21765
- if (role2 === "toolResult")
21766
- return {
21767
- role: role2,
21768
- timestamp: timestamp2,
21769
- content,
21770
- toolCallId: clean(message.toolCallId, secrets, 512),
21771
- toolName: clean(message.toolName, secrets, 128),
21772
- isError: message.isError === true
21773
- };
21774
- const usage = counts(message.usage, [
21775
- "input",
21776
- "output",
21777
- "cacheRead",
21778
- "cacheWrite",
21779
- "totalTokens"
21780
- ]);
21781
- usage.cost = counts(own2(message.usage, "cost"), [
21782
- "input",
21783
- "output",
21784
- "cacheRead",
21785
- "cacheWrite",
21786
- "total"
21787
- ]);
21788
- return {
21789
- role: role2,
21790
- timestamp: timestamp2,
21791
- content,
21792
- api: clean(message.api, secrets, 128),
21793
- provider: clean(message.provider, secrets, 128),
21794
- model: clean(message.model, secrets, 256),
21795
- usage,
21796
- stopReason: oneOf(message.stopReason, [
21797
- "stop",
21798
- "length",
21799
- "toolUse",
21800
- "error",
21801
- "aborted"
21802
- ])
21803
- };
21804
- });
21805
- }
21806
21974
  // src/worker-capture.mjs
21807
21975
  import { createHash as createHash23, randomUUID as randomUUID16 } from "node:crypto";
21808
21976
  var completeCoverage = () => ({
@@ -22434,13 +22602,9 @@ function runProcess(spec) {
22434
22602
  spec.input === undefined ? "ignore" : "pipe",
22435
22603
  "pipe",
22436
22604
  "pipe",
22437
- ...spec.onContext || spec.onCoordinator ? [spec.onContext ? "pipe" : "ignore"] : [],
22438
- ...spec.onCoordinator ? ["ipc"] : []
22605
+ ...spec.onCoordinator ? ["ignore", "ipc"] : []
22439
22606
  ]
22440
22607
  });
22441
- const contextStream = spec.onContext ? child.stdio[3] : null;
22442
- let contextEnded = false, contextBytes = 0;
22443
- const contextChunks = [];
22444
22608
  let settled = false;
22445
22609
  let nativeClosed = false;
22446
22610
  let launched = false;
@@ -22476,7 +22640,7 @@ function runProcess(spec) {
22476
22640
  const stderrDecoder = new StringDecoder("utf8");
22477
22641
  let killTimer;
22478
22642
  let unknownTimer;
22479
- const clean2 = (text2, max = 65536) => diagnosticText(text2, max, spec.secrets);
22643
+ const clean = (text2, max = 65536) => diagnosticText(text2, max, spec.secrets);
22480
22644
  const finish = (closed2, exitCode, signal) => {
22481
22645
  if (settled)
22482
22646
  return;
@@ -22519,8 +22683,8 @@ function runProcess(spec) {
22519
22683
  exitCode,
22520
22684
  signal,
22521
22685
  durationMs: Date.now() - started,
22522
- text: clean2(outcome === "completed" && spec.protocol ? final ?? "" : `${outcome === "timeout" ? `timeout: total process deadline ${spec.timeoutMs}ms reached (activity does not extend it)` : outcome}${closed2 ? "; direct child closed; descendant closure was not verified (not evidence of a surviving process)" : "; stop unconfirmed; coordination lock retained"}`, 16384),
22523
- output: clean2(output),
22686
+ text: clean(outcome === "completed" && spec.protocol ? final ?? "" : `${outcome === "timeout" ? `timeout: total process deadline ${spec.timeoutMs}ms reached (activity does not extend it)` : outcome}${closed2 ? "; direct child closed; descendant closure was not verified (not evidence of a surviving process)" : "; stop unconfirmed; coordination lock retained"}`, 16384),
22687
+ output: clean(output),
22524
22688
  truncated
22525
22689
  });
22526
22690
  if (!closed2) {
@@ -22528,7 +22692,6 @@ function runProcess(spec) {
22528
22692
  child.stdout.destroy();
22529
22693
  child.stderr.destroy();
22530
22694
  child.stdin?.destroy();
22531
- contextStream?.destroy();
22532
22695
  if (child.connected)
22533
22696
  child.disconnect();
22534
22697
  }
@@ -22629,7 +22792,7 @@ function runProcess(spec) {
22629
22792
  spec.onProgress?.("Agent ready");
22630
22793
  }
22631
22794
  if (decoded2.event.kind === "tool-start")
22632
- spec.onProgress?.(clean2(`Tool: ${decoded2.event.name}`, 128));
22795
+ spec.onProgress?.(clean(`Tool: ${decoded2.event.name}`, 128));
22633
22796
  if (decoded2.event.kind === "final")
22634
22797
  final = capture.preview;
22635
22798
  if (lease) {
@@ -22669,7 +22832,7 @@ function runProcess(spec) {
22669
22832
  if (Buffer.byteLength(output) > 256 * 1024) {
22670
22833
  truncated = true;
22671
22834
  if (spec.uninterruptible)
22672
- output = clean2(output, 256 * 1024);
22835
+ output = clean(output, 256 * 1024);
22673
22836
  else
22674
22837
  stop("failed");
22675
22838
  }
@@ -22701,34 +22864,6 @@ function runProcess(spec) {
22701
22864
  }
22702
22865
  }
22703
22866
  };
22704
- contextStream?.on("data", (chunk) => {
22705
- if (settled || stopping)
22706
- return;
22707
- try {
22708
- let offset = 0;
22709
- while (offset < chunk.length) {
22710
- const end = chunk.indexOf(10, offset);
22711
- const part = chunk.subarray(offset, end < 0 ? chunk.length : end);
22712
- contextBytes += part.length;
22713
- if (contextBytes > CONTEXT_RECORD_BYTES)
22714
- throw new Error("Checkpoint record too large");
22715
- contextChunks.push(part);
22716
- if (end < 0)
22717
- break;
22718
- const source = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(contextChunks, contextBytes));
22719
- contextChunks.length = 0;
22720
- contextBytes = 0;
22721
- spec.onContext?.(source);
22722
- offset = end + 1;
22723
- }
22724
- } catch {
22725
- stop("failed");
22726
- }
22727
- });
22728
- contextStream?.once("end", () => {
22729
- contextEnded = true;
22730
- });
22731
- contextStream?.on("error", () => stop("failed"));
22732
22867
  let stdoutWork = Promise.resolve();
22733
22868
  let stderrWork = Promise.resolve();
22734
22869
  let stdoutEnded = false, stderrEnded = false;
@@ -22781,15 +22916,6 @@ function runProcess(spec) {
22781
22916
  clearTimeout(killTimer);
22782
22917
  clearTimeout(unknownTimer);
22783
22918
  const close = () => {
22784
- if (spec.onContext && !stopping && code2 === 0) {
22785
- try {
22786
- if (!contextEnded || contextBytes)
22787
- throw new Error("Context EOF missing");
22788
- spec.onContextEnd?.();
22789
- } catch {
22790
- stopping = "failed";
22791
- }
22792
- }
22793
22919
  if (!spec.protocol)
22794
22920
  output += stdoutDecoder.end();
22795
22921
  else {
@@ -22888,34 +23014,11 @@ function launchConversation(prepared, conversation, signal, options) {
22888
23014
  if (!encoded2 || encoded2.input !== input)
22889
23015
  throw new Error("Invalid chat launch");
22890
23016
  const secrets = encoded2.secrets;
22891
- let contextCount = 0, contextComplete = false;
22892
23017
  return launchEncoded(encoded2, signal, options.timeoutMs, {
22893
23018
  maySignal: options.maySignal,
22894
23019
  onNative: options.onNative,
22895
23020
  onCoordinator: options.onCoordinator,
22896
- onFrame: (frame) => options.onFrame(frame, secrets),
22897
- onContext: (source) => {
22898
- if (contextComplete)
22899
- throw new Error("Checkpoint after end");
22900
- const value = parseWireJson(source, CONTEXT_RECORD_BYTES);
22901
- if (value.schema === "cadence-conversation-stream-end/1") {
22902
- const record3 = closed(value, ["schema", "count"]);
22903
- if (record3.count !== contextCount)
22904
- throw new Error("Invalid checkpoint count");
22905
- contextComplete = true;
22906
- return;
22907
- }
22908
- const record2 = closed(value, ["schema", "message"]);
22909
- if (record2.schema !== "cadence-conversation-stream/1")
22910
- throw new Error("Invalid checkpoint");
22911
- options.onContext(conversationMessages([record2.message], [...options.ownerSecrets(), ...secrets])[0]);
22912
- contextCount++;
22913
- },
22914
- onContextEnd: () => {
22915
- if (!contextComplete)
22916
- throw new Error("Incomplete checkpoint");
22917
- options.onContextEnd();
22918
- }
23021
+ onFrame: (frame) => options.onFrame(frame, secrets)
22919
23022
  });
22920
23023
  });
22921
23024
  }
@@ -24708,270 +24811,999 @@ class ServiceOwner {
24708
24811
 
24709
24812
  // src/service/workbench.ts
24710
24813
  import { opendirSync as opendirSync14 } from "node:fs";
24711
- import { join as join33 } from "node:path";
24712
-
24713
- // src/service/conversation-workflow.ts
24714
- import { randomUUID as randomUUID21 } from "node:crypto";
24715
- import { opendirSync as opendirSync11 } from "node:fs";
24716
- import { dirname as dirname20, join as join29 } from "node:path";
24814
+ import { join as join36 } from "node:path";
24717
24815
 
24718
- // src/cadence-instructions.ts
24719
- var CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits by typing 退出 Cadence or exit cadence. Only the user can exit; leaving never cancels accepted work. When asked how to leave, say exactly this.
24720
- You are the sole user-facing coordinator. Continue normal conversation, not a task-manager UI. Do not ask the user to manage tasks, IDs, JSON, service ports, Save/Start/check menus or agent assignments.
24721
- For each new goal: inspect relevant project evidence through cadence_research (up to two independent readonly subagents); read existing AGENTS/docs/.cadence/project.md before proposing conventions. Reuse still-current findings; do not rescan the entire repository or spawn agents merely to fill slots. Aggregate questions yourself. Investigate discoverable facts and ask focused, frequent questions only for unresolved product/technical decisions. Preserve confirmed decisions across turns. Diagnosis/research alone never imply implementation.
24722
- Once material decisions and acceptance criteria are aligned, use cadence_plan with a readable design, explicit non-goals/decisions, exact file scopes, a finite dependency DAG, real verification commands, worktree prerequisites and a bounded repair budget. Independent writes may run concurrently; shared files need a single owner or dependency. Investigate local tool/dependency prerequisites BEFORE finalizing: isolated worktrees do not inherit ignored node_modules. Setup commands require inclusion in the final approval; never silently install/download/copy dependencies or credentials. local-merge needs an existing Git branch and commit identity; working-copy is explicit direct editing without Git mutation and is serialized.
24723
- Present the returned complete plan and invite a single clear execution approval (the user can type 按计划实施). cadence_start binds the exact displayed plan and obtains fresh user consent; never interpret a vague acknowledgement as approval. No further confirmations are needed for the approved bounded pipeline. No push, publication, deployment, recursive delegation or scope expansion. If a material decision changes, revise the plan and seek fresh approval.
24724
- During accepted work answer questions, report actual retained progress, and let the service execute. cadence_cancel is explicit cancellation, not navigation/exit. Never claim a worker's prose is a passing check or automatic review is human review. Failed/unknown/blocked outcomes are not success. A completed goal leaves Cadence ON and ready for the next goal; do not require /cadence again. Unrelated discussion is still ordinary conversation within this mode, not implicit permission to start another implementation. Tools operate on the host; this is not a sandbox.`;
24816
+ // src/service/conversation-migration.ts
24817
+ import { randomBytes as randomBytes6 } from "node:crypto";
24818
+ import {
24819
+ closeSync as closeSync10,
24820
+ fsyncSync as fsyncSync6,
24821
+ linkSync,
24822
+ mkdirSync as mkdirSync5,
24823
+ opendirSync as opendirSync9,
24824
+ openSync as openSync10,
24825
+ unlinkSync as unlinkSync4,
24826
+ writeSync
24827
+ } from "node:fs";
24828
+ import { join as join29 } from "node:path";
24725
24829
 
24726
- // src/service/conversations.ts
24727
- import { randomUUID as randomUUID20 } from "node:crypto";
24728
- import { lstatSync as lstatSync17, opendirSync as opendirSync10, realpathSync as realpathSync10, statfsSync as statfsSync2 } from "node:fs";
24830
+ // src/conversation-context.mjs
24831
+ import { createHash as createHash24 } from "node:crypto";
24832
+ import {
24833
+ closeSync as closeSync9,
24834
+ constants as constants8,
24835
+ fstatSync as fstatSync6,
24836
+ lstatSync as lstatSync16,
24837
+ openSync as openSync9,
24838
+ readSync as readSync5
24839
+ } from "node:fs";
24729
24840
  import { dirname as dirname19, join as join28 } from "node:path";
24841
+ var CONTEXT_BYTES = 2 * 1024 * 1024;
24842
+ var CONTEXT_RECORD_BYTES = LIMITS.detailBytes;
24843
+ var clean = (s, secrets, max = CONTEXT_RECORD_BYTES) => sanitizeText(text(s, max), secrets);
24844
+ function argumentsData(value, secrets) {
24845
+ const sanitizer = new DetailSanitizer("canonical-json", secrets);
24846
+ const source = sanitizer.write(canonicalJson(value, CONTEXT_RECORD_BYTES)) + sanitizer.end();
24847
+ if (sanitizer.limited)
24848
+ throw new Error("Unsupported context arguments");
24849
+ return parseWireJson(source, CONTEXT_RECORD_BYTES);
24850
+ }
24851
+ function own2(value, key2) {
24852
+ const d = value && typeof value === "object" ? Object.getOwnPropertyDescriptor(value, key2) : undefined;
24853
+ if (!d || !("value" in d))
24854
+ throw new Error("Invalid usage");
24855
+ return d.value;
24856
+ }
24857
+ function counts(value, keys3) {
24858
+ const out = Object.create(null);
24859
+ for (const key2 of keys3) {
24860
+ const n = own2(value, key2);
24861
+ if (typeof n !== "number" || !Number.isFinite(n) || n < 0)
24862
+ throw new Error("Invalid usage");
24863
+ out[key2] = n;
24864
+ }
24865
+ return out;
24866
+ }
24867
+ function conversationMessages(messages, secrets = []) {
24868
+ return list(messages, 4096, (message) => {
24869
+ if (!message || typeof message !== "object")
24870
+ throw new Error("Invalid context");
24871
+ const role2 = oneOf(message.role, ["user", "assistant", "toolResult"]);
24872
+ const timestamp2 = integer(message.timestamp, 0);
24873
+ const content = typeof message.content === "string" ? [{ type: "text", text: clean(message.content, secrets) }] : list(message.content, 256, (block) => {
24874
+ if (block.type === "text")
24875
+ return { type: "text", text: clean(block.text, secrets) };
24876
+ if (role2 === "assistant" && block.type === "toolCall")
24877
+ return {
24878
+ type: "toolCall",
24879
+ id: clean(block.id, secrets, 512),
24880
+ name: clean(block.name, secrets, 128),
24881
+ arguments: argumentsData(block.arguments, secrets)
24882
+ };
24883
+ return null;
24884
+ }).filter(Boolean);
24885
+ if (role2 === "user")
24886
+ return { role: role2, timestamp: timestamp2, content };
24887
+ if (role2 === "toolResult")
24888
+ return {
24889
+ role: role2,
24890
+ timestamp: timestamp2,
24891
+ content,
24892
+ toolCallId: clean(message.toolCallId, secrets, 512),
24893
+ toolName: clean(message.toolName, secrets, 128),
24894
+ isError: message.isError === true
24895
+ };
24896
+ const usage = counts(message.usage, [
24897
+ "input",
24898
+ "output",
24899
+ "cacheRead",
24900
+ "cacheWrite",
24901
+ "totalTokens"
24902
+ ]);
24903
+ usage.cost = counts(own2(message.usage, "cost"), [
24904
+ "input",
24905
+ "output",
24906
+ "cacheRead",
24907
+ "cacheWrite",
24908
+ "total"
24909
+ ]);
24910
+ return {
24911
+ role: role2,
24912
+ timestamp: timestamp2,
24913
+ content,
24914
+ api: clean(message.api, secrets, 128),
24915
+ provider: clean(message.provider, secrets, 128),
24916
+ model: clean(message.model, secrets, 256),
24917
+ usage,
24918
+ stopReason: oneOf(message.stopReason, [
24919
+ "stop",
24920
+ "length",
24921
+ "toolUse",
24922
+ "error",
24923
+ "aborted"
24924
+ ])
24925
+ };
24926
+ });
24927
+ }
24928
+ function readPrivateContext(path, maximum) {
24929
+ const fd = openSync9(path, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
24930
+ try {
24931
+ const st = fstatSync6(fd);
24932
+ if (!st.isFile() || st.nlink !== 1 || st.size > maximum || process.platform !== "win32" && (st.mode & 63 || st.uid !== process.getuid()))
24933
+ throw new Error("Invalid context file");
24934
+ const buffer = Buffer.alloc(st.size + 1);
24935
+ let size2 = 0;
24936
+ while (size2 < buffer.length) {
24937
+ const n = readSync5(fd, buffer, size2, buffer.length - size2, null);
24938
+ if (!n)
24939
+ break;
24940
+ size2 += n;
24941
+ }
24942
+ const after = fstatSync6(fd);
24943
+ if (size2 !== st.size || after.size !== st.size || after.mtimeMs !== st.mtimeMs || after.ctimeMs !== st.ctimeMs || lstatSync16(path).ino !== st.ino)
24944
+ throw new Error("Changed context file");
24945
+ return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, size2));
24946
+ } finally {
24947
+ closeSync9(fd);
24948
+ }
24949
+ }
24950
+ function* iterateConversationContext(path) {
24951
+ if (path === null)
24952
+ return;
24953
+ const source = readPrivateContext(path, CONTEXT_BYTES);
24954
+ const value = parseWireJson(source, CONTEXT_BYTES);
24955
+ if (value.schema === "cadence-conversation-context/1") {
24956
+ const o2 = closed(value, ["schema", "messages"]);
24957
+ yield* conversationMessages(o2.messages);
24958
+ return;
24959
+ }
24960
+ const o = closed(value, ["schema", "messages", "head"]);
24961
+ if (o.schema !== "cadence-conversation-context/2")
24962
+ throw new Error("Invalid context format");
24963
+ const count2 = integer(o.messages, 0);
24964
+ let head = null;
24965
+ for (let index = 0;index < count2; index++) {
24966
+ const body = readPrivateContext(join28(dirname19(path), `context-${index}.json`), CONTEXT_RECORD_BYTES);
24967
+ const record2 = closed(parseWireJson(body, CONTEXT_RECORD_BYTES), [
24968
+ "schema",
24969
+ "index",
24970
+ "previous",
24971
+ "message"
24972
+ ]);
24973
+ if (record2.schema !== "cadence-conversation-message/1" || record2.index !== index || record2.previous !== head)
24974
+ throw new Error("Invalid context chain");
24975
+ head = createHash24("sha256").update(body).digest("hex");
24976
+ yield conversationMessages([record2.message])[0];
24977
+ }
24978
+ if (o.head !== head)
24979
+ throw new Error("Changed context chain");
24980
+ }
24730
24981
 
24731
- // src/service/conversation-history.ts
24732
- import { randomUUID as randomUUID19 } from "node:crypto";
24733
- import { lstatSync as lstatSync16, opendirSync as opendirSync9 } from "node:fs";
24734
- var CONVERSATION_PAGE = 50;
24735
- var SCAN_ENTRIES = 8;
24736
- var SCANS = 16;
24737
- var IDLE_MS = 120000;
24738
- var compareChats = (a, b) => b.updatedAt - a.updatedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
24982
+ // src/session-entries.mjs
24983
+ var CADENCE_MODE_ENTRY = "cadence-conversation-mode/1";
24984
+ var WEBUI_SESSION_ENTRY = "cadence-webui/1";
24739
24985
 
24740
- class ConversationHistory {
24741
- path;
24742
- directory;
24743
- summary;
24744
- scans = new Map;
24745
- closed = false;
24746
- constructor(path, directory, summary2) {
24747
- this.path = path;
24748
- this.directory = directory;
24749
- this.summary = summary2;
24986
+ // src/service/conversation-migration.ts
24987
+ var META_BYTES = 64 * 1024;
24988
+
24989
+ class ConversationMigration {
24990
+ o;
24991
+ root;
24992
+ constructor(o) {
24993
+ this.o = o;
24994
+ this.root = join29(o.coordination.directory, "conversations-v1");
24750
24995
  }
24751
- incarnation() {
24752
- const st = lstatSync16(this.path, { bigint: true });
24753
- if (!st.isDirectory() || st.isSymbolicLink())
24754
- throw new ContractError("corrupt-selected");
24755
- return `${st.dev}:${st.ino}`;
24996
+ read(path) {
24997
+ const file = this.o.coordination.files.read(path, META_BYTES);
24998
+ return file ? parseWireJson(file.bytes.toString("utf8"), META_BYTES) : undefined;
24756
24999
  }
24757
- read(after, cursor) {
24758
- if (this.closed)
24759
- throw new ContractError("unavailable");
24760
- let state;
24761
- if (cursor) {
24762
- const selected2 = this.scans.get(cursor);
24763
- if (!selected2 || selected2.after?.id !== after?.id || selected2.after?.updatedAt !== after?.updatedAt)
24764
- throw new ContractError("stale");
24765
- this.scans.delete(cursor);
24766
- clearTimeout(selected2.timer);
24767
- state = selected2;
24768
- } else {
24769
- if (!this.directory())
24770
- return { kind: "conversations", entries: [], next: null };
24771
- if (this.scans.size >= SCANS)
24772
- throw new ContractError("capacity");
24773
- const incarnation3 = this.incarnation();
24774
- state = {
24775
- dir: opendirSync9(this.path),
24776
- incarnation: incarnation3,
24777
- after,
24778
- entries: []
24779
- };
25000
+ legacy() {
25001
+ const dir = join29(this.root, "sessions");
25002
+ if (!this.o.coordination.files.directory(dir))
25003
+ return [];
25004
+ const out = [];
25005
+ const handle = opendirSync9(dir);
25006
+ try {
25007
+ for (let e = handle.readSync();e; e = handle.readSync()) {
25008
+ try {
25009
+ if (!e.isFile() || !e.name.endsWith(".json"))
25010
+ continue;
25011
+ const id = decodeId(e.name.slice(0, -5));
25012
+ const identity = this.read(join29(this.root, "identities", `${id}.json`));
25013
+ if (!identity || typeof identity !== "object" || identity.schema !== "cadence-conversation/1" || identity.id !== id || identity.cwd !== this.o.cwd)
25014
+ continue;
25015
+ const meta = this.read(join29(dir, e.name));
25016
+ const checkpoint = meta && typeof meta === "object" ? meta.checkpoint : null;
25017
+ if (typeof checkpoint === "string")
25018
+ out.push({ id, checkpoint: decodeId(checkpoint) });
25019
+ } catch {}
25020
+ }
25021
+ } finally {
25022
+ handle.closeSync();
24780
25023
  }
24781
- let suspended = false;
25024
+ return out;
25025
+ }
25026
+ pending() {
25027
+ this.o.owner.lease.assert();
25028
+ const sessions = new Set(this.o.sessions.list().map((l) => l.summary.id));
25029
+ return this.legacy().filter((c) => !sessions.has(c.id)).length;
25030
+ }
25031
+ migrate() {
25032
+ this.o.owner.lease.assert();
25033
+ if (this.o.owner.state !== "idle")
25034
+ throw new ContractError("quarantine");
25035
+ const sessions = new Set(this.o.sessions.list().map((l) => l.summary.id));
25036
+ let migrated = 0, skipped = 0;
25037
+ for (const conversation of this.legacy()) {
25038
+ if (sessions.has(conversation.id))
25039
+ continue;
25040
+ try {
25041
+ this.copy(conversation);
25042
+ migrated++;
25043
+ } catch {
25044
+ skipped++;
25045
+ }
25046
+ }
25047
+ return { migrated, skipped };
25048
+ }
25049
+ copy(conversation) {
25050
+ const messages = [
25051
+ ...iterateConversationContext(join29(this.root, "turns", conversation.checkpoint, "context.json"))
25052
+ ];
25053
+ if (!messages.length)
25054
+ throw new ContractError("invalid");
25055
+ const first = messages[0].timestamp || Date.now();
25056
+ const iso = (ms) => new Date(ms || first).toISOString();
25057
+ const ids = new Set;
25058
+ const nextId = () => {
25059
+ for (;; ) {
25060
+ const id = randomBytes6(4).toString("hex");
25061
+ if (!ids.has(id)) {
25062
+ ids.add(id);
25063
+ return id;
25064
+ }
25065
+ }
25066
+ };
25067
+ let parentId = null;
25068
+ const lines = [
25069
+ {
25070
+ type: "session",
25071
+ version: 3,
25072
+ id: conversation.id,
25073
+ timestamp: iso(first),
25074
+ cwd: this.o.cwd
25075
+ }
25076
+ ];
25077
+ const append = (entry) => {
25078
+ const id = nextId();
25079
+ lines.push({ ...entry, id, parentId });
25080
+ parentId = id;
25081
+ };
25082
+ append({
25083
+ type: "custom",
25084
+ customType: WEBUI_SESSION_ENTRY,
25085
+ timestamp: iso(first)
25086
+ });
25087
+ const assistant = messages.find((m) => m.role === "assistant");
25088
+ if (assistant?.provider && assistant.model)
25089
+ append({
25090
+ type: "model_change",
25091
+ timestamp: iso(first),
25092
+ provider: assistant.provider,
25093
+ modelId: assistant.model
25094
+ });
25095
+ for (const message of messages)
25096
+ append({ type: "message", timestamp: iso(message.timestamp), message });
25097
+ const name = `${iso(first).replace(/[:.]/g, "-")}_${conversation.id}.jsonl`;
25098
+ const directory = this.o.sessions.directory;
25099
+ mkdirSync5(directory, { recursive: true, mode: 448 });
25100
+ const temporary = join29(directory, `.${name}.${randomBytes6(6).toString("hex")}`);
25101
+ const fd = openSync10(temporary, "wx", 384);
24782
25102
  try {
24783
- if (!this.directory() || this.incarnation() !== state.incarnation)
24784
- throw new ContractError("stale");
24785
- const started = performance.now();
24786
- for (let n = 0;n < SCAN_ENTRIES; n++) {
24787
- if (n && performance.now() - started >= LIMITS.searchMs)
25103
+ writeSync(fd, `${lines.map((line) => JSON.stringify(line)).join(`
25104
+ `)}
25105
+ `);
25106
+ fsyncSync6(fd);
25107
+ } finally {
25108
+ closeSync10(fd);
25109
+ }
25110
+ try {
25111
+ linkSync(temporary, join29(directory, name));
25112
+ } finally {
25113
+ unlinkSync4(temporary);
25114
+ }
25115
+ }
25116
+ }
25117
+
25118
+ // src/service/conversation-workflow.ts
25119
+ import { randomUUID as randomUUID20 } from "node:crypto";
25120
+ import { opendirSync as opendirSync11 } from "node:fs";
25121
+ import { dirname as dirname21, join as join32 } from "node:path";
25122
+
25123
+ // src/cadence-instructions.ts
25124
+ var CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits by typing 退出 Cadence or exit cadence. Only the user can exit; leaving never cancels accepted work. When asked how to leave, say exactly this.
25125
+ You are the sole user-facing coordinator. Continue normal conversation, not a task-manager UI. Do not ask the user to manage tasks, IDs, JSON, service ports, Save/Start/check menus or agent assignments.
25126
+ For each new goal: inspect relevant project evidence through cadence_research (up to two independent readonly subagents); read existing AGENTS/docs/.cadence/project.md before proposing conventions. Reuse still-current findings; do not rescan the entire repository or spawn agents merely to fill slots. Aggregate questions yourself. Investigate discoverable facts and ask focused, frequent questions only for unresolved product/technical decisions. Preserve confirmed decisions across turns. Diagnosis/research alone never imply implementation.
25127
+ Once material decisions and acceptance criteria are aligned, use cadence_plan with a readable design, explicit non-goals/decisions, exact file scopes, a finite dependency DAG, real verification commands, worktree prerequisites and a bounded repair budget. Independent writes may run concurrently; shared files need a single owner or dependency. Investigate local tool/dependency prerequisites BEFORE finalizing: isolated worktrees do not inherit ignored node_modules. Setup commands require inclusion in the final approval; never silently install/download/copy dependencies or credentials. local-merge needs an existing Git branch and commit identity; working-copy is explicit direct editing without Git mutation and is serialized.
25128
+ Present the returned complete plan and invite a single clear execution approval (the user can type 按计划实施). cadence_start binds the exact displayed plan and obtains fresh user consent; never interpret a vague acknowledgement as approval. No further confirmations are needed for the approved bounded pipeline. No push, publication, deployment, recursive delegation or scope expansion. If a material decision changes, revise the plan and seek fresh approval.
25129
+ During accepted work answer questions, report actual retained progress, and let the service execute. cadence_cancel is explicit cancellation, not navigation/exit. Never claim a worker's prose is a passing check or automatic review is human review. Failed/unknown/blocked outcomes are not success. A completed goal leaves Cadence ON and ready for the next goal; do not require /cadence again. Unrelated discussion is still ordinary conversation within this mode, not implicit permission to start another implementation. Tools operate on the host; this is not a sandbox.`;
25130
+
25131
+ // src/service/conversations.ts
25132
+ import { randomUUID as randomUUID19 } from "node:crypto";
25133
+ import { lstatSync as lstatSync18, opendirSync as opendirSync10, realpathSync as realpathSync10, statfsSync as statfsSync2 } from "node:fs";
25134
+ import { dirname as dirname20, join as join31 } from "node:path";
25135
+
25136
+ // src/service/pi-sessions.ts
25137
+ import { createHash as createHash25 } from "node:crypto";
25138
+ import {
25139
+ closeSync as closeSync11,
25140
+ constants as constants9,
25141
+ fstatSync as fstatSync7,
25142
+ lstatSync as lstatSync17,
25143
+ openSync as openSync11,
25144
+ readdirSync as readdirSync3,
25145
+ readSync as readSync6
25146
+ } from "node:fs";
25147
+ import { homedir as homedir7 } from "node:os";
25148
+ import { isAbsolute as isAbsolute10, join as join30, resolve as resolve10 } from "node:path";
25149
+ var SESSION_BYTES = 64 * 1024 * 1024;
25150
+ var LISTED_FILES = 1e4;
25151
+ var OPEN_SESSIONS = 8;
25152
+ var BUILT_TURNS = 64;
25153
+ var SETTINGS_BYTES = 1024 * 1024;
25154
+ var TITLE_CHARS = 100;
25155
+ var NOTICE_BYTES = 1024;
25156
+ var PART_TEXT_BYTES = 200 * 1024;
25157
+ var PART_ARGS_BYTES = 48 * 1024;
25158
+ var TARGET_ARGS = 1024 * 1024;
25159
+ function sessionDirectory(cwd, agentDir, env = process.env) {
25160
+ const expand = (value) => {
25161
+ const home = value === "~" ? homedir7() : value.startsWith("~/") ? join30(homedir7(), value.slice(2)) : value;
25162
+ return isAbsolute10(home) ? resolve10(home) : resolve10(cwd, home);
25163
+ };
25164
+ const fromEnv = env.PI_CODING_AGENT_SESSION_DIR;
25165
+ if (fromEnv)
25166
+ return expand(fromEnv);
25167
+ let configured;
25168
+ for (const file of [
25169
+ join30(agentDir, "settings.json"),
25170
+ join30(cwd, ".pi", "settings.json")
25171
+ ]) {
25172
+ const value = settingsSessionDir(file);
25173
+ if (value)
25174
+ configured = value;
25175
+ }
25176
+ if (configured)
25177
+ return expand(configured);
25178
+ return join30(agentDir, "sessions", `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`);
25179
+ }
25180
+ function settingsSessionDir(file) {
25181
+ let fd;
25182
+ try {
25183
+ fd = openSync11(file, constants9.O_RDONLY | (constants9.O_NOFOLLOW ?? 0));
25184
+ const st = fstatSync7(fd);
25185
+ if (!st.isFile() || st.size > SETTINGS_BYTES)
25186
+ return;
25187
+ const buffer = Buffer.alloc(st.size);
25188
+ readSync6(fd, buffer, 0, st.size, 0);
25189
+ const value = JSON.parse(buffer.toString("utf8"));
25190
+ const dir = value && typeof value === "object" && !Array.isArray(value) ? value.sessionDir : undefined;
25191
+ return typeof dir === "string" && dir.trim() ? dir.trim() : undefined;
25192
+ } catch {
25193
+ return;
25194
+ } finally {
25195
+ if (fd !== undefined)
25196
+ closeSync11(fd);
25197
+ }
25198
+ }
25199
+ var own3 = (o, key2) => Object.hasOwn(o, key2) ? o[key2] : undefined;
25200
+ function parseLine(text2, pos) {
25201
+ let value;
25202
+ try {
25203
+ value = JSON.parse(text2);
25204
+ } catch {
25205
+ return;
25206
+ }
25207
+ if (!value || typeof value !== "object" || Array.isArray(value))
25208
+ return;
25209
+ const o = value;
25210
+ const type = own3(o, "type");
25211
+ if (type === "session") {
25212
+ const id2 = own3(o, "id"), cwd = own3(o, "cwd"), version = own3(o, "version"), timestamp3 = own3(o, "timestamp");
25213
+ if (typeof id2 !== "string" || !id2)
25214
+ return;
25215
+ return {
25216
+ kind: "header",
25217
+ header: {
25218
+ id: id2,
25219
+ cwd: typeof cwd === "string" ? cwd : "",
25220
+ version: typeof version === "number" ? version : 1,
25221
+ timestamp: typeof timestamp3 === "string" ? timestamp3 : ""
25222
+ }
25223
+ };
25224
+ }
25225
+ const id = own3(o, "id"), parentId = own3(o, "parentId"), timestamp2 = own3(o, "timestamp");
25226
+ if (typeof type !== "string" || typeof id !== "string" || !id || id.length > 64 || !/^[A-Za-z0-9_-]+$/.test(id) || !(parentId === null || typeof parentId === "string"))
25227
+ return;
25228
+ return {
25229
+ kind: "entry",
25230
+ entry: {
25231
+ type,
25232
+ id,
25233
+ parentId,
25234
+ timestamp: typeof timestamp2 === "string" ? timestamp2 : "",
25235
+ pos,
25236
+ raw: o
25237
+ }
25238
+ };
25239
+ }
25240
+ function readLines(path, from, onLine) {
25241
+ const fd = openSync11(path, constants9.O_RDONLY | (constants9.O_NOFOLLOW ?? 0));
25242
+ try {
25243
+ const st = fstatSync7(fd);
25244
+ if (!st.isFile())
25245
+ throw new ContractError("forbidden");
25246
+ if (st.size > SESSION_BYTES)
25247
+ throw new ContractError("capacity");
25248
+ const restarted = !from || from.ino !== st.ino || st.size < from.end;
25249
+ const start = restarted ? 0 : from.end;
25250
+ const length = st.size - start;
25251
+ let end = start;
25252
+ if (length > 0) {
25253
+ const buffer = Buffer.allocUnsafe(length);
25254
+ let read2 = 0;
25255
+ while (read2 < length) {
25256
+ const n = readSync6(fd, buffer, read2, length - read2, start + read2);
25257
+ if (n === 0)
24788
25258
  break;
24789
- const e = state.dir.readSync();
24790
- if (!e) {
24791
- const entries2 = state.entries.slice(0, CONVERSATION_PAGE);
24792
- const last = entries2.at(-1);
24793
- return {
24794
- kind: "conversations",
24795
- entries: entries2,
24796
- next: state.entries.length > entries2.length && last ? { id: last.id, updatedAt: last.updatedAt } : null
24797
- };
24798
- }
24799
- if (!e.isFile() || !e.name.endsWith(".json"))
24800
- throw new ContractError("corrupt-selected");
24801
- const summary2 = this.summary(decodeId(e.name.slice(0, -5)));
24802
- if (after && compareChats(summary2, after) <= 0)
24803
- continue;
24804
- if (state.entries.some((row) => row.id === summary2.id))
24805
- continue;
24806
- state.entries.push(summary2);
24807
- state.entries.sort(compareChats);
24808
- if (state.entries.length > CONVERSATION_PAGE + 1)
24809
- state.entries.pop();
25259
+ read2 += n;
25260
+ }
25261
+ let line = 0;
25262
+ for (let i = buffer.indexOf(10);i >= 0 && i < read2; ) {
25263
+ const text2 = buffer.toString("utf8", line, i);
25264
+ if (text2.trim())
25265
+ onLine(text2, start + line);
25266
+ line = i + 1;
25267
+ i = buffer.indexOf(10, line);
25268
+ }
25269
+ end = start + line;
25270
+ }
25271
+ return { ino: st.ino, size: st.size, mtimeMs: st.mtimeMs, end, restarted };
25272
+ } finally {
25273
+ closeSync11(fd);
25274
+ }
25275
+ }
25276
+ var message = (entry) => {
25277
+ if (entry.type !== "message")
25278
+ return;
25279
+ const m = own3(entry.raw, "message");
25280
+ return m && typeof m === "object" && !Array.isArray(m) ? m : undefined;
25281
+ };
25282
+ var role2 = (entry) => {
25283
+ const m = message(entry);
25284
+ return m ? own3(m, "role") : undefined;
25285
+ };
25286
+ var isUser = (entry) => role2(entry) === "user";
25287
+ function contentText(content, omitted2) {
25288
+ if (typeof content === "string")
25289
+ return content;
25290
+ if (!Array.isArray(content))
25291
+ return "";
25292
+ const parts = [];
25293
+ for (const block of content) {
25294
+ const b = block && typeof block === "object" ? block : {};
25295
+ const kind = own3(b, "type");
25296
+ const value = own3(b, "text");
25297
+ if (kind === "text" && typeof value === "string")
25298
+ parts.push(value);
25299
+ else if (omitted2 && kind === "image")
25300
+ omitted2.media = true;
25301
+ else if (omitted2)
25302
+ omitted2.other = true;
25303
+ }
25304
+ return parts.join(`
25305
+ `);
25306
+ }
25307
+ var firstLine = (value) => [...value.trim().split(`
25308
+ `, 1)[0] ?? ""].slice(0, TITLE_CHARS).join("");
25309
+ var time = (value) => {
25310
+ const ms = Date.parse(value);
25311
+ return Number.isFinite(ms) && ms > 0 ? ms : 0;
25312
+ };
25313
+ function stopStatus(m) {
25314
+ const reason = own3(m, "stopReason");
25315
+ if (reason === "error") {
25316
+ const error = own3(m, "errorMessage");
25317
+ return {
25318
+ status: "failed",
25319
+ notice: typeof error === "string" ? error : "The model request failed."
25320
+ };
25321
+ }
25322
+ if (reason === "aborted")
25323
+ return { status: "canceled", notice: "" };
25324
+ return { status: "completed", notice: "" };
25325
+ }
25326
+ function emptySummary() {
25327
+ return {
25328
+ id: "",
25329
+ cwd: "",
25330
+ version: 0,
25331
+ created: 0,
25332
+ name: null,
25333
+ firstUser: null,
25334
+ leaf: null,
25335
+ webui: false,
25336
+ runs: [],
25337
+ cadence: false,
25338
+ stop: null
25339
+ };
25340
+ }
25341
+ function fold(summary2, line) {
25342
+ if (line.kind === "header") {
25343
+ summary2.id = line.header.id;
25344
+ summary2.cwd = line.header.cwd;
25345
+ summary2.version = line.header.version;
25346
+ summary2.created = time(line.header.timestamp);
25347
+ return;
25348
+ }
25349
+ const entry = line.entry;
25350
+ summary2.leaf = entry.id;
25351
+ if (entry.type === "session_info") {
25352
+ const name = own3(entry.raw, "name");
25353
+ summary2.name = typeof name === "string" && name.trim() ? name : null;
25354
+ } else if (entry.type === "custom") {
25355
+ const kind = own3(entry.raw, "customType");
25356
+ if (kind === WEBUI_SESSION_ENTRY)
25357
+ summary2.webui = true;
25358
+ if (kind === CADENCE_MODE_ENTRY) {
25359
+ const data2 = own3(entry.raw, "data");
25360
+ const d = data2 && typeof data2 === "object" ? data2 : {};
25361
+ const runId = own3(d, "runId");
25362
+ summary2.cadence = own3(d, "enabled") === true;
25363
+ if (typeof runId === "string" && /^[0-9a-f-]{36}$/.test(runId) && !summary2.runs.includes(runId) && summary2.runs.length < 200)
25364
+ summary2.runs.push(runId);
25365
+ }
25366
+ } else {
25367
+ const m = message(entry);
25368
+ if (m && own3(m, "role") === "user" && summary2.firstUser === null) {
25369
+ const text2 = firstLine(contentText(own3(m, "content")));
25370
+ if (text2)
25371
+ summary2.firstUser = text2;
25372
+ }
25373
+ if (m && own3(m, "role") === "assistant")
25374
+ summary2.stop = stopStatus(m);
25375
+ }
25376
+ }
25377
+
25378
+ class ParsedSession {
25379
+ path;
25380
+ entries = [];
25381
+ byId = new Map;
25382
+ children = new Map;
25383
+ header = null;
25384
+ read;
25385
+ constructor(path) {
25386
+ this.path = path;
25387
+ }
25388
+ refresh() {
25389
+ const lines = [];
25390
+ const next = readLines(this.path, this.read, (text2, pos) => {
25391
+ const line = parseLine(text2, pos);
25392
+ if (line)
25393
+ lines.push(line);
25394
+ });
25395
+ if (next.restarted) {
25396
+ this.entries.length = 0;
25397
+ this.byId.clear();
25398
+ this.children.clear();
25399
+ this.header = null;
25400
+ }
25401
+ for (const line of lines) {
25402
+ if (line.kind === "header") {
25403
+ this.header ??= line.header;
25404
+ continue;
24810
25405
  }
24811
- const scan = randomUUID19();
24812
- state.timer = setTimeout(() => {
24813
- this.scans.delete(scan);
24814
- try {
24815
- state.dir.closeSync();
24816
- } catch {
24817
- this.closed = true;
24818
- }
24819
- }, IDLE_MS);
24820
- state.timer.unref();
24821
- this.scans.set(scan, state);
24822
- suspended = true;
24823
- return { kind: "conversations-progress", after, scan };
24824
- } finally {
24825
- if (!suspended)
24826
- state.dir.closeSync();
25406
+ const entry = line.entry;
25407
+ if (this.byId.has(entry.id))
25408
+ continue;
25409
+ this.entries.push(entry);
25410
+ this.byId.set(entry.id, entry);
25411
+ const key2 = entry.parentId ?? "";
25412
+ const siblings = this.children.get(key2);
25413
+ if (siblings)
25414
+ siblings.push(entry);
25415
+ else
25416
+ this.children.set(key2, [entry]);
24827
25417
  }
25418
+ this.read = next;
25419
+ return this;
24828
25420
  }
24829
- close() {
24830
- this.closed = true;
24831
- let failed = false;
24832
- for (const state of this.scans.values()) {
24833
- clearTimeout(state.timer);
24834
- try {
24835
- state.dir.closeSync();
24836
- } catch {
24837
- failed = true;
25421
+ current() {
25422
+ return this.entries.at(-1)?.id ?? null;
25423
+ }
25424
+ branch(leaf) {
25425
+ const out = [];
25426
+ let entry = leaf === null ? undefined : this.byId.get(leaf);
25427
+ if (leaf !== null && !entry)
25428
+ throw new ContractError("stale");
25429
+ for (let n = 0;entry && n <= this.entries.length; n++) {
25430
+ out.push(entry);
25431
+ entry = entry.parentId === null ? undefined : this.byId.get(entry.parentId);
25432
+ }
25433
+ return out.reverse();
25434
+ }
25435
+ contains(leaf, ancestor) {
25436
+ let entry = leaf === null ? undefined : this.byId.get(leaf);
25437
+ for (let n = 0;entry && n <= this.entries.length; n++) {
25438
+ if (entry.id === ancestor)
25439
+ return true;
25440
+ entry = entry.parentId === null ? undefined : this.byId.get(entry.parentId);
25441
+ }
25442
+ return false;
25443
+ }
25444
+ leaves() {
25445
+ let count2 = 0;
25446
+ for (const entry of this.entries)
25447
+ if (!this.children.has(entry.id))
25448
+ count2++;
25449
+ return count2;
25450
+ }
25451
+ chain(parent, offset, text2) {
25452
+ const fresh2 = (entry) => entry.pos >= offset;
25453
+ const reaches = (entry) => {
25454
+ let current2 = entry;
25455
+ for (let n = 0;current2 && n <= this.entries.length; n++) {
25456
+ if (current2.parentId === null)
25457
+ return parent === null;
25458
+ if (current2.parentId === parent)
25459
+ return true;
25460
+ current2 = this.byId.get(current2.parentId);
25461
+ if (current2 && !fresh2(current2))
25462
+ return false;
24838
25463
  }
25464
+ return false;
25465
+ };
25466
+ const user = this.entries.find((entry) => fresh2(entry) && isUser(entry) && contentText(own3(message(entry) ?? {}, "content")) === text2 && reaches(entry));
25467
+ if (!user)
25468
+ return [];
25469
+ const out = [user];
25470
+ for (let n = 0;n < this.entries.length; n++) {
25471
+ const next = (this.children.get(out[out.length - 1].id) ?? []).filter(fresh2);
25472
+ if (!next.length)
25473
+ break;
25474
+ out.push(next.reduce((a, b) => b.pos > a.pos ? b : a));
24839
25475
  }
24840
- this.scans.clear();
24841
- if (failed)
24842
- throw new ContractError("unavailable");
25476
+ return out;
25477
+ }
25478
+ tree(leaf, secrets) {
25479
+ const newest = new Map;
25480
+ for (let i = this.entries.length - 1;i >= 0; i--) {
25481
+ let entry = this.entries[i];
25482
+ const leaf2 = entry;
25483
+ for (let n = 0;entry && !newest.has(entry.id) && n <= i; n++) {
25484
+ newest.set(entry.id, leaf2);
25485
+ entry = entry.parentId === null ? undefined : this.byId.get(entry.parentId);
25486
+ }
25487
+ }
25488
+ const onBranch = new Set(this.branch(leaf).map((entry) => entry.id));
25489
+ const users = this.entries.filter(isUser);
25490
+ const kept = users.slice(-TREE_NODES);
25491
+ const keep = new Set(kept.map((entry) => entry.id));
25492
+ const nodes = kept.map((entry) => {
25493
+ let parent = entry.parentId === null ? undefined : this.byId.get(entry.parentId);
25494
+ for (let n = 0;parent && !keep.has(parent.id) && n <= this.entries.length; n++)
25495
+ parent = parent.parentId === null ? undefined : this.byId.get(parent.parentId);
25496
+ const m = message(entry) ?? {};
25497
+ return {
25498
+ id: entry.id,
25499
+ parent: parent?.id ?? null,
25500
+ text: clipText(sanitizeText(firstLine(contentText(own3(m, "content"))), secrets), 512),
25501
+ at: time(entry.timestamp),
25502
+ leaf: (newest.get(entry.id) ?? entry).id,
25503
+ current: onBranch.has(entry.id)
25504
+ };
25505
+ });
25506
+ return { nodes, truncated: kept.length < users.length };
24843
25507
  }
24844
25508
  }
25509
+ function turnSpans(path) {
25510
+ const turns = [];
25511
+ for (const entry of path) {
25512
+ if (isUser(entry) || !turns.length)
25513
+ turns.push([entry]);
25514
+ else
25515
+ turns[turns.length - 1].push(entry);
25516
+ }
25517
+ if (turns.length && !isUser(turns[0][0]) && !turns[0].some(shown))
25518
+ turns.shift();
25519
+ return turns;
25520
+ }
25521
+ function shown(entry) {
25522
+ if (entry.type === "message")
25523
+ return ["user", "assistant", "toolResult", "bashExecution"].includes(role2(entry));
25524
+ if (entry.type === "custom_message")
25525
+ return own3(entry.raw, "display") === true;
25526
+ return entry.type === "compaction" || entry.type === "branch_summary";
25527
+ }
25528
+ var clip = (value, bytes) => clipText(value, bytes);
25529
+ function turnItems(entries2, secrets) {
25530
+ const omitted2 = { thinking: false, media: false, other: false };
25531
+ const items = [];
25532
+ const tools = new Map;
25533
+ let status = "completed", notice = "";
25534
+ const add = (item) => {
25535
+ items.push({
25536
+ ...item,
25537
+ id: clip(item.id, 160) || "item",
25538
+ name: clip(sanitizeText(item.name, secrets), 128),
25539
+ text: sanitizeText(item.text, secrets),
25540
+ args: sanitizeText(item.args, secrets)
25541
+ });
25542
+ return items[items.length - 1];
25543
+ };
25544
+ const tool = (id, name, args, text2 = "", error = false) => add({ id, role: "tool", name, args, text: text2, error });
25545
+ for (const entry of entries2) {
25546
+ const m = message(entry);
25547
+ if (m) {
25548
+ const kind = own3(m, "role");
25549
+ if (kind === "user")
25550
+ add({
25551
+ id: entry.id,
25552
+ role: "user",
25553
+ text: contentText(own3(m, "content"), omitted2),
25554
+ name: "",
25555
+ args: "",
25556
+ error: false
25557
+ });
25558
+ else if (kind === "assistant") {
25559
+ let text2;
25560
+ const content = own3(m, "content");
25561
+ for (const block of Array.isArray(content) ? content : []) {
25562
+ const b = block && typeof block === "object" ? block : {};
25563
+ const type = own3(b, "type");
25564
+ if (type === "text" && typeof own3(b, "text") === "string") {
25565
+ const value = own3(b, "text");
25566
+ if (text2 && items[items.length - 1] === text2)
25567
+ text2.text += sanitizeText(`
24845
25568
 
24846
- // src/service/conversation-transcript.ts
24847
- var TRANSCRIPT_PAGE_BYTES = 384 * 1024;
24848
- var PREVIEW_BYTES = 300 * 1024;
24849
- var FIELD_CHARS = 16 * 1024;
24850
- var PREVIEW_MARK = `
24851
- [Preview only; open the full transcript.]`;
24852
- function part(value, offset, chars = FIELD_CHARS) {
24853
- let end = Math.min(value.length, offset + chars);
24854
- if (end < value.length && /[\uD800-\uDBFF]/u.test(value[end - 1]))
24855
- end--;
24856
- return value.slice(offset, end);
25569
+ ${value}`, secrets);
25570
+ else
25571
+ text2 = add({
25572
+ id: `${entry.id}:${items.length}`,
25573
+ role: "assistant",
25574
+ text: value,
25575
+ name: "",
25576
+ args: "",
25577
+ error: false
25578
+ });
25579
+ } else if (type === "toolCall") {
25580
+ const id = own3(b, "id"), name = own3(b, "name");
25581
+ let args = "";
25582
+ try {
25583
+ args = JSON.stringify(own3(b, "arguments") ?? {}) ?? "";
25584
+ } catch {
25585
+ omitted2.other = true;
25586
+ }
25587
+ const call = tool(typeof id === "string" && id ? id : `${entry.id}:${items.length}`, typeof name === "string" ? name : "tool", args);
25588
+ if (typeof id === "string")
25589
+ tools.set(id, call);
25590
+ } else if (type === "thinking" || type === "redactedThinking")
25591
+ omitted2.thinking = true;
25592
+ else if (type === "image")
25593
+ omitted2.media = true;
25594
+ else
25595
+ omitted2.other = true;
25596
+ }
25597
+ ({ status, notice } = stopStatus(m));
25598
+ } else if (kind === "toolResult") {
25599
+ const id = own3(m, "toolCallId"), name = own3(m, "toolName");
25600
+ const output = sanitizeText(contentText(own3(m, "content"), omitted2), secrets);
25601
+ const call = typeof id === "string" ? tools.get(id) : undefined;
25602
+ if (call) {
25603
+ call.text = output;
25604
+ call.error = own3(m, "isError") === true;
25605
+ } else
25606
+ tool(typeof id === "string" && id ? id : entry.id, typeof name === "string" ? name : "tool", "", output, own3(m, "isError") === true);
25607
+ } else if (kind === "bashExecution") {
25608
+ const command = own3(m, "command"), output = own3(m, "output"), code2 = own3(m, "exitCode");
25609
+ tool(entry.id, "bash", JSON.stringify({
25610
+ command: typeof command === "string" ? command : ""
25611
+ }), typeof output === "string" ? output : "", own3(m, "cancelled") === true || typeof code2 === "number" && code2 !== 0);
25612
+ }
25613
+ } else if (entry.type === "custom_message" && own3(entry.raw, "display") === true) {
25614
+ const kind = own3(entry.raw, "customType");
25615
+ tool(entry.id, typeof kind === "string" ? kind : "message", "", contentText(own3(entry.raw, "content"), omitted2));
25616
+ } else if (entry.type === "compaction" || entry.type === "branch_summary") {
25617
+ const summary2 = own3(entry.raw, "summary");
25618
+ tool(entry.id, entry.type === "compaction" ? "compaction" : "branch-summary", "", typeof summary2 === "string" ? summary2 : "");
25619
+ }
25620
+ }
25621
+ const first = entries2.find(isUser) ?? entries2[0];
25622
+ return {
25623
+ id: first?.id ?? "",
25624
+ entry: entries2.at(-1)?.id ?? null,
25625
+ at: first ? time(first.timestamp) : 0,
25626
+ status,
25627
+ notice: clip(sanitizeText(notice, secrets), NOTICE_BYTES),
25628
+ omitted: omitted2,
25629
+ items
25630
+ };
25631
+ }
25632
+ function encodedChunks(value, bytes) {
25633
+ const chunks2 = [];
25634
+ let start = 0, size2 = 2;
25635
+ for (let i = 0;i < value.length; i++) {
25636
+ const c = value.charCodeAt(i);
25637
+ const pair = c >= 55296 && c <= 56319 && i + 1 < value.length;
25638
+ const unit = c === 34 || c === 92 ? 2 : c < 32 ? [8, 9, 10, 12, 13].includes(c) ? 2 : 6 : c < 128 ? 1 : c < 2048 ? 2 : pair ? 4 : c >= 55296 && c <= 57343 ? 6 : 3;
25639
+ if (size2 + unit > bytes && i > start) {
25640
+ chunks2.push(value.slice(start, i));
25641
+ start = i;
25642
+ size2 = 2;
25643
+ }
25644
+ size2 += unit;
25645
+ if (pair)
25646
+ i++;
25647
+ }
25648
+ if (start < value.length)
25649
+ chunks2.push(value.slice(start));
25650
+ return chunks2;
25651
+ }
25652
+ function itemParts(item) {
25653
+ const text2 = encodedChunks(item.text, PART_TEXT_BYTES), args = encodedChunks(item.args, PART_ARGS_BYTES);
25654
+ const count2 = Math.max(text2.length, args.length, 1);
25655
+ return Array.from({ length: count2 }, (_, i) => ({
25656
+ ...item,
25657
+ text: text2[i] ?? "",
25658
+ args: args[i] ?? ""
25659
+ }));
25660
+ }
25661
+ function listTurn(turn) {
25662
+ const parts = turn.items.map(itemParts);
25663
+ const steps = turn.items.map((item, index) => {
25664
+ const listed = chatStep(item.role === "tool" && item.args.length > TARGET_ARGS ? { ...item, args: "" } : item, 0);
25665
+ const more = listed.clipped || item.role === "tool" && !!(item.args || item.text);
25666
+ return { ...listed, parts: more ? parts[index].length : 0 };
25667
+ });
25668
+ return { ...turn, steps, parts };
24857
25669
  }
24858
25670
 
24859
- class ConversationTranscript {
24860
- turn;
24861
- write;
24862
- state = { pages: 0 };
24863
- workingSizes = new Map;
24864
- workingBytes = 0;
24865
- sizes = new Map;
24866
- bytes = 4096;
24867
- pending = new Map;
24868
- constructor(turn, write2) {
24869
- this.turn = turn;
24870
- this.write = write2;
24871
- turn.transcript = this.state;
24872
- for (const item of [...turn.items]) {
24873
- this.archive(item);
24874
- this.preview(item);
25671
+ class PiSessions {
25672
+ directory;
25673
+ cwd;
25674
+ listed = new Map;
25675
+ open = new Map;
25676
+ built = new Map;
25677
+ constructor(directory, cwd) {
25678
+ this.directory = directory;
25679
+ this.cwd = cwd;
25680
+ }
25681
+ list() {
25682
+ let names2;
25683
+ try {
25684
+ names2 = readdirSync3(this.directory, { withFileTypes: true }).filter((d) => d.isFile() && d.name.endsWith(".jsonl")).map((d) => d.name).sort().reverse().slice(0, LISTED_FILES);
25685
+ } catch (error) {
25686
+ if (error.code === "ENOENT")
25687
+ return [];
25688
+ throw new ContractError("unavailable");
25689
+ }
25690
+ const seen = new Set;
25691
+ const out = [];
25692
+ for (const name of names2) {
25693
+ const path = join30(this.directory, name);
25694
+ seen.add(path);
25695
+ try {
25696
+ const listed = this.summary(path);
25697
+ if (listed.summary.cwd === this.cwd && listed.summary.version >= 3)
25698
+ out.push(listed);
25699
+ } catch {
25700
+ this.listed.delete(path);
25701
+ }
24875
25702
  }
25703
+ for (const path of this.listed.keys())
25704
+ if (!seen.has(path))
25705
+ this.listed.delete(path);
25706
+ return out.sort((a, b) => b.mtimeMs - a.mtimeMs || (a.summary.id < b.summary.id ? -1 : 1));
24876
25707
  }
24877
- item(id, role2) {
24878
- let item = this.pending.get(id);
24879
- if (!item) {
24880
- if (this.pending.size >= 256)
24881
- throw new ContractError("capacity");
24882
- item = { id, role: role2, text: "", name: "", args: "", error: false };
24883
- this.pending.set(id, item);
24884
- this.preview(item);
25708
+ summary(path) {
25709
+ const st = lstatSync17(path);
25710
+ if (!st.isFile())
25711
+ throw new ContractError("forbidden");
25712
+ const cached = this.listed.get(path);
25713
+ if (cached && cached.ino === st.ino && cached.size === st.size) {
25714
+ cached.mtimeMs = st.mtimeMs;
25715
+ return cached;
24885
25716
  }
24886
- return item;
25717
+ let summary2 = cached && cached.ino === st.ino && st.size >= cached.end ? cached.summary : emptySummary();
25718
+ const lines = [];
25719
+ const read2 = readLines(path, cached, (text2, pos) => {
25720
+ const line = parseLine(text2, pos);
25721
+ if (line)
25722
+ lines.push(line);
25723
+ });
25724
+ if (read2.restarted)
25725
+ summary2 = emptySummary();
25726
+ for (const line of lines)
25727
+ fold(summary2, line);
25728
+ const listed = { path, ...read2, summary: summary2 };
25729
+ this.listed.set(path, listed);
25730
+ return listed;
24887
25731
  }
24888
25732
  find(id) {
24889
- return this.pending.get(id);
24890
- }
24891
- preview(item) {
24892
- if (this.pending.has(item.id)) {
24893
- const size3 = Buffer.byteLength(item.text) + Buffer.byteLength(item.args) + Buffer.byteLength(item.name);
24894
- this.workingBytes += size3 - (this.workingSizes.get(item.id) ?? 0);
24895
- this.workingSizes.set(item.id, size3);
24896
- if (this.workingBytes > 2 * LIMITS.detailBytes)
24897
- throw new ContractError("capacity");
24898
- }
24899
- const clip = (value) => {
24900
- const prefix = part(value, 0);
24901
- return prefix.length < value.length ? prefix + PREVIEW_MARK : value;
24902
- };
24903
- const preview = { ...item, text: clip(item.text), args: clip(item.args) };
24904
- const size2 = Buffer.byteLength(canonicalJson(preview, PREVIEW_BYTES));
24905
- this.bytes += size2 - (this.sizes.get(item.id) ?? 0);
24906
- this.sizes.set(item.id, size2);
24907
- const at = this.turn.items.findIndex((i) => i.id === item.id);
24908
- if (at < 0)
24909
- this.turn.items.push(preview);
24910
- else
24911
- this.turn.items[at] = preview;
24912
- while (this.bytes > PREVIEW_BYTES || this.turn.items.length > 128) {
24913
- if (this.turn.items.length <= 2)
24914
- throw new ContractError("oversize");
24915
- const [removed] = this.turn.items.splice(this.turn.items[0].role === "user" ? 1 : 0, 1);
24916
- this.bytes -= this.sizes.get(removed.id) ?? 0;
24917
- this.sizes.delete(removed.id);
24918
- }
25733
+ const known = [...this.listed.values()].find((listed) => listed.summary.id === id);
25734
+ if (known)
25735
+ try {
25736
+ const listed = this.summary(known.path);
25737
+ if (listed.summary.id === id && listed.summary.cwd === this.cwd)
25738
+ return listed;
25739
+ } catch {
25740
+ this.listed.delete(known.path);
25741
+ }
25742
+ return this.list().find((listed) => listed.summary.id === id);
24919
25743
  }
24920
- complete(id) {
24921
- const item = this.pending.get(id);
24922
- if (!item)
25744
+ session(id) {
25745
+ const listed = this.find(id);
25746
+ if (!listed)
24923
25747
  return;
24924
- this.preview(item);
24925
- this.archive(item);
24926
- this.pending.delete(id);
24927
- this.workingBytes -= this.workingSizes.get(id) ?? 0;
24928
- this.workingSizes.delete(id);
24929
- }
24930
- finish() {
24931
- for (const id of this.pending.keys())
24932
- this.complete(id);
24933
- }
24934
- archive(item) {
24935
- let text2 = 0, args = 0;
24936
- do {
24937
- let chars = 128 * 1024;
24938
- const fragment = { ...item, text: "", args: part(item.args, args) };
24939
- for (;; ) {
24940
- fragment.text = part(item.text, text2, chars);
24941
- try {
24942
- if (Buffer.byteLength(fragment.text) > 256 * 1024)
24943
- throw new ContractError("oversize");
24944
- canonicalJson(fragment, TRANSCRIPT_PAGE_BYTES - 4096);
24945
- break;
24946
- } catch (error) {
24947
- if (!(error instanceof ContractError) || error.code !== "oversize" || chars <= FIELD_CHARS)
24948
- throw error;
24949
- chars /= 2;
24950
- }
24951
- }
24952
- const page = this.state.pages;
24953
- if (!Number.isSafeInteger(page + 1))
24954
- throw new ContractError("capacity");
24955
- this.write({ turnId: this.turn.id, page, items: [fragment] });
24956
- this.state.pages = page + 1;
24957
- text2 += fragment.text.length;
24958
- args += fragment.args.length;
24959
- } while (text2 < item.text.length || args < item.args.length);
25748
+ let parsed = this.open.get(listed.path);
25749
+ this.open.delete(listed.path);
25750
+ parsed ??= new ParsedSession(listed.path);
25751
+ parsed.refresh();
25752
+ if (parsed.header?.id !== id)
25753
+ throw new ContractError("corrupt-selected");
25754
+ this.open.set(listed.path, parsed);
25755
+ if (this.open.size > OPEN_SESSIONS)
25756
+ this.open.delete(this.open.keys().next().value);
25757
+ return parsed;
25758
+ }
25759
+ turn(session, entries2, secrets) {
25760
+ const key2 = [
25761
+ session.path,
25762
+ entries2[0]?.id,
25763
+ entries2.at(-1)?.id,
25764
+ entries2.length,
25765
+ createHash25("sha256").update(secrets.join("\x00")).digest("hex")
25766
+ ].join("|");
25767
+ const hit = this.built.get(key2);
25768
+ this.built.delete(key2);
25769
+ const turn = hit ?? listTurn(turnItems(entries2, secrets));
25770
+ this.built.set(key2, turn);
25771
+ if (this.built.size > BUILT_TURNS)
25772
+ this.built.delete(this.built.keys().next().value);
25773
+ return turn;
25774
+ }
25775
+ nativeRuns() {
25776
+ const out = new Map;
25777
+ for (const listed of this.list())
25778
+ for (const run2 of listed.summary.runs)
25779
+ if (!out.has(run2))
25780
+ out.set(run2, listed.summary.id);
25781
+ return out;
24960
25782
  }
24961
25783
  }
25784
+ function summaryTitle(summary2) {
25785
+ return summary2.name ?? summary2.firstUser ?? "Conversation";
25786
+ }
24962
25787
 
24963
25788
  // src/service/conversations.ts
24964
- var TURN_BYTES = 384 * 1024;
24965
- var META_BYTES = 64 * 1024;
24966
- var SUMMARY_CACHE = 256;
25789
+ var META_BYTES2 = 64 * 1024;
25790
+ var PAGE = 50;
25791
+ var INDEXED_COMMANDS = 64;
25792
+ var COMMAND_STATES = 512;
25793
+ var PREVIEW_BYTES = 64 * 1024;
25794
+ var RECENT_PREVIEWS = 8;
25795
+ var PREVIEW_MARK = `
25796
+ [Preview truncated; the rest appears once it is written.]`;
25797
+ var INTERRUPTED = "Interrupted: Cadence stopped before this reply finished. Nothing was replayed; send the message again to retry.";
24967
25798
  var OMITTED_FLAG = {
24968
25799
  "hidden-thinking": "thinking",
24969
25800
  binary: "media",
24970
25801
  unsupported: "other"
24971
25802
  };
25803
+ var LIVE = ["queued", "running"];
24972
25804
  function observedFile(path) {
24973
25805
  try {
24974
- const s = lstatSync17(path);
25806
+ const s = lstatSync18(path);
24975
25807
  return [s.dev, s.ino, s.size, s.mode, s.nlink, s.ctimeMs, s.mtimeMs].join(":");
24976
25808
  } catch (error) {
24977
25809
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
@@ -24980,65 +25812,51 @@ function observedFile(path) {
24980
25812
  }
24981
25813
  }
24982
25814
 
24983
- class ConversationCapture {
24984
- turn;
24985
- save;
25815
+ class LiveCapture {
24986
25816
  secrets;
24987
- transcript;
25817
+ omitted = { thinking: false, media: false, other: false };
25818
+ notice = "";
25819
+ assistants = [];
25820
+ tools = [];
24988
25821
  details = new Map;
24989
- messageText = new Map;
24990
- constructor(turn, save, secrets, transcript) {
24991
- this.turn = turn;
24992
- this.save = save;
25822
+ blocks = new Map;
25823
+ constructor(secrets) {
24993
25824
  this.secrets = secrets;
24994
- this.transcript = transcript;
24995
25825
  }
24996
- item(id, role2) {
24997
- if (this.transcript)
24998
- return this.transcript.item(id, role2);
24999
- let item = this.turn.items.find((i) => i.id === id);
25000
- if (!item) {
25001
- if (this.turn.items.length >= 256)
25002
- throw new ContractError("capacity");
25003
- item = { id, role: role2, text: "", name: "", args: "", error: false };
25004
- this.turn.items.push(item);
25005
- try {
25006
- canonicalJson(this.turn, TURN_BYTES - 2048);
25007
- } catch (error) {
25008
- this.turn.items.pop();
25009
- this.turn.notice = "Conversation capture limit exceeded.";
25010
- throw error;
25011
- }
25012
- }
25013
- return item;
25826
+ bounded(value) {
25827
+ return Buffer.byteLength(value) <= PREVIEW_BYTES ? value : `${Buffer.from(value).subarray(0, PREVIEW_BYTES).toString("utf8").replace(/�$/u, "")}${PREVIEW_MARK}`;
25014
25828
  }
25015
- update(item, field, value, maximum) {
25016
- if (this.transcript) {
25017
- if (Buffer.byteLength(value) > LIMITS.detailBytes)
25018
- throw new ContractError("capacity");
25019
- item[field] = value;
25020
- this.transcript.preview(item);
25021
- return;
25022
- }
25023
- const before = item[field];
25024
- try {
25025
- if (Buffer.byteLength(value) > maximum)
25026
- throw new ContractError("capacity");
25027
- item[field] = value;
25028
- canonicalJson(this.turn, TURN_BYTES - 2048);
25029
- } catch (error) {
25030
- item[field] = before;
25031
- this.turn.notice = "Conversation capture limit exceeded.";
25032
- throw error;
25829
+ tool(callId) {
25830
+ let tool = this.tools.find((t) => t.id === callId);
25831
+ if (!tool) {
25832
+ tool = { id: callId, name: "", args: "", text: "", error: false };
25833
+ this.tools.push(tool);
25834
+ const stale = this.tools[this.tools.length - 1 - RECENT_PREVIEWS];
25835
+ if (stale)
25836
+ stale.args = stale.text = "";
25033
25837
  }
25838
+ return tool;
25034
25839
  }
25035
25840
  accept(frame) {
25036
25841
  const e = frame.event;
25037
- if (e.kind === "detail-begin") {
25038
- if (e.descriptor.owner.kind === "context" || e.descriptor.owner.kind === "handoff")
25842
+ if (e.kind === "message-start" && e.role === "assistant") {
25843
+ if (!this.assistants.some((a) => a.id === e.messageId)) {
25844
+ this.assistants.push({ id: e.messageId, text: "" });
25845
+ const stale = this.assistants[this.assistants.length - 1 - RECENT_PREVIEWS];
25846
+ if (stale)
25847
+ stale.text = "";
25848
+ }
25849
+ } else if (e.kind === "tool-start" || e.kind === "tool-end") {
25850
+ const tool = this.tool(e.callId);
25851
+ tool.name = sanitizeText(e.name, this.secrets()).slice(0, 128);
25852
+ if (e.kind === "tool-end")
25853
+ tool.error = e.isError;
25854
+ } else if (e.kind === "detail-begin") {
25855
+ const kind = e.descriptor.owner.kind;
25856
+ if (kind === "context" || kind === "handoff")
25039
25857
  return;
25040
25858
  if (this.details.size >= 64)
25041
- throw new ContractError("capacity");
25859
+ return;
25042
25860
  this.details.set(e.detailId, {
25043
25861
  descriptor: e.descriptor,
25044
25862
  sanitizer: new DetailSanitizer(e.descriptor.encoding, this.secrets()),
@@ -25048,75 +25866,137 @@ class ConversationCapture {
25048
25866
  const d = this.details.get(e.detailId);
25049
25867
  if (!d)
25050
25868
  return;
25051
- d.text += e.kind === "detail-chunk" ? d.sanitizer.write(e.text) : d.sanitizer.end();
25052
- if (Buffer.byteLength(d.text) > (this.transcript ? LIMITS.detailBytes : 256 * 1024))
25053
- throw new ContractError("capacity");
25869
+ const added = e.kind === "detail-chunk" ? d.sanitizer.write(e.text) : d.sanitizer.end();
25870
+ if (Buffer.byteLength(d.text) <= PREVIEW_BYTES)
25871
+ d.text += added;
25054
25872
  const o = d.descriptor.owner;
25055
- if (o.kind === "message") {
25056
- const role2 = (this.transcript?.find(o.messageId) ?? this.turn.items.find((i) => i.id === o.messageId))?.role;
25057
- if (role2 === "assistant" && o.stage === "stream") {
25058
- this.messageText.set(o.blockId, {
25059
- messageId: o.messageId,
25060
- text: d.text
25061
- });
25062
- this.update(this.item(o.messageId, "assistant"), "text", [...this.messageText.values()].filter((block) => block.messageId === o.messageId).map((block) => block.text).join(""), 256 * 1024);
25063
- }
25873
+ if (o.kind === "message" && o.stage === "stream") {
25874
+ this.blocks.set(o.blockId, { messageId: o.messageId, text: d.text });
25875
+ const message2 = this.assistants.find((a) => a.id === o.messageId);
25876
+ if (message2)
25877
+ message2.text = this.bounded([...this.blocks.values()].filter((b) => b.messageId === o.messageId).map((b) => b.text).join(""));
25064
25878
  } else if (o.kind === "message-final") {
25065
- const item = this.transcript?.find(o.messageId) ?? this.turn.items.find((i) => i.id === o.messageId);
25066
- if (item?.role === "assistant")
25067
- this.update(item, "text", d.text, 256 * 1024);
25879
+ const message2 = this.assistants.find((a) => a.id === o.messageId);
25880
+ if (message2)
25881
+ message2.text = this.bounded(d.text);
25068
25882
  } else if (o.kind === "tool") {
25069
- const item = this.item(o.callId, "tool");
25883
+ const tool = this.tool(o.callId);
25070
25884
  if (o.stage === "execution-arguments" || o.stage === "arguments-final")
25071
- this.update(item, "args", d.text, 64 * 1024);
25885
+ tool.args = this.bounded(d.text);
25072
25886
  if (o.stage === "result" || o.stage === "update-snapshot")
25073
- this.update(item, "text", d.text, 256 * 1024);
25887
+ tool.text = this.bounded(d.text);
25074
25888
  }
25075
25889
  if (e.kind === "detail-end")
25076
25890
  this.details.delete(e.detailId);
25077
- } else if (e.kind === "message-start" && e.role === "assistant") {
25078
- this.item(e.messageId, "assistant");
25079
- } else if (e.kind === "tool-start" || e.kind === "tool-end") {
25080
- const item = this.item(e.callId, "tool");
25081
- this.update(item, "name", sanitizeText(e.name, this.secrets()), 128);
25082
- if (e.kind === "tool-end")
25083
- item.error = e.isError;
25891
+ } else if (e.kind === "message-end") {
25892
+ for (const [id, block] of this.blocks)
25893
+ if (block.messageId === e.messageId)
25894
+ this.blocks.delete(id);
25084
25895
  } else if (e.kind === "worker-failure")
25085
- this.turn.notice = `worker-failure: ${e.code}`;
25896
+ this.notice = `worker-failure: ${e.code}`;
25086
25897
  else if (e.kind === "omitted-block" && e.block.owner.kind !== "context" && e.block.owner.kind !== "handoff")
25087
- this.turn.omitted[OMITTED_FLAG[e.block.reason]] = true;
25088
- if ([...this.details.values()].reduce((size2, detail) => size2 + Buffer.byteLength(detail.text) + detail.sanitizer.retainedBytes, 0) > (this.transcript ? 2 * LIMITS.detailBytes : TURN_BYTES))
25089
- throw new ContractError("capacity");
25090
- if (!this.transcript)
25091
- canonicalJson(this.turn, TURN_BYTES);
25092
- if (e.kind === "message-end") {
25093
- for (const [id, block] of this.messageText)
25094
- if (block.messageId === e.messageId)
25095
- this.messageText.delete(id);
25096
- }
25097
- if (e.kind === "message-end" || e.kind === "tool-end") {
25098
- this.transcript?.complete(e.kind === "message-end" ? e.messageId : e.callId);
25099
- this.save();
25100
- }
25898
+ this.omitted[OMITTED_FLAG[e.block.reason]] = true;
25899
+ }
25900
+ extend(items) {
25901
+ const out = items.map((item) => ({ ...item }));
25902
+ const written = out.filter((i) => i.role === "assistant").length;
25903
+ const calls = out.filter((i) => i.role === "tool");
25904
+ const results = calls.filter((i) => i.text || i.error).length;
25905
+ let stable = out.length;
25906
+ this.tools.forEach((tool, index) => {
25907
+ if (index < results)
25908
+ return;
25909
+ const item = index < calls.length ? calls[index] : (() => {
25910
+ const added = {
25911
+ id: tool.id,
25912
+ role: "tool",
25913
+ name: tool.name,
25914
+ args: tool.args,
25915
+ text: "",
25916
+ error: false
25917
+ };
25918
+ out.push(added);
25919
+ return added;
25920
+ })();
25921
+ item.text = tool.text;
25922
+ item.error = tool.error;
25923
+ stable = Math.min(stable, out.indexOf(item));
25924
+ });
25925
+ this.assistants.slice(written).forEach((message2) => {
25926
+ stable = Math.min(stable, out.length);
25927
+ out.push({
25928
+ id: message2.id,
25929
+ role: "assistant",
25930
+ text: message2.text,
25931
+ name: "",
25932
+ args: "",
25933
+ error: false
25934
+ });
25935
+ });
25936
+ return { items: out, stable };
25101
25937
  }
25102
25938
  }
25939
+ function decodeAccepted(value) {
25940
+ const o = closed(value, ["command", "at", "session", "parent", "offset"]);
25941
+ const command = decodeWorkbenchCommand(o.command);
25942
+ if (command.kind !== "send")
25943
+ throw new ContractError("corrupt-selected");
25944
+ return {
25945
+ command,
25946
+ at: integer(o.at, 0),
25947
+ session: decodeSessionId(o.session),
25948
+ parent: o.parent === null ? null : decodeEntryId(o.parent),
25949
+ offset: integer(o.offset, 0)
25950
+ };
25951
+ }
25952
+ var statuses2 = [
25953
+ "queued",
25954
+ "running",
25955
+ "completed",
25956
+ "failed",
25957
+ "canceled",
25958
+ "timeout",
25959
+ "unknown"
25960
+ ];
25961
+ function decodeState2(value) {
25962
+ const o = closed(value, ["status", "notice", "omitted", "user"]);
25963
+ const omitted2 = closed(o.omitted, ["thinking", "media", "other"]);
25964
+ return {
25965
+ status: oneOf(o.status, statuses2),
25966
+ notice: text(o.notice, 4096),
25967
+ omitted: {
25968
+ thinking: omitted2.thinking === true,
25969
+ media: omitted2.media === true,
25970
+ other: omitted2.other === true
25971
+ },
25972
+ user: o.user === null ? null : decodeEntryId(o.user)
25973
+ };
25974
+ }
25103
25975
 
25104
25976
  class Conversations {
25105
25977
  o;
25106
25978
  root;
25107
- history;
25979
+ legacy;
25108
25980
  cwd;
25981
+ sessions;
25109
25982
  active = new Map;
25110
- summaries = new Map;
25983
+ knownSecrets;
25984
+ states = new Map;
25111
25985
  constructor(o) {
25112
25986
  this.o = o;
25113
- this.root = join28(o.coordination.directory, "conversations-v1");
25987
+ this.root = join31(o.coordination.directory, "conversation-commands-v1");
25988
+ this.legacy = join31(o.coordination.directory, "conversations-v1");
25114
25989
  this.cwd = realpathSync10(o.cwd);
25115
- const sessions = join28(this.root, "sessions");
25116
- this.history = new ConversationHistory(sessions, () => {
25117
- this.o.owner.lease.assert();
25118
- return this.files.directory(sessions);
25119
- }, (id) => this.retainedSummary(id));
25990
+ this.sessions = new PiSessions(o.sessionDir ?? sessionDirectory(this.cwd, o.agentDir), this.cwd);
25991
+ }
25992
+ readSecrets() {
25993
+ try {
25994
+ this.knownSecrets = this.o.secrets();
25995
+ } catch (error) {
25996
+ if (!this.knownSecrets)
25997
+ throw error instanceof ContractError ? error : new ContractError("unavailable");
25998
+ }
25999
+ return this.knownSecrets;
25120
26000
  }
25121
26001
  currentDirectory() {
25122
26002
  const current2 = resolveWorkspace(this.o.cwd);
@@ -25125,20 +26005,17 @@ class Conversations {
25125
26005
  get files() {
25126
26006
  return this.o.coordination.files;
25127
26007
  }
25128
- path(id, name) {
25129
- return join28(this.root, "turns", decodeId(id), name);
25130
- }
25131
- identityPath(id) {
25132
- return join28(this.root, "identities", `${decodeId(id)}.json`);
26008
+ path(commandId, name) {
26009
+ return join31(this.root, "commands", decodeId(commandId), name);
25133
26010
  }
25134
- metadataPath(id) {
25135
- return join28(this.root, "sessions", `${decodeId(id)}.json`);
26011
+ indexPath(id) {
26012
+ return join31(this.root, "sessions", `${decodeSessionId(id)}.json`);
25136
26013
  }
25137
- read(path, max) {
26014
+ read(path, max = META_BYTES2) {
25138
26015
  const value = this.files.read(path, max);
25139
26016
  return value ? parseWireJson(value.bytes.toString("utf8"), max) : undefined;
25140
26017
  }
25141
- write(path, value, max, expected) {
26018
+ write(path, value, max = META_BYTES2, expected) {
25142
26019
  this.o.owner.lease.assert();
25143
26020
  const source = canonicalJson(value, max);
25144
26021
  try {
@@ -25148,91 +26025,50 @@ class Conversations {
25148
26025
  throw error;
25149
26026
  }
25150
26027
  }
25151
- metadata(id) {
25152
- const value = this.read(this.metadataPath(id), META_BYTES);
25153
- if (value === undefined)
25154
- return null;
25155
- const identity = closed(this.read(this.identityPath(id), META_BYTES), [
26028
+ index(id) {
26029
+ const file = this.files.read(this.indexPath(id), META_BYTES2);
26030
+ if (!file)
26031
+ return { commands: [] };
26032
+ const o = closed(parseWireJson(file.bytes.toString("utf8"), META_BYTES2), [
25156
26033
  "schema",
25157
26034
  "id",
25158
- "cwd"
25159
- ]);
25160
- if (identity.schema !== "cadence-conversation/1" || identity.id !== id || identity.cwd !== this.cwd)
25161
- throw new ContractError("corrupt-selected");
25162
- const indexed = value !== null && typeof value === "object" && Object.hasOwn(value, "count");
25163
- const m = closed(value, [
25164
- "id",
25165
- "title",
25166
- "turns",
25167
- "checkpoint",
25168
- ...indexed ? ["head", "count"] : []
25169
- ]);
25170
- const turns = list(m.turns, 1000, decodeId);
25171
- const count2 = indexed ? integer(m.count, Math.max(1, turns.length)) : turns.length;
25172
- const head = indexed ? decodeId(m.head) : turns.at(-1);
25173
- if (!head || !count2 || new Set(turns).size !== turns.length || m.id !== id)
25174
- throw new ContractError("corrupt-selected");
25175
- const meta = {
25176
- id,
25177
- title: text(m.title, 512, true),
25178
- turns,
25179
- head,
25180
- count: count2,
25181
- checkpoint: m.checkpoint === null ? null : decodeId(m.checkpoint)
25182
- };
25183
- if (this.turnAt(meta, count2 - 1) !== head || indexed && this.position(meta, head) !== count2 - 1 || meta.checkpoint && !this.contains(meta, meta.checkpoint))
25184
- throw new ContractError("corrupt-selected");
25185
- return meta;
25186
- }
25187
- slotPath(id, ordinal) {
25188
- return join28(this.root, "indices", decodeId(id), `${integer(ordinal, 0)}.json`);
25189
- }
25190
- turnAt(meta, ordinal) {
25191
- if (ordinal < 0 || ordinal >= meta.count)
25192
- throw new ContractError("stale");
25193
- if (ordinal < meta.turns.length)
25194
- return meta.turns[ordinal];
25195
- const row = closed(this.read(this.slotPath(meta.id, ordinal), META_BYTES), [
25196
- "conversationId",
25197
- "ordinal",
25198
- "turnId"
26035
+ "commands"
25199
26036
  ]);
25200
- if (row.conversationId !== meta.id || row.ordinal !== ordinal)
26037
+ if (o.schema !== "cadence-session-commands/1" || o.id !== id)
25201
26038
  throw new ContractError("corrupt-selected");
25202
- return decodeId(row.turnId);
25203
- }
25204
- position(meta, turnId) {
25205
- const legacy = meta.turns.indexOf(turnId);
25206
- if (legacy >= 0)
25207
- return legacy;
25208
- const value = this.read(this.path(turnId, "position.json"), META_BYTES);
26039
+ return { file, commands: list(o.commands, INDEXED_COMMANDS, decodeId) };
26040
+ }
26041
+ accepted(commandId) {
26042
+ const value = this.read(this.path(commandId, "accepted.json"));
26043
+ return value === undefined ? undefined : decodeAccepted(value);
26044
+ }
26045
+ state(commandId) {
26046
+ const live2 = this.active.get(commandId);
26047
+ if (live2)
26048
+ return live2.state;
26049
+ const path = this.path(commandId, "state.json");
26050
+ const key2 = observedFile(path);
26051
+ const hit = this.states.get(commandId);
26052
+ if (hit?.key === key2)
26053
+ return hit.state;
26054
+ const value = this.read(path);
25209
26055
  if (value === undefined)
25210
- return -1;
25211
- const row = closed(value, ["conversationId", "ordinal", "turnId"]);
25212
- if (row.turnId !== turnId)
25213
26056
  throw new ContractError("corrupt-selected");
25214
- const ordinal = integer(row.ordinal, 0);
25215
- if (row.conversationId !== meta.id || ordinal >= meta.count)
25216
- return -1;
25217
- return this.turnAt(meta, ordinal) === turnId ? ordinal : -1;
25218
- }
25219
- contains(meta, turnId) {
25220
- return this.position(meta, turnId) >= 0;
26057
+ const decoded2 = decodeState2(value);
26058
+ const state = LIVE.includes(decoded2.status) ? { ...decoded2, status: "unknown", notice: INTERRUPTED } : decoded2;
26059
+ if (this.states.size >= COMMAND_STATES)
26060
+ this.states.clear();
26061
+ this.states.set(commandId, { key: key2, state });
26062
+ return state;
25221
26063
  }
25222
- turn(id) {
25223
- const live2 = this.active.get(id);
25224
- const turn = live2?.turn ?? decodeChatTurn(this.read(this.path(id, "turn.json"), TURN_BYTES));
25225
- if (turn.id !== id)
25226
- throw new ContractError("corrupt-selected");
25227
- return !live2 && ["queued", "running"].includes(turn.status) ? {
25228
- ...turn,
25229
- status: "unknown",
25230
- notice: "Interrupted: Cadence stopped before this reply finished. Nothing was replayed; send the message again to retry."
25231
- } : turn;
26064
+ liveFor(id) {
26065
+ for (const live2 of this.active.values())
26066
+ if (live2.accepted.session === id)
26067
+ return live2;
26068
+ return;
25232
26069
  }
25233
26070
  controlBound(id) {
25234
- const path = join28(this.root, "control-links", `${decodeId(id)}.json`);
25235
- const value = this.read(path, META_BYTES);
26071
+ const value = this.read(this.controlPath(id));
25236
26072
  if (value === undefined)
25237
26073
  return false;
25238
26074
  const record2 = closed(value, ["schema", "conversationId"]);
@@ -25240,164 +26076,308 @@ class Conversations {
25240
26076
  throw new ContractError("corrupt-selected");
25241
26077
  return true;
25242
26078
  }
26079
+ controlPath(id) {
26080
+ return join31(this.legacy, "control-links", `${decodeSessionId(id)}.json`);
26081
+ }
25243
26082
  controlKey(id) {
25244
- return observedFile(join28(this.root, "control-links", `${decodeId(id)}.json`));
26083
+ return observedFile(this.controlPath(id));
25245
26084
  }
25246
26085
  bindControl(id) {
25247
26086
  if (!this.controlBound(id))
25248
- this.write(join28(this.root, "control-links", `${decodeId(id)}.json`), { schema: "cadence-conversation-control/1", conversationId: id }, META_BYTES);
26087
+ this.write(this.controlPath(id), {
26088
+ schema: "cadence-conversation-control/1",
26089
+ conversationId: id
26090
+ });
25249
26091
  }
25250
- hasTurn(id, turnId) {
25251
- const meta = this.metadata(id);
25252
- return !!meta && this.contains(meta, turnId);
26092
+ hasCommand(id, commandId) {
26093
+ return this.accepted(commandId)?.session === id;
25253
26094
  }
25254
- summary(meta) {
25255
- const head = meta.head, turn = this.turn(head);
25256
- const accepted2 = closed(this.read(this.path(head, "accepted.json"), META_BYTES), ["command", "at"]);
25257
- const command = decodeWorkbenchCommand(accepted2.command);
25258
- if (command.kind !== "send" || command.commandId !== head || command.conversationId !== meta.id || command.model.epoch !== turn.epoch)
25259
- throw new ContractError("corrupt-selected");
25260
- return {
25261
- id: meta.id,
25262
- title: meta.title,
25263
- head,
25264
- status: turn.status,
25265
- updatedAt: integer(accepted2.at, 0)
25266
- };
26095
+ latestCommand(id) {
26096
+ this.o.owner.lease.assert();
26097
+ const commandId = this.index(id).commands.at(-1);
26098
+ return commandId ? { commandId, status: this.state(commandId).status } : null;
25267
26099
  }
25268
- headKey(head, id, count2) {
25269
- return [
25270
- this.path(head, "turn.json"),
25271
- this.path(head, "accepted.json"),
25272
- this.path(head, "position.json"),
25273
- this.slotPath(id, count2 - 1)
25274
- ].map(observedFile).join("|");
25275
- }
25276
- retainedSummary(id) {
25277
- const base = [this.metadataPath(id), this.identityPath(id)].map(observedFile).join("|");
25278
- const hit = this.summaries.get(id);
25279
- if (hit && !this.active.has(hit.summary.head) && hit.key === `${base}|${this.headKey(hit.summary.head, id, hit.count)}`)
25280
- return { ...hit.summary };
25281
- const meta = this.metadata(id);
25282
- if (!meta)
25283
- throw new ContractError("corrupt-selected");
25284
- const head = meta.head;
25285
- const key2 = `${base}|${this.headKey(head, id, meta.count)}`;
25286
- const summary2 = this.summary(meta);
25287
- this.summaries.delete(id);
25288
- if (!this.active.has(head) && !["queued", "running"].includes(summary2.status)) {
25289
- if (this.summaries.size >= SUMMARY_CACHE)
25290
- this.summaries.delete(this.summaries.keys().next().value);
25291
- this.summaries.set(id, {
25292
- key: key2,
25293
- summary: { ...summary2 },
25294
- count: meta.count
25295
- });
25296
- }
25297
- return summary2;
26100
+ nativeLinks(runIds) {
26101
+ if (!runIds.length)
26102
+ return [];
26103
+ const recorded = this.sessions.nativeRuns();
26104
+ return runIds.flatMap((runId) => {
26105
+ const conversationId = recorded.get(runId);
26106
+ return conversationId ? [{ runId, conversationId }] : [];
26107
+ });
25298
26108
  }
25299
- liveSummary(live2) {
26109
+ summary(id, live2) {
26110
+ const listed = this.sessions.find(id);
26111
+ const secrets = this.readSecrets();
26112
+ if (!listed) {
26113
+ if (!live2)
26114
+ return null;
26115
+ return {
26116
+ id,
26117
+ title: live2.title,
26118
+ leaf: null,
26119
+ status: live2.state.status,
26120
+ updatedAt: live2.accepted.at,
26121
+ origin: "webui",
26122
+ live: { commandId: live2.commandId, epoch: live2.epoch }
26123
+ };
26124
+ }
26125
+ const s = listed.summary;
25300
26126
  return {
25301
- id: live2.conversationId,
25302
- title: live2.title,
25303
- head: live2.turn.id,
25304
- status: live2.turn.status,
25305
- updatedAt: live2.acceptedAt
26127
+ id,
26128
+ title: text([...sanitizeText(summaryTitle(s), secrets)].slice(0, 100).join("") || "Conversation", 512, true),
26129
+ leaf: s.leaf,
26130
+ status: live2?.state.status ?? s.stop?.status ?? "completed",
26131
+ updatedAt: Math.max(Math.trunc(listed.mtimeMs), live2?.accepted.at ?? 0),
26132
+ origin: s.webui ? "webui" : "terminal",
26133
+ ...live2 ? { live: { commandId: live2.commandId, epoch: live2.epoch } } : {}
25306
26134
  };
25307
26135
  }
25308
- list(after = null, scan) {
26136
+ list(after = null) {
25309
26137
  this.o.owner.lease.assert();
25310
- return this.history.read(after, scan);
26138
+ const listed = this.sessions.list();
26139
+ let start = 0;
26140
+ if (after) {
26141
+ start = listed.findIndex((l) => Math.trunc(l.mtimeMs) < after.updatedAt || Math.trunc(l.mtimeMs) === after.updatedAt && l.summary.id > after.id);
26142
+ if (start < 0)
26143
+ start = listed.length;
26144
+ }
26145
+ const page = listed.slice(start, start + PAGE);
26146
+ const entries2 = page.flatMap((l) => {
26147
+ const summary2 = this.summary(l.summary.id, this.liveFor(l.summary.id));
26148
+ return summary2 ? [summary2] : [];
26149
+ });
26150
+ const last = page.at(-1);
26151
+ return {
26152
+ kind: "conversations",
26153
+ entries: entries2,
26154
+ next: last && start + PAGE < listed.length ? { id: last.summary.id, updatedAt: Math.trunc(last.mtimeMs) } : null
26155
+ };
25311
26156
  }
25312
26157
  activeConversations() {
25313
26158
  this.o.owner.lease.assert();
25314
26159
  return {
25315
26160
  kind: "conversation-active",
25316
- entries: [...this.active.values()].map((live2) => this.liveSummary(live2))
26161
+ entries: [...this.active.values()].flatMap((live2) => {
26162
+ const summary2 = this.summary(live2.accepted.session, live2);
26163
+ return summary2 ? [summary2] : [];
26164
+ })
25317
26165
  };
25318
26166
  }
25319
- closeReads() {
25320
- this.history.close();
25321
- }
25322
26167
  assertSettled() {
25323
26168
  this.o.owner.lease.assert();
25324
- const path = join28(this.root, "sessions");
25325
- if (!this.files.directory(path))
26169
+ const sessions = join31(this.root, "sessions");
26170
+ if (!this.files.directory(sessions))
25326
26171
  return;
25327
- const dir = opendirSync10(path);
26172
+ const dir = opendirSync10(sessions);
25328
26173
  try {
25329
26174
  for (let e = dir.readSync();e; e = dir.readSync()) {
25330
26175
  if (!e.isFile() || !e.name.endsWith(".json"))
25331
26176
  throw new ContractError("corrupt-selected");
25332
- if (this.retainedSummary(decodeId(e.name.slice(0, -5))).status === "unknown")
26177
+ const latest = this.index(decodeSessionId(e.name.slice(0, -5))).commands.at(-1);
26178
+ if (latest && this.state(latest).status === "unknown")
25333
26179
  throw new ContractError("quarantine");
25334
26180
  }
25335
26181
  } finally {
25336
26182
  dir.closeSync();
25337
26183
  }
25338
26184
  }
25339
- view(id, before) {
26185
+ branch(id, leaf, exact) {
26186
+ const session = this.sessions.session(id);
26187
+ const running = this.liveFor(id);
26188
+ let view;
26189
+ if (exact || leaf !== null) {
26190
+ if (leaf !== null && !session?.byId.has(leaf))
26191
+ throw new ContractError("stale");
26192
+ view = leaf;
26193
+ } else
26194
+ view = running ? running.accepted.parent : session?.current() ?? null;
26195
+ const turns = session ? turnSpans(session.branch(view)) : [];
26196
+ const live2 = running && running.accepted.parent === view ? running : undefined;
26197
+ return { session, leaf: view, turns, live: live2 };
26198
+ }
26199
+ attempt(id, leaf) {
26200
+ const commandId = this.index(id).commands.at(-1);
26201
+ if (!commandId || this.active.has(commandId))
26202
+ return null;
26203
+ const accepted2 = this.accepted(commandId);
26204
+ const state = this.state(commandId);
26205
+ if (!accepted2 || state.user !== null || accepted2.parent !== leaf)
26206
+ return null;
26207
+ if (state.status === "unknown") {
26208
+ const session = this.sessions.session(id);
26209
+ if (session?.chain(accepted2.parent, accepted2.offset, accepted2.command.text).length)
26210
+ return null;
26211
+ }
26212
+ return {
26213
+ commandId,
26214
+ text: accepted2.command.text,
26215
+ status: state.status,
26216
+ notice: state.notice
26217
+ };
26218
+ }
26219
+ conversation(id, leaf, known) {
26220
+ this.o.owner.lease.assert();
26221
+ const view = this.branch(id, leaf, false);
26222
+ const summary2 = this.summary(id, view.live ?? this.liveFor(id));
26223
+ const listed = this.sessions.find(id);
26224
+ return {
26225
+ kind: "conversation",
26226
+ summary: summary2,
26227
+ leaf: view.leaf,
26228
+ continues: known === null || known === view.leaf || !!view.session?.contains(view.leaf, known),
26229
+ turns: summary2 ? view.turns.length + (view.live ? 1 : 0) : 0,
26230
+ branches: view.session?.leaves() ?? 0,
26231
+ runs: listed?.summary.runs ?? [],
26232
+ attempt: view.live ? null : this.attempt(id, view.leaf)
26233
+ };
26234
+ }
26235
+ tree(id, leaf) {
25340
26236
  this.o.owner.lease.assert();
25341
- const meta = this.metadata(id);
25342
- if (!meta) {
25343
- const live2 = before === null ? [...this.active.values()].find((turn) => turn.conversationId === id) : undefined;
26237
+ const view = this.branch(id, leaf, false);
26238
+ return {
26239
+ kind: "conversation-tree",
26240
+ conversationId: id,
26241
+ ...view.session?.tree(view.leaf, this.readSecrets()) ?? {
26242
+ nodes: [],
26243
+ truncated: false
26244
+ }
26245
+ };
26246
+ }
26247
+ overlay(id, session) {
26248
+ const out = new Map;
26249
+ for (const commandId of this.index(id).commands) {
26250
+ if (this.active.has(commandId))
26251
+ continue;
26252
+ const state = this.state(commandId);
26253
+ if (state.status === "completed" && !state.notice)
26254
+ continue;
26255
+ let user = state.user;
26256
+ if (user === null && state.status === "unknown" && session) {
26257
+ const accepted2 = this.accepted(commandId);
26258
+ user = accepted2 ? session.chain(accepted2.parent, accepted2.offset, accepted2.command.text)[0]?.id ?? null : null;
26259
+ }
26260
+ if (user !== null)
26261
+ out.set(user, state);
26262
+ }
26263
+ return out;
26264
+ }
26265
+ built(id, leaf, ordinal) {
26266
+ const view = this.branch(id, leaf, true);
26267
+ const secrets = this.readSecrets();
26268
+ if (ordinal < view.turns.length && view.session) {
26269
+ const turn2 = this.sessions.turn(view.session, view.turns[ordinal], secrets);
26270
+ const recorded = this.overlay(id, view.session).get(turn2.id);
25344
26271
  return {
25345
- kind: "conversation",
25346
- summary: live2 ? this.liveSummary(live2) : null,
25347
- turns: live2 ? [
25348
- {
25349
- ...structuredClone(live2.turn),
25350
- notice: [
25351
- "Current metadata unavailable; showing the active turn only. No state was reconstructed.",
25352
- live2.turn.notice
25353
- ].filter(Boolean).join(`
25354
- `)
26272
+ turn: recorded ? {
26273
+ ...turn2,
26274
+ status: turn2.status === "completed" ? recorded.status : turn2.status,
26275
+ notice: turn2.notice || recorded.notice,
26276
+ omitted: {
26277
+ thinking: turn2.omitted.thinking || recorded.omitted.thinking,
26278
+ media: turn2.omitted.media || recorded.omitted.media,
26279
+ other: turn2.omitted.other || recorded.omitted.other
25355
26280
  }
25356
- ] : [],
25357
- before: null
26281
+ } : turn2,
26282
+ stable: turn2.steps.length
25358
26283
  };
25359
26284
  }
25360
- let end = before === null ? meta.count : this.position(meta, before);
25361
- if (end < 0)
26285
+ const live2 = view.live;
26286
+ if (!live2 || ordinal !== view.turns.length)
25362
26287
  throw new ContractError("stale");
25363
- const turns = [];
25364
- let bytes = 0;
25365
- while (end > 0 && turns.length < 20) {
25366
- const turn = this.turn(this.turnAt(meta, end - 1)), size2 = Buffer.byteLength(canonicalJson(turn, TURN_BYTES));
25367
- if (bytes + size2 > 400 * 1024)
25368
- break;
25369
- bytes += size2;
25370
- turns.unshift(structuredClone(turn));
25371
- --end;
25372
- }
26288
+ const chain = view.session ? view.session.chain(live2.accepted.parent, live2.accepted.offset, live2.accepted.command.text) : [];
26289
+ const written = turnItems(chain, secrets);
26290
+ const items = chain.length ? written.items : [
26291
+ {
26292
+ id: "user",
26293
+ role: "user",
26294
+ text: live2.accepted.command.text,
26295
+ name: "",
26296
+ args: "",
26297
+ error: false
26298
+ }
26299
+ ];
26300
+ const extended = live2.capture?.extend(items) ?? {
26301
+ items,
26302
+ stable: items.length
26303
+ };
26304
+ const omitted2 = live2.capture?.omitted;
26305
+ const turn = listTurn({
26306
+ id: chain[0]?.id ?? live2.commandId,
26307
+ entry: null,
26308
+ at: live2.accepted.at,
26309
+ status: live2.state.status,
26310
+ notice: live2.capture?.notice ?? "",
26311
+ omitted: {
26312
+ thinking: written.omitted.thinking || !!omitted2?.thinking,
26313
+ media: written.omitted.media || !!omitted2?.media,
26314
+ other: written.omitted.other || !!omitted2?.other
26315
+ },
26316
+ items: extended.items
26317
+ });
26318
+ return { turn, stable: extended.stable };
26319
+ }
26320
+ turnSteps(id, leaf, ordinal, before) {
26321
+ this.o.owner.lease.assert();
26322
+ const { turn, stable } = this.built(id, leaf, ordinal);
26323
+ const end = before ?? turn.steps.length;
26324
+ if (end > turn.steps.length)
26325
+ throw new ContractError("stale");
26326
+ const start = Math.max(0, end - STEP_READ);
25373
26327
  return {
25374
- kind: "conversation",
25375
- summary: this.summary(meta),
25376
- turns,
25377
- before: end > 0 ? turns[0].id : null
26328
+ kind: "conversation-turn",
26329
+ conversationId: id,
26330
+ leaf,
26331
+ ordinal,
26332
+ turn: {
26333
+ id: turn.id,
26334
+ status: turn.status,
26335
+ notice: turn.notice,
26336
+ omitted: { ...turn.omitted },
26337
+ steps: turn.steps.length,
26338
+ stable,
26339
+ entry: turn.entry,
26340
+ at: turn.at
26341
+ },
26342
+ start,
26343
+ steps: turn.steps.slice(start, end)
25378
26344
  };
25379
26345
  }
25380
- transcript(id, turnId, page) {
26346
+ step(id, leaf, turnId, step, part) {
25381
26347
  this.o.owner.lease.assert();
25382
- if (!this.hasTurn(id, turnId))
25383
- throw new ContractError("invalid");
25384
- const turn = this.turn(turnId);
25385
- if (!turn.transcript || page >= turn.transcript.pages)
26348
+ const view = this.branch(id, leaf, true);
26349
+ const ordinal = view.turns.findIndex((turn2) => turn2[0]?.id === turnId);
26350
+ const { turn } = this.built(id, leaf, ordinal >= 0 ? ordinal : view.turns.length);
26351
+ if (turn.id !== turnId)
26352
+ throw new ContractError("stale");
26353
+ const item = turn.parts[step]?.[part];
26354
+ if (!item || part >= turn.steps[step].parts)
25386
26355
  throw new ContractError("stale");
25387
- const record2 = closed(this.read(this.path(turnId, `transcript/${page}.json`), TRANSCRIPT_PAGE_BYTES), ["turnId", "page", "items"]);
25388
- if (record2.turnId !== turnId || record2.page !== page)
25389
- throw new ContractError("corrupt-selected");
25390
26356
  return {
25391
- kind: "conversation-transcript",
26357
+ kind: "conversation-step",
25392
26358
  conversationId: id,
25393
- page,
25394
- turn: decodeChatTurn({ ...turn, items: record2.items })
26359
+ leaf,
26360
+ turnId,
26361
+ step,
26362
+ part,
26363
+ item
26364
+ };
26365
+ }
26366
+ origin(taskId2) {
26367
+ this.o.owner.lease.assert();
26368
+ const value = this.read(join31(this.legacy, "task-links", `${decodeId(taskId2)}.json`));
26369
+ if (value === undefined)
26370
+ return { kind: "task-origin", taskId: taskId2, conversationId: null };
26371
+ const row = closed(value, ["conversationId"]);
26372
+ return {
26373
+ kind: "task-origin",
26374
+ taskId: taskId2,
26375
+ conversationId: decodeSessionId(row.conversationId)
25395
26376
  };
25396
26377
  }
25397
26378
  attempted(conversationId, commandId) {
25398
26379
  this.o.owner.lease.assert();
25399
- const meta = this.metadata(conversationId);
25400
- return this.active.has(commandId) || this.files.directory(dirname19(this.path(commandId, "accepted.json"))) || !!meta && this.contains(meta, commandId) || !meta && !!this.files.read(this.identityPath(conversationId), META_BYTES);
26380
+ return this.active.has(commandId) || this.files.directory(dirname20(this.path(commandId, "accepted.json"))) || this.index(conversationId).commands.includes(commandId);
25401
26381
  }
25402
26382
  command(input, reply) {
25403
26383
  return {
@@ -25407,11 +26387,10 @@ class Conversations {
25407
26387
  }
25408
26388
  receipt(input, reply = false) {
25409
26389
  this.o.owner.lease.assert();
25410
- const prior = this.read(this.path(input.commandId, "accepted.json"), META_BYTES);
25411
- if (prior === undefined)
26390
+ const prior = this.accepted(input.commandId);
26391
+ if (!prior)
25412
26392
  return;
25413
- const saved = closed(prior, ["command", "at"]);
25414
- if (canonicalJson(saved.command) !== canonicalJson(this.command(input, reply)))
26393
+ if (canonicalJson(prior.command) !== canonicalJson(this.command(input, reply)))
25415
26394
  throw new ContractError("conflict");
25416
26395
  return { kind: "accepted", commandId: input.commandId };
25417
26396
  }
@@ -25421,7 +26400,7 @@ class Conversations {
25421
26400
  const receipt = this.receipt(input, !!control?.reply);
25422
26401
  if (receipt)
25423
26402
  return receipt;
25424
- if (this.files.directory(dirname19(this.path(input.commandId, "accepted.json"))))
26403
+ if (this.files.directory(dirname20(this.path(input.commandId, "state.json"))))
25425
26404
  throw new ContractError("corrupt-selected");
25426
26405
  if (this.o.owner.state !== "idle")
25427
26406
  throw new ContractError("quarantine");
@@ -25432,85 +26411,59 @@ class Conversations {
25432
26411
  this.o.models.assertCurrent(choice.selected);
25433
26412
  if (!this.currentDirectory())
25434
26413
  throw new ContractError("stale");
25435
- const beforeMeta = this.files.read(this.metadataPath(input.conversationId), META_BYTES);
25436
- const meta = this.metadata(input.conversationId);
25437
- this.files.assert(this.metadataPath(input.conversationId), beforeMeta, META_BYTES);
25438
- if (!meta && this.files.read(this.identityPath(input.conversationId), META_BYTES))
25439
- throw new ContractError("corrupt-selected");
25440
- if ((meta?.head ?? null) !== input.head)
25441
- throw new ContractError("stale");
25442
- if (meta && this.turn(input.head).status !== "completed" && (!control || ["queued", "running", "unknown"].includes(this.turn(input.head).status)))
26414
+ if (this.liveFor(input.conversationId))
25443
26415
  throw new ContractError("conflict");
25444
- if (this.active.size >= 8 || meta && !Number.isSafeInteger(meta.count + 1))
26416
+ const index = this.index(input.conversationId);
26417
+ const session = this.sessions.session(input.conversationId);
26418
+ if (input.head !== null && !session?.byId.has(input.head))
26419
+ throw new ContractError("stale");
26420
+ if (this.active.size >= 8)
25445
26421
  throw new ContractError("capacity");
25446
26422
  if (!input.text.trim())
25447
26423
  throw new ContractError("invalid");
25448
26424
  const space = statfsSync2(this.o.coordination.directory);
25449
26425
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
25450
26426
  throw new ContractError("capacity");
25451
- const turn = {
25452
- id: input.commandId,
25453
- epoch: input.model.epoch,
25454
- status: "queued",
25455
- notice: "",
25456
- omitted: { thinking: false, media: false, other: false },
25457
- items: [
25458
- {
25459
- id: "user",
25460
- role: "user",
25461
- text: command.text,
25462
- name: "",
25463
- args: "",
25464
- error: false
25465
- }
25466
- ]
25467
- };
25468
- const next = meta ?? {
25469
- id: input.conversationId,
25470
- title: [...command.text.trim()].slice(0, 100).join("") || "Conversation",
25471
- turns: [],
25472
- head: turn.id,
25473
- count: 0,
25474
- checkpoint: null
26427
+ const listed = session ? this.sessions.find(input.conversationId) : undefined;
26428
+ const accepted2 = {
26429
+ command,
26430
+ at: Date.now(),
26431
+ session: input.conversationId,
26432
+ parent: input.head,
26433
+ offset: session?.read?.size ?? 0
25475
26434
  };
25476
- const previous = next.checkpoint ? this.path(next.checkpoint, "context.json") : null;
25477
- const previousFile = previous ? this.files.read(previous, CONTEXT_BYTES) : undefined;
25478
- if (previous && !previousFile)
25479
- throw new ContractError("corrupt-selected");
25480
26435
  const abort = new AbortController;
25481
26436
  let begin;
25482
- const ready2 = new Promise((resolve10) => {
25483
- begin = resolve10;
26437
+ const ready2 = new Promise((resolve11) => {
26438
+ begin = resolve11;
25484
26439
  });
25485
- const original = ready2.then(() => this.run(command, turn, previous, previousFile, next, abort, control));
25486
26440
  const live2 = {
25487
- turn,
26441
+ accepted: accepted2,
26442
+ commandId: input.commandId,
26443
+ epoch: input.model.epoch,
26444
+ title: listed ? summaryTitle(listed.summary) : [...command.text.trim()].slice(0, 100).join("") || "Conversation",
26445
+ state: {
26446
+ status: "queued",
26447
+ notice: "",
26448
+ omitted: { thinking: false, media: false, other: false },
26449
+ user: null
26450
+ },
26451
+ stateFile: null,
26452
+ capture: null,
25488
26453
  abort,
25489
- original,
25490
- conversationId: next.id,
25491
- title: next.title,
25492
- acceptedAt: Date.now(),
25493
- turnFile: null,
25494
- metaFile: null
26454
+ original: ready2.then(() => this.run(live2, control))
25495
26455
  };
25496
26456
  beforeAccept?.();
25497
- this.active.set(turn.id, live2);
25498
- this.o.owner.trackConversation(original, () => abort.abort());
26457
+ this.active.set(input.commandId, live2);
26458
+ this.o.owner.trackConversation(live2.original, () => abort.abort());
25499
26459
  try {
25500
- if (!meta)
25501
- this.write(this.identityPath(next.id), { schema: "cadence-conversation/1", id: next.id, cwd: this.cwd }, META_BYTES);
25502
- this.write(this.path(turn.id, "accepted.json"), { command, at: live2.acceptedAt }, META_BYTES);
25503
- live2.turnFile = this.write(this.path(turn.id, "turn.json"), turn, TURN_BYTES);
25504
- const position2 = {
25505
- conversationId: next.id,
25506
- ordinal: next.count,
25507
- turnId: turn.id
25508
- };
25509
- this.write(this.slotPath(next.id, next.count), position2, META_BYTES);
25510
- this.write(this.path(turn.id, "position.json"), position2, META_BYTES);
25511
- next.head = turn.id;
25512
- next.count++;
25513
- live2.metaFile = this.write(this.metadataPath(next.id), next, META_BYTES, beforeMeta);
26460
+ this.write(this.path(input.commandId, "accepted.json"), accepted2);
26461
+ live2.stateFile = this.write(this.path(input.commandId, "state.json"), live2.state);
26462
+ this.write(this.indexPath(input.conversationId), {
26463
+ schema: "cadence-session-commands/1",
26464
+ id: input.conversationId,
26465
+ commands: [...index.commands, input.commandId].slice(-INDEXED_COMMANDS)
26466
+ }, META_BYTES2, index.file);
25514
26467
  control?.accept();
25515
26468
  } catch (error) {
25516
26469
  abort.abort();
@@ -25518,38 +26471,23 @@ class Conversations {
25518
26471
  throw error;
25519
26472
  }
25520
26473
  begin();
25521
- return { kind: "accepted", commandId: turn.id };
25522
- }
25523
- origin(taskId2) {
25524
- this.o.owner.lease.assert();
25525
- const value = this.read(join28(this.root, "task-links", `${decodeId(taskId2)}.json`), META_BYTES);
25526
- if (value === undefined)
25527
- return { kind: "task-origin", taskId: taskId2, conversationId: null };
25528
- const row = closed(value, ["conversationId"]);
25529
- return {
25530
- kind: "task-origin",
25531
- taskId: taskId2,
25532
- conversationId: decodeId(row.conversationId)
25533
- };
26474
+ return { kind: "accepted", commandId: input.commandId };
25534
26475
  }
25535
26476
  interrupt(id, turnId, epoch) {
25536
26477
  this.o.owner.lease.assert();
25537
26478
  const live2 = this.active.get(turnId);
25538
26479
  if (live2) {
25539
- if (live2.conversationId !== id || live2.turn.epoch !== epoch)
26480
+ if (live2.accepted.session !== id || live2.epoch !== epoch)
25540
26481
  throw new ContractError("stale");
25541
26482
  live2.abort.abort();
25542
26483
  return;
25543
26484
  }
25544
- const meta = this.metadata(id);
25545
- if (!meta || !this.contains(meta, turnId))
26485
+ if (!this.hasCommand(id, turnId))
25546
26486
  throw new ContractError("invalid");
25547
- if (this.turn(turnId).epoch !== epoch)
25548
- throw new ContractError("stale");
25549
- this.active.get(turnId)?.abort.abort();
25550
26487
  }
25551
- async run(command, turn, previous, previousFile, meta, abort, control) {
25552
- let transcript;
26488
+ async run(live2, control) {
26489
+ const { accepted: accepted2, abort, state } = live2;
26490
+ const commandId = live2.commandId;
25553
26491
  let barrier;
25554
26492
  let authSettled;
25555
26493
  let uncertain = false;
@@ -25569,42 +26507,35 @@ class Conversations {
25569
26507
  omissions: ["gap"]
25570
26508
  }
25571
26509
  };
25572
- const live2 = this.active.get(turn.id);
25573
26510
  const save = () => {
25574
- if (!live2?.turnFile)
26511
+ if (!live2.stateFile)
25575
26512
  throw new ContractError("corrupt-selected");
25576
- live2.turnFile = this.write(this.path(turn.id, "turn.json"), turn, TURN_BYTES, live2.turnFile);
25577
- };
25578
- const current2 = () => {
25579
- if (abort.signal.aborted || this.o.owner.state !== "idle" || !this.currentDirectory())
25580
- return false;
25581
- if (previous)
25582
- this.files.assert(previous, previousFile, CONTEXT_BYTES);
25583
- return true;
26513
+ live2.stateFile = this.write(this.path(commandId, "state.json"), state, META_BYTES2, live2.stateFile);
25584
26514
  };
26515
+ const current2 = () => !abort.signal.aborted && this.o.owner.state === "idle" && this.currentDirectory();
25585
26516
  try {
25586
26517
  if (!current2())
25587
26518
  throw new ContractError("stale");
25588
26519
  if (control?.reply) {
25589
- turn.status = "completed";
25590
- turn.notice = control.reply;
26520
+ state.status = "completed";
26521
+ state.notice = control.reply;
25591
26522
  return { status: "settled" };
25592
26523
  }
25593
26524
  if (!control) {
25594
- barrier = await this.o.gate.acquire(turn.id, abort.signal);
26525
+ barrier = await this.o.gate.acquire(commandId, abort.signal);
25595
26526
  barrier.assertHeld();
25596
26527
  }
25597
26528
  if (!current2())
25598
26529
  throw new ContractError("stale");
25599
26530
  const choice = this.o.choice.snapshot(), selected2 = choice.selected;
25600
- if (!selected2 || command.model.epoch !== choice.version.epoch || command.model.configRev !== choice.version.configRev || command.model.catalogId !== choice.version.catalogId)
26531
+ if (!selected2 || accepted2.command.model.epoch !== choice.version.epoch || accepted2.command.model.configRev !== choice.version.configRev || accepted2.command.model.catalogId !== choice.version.catalogId)
25601
26532
  throw new ContractError("stale");
25602
26533
  const request3 = decodeWorkerPublicRequest({
25603
26534
  protocol: 2,
25604
- taskId: meta.id,
26535
+ taskId: randomUUID19(),
25605
26536
  taskKind: control ? "research" : "code",
25606
- runId: turn.id,
25607
- childRunId: randomUUID20(),
26537
+ runId: commandId,
26538
+ childRunId: randomUUID19(),
25608
26539
  assignmentId: "conversation",
25609
26540
  purpose: control ? "research" : "edit",
25610
26541
  model: selected2,
@@ -25614,62 +26545,51 @@ class Conversations {
25614
26545
  },
25615
26546
  context: "",
25616
26547
  instructions: control?.instructions ?? "Ordinary conversation.",
25617
- prompt: command.text,
26548
+ prompt: accepted2.command.text,
25618
26549
  handoff: { graphRevision: 1, inputs: [] }
25619
26550
  });
25620
26551
  const auth = this.o.models.prepareTracked({
25621
26552
  request: request3,
25622
- operationId: randomUUID20(),
25623
- epoch: turn.epoch,
26553
+ operationId: randomUUID19(),
26554
+ epoch: live2.epoch,
25624
26555
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
25625
26556
  signal: abort.signal,
25626
26557
  current: current2,
25627
26558
  journal: {
25628
- preparation: (value) => this.write(this.path(turn.id, "auth-intent.json"), value, META_BYTES),
25629
- settlement: (value) => this.write(this.path(turn.id, "auth-settled.json"), value, META_BYTES)
26559
+ preparation: (value) => this.write(this.path(commandId, "auth-intent.json"), value),
26560
+ settlement: (value) => this.write(this.path(commandId, "auth-settled.json"), value)
25630
26561
  }
25631
26562
  });
25632
26563
  authSettled = auth.settled;
25633
26564
  const prepared = await auth.result;
25634
26565
  if (prepared.status !== "prepared" || !current2())
25635
26566
  throw new ContractError("auth-unavailable");
25636
- turn.status = "running";
26567
+ state.status = "running";
25637
26568
  save();
25638
- this.write(this.path(turn.id, "launch.json"), { epoch: turn.epoch, childRunId: request3.childRunId }, META_BYTES);
25639
- let credentials = [];
25640
- let checkpoint = false, contextCount = 0;
25641
- let contextHead = null;
25642
- transcript = new ConversationTranscript(turn, (page) => {
25643
- const space = statfsSync2(this.o.coordination.directory);
25644
- if (space.bavail * space.bsize - TRANSCRIPT_PAGE_BYTES < LIMITS.freeSpaceFloorBytes)
25645
- throw new ContractError("capacity");
25646
- this.write(this.path(turn.id, `transcript/${page.page}.json`), page, TRANSCRIPT_PAGE_BYTES);
26569
+ this.write(this.path(commandId, "launch.json"), {
26570
+ epoch: live2.epoch,
26571
+ childRunId: request3.childRunId
25647
26572
  });
25648
- const capture = new ConversationCapture(turn, save, () => [...this.o.secrets(), ...credentials], transcript);
26573
+ let credentials = [];
26574
+ const capture = new LiveCapture(() => [
26575
+ ...this.readSecrets(),
26576
+ ...credentials
26577
+ ]);
26578
+ live2.capture = capture;
26579
+ const existing = this.sessions.find(accepted2.session);
25649
26580
  const running = Promise.resolve().then(() => launchConversation(prepared.prepared, {
25650
- previous,
26581
+ session: {
26582
+ id: accepted2.session,
26583
+ dir: this.sessions.directory,
26584
+ file: existing?.path ?? null,
26585
+ head: accepted2.parent
26586
+ },
25651
26587
  agentDir: this.o.agentDir,
25652
26588
  ...control ? { coordinator: true } : {}
25653
26589
  }, abort.signal, {
25654
26590
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
25655
26591
  ownerSecrets: this.o.secrets,
25656
26592
  onCoordinator: control?.onTool,
25657
- onContext: (message) => {
25658
- const space = statfsSync2(this.o.coordination.directory);
25659
- if (space.bavail * space.bsize - CONTEXT_RECORD_BYTES < LIMITS.freeSpaceFloorBytes)
25660
- throw new ContractError("capacity");
25661
- const file = this.write(this.path(turn.id, `context-${contextCount}.json`), {
25662
- schema: "cadence-conversation-message/1",
25663
- index: contextCount,
25664
- previous: contextHead,
25665
- message
25666
- }, CONTEXT_RECORD_BYTES);
25667
- contextHead = file.identity;
25668
- contextCount++;
25669
- },
25670
- onContextEnd: () => {
25671
- checkpoint = true;
25672
- },
25673
26593
  maySignal: () => {
25674
26594
  try {
25675
26595
  this.o.owner.lease.assert();
@@ -25690,39 +26610,29 @@ class Conversations {
25690
26610
  this.o.owner.trackConversationProcess(tracked, () => abort.abort());
25691
26611
  const result = await running;
25692
26612
  uncertain = !result.closed;
25693
- turn.status = result.outcome;
25694
- if (result.outcome === "completed") {
25695
- if (!checkpoint)
25696
- throw new ContractError("corrupt-selected");
25697
- this.write(this.path(turn.id, "context.json"), {
25698
- schema: "cadence-conversation-context/2",
25699
- messages: contextCount,
25700
- head: contextHead
25701
- }, CONTEXT_BYTES);
25702
- meta.checkpoint = turn.id;
25703
- if (!live2?.metaFile)
25704
- throw new ContractError("corrupt-selected");
25705
- live2.metaFile = this.write(this.metadataPath(meta.id), meta, META_BYTES, live2.metaFile);
25706
- }
26613
+ state.status = result.outcome;
25707
26614
  } catch (error) {
25708
26615
  uncertain ||= this.o.owner.state === "quarantined";
25709
- turn.status = uncertain ? "unknown" : abort.signal.aborted ? "canceled" : "failed";
25710
- turn.notice ||= error instanceof ContractError ? error.code : "Conversation failed.";
26616
+ state.status = uncertain ? "unknown" : abort.signal.aborted ? "canceled" : "failed";
26617
+ state.notice ||= error instanceof ContractError ? error.code : "Conversation failed.";
25711
26618
  } finally {
25712
26619
  await control?.settle();
25713
26620
  await authSettled;
25714
26621
  uncertain ||= this.o.owner.state === "quarantined";
25715
26622
  if (uncertain)
25716
- turn.status = "unknown";
26623
+ state.status = "unknown";
25717
26624
  try {
25718
- this.write(this.path(turn.id, "native.json"), native, META_BYTES);
25719
- transcript?.finish();
25720
- if (turn.status !== "completed")
25721
- turn.notice = [
25722
- turn.notice,
25723
- control ? "Incomplete work is not replayed. A new explicit message may continue from the last complete checkpoint." : "Start a new conversation; incomplete context is not replayed."
25724
- ].filter(Boolean).join(`
25725
- `);
26625
+ this.write(this.path(commandId, "native.json"), native);
26626
+ if (live2.capture) {
26627
+ if (state.status !== "completed")
26628
+ state.notice ||= live2.capture.notice;
26629
+ state.omitted = { ...live2.capture.omitted };
26630
+ }
26631
+ try {
26632
+ state.user = this.sessions.session(accepted2.session)?.chain(accepted2.parent, accepted2.offset, accepted2.command.text)[0]?.id ?? null;
26633
+ } catch {
26634
+ state.user = null;
26635
+ }
25726
26636
  save();
25727
26637
  } catch {
25728
26638
  uncertain = true;
@@ -25731,7 +26641,7 @@ class Conversations {
25731
26641
  this.o.owner.quarantine();
25732
26642
  else if (this.o.owner.state === "idle")
25733
26643
  barrier?.release();
25734
- this.active.delete(turn.id);
26644
+ this.active.delete(commandId);
25735
26645
  }
25736
26646
  return { status: uncertain ? "uncertain" : "settled" };
25737
26647
  }
@@ -25790,10 +26700,10 @@ class ConversationWorkflow {
25790
26700
  grants = new Map;
25791
26701
  constructor(o) {
25792
26702
  this.o = o;
25793
- this.root = join29(o.coordination.directory, "conversation-workflows-v1");
26703
+ this.root = join32(o.coordination.directory, "conversation-workflows-v1");
25794
26704
  }
25795
26705
  path(id) {
25796
- return join29(this.root, decodeId(id), "state.json");
26706
+ return join32(this.root, decodeSessionId(id), "state.json");
25797
26707
  }
25798
26708
  read(id) {
25799
26709
  this.o.owner.lease.assert();
@@ -25802,7 +26712,7 @@ class ConversationWorkflow {
25802
26712
  const bound = this.o.conversations.controlBound(id);
25803
26713
  const file = this.o.coordination.files.read(path, BYTES);
25804
26714
  if (!file)
25805
- return bound || this.o.coordination.files.directory(dirname20(path)) ? unusable2(id) : { state: fresh2(id) };
26715
+ return bound || this.o.coordination.files.directory(dirname21(path)) ? unusable2(id) : { state: fresh2(id) };
25806
26716
  const record2 = closed(parseWireJson(file.bytes.toString("utf8"), BYTES), [
25807
26717
  "schema",
25808
26718
  "state"
@@ -25810,7 +26720,7 @@ class ConversationWorkflow {
25810
26720
  const state = decodeCadenceConversation(record2.state);
25811
26721
  if (record2.schema !== SCHEMA || !bound || state.id !== id || state.notice !== undefined)
25812
26722
  return unusable2(id);
25813
- if (state.head && !this.o.conversations.hasTurn(id, state.head))
26723
+ if (state.head && !this.o.conversations.hasCommand(id, state.head))
25814
26724
  return {
25815
26725
  state: { ...state, proposal: null, notice: UNRECORDED },
25816
26726
  problem: true
@@ -25898,7 +26808,7 @@ class ConversationWorkflow {
25898
26808
  return loaded.state;
25899
26809
  }
25900
26810
  runLink(runId) {
25901
- return join29(this.o.coordination.directory, "conversations-v1", "workflow-links", `${decodeId(runId)}.json`);
26811
+ return join32(this.o.coordination.directory, "conversations-v1", "workflow-links", `${decodeId(runId)}.json`);
25902
26812
  }
25903
26813
  links(runIds) {
25904
26814
  this.o.owner.lease.assert();
@@ -25914,7 +26824,7 @@ class ConversationWorkflow {
25914
26824
  ]);
25915
26825
  if (row.runId !== runId)
25916
26826
  continue;
25917
- const conversationId = decodeId(row.conversationId);
26827
+ const conversationId = decodeSessionId(row.conversationId);
25918
26828
  if (this.observe(conversationId).notice)
25919
26829
  continue;
25920
26830
  links.push({ runId, conversationId });
@@ -25935,7 +26845,7 @@ class ConversationWorkflow {
25935
26845
  ++seen;
25936
26846
  let id;
25937
26847
  try {
25938
- id = decodeId(e.name);
26848
+ id = decodeSessionId(e.name);
25939
26849
  } catch {
25940
26850
  continue;
25941
26851
  }
@@ -25981,14 +26891,14 @@ class ConversationWorkflow {
25981
26891
  } catch {}
25982
26892
  }
25983
26893
  preview(run2, bytes, steps) {
25984
- const clip = (value, maximum) => diagnosticText(value, maximum, this.o.secrets());
26894
+ const clip2 = (value, maximum) => diagnosticText(value, maximum, this.o.secrets());
25985
26895
  return {
25986
26896
  ...run2,
25987
- goal: clip(run2.goal, 320),
25988
- notice: clip(run2.notice, 512),
26897
+ goal: clip2(run2.goal, 320),
26898
+ notice: clip2(run2.notice, 512),
25989
26899
  stepsOmitted: Math.max(0, run2.steps.length - steps),
25990
26900
  steps: run2.steps.slice(-steps).map((s) => {
25991
- const text2 = clip(s.text, bytes);
26901
+ const text2 = clip2(s.text, bytes);
25992
26902
  return { ...s, text: text2, truncated: s.truncated || text2 !== s.text };
25993
26903
  })
25994
26904
  };
@@ -26097,7 +27007,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26097
27007
  }
26098
27008
  let published;
26099
27009
  try {
26100
- published = this.o.workflows.command(randomUUID21(), epoch, {
27010
+ published = this.o.workflows.command(randomUUID20(), epoch, {
26101
27011
  action: "propose",
26102
27012
  plan,
26103
27013
  model
@@ -26141,7 +27051,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26141
27051
  const busy = this.o.workflows.activeRuns().runs.filter((r) => r.phase !== "research").map((r) => r.id);
26142
27052
  if (busy.length)
26143
27053
  return refusal3("checkout-busy", `An approved workflow (${busy.join(", ")}) is using this checkout. New investigations start only after it settles; meanwhile discuss recorded evidence or use cadence_status. Nothing was started.`);
26144
- const id = randomUUID21(), conversationId = current2.state.id;
27054
+ const id = randomUUID20(), conversationId = current2.state.id;
26145
27055
  try {
26146
27056
  this.o.workflows.command(id, epoch, {
26147
27057
  action: "research",
@@ -26165,7 +27075,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26165
27075
  }, current2.file);
26166
27076
  const cancel = () => {
26167
27077
  try {
26168
- this.o.workflows.command(randomUUID21(), epoch, {
27078
+ this.o.workflows.command(randomUUID20(), epoch, {
26169
27079
  action: "cancel",
26170
27080
  runId: id
26171
27081
  });
@@ -26184,7 +27094,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26184
27094
  approval(c, caller) {
26185
27095
  if (!caller)
26186
27096
  throw new ContractError("forbidden");
26187
- const evidence = join29(this.root, decodeId(c.conversationId), "approvals", `${decodeId(c.commandId)}.json`);
27097
+ const evidence = join32(this.root, decodeSessionId(c.conversationId), "approvals", `${decodeId(c.commandId)}.json`);
26188
27098
  let effects = true;
26189
27099
  try {
26190
27100
  effects = this.o.owner.state !== "idle";
@@ -26226,8 +27136,8 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26226
27136
  }
26227
27137
  decide(c, caller, evidence, recording) {
26228
27138
  const { state, file } = this.usable(c.conversationId);
26229
- const view = this.o.conversations.view(c.conversationId, null);
26230
- if (!state.enabled || c.revision !== state.revision || !state.proposal || state.proposal.id !== c.proposalId || state.proposal.digest !== c.digest || view.kind !== "conversation" || view.summary?.head !== state.head || ["queued", "running", "unknown"].includes(view.summary.status) || this.active.has(c.conversationId))
27139
+ const latest = this.o.conversations.latestCommand(c.conversationId);
27140
+ if (!state.enabled || c.revision !== state.revision || !state.proposal || state.proposal.id !== c.proposalId || state.proposal.digest !== c.digest || !latest || latest.commandId !== state.head || ["queued", "running", "unknown"].includes(latest.status) || this.active.has(c.conversationId))
26231
27141
  throw new ContractError("stale");
26232
27142
  const epoch = this.o.owner.lease.registration.epoch;
26233
27143
  if (c.kind === "cadence-prepare") {
@@ -26243,7 +27153,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26243
27153
  });
26244
27154
  if (prepared.kind !== "workflow" || prepared.response.type !== "grant")
26245
27155
  throw new ContractError("unavailable");
26246
- const g = prepared.response, grant2 = randomUUID21();
27156
+ const g = prepared.response, grant2 = randomUUID20();
26247
27157
  this.grants.set(grant2, {
26248
27158
  caller: canonicalJson(caller),
26249
27159
  revision: c.revision,
@@ -26308,28 +27218,28 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26308
27218
  }
26309
27219
 
26310
27220
  // src/service/workflows.ts
26311
- import { randomUUID as randomUUID23 } from "node:crypto";
27221
+ import { randomUUID as randomUUID22 } from "node:crypto";
26312
27222
  import {
26313
- lstatSync as lstatSync21,
27223
+ lstatSync as lstatSync22,
26314
27224
  opendirSync as opendirSync13,
26315
27225
  realpathSync as realpathSync12,
26316
27226
  rmdirSync,
26317
27227
  statfsSync as statfsSync3,
26318
27228
  writeFileSync as writeFileSync5
26319
27229
  } from "node:fs";
26320
- import { basename as basename3, dirname as dirname22, join as join32, resolve as resolve11 } from "node:path";
27230
+ import { basename as basename3, dirname as dirname23, join as join35, resolve as resolve12 } from "node:path";
26321
27231
  import { fileURLToPath as fileURLToPath6 } from "node:url";
26322
27232
 
26323
27233
  // src/task-diff.ts
26324
27234
  import { spawnSync as spawnSync5 } from "node:child_process";
26325
- import { createHash as createHash24 } from "node:crypto";
26326
- import { lstatSync as lstatSync18, readdirSync as readdirSync3, readlinkSync } from "node:fs";
26327
- import { join as join30, relative as relative8 } from "node:path";
27235
+ import { createHash as createHash26 } from "node:crypto";
27236
+ import { lstatSync as lstatSync19, readdirSync as readdirSync4, readlinkSync } from "node:fs";
27237
+ import { join as join33, relative as relative8 } from "node:path";
26328
27238
  var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
26329
27239
  var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
26330
27240
  function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
26331
27241
  const deadline = Date.now() + 3000;
26332
- const hash3 = createHash24("sha256");
27242
+ const hash3 = createHash26("sha256");
26333
27243
  const parts = [];
26334
27244
  let complete = true;
26335
27245
  const limits = [];
@@ -26367,8 +27277,8 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
26367
27277
  return;
26368
27278
  }
26369
27279
  try {
26370
- const path = join30(root, name);
26371
- const st = lstatSync18(path);
27280
+ const path = join33(root, name);
27281
+ const st = lstatSync19(path);
26372
27282
  add(name, `${st.mode}:${st.size}`);
26373
27283
  if (st.isSymbolicLink()) {
26374
27284
  add(name, readlinkSync(path));
@@ -26387,7 +27297,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
26387
27297
  fileBytes += data2.length;
26388
27298
  add(name, data2);
26389
27299
  const binary = data2.includes(0);
26390
- parts.push(`${name} (${binary ? "binary" : "text"}, ${data2.length} bytes, sha256 ${createHash24("sha256").update(data2).digest("hex")})`);
27300
+ parts.push(`${name} (${binary ? "binary" : "text"}, ${data2.length} bytes, sha256 ${createHash26("sha256").update(data2).digest("hex")})`);
26391
27301
  } catch {
26392
27302
  complete = false;
26393
27303
  limits.push(`Unreadable/changing: ${name}`);
@@ -26502,13 +27412,13 @@ ${data2.toString("utf8")}`);
26502
27412
  }
26503
27413
  let names2;
26504
27414
  try {
26505
- names2 = readdirSync3(dir).sort();
27415
+ names2 = readdirSync4(dir).sort();
26506
27416
  } catch {
26507
27417
  complete = false;
26508
27418
  return;
26509
27419
  }
26510
27420
  for (const name of names2) {
26511
- const path = join30(dir, name);
27421
+ const path = join33(dir, name);
26512
27422
  const rel = relative8(root, path).split("\\").join("/");
26513
27423
  if (rel === ".git" || admin(rel))
26514
27424
  continue;
@@ -26517,7 +27427,7 @@ ${data2.toString("utf8")}`);
26517
27427
  break;
26518
27428
  }
26519
27429
  try {
26520
- const st = lstatSync18(path);
27430
+ const st = lstatSync19(path);
26521
27431
  if (st.isDirectory())
26522
27432
  walk(path, depth + 1);
26523
27433
  else
@@ -26542,22 +27452,142 @@ ${data2.toString("utf8")}`);
26542
27452
  return { fingerprint: hash3.digest("hex"), text: text2, complete, git: isGit };
26543
27453
  }
26544
27454
 
27455
+ // src/service/turn-capture.ts
27456
+ var TURN_BYTES = 384 * 1024;
27457
+ var OMITTED_FLAG2 = {
27458
+ "hidden-thinking": "thinking",
27459
+ binary: "media",
27460
+ unsupported: "other"
27461
+ };
27462
+
27463
+ class TurnCapture {
27464
+ turn;
27465
+ save;
27466
+ secrets;
27467
+ details = new Map;
27468
+ messageText = new Map;
27469
+ constructor(turn, save, secrets) {
27470
+ this.turn = turn;
27471
+ this.save = save;
27472
+ this.secrets = secrets;
27473
+ }
27474
+ item(id, role3) {
27475
+ let item = this.turn.items.find((i) => i.id === id);
27476
+ if (!item) {
27477
+ if (this.turn.items.length >= 256)
27478
+ throw new ContractError("capacity");
27479
+ item = { id, role: role3, text: "", name: "", args: "", error: false };
27480
+ this.turn.items.push(item);
27481
+ try {
27482
+ canonicalJson(this.turn, TURN_BYTES - 2048);
27483
+ } catch (error) {
27484
+ this.turn.items.pop();
27485
+ this.turn.notice = "Conversation capture limit exceeded.";
27486
+ throw error;
27487
+ }
27488
+ }
27489
+ return item;
27490
+ }
27491
+ update(item, field, value, maximum, bytes = Buffer.byteLength(value)) {
27492
+ const before = item[field];
27493
+ try {
27494
+ if (bytes > maximum)
27495
+ throw new ContractError("capacity");
27496
+ item[field] = value;
27497
+ canonicalJson(this.turn, TURN_BYTES - 2048);
27498
+ } catch (error) {
27499
+ item[field] = before;
27500
+ this.turn.notice = "Conversation capture limit exceeded.";
27501
+ throw error;
27502
+ }
27503
+ }
27504
+ accept(frame) {
27505
+ const e = frame.event;
27506
+ if (e.kind === "detail-begin") {
27507
+ if (e.descriptor.owner.kind === "context" || e.descriptor.owner.kind === "handoff")
27508
+ return;
27509
+ if (this.details.size >= 64)
27510
+ throw new ContractError("capacity");
27511
+ this.details.set(e.detailId, {
27512
+ descriptor: e.descriptor,
27513
+ sanitizer: new DetailSanitizer(e.descriptor.encoding, this.secrets()),
27514
+ text: "",
27515
+ bytes: 0
27516
+ });
27517
+ } else if (e.kind === "detail-chunk" || e.kind === "detail-end") {
27518
+ const d = this.details.get(e.detailId);
27519
+ if (!d)
27520
+ return;
27521
+ const added = e.kind === "detail-chunk" ? d.sanitizer.write(e.text) : d.sanitizer.end();
27522
+ d.text += added;
27523
+ d.bytes += Buffer.byteLength(added);
27524
+ if (d.bytes > 256 * 1024)
27525
+ throw new ContractError("capacity");
27526
+ const o = d.descriptor.owner;
27527
+ if (o.kind === "message") {
27528
+ const role3 = this.turn.items.find((i) => i.id === o.messageId)?.role;
27529
+ if (role3 === "assistant" && o.stage === "stream") {
27530
+ this.messageText.set(o.blockId, {
27531
+ messageId: o.messageId,
27532
+ text: d.text,
27533
+ bytes: d.bytes
27534
+ });
27535
+ const blocks = [...this.messageText.values()].filter((block) => block.messageId === o.messageId);
27536
+ this.update(this.item(o.messageId, "assistant"), "text", blocks.map((block) => block.text).join(""), 256 * 1024, blocks.reduce((size2, block) => size2 + block.bytes, 0));
27537
+ }
27538
+ } else if (o.kind === "message-final") {
27539
+ const item = this.turn.items.find((i) => i.id === o.messageId);
27540
+ if (item?.role === "assistant")
27541
+ this.update(item, "text", d.text, 256 * 1024, d.bytes);
27542
+ } else if (o.kind === "tool") {
27543
+ const item = this.item(o.callId, "tool");
27544
+ if (o.stage === "execution-arguments" || o.stage === "arguments-final")
27545
+ this.update(item, "args", d.text, 64 * 1024, d.bytes);
27546
+ if (o.stage === "result" || o.stage === "update-snapshot")
27547
+ this.update(item, "text", d.text, 256 * 1024, d.bytes);
27548
+ }
27549
+ if (e.kind === "detail-end")
27550
+ this.details.delete(e.detailId);
27551
+ } else if (e.kind === "message-start" && e.role === "assistant") {
27552
+ this.item(e.messageId, "assistant");
27553
+ } else if (e.kind === "tool-start" || e.kind === "tool-end") {
27554
+ const item = this.item(e.callId, "tool");
27555
+ this.update(item, "name", sanitizeText(e.name, this.secrets()), 128);
27556
+ if (e.kind === "tool-end")
27557
+ item.error = e.isError;
27558
+ } else if (e.kind === "worker-failure")
27559
+ this.turn.notice = `worker-failure: ${e.code}`;
27560
+ else if (e.kind === "omitted-block" && e.block.owner.kind !== "context" && e.block.owner.kind !== "handoff")
27561
+ this.turn.omitted[OMITTED_FLAG2[e.block.reason]] = true;
27562
+ if ([...this.details.values()].reduce((size2, detail) => size2 + detail.bytes + detail.sanitizer.retainedBytes, 0) > TURN_BYTES)
27563
+ throw new ContractError("capacity");
27564
+ canonicalJson(this.turn, TURN_BYTES);
27565
+ if (e.kind === "message-end") {
27566
+ for (const [id, block] of this.messageText)
27567
+ if (block.messageId === e.messageId)
27568
+ this.messageText.delete(id);
27569
+ }
27570
+ if (e.kind === "message-end" || e.kind === "tool-end")
27571
+ this.save();
27572
+ }
27573
+ }
27574
+
26545
27575
  // src/service/workflow-git.ts
26546
27576
  import { spawn as spawn4, spawnSync as spawnSync6 } from "node:child_process";
26547
- import { createHash as createHash25 } from "node:crypto";
27577
+ import { createHash as createHash27 } from "node:crypto";
26548
27578
  import {
26549
- closeSync as closeSync9,
26550
- constants as constants8,
26551
- fstatSync as fstatSync6,
26552
- lstatSync as lstatSync19,
26553
- openSync as openSync9,
26554
- readdirSync as readdirSync4,
27579
+ closeSync as closeSync12,
27580
+ constants as constants10,
27581
+ fstatSync as fstatSync8,
27582
+ lstatSync as lstatSync20,
27583
+ openSync as openSync12,
27584
+ readdirSync as readdirSync5,
26555
27585
  readlinkSync as readlinkSync2,
26556
- readSync as readSync5,
27586
+ readSync as readSync7,
26557
27587
  realpathSync as realpathSync11
26558
27588
  } from "node:fs";
26559
27589
  import { lstat, open as open2, readdir, readlink } from "node:fs/promises";
26560
- import { dirname as dirname21, isAbsolute as isAbsolute10, join as join31, relative as relative9, resolve as resolve10, sep as sep7 } from "node:path";
27590
+ import { dirname as dirname22, isAbsolute as isAbsolute11, join as join34, relative as relative9, resolve as resolve11, sep as sep7 } from "node:path";
26561
27591
  var NAMES_BYTES = 64 * 1024 * 1024;
26562
27592
  var SYNC_MS = 30000;
26563
27593
  var READ_MS = 120000;
@@ -26643,19 +27673,19 @@ async function gitHead(cwd) {
26643
27673
  }
26644
27674
  function contains2(root, path) {
26645
27675
  const within = relative9(root, path);
26646
- return !within || !within.startsWith(`..${sep7}`) && within !== ".." && !isAbsolute10(within);
27676
+ return !within || !within.startsWith(`..${sep7}`) && within !== ".." && !isAbsolute11(within);
26647
27677
  }
26648
27678
  function nested(a, b) {
26649
27679
  return contains2(a, b) || contains2(b, a);
26650
27680
  }
26651
27681
  function safeWorkflowFile(cwd, name) {
26652
27682
  workflowPath(name);
26653
- const p = resolve10(cwd, name);
27683
+ const p = resolve11(cwd, name);
26654
27684
  if (relative9(cwd, p).startsWith(".."))
26655
27685
  throw new ContractError("forbidden");
26656
- safeDirectory(dirname21(p));
27686
+ safeDirectory(dirname22(p));
26657
27687
  try {
26658
- const st = lstatSync19(p);
27688
+ const st = lstatSync20(p);
26659
27689
  if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
26660
27690
  throw new ContractError("forbidden");
26661
27691
  } catch (e) {
@@ -26666,12 +27696,12 @@ function safeWorkflowFile(cwd, name) {
26666
27696
  }
26667
27697
  function declaredTarget(cwd, name) {
26668
27698
  workflowPath(name);
26669
- const p = resolve10(cwd, name);
27699
+ const p = resolve11(cwd, name);
26670
27700
  if (relative9(cwd, p).startsWith(".."))
26671
27701
  throw new ContractError("forbidden");
26672
- safeDirectory(dirname21(p));
27702
+ safeDirectory(dirname22(p));
26673
27703
  try {
26674
- const st = lstatSync19(p);
27704
+ const st = lstatSync20(p);
26675
27705
  if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory() || st.isFile() && st.nlink !== 1)
26676
27706
  throw new ContractError("forbidden");
26677
27707
  } catch (e) {
@@ -26697,21 +27727,21 @@ function fileIdentity(p, st, hashBytes) {
26697
27727
  return quick;
26698
27728
  let fd;
26699
27729
  try {
26700
- fd = openSync9(p, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
27730
+ fd = openSync12(p, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0));
26701
27731
  } catch (e) {
26702
27732
  if (absent2(e))
26703
27733
  return null;
26704
27734
  throw e;
26705
27735
  }
26706
27736
  try {
26707
- if (!fstatSync6(fd).isFile())
27737
+ if (!fstatSync8(fd).isFile())
26708
27738
  throw new ContractError("stale");
26709
- const digest = createHash25("sha256"), buffer = Buffer.alloc(CHUNK);
26710
- for (let n = readSync5(fd, buffer);n > 0; n = readSync5(fd, buffer))
27739
+ const digest = createHash27("sha256"), buffer = Buffer.alloc(CHUNK);
27740
+ for (let n = readSync7(fd, buffer);n > 0; n = readSync7(fd, buffer))
26711
27741
  digest.update(buffer.subarray(0, n));
26712
27742
  return `sha256:${digest.digest("hex")}`;
26713
27743
  } finally {
26714
- closeSync9(fd);
27744
+ closeSync12(fd);
26715
27745
  }
26716
27746
  }
26717
27747
  async function fileIdentityAsync(p, st, hashBytes) {
@@ -26722,14 +27752,14 @@ async function fileIdentityAsync(p, st, hashBytes) {
26722
27752
  return quick;
26723
27753
  let handle;
26724
27754
  try {
26725
- handle = await open2(p, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
27755
+ handle = await open2(p, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0));
26726
27756
  } catch (e) {
26727
27757
  if (absent2(e))
26728
27758
  return null;
26729
27759
  throw e;
26730
27760
  }
26731
27761
  try {
26732
- const digest = createHash25("sha256"), buffer = Buffer.alloc(CHUNK);
27762
+ const digest = createHash27("sha256"), buffer = Buffer.alloc(CHUNK);
26733
27763
  for (;; ) {
26734
27764
  const { bytesRead } = await handle.read(buffer, 0, CHUNK, null);
26735
27765
  if (!bytesRead)
@@ -26746,13 +27776,13 @@ function directoryIdentity(root, name) {
26746
27776
  const rows = [];
26747
27777
  let count2 = 0;
26748
27778
  const visit = (directory, prefix) => {
26749
- for (const entry of readdirSync4(directory).sort()) {
27779
+ for (const entry of readdirSync5(directory).sort()) {
26750
27780
  if (entry === ".git")
26751
27781
  continue;
26752
27782
  if (++count2 > DIRECTORY_ENTRIES)
26753
27783
  throw tooLarge(name);
26754
- const full = join31(directory, entry), relative10 = `${prefix}${entry}`;
26755
- const st = lstatSync19(full);
27784
+ const full = join34(directory, entry), relative10 = `${prefix}${entry}`;
27785
+ const st = lstatSync20(full);
26756
27786
  if (st.isDirectory()) {
26757
27787
  rows.push(`${relative10}/`);
26758
27788
  visit(full, `${relative10}/`);
@@ -26773,7 +27803,7 @@ async function directoryIdentityAsync(root, name) {
26773
27803
  continue;
26774
27804
  if (++count2 > DIRECTORY_ENTRIES)
26775
27805
  throw tooLarge(name);
26776
- const full = join31(directory, entry), relative10 = `${prefix}${entry}`;
27806
+ const full = join34(directory, entry), relative10 = `${prefix}${entry}`;
26777
27807
  const st = await lstat(full);
26778
27808
  if (st.isDirectory()) {
26779
27809
  rows.push(`${relative10}/`);
@@ -26787,12 +27817,12 @@ async function directoryIdentityAsync(root, name) {
26787
27817
  `))}`;
26788
27818
  }
26789
27819
  function pathIdentity(cwd, name, walk = true) {
26790
- const p = resolve10(cwd, name);
27820
+ const p = resolve11(cwd, name);
26791
27821
  if (relative9(cwd, p).startsWith(".."))
26792
27822
  throw new ContractError("forbidden");
26793
27823
  let st;
26794
27824
  try {
26795
- st = lstatSync19(p);
27825
+ st = lstatSync20(p);
26796
27826
  } catch (e) {
26797
27827
  if (absent2(e))
26798
27828
  return null;
@@ -26803,7 +27833,7 @@ function pathIdentity(cwd, name, walk = true) {
26803
27833
  return fileIdentity(p, st, HASH_BYTES);
26804
27834
  }
26805
27835
  async function pathIdentityAsync(cwd, name) {
26806
- const p = resolve10(cwd, name);
27836
+ const p = resolve11(cwd, name);
26807
27837
  if (relative9(cwd, p).startsWith(".."))
26808
27838
  throw new ContractError("forbidden");
26809
27839
  let st;
@@ -27007,20 +28037,20 @@ ${block}
27007
28037
  async function assertWorktree(root, cwd) {
27008
28038
  if (!safeDirectory(cwd))
27009
28039
  throw new ContractError("stale");
27010
- const real = (p) => realpathSync11(resolve10(p));
28040
+ const real = (p) => realpathSync11(resolve11(p));
27011
28041
  if (real((await gitText(cwd, ["rev-parse", "--show-toplevel"])).trim()) !== real(cwd))
27012
28042
  throw new ContractError("stale");
27013
- const common = async (p) => real(resolve10(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()));
28043
+ const common = async (p) => real(resolve11(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()));
27014
28044
  if (await common(root) !== await common(cwd))
27015
28045
  throw new ContractError("stale");
27016
- const marker2 = resolve10(cwd, ".git");
27017
- if (!lstatSync19(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
28046
+ const marker2 = resolve11(cwd, ".git");
28047
+ if (!lstatSync20(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
27018
28048
  throw new ContractError("stale");
27019
28049
  }
27020
28050
 
27021
28051
  // src/service/workflow-history.ts
27022
- import { randomUUID as randomUUID22 } from "node:crypto";
27023
- import { lstatSync as lstatSync20, opendirSync as opendirSync12 } from "node:fs";
28052
+ import { randomUUID as randomUUID21 } from "node:crypto";
28053
+ import { lstatSync as lstatSync21, opendirSync as opendirSync12 } from "node:fs";
27024
28054
  class WorkflowHistoryScanner {
27025
28055
  path;
27026
28056
  directory;
@@ -27031,7 +28061,7 @@ class WorkflowHistoryScanner {
27031
28061
  this.directory = directory;
27032
28062
  }
27033
28063
  incarnation() {
27034
- const st = lstatSync20(this.path, { bigint: true });
28064
+ const st = lstatSync21(this.path, { bigint: true });
27035
28065
  if (!st.isDirectory() || st.isSymbolicLink())
27036
28066
  throw new ContractError("corrupt-selected");
27037
28067
  return `${st.dev}:${st.ino}`;
@@ -27083,7 +28113,7 @@ class WorkflowHistoryScanner {
27083
28113
  if (state.ids.length > WORKFLOW_LIMITS.historyPage + 1)
27084
28114
  state.ids.pop();
27085
28115
  }
27086
- const scan = randomUUID22();
28116
+ const scan = randomUUID21();
27087
28117
  state.timer = setTimeout(() => {
27088
28118
  this.scans.delete(scan);
27089
28119
  try {
@@ -27120,8 +28150,8 @@ class WorkflowHistoryScanner {
27120
28150
 
27121
28151
  // src/service/workflows.ts
27122
28152
  var OWNER_RUNTIME = Object.freeze({
27123
- version: "2.0.29",
27124
- build: "159ebb3ba7182c899b19bd0e5349d74397c5f1bbb6ae29dc9f03848edd457b24",
28153
+ version: "2.0.31",
28154
+ build: "b2e9f553ead7bbf1508624a3e834a8654557687cf2a3a26f2aa1161843abe5eb",
27125
28155
  entry: fileURLToPath6(import.meta.url),
27126
28156
  pid: process.pid,
27127
28157
  node: process.versions.node,
@@ -27147,8 +28177,8 @@ class UnacceptedWorkflowCommand extends UnacceptedConversationCommand {
27147
28177
 
27148
28178
  class WorkflowFailure extends Error {
27149
28179
  outcome;
27150
- constructor(outcome, message) {
27151
- super(message);
28180
+ constructor(outcome, message2) {
28181
+ super(message2);
27152
28182
  this.outcome = outcome;
27153
28183
  }
27154
28184
  }
@@ -27225,7 +28255,7 @@ class WorkflowTranscript {
27225
28255
  constructor(turn, secrets) {
27226
28256
  this.turn = turn;
27227
28257
  this.secrets = secrets;
27228
- this.capture = new ConversationCapture(turn, () => {
28258
+ this.capture = new TurnCapture(turn, () => {
27229
28259
  this.pending = true;
27230
28260
  }, secrets);
27231
28261
  this.latest = { ...structuredClone(turn), items: [] };
@@ -27265,7 +28295,7 @@ class WorkflowTranscript {
27265
28295
  if (e.kind === "message-start") {
27266
28296
  if (e.role === "assistant") {
27267
28297
  this.latest = { ...structuredClone(this.latest), items: [] };
27268
- this.final = new ConversationCapture(this.latest, () => {}, this.secrets);
28298
+ this.final = new TurnCapture(this.latest, () => {}, this.secrets);
27269
28299
  }
27270
28300
  relevant = true;
27271
28301
  } else if (e.kind === "message-end")
@@ -27308,12 +28338,12 @@ class Workflows {
27308
28338
  grants = new Map;
27309
28339
  constructor(o) {
27310
28340
  this.o = o;
27311
- this.root = join32(o.coordination.directory, "workflows-v1");
28341
+ this.root = join35(o.coordination.directory, "workflows-v1");
27312
28342
  this.cwd = realpathSync12(o.coordination.store.root);
27313
- this.worktreeRoot = join32(o.coordination.stateHome, "cadence-worktrees-v1", basename3(o.coordination.store.privateRoot));
27314
- this.historyScanner = new WorkflowHistoryScanner(join32(this.root, "runs"), () => {
28343
+ this.worktreeRoot = join35(o.coordination.stateHome, "cadence-worktrees-v1", basename3(o.coordination.store.privateRoot));
28344
+ this.historyScanner = new WorkflowHistoryScanner(join35(this.root, "runs"), () => {
27315
28345
  this.o.owner.lease.assert();
27316
- return this.files.directory(join32(this.root, "runs"));
28346
+ return this.files.directory(join35(this.root, "runs"));
27317
28347
  });
27318
28348
  this.recover();
27319
28349
  }
@@ -27321,7 +28351,7 @@ class Workflows {
27321
28351
  return this.o.coordination.files;
27322
28352
  }
27323
28353
  path(id, name) {
27324
- return join32(this.root, "runs", decodeId(id), name);
28354
+ return join35(this.root, "runs", decodeId(id), name);
27325
28355
  }
27326
28356
  write(path, value, expected, max = RECORD_BYTES2) {
27327
28357
  this.o.owner.lease.assert();
@@ -27338,7 +28368,7 @@ class Workflows {
27338
28368
  `), 2048, this.o.secrets());
27339
28369
  }
27340
28370
  recover() {
27341
- const runs = join32(this.root, "runs");
28371
+ const runs = join35(this.root, "runs");
27342
28372
  if (!this.files.directory(runs))
27343
28373
  return;
27344
28374
  const ids = [];
@@ -27449,7 +28479,7 @@ class Workflows {
27449
28479
  };
27450
28480
  }
27451
28481
  proposal(id) {
27452
- const file = this.files.read(join32(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES2);
28482
+ const file = this.files.read(join35(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES2);
27453
28483
  if (!file)
27454
28484
  throw new ContractError("unavailable");
27455
28485
  return decodeWorkflowProposal(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
@@ -27603,8 +28633,8 @@ class Workflows {
27603
28633
  if (action === "prepare")
27604
28634
  return [...this.grants.values()].some((g) => g.commandId === id && g.expiresAt >= Date.now());
27605
28635
  if (action === "propose")
27606
- return !!this.files.read(join32(this.root, "proposals", `${id}.json`), RECORD_BYTES2);
27607
- return this.files.directory(join32(this.root, "runs", id));
28636
+ return !!this.files.read(join35(this.root, "proposals", `${id}.json`), RECORD_BYTES2);
28637
+ return this.files.directory(join35(this.root, "runs", id));
27608
28638
  }
27609
28639
  admit(commandId, epoch, r, effect) {
27610
28640
  this.current();
@@ -27633,7 +28663,7 @@ class Workflows {
27633
28663
  };
27634
28664
  if (sanitizeData(p, secrets) !== canonicalJson(p))
27635
28665
  throw new ContractError("forbidden");
27636
- const target3 = join32(this.root, "proposals", `${commandId}.json`);
28666
+ const target3 = join35(this.root, "proposals", `${commandId}.json`);
27637
28667
  const previous = this.files.read(target3, RECORD_BYTES2);
27638
28668
  if (previous) {
27639
28669
  if (previous.bytes.toString("utf8") !== canonicalJson(p))
@@ -27656,7 +28686,7 @@ class Workflows {
27656
28686
  this.grants.delete(key2);
27657
28687
  if (this.grants.size >= 16)
27658
28688
  throw new ContractError("capacity");
27659
- const grant = randomUUID23(), expiresAt = Date.now() + 120000;
28689
+ const grant = randomUUID22(), expiresAt = Date.now() + 120000;
27660
28690
  effect();
27661
28691
  this.grants.set(grant, {
27662
28692
  commandId,
@@ -27684,7 +28714,7 @@ class Workflows {
27684
28714
  throw new ContractError("conflict");
27685
28715
  return { ...this.view(commandId), commandId };
27686
28716
  }
27687
- if (this.files.directory(dirname22(acceptedPath)))
28717
+ if (this.files.directory(dirname23(acceptedPath)))
27688
28718
  throw new ContractError("quarantine");
27689
28719
  let proposal;
27690
28720
  let target2;
@@ -27734,8 +28764,8 @@ class Workflows {
27734
28764
  };
27735
28765
  const abort = new AbortController;
27736
28766
  let begin;
27737
- const ready2 = new Promise((resolve12) => {
27738
- begin = resolve12;
28767
+ const ready2 = new Promise((resolve13) => {
28768
+ begin = resolve13;
27739
28769
  });
27740
28770
  const live2 = {
27741
28771
  run: run2,
@@ -27798,7 +28828,7 @@ class Workflows {
27798
28828
  if (live2.run.steps.length >= MAX_STEPS)
27799
28829
  throw new ContractError("capacity");
27800
28830
  const s = {
27801
- id: `${clipUnits(id, STEP_UNITS)}-${randomUUID23()}`,
28831
+ id: `${clipUnits(id, STEP_UNITS)}-${randomUUID22()}`,
27802
28832
  ...childRunId ? { childRunId } : {},
27803
28833
  kind,
27804
28834
  ...childRunId ? {
@@ -27850,11 +28880,11 @@ class Workflows {
27850
28880
  stepId: s.id,
27851
28881
  result
27852
28882
  });
27853
- const shown = preview ?? (result.text || result.output);
28883
+ const shown2 = preview ?? (result.text || result.output);
27854
28884
  s.status = result.outcome;
27855
- s.text = diagnosticText(shown, s.kind === "research" ? 16384 : 1024, this.o.secrets());
28885
+ s.text = diagnosticText(shown2, s.kind === "research" ? 16384 : 1024, this.o.secrets());
27856
28886
  s.exitCode = result.exitCode;
27857
- s.truncated = result.truncated || Buffer.byteLength(shown) > Buffer.byteLength(s.text);
28887
+ s.truncated = result.truncated || Buffer.byteLength(shown2) > Buffer.byteLength(s.text);
27858
28888
  if (!result.closed)
27859
28889
  this.o.owner.quarantine();
27860
28890
  this.save(live2);
@@ -27862,12 +28892,12 @@ class Workflows {
27862
28892
  async worker(live2, cwd, id, prompt, readonly, version, roots) {
27863
28893
  this.assertRunning(live2);
27864
28894
  const model = this.model(version, true);
27865
- const role2 = loadAgentDefinitions().find((r) => r.role === (readonly ? "design-explorer" : "implementation-worker"));
27866
- if (!role2)
28895
+ const role3 = loadAgentDefinitions().find((r) => r.role === (readonly ? "design-explorer" : "implementation-worker"));
28896
+ if (!role3)
27867
28897
  throw new ContractError("unavailable");
27868
28898
  if (cwd !== this.cwd)
27869
28899
  await assertWorktree(this.cwd, cwd);
27870
- const childRunId = randomUUID23(), op = randomUUID23();
28900
+ const childRunId = randomUUID22(), op = randomUUID22();
27871
28901
  const plan = live2.proposal?.plan;
27872
28902
  const request3 = decodeWorkerPublicRequest({
27873
28903
  protocol: 2,
@@ -27878,9 +28908,9 @@ class Workflows {
27878
28908
  assignmentId: id,
27879
28909
  purpose: readonly ? "research" : "edit",
27880
28910
  model,
27881
- role: { role: role2.role, sha256: role2.sha256 },
28911
+ role: { role: role3.role, sha256: role3.sha256 },
27882
28912
  context: plan ? workflowContext(plan) : "Read applicable AGENTS.md and existing project documentation, including .cadence/project.md. Cite evidence and separate observations from assumptions.",
27883
- instructions: `${role2.content}
28913
+ instructions: `${role3.content}
27884
28914
  Read applicable AGENTS.md, existing project conventions and relevant tests before work. Do not delegate, retry, mutate Git, install dependencies, publish or deploy. Report actual work and uncertainty. Do not weaken tests to manufacture success. Worker completion is not verification.`,
27885
28915
  prompt: text(prompt, 32768, true),
27886
28916
  handoff: { graphRevision: 1, inputs: [] }
@@ -27944,7 +28974,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
27944
28974
  const running = Promise.resolve().then(() => launchWorkflowWorker(prepared.prepared, cwd, live2.abort.signal, {
27945
28975
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
27946
28976
  ownerSecrets: this.o.secrets(),
27947
- roots: roots?.length ? roots.map((p) => resolve11(cwd, p)) : [cwd],
28977
+ roots: roots?.length ? roots.map((p) => resolve12(cwd, p)) : [cwd],
27948
28978
  onLifecycle: (event) => {
27949
28979
  if (!step.timing)
27950
28980
  return;
@@ -28025,7 +29055,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28025
29055
  const shell = "check" in operation;
28026
29056
  if (cwd !== this.cwd && shell)
28027
29057
  await assertWorktree(this.cwd, cwd);
28028
- const id = randomUUID23();
29058
+ const id = randomUUID22();
28029
29059
  this.write(this.path(live2.run.id, `operations/${id}-intent.json`), {
28030
29060
  cwd,
28031
29061
  args: shell ? operation.check : operation.git
@@ -28039,7 +29069,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28039
29069
  command: shell ? process.platform === "win32" ? environment2.COMSPEC ?? "cmd.exe" : "/bin/sh" : "git",
28040
29070
  args: shell ? process.platform === "win32" ? ["/d", "/s", "/c", `"${operation.check.command}"`] : ["-c", operation.check.command] : gitArguments([
28041
29071
  "-c",
28042
- `core.hooksPath=${join32(this.root, "empty-hooks")}`,
29072
+ `core.hooksPath=${join35(this.root, "empty-hooks")}`,
28043
29073
  "-c",
28044
29074
  "commit.gpgsign=false",
28045
29075
  "-c",
@@ -28152,7 +29182,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28152
29182
  if (await gitHead(cwd) !== before)
28153
29183
  throw new ContractError("stale");
28154
29184
  }
28155
- async commit(live2, cwd, allowed, message, before, title) {
29185
+ async commit(live2, cwd, allowed, message2, before, title) {
28156
29186
  await this.unchangedHead(cwd, before);
28157
29187
  const changes = await assertWorkflowScope(cwd, allowed);
28158
29188
  if (!changes.length)
@@ -28172,7 +29202,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28172
29202
  ]);
28173
29203
  if (staged.code === 0)
28174
29204
  return null;
28175
- await git(["commit", "--no-verify", "-m", message]);
29205
+ await git(["commit", "--no-verify", "-m", message2]);
28176
29206
  const commit = await gitHead(cwd);
28177
29207
  await assertWorkflowCommit(cwd, before, commit, allowed);
28178
29208
  return commit;
@@ -28181,7 +29211,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28181
29211
  async review(live2, cwd, p) {
28182
29212
  live2.run.phase = "reviewing";
28183
29213
  this.save(live2);
28184
- const { result, step } = await this.worker(live2, cwd, `review-${randomUUID23()}`, `Independently inspect the implemented files against the approved plan and acceptance. Look for missing behavior, regressions, weakened tests and scope violations. Do not edit or run commands. Reply with exactly JSON {"approved":true|false,"summary":"...","blockingIssues":["..."]}. Automatic review is not human review.
29214
+ const { result, step } = await this.worker(live2, cwd, `review-${randomUUID22()}`, `Independently inspect the implemented files against the approved plan and acceptance. Look for missing behavior, regressions, weakened tests and scope violations. Do not edit or run commands. Reply with exactly JSON {"approved":true|false,"summary":"...","blockingIssues":["..."]}. Automatic review is not human review.
28185
29215
  Files: ${p.plan.tasks.flatMap((t) => t.writes).join(", ")}`, true, p.model);
28186
29216
  this.success(result);
28187
29217
  const verdict = reviewVerdict(result.text);
@@ -28276,7 +29306,7 @@ ${changed.map((p) => `- ${p}`).join(`
28276
29306
  publish(live2, cwd, plan, names3, changed) {
28277
29307
  for (const name of names3) {
28278
29308
  const file = safeWorkflowFile(cwd, name);
28279
- if (!safeDirectory(dirname22(file), true))
29309
+ if (!safeDirectory(dirname23(file), true))
28280
29310
  throw new ContractError("forbidden");
28281
29311
  writeFileSync5(file, this.documentBody(live2, cwd, plan, name, changed), {
28282
29312
  flag: name === ".cadence/project.md" ? "w" : "wx"
@@ -28286,17 +29316,17 @@ ${changed.map((p) => `- ${p}`).join(`
28286
29316
  worktreeHome(id) {
28287
29317
  if (nested(this.cwd, this.worktreeRoot))
28288
29318
  throw new ContractError("unsupported-context");
28289
- for (const directory of [dirname22(this.worktreeRoot), this.worktreeRoot]) {
29319
+ for (const directory of [dirname23(this.worktreeRoot), this.worktreeRoot]) {
28290
29320
  if (!safeDirectory(directory, true))
28291
29321
  throw new ContractError("forbidden");
28292
- const st = lstatSync21(directory);
29322
+ const st = lstatSync22(directory);
28293
29323
  if (process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
28294
29324
  throw new ContractError("forbidden");
28295
29325
  }
28296
- const home = join32(this.worktreeRoot, decodeId(id));
29326
+ const home = join35(this.worktreeRoot, decodeId(id));
28297
29327
  if (safeDirectory(home))
28298
29328
  throw new ContractError("conflict");
28299
- safeDirectory(join32(home, "tasks"), true);
29329
+ safeDirectory(join35(home, "tasks"), true);
28300
29330
  return home;
28301
29331
  }
28302
29332
  async merge(live2, candidate) {
@@ -28364,7 +29394,7 @@ ${result.output}`}`);
28364
29394
  } finally {
28365
29395
  this.closeStep(live2, step);
28366
29396
  }
28367
- for (const directory of [join32(home, "tasks"), home])
29397
+ for (const directory of [join35(home, "tasks"), home])
28368
29398
  try {
28369
29399
  rmdirSync(directory);
28370
29400
  } catch {}
@@ -28396,8 +29426,8 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
28396
29426
  throw new ContractError("invalid");
28397
29427
  const base = target2.head;
28398
29428
  const home = this.worktreeHome(live2.run.id);
28399
- const taskHome = join32(home, "tasks");
28400
- const integration = join32(home, "integration");
29429
+ const taskHome = join35(home, "tasks");
29430
+ const integration = join35(home, "integration");
28401
29431
  await this.gitStep(live2, this.cwd, "worktree-integration", (git) => git(["worktree", "add", "--detach", integration, base]));
28402
29432
  await assertWorktree(this.cwd, integration);
28403
29433
  await this.setup(live2, integration, plan);
@@ -28414,7 +29444,7 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
28414
29444
  live2.run.phase = "implementing";
28415
29445
  this.save(live2);
28416
29446
  const outcomes2 = await Promise.allSettled(batch.map(async (task) => {
28417
- const cwd = join32(taskHome, task.id);
29447
+ const cwd = join35(taskHome, task.id);
28418
29448
  await this.gitStep(live2, this.cwd, `worktree-${task.id}`, (git) => git(["worktree", "add", "--detach", cwd, base]));
28419
29449
  const picks2 = workflowAncestors(plan.tasks, task.id).map((dep) => commits.get(dep.id)).filter((c) => !!c);
28420
29450
  if (picks2.length)
@@ -28479,7 +29509,7 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
28479
29509
  const file = safeWorkflowFile(this.cwd, name), before = documentBefore.get(name) ?? null;
28480
29510
  if (before !== pathIdentity(this.cwd, name))
28481
29511
  throw new WorkflowRefusal("conflict", `${name} changed during the run; the generated note was not written.`);
28482
- if (!safeDirectory(dirname22(file), true))
29512
+ if (!safeDirectory(dirname23(file), true))
28483
29513
  throw new ContractError("unavailable");
28484
29514
  writeFileSync5(file, this.documentBody(live2, this.cwd, plan, name, [...live2.delivered].sort(), true), { flag: before ? "w" : "wx" });
28485
29515
  }
@@ -28581,11 +29611,17 @@ class Workbench {
28581
29611
  files;
28582
29612
  workflows;
28583
29613
  cadence;
29614
+ migration;
28584
29615
  projectRoot;
28585
29616
  opening = new Map;
28586
29617
  constructor(o) {
28587
29618
  this.o = o;
28588
29619
  this.conversations = new Conversations(o);
29620
+ this.migration = new ConversationMigration({
29621
+ ...o,
29622
+ cwd: this.conversations.cwd,
29623
+ sessions: this.conversations.sessions
29624
+ });
28589
29625
  this.workflows = new Workflows(o);
28590
29626
  this.cadence = new ConversationWorkflow({
28591
29627
  ...o,
@@ -28594,14 +29630,10 @@ class Workbench {
28594
29630
  });
28595
29631
  this.conversations.assertSettled();
28596
29632
  this.files = new WorkbenchFiles(o.cwd, [o.coordination.files.namespace, o.agentDir], o.secrets);
28597
- this.projectRoot = join33(o.coordination.files.namespace, "workbench-projects-v1");
29633
+ this.projectRoot = join36(o.coordination.files.namespace, "workbench-projects-v1");
28598
29634
  }
28599
29635
  closeReads() {
28600
- try {
28601
- this.workflows.closeHistory();
28602
- } finally {
28603
- this.conversations.closeReads();
28604
- }
29636
+ this.workflows.closeHistory();
28605
29637
  }
28606
29638
  read(value) {
28607
29639
  const request3 = decodeWorkbenchRead(value);
@@ -28611,10 +29643,10 @@ class Workbench {
28611
29643
  return { kind: request3.kind, state: this.cadence.state(request3.id) };
28612
29644
  case "workflow-active": {
28613
29645
  const active2 = this.workflows.activeRuns();
28614
- return {
28615
- ...active2,
28616
- links: this.cadence.links(active2.runs.map((run2) => run2.id))
28617
- };
29646
+ const ids = active2.runs.map((run2) => run2.id);
29647
+ const browser = this.cadence.links(ids);
29648
+ const terminal = this.conversations.nativeLinks(ids).filter((link) => !browser.some((b) => b.runId === link.runId));
29649
+ return { ...active2, links: [...browser, ...terminal] };
28618
29650
  }
28619
29651
  case "workflow-history":
28620
29652
  return this.workflows.history(request3.after, request3.scan);
@@ -28628,7 +29660,7 @@ class Workbench {
28628
29660
  return this.conversations.origin(request3.taskId);
28629
29661
  case "conversation-active":
28630
29662
  case "conversations": {
28631
- const value2 = request3.kind === "conversation-active" ? this.conversations.activeConversations() : this.conversations.list(request3.after ?? null, request3.scan);
29663
+ const value2 = request3.kind === "conversation-active" ? this.conversations.activeConversations() : this.conversations.list(request3.after ?? null);
28632
29664
  if (value2.kind !== "conversations" && value2.kind !== "conversation-active")
28633
29665
  return value2;
28634
29666
  return {
@@ -28639,10 +29671,16 @@ class Workbench {
28639
29671
  }))
28640
29672
  };
28641
29673
  }
28642
- case "conversation-transcript":
28643
- return this.conversations.transcript(request3.id, request3.turnId, request3.page);
28644
29674
  case "conversation":
28645
- return this.conversations.view(request3.id, request3.before);
29675
+ return this.conversations.conversation(request3.id, request3.leaf, request3.known);
29676
+ case "conversation-turn":
29677
+ return this.conversations.turnSteps(request3.id, request3.leaf, request3.ordinal, request3.before);
29678
+ case "conversation-step":
29679
+ return this.conversations.step(request3.id, request3.leaf, request3.turnId, request3.step, request3.part);
29680
+ case "conversation-tree":
29681
+ return this.conversations.tree(request3.id, request3.leaf);
29682
+ case "conversation-legacy":
29683
+ return { kind: request3.kind, pending: this.migration.pending() };
28646
29684
  case "files":
28647
29685
  return this.files.list(request3.path);
28648
29686
  case "file":
@@ -28698,7 +29736,7 @@ class Workbench {
28698
29736
  for (let e = directory.readSync();e; e = directory.readSync()) {
28699
29737
  if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries2.length > 128)
28700
29738
  throw new ContractError("corrupt-selected");
28701
- const saved = files.read(join33(this.projectRoot, e.name));
29739
+ const saved = files.read(join36(this.projectRoot, e.name));
28702
29740
  if (!saved)
28703
29741
  throw new ContractError("corrupt-selected");
28704
29742
  const row = closed(parseWireJson(saved.bytes.toString("utf8")), [
@@ -28751,6 +29789,15 @@ class Workbench {
28751
29789
  this.conversations.interrupt(request3.conversationId, request3.turnId, request3.epoch);
28752
29790
  return { kind: "accepted", commandId: request3.commandId };
28753
29791
  }
29792
+ if (request3.kind === "conversation-migrate") {
29793
+ if (!caller)
29794
+ throw new ContractError("forbidden");
29795
+ return {
29796
+ kind: "conversation-migrated",
29797
+ commandId: request3.commandId,
29798
+ ...this.migration.migrate()
29799
+ };
29800
+ }
28754
29801
  this.o.owner.lease.assert();
28755
29802
  if (!this.o.projectsEnabled)
28756
29803
  throw new ContractError("unsupported-context");
@@ -28767,7 +29814,7 @@ class Workbench {
28767
29814
  if (this.opening.size >= 64)
28768
29815
  throw new ContractError("capacity");
28769
29816
  const path = this.files.directory(request3.path);
28770
- const marker2 = join33(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
29817
+ const marker2 = join36(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
28771
29818
  const files = this.o.coordination.files;
28772
29819
  if (files.read(marker2))
28773
29820
  throw new ContractError("receipt-inconclusive");
@@ -28785,7 +29832,7 @@ class Workbench {
28785
29832
  }
28786
29833
  const opened = await openProjectDirectory(path, this.o.coordination.stateHome, this.o.agentDir, this.o.hostUrl);
28787
29834
  for (const root of [this.o.cwd, opened.path]) {
28788
- const entry = join33(this.projectRoot, `${hash2(root)}.json`);
29835
+ const entry = join36(this.projectRoot, `${hash2(root)}.json`);
28789
29836
  const saved = files.read(entry);
28790
29837
  if (!saved)
28791
29838
  files.create(entry, canonicalJson({ path: root }));
@@ -28815,7 +29862,7 @@ async function predecessorExited() {
28815
29862
  } catch {
28816
29863
  return;
28817
29864
  }
28818
- await new Promise((resolve12) => setTimeout(resolve12, 100));
29865
+ await new Promise((resolve13) => setTimeout(resolve13, 100));
28819
29866
  }
28820
29867
  }
28821
29868
  async function healBeforeStart(c) {
@@ -28825,8 +29872,8 @@ async function healBeforeStart(c) {
28825
29872
  if (lock.status === "blocked" || lock.status === "live")
28826
29873
  throw new ContractError("registry-locked");
28827
29874
  await registry.sweep();
28828
- const own3 = await healProject(c, { responsive: async () => true });
28829
- if (own3.status === "blocked")
29875
+ const own4 = await healProject(c, { responsive: async () => true });
29876
+ if (own4.status === "blocked")
28830
29877
  throw new ContractError("quarantine");
28831
29878
  }
28832
29879
  function legacy(store, budget, reader) {
@@ -28853,8 +29900,8 @@ function legacy(store, budget, reader) {
28853
29900
  decodeId(entry.name);
28854
29901
  if (created.has(entry.name))
28855
29902
  continue;
28856
- const path = join34(store.tasks, entry.name, "task.json");
28857
- const size2 = lstatSync22(path).size;
29903
+ const path = join37(store.tasks, entry.name, "task.json");
29904
+ const size2 = lstatSync23(path).size;
28858
29905
  if (size2 > 128 * 1024)
28859
29906
  throw new ContractError("corrupt-selected");
28860
29907
  budget.reserve(size2);
@@ -28907,7 +29954,7 @@ var processLifetime = {
28907
29954
  }
28908
29955
  };
28909
29956
  async function createServiceHost(value, sourceBuild, lifetime) {
28910
- const embedded = "70b7d387e5677a43ff0a80f82aad39684362496916c796150a4e326cd7756b65";
29957
+ const embedded = "3305384b10bb0c658565426ec2291d0237533cb9ae7aeb1d63f42ac8824b0c82";
28911
29958
  if (embedded && sourceBuild)
28912
29959
  throw new ContractError("unsupported-context");
28913
29960
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -28991,8 +30038,8 @@ async function createServiceHost(value, sourceBuild, lifetime) {
28991
30038
  let timer;
28992
30039
  await Promise.race([
28993
30040
  owner?.idle(),
28994
- new Promise((resolve12) => {
28995
- timer = setTimeout(resolve12, FAULT_SETTLE_MS);
30041
+ new Promise((resolve13) => {
30042
+ timer = setTimeout(resolve13, FAULT_SETTLE_MS);
28996
30043
  })
28997
30044
  ]);
28998
30045
  clearTimeout(timer);