@abelxiaoxing/cadence 2.0.30 → 2.0.32

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,6 +4072,19 @@ 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;
4075
4088
  var STEP_TEXT_BYTES = 16 * 1024;
4076
4089
  var TARGET_BYTES = 1024;
4077
4090
  var STEP_READ = 24;
@@ -4124,7 +4137,7 @@ function chatStep(item, parts, more = false) {
4124
4137
  }
4125
4138
  function decodeChatCursor(value) {
4126
4139
  const o = closed(value, ["id", "updatedAt"]);
4127
- return { id: decodeId(o.id), updatedAt: integer(o.updatedAt, 0) };
4140
+ return { id: decodeSessionId(o.id), updatedAt: integer(o.updatedAt, 0) };
4128
4141
  }
4129
4142
  var statuses = [
4130
4143
  "queued",
@@ -4139,27 +4152,37 @@ function decodeWorkbenchRead(v) {
4139
4152
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
4140
4153
  switch (kind) {
4141
4154
  case "conversation-turn": {
4142
- const o = closed(v, ["kind", "id", "ordinal", "before"]);
4155
+ const o = closed(v, ["kind", "id", "leaf", "ordinal", "before"]);
4143
4156
  return {
4144
4157
  kind,
4145
- id: decodeId(o.id),
4158
+ id: decodeSessionId(o.id),
4159
+ leaf: nullable(o.leaf, decodeEntryId),
4146
4160
  ordinal: integer(o.ordinal, 0),
4147
4161
  before: nullable(o.before, (b) => integer(b, 0))
4148
4162
  };
4149
4163
  }
4150
4164
  case "conversation-step": {
4151
- const o = closed(v, ["kind", "id", "turnId", "step", "part"]);
4165
+ const o = closed(v, ["kind", "id", "leaf", "turnId", "step", "part"]);
4152
4166
  return {
4153
4167
  kind,
4154
- id: decodeId(o.id),
4155
- turnId: decodeId(o.turnId),
4168
+ id: decodeSessionId(o.id),
4169
+ leaf: nullable(o.leaf, decodeEntryId),
4170
+ turnId: decodeEntryId(o.turnId),
4156
4171
  step: integer(o.step, 0),
4157
4172
  part: integer(o.part, 0)
4158
4173
  };
4159
4174
  }
4160
4175
  case "cadence-conversation": {
4161
4176
  const o = closed(v, ["kind", "id"]);
4162
- 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
+ };
4163
4186
  }
4164
4187
  case "workflow-history": {
4165
4188
  const continued = Object.hasOwn(v, "scan");
@@ -4183,19 +4206,15 @@ function decodeWorkbenchRead(v) {
4183
4206
  return { kind, id: decodeId(o.id) };
4184
4207
  }
4185
4208
  case "conversations": {
4186
- const after = Object.hasOwn(v, "after"), scan = Object.hasOwn(v, "scan");
4187
- const o = closed(v, [
4188
- "kind",
4189
- ...after ? ["after"] : [],
4190
- ...scan ? ["scan"] : []
4191
- ]);
4209
+ const after = Object.hasOwn(v, "after");
4210
+ const o = closed(v, ["kind", ...after ? ["after"] : []]);
4192
4211
  return {
4193
4212
  kind,
4194
- ...after ? { after: nullable(o.after, decodeChatCursor) } : {},
4195
- ...scan ? { scan: decodeId(o.scan) } : {}
4213
+ ...after ? { after: nullable(o.after, decodeChatCursor) } : {}
4196
4214
  };
4197
4215
  }
4198
4216
  case "conversation-active":
4217
+ case "conversation-legacy":
4199
4218
  case "projects":
4200
4219
  closed(v, ["kind"]);
4201
4220
  return { kind };
@@ -4204,8 +4223,13 @@ function decodeWorkbenchRead(v) {
4204
4223
  return { kind, taskId: decodeId(o.taskId) };
4205
4224
  }
4206
4225
  case "conversation": {
4207
- const o = closed(v, ["kind", "id"]);
4208
- return { kind, id: decodeId(o.id) };
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
+ };
4209
4233
  }
4210
4234
  default: {
4211
4235
  const o = closed(v, ["kind", "path"]);
@@ -4234,8 +4258,8 @@ function decodeWorkbenchCommand(v) {
4234
4258
  return {
4235
4259
  kind,
4236
4260
  commandId: decodeId(o2.commandId),
4237
- conversationId: decodeId(o2.conversationId),
4238
- head: nullable(o2.head, decodeId),
4261
+ conversationId: decodeSessionId(o2.conversationId),
4262
+ head: nullable(o2.head, decodeEntryId),
4239
4263
  revision: integer(o2.revision, 0)
4240
4264
  };
4241
4265
  }
@@ -4253,8 +4277,8 @@ function decodeWorkbenchCommand(v) {
4253
4277
  return {
4254
4278
  kind,
4255
4279
  commandId: decodeId(o2.commandId),
4256
- conversationId: decodeId(o2.conversationId),
4257
- head: nullable(o2.head, decodeId),
4280
+ conversationId: decodeSessionId(o2.conversationId),
4281
+ head: nullable(o2.head, decodeEntryId),
4258
4282
  text: text(o2.text, 16384, true),
4259
4283
  model: decodeChoiceVersion(o2.model),
4260
4284
  revision: integer(o2.revision, 0),
@@ -4273,7 +4297,7 @@ function decodeWorkbenchCommand(v) {
4273
4297
  const o2 = closed(v, kind === "cadence-approve" ? [...keys2, "grant"] : keys2);
4274
4298
  const base = {
4275
4299
  commandId: decodeId(o2.commandId),
4276
- conversationId: decodeId(o2.conversationId),
4300
+ conversationId: decodeSessionId(o2.conversationId),
4277
4301
  revision: integer(o2.revision, 0),
4278
4302
  proposalId: decodeId(o2.proposalId),
4279
4303
  digest: decodeHash(o2.digest)
@@ -4301,8 +4325,8 @@ function decodeWorkbenchCommand(v) {
4301
4325
  return {
4302
4326
  kind,
4303
4327
  commandId: decodeId(o2.commandId),
4304
- conversationId: decodeId(o2.conversationId),
4305
- head: nullable(o2.head, decodeId),
4328
+ conversationId: decodeSessionId(o2.conversationId),
4329
+ head: nullable(o2.head, decodeEntryId),
4306
4330
  text: text(o2.text, 16 * 1024, true),
4307
4331
  model: decodeChoiceVersion(o2.model)
4308
4332
  };
@@ -4318,11 +4342,15 @@ function decodeWorkbenchCommand(v) {
4318
4342
  return {
4319
4343
  kind,
4320
4344
  commandId: decodeId(o2.commandId),
4321
- conversationId: decodeId(o2.conversationId),
4345
+ conversationId: decodeSessionId(o2.conversationId),
4322
4346
  turnId: decodeId(o2.turnId),
4323
4347
  epoch: decodeId(o2.epoch)
4324
4348
  };
4325
4349
  }
4350
+ if (kind === "conversation-migrate") {
4351
+ const o2 = closed(v, ["kind", "commandId"]);
4352
+ return { kind, commandId: decodeId(o2.commandId) };
4353
+ }
4326
4354
  const o = closed(v, ["kind", "commandId", "path", "epoch"]);
4327
4355
  return {
4328
4356
  kind: oneOf(o.kind, ["open-project"]),
@@ -4395,18 +4423,20 @@ function decodeChatStep(v) {
4395
4423
  function decodeChatTurnHeader(v) {
4396
4424
  const o = closed(v, [
4397
4425
  "id",
4398
- "epoch",
4399
4426
  "status",
4400
4427
  "notice",
4401
4428
  "omitted",
4402
4429
  "steps",
4403
- "stable"
4430
+ "stable",
4431
+ "entry",
4432
+ "at"
4404
4433
  ]);
4405
4434
  const omitted = closed(o.omitted, ["thinking", "media", "other"]);
4406
4435
  const steps = integer(o.steps, 0);
4407
4436
  return {
4408
- id: decodeId(o.id),
4409
- epoch: decodeId(o.epoch),
4437
+ id: decodeEntryId(o.id),
4438
+ entry: nullable(o.entry, decodeEntryId),
4439
+ at: integer(o.at, 0),
4410
4440
  status: oneOf(o.status, statuses),
4411
4441
  notice: text(o.notice, 1024),
4412
4442
  omitted: {
@@ -4419,22 +4449,52 @@ function decodeChatTurnHeader(v) {
4419
4449
  };
4420
4450
  }
4421
4451
  function decodeChatSummary(v) {
4422
- const modern = v !== null && typeof v === "object" && Object.hasOwn(v, "cadence");
4452
+ const has = (key) => v !== null && typeof v === "object" && Object.hasOwn(v, key);
4423
4453
  const o = closed(v, [
4424
4454
  "id",
4425
4455
  "title",
4426
- "head",
4456
+ "leaf",
4427
4457
  "status",
4428
4458
  "updatedAt",
4429
- ...modern ? ["cadence"] : []
4459
+ "origin",
4460
+ ...has("cadence") ? ["cadence"] : [],
4461
+ ...has("live") ? ["live"] : []
4430
4462
  ]);
4463
+ const live = has("live") ? closed(o.live, ["commandId", "epoch"]) : null;
4431
4464
  return {
4432
- id: decodeId(o.id),
4465
+ id: decodeSessionId(o.id),
4433
4466
  title: text(o.title, 512, true),
4434
- head: decodeId(o.head),
4467
+ leaf: nullable(o.leaf, decodeEntryId),
4435
4468
  status: oneOf(o.status, statuses),
4436
4469
  updatedAt: integer(o.updatedAt, 0),
4437
- ...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)
4438
4498
  };
4439
4499
  }
4440
4500
  function decodeWorkbenchResult(v) {
@@ -4483,7 +4543,7 @@ function decodeWorkbenchResult(v) {
4483
4543
  const l = closed(value, ["runId", "conversationId"]);
4484
4544
  return {
4485
4545
  runId: decodeId(l.runId),
4486
- conversationId: decodeId(l.conversationId)
4546
+ conversationId: decodeSessionId(l.conversationId)
4487
4547
  };
4488
4548
  }) : [];
4489
4549
  if (new Set(links.map((l) => l.runId)).size !== links.length || links.some((l) => !runs.some((r) => r.id === l.runId)))
@@ -4522,15 +4582,7 @@ function decodeWorkbenchResult(v) {
4522
4582
  return {
4523
4583
  kind,
4524
4584
  taskId: decodeId(o2.taskId),
4525
- conversationId: nullable(o2.conversationId, decodeId)
4526
- };
4527
- }
4528
- if (kind === "conversations-progress") {
4529
- const o2 = closed(v, ["kind", "after", "scan"]);
4530
- return {
4531
- kind,
4532
- after: nullable(o2.after, decodeChatCursor),
4533
- scan: decodeId(o2.scan)
4585
+ conversationId: nullable(o2.conversationId, decodeSessionId)
4534
4586
  };
4535
4587
  }
4536
4588
  if (kind === "conversation-active") {
@@ -4538,25 +4590,65 @@ function decodeWorkbenchResult(v) {
4538
4590
  return { kind, entries: list(o2.entries, 8, decodeChatSummary) };
4539
4591
  }
4540
4592
  if (kind === "conversations") {
4541
- const paged = Object.hasOwn(v, "next");
4542
- const o2 = closed(v, ["kind", "entries", ...paged ? ["next"] : []]);
4593
+ const o2 = closed(v, ["kind", "entries", "next"]);
4543
4594
  return {
4544
4595
  kind,
4545
4596
  entries: list(o2.entries, 200, decodeChatSummary),
4546
- ...paged ? { next: nullable(o2.next, decodeChatCursor) } : {}
4597
+ next: nullable(o2.next, decodeChatCursor)
4547
4598
  };
4548
4599
  }
4549
4600
  if (kind === "conversation") {
4550
- const o2 = closed(v, ["kind", "summary", "turns"]);
4601
+ const o2 = closed(v, [
4602
+ "kind",
4603
+ "summary",
4604
+ "leaf",
4605
+ "continues",
4606
+ "turns",
4607
+ "branches",
4608
+ "runs",
4609
+ "attempt"
4610
+ ]);
4551
4611
  const summary = nullable(o2.summary, decodeChatSummary), turns = integer(o2.turns, 0);
4552
4612
  if (!summary && turns)
4553
4613
  throw new ContractError("invalid");
4554
- return { kind, summary, turns };
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
+ };
4555
4646
  }
4556
4647
  if (kind === "conversation-turn") {
4557
4648
  const o2 = closed(v, [
4558
4649
  "kind",
4559
4650
  "conversationId",
4651
+ "leaf",
4560
4652
  "ordinal",
4561
4653
  "turn",
4562
4654
  "start",
@@ -4567,7 +4659,8 @@ function decodeWorkbenchResult(v) {
4567
4659
  throw new ContractError("invalid");
4568
4660
  return {
4569
4661
  kind,
4570
- conversationId: decodeId(o2.conversationId),
4662
+ conversationId: decodeSessionId(o2.conversationId),
4663
+ leaf: nullable(o2.leaf, decodeEntryId),
4571
4664
  ordinal: integer(o2.ordinal, 0),
4572
4665
  turn,
4573
4666
  start,
@@ -4578,6 +4671,7 @@ function decodeWorkbenchResult(v) {
4578
4671
  const o2 = closed(v, [
4579
4672
  "kind",
4580
4673
  "conversationId",
4674
+ "leaf",
4581
4675
  "turnId",
4582
4676
  "step",
4583
4677
  "part",
@@ -4585,8 +4679,9 @@ function decodeWorkbenchResult(v) {
4585
4679
  ]);
4586
4680
  return {
4587
4681
  kind,
4588
- conversationId: decodeId(o2.conversationId),
4589
- turnId: decodeId(o2.turnId),
4682
+ conversationId: decodeSessionId(o2.conversationId),
4683
+ leaf: nullable(o2.leaf, decodeEntryId),
4684
+ turnId: decodeEntryId(o2.turnId),
4590
4685
  step: integer(o2.step, 0),
4591
4686
  part: integer(o2.part, 0),
4592
4687
  item: decodeChatItem(o2.item)
@@ -5222,7 +5317,7 @@ var CONFIG_BYTES = 64 * 1024;
5222
5317
  var TOKEN_BYTES = 1024;
5223
5318
  function accessToken(value) {
5224
5319
  const result = text(value, TOKEN_BYTES, true);
5225
- if (utf8Bytes(result) < 32 || /[\p{Cc}\p{Cf}]/u.test(result))
5320
+ if (/[\p{Cc}\p{Cf}]/u.test(result))
5226
5321
  throw new ContractError("invalid");
5227
5322
  return result;
5228
5323
  }
@@ -5298,7 +5393,7 @@ function decode(source) {
5298
5393
  try {
5299
5394
  return { port: number, token: accessToken(t.value) };
5300
5395
  } catch {
5301
- 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`);
5302
5397
  }
5303
5398
  }
5304
5399
  var code = (error) => error?.code ?? "error";
@@ -6583,6 +6678,7 @@ class ServiceCoordination {
6583
6678
  "host-config.json",
6584
6679
  "history-v2",
6585
6680
  "conversations-v1",
6681
+ "conversation-commands-v1",
6586
6682
  "conversation-workflows-v1",
6587
6683
  "workflows-v1"
6588
6684
  ]);
@@ -8742,7 +8838,7 @@ function managementExitCode(result, foreground = false) {
8742
8838
  }
8743
8839
  function serverConfigHint(error) {
8744
8840
  return `Cadence changed nothing: ${error.path} ${error.reason}.
8745
- 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.
8746
8842
  `;
8747
8843
  }
8748
8844
  function registryGuidance(_workspace, stateHome) {
@@ -10491,7 +10587,7 @@ async function createGateway(value, hostUrl, source) {
10491
10587
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
10492
10588
  const web = loadWebAssets(source?.webDirectory);
10493
10589
  const build2 = {
10494
- contractHash: "d0edc9d93f682dd7c637bd28cdb756b823ad8eafeabebc63479bee1bac5b2b55",
10590
+ contractHash: "3305384b10bb0c658565426ec2291d0237533cb9ae7aeb1d63f42ac8824b0c82",
10495
10591
  assets: {
10496
10592
  sourceHash: web.manifest.sourceHash,
10497
10593
  contractHash: web.manifest.contractHash,
@@ -11174,8 +11270,8 @@ Content-Length: 0\r
11174
11270
 
11175
11271
  // src/service/host.ts
11176
11272
  import { spawn as spawn5 } from "node:child_process";
11177
- import { lstatSync as lstatSync22, opendirSync as opendirSync15 } from "node:fs";
11178
- 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";
11179
11275
  import { fileURLToPath as fileURLToPath7 } from "node:url";
11180
11276
 
11181
11277
  // src/agent-registry.ts
@@ -21875,95 +21971,6 @@ import { spawn as spawn3 } from "node:child_process";
21875
21971
  import { join as join26 } from "node:path";
21876
21972
  import { StringDecoder } from "node:string_decoder";
21877
21973
  import { fileURLToPath as fileURLToPath5 } from "node:url";
21878
-
21879
- // src/conversation-context.mjs
21880
- var CONTEXT_BYTES = 2 * 1024 * 1024;
21881
- var CONTEXT_RECORD_BYTES = LIMITS.detailBytes;
21882
- var clean = (s, secrets, max = CONTEXT_RECORD_BYTES) => sanitizeText(text(s, max), secrets);
21883
- function argumentsData(value, secrets) {
21884
- const sanitizer = new DetailSanitizer("canonical-json", secrets);
21885
- const source = sanitizer.write(canonicalJson(value, CONTEXT_RECORD_BYTES)) + sanitizer.end();
21886
- if (sanitizer.limited)
21887
- throw new Error("Unsupported context arguments");
21888
- return parseWireJson(source, CONTEXT_RECORD_BYTES);
21889
- }
21890
- function own2(value, key2) {
21891
- const d = value && typeof value === "object" ? Object.getOwnPropertyDescriptor(value, key2) : undefined;
21892
- if (!d || !("value" in d))
21893
- throw new Error("Invalid usage");
21894
- return d.value;
21895
- }
21896
- function counts(value, keys2) {
21897
- const out = Object.create(null);
21898
- for (const key2 of keys2) {
21899
- const n = own2(value, key2);
21900
- if (typeof n !== "number" || !Number.isFinite(n) || n < 0)
21901
- throw new Error("Invalid usage");
21902
- out[key2] = n;
21903
- }
21904
- return out;
21905
- }
21906
- function conversationMessages(messages, secrets = []) {
21907
- return list(messages, 4096, (message) => {
21908
- if (!message || typeof message !== "object")
21909
- throw new Error("Invalid context");
21910
- const role2 = oneOf(message.role, ["user", "assistant", "toolResult"]);
21911
- const timestamp2 = integer(message.timestamp, 0);
21912
- const content = typeof message.content === "string" ? [{ type: "text", text: clean(message.content, secrets) }] : list(message.content, 256, (block) => {
21913
- if (block.type === "text")
21914
- return { type: "text", text: clean(block.text, secrets) };
21915
- if (role2 === "assistant" && block.type === "toolCall")
21916
- return {
21917
- type: "toolCall",
21918
- id: clean(block.id, secrets, 512),
21919
- name: clean(block.name, secrets, 128),
21920
- arguments: argumentsData(block.arguments, secrets)
21921
- };
21922
- return null;
21923
- }).filter(Boolean);
21924
- if (role2 === "user")
21925
- return { role: role2, timestamp: timestamp2, content };
21926
- if (role2 === "toolResult")
21927
- return {
21928
- role: role2,
21929
- timestamp: timestamp2,
21930
- content,
21931
- toolCallId: clean(message.toolCallId, secrets, 512),
21932
- toolName: clean(message.toolName, secrets, 128),
21933
- isError: message.isError === true
21934
- };
21935
- const usage = counts(message.usage, [
21936
- "input",
21937
- "output",
21938
- "cacheRead",
21939
- "cacheWrite",
21940
- "totalTokens"
21941
- ]);
21942
- usage.cost = counts(own2(message.usage, "cost"), [
21943
- "input",
21944
- "output",
21945
- "cacheRead",
21946
- "cacheWrite",
21947
- "total"
21948
- ]);
21949
- return {
21950
- role: role2,
21951
- timestamp: timestamp2,
21952
- content,
21953
- api: clean(message.api, secrets, 128),
21954
- provider: clean(message.provider, secrets, 128),
21955
- model: clean(message.model, secrets, 256),
21956
- usage,
21957
- stopReason: oneOf(message.stopReason, [
21958
- "stop",
21959
- "length",
21960
- "toolUse",
21961
- "error",
21962
- "aborted"
21963
- ])
21964
- };
21965
- });
21966
- }
21967
21974
  // src/worker-capture.mjs
21968
21975
  import { createHash as createHash23, randomUUID as randomUUID16 } from "node:crypto";
21969
21976
  var completeCoverage = () => ({
@@ -22595,13 +22602,9 @@ function runProcess(spec) {
22595
22602
  spec.input === undefined ? "ignore" : "pipe",
22596
22603
  "pipe",
22597
22604
  "pipe",
22598
- ...spec.onContext || spec.onCoordinator ? [spec.onContext ? "pipe" : "ignore"] : [],
22599
- ...spec.onCoordinator ? ["ipc"] : []
22605
+ ...spec.onCoordinator ? ["ignore", "ipc"] : []
22600
22606
  ]
22601
22607
  });
22602
- const contextStream = spec.onContext ? child.stdio[3] : null;
22603
- let contextEnded = false, contextBytes = 0;
22604
- const contextChunks = [];
22605
22608
  let settled = false;
22606
22609
  let nativeClosed = false;
22607
22610
  let launched = false;
@@ -22637,7 +22640,7 @@ function runProcess(spec) {
22637
22640
  const stderrDecoder = new StringDecoder("utf8");
22638
22641
  let killTimer;
22639
22642
  let unknownTimer;
22640
- const clean2 = (text2, max = 65536) => diagnosticText(text2, max, spec.secrets);
22643
+ const clean = (text2, max = 65536) => diagnosticText(text2, max, spec.secrets);
22641
22644
  const finish = (closed2, exitCode, signal) => {
22642
22645
  if (settled)
22643
22646
  return;
@@ -22680,8 +22683,8 @@ function runProcess(spec) {
22680
22683
  exitCode,
22681
22684
  signal,
22682
22685
  durationMs: Date.now() - started,
22683
- 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),
22684
- 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),
22685
22688
  truncated
22686
22689
  });
22687
22690
  if (!closed2) {
@@ -22689,7 +22692,6 @@ function runProcess(spec) {
22689
22692
  child.stdout.destroy();
22690
22693
  child.stderr.destroy();
22691
22694
  child.stdin?.destroy();
22692
- contextStream?.destroy();
22693
22695
  if (child.connected)
22694
22696
  child.disconnect();
22695
22697
  }
@@ -22790,7 +22792,7 @@ function runProcess(spec) {
22790
22792
  spec.onProgress?.("Agent ready");
22791
22793
  }
22792
22794
  if (decoded2.event.kind === "tool-start")
22793
- spec.onProgress?.(clean2(`Tool: ${decoded2.event.name}`, 128));
22795
+ spec.onProgress?.(clean(`Tool: ${decoded2.event.name}`, 128));
22794
22796
  if (decoded2.event.kind === "final")
22795
22797
  final = capture.preview;
22796
22798
  if (lease) {
@@ -22830,7 +22832,7 @@ function runProcess(spec) {
22830
22832
  if (Buffer.byteLength(output) > 256 * 1024) {
22831
22833
  truncated = true;
22832
22834
  if (spec.uninterruptible)
22833
- output = clean2(output, 256 * 1024);
22835
+ output = clean(output, 256 * 1024);
22834
22836
  else
22835
22837
  stop("failed");
22836
22838
  }
@@ -22862,34 +22864,6 @@ function runProcess(spec) {
22862
22864
  }
22863
22865
  }
22864
22866
  };
22865
- contextStream?.on("data", (chunk) => {
22866
- if (settled || stopping)
22867
- return;
22868
- try {
22869
- let offset = 0;
22870
- while (offset < chunk.length) {
22871
- const end = chunk.indexOf(10, offset);
22872
- const part = chunk.subarray(offset, end < 0 ? chunk.length : end);
22873
- contextBytes += part.length;
22874
- if (contextBytes > CONTEXT_RECORD_BYTES)
22875
- throw new Error("Checkpoint record too large");
22876
- contextChunks.push(part);
22877
- if (end < 0)
22878
- break;
22879
- const source = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(contextChunks, contextBytes));
22880
- contextChunks.length = 0;
22881
- contextBytes = 0;
22882
- spec.onContext?.(source);
22883
- offset = end + 1;
22884
- }
22885
- } catch {
22886
- stop("failed");
22887
- }
22888
- });
22889
- contextStream?.once("end", () => {
22890
- contextEnded = true;
22891
- });
22892
- contextStream?.on("error", () => stop("failed"));
22893
22867
  let stdoutWork = Promise.resolve();
22894
22868
  let stderrWork = Promise.resolve();
22895
22869
  let stdoutEnded = false, stderrEnded = false;
@@ -22942,15 +22916,6 @@ function runProcess(spec) {
22942
22916
  clearTimeout(killTimer);
22943
22917
  clearTimeout(unknownTimer);
22944
22918
  const close = () => {
22945
- if (spec.onContext && !stopping && code2 === 0) {
22946
- try {
22947
- if (!contextEnded || contextBytes)
22948
- throw new Error("Context EOF missing");
22949
- spec.onContextEnd?.();
22950
- } catch {
22951
- stopping = "failed";
22952
- }
22953
- }
22954
22919
  if (!spec.protocol)
22955
22920
  output += stdoutDecoder.end();
22956
22921
  else {
@@ -23049,34 +23014,11 @@ function launchConversation(prepared, conversation, signal, options) {
23049
23014
  if (!encoded2 || encoded2.input !== input)
23050
23015
  throw new Error("Invalid chat launch");
23051
23016
  const secrets = encoded2.secrets;
23052
- let contextCount = 0, contextComplete = false;
23053
23017
  return launchEncoded(encoded2, signal, options.timeoutMs, {
23054
23018
  maySignal: options.maySignal,
23055
23019
  onNative: options.onNative,
23056
23020
  onCoordinator: options.onCoordinator,
23057
- onFrame: (frame) => options.onFrame(frame, secrets),
23058
- onContext: (source) => {
23059
- if (contextComplete)
23060
- throw new Error("Checkpoint after end");
23061
- const value = parseWireJson(source, CONTEXT_RECORD_BYTES);
23062
- if (value.schema === "cadence-conversation-stream-end/1") {
23063
- const record3 = closed(value, ["schema", "count"]);
23064
- if (record3.count !== contextCount)
23065
- throw new Error("Invalid checkpoint count");
23066
- contextComplete = true;
23067
- return;
23068
- }
23069
- const record2 = closed(value, ["schema", "message"]);
23070
- if (record2.schema !== "cadence-conversation-stream/1")
23071
- throw new Error("Invalid checkpoint");
23072
- options.onContext(conversationMessages([record2.message], [...options.ownerSecrets(), ...secrets])[0]);
23073
- contextCount++;
23074
- },
23075
- onContextEnd: () => {
23076
- if (!contextComplete)
23077
- throw new Error("Incomplete checkpoint");
23078
- options.onContextEnd();
23079
- }
23021
+ onFrame: (frame) => options.onFrame(frame, secrets)
23080
23022
  });
23081
23023
  });
23082
23024
  }
@@ -24869,366 +24811,999 @@ class ServiceOwner {
24869
24811
 
24870
24812
  // src/service/workbench.ts
24871
24813
  import { opendirSync as opendirSync14 } from "node:fs";
24872
- import { join as join33 } from "node:path";
24873
-
24874
- // src/service/conversation-workflow.ts
24875
- import { randomUUID as randomUUID21 } from "node:crypto";
24876
- import { opendirSync as opendirSync11 } from "node:fs";
24877
- import { dirname as dirname20, join as join29 } from "node:path";
24814
+ import { join as join36 } from "node:path";
24878
24815
 
24879
- // src/cadence-instructions.ts
24880
- 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.
24881
- 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.
24882
- 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.
24883
- 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.
24884
- 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.
24885
- 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";
24886
24829
 
24887
- // src/service/conversations.ts
24888
- import { randomUUID as randomUUID20 } from "node:crypto";
24889
- 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";
24890
24840
  import { dirname as dirname19, join as join28 } from "node:path";
24891
-
24892
- // src/service/conversation-history.ts
24893
- import { randomUUID as randomUUID19 } from "node:crypto";
24894
- import { lstatSync as lstatSync16, opendirSync as opendirSync9 } from "node:fs";
24895
- var CONVERSATION_PAGE = 50;
24896
- var SCAN_ENTRIES = 8;
24897
- var SCANS = 16;
24898
- var IDLE_MS = 120000;
24899
- var compareChats = (a, b) => b.updatedAt - a.updatedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
24900
-
24901
- class ConversationHistory {
24902
- path;
24903
- directory;
24904
- summary;
24905
- scans = new Map;
24906
- closed = false;
24907
- constructor(path, directory, summary2) {
24908
- this.path = path;
24909
- this.directory = directory;
24910
- this.summary = summary2;
24911
- }
24912
- incarnation() {
24913
- const st = lstatSync16(this.path, { bigint: true });
24914
- if (!st.isDirectory() || st.isSymbolicLink())
24915
- throw new ContractError("corrupt-selected");
24916
- return `${st.dev}:${st.ino}`;
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;
24917
24864
  }
24918
- read(after, cursor) {
24919
- if (this.closed)
24920
- throw new ContractError("unavailable");
24921
- let state;
24922
- if (cursor) {
24923
- const selected2 = this.scans.get(cursor);
24924
- if (!selected2 || selected2.after?.id !== after?.id || selected2.after?.updatedAt !== after?.updatedAt)
24925
- throw new ContractError("stale");
24926
- this.scans.delete(cursor);
24927
- clearTimeout(selected2.timer);
24928
- state = selected2;
24929
- } else {
24930
- if (!this.directory())
24931
- return { kind: "conversations", entries: [], next: null };
24932
- if (this.scans.size >= SCANS)
24933
- throw new ContractError("capacity");
24934
- const incarnation3 = this.incarnation();
24935
- state = {
24936
- dir: opendirSync9(this.path),
24937
- incarnation: incarnation3,
24938
- after,
24939
- entries: []
24940
- };
24941
- }
24942
- let suspended = false;
24943
- try {
24944
- if (!this.directory() || this.incarnation() !== state.incarnation)
24945
- throw new ContractError("stale");
24946
- const started = performance.now();
24947
- for (let n = 0;n < SCAN_ENTRIES; n++) {
24948
- if (n && performance.now() - started >= LIMITS.searchMs)
24949
- break;
24950
- const e = state.dir.readSync();
24951
- if (!e) {
24952
- const entries2 = state.entries.slice(0, CONVERSATION_PAGE);
24953
- const last = entries2.at(-1);
24954
- return {
24955
- kind: "conversations",
24956
- entries: entries2,
24957
- next: state.entries.length > entries2.length && last ? { id: last.id, updatedAt: last.updatedAt } : null
24958
- };
24959
- }
24960
- if (!e.isFile() || !e.name.endsWith(".json"))
24961
- throw new ContractError("corrupt-selected");
24962
- const summary2 = this.summary(decodeId(e.name.slice(0, -5)));
24963
- if (after && compareChats(summary2, after) <= 0)
24964
- continue;
24965
- if (state.entries.some((row) => row.id === summary2.id))
24966
- continue;
24967
- state.entries.push(summary2);
24968
- state.entries.sort(compareChats);
24969
- if (state.entries.length > CONVERSATION_PAGE + 1)
24970
- state.entries.pop();
24971
- }
24972
- const scan = randomUUID19();
24973
- state.timer = setTimeout(() => {
24974
- this.scans.delete(scan);
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
+ }
24981
+
24982
+ // src/session-entries.mjs
24983
+ var CADENCE_MODE_ENTRY = "cadence-conversation-mode/1";
24984
+ var WEBUI_SESSION_ENTRY = "cadence-webui/1";
24985
+
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");
24995
+ }
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;
24999
+ }
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()) {
24975
25008
  try {
24976
- state.dir.closeSync();
24977
- } catch {
24978
- this.closed = true;
24979
- }
24980
- }, IDLE_MS);
24981
- state.timer.unref();
24982
- this.scans.set(scan, state);
24983
- suspended = true;
24984
- return { kind: "conversations-progress", after, scan };
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
+ }
24985
25021
  } finally {
24986
- if (!suspended)
24987
- state.dir.closeSync();
25022
+ handle.closeSync();
24988
25023
  }
25024
+ return out;
24989
25025
  }
24990
- close() {
24991
- this.closed = true;
24992
- let failed = false;
24993
- for (const state of this.scans.values()) {
24994
- clearTimeout(state.timer);
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;
24995
25040
  try {
24996
- state.dir.closeSync();
25041
+ this.copy(conversation);
25042
+ migrated++;
24997
25043
  } catch {
24998
- failed = true;
25044
+ skipped++;
24999
25045
  }
25000
25046
  }
25001
- this.scans.clear();
25002
- if (failed)
25003
- throw new ContractError("unavailable");
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);
25102
+ try {
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
+ }
25004
25115
  }
25005
25116
  }
25006
25117
 
25007
- // src/service/conversation-steps.ts
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;
25008
25158
  var TARGET_ARGS = 1024 * 1024;
25009
- var INDEXED_TURNS = 32;
25010
- function itemStep(item) {
25011
- const step = chatStep(item, 0);
25012
- const more = step.clipped || item.role === "tool" && !!(item.args || item.text);
25013
- return { ...step, parts: more ? 1 : 0 };
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
+ }
25014
25198
  }
25015
-
25016
- class ConversationSteps {
25017
- page;
25018
- indexes = new Map;
25019
- constructor(page) {
25020
- this.page = page;
25021
- }
25022
- list(turn) {
25023
- const settled = !["queued", "running"].includes(turn.status);
25024
- if (!turn.transcript) {
25025
- const steps2 = turn.items.map((item, index2) => ({
25026
- step: itemStep(item),
25027
- source: { kind: "item", index: index2 }
25028
- }));
25029
- return { steps: steps2, stable: settled ? steps2.length : 0 };
25030
- }
25031
- const index = this.index(turn.id, turn.transcript.pages);
25032
- const steps = [
25033
- ...index.steps,
25034
- ...turn.items.filter((item) => !index.ids.has(item.id)).map((item) => ({
25035
- step: itemStep(item),
25036
- source: { kind: "preview", id: item.id }
25037
- }))
25038
- ];
25039
- return { steps, stable: settled ? steps.length : index.steps.length };
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;
25040
25206
  }
25041
- detail(turn, step, part) {
25042
- const listed = this.list(turn).steps[step];
25043
- if (!listed || part >= listed.step.parts)
25044
- throw new ContractError("stale");
25045
- const source = listed.source;
25046
- if (source.kind === "pages")
25047
- return this.page(turn.id, source.first + part);
25048
- const item = source.kind === "item" ? turn.items[source.index] : turn.items.find((i) => i.id === source.id);
25049
- if (!item)
25050
- throw new ContractError("stale");
25051
- return item;
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
+ };
25052
25224
  }
25053
- index(turnId, pages) {
25054
- let index = this.indexes.get(turnId);
25055
- this.indexes.delete(turnId);
25056
- if (!index || index.pages > pages)
25057
- index = { pages: 0, steps: [], ids: new Set, last: null };
25058
- for (;index.pages < pages; index.pages++) {
25059
- const fragment = this.page(turnId, index.pages);
25060
- const last = index.last;
25061
- const tail = index.steps.at(-1);
25062
- if (last && tail && last.item.id === fragment.id) {
25063
- const text2 = last.item.text + fragment.text, head2 = clipText(text2, STEP_TEXT_BYTES);
25064
- last.more ||= head2.length < text2.length;
25065
- last.args = last.args !== null && last.args.length + fragment.args.length <= TARGET_ARGS ? last.args + fragment.args : null;
25066
- last.item = { ...fragment, text: head2, args: last.args ?? "" };
25067
- tail.step = chatStep(last.item, tail.step.parts + 1, last.more);
25068
- continue;
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)
25258
+ break;
25259
+ read2 += n;
25069
25260
  }
25070
- const head = clipText(fragment.text, STEP_TEXT_BYTES);
25071
- index.last = {
25072
- item: { ...fragment, text: head },
25073
- more: head.length < fragment.text.length,
25074
- args: fragment.args
25075
- };
25076
- index.steps.push({
25077
- step: chatStep(index.last.item, 1, index.last.more),
25078
- source: { kind: "pages", first: index.pages }
25079
- });
25080
- index.ids.add(fragment.id);
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;
25081
25270
  }
25082
- this.indexes.set(turnId, index);
25083
- if (this.indexes.size > INDEXED_TURNS)
25084
- this.indexes.delete(this.indexes.keys().next().value);
25085
- return index;
25271
+ return { ino: st.ino, size: st.size, mtimeMs: st.mtimeMs, end, restarted };
25272
+ } finally {
25273
+ closeSync11(fd);
25086
25274
  }
25087
25275
  }
25088
-
25089
- // src/service/conversation-transcript.ts
25090
- var TRANSCRIPT_PAGE_BYTES = 384 * 1024;
25091
- var PREVIEW_BYTES = 300 * 1024;
25092
- var FIELD_CHARS = 16 * 1024;
25093
- var PREVIEW_MARK = `
25094
- [Preview only; the rest appears once this step completes.]`;
25095
- function part(value, offset, chars = FIELD_CHARS) {
25096
- let end = Math.min(value.length, offset + chars);
25097
- if (end < value.length && /[\uD800-\uDBFF]/u.test(value[end - 1]))
25098
- end--;
25099
- return value.slice(offset, end);
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: "" };
25100
25325
  }
25101
- function previewHead(head, added) {
25102
- return head.length > FIELD_CHARS ? head : head + added.slice(0, FIELD_CHARS + 1 - head.length);
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
+ }
25103
25376
  }
25104
25377
 
25105
- class ConversationTranscript {
25106
- turn;
25107
- write;
25108
- state = { pages: 0 };
25109
- workingSizes = new Map;
25110
- fieldBytes = new Map;
25111
- workingBytes = 0;
25112
- sizes = new Map;
25113
- bytes = 4096;
25114
- pending = new Map;
25115
- constructor(turn, write2) {
25116
- this.turn = turn;
25117
- this.write = write2;
25118
- turn.transcript = this.state;
25119
- for (const item of [...turn.items]) {
25120
- this.archive(item);
25121
- this.preview(item);
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;
25405
+ }
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]);
25122
25417
  }
25418
+ this.read = next;
25419
+ return this;
25123
25420
  }
25124
- item(id, role2) {
25125
- let item = this.pending.get(id);
25126
- if (!item) {
25127
- if (this.pending.size >= 256)
25128
- throw new ContractError("capacity");
25129
- item = { id, role: role2, text: "", name: "", args: "", error: false };
25130
- this.pending.set(id, item);
25131
- this.preview(item);
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);
25132
25432
  }
25133
- return item;
25433
+ return out.reverse();
25134
25434
  }
25135
- find(id) {
25136
- return this.pending.get(id);
25137
- }
25138
- preview(item, known = {}) {
25139
- if (this.pending.has(item.id)) {
25140
- const cached = this.fieldBytes.get(item.id);
25141
- const bytes = (field) => known[field]?.bytes ?? cached?.[field] ?? Buffer.byteLength(item[field]);
25142
- const fields2 = {
25143
- text: bytes("text"),
25144
- args: bytes("args"),
25145
- name: bytes("name")
25146
- };
25147
- this.fieldBytes.set(item.id, fields2);
25148
- const size3 = fields2.text + fields2.args + fields2.name;
25149
- this.workingBytes += size3 - (this.workingSizes.get(item.id) ?? 0);
25150
- this.workingSizes.set(item.id, size3);
25151
- if (this.workingBytes > 2 * LIMITS.detailBytes)
25152
- throw new ContractError("capacity");
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);
25153
25441
  }
25154
- const clip = (field) => {
25155
- const value = item[field];
25156
- const prefix = part(known[field]?.head ?? value, 0);
25157
- return prefix.length < value.length ? prefix + PREVIEW_MARK : value;
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;
25463
+ }
25464
+ return false;
25158
25465
  };
25159
- const preview = { ...item, text: clip("text"), args: clip("args") };
25160
- const size2 = Buffer.byteLength(canonicalJson(preview, PREVIEW_BYTES));
25161
- this.bytes += size2 - (this.sizes.get(item.id) ?? 0);
25162
- this.sizes.set(item.id, size2);
25163
- const at = this.turn.items.findIndex((i) => i.id === item.id);
25164
- if (at < 0)
25165
- this.turn.items.push(preview);
25166
- else
25167
- this.turn.items[at] = preview;
25168
- while (this.bytes > PREVIEW_BYTES || this.turn.items.length > 128) {
25169
- if (this.turn.items.length <= 2)
25170
- throw new ContractError("oversize");
25171
- const [removed] = this.turn.items.splice(this.turn.items[0].role === "user" ? 1 : 0, 1);
25172
- this.bytes -= this.sizes.get(removed.id) ?? 0;
25173
- this.sizes.delete(removed.id);
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));
25174
25475
  }
25476
+ return out;
25175
25477
  }
25176
- complete(id) {
25177
- const item = this.pending.get(id);
25178
- if (!item)
25179
- return;
25180
- this.preview(item);
25181
- this.archive(item);
25182
- this.pending.delete(id);
25183
- this.fieldBytes.delete(id);
25184
- this.workingBytes -= this.workingSizes.get(id) ?? 0;
25185
- this.workingSizes.delete(id);
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 };
25186
25507
  }
25187
- finish() {
25188
- for (const id of this.pending.keys())
25189
- this.complete(id);
25190
- }
25191
- archive(item) {
25192
- let text2 = 0, args = 0;
25193
- do {
25194
- let chars = 128 * 1024;
25195
- const fragment = { ...item, text: "", args: part(item.args, args) };
25196
- for (;; ) {
25197
- fragment.text = part(item.text, text2, chars);
25198
- try {
25199
- if (Buffer.byteLength(fragment.text) > 256 * 1024)
25200
- throw new ContractError("oversize");
25201
- canonicalJson(fragment, TRANSCRIPT_PAGE_BYTES - 4096);
25202
- break;
25203
- } catch (error) {
25204
- if (!(error instanceof ContractError) || error.code !== "oversize" || chars <= FIELD_CHARS)
25205
- throw error;
25206
- chars /= 2;
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(`
25568
+
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;
25207
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 };
25669
+ }
25670
+
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);
25208
25701
  }
25209
- const page = this.state.pages;
25210
- if (!Number.isSafeInteger(page + 1))
25211
- throw new ContractError("capacity");
25212
- this.write({ turnId: this.turn.id, page, items: [fragment] });
25213
- this.state.pages = page + 1;
25214
- text2 += fragment.text.length;
25215
- args += fragment.args.length;
25216
- } while (text2 < item.text.length || args < item.args.length);
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));
25707
+ }
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;
25716
+ }
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;
25731
+ }
25732
+ find(id) {
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);
25743
+ }
25744
+ session(id) {
25745
+ const listed = this.find(id);
25746
+ if (!listed)
25747
+ return;
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;
25217
25782
  }
25218
25783
  }
25784
+ function summaryTitle(summary2) {
25785
+ return summary2.name ?? summary2.firstUser ?? "Conversation";
25786
+ }
25219
25787
 
25220
25788
  // src/service/conversations.ts
25221
- var TURN_BYTES = 384 * 1024;
25222
- var META_BYTES = 64 * 1024;
25223
- 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.";
25224
25798
  var OMITTED_FLAG = {
25225
25799
  "hidden-thinking": "thinking",
25226
25800
  binary: "media",
25227
25801
  unsupported: "other"
25228
25802
  };
25803
+ var LIVE = ["queued", "running"];
25229
25804
  function observedFile(path) {
25230
25805
  try {
25231
- const s = lstatSync17(path);
25806
+ const s = lstatSync18(path);
25232
25807
  return [s.dev, s.ino, s.size, s.mode, s.nlink, s.ctimeMs, s.mtimeMs].join(":");
25233
25808
  } catch (error) {
25234
25809
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
@@ -25237,156 +25812,191 @@ function observedFile(path) {
25237
25812
  }
25238
25813
  }
25239
25814
 
25240
- class ConversationCapture {
25241
- turn;
25242
- save;
25815
+ class LiveCapture {
25243
25816
  secrets;
25244
- transcript;
25817
+ omitted = { thinking: false, media: false, other: false };
25818
+ notice = "";
25819
+ assistants = [];
25820
+ tools = [];
25245
25821
  details = new Map;
25246
- messageText = new Map;
25247
- constructor(turn, save, secrets, transcript) {
25248
- this.turn = turn;
25249
- this.save = save;
25822
+ blocks = new Map;
25823
+ constructor(secrets) {
25250
25824
  this.secrets = secrets;
25251
- this.transcript = transcript;
25252
25825
  }
25253
- item(id, role2) {
25254
- if (this.transcript)
25255
- return this.transcript.item(id, role2);
25256
- let item = this.turn.items.find((i) => i.id === id);
25257
- if (!item) {
25258
- if (this.turn.items.length >= 256)
25259
- throw new ContractError("capacity");
25260
- item = { id, role: role2, text: "", name: "", args: "", error: false };
25261
- this.turn.items.push(item);
25262
- try {
25263
- canonicalJson(this.turn, TURN_BYTES - 2048);
25264
- } catch (error) {
25265
- this.turn.items.pop();
25266
- this.turn.notice = "Conversation capture limit exceeded.";
25267
- throw error;
25268
- }
25269
- }
25270
- 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}`;
25271
25828
  }
25272
- update(item, field, value, maximum, known = { bytes: Buffer.byteLength(value), head: value }) {
25273
- const bytes = known.bytes;
25274
- if (this.transcript) {
25275
- if (bytes > LIMITS.detailBytes)
25276
- throw new ContractError("capacity");
25277
- item[field] = value;
25278
- this.transcript.preview(item, { [field]: known });
25279
- return;
25280
- }
25281
- const before = item[field];
25282
- try {
25283
- if (bytes > maximum)
25284
- throw new ContractError("capacity");
25285
- item[field] = value;
25286
- canonicalJson(this.turn, TURN_BYTES - 2048);
25287
- } catch (error) {
25288
- item[field] = before;
25289
- this.turn.notice = "Conversation capture limit exceeded.";
25290
- 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 = "";
25291
25837
  }
25838
+ return tool;
25292
25839
  }
25293
25840
  accept(frame) {
25294
25841
  const e = frame.event;
25295
- if (e.kind === "detail-begin") {
25296
- 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")
25297
25857
  return;
25298
25858
  if (this.details.size >= 64)
25299
- throw new ContractError("capacity");
25859
+ return;
25300
25860
  this.details.set(e.detailId, {
25301
25861
  descriptor: e.descriptor,
25302
25862
  sanitizer: new DetailSanitizer(e.descriptor.encoding, this.secrets()),
25303
- text: "",
25304
- bytes: 0,
25305
- head: ""
25863
+ text: ""
25306
25864
  });
25307
25865
  } else if (e.kind === "detail-chunk" || e.kind === "detail-end") {
25308
25866
  const d = this.details.get(e.detailId);
25309
25867
  if (!d)
25310
25868
  return;
25311
25869
  const added = e.kind === "detail-chunk" ? d.sanitizer.write(e.text) : d.sanitizer.end();
25312
- d.text += added;
25313
- d.bytes += Buffer.byteLength(added);
25314
- d.head = previewHead(d.head, added);
25315
- if (d.bytes > (this.transcript ? LIMITS.detailBytes : 256 * 1024))
25316
- throw new ContractError("capacity");
25870
+ if (Buffer.byteLength(d.text) <= PREVIEW_BYTES)
25871
+ d.text += added;
25317
25872
  const o = d.descriptor.owner;
25318
- if (o.kind === "message") {
25319
- const role2 = (this.transcript?.find(o.messageId) ?? this.turn.items.find((i) => i.id === o.messageId))?.role;
25320
- if (role2 === "assistant" && o.stage === "stream") {
25321
- this.messageText.set(o.blockId, {
25322
- messageId: o.messageId,
25323
- text: d.text,
25324
- bytes: d.bytes,
25325
- head: d.head
25326
- });
25327
- const blocks = [...this.messageText.values()].filter((block) => block.messageId === o.messageId);
25328
- this.update(this.item(o.messageId, "assistant"), "text", blocks.length === 1 ? blocks[0].text : blocks.map((block) => block.text).join(""), 256 * 1024, {
25329
- bytes: blocks.reduce((size2, block) => size2 + block.bytes, 0),
25330
- head: blocks.reduce((head, block) => previewHead(head, block.head), "")
25331
- });
25332
- }
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(""));
25333
25878
  } else if (o.kind === "message-final") {
25334
- const item = this.transcript?.find(o.messageId) ?? this.turn.items.find((i) => i.id === o.messageId);
25335
- if (item?.role === "assistant")
25336
- this.update(item, "text", d.text, 256 * 1024, d);
25879
+ const message2 = this.assistants.find((a) => a.id === o.messageId);
25880
+ if (message2)
25881
+ message2.text = this.bounded(d.text);
25337
25882
  } else if (o.kind === "tool") {
25338
- const item = this.item(o.callId, "tool");
25883
+ const tool = this.tool(o.callId);
25339
25884
  if (o.stage === "execution-arguments" || o.stage === "arguments-final")
25340
- this.update(item, "args", d.text, 64 * 1024, d);
25885
+ tool.args = this.bounded(d.text);
25341
25886
  if (o.stage === "result" || o.stage === "update-snapshot")
25342
- this.update(item, "text", d.text, 256 * 1024, d);
25887
+ tool.text = this.bounded(d.text);
25343
25888
  }
25344
25889
  if (e.kind === "detail-end")
25345
25890
  this.details.delete(e.detailId);
25346
- } else if (e.kind === "message-start" && e.role === "assistant") {
25347
- this.item(e.messageId, "assistant");
25348
- } else if (e.kind === "tool-start" || e.kind === "tool-end") {
25349
- const item = this.item(e.callId, "tool");
25350
- this.update(item, "name", sanitizeText(e.name, this.secrets()), 128);
25351
- if (e.kind === "tool-end")
25352
- 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);
25353
25895
  } else if (e.kind === "worker-failure")
25354
- this.turn.notice = `worker-failure: ${e.code}`;
25896
+ this.notice = `worker-failure: ${e.code}`;
25355
25897
  else if (e.kind === "omitted-block" && e.block.owner.kind !== "context" && e.block.owner.kind !== "handoff")
25356
- this.turn.omitted[OMITTED_FLAG[e.block.reason]] = true;
25357
- if ([...this.details.values()].reduce((size2, detail) => size2 + detail.bytes + detail.sanitizer.retainedBytes, 0) > (this.transcript ? 2 * LIMITS.detailBytes : TURN_BYTES))
25358
- throw new ContractError("capacity");
25359
- if (!this.transcript)
25360
- canonicalJson(this.turn, TURN_BYTES);
25361
- if (e.kind === "message-end") {
25362
- for (const [id, block] of this.messageText)
25363
- if (block.messageId === e.messageId)
25364
- this.messageText.delete(id);
25365
- }
25366
- if (e.kind === "message-end" || e.kind === "tool-end") {
25367
- this.transcript?.complete(e.kind === "message-end" ? e.messageId : e.callId);
25368
- this.save();
25369
- }
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 };
25370
25937
  }
25371
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
+ }
25372
25975
 
25373
25976
  class Conversations {
25374
25977
  o;
25375
25978
  root;
25376
- history;
25979
+ legacy;
25377
25980
  cwd;
25981
+ sessions;
25378
25982
  active = new Map;
25379
- summaries = new Map;
25380
- steps = new ConversationSteps((turnId, page) => this.page(turnId, page));
25983
+ knownSecrets;
25984
+ states = new Map;
25381
25985
  constructor(o) {
25382
25986
  this.o = o;
25383
- 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");
25384
25989
  this.cwd = realpathSync10(o.cwd);
25385
- const sessions = join28(this.root, "sessions");
25386
- this.history = new ConversationHistory(sessions, () => {
25387
- this.o.owner.lease.assert();
25388
- return this.files.directory(sessions);
25389
- }, (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;
25390
26000
  }
25391
26001
  currentDirectory() {
25392
26002
  const current2 = resolveWorkspace(this.o.cwd);
@@ -25395,20 +26005,17 @@ class Conversations {
25395
26005
  get files() {
25396
26006
  return this.o.coordination.files;
25397
26007
  }
25398
- path(id, name) {
25399
- return join28(this.root, "turns", decodeId(id), name);
25400
- }
25401
- identityPath(id) {
25402
- return join28(this.root, "identities", `${decodeId(id)}.json`);
26008
+ path(commandId, name) {
26009
+ return join31(this.root, "commands", decodeId(commandId), name);
25403
26010
  }
25404
- metadataPath(id) {
25405
- return join28(this.root, "sessions", `${decodeId(id)}.json`);
26011
+ indexPath(id) {
26012
+ return join31(this.root, "sessions", `${decodeSessionId(id)}.json`);
25406
26013
  }
25407
- read(path, max) {
26014
+ read(path, max = META_BYTES2) {
25408
26015
  const value = this.files.read(path, max);
25409
26016
  return value ? parseWireJson(value.bytes.toString("utf8"), max) : undefined;
25410
26017
  }
25411
- write(path, value, max, expected) {
26018
+ write(path, value, max = META_BYTES2, expected) {
25412
26019
  this.o.owner.lease.assert();
25413
26020
  const source = canonicalJson(value, max);
25414
26021
  try {
@@ -25418,91 +26025,50 @@ class Conversations {
25418
26025
  throw error;
25419
26026
  }
25420
26027
  }
25421
- metadata(id) {
25422
- const value = this.read(this.metadataPath(id), META_BYTES);
25423
- if (value === undefined)
25424
- return null;
25425
- 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), [
25426
26033
  "schema",
25427
26034
  "id",
25428
- "cwd"
25429
- ]);
25430
- if (identity.schema !== "cadence-conversation/1" || identity.id !== id || identity.cwd !== this.cwd)
25431
- throw new ContractError("corrupt-selected");
25432
- const indexed = value !== null && typeof value === "object" && Object.hasOwn(value, "count");
25433
- const m = closed(value, [
25434
- "id",
25435
- "title",
25436
- "turns",
25437
- "checkpoint",
25438
- ...indexed ? ["head", "count"] : []
25439
- ]);
25440
- const turns = list(m.turns, 1000, decodeId);
25441
- const count2 = indexed ? integer(m.count, Math.max(1, turns.length)) : turns.length;
25442
- const head = indexed ? decodeId(m.head) : turns.at(-1);
25443
- if (!head || !count2 || new Set(turns).size !== turns.length || m.id !== id)
25444
- throw new ContractError("corrupt-selected");
25445
- const meta = {
25446
- id,
25447
- title: text(m.title, 512, true),
25448
- turns,
25449
- head,
25450
- count: count2,
25451
- checkpoint: m.checkpoint === null ? null : decodeId(m.checkpoint)
25452
- };
25453
- if (this.turnAt(meta, count2 - 1) !== head || indexed && this.position(meta, head) !== count2 - 1 || meta.checkpoint && !this.contains(meta, meta.checkpoint))
25454
- throw new ContractError("corrupt-selected");
25455
- return meta;
25456
- }
25457
- slotPath(id, ordinal) {
25458
- return join28(this.root, "indices", decodeId(id), `${integer(ordinal, 0)}.json`);
25459
- }
25460
- turnAt(meta, ordinal) {
25461
- if (ordinal < 0 || ordinal >= meta.count)
25462
- throw new ContractError("stale");
25463
- if (ordinal < meta.turns.length)
25464
- return meta.turns[ordinal];
25465
- const row = closed(this.read(this.slotPath(meta.id, ordinal), META_BYTES), [
25466
- "conversationId",
25467
- "ordinal",
25468
- "turnId"
26035
+ "commands"
25469
26036
  ]);
25470
- if (row.conversationId !== meta.id || row.ordinal !== ordinal)
26037
+ if (o.schema !== "cadence-session-commands/1" || o.id !== id)
25471
26038
  throw new ContractError("corrupt-selected");
25472
- return decodeId(row.turnId);
25473
- }
25474
- position(meta, turnId) {
25475
- const legacy = meta.turns.indexOf(turnId);
25476
- if (legacy >= 0)
25477
- return legacy;
25478
- 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);
25479
26055
  if (value === undefined)
25480
- return -1;
25481
- const row = closed(value, ["conversationId", "ordinal", "turnId"]);
25482
- if (row.turnId !== turnId)
25483
- throw new ContractError("corrupt-selected");
25484
- const ordinal = integer(row.ordinal, 0);
25485
- if (row.conversationId !== meta.id || ordinal >= meta.count)
25486
- return -1;
25487
- return this.turnAt(meta, ordinal) === turnId ? ordinal : -1;
25488
- }
25489
- contains(meta, turnId) {
25490
- return this.position(meta, turnId) >= 0;
25491
- }
25492
- turn(id) {
25493
- const live2 = this.active.get(id);
25494
- const turn = live2?.turn ?? decodeChatTurn(this.read(this.path(id, "turn.json"), TURN_BYTES));
25495
- if (turn.id !== id)
25496
26056
  throw new ContractError("corrupt-selected");
25497
- return !live2 && ["queued", "running"].includes(turn.status) ? {
25498
- ...turn,
25499
- status: "unknown",
25500
- notice: "Interrupted: Cadence stopped before this reply finished. Nothing was replayed; send the message again to retry."
25501
- } : turn;
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;
26063
+ }
26064
+ liveFor(id) {
26065
+ for (const live2 of this.active.values())
26066
+ if (live2.accepted.session === id)
26067
+ return live2;
26068
+ return;
25502
26069
  }
25503
26070
  controlBound(id) {
25504
- const path = join28(this.root, "control-links", `${decodeId(id)}.json`);
25505
- const value = this.read(path, META_BYTES);
26071
+ const value = this.read(this.controlPath(id));
25506
26072
  if (value === undefined)
25507
26073
  return false;
25508
26074
  const record2 = closed(value, ["schema", "conversationId"]);
@@ -25510,173 +26076,308 @@ class Conversations {
25510
26076
  throw new ContractError("corrupt-selected");
25511
26077
  return true;
25512
26078
  }
26079
+ controlPath(id) {
26080
+ return join31(this.legacy, "control-links", `${decodeSessionId(id)}.json`);
26081
+ }
25513
26082
  controlKey(id) {
25514
- return observedFile(join28(this.root, "control-links", `${decodeId(id)}.json`));
26083
+ return observedFile(this.controlPath(id));
25515
26084
  }
25516
26085
  bindControl(id) {
25517
26086
  if (!this.controlBound(id))
25518
- 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
+ });
25519
26091
  }
25520
- hasTurn(id, turnId) {
25521
- const meta = this.metadata(id);
25522
- return !!meta && this.contains(meta, turnId);
26092
+ hasCommand(id, commandId) {
26093
+ return this.accepted(commandId)?.session === id;
25523
26094
  }
25524
- summary(meta) {
25525
- const head = meta.head, turn = this.turn(head);
25526
- const accepted2 = closed(this.read(this.path(head, "accepted.json"), META_BYTES), ["command", "at"]);
25527
- const command = decodeWorkbenchCommand(accepted2.command);
25528
- if (command.kind !== "send" || command.commandId !== head || command.conversationId !== meta.id || command.model.epoch !== turn.epoch)
25529
- throw new ContractError("corrupt-selected");
25530
- return {
25531
- id: meta.id,
25532
- title: meta.title,
25533
- head,
25534
- status: turn.status,
25535
- updatedAt: integer(accepted2.at, 0)
25536
- };
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;
25537
26099
  }
25538
- headKey(head, id, count2) {
25539
- return [
25540
- this.path(head, "turn.json"),
25541
- this.path(head, "accepted.json"),
25542
- this.path(head, "position.json"),
25543
- this.slotPath(id, count2 - 1)
25544
- ].map(observedFile).join("|");
25545
- }
25546
- retainedSummary(id) {
25547
- return this.retained(id).summary;
25548
- }
25549
- retained(id) {
25550
- const base = [this.metadataPath(id), this.identityPath(id)].map(observedFile).join("|");
25551
- const hit = this.summaries.get(id);
25552
- if (hit && !this.active.has(hit.summary.head) && hit.key === `${base}|${this.headKey(hit.summary.head, id, hit.count)}`)
25553
- return { summary: { ...hit.summary }, count: hit.count };
25554
- const meta = this.metadata(id);
25555
- if (!meta)
25556
- throw new ContractError("corrupt-selected");
25557
- const head = meta.head;
25558
- const key2 = `${base}|${this.headKey(head, id, meta.count)}`;
25559
- const summary2 = this.summary(meta);
25560
- this.summaries.delete(id);
25561
- if (!this.active.has(head) && !["queued", "running"].includes(summary2.status)) {
25562
- if (this.summaries.size >= SUMMARY_CACHE)
25563
- this.summaries.delete(this.summaries.keys().next().value);
25564
- this.summaries.set(id, {
25565
- key: key2,
25566
- summary: { ...summary2 },
25567
- count: meta.count
25568
- });
25569
- }
25570
- return { summary: summary2, count: meta.count };
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
+ });
25571
26108
  }
25572
- 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;
25573
26126
  return {
25574
- id: live2.conversationId,
25575
- title: live2.title,
25576
- head: live2.turn.id,
25577
- status: live2.turn.status,
25578
- 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 } } : {}
25579
26134
  };
25580
26135
  }
25581
- list(after = null, scan) {
26136
+ list(after = null) {
25582
26137
  this.o.owner.lease.assert();
25583
- 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
+ };
25584
26156
  }
25585
26157
  activeConversations() {
25586
26158
  this.o.owner.lease.assert();
25587
26159
  return {
25588
26160
  kind: "conversation-active",
25589
- 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
+ })
25590
26165
  };
25591
26166
  }
25592
- closeReads() {
25593
- this.history.close();
25594
- }
25595
26167
  assertSettled() {
25596
26168
  this.o.owner.lease.assert();
25597
- const path = join28(this.root, "sessions");
25598
- if (!this.files.directory(path))
26169
+ const sessions = join31(this.root, "sessions");
26170
+ if (!this.files.directory(sessions))
25599
26171
  return;
25600
- const dir = opendirSync10(path);
26172
+ const dir = opendirSync10(sessions);
25601
26173
  try {
25602
26174
  for (let e = dir.readSync();e; e = dir.readSync()) {
25603
26175
  if (!e.isFile() || !e.name.endsWith(".json"))
25604
26176
  throw new ContractError("corrupt-selected");
25605
- 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")
25606
26179
  throw new ContractError("quarantine");
25607
26180
  }
25608
26181
  } finally {
25609
26182
  dir.closeSync();
25610
26183
  }
25611
26184
  }
25612
- conversation(id) {
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) {
25613
26236
  this.o.owner.lease.assert();
25614
- if (observedFile(this.metadataPath(id)) === "absent") {
25615
- const live2 = [...this.active.values()].find((turn) => turn.conversationId === id);
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);
25616
26271
  return {
25617
- kind: "conversation",
25618
- summary: live2 ? this.liveSummary(live2) : null,
25619
- turns: 0
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
26280
+ }
26281
+ } : turn2,
26282
+ stable: turn2.steps.length
25620
26283
  };
25621
26284
  }
25622
- const { summary: summary2, count: count2 } = this.retained(id);
25623
- return { kind: "conversation", summary: summary2, turns: count2 };
26285
+ const live2 = view.live;
26286
+ if (!live2 || ordinal !== view.turns.length)
26287
+ throw new ContractError("stale");
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 };
25624
26319
  }
25625
- turnSteps(id, ordinal, before) {
26320
+ turnSteps(id, leaf, ordinal, before) {
25626
26321
  this.o.owner.lease.assert();
25627
- const meta = this.metadata(id);
25628
- if (!meta)
25629
- throw new ContractError("stale");
25630
- const turn = this.turn(this.turnAt(meta, ordinal));
25631
- const { steps, stable } = this.steps.list(turn);
25632
- const end = before ?? steps.length;
25633
- if (end > steps.length)
26322
+ const { turn, stable } = this.built(id, leaf, ordinal);
26323
+ const end = before ?? turn.steps.length;
26324
+ if (end > turn.steps.length)
25634
26325
  throw new ContractError("stale");
25635
26326
  const start = Math.max(0, end - STEP_READ);
25636
26327
  return {
25637
26328
  kind: "conversation-turn",
25638
26329
  conversationId: id,
26330
+ leaf,
25639
26331
  ordinal,
25640
26332
  turn: {
25641
26333
  id: turn.id,
25642
- epoch: turn.epoch,
25643
26334
  status: turn.status,
25644
26335
  notice: turn.notice,
25645
26336
  omitted: { ...turn.omitted },
25646
- steps: steps.length,
25647
- stable
26337
+ steps: turn.steps.length,
26338
+ stable,
26339
+ entry: turn.entry,
26340
+ at: turn.at
25648
26341
  },
25649
26342
  start,
25650
- steps: steps.slice(start, end).map((row) => row.step)
26343
+ steps: turn.steps.slice(start, end)
25651
26344
  };
25652
26345
  }
25653
- step(id, turnId, step, part2) {
26346
+ step(id, leaf, turnId, step, part) {
25654
26347
  this.o.owner.lease.assert();
25655
- if (!this.hasTurn(id, turnId))
25656
- throw new ContractError("invalid");
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)
26355
+ throw new ContractError("stale");
25657
26356
  return {
25658
26357
  kind: "conversation-step",
25659
26358
  conversationId: id,
26359
+ leaf,
25660
26360
  turnId,
25661
26361
  step,
25662
- part: part2,
25663
- item: { ...this.steps.detail(this.turn(turnId), step, part2) }
26362
+ part,
26363
+ item
25664
26364
  };
25665
26365
  }
25666
- page(turnId, page) {
25667
- const value = this.read(this.path(turnId, `transcript/${integer(page, 0)}.json`), TRANSCRIPT_PAGE_BYTES);
26366
+ origin(taskId2) {
26367
+ this.o.owner.lease.assert();
26368
+ const value = this.read(join31(this.legacy, "task-links", `${decodeId(taskId2)}.json`));
25668
26369
  if (value === undefined)
25669
- throw new ContractError("corrupt-selected");
25670
- const record2 = closed(value, ["turnId", "page", "items"]);
25671
- const items = list(record2.items, 1, decodeChatItem);
25672
- if (record2.turnId !== turnId || record2.page !== page || !items.length)
25673
- throw new ContractError("corrupt-selected");
25674
- return items[0];
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)
26376
+ };
25675
26377
  }
25676
26378
  attempted(conversationId, commandId) {
25677
26379
  this.o.owner.lease.assert();
25678
- const meta = this.metadata(conversationId);
25679
- 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);
25680
26381
  }
25681
26382
  command(input, reply) {
25682
26383
  return {
@@ -25686,11 +26387,10 @@ class Conversations {
25686
26387
  }
25687
26388
  receipt(input, reply = false) {
25688
26389
  this.o.owner.lease.assert();
25689
- const prior = this.read(this.path(input.commandId, "accepted.json"), META_BYTES);
25690
- if (prior === undefined)
26390
+ const prior = this.accepted(input.commandId);
26391
+ if (!prior)
25691
26392
  return;
25692
- const saved = closed(prior, ["command", "at"]);
25693
- if (canonicalJson(saved.command) !== canonicalJson(this.command(input, reply)))
26393
+ if (canonicalJson(prior.command) !== canonicalJson(this.command(input, reply)))
25694
26394
  throw new ContractError("conflict");
25695
26395
  return { kind: "accepted", commandId: input.commandId };
25696
26396
  }
@@ -25700,7 +26400,7 @@ class Conversations {
25700
26400
  const receipt = this.receipt(input, !!control?.reply);
25701
26401
  if (receipt)
25702
26402
  return receipt;
25703
- if (this.files.directory(dirname19(this.path(input.commandId, "accepted.json"))))
26403
+ if (this.files.directory(dirname20(this.path(input.commandId, "state.json"))))
25704
26404
  throw new ContractError("corrupt-selected");
25705
26405
  if (this.o.owner.state !== "idle")
25706
26406
  throw new ContractError("quarantine");
@@ -25711,85 +26411,59 @@ class Conversations {
25711
26411
  this.o.models.assertCurrent(choice.selected);
25712
26412
  if (!this.currentDirectory())
25713
26413
  throw new ContractError("stale");
25714
- const beforeMeta = this.files.read(this.metadataPath(input.conversationId), META_BYTES);
25715
- const meta = this.metadata(input.conversationId);
25716
- this.files.assert(this.metadataPath(input.conversationId), beforeMeta, META_BYTES);
25717
- if (!meta && this.files.read(this.identityPath(input.conversationId), META_BYTES))
25718
- throw new ContractError("corrupt-selected");
25719
- if ((meta?.head ?? null) !== input.head)
25720
- throw new ContractError("stale");
25721
- if (meta && this.turn(input.head).status !== "completed" && (!control || ["queued", "running", "unknown"].includes(this.turn(input.head).status)))
26414
+ if (this.liveFor(input.conversationId))
25722
26415
  throw new ContractError("conflict");
25723
- 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)
25724
26421
  throw new ContractError("capacity");
25725
26422
  if (!input.text.trim())
25726
26423
  throw new ContractError("invalid");
25727
26424
  const space = statfsSync2(this.o.coordination.directory);
25728
26425
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
25729
26426
  throw new ContractError("capacity");
25730
- const turn = {
25731
- id: input.commandId,
25732
- epoch: input.model.epoch,
25733
- status: "queued",
25734
- notice: "",
25735
- omitted: { thinking: false, media: false, other: false },
25736
- items: [
25737
- {
25738
- id: "user",
25739
- role: "user",
25740
- text: command.text,
25741
- name: "",
25742
- args: "",
25743
- error: false
25744
- }
25745
- ]
25746
- };
25747
- const next = meta ?? {
25748
- id: input.conversationId,
25749
- title: [...command.text.trim()].slice(0, 100).join("") || "Conversation",
25750
- turns: [],
25751
- head: turn.id,
25752
- count: 0,
25753
- 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
25754
26434
  };
25755
- const previous = next.checkpoint ? this.path(next.checkpoint, "context.json") : null;
25756
- const previousFile = previous ? this.files.read(previous, CONTEXT_BYTES) : undefined;
25757
- if (previous && !previousFile)
25758
- throw new ContractError("corrupt-selected");
25759
26435
  const abort = new AbortController;
25760
26436
  let begin;
25761
- const ready2 = new Promise((resolve10) => {
25762
- begin = resolve10;
26437
+ const ready2 = new Promise((resolve11) => {
26438
+ begin = resolve11;
25763
26439
  });
25764
- const original = ready2.then(() => this.run(command, turn, previous, previousFile, next, abort, control));
25765
26440
  const live2 = {
25766
- 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,
25767
26453
  abort,
25768
- original,
25769
- conversationId: next.id,
25770
- title: next.title,
25771
- acceptedAt: Date.now(),
25772
- turnFile: null,
25773
- metaFile: null
26454
+ original: ready2.then(() => this.run(live2, control))
25774
26455
  };
25775
26456
  beforeAccept?.();
25776
- this.active.set(turn.id, live2);
25777
- this.o.owner.trackConversation(original, () => abort.abort());
26457
+ this.active.set(input.commandId, live2);
26458
+ this.o.owner.trackConversation(live2.original, () => abort.abort());
25778
26459
  try {
25779
- if (!meta)
25780
- this.write(this.identityPath(next.id), { schema: "cadence-conversation/1", id: next.id, cwd: this.cwd }, META_BYTES);
25781
- this.write(this.path(turn.id, "accepted.json"), { command, at: live2.acceptedAt }, META_BYTES);
25782
- live2.turnFile = this.write(this.path(turn.id, "turn.json"), turn, TURN_BYTES);
25783
- const position2 = {
25784
- conversationId: next.id,
25785
- ordinal: next.count,
25786
- turnId: turn.id
25787
- };
25788
- this.write(this.slotPath(next.id, next.count), position2, META_BYTES);
25789
- this.write(this.path(turn.id, "position.json"), position2, META_BYTES);
25790
- next.head = turn.id;
25791
- next.count++;
25792
- 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);
25793
26467
  control?.accept();
25794
26468
  } catch (error) {
25795
26469
  abort.abort();
@@ -25797,38 +26471,23 @@ class Conversations {
25797
26471
  throw error;
25798
26472
  }
25799
26473
  begin();
25800
- return { kind: "accepted", commandId: turn.id };
25801
- }
25802
- origin(taskId2) {
25803
- this.o.owner.lease.assert();
25804
- const value = this.read(join28(this.root, "task-links", `${decodeId(taskId2)}.json`), META_BYTES);
25805
- if (value === undefined)
25806
- return { kind: "task-origin", taskId: taskId2, conversationId: null };
25807
- const row = closed(value, ["conversationId"]);
25808
- return {
25809
- kind: "task-origin",
25810
- taskId: taskId2,
25811
- conversationId: decodeId(row.conversationId)
25812
- };
26474
+ return { kind: "accepted", commandId: input.commandId };
25813
26475
  }
25814
26476
  interrupt(id, turnId, epoch) {
25815
26477
  this.o.owner.lease.assert();
25816
26478
  const live2 = this.active.get(turnId);
25817
26479
  if (live2) {
25818
- if (live2.conversationId !== id || live2.turn.epoch !== epoch)
26480
+ if (live2.accepted.session !== id || live2.epoch !== epoch)
25819
26481
  throw new ContractError("stale");
25820
26482
  live2.abort.abort();
25821
26483
  return;
25822
26484
  }
25823
- const meta = this.metadata(id);
25824
- if (!meta || !this.contains(meta, turnId))
26485
+ if (!this.hasCommand(id, turnId))
25825
26486
  throw new ContractError("invalid");
25826
- if (this.turn(turnId).epoch !== epoch)
25827
- throw new ContractError("stale");
25828
- this.active.get(turnId)?.abort.abort();
25829
26487
  }
25830
- async run(command, turn, previous, previousFile, meta, abort, control) {
25831
- let transcript;
26488
+ async run(live2, control) {
26489
+ const { accepted: accepted2, abort, state } = live2;
26490
+ const commandId = live2.commandId;
25832
26491
  let barrier;
25833
26492
  let authSettled;
25834
26493
  let uncertain = false;
@@ -25848,42 +26507,35 @@ class Conversations {
25848
26507
  omissions: ["gap"]
25849
26508
  }
25850
26509
  };
25851
- const live2 = this.active.get(turn.id);
25852
26510
  const save = () => {
25853
- if (!live2?.turnFile)
26511
+ if (!live2.stateFile)
25854
26512
  throw new ContractError("corrupt-selected");
25855
- live2.turnFile = this.write(this.path(turn.id, "turn.json"), turn, TURN_BYTES, live2.turnFile);
25856
- };
25857
- const current2 = () => {
25858
- if (abort.signal.aborted || this.o.owner.state !== "idle" || !this.currentDirectory())
25859
- return false;
25860
- if (previous)
25861
- this.files.assert(previous, previousFile, CONTEXT_BYTES);
25862
- return true;
26513
+ live2.stateFile = this.write(this.path(commandId, "state.json"), state, META_BYTES2, live2.stateFile);
25863
26514
  };
26515
+ const current2 = () => !abort.signal.aborted && this.o.owner.state === "idle" && this.currentDirectory();
25864
26516
  try {
25865
26517
  if (!current2())
25866
26518
  throw new ContractError("stale");
25867
26519
  if (control?.reply) {
25868
- turn.status = "completed";
25869
- turn.notice = control.reply;
26520
+ state.status = "completed";
26521
+ state.notice = control.reply;
25870
26522
  return { status: "settled" };
25871
26523
  }
25872
26524
  if (!control) {
25873
- barrier = await this.o.gate.acquire(turn.id, abort.signal);
26525
+ barrier = await this.o.gate.acquire(commandId, abort.signal);
25874
26526
  barrier.assertHeld();
25875
26527
  }
25876
26528
  if (!current2())
25877
26529
  throw new ContractError("stale");
25878
26530
  const choice = this.o.choice.snapshot(), selected2 = choice.selected;
25879
- 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)
25880
26532
  throw new ContractError("stale");
25881
26533
  const request3 = decodeWorkerPublicRequest({
25882
26534
  protocol: 2,
25883
- taskId: meta.id,
26535
+ taskId: randomUUID19(),
25884
26536
  taskKind: control ? "research" : "code",
25885
- runId: turn.id,
25886
- childRunId: randomUUID20(),
26537
+ runId: commandId,
26538
+ childRunId: randomUUID19(),
25887
26539
  assignmentId: "conversation",
25888
26540
  purpose: control ? "research" : "edit",
25889
26541
  model: selected2,
@@ -25893,62 +26545,51 @@ class Conversations {
25893
26545
  },
25894
26546
  context: "",
25895
26547
  instructions: control?.instructions ?? "Ordinary conversation.",
25896
- prompt: command.text,
26548
+ prompt: accepted2.command.text,
25897
26549
  handoff: { graphRevision: 1, inputs: [] }
25898
26550
  });
25899
26551
  const auth = this.o.models.prepareTracked({
25900
26552
  request: request3,
25901
- operationId: randomUUID20(),
25902
- epoch: turn.epoch,
26553
+ operationId: randomUUID19(),
26554
+ epoch: live2.epoch,
25903
26555
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
25904
26556
  signal: abort.signal,
25905
26557
  current: current2,
25906
26558
  journal: {
25907
- preparation: (value) => this.write(this.path(turn.id, "auth-intent.json"), value, META_BYTES),
25908
- 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)
25909
26561
  }
25910
26562
  });
25911
26563
  authSettled = auth.settled;
25912
26564
  const prepared = await auth.result;
25913
26565
  if (prepared.status !== "prepared" || !current2())
25914
26566
  throw new ContractError("auth-unavailable");
25915
- turn.status = "running";
26567
+ state.status = "running";
25916
26568
  save();
25917
- this.write(this.path(turn.id, "launch.json"), { epoch: turn.epoch, childRunId: request3.childRunId }, META_BYTES);
25918
- let credentials = [];
25919
- let checkpoint = false, contextCount = 0;
25920
- let contextHead = null;
25921
- transcript = new ConversationTranscript(turn, (page) => {
25922
- const space = statfsSync2(this.o.coordination.directory);
25923
- if (space.bavail * space.bsize - TRANSCRIPT_PAGE_BYTES < LIMITS.freeSpaceFloorBytes)
25924
- throw new ContractError("capacity");
25925
- 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
25926
26572
  });
25927
- 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);
25928
26580
  const running = Promise.resolve().then(() => launchConversation(prepared.prepared, {
25929
- previous,
26581
+ session: {
26582
+ id: accepted2.session,
26583
+ dir: this.sessions.directory,
26584
+ file: existing?.path ?? null,
26585
+ head: accepted2.parent
26586
+ },
25930
26587
  agentDir: this.o.agentDir,
25931
26588
  ...control ? { coordinator: true } : {}
25932
26589
  }, abort.signal, {
25933
26590
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
25934
26591
  ownerSecrets: this.o.secrets,
25935
26592
  onCoordinator: control?.onTool,
25936
- onContext: (message) => {
25937
- const space = statfsSync2(this.o.coordination.directory);
25938
- if (space.bavail * space.bsize - CONTEXT_RECORD_BYTES < LIMITS.freeSpaceFloorBytes)
25939
- throw new ContractError("capacity");
25940
- const file = this.write(this.path(turn.id, `context-${contextCount}.json`), {
25941
- schema: "cadence-conversation-message/1",
25942
- index: contextCount,
25943
- previous: contextHead,
25944
- message
25945
- }, CONTEXT_RECORD_BYTES);
25946
- contextHead = file.identity;
25947
- contextCount++;
25948
- },
25949
- onContextEnd: () => {
25950
- checkpoint = true;
25951
- },
25952
26593
  maySignal: () => {
25953
26594
  try {
25954
26595
  this.o.owner.lease.assert();
@@ -25969,39 +26610,29 @@ class Conversations {
25969
26610
  this.o.owner.trackConversationProcess(tracked, () => abort.abort());
25970
26611
  const result = await running;
25971
26612
  uncertain = !result.closed;
25972
- turn.status = result.outcome;
25973
- if (result.outcome === "completed") {
25974
- if (!checkpoint)
25975
- throw new ContractError("corrupt-selected");
25976
- this.write(this.path(turn.id, "context.json"), {
25977
- schema: "cadence-conversation-context/2",
25978
- messages: contextCount,
25979
- head: contextHead
25980
- }, CONTEXT_BYTES);
25981
- meta.checkpoint = turn.id;
25982
- if (!live2?.metaFile)
25983
- throw new ContractError("corrupt-selected");
25984
- live2.metaFile = this.write(this.metadataPath(meta.id), meta, META_BYTES, live2.metaFile);
25985
- }
26613
+ state.status = result.outcome;
25986
26614
  } catch (error) {
25987
26615
  uncertain ||= this.o.owner.state === "quarantined";
25988
- turn.status = uncertain ? "unknown" : abort.signal.aborted ? "canceled" : "failed";
25989
- 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.";
25990
26618
  } finally {
25991
26619
  await control?.settle();
25992
26620
  await authSettled;
25993
26621
  uncertain ||= this.o.owner.state === "quarantined";
25994
26622
  if (uncertain)
25995
- turn.status = "unknown";
26623
+ state.status = "unknown";
25996
26624
  try {
25997
- this.write(this.path(turn.id, "native.json"), native, META_BYTES);
25998
- transcript?.finish();
25999
- if (turn.status !== "completed")
26000
- turn.notice = [
26001
- turn.notice,
26002
- 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."
26003
- ].filter(Boolean).join(`
26004
- `);
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
+ }
26005
26636
  save();
26006
26637
  } catch {
26007
26638
  uncertain = true;
@@ -26010,7 +26641,7 @@ class Conversations {
26010
26641
  this.o.owner.quarantine();
26011
26642
  else if (this.o.owner.state === "idle")
26012
26643
  barrier?.release();
26013
- this.active.delete(turn.id);
26644
+ this.active.delete(commandId);
26014
26645
  }
26015
26646
  return { status: uncertain ? "uncertain" : "settled" };
26016
26647
  }
@@ -26069,10 +26700,10 @@ class ConversationWorkflow {
26069
26700
  grants = new Map;
26070
26701
  constructor(o) {
26071
26702
  this.o = o;
26072
- this.root = join29(o.coordination.directory, "conversation-workflows-v1");
26703
+ this.root = join32(o.coordination.directory, "conversation-workflows-v1");
26073
26704
  }
26074
26705
  path(id) {
26075
- return join29(this.root, decodeId(id), "state.json");
26706
+ return join32(this.root, decodeSessionId(id), "state.json");
26076
26707
  }
26077
26708
  read(id) {
26078
26709
  this.o.owner.lease.assert();
@@ -26081,7 +26712,7 @@ class ConversationWorkflow {
26081
26712
  const bound = this.o.conversations.controlBound(id);
26082
26713
  const file = this.o.coordination.files.read(path, BYTES);
26083
26714
  if (!file)
26084
- 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) };
26085
26716
  const record2 = closed(parseWireJson(file.bytes.toString("utf8"), BYTES), [
26086
26717
  "schema",
26087
26718
  "state"
@@ -26089,7 +26720,7 @@ class ConversationWorkflow {
26089
26720
  const state = decodeCadenceConversation(record2.state);
26090
26721
  if (record2.schema !== SCHEMA || !bound || state.id !== id || state.notice !== undefined)
26091
26722
  return unusable2(id);
26092
- if (state.head && !this.o.conversations.hasTurn(id, state.head))
26723
+ if (state.head && !this.o.conversations.hasCommand(id, state.head))
26093
26724
  return {
26094
26725
  state: { ...state, proposal: null, notice: UNRECORDED },
26095
26726
  problem: true
@@ -26177,7 +26808,7 @@ class ConversationWorkflow {
26177
26808
  return loaded.state;
26178
26809
  }
26179
26810
  runLink(runId) {
26180
- 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`);
26181
26812
  }
26182
26813
  links(runIds) {
26183
26814
  this.o.owner.lease.assert();
@@ -26193,7 +26824,7 @@ class ConversationWorkflow {
26193
26824
  ]);
26194
26825
  if (row.runId !== runId)
26195
26826
  continue;
26196
- const conversationId = decodeId(row.conversationId);
26827
+ const conversationId = decodeSessionId(row.conversationId);
26197
26828
  if (this.observe(conversationId).notice)
26198
26829
  continue;
26199
26830
  links.push({ runId, conversationId });
@@ -26214,7 +26845,7 @@ class ConversationWorkflow {
26214
26845
  ++seen;
26215
26846
  let id;
26216
26847
  try {
26217
- id = decodeId(e.name);
26848
+ id = decodeSessionId(e.name);
26218
26849
  } catch {
26219
26850
  continue;
26220
26851
  }
@@ -26260,14 +26891,14 @@ class ConversationWorkflow {
26260
26891
  } catch {}
26261
26892
  }
26262
26893
  preview(run2, bytes, steps) {
26263
- const clip = (value, maximum) => diagnosticText(value, maximum, this.o.secrets());
26894
+ const clip2 = (value, maximum) => diagnosticText(value, maximum, this.o.secrets());
26264
26895
  return {
26265
26896
  ...run2,
26266
- goal: clip(run2.goal, 320),
26267
- notice: clip(run2.notice, 512),
26897
+ goal: clip2(run2.goal, 320),
26898
+ notice: clip2(run2.notice, 512),
26268
26899
  stepsOmitted: Math.max(0, run2.steps.length - steps),
26269
26900
  steps: run2.steps.slice(-steps).map((s) => {
26270
- const text2 = clip(s.text, bytes);
26901
+ const text2 = clip2(s.text, bytes);
26271
26902
  return { ...s, text: text2, truncated: s.truncated || text2 !== s.text };
26272
26903
  })
26273
26904
  };
@@ -26376,7 +27007,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26376
27007
  }
26377
27008
  let published;
26378
27009
  try {
26379
- published = this.o.workflows.command(randomUUID21(), epoch, {
27010
+ published = this.o.workflows.command(randomUUID20(), epoch, {
26380
27011
  action: "propose",
26381
27012
  plan,
26382
27013
  model
@@ -26420,7 +27051,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26420
27051
  const busy = this.o.workflows.activeRuns().runs.filter((r) => r.phase !== "research").map((r) => r.id);
26421
27052
  if (busy.length)
26422
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.`);
26423
- const id = randomUUID21(), conversationId = current2.state.id;
27054
+ const id = randomUUID20(), conversationId = current2.state.id;
26424
27055
  try {
26425
27056
  this.o.workflows.command(id, epoch, {
26426
27057
  action: "research",
@@ -26444,7 +27075,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26444
27075
  }, current2.file);
26445
27076
  const cancel = () => {
26446
27077
  try {
26447
- this.o.workflows.command(randomUUID21(), epoch, {
27078
+ this.o.workflows.command(randomUUID20(), epoch, {
26448
27079
  action: "cancel",
26449
27080
  runId: id
26450
27081
  });
@@ -26463,7 +27094,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26463
27094
  approval(c, caller) {
26464
27095
  if (!caller)
26465
27096
  throw new ContractError("forbidden");
26466
- 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`);
26467
27098
  let effects = true;
26468
27099
  try {
26469
27100
  effects = this.o.owner.state !== "idle";
@@ -26505,8 +27136,8 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26505
27136
  }
26506
27137
  decide(c, caller, evidence, recording) {
26507
27138
  const { state, file } = this.usable(c.conversationId);
26508
- const view = this.o.conversations.conversation(c.conversationId);
26509
- 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))
26510
27141
  throw new ContractError("stale");
26511
27142
  const epoch = this.o.owner.lease.registration.epoch;
26512
27143
  if (c.kind === "cadence-prepare") {
@@ -26522,7 +27153,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26522
27153
  });
26523
27154
  if (prepared.kind !== "workflow" || prepared.response.type !== "grant")
26524
27155
  throw new ContractError("unavailable");
26525
- const g = prepared.response, grant2 = randomUUID21();
27156
+ const g = prepared.response, grant2 = randomUUID20();
26526
27157
  this.grants.set(grant2, {
26527
27158
  caller: canonicalJson(caller),
26528
27159
  revision: c.revision,
@@ -26587,28 +27218,28 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
26587
27218
  }
26588
27219
 
26589
27220
  // src/service/workflows.ts
26590
- import { randomUUID as randomUUID23 } from "node:crypto";
27221
+ import { randomUUID as randomUUID22 } from "node:crypto";
26591
27222
  import {
26592
- lstatSync as lstatSync21,
27223
+ lstatSync as lstatSync22,
26593
27224
  opendirSync as opendirSync13,
26594
27225
  realpathSync as realpathSync12,
26595
27226
  rmdirSync,
26596
27227
  statfsSync as statfsSync3,
26597
27228
  writeFileSync as writeFileSync5
26598
27229
  } from "node:fs";
26599
- 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";
26600
27231
  import { fileURLToPath as fileURLToPath6 } from "node:url";
26601
27232
 
26602
27233
  // src/task-diff.ts
26603
27234
  import { spawnSync as spawnSync5 } from "node:child_process";
26604
- import { createHash as createHash24 } from "node:crypto";
26605
- import { lstatSync as lstatSync18, readdirSync as readdirSync3, readlinkSync } from "node:fs";
26606
- 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";
26607
27238
  var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
26608
27239
  var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
26609
27240
  function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
26610
27241
  const deadline = Date.now() + 3000;
26611
- const hash3 = createHash24("sha256");
27242
+ const hash3 = createHash26("sha256");
26612
27243
  const parts = [];
26613
27244
  let complete = true;
26614
27245
  const limits = [];
@@ -26646,8 +27277,8 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
26646
27277
  return;
26647
27278
  }
26648
27279
  try {
26649
- const path = join30(root, name);
26650
- const st = lstatSync18(path);
27280
+ const path = join33(root, name);
27281
+ const st = lstatSync19(path);
26651
27282
  add(name, `${st.mode}:${st.size}`);
26652
27283
  if (st.isSymbolicLink()) {
26653
27284
  add(name, readlinkSync(path));
@@ -26666,7 +27297,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
26666
27297
  fileBytes += data2.length;
26667
27298
  add(name, data2);
26668
27299
  const binary = data2.includes(0);
26669
- 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")})`);
26670
27301
  } catch {
26671
27302
  complete = false;
26672
27303
  limits.push(`Unreadable/changing: ${name}`);
@@ -26781,13 +27412,13 @@ ${data2.toString("utf8")}`);
26781
27412
  }
26782
27413
  let names2;
26783
27414
  try {
26784
- names2 = readdirSync3(dir).sort();
27415
+ names2 = readdirSync4(dir).sort();
26785
27416
  } catch {
26786
27417
  complete = false;
26787
27418
  return;
26788
27419
  }
26789
27420
  for (const name of names2) {
26790
- const path = join30(dir, name);
27421
+ const path = join33(dir, name);
26791
27422
  const rel = relative8(root, path).split("\\").join("/");
26792
27423
  if (rel === ".git" || admin(rel))
26793
27424
  continue;
@@ -26796,7 +27427,7 @@ ${data2.toString("utf8")}`);
26796
27427
  break;
26797
27428
  }
26798
27429
  try {
26799
- const st = lstatSync18(path);
27430
+ const st = lstatSync19(path);
26800
27431
  if (st.isDirectory())
26801
27432
  walk(path, depth + 1);
26802
27433
  else
@@ -26821,22 +27452,142 @@ ${data2.toString("utf8")}`);
26821
27452
  return { fingerprint: hash3.digest("hex"), text: text2, complete, git: isGit };
26822
27453
  }
26823
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
+
26824
27575
  // src/service/workflow-git.ts
26825
27576
  import { spawn as spawn4, spawnSync as spawnSync6 } from "node:child_process";
26826
- import { createHash as createHash25 } from "node:crypto";
27577
+ import { createHash as createHash27 } from "node:crypto";
26827
27578
  import {
26828
- closeSync as closeSync9,
26829
- constants as constants8,
26830
- fstatSync as fstatSync6,
26831
- lstatSync as lstatSync19,
26832
- openSync as openSync9,
26833
- 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,
26834
27585
  readlinkSync as readlinkSync2,
26835
- readSync as readSync5,
27586
+ readSync as readSync7,
26836
27587
  realpathSync as realpathSync11
26837
27588
  } from "node:fs";
26838
27589
  import { lstat, open as open2, readdir, readlink } from "node:fs/promises";
26839
- 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";
26840
27591
  var NAMES_BYTES = 64 * 1024 * 1024;
26841
27592
  var SYNC_MS = 30000;
26842
27593
  var READ_MS = 120000;
@@ -26922,19 +27673,19 @@ async function gitHead(cwd) {
26922
27673
  }
26923
27674
  function contains2(root, path) {
26924
27675
  const within = relative9(root, path);
26925
- return !within || !within.startsWith(`..${sep7}`) && within !== ".." && !isAbsolute10(within);
27676
+ return !within || !within.startsWith(`..${sep7}`) && within !== ".." && !isAbsolute11(within);
26926
27677
  }
26927
27678
  function nested(a, b) {
26928
27679
  return contains2(a, b) || contains2(b, a);
26929
27680
  }
26930
27681
  function safeWorkflowFile(cwd, name) {
26931
27682
  workflowPath(name);
26932
- const p = resolve10(cwd, name);
27683
+ const p = resolve11(cwd, name);
26933
27684
  if (relative9(cwd, p).startsWith(".."))
26934
27685
  throw new ContractError("forbidden");
26935
- safeDirectory(dirname21(p));
27686
+ safeDirectory(dirname22(p));
26936
27687
  try {
26937
- const st = lstatSync19(p);
27688
+ const st = lstatSync20(p);
26938
27689
  if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
26939
27690
  throw new ContractError("forbidden");
26940
27691
  } catch (e) {
@@ -26945,12 +27696,12 @@ function safeWorkflowFile(cwd, name) {
26945
27696
  }
26946
27697
  function declaredTarget(cwd, name) {
26947
27698
  workflowPath(name);
26948
- const p = resolve10(cwd, name);
27699
+ const p = resolve11(cwd, name);
26949
27700
  if (relative9(cwd, p).startsWith(".."))
26950
27701
  throw new ContractError("forbidden");
26951
- safeDirectory(dirname21(p));
27702
+ safeDirectory(dirname22(p));
26952
27703
  try {
26953
- const st = lstatSync19(p);
27704
+ const st = lstatSync20(p);
26954
27705
  if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory() || st.isFile() && st.nlink !== 1)
26955
27706
  throw new ContractError("forbidden");
26956
27707
  } catch (e) {
@@ -26976,21 +27727,21 @@ function fileIdentity(p, st, hashBytes) {
26976
27727
  return quick;
26977
27728
  let fd;
26978
27729
  try {
26979
- fd = openSync9(p, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
27730
+ fd = openSync12(p, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0));
26980
27731
  } catch (e) {
26981
27732
  if (absent2(e))
26982
27733
  return null;
26983
27734
  throw e;
26984
27735
  }
26985
27736
  try {
26986
- if (!fstatSync6(fd).isFile())
27737
+ if (!fstatSync8(fd).isFile())
26987
27738
  throw new ContractError("stale");
26988
- const digest = createHash25("sha256"), buffer = Buffer.alloc(CHUNK);
26989
- 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))
26990
27741
  digest.update(buffer.subarray(0, n));
26991
27742
  return `sha256:${digest.digest("hex")}`;
26992
27743
  } finally {
26993
- closeSync9(fd);
27744
+ closeSync12(fd);
26994
27745
  }
26995
27746
  }
26996
27747
  async function fileIdentityAsync(p, st, hashBytes) {
@@ -27001,14 +27752,14 @@ async function fileIdentityAsync(p, st, hashBytes) {
27001
27752
  return quick;
27002
27753
  let handle;
27003
27754
  try {
27004
- handle = await open2(p, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
27755
+ handle = await open2(p, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0));
27005
27756
  } catch (e) {
27006
27757
  if (absent2(e))
27007
27758
  return null;
27008
27759
  throw e;
27009
27760
  }
27010
27761
  try {
27011
- const digest = createHash25("sha256"), buffer = Buffer.alloc(CHUNK);
27762
+ const digest = createHash27("sha256"), buffer = Buffer.alloc(CHUNK);
27012
27763
  for (;; ) {
27013
27764
  const { bytesRead } = await handle.read(buffer, 0, CHUNK, null);
27014
27765
  if (!bytesRead)
@@ -27025,13 +27776,13 @@ function directoryIdentity(root, name) {
27025
27776
  const rows = [];
27026
27777
  let count2 = 0;
27027
27778
  const visit = (directory, prefix) => {
27028
- for (const entry of readdirSync4(directory).sort()) {
27779
+ for (const entry of readdirSync5(directory).sort()) {
27029
27780
  if (entry === ".git")
27030
27781
  continue;
27031
27782
  if (++count2 > DIRECTORY_ENTRIES)
27032
27783
  throw tooLarge(name);
27033
- const full = join31(directory, entry), relative10 = `${prefix}${entry}`;
27034
- const st = lstatSync19(full);
27784
+ const full = join34(directory, entry), relative10 = `${prefix}${entry}`;
27785
+ const st = lstatSync20(full);
27035
27786
  if (st.isDirectory()) {
27036
27787
  rows.push(`${relative10}/`);
27037
27788
  visit(full, `${relative10}/`);
@@ -27052,7 +27803,7 @@ async function directoryIdentityAsync(root, name) {
27052
27803
  continue;
27053
27804
  if (++count2 > DIRECTORY_ENTRIES)
27054
27805
  throw tooLarge(name);
27055
- const full = join31(directory, entry), relative10 = `${prefix}${entry}`;
27806
+ const full = join34(directory, entry), relative10 = `${prefix}${entry}`;
27056
27807
  const st = await lstat(full);
27057
27808
  if (st.isDirectory()) {
27058
27809
  rows.push(`${relative10}/`);
@@ -27066,12 +27817,12 @@ async function directoryIdentityAsync(root, name) {
27066
27817
  `))}`;
27067
27818
  }
27068
27819
  function pathIdentity(cwd, name, walk = true) {
27069
- const p = resolve10(cwd, name);
27820
+ const p = resolve11(cwd, name);
27070
27821
  if (relative9(cwd, p).startsWith(".."))
27071
27822
  throw new ContractError("forbidden");
27072
27823
  let st;
27073
27824
  try {
27074
- st = lstatSync19(p);
27825
+ st = lstatSync20(p);
27075
27826
  } catch (e) {
27076
27827
  if (absent2(e))
27077
27828
  return null;
@@ -27082,7 +27833,7 @@ function pathIdentity(cwd, name, walk = true) {
27082
27833
  return fileIdentity(p, st, HASH_BYTES);
27083
27834
  }
27084
27835
  async function pathIdentityAsync(cwd, name) {
27085
- const p = resolve10(cwd, name);
27836
+ const p = resolve11(cwd, name);
27086
27837
  if (relative9(cwd, p).startsWith(".."))
27087
27838
  throw new ContractError("forbidden");
27088
27839
  let st;
@@ -27286,20 +28037,20 @@ ${block}
27286
28037
  async function assertWorktree(root, cwd) {
27287
28038
  if (!safeDirectory(cwd))
27288
28039
  throw new ContractError("stale");
27289
- const real = (p) => realpathSync11(resolve10(p));
28040
+ const real = (p) => realpathSync11(resolve11(p));
27290
28041
  if (real((await gitText(cwd, ["rev-parse", "--show-toplevel"])).trim()) !== real(cwd))
27291
28042
  throw new ContractError("stale");
27292
- 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()));
27293
28044
  if (await common(root) !== await common(cwd))
27294
28045
  throw new ContractError("stale");
27295
- const marker2 = resolve10(cwd, ".git");
27296
- 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: "))
27297
28048
  throw new ContractError("stale");
27298
28049
  }
27299
28050
 
27300
28051
  // src/service/workflow-history.ts
27301
- import { randomUUID as randomUUID22 } from "node:crypto";
27302
- 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";
27303
28054
  class WorkflowHistoryScanner {
27304
28055
  path;
27305
28056
  directory;
@@ -27310,7 +28061,7 @@ class WorkflowHistoryScanner {
27310
28061
  this.directory = directory;
27311
28062
  }
27312
28063
  incarnation() {
27313
- const st = lstatSync20(this.path, { bigint: true });
28064
+ const st = lstatSync21(this.path, { bigint: true });
27314
28065
  if (!st.isDirectory() || st.isSymbolicLink())
27315
28066
  throw new ContractError("corrupt-selected");
27316
28067
  return `${st.dev}:${st.ino}`;
@@ -27362,7 +28113,7 @@ class WorkflowHistoryScanner {
27362
28113
  if (state.ids.length > WORKFLOW_LIMITS.historyPage + 1)
27363
28114
  state.ids.pop();
27364
28115
  }
27365
- const scan = randomUUID22();
28116
+ const scan = randomUUID21();
27366
28117
  state.timer = setTimeout(() => {
27367
28118
  this.scans.delete(scan);
27368
28119
  try {
@@ -27399,8 +28150,8 @@ class WorkflowHistoryScanner {
27399
28150
 
27400
28151
  // src/service/workflows.ts
27401
28152
  var OWNER_RUNTIME = Object.freeze({
27402
- version: "2.0.30",
27403
- build: "b33664958cc26420c95cd53aff826f4f0d87cc3edee145ccb9467cad93ec29e2",
28153
+ version: "2.0.32",
28154
+ build: "b2e9f553ead7bbf1508624a3e834a8654557687cf2a3a26f2aa1161843abe5eb",
27404
28155
  entry: fileURLToPath6(import.meta.url),
27405
28156
  pid: process.pid,
27406
28157
  node: process.versions.node,
@@ -27426,8 +28177,8 @@ class UnacceptedWorkflowCommand extends UnacceptedConversationCommand {
27426
28177
 
27427
28178
  class WorkflowFailure extends Error {
27428
28179
  outcome;
27429
- constructor(outcome, message) {
27430
- super(message);
28180
+ constructor(outcome, message2) {
28181
+ super(message2);
27431
28182
  this.outcome = outcome;
27432
28183
  }
27433
28184
  }
@@ -27504,7 +28255,7 @@ class WorkflowTranscript {
27504
28255
  constructor(turn, secrets) {
27505
28256
  this.turn = turn;
27506
28257
  this.secrets = secrets;
27507
- this.capture = new ConversationCapture(turn, () => {
28258
+ this.capture = new TurnCapture(turn, () => {
27508
28259
  this.pending = true;
27509
28260
  }, secrets);
27510
28261
  this.latest = { ...structuredClone(turn), items: [] };
@@ -27544,7 +28295,7 @@ class WorkflowTranscript {
27544
28295
  if (e.kind === "message-start") {
27545
28296
  if (e.role === "assistant") {
27546
28297
  this.latest = { ...structuredClone(this.latest), items: [] };
27547
- this.final = new ConversationCapture(this.latest, () => {}, this.secrets);
28298
+ this.final = new TurnCapture(this.latest, () => {}, this.secrets);
27548
28299
  }
27549
28300
  relevant = true;
27550
28301
  } else if (e.kind === "message-end")
@@ -27587,12 +28338,12 @@ class Workflows {
27587
28338
  grants = new Map;
27588
28339
  constructor(o) {
27589
28340
  this.o = o;
27590
- this.root = join32(o.coordination.directory, "workflows-v1");
28341
+ this.root = join35(o.coordination.directory, "workflows-v1");
27591
28342
  this.cwd = realpathSync12(o.coordination.store.root);
27592
- this.worktreeRoot = join32(o.coordination.stateHome, "cadence-worktrees-v1", basename3(o.coordination.store.privateRoot));
27593
- 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"), () => {
27594
28345
  this.o.owner.lease.assert();
27595
- return this.files.directory(join32(this.root, "runs"));
28346
+ return this.files.directory(join35(this.root, "runs"));
27596
28347
  });
27597
28348
  this.recover();
27598
28349
  }
@@ -27600,7 +28351,7 @@ class Workflows {
27600
28351
  return this.o.coordination.files;
27601
28352
  }
27602
28353
  path(id, name) {
27603
- return join32(this.root, "runs", decodeId(id), name);
28354
+ return join35(this.root, "runs", decodeId(id), name);
27604
28355
  }
27605
28356
  write(path, value, expected, max = RECORD_BYTES2) {
27606
28357
  this.o.owner.lease.assert();
@@ -27617,7 +28368,7 @@ class Workflows {
27617
28368
  `), 2048, this.o.secrets());
27618
28369
  }
27619
28370
  recover() {
27620
- const runs = join32(this.root, "runs");
28371
+ const runs = join35(this.root, "runs");
27621
28372
  if (!this.files.directory(runs))
27622
28373
  return;
27623
28374
  const ids = [];
@@ -27728,7 +28479,7 @@ class Workflows {
27728
28479
  };
27729
28480
  }
27730
28481
  proposal(id) {
27731
- 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);
27732
28483
  if (!file)
27733
28484
  throw new ContractError("unavailable");
27734
28485
  return decodeWorkflowProposal(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
@@ -27882,8 +28633,8 @@ class Workflows {
27882
28633
  if (action === "prepare")
27883
28634
  return [...this.grants.values()].some((g) => g.commandId === id && g.expiresAt >= Date.now());
27884
28635
  if (action === "propose")
27885
- return !!this.files.read(join32(this.root, "proposals", `${id}.json`), RECORD_BYTES2);
27886
- 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));
27887
28638
  }
27888
28639
  admit(commandId, epoch, r, effect) {
27889
28640
  this.current();
@@ -27912,7 +28663,7 @@ class Workflows {
27912
28663
  };
27913
28664
  if (sanitizeData(p, secrets) !== canonicalJson(p))
27914
28665
  throw new ContractError("forbidden");
27915
- const target3 = join32(this.root, "proposals", `${commandId}.json`);
28666
+ const target3 = join35(this.root, "proposals", `${commandId}.json`);
27916
28667
  const previous = this.files.read(target3, RECORD_BYTES2);
27917
28668
  if (previous) {
27918
28669
  if (previous.bytes.toString("utf8") !== canonicalJson(p))
@@ -27935,7 +28686,7 @@ class Workflows {
27935
28686
  this.grants.delete(key2);
27936
28687
  if (this.grants.size >= 16)
27937
28688
  throw new ContractError("capacity");
27938
- const grant = randomUUID23(), expiresAt = Date.now() + 120000;
28689
+ const grant = randomUUID22(), expiresAt = Date.now() + 120000;
27939
28690
  effect();
27940
28691
  this.grants.set(grant, {
27941
28692
  commandId,
@@ -27963,7 +28714,7 @@ class Workflows {
27963
28714
  throw new ContractError("conflict");
27964
28715
  return { ...this.view(commandId), commandId };
27965
28716
  }
27966
- if (this.files.directory(dirname22(acceptedPath)))
28717
+ if (this.files.directory(dirname23(acceptedPath)))
27967
28718
  throw new ContractError("quarantine");
27968
28719
  let proposal;
27969
28720
  let target2;
@@ -28013,8 +28764,8 @@ class Workflows {
28013
28764
  };
28014
28765
  const abort = new AbortController;
28015
28766
  let begin;
28016
- const ready2 = new Promise((resolve12) => {
28017
- begin = resolve12;
28767
+ const ready2 = new Promise((resolve13) => {
28768
+ begin = resolve13;
28018
28769
  });
28019
28770
  const live2 = {
28020
28771
  run: run2,
@@ -28077,7 +28828,7 @@ class Workflows {
28077
28828
  if (live2.run.steps.length >= MAX_STEPS)
28078
28829
  throw new ContractError("capacity");
28079
28830
  const s = {
28080
- id: `${clipUnits(id, STEP_UNITS)}-${randomUUID23()}`,
28831
+ id: `${clipUnits(id, STEP_UNITS)}-${randomUUID22()}`,
28081
28832
  ...childRunId ? { childRunId } : {},
28082
28833
  kind,
28083
28834
  ...childRunId ? {
@@ -28129,11 +28880,11 @@ class Workflows {
28129
28880
  stepId: s.id,
28130
28881
  result
28131
28882
  });
28132
- const shown = preview ?? (result.text || result.output);
28883
+ const shown2 = preview ?? (result.text || result.output);
28133
28884
  s.status = result.outcome;
28134
- 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());
28135
28886
  s.exitCode = result.exitCode;
28136
- s.truncated = result.truncated || Buffer.byteLength(shown) > Buffer.byteLength(s.text);
28887
+ s.truncated = result.truncated || Buffer.byteLength(shown2) > Buffer.byteLength(s.text);
28137
28888
  if (!result.closed)
28138
28889
  this.o.owner.quarantine();
28139
28890
  this.save(live2);
@@ -28141,12 +28892,12 @@ class Workflows {
28141
28892
  async worker(live2, cwd, id, prompt, readonly, version, roots) {
28142
28893
  this.assertRunning(live2);
28143
28894
  const model = this.model(version, true);
28144
- const role2 = loadAgentDefinitions().find((r) => r.role === (readonly ? "design-explorer" : "implementation-worker"));
28145
- if (!role2)
28895
+ const role3 = loadAgentDefinitions().find((r) => r.role === (readonly ? "design-explorer" : "implementation-worker"));
28896
+ if (!role3)
28146
28897
  throw new ContractError("unavailable");
28147
28898
  if (cwd !== this.cwd)
28148
28899
  await assertWorktree(this.cwd, cwd);
28149
- const childRunId = randomUUID23(), op = randomUUID23();
28900
+ const childRunId = randomUUID22(), op = randomUUID22();
28150
28901
  const plan = live2.proposal?.plan;
28151
28902
  const request3 = decodeWorkerPublicRequest({
28152
28903
  protocol: 2,
@@ -28157,9 +28908,9 @@ class Workflows {
28157
28908
  assignmentId: id,
28158
28909
  purpose: readonly ? "research" : "edit",
28159
28910
  model,
28160
- role: { role: role2.role, sha256: role2.sha256 },
28911
+ role: { role: role3.role, sha256: role3.sha256 },
28161
28912
  context: plan ? workflowContext(plan) : "Read applicable AGENTS.md and existing project documentation, including .cadence/project.md. Cite evidence and separate observations from assumptions.",
28162
- instructions: `${role2.content}
28913
+ instructions: `${role3.content}
28163
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.`,
28164
28915
  prompt: text(prompt, 32768, true),
28165
28916
  handoff: { graphRevision: 1, inputs: [] }
@@ -28223,7 +28974,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28223
28974
  const running = Promise.resolve().then(() => launchWorkflowWorker(prepared.prepared, cwd, live2.abort.signal, {
28224
28975
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
28225
28976
  ownerSecrets: this.o.secrets(),
28226
- roots: roots?.length ? roots.map((p) => resolve11(cwd, p)) : [cwd],
28977
+ roots: roots?.length ? roots.map((p) => resolve12(cwd, p)) : [cwd],
28227
28978
  onLifecycle: (event) => {
28228
28979
  if (!step.timing)
28229
28980
  return;
@@ -28304,7 +29055,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28304
29055
  const shell = "check" in operation;
28305
29056
  if (cwd !== this.cwd && shell)
28306
29057
  await assertWorktree(this.cwd, cwd);
28307
- const id = randomUUID23();
29058
+ const id = randomUUID22();
28308
29059
  this.write(this.path(live2.run.id, `operations/${id}-intent.json`), {
28309
29060
  cwd,
28310
29061
  args: shell ? operation.check : operation.git
@@ -28318,7 +29069,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28318
29069
  command: shell ? process.platform === "win32" ? environment2.COMSPEC ?? "cmd.exe" : "/bin/sh" : "git",
28319
29070
  args: shell ? process.platform === "win32" ? ["/d", "/s", "/c", `"${operation.check.command}"`] : ["-c", operation.check.command] : gitArguments([
28320
29071
  "-c",
28321
- `core.hooksPath=${join32(this.root, "empty-hooks")}`,
29072
+ `core.hooksPath=${join35(this.root, "empty-hooks")}`,
28322
29073
  "-c",
28323
29074
  "commit.gpgsign=false",
28324
29075
  "-c",
@@ -28431,7 +29182,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28431
29182
  if (await gitHead(cwd) !== before)
28432
29183
  throw new ContractError("stale");
28433
29184
  }
28434
- async commit(live2, cwd, allowed, message, before, title) {
29185
+ async commit(live2, cwd, allowed, message2, before, title) {
28435
29186
  await this.unchangedHead(cwd, before);
28436
29187
  const changes = await assertWorkflowScope(cwd, allowed);
28437
29188
  if (!changes.length)
@@ -28451,7 +29202,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28451
29202
  ]);
28452
29203
  if (staged.code === 0)
28453
29204
  return null;
28454
- await git(["commit", "--no-verify", "-m", message]);
29205
+ await git(["commit", "--no-verify", "-m", message2]);
28455
29206
  const commit = await gitHead(cwd);
28456
29207
  await assertWorkflowCommit(cwd, before, commit, allowed);
28457
29208
  return commit;
@@ -28460,7 +29211,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
28460
29211
  async review(live2, cwd, p) {
28461
29212
  live2.run.phase = "reviewing";
28462
29213
  this.save(live2);
28463
- 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.
28464
29215
  Files: ${p.plan.tasks.flatMap((t) => t.writes).join(", ")}`, true, p.model);
28465
29216
  this.success(result);
28466
29217
  const verdict = reviewVerdict(result.text);
@@ -28555,7 +29306,7 @@ ${changed.map((p) => `- ${p}`).join(`
28555
29306
  publish(live2, cwd, plan, names3, changed) {
28556
29307
  for (const name of names3) {
28557
29308
  const file = safeWorkflowFile(cwd, name);
28558
- if (!safeDirectory(dirname22(file), true))
29309
+ if (!safeDirectory(dirname23(file), true))
28559
29310
  throw new ContractError("forbidden");
28560
29311
  writeFileSync5(file, this.documentBody(live2, cwd, plan, name, changed), {
28561
29312
  flag: name === ".cadence/project.md" ? "w" : "wx"
@@ -28565,17 +29316,17 @@ ${changed.map((p) => `- ${p}`).join(`
28565
29316
  worktreeHome(id) {
28566
29317
  if (nested(this.cwd, this.worktreeRoot))
28567
29318
  throw new ContractError("unsupported-context");
28568
- for (const directory of [dirname22(this.worktreeRoot), this.worktreeRoot]) {
29319
+ for (const directory of [dirname23(this.worktreeRoot), this.worktreeRoot]) {
28569
29320
  if (!safeDirectory(directory, true))
28570
29321
  throw new ContractError("forbidden");
28571
- const st = lstatSync21(directory);
29322
+ const st = lstatSync22(directory);
28572
29323
  if (process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
28573
29324
  throw new ContractError("forbidden");
28574
29325
  }
28575
- const home = join32(this.worktreeRoot, decodeId(id));
29326
+ const home = join35(this.worktreeRoot, decodeId(id));
28576
29327
  if (safeDirectory(home))
28577
29328
  throw new ContractError("conflict");
28578
- safeDirectory(join32(home, "tasks"), true);
29329
+ safeDirectory(join35(home, "tasks"), true);
28579
29330
  return home;
28580
29331
  }
28581
29332
  async merge(live2, candidate) {
@@ -28643,7 +29394,7 @@ ${result.output}`}`);
28643
29394
  } finally {
28644
29395
  this.closeStep(live2, step);
28645
29396
  }
28646
- for (const directory of [join32(home, "tasks"), home])
29397
+ for (const directory of [join35(home, "tasks"), home])
28647
29398
  try {
28648
29399
  rmdirSync(directory);
28649
29400
  } catch {}
@@ -28675,8 +29426,8 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
28675
29426
  throw new ContractError("invalid");
28676
29427
  const base = target2.head;
28677
29428
  const home = this.worktreeHome(live2.run.id);
28678
- const taskHome = join32(home, "tasks");
28679
- const integration = join32(home, "integration");
29429
+ const taskHome = join35(home, "tasks");
29430
+ const integration = join35(home, "integration");
28680
29431
  await this.gitStep(live2, this.cwd, "worktree-integration", (git) => git(["worktree", "add", "--detach", integration, base]));
28681
29432
  await assertWorktree(this.cwd, integration);
28682
29433
  await this.setup(live2, integration, plan);
@@ -28693,7 +29444,7 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
28693
29444
  live2.run.phase = "implementing";
28694
29445
  this.save(live2);
28695
29446
  const outcomes2 = await Promise.allSettled(batch.map(async (task) => {
28696
- const cwd = join32(taskHome, task.id);
29447
+ const cwd = join35(taskHome, task.id);
28697
29448
  await this.gitStep(live2, this.cwd, `worktree-${task.id}`, (git) => git(["worktree", "add", "--detach", cwd, base]));
28698
29449
  const picks2 = workflowAncestors(plan.tasks, task.id).map((dep) => commits.get(dep.id)).filter((c) => !!c);
28699
29450
  if (picks2.length)
@@ -28758,7 +29509,7 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
28758
29509
  const file = safeWorkflowFile(this.cwd, name), before = documentBefore.get(name) ?? null;
28759
29510
  if (before !== pathIdentity(this.cwd, name))
28760
29511
  throw new WorkflowRefusal("conflict", `${name} changed during the run; the generated note was not written.`);
28761
- if (!safeDirectory(dirname22(file), true))
29512
+ if (!safeDirectory(dirname23(file), true))
28762
29513
  throw new ContractError("unavailable");
28763
29514
  writeFileSync5(file, this.documentBody(live2, this.cwd, plan, name, [...live2.delivered].sort(), true), { flag: before ? "w" : "wx" });
28764
29515
  }
@@ -28860,11 +29611,17 @@ class Workbench {
28860
29611
  files;
28861
29612
  workflows;
28862
29613
  cadence;
29614
+ migration;
28863
29615
  projectRoot;
28864
29616
  opening = new Map;
28865
29617
  constructor(o) {
28866
29618
  this.o = o;
28867
29619
  this.conversations = new Conversations(o);
29620
+ this.migration = new ConversationMigration({
29621
+ ...o,
29622
+ cwd: this.conversations.cwd,
29623
+ sessions: this.conversations.sessions
29624
+ });
28868
29625
  this.workflows = new Workflows(o);
28869
29626
  this.cadence = new ConversationWorkflow({
28870
29627
  ...o,
@@ -28873,14 +29630,10 @@ class Workbench {
28873
29630
  });
28874
29631
  this.conversations.assertSettled();
28875
29632
  this.files = new WorkbenchFiles(o.cwd, [o.coordination.files.namespace, o.agentDir], o.secrets);
28876
- this.projectRoot = join33(o.coordination.files.namespace, "workbench-projects-v1");
29633
+ this.projectRoot = join36(o.coordination.files.namespace, "workbench-projects-v1");
28877
29634
  }
28878
29635
  closeReads() {
28879
- try {
28880
- this.workflows.closeHistory();
28881
- } finally {
28882
- this.conversations.closeReads();
28883
- }
29636
+ this.workflows.closeHistory();
28884
29637
  }
28885
29638
  read(value) {
28886
29639
  const request3 = decodeWorkbenchRead(value);
@@ -28890,10 +29643,10 @@ class Workbench {
28890
29643
  return { kind: request3.kind, state: this.cadence.state(request3.id) };
28891
29644
  case "workflow-active": {
28892
29645
  const active2 = this.workflows.activeRuns();
28893
- return {
28894
- ...active2,
28895
- links: this.cadence.links(active2.runs.map((run2) => run2.id))
28896
- };
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] };
28897
29650
  }
28898
29651
  case "workflow-history":
28899
29652
  return this.workflows.history(request3.after, request3.scan);
@@ -28907,7 +29660,7 @@ class Workbench {
28907
29660
  return this.conversations.origin(request3.taskId);
28908
29661
  case "conversation-active":
28909
29662
  case "conversations": {
28910
- 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);
28911
29664
  if (value2.kind !== "conversations" && value2.kind !== "conversation-active")
28912
29665
  return value2;
28913
29666
  return {
@@ -28919,11 +29672,15 @@ class Workbench {
28919
29672
  };
28920
29673
  }
28921
29674
  case "conversation":
28922
- return this.conversations.conversation(request3.id);
29675
+ return this.conversations.conversation(request3.id, request3.leaf, request3.known);
28923
29676
  case "conversation-turn":
28924
- return this.conversations.turnSteps(request3.id, request3.ordinal, request3.before);
29677
+ return this.conversations.turnSteps(request3.id, request3.leaf, request3.ordinal, request3.before);
28925
29678
  case "conversation-step":
28926
- return this.conversations.step(request3.id, request3.turnId, request3.step, request3.part);
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() };
28927
29684
  case "files":
28928
29685
  return this.files.list(request3.path);
28929
29686
  case "file":
@@ -28979,7 +29736,7 @@ class Workbench {
28979
29736
  for (let e = directory.readSync();e; e = directory.readSync()) {
28980
29737
  if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries2.length > 128)
28981
29738
  throw new ContractError("corrupt-selected");
28982
- const saved = files.read(join33(this.projectRoot, e.name));
29739
+ const saved = files.read(join36(this.projectRoot, e.name));
28983
29740
  if (!saved)
28984
29741
  throw new ContractError("corrupt-selected");
28985
29742
  const row = closed(parseWireJson(saved.bytes.toString("utf8")), [
@@ -29032,6 +29789,15 @@ class Workbench {
29032
29789
  this.conversations.interrupt(request3.conversationId, request3.turnId, request3.epoch);
29033
29790
  return { kind: "accepted", commandId: request3.commandId };
29034
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
+ }
29035
29801
  this.o.owner.lease.assert();
29036
29802
  if (!this.o.projectsEnabled)
29037
29803
  throw new ContractError("unsupported-context");
@@ -29048,7 +29814,7 @@ class Workbench {
29048
29814
  if (this.opening.size >= 64)
29049
29815
  throw new ContractError("capacity");
29050
29816
  const path = this.files.directory(request3.path);
29051
- 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`);
29052
29818
  const files = this.o.coordination.files;
29053
29819
  if (files.read(marker2))
29054
29820
  throw new ContractError("receipt-inconclusive");
@@ -29066,7 +29832,7 @@ class Workbench {
29066
29832
  }
29067
29833
  const opened = await openProjectDirectory(path, this.o.coordination.stateHome, this.o.agentDir, this.o.hostUrl);
29068
29834
  for (const root of [this.o.cwd, opened.path]) {
29069
- const entry = join33(this.projectRoot, `${hash2(root)}.json`);
29835
+ const entry = join36(this.projectRoot, `${hash2(root)}.json`);
29070
29836
  const saved = files.read(entry);
29071
29837
  if (!saved)
29072
29838
  files.create(entry, canonicalJson({ path: root }));
@@ -29096,7 +29862,7 @@ async function predecessorExited() {
29096
29862
  } catch {
29097
29863
  return;
29098
29864
  }
29099
- await new Promise((resolve12) => setTimeout(resolve12, 100));
29865
+ await new Promise((resolve13) => setTimeout(resolve13, 100));
29100
29866
  }
29101
29867
  }
29102
29868
  async function healBeforeStart(c) {
@@ -29106,8 +29872,8 @@ async function healBeforeStart(c) {
29106
29872
  if (lock.status === "blocked" || lock.status === "live")
29107
29873
  throw new ContractError("registry-locked");
29108
29874
  await registry.sweep();
29109
- const own3 = await healProject(c, { responsive: async () => true });
29110
- if (own3.status === "blocked")
29875
+ const own4 = await healProject(c, { responsive: async () => true });
29876
+ if (own4.status === "blocked")
29111
29877
  throw new ContractError("quarantine");
29112
29878
  }
29113
29879
  function legacy(store, budget, reader) {
@@ -29134,8 +29900,8 @@ function legacy(store, budget, reader) {
29134
29900
  decodeId(entry.name);
29135
29901
  if (created.has(entry.name))
29136
29902
  continue;
29137
- const path = join34(store.tasks, entry.name, "task.json");
29138
- const size2 = lstatSync22(path).size;
29903
+ const path = join37(store.tasks, entry.name, "task.json");
29904
+ const size2 = lstatSync23(path).size;
29139
29905
  if (size2 > 128 * 1024)
29140
29906
  throw new ContractError("corrupt-selected");
29141
29907
  budget.reserve(size2);
@@ -29188,7 +29954,7 @@ var processLifetime = {
29188
29954
  }
29189
29955
  };
29190
29956
  async function createServiceHost(value, sourceBuild, lifetime) {
29191
- const embedded = "d0edc9d93f682dd7c637bd28cdb756b823ad8eafeabebc63479bee1bac5b2b55";
29957
+ const embedded = "3305384b10bb0c658565426ec2291d0237533cb9ae7aeb1d63f42ac8824b0c82";
29192
29958
  if (embedded && sourceBuild)
29193
29959
  throw new ContractError("unsupported-context");
29194
29960
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -29272,8 +30038,8 @@ async function createServiceHost(value, sourceBuild, lifetime) {
29272
30038
  let timer;
29273
30039
  await Promise.race([
29274
30040
  owner?.idle(),
29275
- new Promise((resolve12) => {
29276
- timer = setTimeout(resolve12, FAULT_SETTLE_MS);
30041
+ new Promise((resolve13) => {
30042
+ timer = setTimeout(resolve13, FAULT_SETTLE_MS);
29277
30043
  })
29278
30044
  ]);
29279
30045
  clearTimeout(timer);