@abelxiaoxing/cadence 2.0.27 → 2.0.28

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.
@@ -4070,6 +4070,10 @@ function decodeCadenceConversation(v) {
4070
4070
  ...degraded ? { notice: text(o.notice, 1024, true) } : {}
4071
4071
  };
4072
4072
  }
4073
+ function decodeChatCursor(value) {
4074
+ const o = closed(value, ["id", "updatedAt"]);
4075
+ return { id: decodeId(o.id), updatedAt: integer(o.updatedAt, 0) };
4076
+ }
4073
4077
  var statuses = [
4074
4078
  "queued",
4075
4079
  "running",
@@ -4082,6 +4086,15 @@ var statuses = [
4082
4086
  function decodeWorkbenchRead(v) {
4083
4087
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
4084
4088
  switch (kind) {
4089
+ case "conversation-transcript": {
4090
+ const o = closed(v, ["kind", "id", "turnId", "page"]);
4091
+ return {
4092
+ kind,
4093
+ id: decodeId(o.id),
4094
+ turnId: decodeId(o.turnId),
4095
+ page: integer(o.page, 0)
4096
+ };
4097
+ }
4085
4098
  case "cadence-conversation": {
4086
4099
  const o = closed(v, ["kind", "id"]);
4087
4100
  return { kind, id: decodeId(o.id) };
@@ -4107,7 +4120,20 @@ function decodeWorkbenchRead(v) {
4107
4120
  const o = closed(v, ["kind", "id"]);
4108
4121
  return { kind, id: decodeId(o.id) };
4109
4122
  }
4110
- case "conversations":
4123
+ case "conversations": {
4124
+ const after = Object.hasOwn(v, "after"), scan = Object.hasOwn(v, "scan");
4125
+ const o = closed(v, [
4126
+ "kind",
4127
+ ...after ? ["after"] : [],
4128
+ ...scan ? ["scan"] : []
4129
+ ]);
4130
+ return {
4131
+ kind,
4132
+ ...after ? { after: nullable(o.after, decodeChatCursor) } : {},
4133
+ ...scan ? { scan: decodeId(o.scan) } : {}
4134
+ };
4135
+ }
4136
+ case "conversation-active":
4111
4137
  case "projects":
4112
4138
  closed(v, ["kind"]);
4113
4139
  return { kind };
@@ -4246,13 +4272,20 @@ function decodeWorkbenchCommand(v) {
4246
4272
  function decodeChatTurn(v) {
4247
4273
  const keys2 = ["id", "epoch", "status", "items", "notice"];
4248
4274
  const current = v !== null && typeof v === "object" && Object.hasOwn(v, "omitted");
4249
- const o = closed(v, current ? [...keys2, "omitted"] : keys2);
4275
+ const paged = v !== null && typeof v === "object" && Object.hasOwn(v, "transcript");
4276
+ const o = closed(v, [
4277
+ ...keys2,
4278
+ ...current ? ["omitted"] : [],
4279
+ ...paged ? ["transcript"] : []
4280
+ ]);
4281
+ const transcript = paged ? closed(o.transcript, ["pages"]) : null;
4250
4282
  const omitted = current ? closed(o.omitted, ["thinking", "media", "other"]) : null;
4251
4283
  return {
4252
4284
  id: decodeId(o.id),
4253
4285
  epoch: decodeId(o.epoch),
4254
4286
  status: oneOf(o.status, statuses),
4255
4287
  notice: text(o.notice, 1024),
4288
+ ...transcript ? { transcript: { pages: integer(transcript.pages, 0) } } : {},
4256
4289
  omitted: {
4257
4290
  thinking: omitted ? bool(omitted.thinking) : false,
4258
4291
  media: omitted ? bool(omitted.media) : false,
@@ -4293,6 +4326,13 @@ function decodeChatSummary(v) {
4293
4326
  function decodeWorkbenchResult(v) {
4294
4327
  canonicalJson(v, 512 * 1024);
4295
4328
  const k = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
4329
+ if (k === "conversation-transcript") {
4330
+ const o2 = closed(v, ["kind", "conversationId", "page", "turn"]);
4331
+ const turn = decodeChatTurn(o2.turn), page = integer(o2.page, 0);
4332
+ if (!turn.transcript || page >= turn.transcript.pages)
4333
+ throw new ContractError("invalid");
4334
+ return { kind: k, conversationId: decodeId(o2.conversationId), page, turn };
4335
+ }
4296
4336
  if (k === "workflow-transcript") {
4297
4337
  const o2 = closed(v, ["kind", "runId", "stepId", "turn"]);
4298
4338
  return {
@@ -4378,9 +4418,26 @@ function decodeWorkbenchResult(v) {
4378
4418
  conversationId: nullable(o2.conversationId, decodeId)
4379
4419
  };
4380
4420
  }
4381
- if (kind === "conversations") {
4421
+ if (kind === "conversations-progress") {
4422
+ const o2 = closed(v, ["kind", "after", "scan"]);
4423
+ return {
4424
+ kind,
4425
+ after: nullable(o2.after, decodeChatCursor),
4426
+ scan: decodeId(o2.scan)
4427
+ };
4428
+ }
4429
+ if (kind === "conversation-active") {
4382
4430
  const o2 = closed(v, ["kind", "entries"]);
4383
- return { kind, entries: list(o2.entries, 200, decodeChatSummary) };
4431
+ return { kind, entries: list(o2.entries, 8, decodeChatSummary) };
4432
+ }
4433
+ if (kind === "conversations") {
4434
+ const paged = Object.hasOwn(v, "next");
4435
+ const o2 = closed(v, ["kind", "entries", ...paged ? ["next"] : []]);
4436
+ return {
4437
+ kind,
4438
+ entries: list(o2.entries, 200, decodeChatSummary),
4439
+ ...paged ? { next: nullable(o2.next, decodeChatCursor) } : {}
4440
+ };
4384
4441
  }
4385
4442
  if (kind === "conversation") {
4386
4443
  const o2 = closed(v, ["kind", "summary", "turns", "before"]);
@@ -9890,7 +9947,7 @@ async function createGateway(value, hostUrl, source) {
9890
9947
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
9891
9948
  const web = loadWebAssets(source?.webDirectory);
9892
9949
  const build2 = {
9893
- contractHash: "b6935a8daa09f70de094136c18d8e3588fdd34fc24b9a8fe95e465de11ddae8d",
9950
+ contractHash: "45f3666b0fc0d853e95e618b50156819f6282ce648e9703b876d9658ae15b78f",
9894
9951
  assets: {
9895
9952
  sourceHash: web.manifest.sourceHash,
9896
9953
  contractHash: web.manifest.contractHash,
@@ -10475,7 +10532,7 @@ Content-Length: 0\r
10475
10532
 
10476
10533
  // src/service/host.ts
10477
10534
  import { spawn as spawn4 } from "node:child_process";
10478
- import { lstatSync as lstatSync20, opendirSync as opendirSync14 } from "node:fs";
10535
+ import { lstatSync as lstatSync21, opendirSync as opendirSync15 } from "node:fs";
10479
10536
  import { join as join32 } from "node:path";
10480
10537
  import { fileURLToPath as fileURLToPath6 } from "node:url";
10481
10538
 
@@ -21179,13 +21236,14 @@ import { fileURLToPath as fileURLToPath4 } from "node:url";
21179
21236
 
21180
21237
  // src/conversation-context.mjs
21181
21238
  var CONTEXT_BYTES = 2 * 1024 * 1024;
21182
- var clean = (s, secrets, max = CONTEXT_BYTES) => sanitizeText(text(s, max), secrets);
21239
+ var CONTEXT_RECORD_BYTES = LIMITS.detailBytes;
21240
+ var clean = (s, secrets, max = CONTEXT_RECORD_BYTES) => sanitizeText(text(s, max), secrets);
21183
21241
  function argumentsData(value, secrets) {
21184
21242
  const sanitizer = new DetailSanitizer("canonical-json", secrets);
21185
- const source = sanitizer.write(canonicalJson(value, 64 * 1024)) + sanitizer.end();
21243
+ const source = sanitizer.write(canonicalJson(value, CONTEXT_RECORD_BYTES)) + sanitizer.end();
21186
21244
  if (sanitizer.limited)
21187
21245
  throw new Error("Unsupported context arguments");
21188
- return parseWireJson(source, 64 * 1024);
21246
+ return parseWireJson(source, CONTEXT_RECORD_BYTES);
21189
21247
  }
21190
21248
  function own2(value, key2) {
21191
21249
  const d = value && typeof value === "object" ? Object.getOwnPropertyDescriptor(value, key2) : undefined;
@@ -22165,12 +22223,26 @@ function runProcess(spec) {
22165
22223
  contextStream?.on("data", (chunk) => {
22166
22224
  if (settled || stopping)
22167
22225
  return;
22168
- contextBytes += chunk.length;
22169
- if (contextBytes > CONTEXT_BYTES) {
22226
+ try {
22227
+ let offset = 0;
22228
+ while (offset < chunk.length) {
22229
+ const end = chunk.indexOf(10, offset);
22230
+ const part = chunk.subarray(offset, end < 0 ? chunk.length : end);
22231
+ contextBytes += part.length;
22232
+ if (contextBytes > CONTEXT_RECORD_BYTES)
22233
+ throw new Error("Checkpoint record too large");
22234
+ contextChunks.push(part);
22235
+ if (end < 0)
22236
+ break;
22237
+ const source = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(contextChunks, contextBytes));
22238
+ contextChunks.length = 0;
22239
+ contextBytes = 0;
22240
+ spec.onContext?.(source);
22241
+ offset = end + 1;
22242
+ }
22243
+ } catch {
22170
22244
  stop("failed");
22171
- return;
22172
22245
  }
22173
- contextChunks.push(chunk);
22174
22246
  });
22175
22247
  contextStream?.once("end", () => {
22176
22248
  contextEnded = true;
@@ -22230,9 +22302,9 @@ function runProcess(spec) {
22230
22302
  const close = () => {
22231
22303
  if (spec.onContext && !stopping && code2 === 0) {
22232
22304
  try {
22233
- if (!contextEnded)
22305
+ if (!contextEnded || contextBytes)
22234
22306
  throw new Error("Context EOF missing");
22235
- spec.onContext(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(contextChunks)));
22307
+ spec.onContextEnd?.();
22236
22308
  } catch {
22237
22309
  stopping = "failed";
22238
22310
  }
@@ -22335,22 +22407,33 @@ function launchConversation(prepared, conversation, signal, options) {
22335
22407
  if (!encoded2 || encoded2.input !== input)
22336
22408
  throw new Error("Invalid chat launch");
22337
22409
  const secrets = encoded2.secrets;
22410
+ let contextCount = 0, contextComplete = false;
22338
22411
  return launchEncoded(encoded2, signal, options.timeoutMs, {
22339
22412
  maySignal: options.maySignal,
22340
22413
  onNative: options.onNative,
22341
22414
  onCoordinator: options.onCoordinator,
22342
22415
  onFrame: (frame) => options.onFrame(frame, secrets),
22343
22416
  onContext: (source) => {
22344
- const value = closed(parseWireJson(source, CONTEXT_BYTES), [
22345
- "schema",
22346
- "messages"
22347
- ]);
22348
- if (value.schema !== "cadence-conversation-context/1")
22417
+ if (contextComplete)
22418
+ throw new Error("Checkpoint after end");
22419
+ const value = parseWireJson(source, CONTEXT_RECORD_BYTES);
22420
+ if (value.schema === "cadence-conversation-stream-end/1") {
22421
+ const record3 = closed(value, ["schema", "count"]);
22422
+ if (record3.count !== contextCount)
22423
+ throw new Error("Invalid checkpoint count");
22424
+ contextComplete = true;
22425
+ return;
22426
+ }
22427
+ const record2 = closed(value, ["schema", "message"]);
22428
+ if (record2.schema !== "cadence-conversation-stream/1")
22349
22429
  throw new Error("Invalid checkpoint");
22350
- options.onContext(conversationMessages(value.messages, [
22351
- ...options.ownerSecrets(),
22352
- ...secrets
22353
- ]));
22430
+ options.onContext(conversationMessages([record2.message], [...options.ownerSecrets(), ...secrets])[0]);
22431
+ contextCount++;
22432
+ },
22433
+ onContextEnd: () => {
22434
+ if (!contextComplete)
22435
+ throw new Error("Incomplete checkpoint");
22436
+ options.onContextEnd();
22354
22437
  }
22355
22438
  });
22356
22439
  });
@@ -24143,12 +24226,12 @@ class ServiceOwner {
24143
24226
  }
24144
24227
 
24145
24228
  // src/service/workbench.ts
24146
- import { opendirSync as opendirSync13 } from "node:fs";
24229
+ import { opendirSync as opendirSync14 } from "node:fs";
24147
24230
  import { join as join31 } from "node:path";
24148
24231
 
24149
24232
  // src/service/conversation-workflow.ts
24150
- import { randomUUID as randomUUID20 } from "node:crypto";
24151
- import { opendirSync as opendirSync10 } from "node:fs";
24233
+ import { randomUUID as randomUUID21 } from "node:crypto";
24234
+ import { opendirSync as opendirSync11 } from "node:fs";
24152
24235
  import { dirname as dirname17, join as join27 } from "node:path";
24153
24236
 
24154
24237
  // src/cadence-instructions.ts
@@ -24160,12 +24243,246 @@ Present the returned complete plan and invite a single clear execution approval
24160
24243
  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.`;
24161
24244
 
24162
24245
  // src/service/conversations.ts
24163
- import { randomUUID as randomUUID19 } from "node:crypto";
24164
- import { lstatSync as lstatSync15, opendirSync as opendirSync9, realpathSync as realpathSync8, statfsSync as statfsSync2 } from "node:fs";
24246
+ import { randomUUID as randomUUID20 } from "node:crypto";
24247
+ import { lstatSync as lstatSync16, opendirSync as opendirSync10, realpathSync as realpathSync8, statfsSync as statfsSync2 } from "node:fs";
24165
24248
  import { dirname as dirname16, join as join26 } from "node:path";
24249
+
24250
+ // src/service/conversation-history.ts
24251
+ import { randomUUID as randomUUID19 } from "node:crypto";
24252
+ import { lstatSync as lstatSync15, opendirSync as opendirSync9 } from "node:fs";
24253
+ var CONVERSATION_PAGE = 50;
24254
+ var SCAN_ENTRIES = 8;
24255
+ var SCANS = 16;
24256
+ var IDLE_MS = 120000;
24257
+ var compareChats = (a, b) => b.updatedAt - a.updatedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
24258
+
24259
+ class ConversationHistory {
24260
+ path;
24261
+ directory;
24262
+ summary;
24263
+ scans = new Map;
24264
+ closed = false;
24265
+ constructor(path, directory, summary2) {
24266
+ this.path = path;
24267
+ this.directory = directory;
24268
+ this.summary = summary2;
24269
+ }
24270
+ incarnation() {
24271
+ const st = lstatSync15(this.path, { bigint: true });
24272
+ if (!st.isDirectory() || st.isSymbolicLink())
24273
+ throw new ContractError("corrupt-selected");
24274
+ return `${st.dev}:${st.ino}`;
24275
+ }
24276
+ read(after, cursor) {
24277
+ if (this.closed)
24278
+ throw new ContractError("unavailable");
24279
+ let state;
24280
+ if (cursor) {
24281
+ const selected2 = this.scans.get(cursor);
24282
+ if (!selected2 || selected2.after?.id !== after?.id || selected2.after?.updatedAt !== after?.updatedAt)
24283
+ throw new ContractError("stale");
24284
+ this.scans.delete(cursor);
24285
+ clearTimeout(selected2.timer);
24286
+ state = selected2;
24287
+ } else {
24288
+ if (!this.directory())
24289
+ return { kind: "conversations", entries: [], next: null };
24290
+ if (this.scans.size >= SCANS)
24291
+ throw new ContractError("capacity");
24292
+ const incarnation3 = this.incarnation();
24293
+ state = {
24294
+ dir: opendirSync9(this.path),
24295
+ incarnation: incarnation3,
24296
+ after,
24297
+ entries: []
24298
+ };
24299
+ }
24300
+ let suspended = false;
24301
+ try {
24302
+ if (!this.directory() || this.incarnation() !== state.incarnation)
24303
+ throw new ContractError("stale");
24304
+ const started = performance.now();
24305
+ for (let n = 0;n < SCAN_ENTRIES; n++) {
24306
+ if (n && performance.now() - started >= LIMITS.searchMs)
24307
+ break;
24308
+ const e = state.dir.readSync();
24309
+ if (!e) {
24310
+ const entries2 = state.entries.slice(0, CONVERSATION_PAGE);
24311
+ const last = entries2.at(-1);
24312
+ return {
24313
+ kind: "conversations",
24314
+ entries: entries2,
24315
+ next: state.entries.length > entries2.length && last ? { id: last.id, updatedAt: last.updatedAt } : null
24316
+ };
24317
+ }
24318
+ if (!e.isFile() || !e.name.endsWith(".json"))
24319
+ throw new ContractError("corrupt-selected");
24320
+ const summary2 = this.summary(decodeId(e.name.slice(0, -5)));
24321
+ if (after && compareChats(summary2, after) <= 0)
24322
+ continue;
24323
+ if (state.entries.some((row) => row.id === summary2.id))
24324
+ continue;
24325
+ state.entries.push(summary2);
24326
+ state.entries.sort(compareChats);
24327
+ if (state.entries.length > CONVERSATION_PAGE + 1)
24328
+ state.entries.pop();
24329
+ }
24330
+ const scan = randomUUID19();
24331
+ state.timer = setTimeout(() => {
24332
+ this.scans.delete(scan);
24333
+ try {
24334
+ state.dir.closeSync();
24335
+ } catch {
24336
+ this.closed = true;
24337
+ }
24338
+ }, IDLE_MS);
24339
+ state.timer.unref();
24340
+ this.scans.set(scan, state);
24341
+ suspended = true;
24342
+ return { kind: "conversations-progress", after, scan };
24343
+ } finally {
24344
+ if (!suspended)
24345
+ state.dir.closeSync();
24346
+ }
24347
+ }
24348
+ close() {
24349
+ this.closed = true;
24350
+ let failed = false;
24351
+ for (const state of this.scans.values()) {
24352
+ clearTimeout(state.timer);
24353
+ try {
24354
+ state.dir.closeSync();
24355
+ } catch {
24356
+ failed = true;
24357
+ }
24358
+ }
24359
+ this.scans.clear();
24360
+ if (failed)
24361
+ throw new ContractError("unavailable");
24362
+ }
24363
+ }
24364
+
24365
+ // src/service/conversation-transcript.ts
24366
+ var TRANSCRIPT_PAGE_BYTES = 384 * 1024;
24367
+ var PREVIEW_BYTES = 300 * 1024;
24368
+ var FIELD_CHARS = 16 * 1024;
24369
+ var PREVIEW_MARK = `
24370
+ [Preview only; open the full transcript.]`;
24371
+ function part(value, offset, chars = FIELD_CHARS) {
24372
+ let end = Math.min(value.length, offset + chars);
24373
+ if (end < value.length && /[\uD800-\uDBFF]/u.test(value[end - 1]))
24374
+ end--;
24375
+ return value.slice(offset, end);
24376
+ }
24377
+
24378
+ class ConversationTranscript {
24379
+ turn;
24380
+ write;
24381
+ state = { pages: 0 };
24382
+ workingSizes = new Map;
24383
+ workingBytes = 0;
24384
+ sizes = new Map;
24385
+ bytes = 4096;
24386
+ pending = new Map;
24387
+ constructor(turn, write2) {
24388
+ this.turn = turn;
24389
+ this.write = write2;
24390
+ turn.transcript = this.state;
24391
+ for (const item of [...turn.items]) {
24392
+ this.archive(item);
24393
+ this.preview(item);
24394
+ }
24395
+ }
24396
+ item(id, role2) {
24397
+ let item = this.pending.get(id);
24398
+ if (!item) {
24399
+ if (this.pending.size >= 256)
24400
+ throw new ContractError("capacity");
24401
+ item = { id, role: role2, text: "", name: "", args: "", error: false };
24402
+ this.pending.set(id, item);
24403
+ this.preview(item);
24404
+ }
24405
+ return item;
24406
+ }
24407
+ find(id) {
24408
+ return this.pending.get(id);
24409
+ }
24410
+ preview(item) {
24411
+ if (this.pending.has(item.id)) {
24412
+ const size3 = Buffer.byteLength(item.text) + Buffer.byteLength(item.args) + Buffer.byteLength(item.name);
24413
+ this.workingBytes += size3 - (this.workingSizes.get(item.id) ?? 0);
24414
+ this.workingSizes.set(item.id, size3);
24415
+ if (this.workingBytes > 2 * LIMITS.detailBytes)
24416
+ throw new ContractError("capacity");
24417
+ }
24418
+ const clip = (value) => {
24419
+ const prefix = part(value, 0);
24420
+ return prefix.length < value.length ? prefix + PREVIEW_MARK : value;
24421
+ };
24422
+ const preview = { ...item, text: clip(item.text), args: clip(item.args) };
24423
+ const size2 = Buffer.byteLength(canonicalJson(preview, PREVIEW_BYTES));
24424
+ this.bytes += size2 - (this.sizes.get(item.id) ?? 0);
24425
+ this.sizes.set(item.id, size2);
24426
+ const at = this.turn.items.findIndex((i) => i.id === item.id);
24427
+ if (at < 0)
24428
+ this.turn.items.push(preview);
24429
+ else
24430
+ this.turn.items[at] = preview;
24431
+ while (this.bytes > PREVIEW_BYTES || this.turn.items.length > 128) {
24432
+ if (this.turn.items.length <= 2)
24433
+ throw new ContractError("oversize");
24434
+ const [removed] = this.turn.items.splice(this.turn.items[0].role === "user" ? 1 : 0, 1);
24435
+ this.bytes -= this.sizes.get(removed.id) ?? 0;
24436
+ this.sizes.delete(removed.id);
24437
+ }
24438
+ }
24439
+ complete(id) {
24440
+ const item = this.pending.get(id);
24441
+ if (!item)
24442
+ return;
24443
+ this.preview(item);
24444
+ this.archive(item);
24445
+ this.pending.delete(id);
24446
+ this.workingBytes -= this.workingSizes.get(id) ?? 0;
24447
+ this.workingSizes.delete(id);
24448
+ }
24449
+ finish() {
24450
+ for (const id of this.pending.keys())
24451
+ this.complete(id);
24452
+ }
24453
+ archive(item) {
24454
+ let text2 = 0, args = 0;
24455
+ do {
24456
+ let chars = 128 * 1024;
24457
+ const fragment = { ...item, text: "", args: part(item.args, args) };
24458
+ for (;; ) {
24459
+ fragment.text = part(item.text, text2, chars);
24460
+ try {
24461
+ if (Buffer.byteLength(fragment.text) > 256 * 1024)
24462
+ throw new ContractError("oversize");
24463
+ canonicalJson(fragment, TRANSCRIPT_PAGE_BYTES - 4096);
24464
+ break;
24465
+ } catch (error) {
24466
+ if (!(error instanceof ContractError) || error.code !== "oversize" || chars <= FIELD_CHARS)
24467
+ throw error;
24468
+ chars /= 2;
24469
+ }
24470
+ }
24471
+ const page = this.state.pages;
24472
+ if (!Number.isSafeInteger(page + 1))
24473
+ throw new ContractError("capacity");
24474
+ this.write({ turnId: this.turn.id, page, items: [fragment] });
24475
+ this.state.pages = page + 1;
24476
+ text2 += fragment.text.length;
24477
+ args += fragment.args.length;
24478
+ } while (text2 < item.text.length || args < item.args.length);
24479
+ }
24480
+ }
24481
+
24482
+ // src/service/conversations.ts
24166
24483
  var TURN_BYTES = 384 * 1024;
24167
24484
  var META_BYTES = 64 * 1024;
24168
- var SESSION_LIMIT = 200;
24485
+ var SUMMARY_CACHE = 256;
24169
24486
  var OMITTED_FLAG = {
24170
24487
  "hidden-thinking": "thinking",
24171
24488
  binary: "media",
@@ -24173,7 +24490,7 @@ var OMITTED_FLAG = {
24173
24490
  };
24174
24491
  function observedFile(path) {
24175
24492
  try {
24176
- const s = lstatSync15(path);
24493
+ const s = lstatSync16(path);
24177
24494
  return [s.dev, s.ino, s.size, s.mode, s.nlink, s.ctimeMs, s.mtimeMs].join(":");
24178
24495
  } catch (error) {
24179
24496
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
@@ -24186,14 +24503,18 @@ class ConversationCapture {
24186
24503
  turn;
24187
24504
  save;
24188
24505
  secrets;
24506
+ transcript;
24189
24507
  details = new Map;
24190
24508
  messageText = new Map;
24191
- constructor(turn, save, secrets) {
24509
+ constructor(turn, save, secrets, transcript) {
24192
24510
  this.turn = turn;
24193
24511
  this.save = save;
24194
24512
  this.secrets = secrets;
24513
+ this.transcript = transcript;
24195
24514
  }
24196
24515
  item(id, role2) {
24516
+ if (this.transcript)
24517
+ return this.transcript.item(id, role2);
24197
24518
  let item = this.turn.items.find((i) => i.id === id);
24198
24519
  if (!item) {
24199
24520
  if (this.turn.items.length >= 256)
@@ -24211,6 +24532,13 @@ class ConversationCapture {
24211
24532
  return item;
24212
24533
  }
24213
24534
  update(item, field, value, maximum) {
24535
+ if (this.transcript) {
24536
+ if (Buffer.byteLength(value) > LIMITS.detailBytes)
24537
+ throw new ContractError("capacity");
24538
+ item[field] = value;
24539
+ this.transcript.preview(item);
24540
+ return;
24541
+ }
24214
24542
  const before = item[field];
24215
24543
  try {
24216
24544
  if (Buffer.byteLength(value) > maximum)
@@ -24240,11 +24568,11 @@ class ConversationCapture {
24240
24568
  if (!d)
24241
24569
  return;
24242
24570
  d.text += e.kind === "detail-chunk" ? d.sanitizer.write(e.text) : d.sanitizer.end();
24243
- if (Buffer.byteLength(d.text) > 256 * 1024)
24571
+ if (Buffer.byteLength(d.text) > (this.transcript ? LIMITS.detailBytes : 256 * 1024))
24244
24572
  throw new ContractError("capacity");
24245
24573
  const o = d.descriptor.owner;
24246
24574
  if (o.kind === "message") {
24247
- const role2 = this.turn.items.find((i) => i.id === o.messageId)?.role;
24575
+ const role2 = (this.transcript?.find(o.messageId) ?? this.turn.items.find((i) => i.id === o.messageId))?.role;
24248
24576
  if (role2 === "assistant" && o.stage === "stream") {
24249
24577
  this.messageText.set(o.blockId, {
24250
24578
  messageId: o.messageId,
@@ -24253,7 +24581,7 @@ class ConversationCapture {
24253
24581
  this.update(this.item(o.messageId, "assistant"), "text", [...this.messageText.values()].filter((block) => block.messageId === o.messageId).map((block) => block.text).join(""), 256 * 1024);
24254
24582
  }
24255
24583
  } else if (o.kind === "message-final") {
24256
- const item = this.turn.items.find((i) => i.id === o.messageId);
24584
+ const item = this.transcript?.find(o.messageId) ?? this.turn.items.find((i) => i.id === o.messageId);
24257
24585
  if (item?.role === "assistant")
24258
24586
  this.update(item, "text", d.text, 256 * 1024);
24259
24587
  } else if (o.kind === "tool") {
@@ -24276,22 +24604,26 @@ class ConversationCapture {
24276
24604
  this.turn.notice = `worker-failure: ${e.code}`;
24277
24605
  else if (e.kind === "omitted-block" && e.block.owner.kind !== "context" && e.block.owner.kind !== "handoff")
24278
24606
  this.turn.omitted[OMITTED_FLAG[e.block.reason]] = true;
24279
- if ([...this.details.values()].reduce((size2, detail) => size2 + Buffer.byteLength(detail.text) + detail.sanitizer.retainedBytes, 0) > TURN_BYTES)
24607
+ if ([...this.details.values()].reduce((size2, detail) => size2 + Buffer.byteLength(detail.text) + detail.sanitizer.retainedBytes, 0) > (this.transcript ? 2 * LIMITS.detailBytes : TURN_BYTES))
24280
24608
  throw new ContractError("capacity");
24281
- canonicalJson(this.turn, TURN_BYTES);
24609
+ if (!this.transcript)
24610
+ canonicalJson(this.turn, TURN_BYTES);
24282
24611
  if (e.kind === "message-end") {
24283
24612
  for (const [id, block] of this.messageText)
24284
24613
  if (block.messageId === e.messageId)
24285
24614
  this.messageText.delete(id);
24286
24615
  }
24287
- if (e.kind === "message-end" || e.kind === "tool-end")
24616
+ if (e.kind === "message-end" || e.kind === "tool-end") {
24617
+ this.transcript?.complete(e.kind === "message-end" ? e.messageId : e.callId);
24288
24618
  this.save();
24619
+ }
24289
24620
  }
24290
24621
  }
24291
24622
 
24292
24623
  class Conversations {
24293
24624
  o;
24294
24625
  root;
24626
+ history;
24295
24627
  cwd;
24296
24628
  active = new Map;
24297
24629
  summaries = new Map;
@@ -24299,6 +24631,11 @@ class Conversations {
24299
24631
  this.o = o;
24300
24632
  this.root = join26(o.coordination.directory, "conversations-v1");
24301
24633
  this.cwd = realpathSync8(o.cwd);
24634
+ const sessions = join26(this.root, "sessions");
24635
+ this.history = new ConversationHistory(sessions, () => {
24636
+ this.o.owner.lease.assert();
24637
+ return this.files.directory(sessions);
24638
+ }, (id) => this.retainedSummary(id));
24302
24639
  }
24303
24640
  currentDirectory() {
24304
24641
  const current2 = resolveWorkspace(this.o.cwd);
@@ -24341,16 +24678,65 @@ class Conversations {
24341
24678
  ]);
24342
24679
  if (identity.schema !== "cadence-conversation/1" || identity.id !== id || identity.cwd !== this.cwd)
24343
24680
  throw new ContractError("corrupt-selected");
24344
- const m = closed(value, ["id", "title", "turns", "checkpoint"]);
24681
+ const indexed = value !== null && typeof value === "object" && Object.hasOwn(value, "count");
24682
+ const m = closed(value, [
24683
+ "id",
24684
+ "title",
24685
+ "turns",
24686
+ "checkpoint",
24687
+ ...indexed ? ["head", "count"] : []
24688
+ ]);
24345
24689
  const turns = list(m.turns, 1000, decodeId);
24346
- if (!turns.length || new Set(turns).size !== turns.length || m.id !== id || m.checkpoint !== null && !turns.includes(decodeId(m.checkpoint)))
24690
+ const count2 = indexed ? integer(m.count, Math.max(1, turns.length)) : turns.length;
24691
+ const head = indexed ? decodeId(m.head) : turns.at(-1);
24692
+ if (!head || !count2 || new Set(turns).size !== turns.length || m.id !== id)
24347
24693
  throw new ContractError("corrupt-selected");
24348
- return {
24694
+ const meta = {
24349
24695
  id,
24350
24696
  title: text(m.title, 512, true),
24351
24697
  turns,
24698
+ head,
24699
+ count: count2,
24352
24700
  checkpoint: m.checkpoint === null ? null : decodeId(m.checkpoint)
24353
24701
  };
24702
+ if (this.turnAt(meta, count2 - 1) !== head || indexed && this.position(meta, head) !== count2 - 1 || meta.checkpoint && !this.contains(meta, meta.checkpoint))
24703
+ throw new ContractError("corrupt-selected");
24704
+ return meta;
24705
+ }
24706
+ slotPath(id, ordinal) {
24707
+ return join26(this.root, "indices", decodeId(id), `${integer(ordinal, 0)}.json`);
24708
+ }
24709
+ turnAt(meta, ordinal) {
24710
+ if (ordinal < 0 || ordinal >= meta.count)
24711
+ throw new ContractError("stale");
24712
+ if (ordinal < meta.turns.length)
24713
+ return meta.turns[ordinal];
24714
+ const row = closed(this.read(this.slotPath(meta.id, ordinal), META_BYTES), [
24715
+ "conversationId",
24716
+ "ordinal",
24717
+ "turnId"
24718
+ ]);
24719
+ if (row.conversationId !== meta.id || row.ordinal !== ordinal)
24720
+ throw new ContractError("corrupt-selected");
24721
+ return decodeId(row.turnId);
24722
+ }
24723
+ position(meta, turnId) {
24724
+ const legacy = meta.turns.indexOf(turnId);
24725
+ if (legacy >= 0)
24726
+ return legacy;
24727
+ const value = this.read(this.path(turnId, "position.json"), META_BYTES);
24728
+ if (value === undefined)
24729
+ return -1;
24730
+ const row = closed(value, ["conversationId", "ordinal", "turnId"]);
24731
+ if (row.turnId !== turnId)
24732
+ throw new ContractError("corrupt-selected");
24733
+ const ordinal = integer(row.ordinal, 0);
24734
+ if (row.conversationId !== meta.id || ordinal >= meta.count)
24735
+ return -1;
24736
+ return this.turnAt(meta, ordinal) === turnId ? ordinal : -1;
24737
+ }
24738
+ contains(meta, turnId) {
24739
+ return this.position(meta, turnId) >= 0;
24354
24740
  }
24355
24741
  turn(id) {
24356
24742
  const live2 = this.active.get(id);
@@ -24381,10 +24767,11 @@ class Conversations {
24381
24767
  this.write(join26(this.root, "control-links", `${decodeId(id)}.json`), { schema: "cadence-conversation-control/1", conversationId: id }, META_BYTES);
24382
24768
  }
24383
24769
  hasTurn(id, turnId) {
24384
- return this.metadata(id)?.turns.includes(turnId) ?? false;
24770
+ const meta = this.metadata(id);
24771
+ return !!meta && this.contains(meta, turnId);
24385
24772
  }
24386
24773
  summary(meta) {
24387
- const head = meta.turns.at(-1), turn = this.turn(head);
24774
+ const head = meta.head, turn = this.turn(head);
24388
24775
  const accepted2 = closed(this.read(this.path(head, "accepted.json"), META_BYTES), ["command", "at"]);
24389
24776
  const command = decodeWorkbenchCommand(accepted2.command);
24390
24777
  if (command.kind !== "send" || command.commandId !== head || command.conversationId !== meta.id || command.model.epoch !== turn.epoch)
@@ -24397,25 +24784,34 @@ class Conversations {
24397
24784
  updatedAt: integer(accepted2.at, 0)
24398
24785
  };
24399
24786
  }
24400
- headKey(head) {
24401
- return [this.path(head, "turn.json"), this.path(head, "accepted.json")].map(observedFile).join("|");
24787
+ headKey(head, id, count2) {
24788
+ return [
24789
+ this.path(head, "turn.json"),
24790
+ this.path(head, "accepted.json"),
24791
+ this.path(head, "position.json"),
24792
+ this.slotPath(id, count2 - 1)
24793
+ ].map(observedFile).join("|");
24402
24794
  }
24403
24795
  retainedSummary(id) {
24404
24796
  const base = [this.metadataPath(id), this.identityPath(id)].map(observedFile).join("|");
24405
24797
  const hit = this.summaries.get(id);
24406
- if (hit && !this.active.has(hit.summary.head) && hit.key === `${base}|${this.headKey(hit.summary.head)}`)
24798
+ if (hit && !this.active.has(hit.summary.head) && hit.key === `${base}|${this.headKey(hit.summary.head, id, hit.count)}`)
24407
24799
  return { ...hit.summary };
24408
24800
  const meta = this.metadata(id);
24409
24801
  if (!meta)
24410
24802
  throw new ContractError("corrupt-selected");
24411
- const head = meta.turns.at(-1);
24412
- const key2 = `${base}|${this.headKey(head)}`;
24803
+ const head = meta.head;
24804
+ const key2 = `${base}|${this.headKey(head, id, meta.count)}`;
24413
24805
  const summary2 = this.summary(meta);
24414
24806
  this.summaries.delete(id);
24415
24807
  if (!this.active.has(head) && !["queued", "running"].includes(summary2.status)) {
24416
- if (this.summaries.size >= SESSION_LIMIT)
24417
- this.summaries.clear();
24418
- this.summaries.set(id, { key: key2, summary: { ...summary2 } });
24808
+ if (this.summaries.size >= SUMMARY_CACHE)
24809
+ this.summaries.delete(this.summaries.keys().next().value);
24810
+ this.summaries.set(id, {
24811
+ key: key2,
24812
+ summary: { ...summary2 },
24813
+ count: meta.count
24814
+ });
24419
24815
  }
24420
24816
  return summary2;
24421
24817
  }
@@ -24428,35 +24824,36 @@ class Conversations {
24428
24824
  updatedAt: live2.acceptedAt
24429
24825
  };
24430
24826
  }
24431
- list() {
24827
+ list(after = null, scan) {
24432
24828
  this.o.owner.lease.assert();
24433
- const dir = join26(this.root, "sessions");
24434
- if (!this.files.directory(dir))
24435
- return {
24436
- kind: "conversations",
24437
- entries: [...this.active.values()].map((live2) => this.liveSummary(live2))
24438
- };
24439
- const entries2 = [], opened = opendirSync9(dir);
24829
+ return this.history.read(after, scan);
24830
+ }
24831
+ activeConversations() {
24832
+ this.o.owner.lease.assert();
24833
+ return {
24834
+ kind: "conversation-active",
24835
+ entries: [...this.active.values()].map((live2) => this.liveSummary(live2))
24836
+ };
24837
+ }
24838
+ closeReads() {
24839
+ this.history.close();
24840
+ }
24841
+ assertSettled() {
24842
+ this.o.owner.lease.assert();
24843
+ const path = join26(this.root, "sessions");
24844
+ if (!this.files.directory(path))
24845
+ return;
24846
+ const dir = opendirSync10(path);
24440
24847
  try {
24441
- for (let e = opened.readSync();e; e = opened.readSync()) {
24442
- if (!e.isFile() || !e.name.endsWith(".json") || entries2.length >= SESSION_LIMIT)
24443
- throw new ContractError("capacity");
24444
- entries2.push(this.retainedSummary(decodeId(e.name.slice(0, -5))));
24848
+ for (let e = dir.readSync();e; e = dir.readSync()) {
24849
+ if (!e.isFile() || !e.name.endsWith(".json"))
24850
+ throw new ContractError("corrupt-selected");
24851
+ if (this.retainedSummary(decodeId(e.name.slice(0, -5))).status === "unknown")
24852
+ throw new ContractError("quarantine");
24445
24853
  }
24446
24854
  } finally {
24447
- opened.closeSync();
24448
- }
24449
- for (const live2 of this.active.values()) {
24450
- const at = entries2.findIndex((entry) => entry.id === live2.conversationId);
24451
- if (at < 0)
24452
- entries2.push(this.liveSummary(live2));
24453
- else
24454
- entries2[at] = this.liveSummary(live2);
24855
+ dir.closeSync();
24455
24856
  }
24456
- return {
24457
- kind: "conversations",
24458
- entries: entries2.sort((a, b) => b.updatedAt - a.updatedAt)
24459
- };
24460
24857
  }
24461
24858
  view(id, before) {
24462
24859
  this.o.owner.lease.assert();
@@ -24479,13 +24876,13 @@ class Conversations {
24479
24876
  before: null
24480
24877
  };
24481
24878
  }
24482
- let end = before === null ? meta.turns.length : meta.turns.indexOf(before);
24879
+ let end = before === null ? meta.count : this.position(meta, before);
24483
24880
  if (end < 0)
24484
24881
  throw new ContractError("stale");
24485
24882
  const turns = [];
24486
24883
  let bytes = 0;
24487
24884
  while (end > 0 && turns.length < 20) {
24488
- const turn = this.turn(meta.turns[end - 1]), size2 = Buffer.byteLength(canonicalJson(turn, TURN_BYTES));
24885
+ const turn = this.turn(this.turnAt(meta, end - 1)), size2 = Buffer.byteLength(canonicalJson(turn, TURN_BYTES));
24489
24886
  if (bytes + size2 > 400 * 1024)
24490
24887
  break;
24491
24888
  bytes += size2;
@@ -24499,36 +24896,27 @@ class Conversations {
24499
24896
  before: end > 0 ? turns[0].id : null
24500
24897
  };
24501
24898
  }
24502
- capacity() {
24503
- let bytes = 0, count2 = 0;
24504
- const visit = (directory, depth) => {
24505
- if (depth > 4 || !this.files.directory(directory))
24506
- return;
24507
- const dir = opendirSync9(directory);
24508
- try {
24509
- for (let entry = dir.readSync();entry; entry = dir.readSync()) {
24510
- if (++count2 > 1e4)
24511
- throw new ContractError("capacity");
24512
- const path = join26(directory, entry.name);
24513
- if (entry.isDirectory())
24514
- visit(path, depth + 1);
24515
- else if (entry.isFile())
24516
- bytes += lstatSync15(path).size;
24517
- else
24518
- throw new ContractError("corrupt-selected");
24519
- if (bytes + (this.active.size + 1) * (CONTEXT_BYTES + TURN_BYTES + 128 * 1024) > 512 * 1024 * 1024)
24520
- throw new ContractError("capacity");
24521
- }
24522
- } finally {
24523
- dir.closeSync();
24524
- }
24899
+ transcript(id, turnId, page) {
24900
+ this.o.owner.lease.assert();
24901
+ if (!this.hasTurn(id, turnId))
24902
+ throw new ContractError("invalid");
24903
+ const turn = this.turn(turnId);
24904
+ if (!turn.transcript || page >= turn.transcript.pages)
24905
+ throw new ContractError("stale");
24906
+ const record2 = closed(this.read(this.path(turnId, `transcript/${page}.json`), TRANSCRIPT_PAGE_BYTES), ["turnId", "page", "items"]);
24907
+ if (record2.turnId !== turnId || record2.page !== page)
24908
+ throw new ContractError("corrupt-selected");
24909
+ return {
24910
+ kind: "conversation-transcript",
24911
+ conversationId: id,
24912
+ page,
24913
+ turn: decodeChatTurn({ ...turn, items: record2.items })
24525
24914
  };
24526
- visit(this.root, 0);
24527
24915
  }
24528
24916
  attempted(conversationId, commandId) {
24529
24917
  this.o.owner.lease.assert();
24530
24918
  const meta = this.metadata(conversationId);
24531
- return this.active.has(commandId) || this.files.directory(dirname16(this.path(commandId, "accepted.json"))) || !!meta?.turns.includes(commandId) || !meta && !!this.files.read(this.identityPath(conversationId), META_BYTES);
24919
+ return this.active.has(commandId) || this.files.directory(dirname16(this.path(commandId, "accepted.json"))) || !!meta && this.contains(meta, commandId) || !meta && !!this.files.read(this.identityPath(conversationId), META_BYTES);
24532
24920
  }
24533
24921
  command(input, reply) {
24534
24922
  return {
@@ -24568,17 +24956,14 @@ class Conversations {
24568
24956
  this.files.assert(this.metadataPath(input.conversationId), beforeMeta, META_BYTES);
24569
24957
  if (!meta && this.files.read(this.identityPath(input.conversationId), META_BYTES))
24570
24958
  throw new ContractError("corrupt-selected");
24571
- if ((meta?.turns.at(-1) ?? null) !== input.head)
24959
+ if ((meta?.head ?? null) !== input.head)
24572
24960
  throw new ContractError("stale");
24573
24961
  if (meta && this.turn(input.head).status !== "completed" && (!control || ["queued", "running", "unknown"].includes(this.turn(input.head).status)))
24574
24962
  throw new ContractError("conflict");
24575
- if (this.active.size >= 8 || (meta?.turns.length ?? 0) >= 1000 || !meta && this.list().entries.length >= SESSION_LIMIT)
24963
+ if (this.active.size >= 8 || meta && !Number.isSafeInteger(meta.count + 1))
24576
24964
  throw new ContractError("capacity");
24577
24965
  if (!input.text.trim())
24578
24966
  throw new ContractError("invalid");
24579
- if (this.list().entries.some((entry) => entry.status === "unknown"))
24580
- throw new ContractError("quarantine");
24581
- this.capacity();
24582
24967
  const space = statfsSync2(this.o.coordination.directory);
24583
24968
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
24584
24969
  throw new ContractError("capacity");
@@ -24603,6 +24988,8 @@ class Conversations {
24603
24988
  id: input.conversationId,
24604
24989
  title: [...command.text.trim()].slice(0, 100).join("") || "Conversation",
24605
24990
  turns: [],
24991
+ head: turn.id,
24992
+ count: 0,
24606
24993
  checkpoint: null
24607
24994
  };
24608
24995
  const previous = next.checkpoint ? this.path(next.checkpoint, "context.json") : null;
@@ -24633,7 +25020,15 @@ class Conversations {
24633
25020
  this.write(this.identityPath(next.id), { schema: "cadence-conversation/1", id: next.id, cwd: this.cwd }, META_BYTES);
24634
25021
  this.write(this.path(turn.id, "accepted.json"), { command, at: live2.acceptedAt }, META_BYTES);
24635
25022
  live2.turnFile = this.write(this.path(turn.id, "turn.json"), turn, TURN_BYTES);
24636
- next.turns.push(turn.id);
25023
+ const position2 = {
25024
+ conversationId: next.id,
25025
+ ordinal: next.count,
25026
+ turnId: turn.id
25027
+ };
25028
+ this.write(this.slotPath(next.id, next.count), position2, META_BYTES);
25029
+ this.write(this.path(turn.id, "position.json"), position2, META_BYTES);
25030
+ next.head = turn.id;
25031
+ next.count++;
24637
25032
  live2.metaFile = this.write(this.metadataPath(next.id), next, META_BYTES, beforeMeta);
24638
25033
  control?.accept();
24639
25034
  } catch (error) {
@@ -24666,13 +25061,14 @@ class Conversations {
24666
25061
  return;
24667
25062
  }
24668
25063
  const meta = this.metadata(id);
24669
- if (!meta?.turns.includes(turnId))
25064
+ if (!meta || !this.contains(meta, turnId))
24670
25065
  throw new ContractError("invalid");
24671
25066
  if (this.turn(turnId).epoch !== epoch)
24672
25067
  throw new ContractError("stale");
24673
25068
  this.active.get(turnId)?.abort.abort();
24674
25069
  }
24675
25070
  async run(command, turn, previous, previousFile, meta, abort, control) {
25071
+ let transcript;
24676
25072
  let barrier;
24677
25073
  let authSettled;
24678
25074
  let uncertain = false;
@@ -24727,7 +25123,7 @@ class Conversations {
24727
25123
  taskId: meta.id,
24728
25124
  taskKind: control ? "research" : "code",
24729
25125
  runId: turn.id,
24730
- childRunId: randomUUID19(),
25126
+ childRunId: randomUUID20(),
24731
25127
  assignmentId: "conversation",
24732
25128
  purpose: control ? "research" : "edit",
24733
25129
  model: selected2,
@@ -24742,7 +25138,7 @@ class Conversations {
24742
25138
  });
24743
25139
  const auth = this.o.models.prepareTracked({
24744
25140
  request: request3,
24745
- operationId: randomUUID19(),
25141
+ operationId: randomUUID20(),
24746
25142
  epoch: turn.epoch,
24747
25143
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
24748
25144
  signal: abort.signal,
@@ -24760,11 +25156,15 @@ class Conversations {
24760
25156
  save();
24761
25157
  this.write(this.path(turn.id, "launch.json"), { epoch: turn.epoch, childRunId: request3.childRunId }, META_BYTES);
24762
25158
  let credentials = [];
24763
- let checkpoint;
24764
- const capture = new ConversationCapture(turn, save, () => [
24765
- ...this.o.secrets(),
24766
- ...credentials
24767
- ]);
25159
+ let checkpoint = false, contextCount = 0;
25160
+ let contextHead = null;
25161
+ transcript = new ConversationTranscript(turn, (page) => {
25162
+ const space = statfsSync2(this.o.coordination.directory);
25163
+ if (space.bavail * space.bsize - TRANSCRIPT_PAGE_BYTES < LIMITS.freeSpaceFloorBytes)
25164
+ throw new ContractError("capacity");
25165
+ this.write(this.path(turn.id, `transcript/${page.page}.json`), page, TRANSCRIPT_PAGE_BYTES);
25166
+ });
25167
+ const capture = new ConversationCapture(turn, save, () => [...this.o.secrets(), ...credentials], transcript);
24768
25168
  const running = Promise.resolve().then(() => launchConversation(prepared.prepared, {
24769
25169
  previous,
24770
25170
  agentDir: this.o.agentDir,
@@ -24773,8 +25173,21 @@ class Conversations {
24773
25173
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
24774
25174
  ownerSecrets: this.o.secrets,
24775
25175
  onCoordinator: control?.onTool,
24776
- onContext: (messages) => {
24777
- checkpoint = messages;
25176
+ onContext: (message) => {
25177
+ const space = statfsSync2(this.o.coordination.directory);
25178
+ if (space.bavail * space.bsize - CONTEXT_RECORD_BYTES < LIMITS.freeSpaceFloorBytes)
25179
+ throw new ContractError("capacity");
25180
+ const file = this.write(this.path(turn.id, `context-${contextCount}.json`), {
25181
+ schema: "cadence-conversation-message/1",
25182
+ index: contextCount,
25183
+ previous: contextHead,
25184
+ message
25185
+ }, CONTEXT_RECORD_BYTES);
25186
+ contextHead = file.identity;
25187
+ contextCount++;
25188
+ },
25189
+ onContextEnd: () => {
25190
+ checkpoint = true;
24778
25191
  },
24779
25192
  maySignal: () => {
24780
25193
  try {
@@ -24800,7 +25213,11 @@ class Conversations {
24800
25213
  if (result.outcome === "completed") {
24801
25214
  if (!checkpoint)
24802
25215
  throw new ContractError("corrupt-selected");
24803
- this.write(this.path(turn.id, "context.json"), { schema: "cadence-conversation-context/1", messages: checkpoint }, CONTEXT_BYTES);
25216
+ this.write(this.path(turn.id, "context.json"), {
25217
+ schema: "cadence-conversation-context/2",
25218
+ messages: contextCount,
25219
+ head: contextHead
25220
+ }, CONTEXT_BYTES);
24804
25221
  meta.checkpoint = turn.id;
24805
25222
  if (!live2?.metaFile)
24806
25223
  throw new ContractError("corrupt-selected");
@@ -24818,6 +25235,7 @@ class Conversations {
24818
25235
  turn.status = "unknown";
24819
25236
  try {
24820
25237
  this.write(this.path(turn.id, "native.json"), native, META_BYTES);
25238
+ transcript?.finish();
24821
25239
  if (turn.status !== "completed")
24822
25240
  turn.notice = [
24823
25241
  turn.notice,
@@ -24843,8 +25261,7 @@ var BYTES = 384 * 1024;
24843
25261
  var EVIDENCE_BYTES = 16384;
24844
25262
  var SCHEMA = "cadence-conversation-workflow/1";
24845
25263
  var COORDINATORS = 8;
24846
- var RECORDS = 200;
24847
- var RUNS = 200;
25264
+ var RECENT_RUNS = 200;
24848
25265
  var SCAN = 256;
24849
25266
  var INCOMPLETE = "Cadence control state for this conversation is missing, incomplete or unreadable. No mode, plan or run is inferred and nothing was repaired. Start a new conversation; preserve this state for local diagnosis.";
24850
25267
  var UNRECORDED = "The last Cadence message of this conversation was not durably recorded. Its plan is not approvable and nothing was replayed or repaired. Start a new conversation; preserve this state for local diagnosis.";
@@ -24853,14 +25270,14 @@ var PLAN_REFUSALS = {
24853
25270
  stale: "The project, model selection or owner changed while publishing. No plan card was published; ask the user before trying again.",
24854
25271
  conflict: "The current project state conflicts with this plan (for example uncommitted changes in a declared target or its project context). No plan card was published; explain this to the user.",
24855
25272
  forbidden: "The plan contains a protected value or an unsafe path and cannot be shown for approval. No plan card was published.",
24856
- capacity: "Retained workflow capacity is exhausted. No plan card was published.",
25273
+ capacity: "Workflow storage is unavailable. No plan card was published.",
24857
25274
  invalid: "The plan cannot use this delivery policy here (for example local-merge outside an existing Git branch). No plan card was published.",
24858
25275
  oversize: "The plan exceeds its size bounds. No plan card was published.",
24859
25276
  unavailable: "Git or the project state could not be observed. No plan card was published."
24860
25277
  };
24861
25278
  var RESEARCH_REFUSALS = {
24862
25279
  stale: "The project, model selection or owner changed. No investigation started.",
24863
- capacity: "The owner is at its workflow capacity (active or retained runs). No investigation started.",
25280
+ capacity: "The owner has no available workflow slot or storage. No investigation started.",
24864
25281
  forbidden: "The request contains a protected value. No investigation started."
24865
25282
  };
24866
25283
  var refusal3 = (refused2, notice) => ({ refused: refused2, notice });
@@ -24941,9 +25358,28 @@ class ConversationWorkflow {
24941
25358
  this.o.owner.lease.assert();
24942
25359
  if (!Number.isSafeInteger(state.revision))
24943
25360
  throw new ContractError("capacity");
24944
- const { notice: _projectionOnly, ...persisted } = state;
25361
+ const { notice: _projectionOnly, ...persisted } = {
25362
+ ...state,
25363
+ runs: state.runs.slice(-RECENT_RUNS)
25364
+ };
24945
25365
  const body = canonicalJson({ schema: SCHEMA, state: decodeCadenceConversation(persisted) }, BYTES);
24946
25366
  try {
25367
+ const prior = file ? decodeCadenceConversation(closed(parseWireJson(file.bytes.toString("utf8"), BYTES), [
25368
+ "schema",
25369
+ "state"
25370
+ ]).state).runs : [];
25371
+ for (const [index, runId] of state.runs.entries()) {
25372
+ if (index >= state.runs.length - RECENT_RUNS && prior.includes(runId))
25373
+ continue;
25374
+ const path = this.runLink(runId);
25375
+ const old = this.o.coordination.files.read(path);
25376
+ const value = canonicalJson({ runId, conversationId: state.id });
25377
+ if (old) {
25378
+ if (old.bytes.toString("utf8") !== value)
25379
+ throw new ContractError("conflict");
25380
+ } else
25381
+ this.o.coordination.files.create(path, value);
25382
+ }
24947
25383
  if (file)
24948
25384
  this.o.coordination.files.replace(this.path(state.id), file, body, BYTES);
24949
25385
  else
@@ -24953,23 +25389,6 @@ class ConversationWorkflow {
24953
25389
  throw e;
24954
25390
  }
24955
25391
  }
24956
- records() {
24957
- if (!this.o.coordination.files.directory(this.root))
24958
- return 0;
24959
- const dir = opendirSync10(this.root);
24960
- let entries2 = 0, records = 0;
24961
- try {
24962
- for (let e = dir.readSync();e; e = dir.readSync()) {
24963
- if (++entries2 > SCAN)
24964
- return RECORDS;
24965
- if (e.isDirectory())
24966
- ++records;
24967
- }
24968
- } finally {
24969
- dir.closeSync();
24970
- }
24971
- return records;
24972
- }
24973
25392
  state(id) {
24974
25393
  const loaded = this.read(id);
24975
25394
  if (loaded.transient)
@@ -24997,15 +25416,38 @@ class ConversationWorkflow {
24997
25416
  this.cache.set(id, { key: key2, state: loaded.state });
24998
25417
  return loaded.state;
24999
25418
  }
25419
+ runLink(runId) {
25420
+ return join27(this.o.coordination.directory, "conversations-v1", "workflow-links", `${decodeId(runId)}.json`);
25421
+ }
25000
25422
  links(runIds) {
25001
25423
  this.o.owner.lease.assert();
25002
25424
  const wanted = new Set(runIds), links = [];
25425
+ for (const runId of runIds) {
25426
+ try {
25427
+ const file = this.o.coordination.files.read(this.runLink(runId));
25428
+ if (!file)
25429
+ continue;
25430
+ const row = closed(parseWireJson(file.bytes.toString("utf8")), [
25431
+ "runId",
25432
+ "conversationId"
25433
+ ]);
25434
+ if (row.runId !== runId)
25435
+ continue;
25436
+ const conversationId = decodeId(row.conversationId);
25437
+ if (this.observe(conversationId).notice)
25438
+ continue;
25439
+ links.push({ runId, conversationId });
25440
+ wanted.delete(runId);
25441
+ } catch {
25442
+ this.o.owner.lease.assert();
25443
+ }
25444
+ }
25003
25445
  if (!wanted.size)
25004
25446
  return links;
25005
25447
  try {
25006
25448
  if (!this.o.coordination.files.directory(this.root))
25007
25449
  return links;
25008
- const dir = opendirSync10(this.root);
25450
+ const dir = opendirSync11(this.root);
25009
25451
  try {
25010
25452
  let seen = 0;
25011
25453
  for (let e = dir.readSync();e && seen < SCAN && wanted.size; e = dir.readSync()) {
@@ -25090,8 +25532,6 @@ class ConversationWorkflow {
25090
25532
  throw new ContractError("conflict");
25091
25533
  if (enabled && this.active.size >= COORDINATORS)
25092
25534
  throw new ContractError("capacity");
25093
- if (!file && this.records() >= RECORDS)
25094
- throw new ContractError("capacity");
25095
25535
  const next = {
25096
25536
  id: state.id,
25097
25537
  revision: state.revision + 1,
@@ -25176,7 +25616,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25176
25616
  }
25177
25617
  let published;
25178
25618
  try {
25179
- published = this.o.workflows.command(randomUUID20(), epoch, {
25619
+ published = this.o.workflows.command(randomUUID21(), epoch, {
25180
25620
  action: "propose",
25181
25621
  plan,
25182
25622
  model
@@ -25217,12 +25657,10 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25217
25657
  } catch {
25218
25658
  return refusal3("invalid", "An investigation needs a goal and one or two non-empty questions. Nothing was started.");
25219
25659
  }
25220
- if (current2.state.runs.length >= RUNS)
25221
- return refusal3("capacity", "This conversation reached its retained workflow limit. Nothing was started; continue in a new conversation.");
25222
25660
  const busy = this.o.workflows.activeRuns().runs.filter((r) => r.phase !== "research").map((r) => r.id);
25223
25661
  if (busy.length)
25224
25662
  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.`);
25225
- const id = randomUUID20(), conversationId = current2.state.id;
25663
+ const id = randomUUID21(), conversationId = current2.state.id;
25226
25664
  try {
25227
25665
  this.o.workflows.command(id, epoch, {
25228
25666
  action: "research",
@@ -25246,7 +25684,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25246
25684
  }, current2.file);
25247
25685
  const cancel = () => {
25248
25686
  try {
25249
- this.o.workflows.command(randomUUID20(), epoch, {
25687
+ this.o.workflows.command(randomUUID21(), epoch, {
25250
25688
  action: "cancel",
25251
25689
  runId: id
25252
25690
  });
@@ -25324,7 +25762,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25324
25762
  });
25325
25763
  if (prepared.kind !== "workflow" || prepared.response.type !== "grant")
25326
25764
  throw new ContractError("unavailable");
25327
- const g = prepared.response, grant2 = randomUUID20();
25765
+ const g = prepared.response, grant2 = randomUUID21();
25328
25766
  this.grants.set(grant2, {
25329
25767
  caller: canonicalJson(caller),
25330
25768
  revision: c.revision,
@@ -25343,8 +25781,6 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25343
25781
  proposal: g.proposal
25344
25782
  };
25345
25783
  }
25346
- if (state.runs.length >= RUNS)
25347
- throw new ContractError("capacity");
25348
25784
  const grant = this.grants.get(c.grant);
25349
25785
  if (grant && grant.expiresAt < Date.now())
25350
25786
  this.grants.delete(c.grant);
@@ -25391,10 +25827,10 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25391
25827
  }
25392
25828
 
25393
25829
  // src/service/workflows.ts
25394
- import { randomUUID as randomUUID22 } from "node:crypto";
25830
+ import { randomUUID as randomUUID23 } from "node:crypto";
25395
25831
  import {
25396
- lstatSync as lstatSync19,
25397
- opendirSync as opendirSync12,
25832
+ lstatSync as lstatSync20,
25833
+ opendirSync as opendirSync13,
25398
25834
  realpathSync as realpathSync10,
25399
25835
  rmdirSync,
25400
25836
  statfsSync as statfsSync3,
@@ -25406,7 +25842,7 @@ import { fileURLToPath as fileURLToPath5 } from "node:url";
25406
25842
  // src/task-diff.ts
25407
25843
  import { spawnSync as spawnSync3 } from "node:child_process";
25408
25844
  import { createHash as createHash24 } from "node:crypto";
25409
- import { lstatSync as lstatSync16, readdirSync as readdirSync3, readlinkSync } from "node:fs";
25845
+ import { lstatSync as lstatSync17, readdirSync as readdirSync3, readlinkSync } from "node:fs";
25410
25846
  import { join as join28, relative as relative8 } from "node:path";
25411
25847
  var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
25412
25848
  var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
@@ -25451,7 +25887,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
25451
25887
  }
25452
25888
  try {
25453
25889
  const path = join28(root, name);
25454
- const st = lstatSync16(path);
25890
+ const st = lstatSync17(path);
25455
25891
  add(name, `${st.mode}:${st.size}`);
25456
25892
  if (st.isSymbolicLink()) {
25457
25893
  add(name, readlinkSync(path));
@@ -25600,7 +26036,7 @@ ${data2.toString("utf8")}`);
25600
26036
  break;
25601
26037
  }
25602
26038
  try {
25603
- const st = lstatSync16(path);
26039
+ const st = lstatSync17(path);
25604
26040
  if (st.isDirectory())
25605
26041
  walk(path, depth + 1);
25606
26042
  else
@@ -25632,7 +26068,7 @@ import {
25632
26068
  closeSync as closeSync9,
25633
26069
  constants as constants7,
25634
26070
  fstatSync as fstatSync6,
25635
- lstatSync as lstatSync17,
26071
+ lstatSync as lstatSync18,
25636
26072
  openSync as openSync9,
25637
26073
  readdirSync as readdirSync4,
25638
26074
  readlinkSync as readlinkSync2,
@@ -25738,7 +26174,7 @@ function safeWorkflowFile(cwd, name) {
25738
26174
  throw new ContractError("forbidden");
25739
26175
  safeDirectory(dirname18(p));
25740
26176
  try {
25741
- const st = lstatSync17(p);
26177
+ const st = lstatSync18(p);
25742
26178
  if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
25743
26179
  throw new ContractError("forbidden");
25744
26180
  } catch (e) {
@@ -25754,7 +26190,7 @@ function declaredTarget(cwd, name) {
25754
26190
  throw new ContractError("forbidden");
25755
26191
  safeDirectory(dirname18(p));
25756
26192
  try {
25757
- const st = lstatSync17(p);
26193
+ const st = lstatSync18(p);
25758
26194
  if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory() || st.isFile() && st.nlink !== 1)
25759
26195
  throw new ContractError("forbidden");
25760
26196
  } catch (e) {
@@ -25835,7 +26271,7 @@ function directoryIdentity(root, name) {
25835
26271
  if (++count2 > DIRECTORY_ENTRIES)
25836
26272
  throw tooLarge(name);
25837
26273
  const full = join29(directory, entry), relative10 = `${prefix}${entry}`;
25838
- const st = lstatSync17(full);
26274
+ const st = lstatSync18(full);
25839
26275
  if (st.isDirectory()) {
25840
26276
  rows.push(`${relative10}/`);
25841
26277
  visit(full, `${relative10}/`);
@@ -25875,7 +26311,7 @@ function pathIdentity(cwd, name, walk = true) {
25875
26311
  throw new ContractError("forbidden");
25876
26312
  let st;
25877
26313
  try {
25878
- st = lstatSync17(p);
26314
+ st = lstatSync18(p);
25879
26315
  } catch (e) {
25880
26316
  if (absent2(e))
25881
26317
  return null;
@@ -26097,13 +26533,13 @@ async function assertWorktree(root, cwd) {
26097
26533
  if (await common(root) !== await common(cwd))
26098
26534
  throw new ContractError("stale");
26099
26535
  const marker2 = resolve9(cwd, ".git");
26100
- if (!lstatSync17(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
26536
+ if (!lstatSync18(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
26101
26537
  throw new ContractError("stale");
26102
26538
  }
26103
26539
 
26104
26540
  // src/service/workflow-history.ts
26105
- import { randomUUID as randomUUID21 } from "node:crypto";
26106
- import { lstatSync as lstatSync18, opendirSync as opendirSync11 } from "node:fs";
26541
+ import { randomUUID as randomUUID22 } from "node:crypto";
26542
+ import { lstatSync as lstatSync19, opendirSync as opendirSync12 } from "node:fs";
26107
26543
  class WorkflowHistoryScanner {
26108
26544
  path;
26109
26545
  directory;
@@ -26114,7 +26550,7 @@ class WorkflowHistoryScanner {
26114
26550
  this.directory = directory;
26115
26551
  }
26116
26552
  incarnation() {
26117
- const st = lstatSync18(this.path, { bigint: true });
26553
+ const st = lstatSync19(this.path, { bigint: true });
26118
26554
  if (!st.isDirectory() || st.isSymbolicLink())
26119
26555
  throw new ContractError("corrupt-selected");
26120
26556
  return `${st.dev}:${st.ino}`;
@@ -26140,7 +26576,7 @@ class WorkflowHistoryScanner {
26140
26576
  if (this.scans.size >= WORKFLOW_LIMITS.historyScans)
26141
26577
  throw new ContractError("capacity");
26142
26578
  const incarnation3 = this.incarnation();
26143
- state = { dir: opendirSync11(this.path), incarnation: incarnation3, after, ids: [] };
26579
+ state = { dir: opendirSync12(this.path), incarnation: incarnation3, after, ids: [] };
26144
26580
  }
26145
26581
  let suspended = false;
26146
26582
  try {
@@ -26166,7 +26602,7 @@ class WorkflowHistoryScanner {
26166
26602
  if (state.ids.length > WORKFLOW_LIMITS.historyPage + 1)
26167
26603
  state.ids.pop();
26168
26604
  }
26169
- const scan = randomUUID21();
26605
+ const scan = randomUUID22();
26170
26606
  state.timer = setTimeout(() => {
26171
26607
  this.scans.delete(scan);
26172
26608
  try {
@@ -26203,8 +26639,8 @@ class WorkflowHistoryScanner {
26203
26639
 
26204
26640
  // src/service/workflows.ts
26205
26641
  var OWNER_RUNTIME = Object.freeze({
26206
- version: "2.0.27",
26207
- build: "8ef1833b9806c52b446f2864252a2cd50eb71fef901da32dcd35aee988c4775c",
26642
+ version: "2.0.28",
26643
+ build: "87bcf7aa64bfe005d9861522dc15aa94185c48c56a4e41b1a1e18645b2d075d5",
26208
26644
  entry: fileURLToPath5(import.meta.url),
26209
26645
  pid: process.pid,
26210
26646
  node: process.versions.node,
@@ -26425,7 +26861,7 @@ class Workflows {
26425
26861
  if (!this.files.directory(runs))
26426
26862
  return;
26427
26863
  const ids = [];
26428
- const dir = opendirSync12(runs);
26864
+ const dir = opendirSync13(runs);
26429
26865
  try {
26430
26866
  for (let e = dir.readSync();e; e = dir.readSync()) {
26431
26867
  if (!e.isDirectory())
@@ -26739,7 +27175,7 @@ class Workflows {
26739
27175
  this.grants.delete(key2);
26740
27176
  if (this.grants.size >= 16)
26741
27177
  throw new ContractError("capacity");
26742
- const grant = randomUUID22(), expiresAt = Date.now() + 120000;
27178
+ const grant = randomUUID23(), expiresAt = Date.now() + 120000;
26743
27179
  effect();
26744
27180
  this.grants.set(grant, {
26745
27181
  commandId,
@@ -26881,7 +27317,7 @@ class Workflows {
26881
27317
  if (live2.run.steps.length >= MAX_STEPS)
26882
27318
  throw new ContractError("capacity");
26883
27319
  const s = {
26884
- id: `${clipUnits(id, STEP_UNITS)}-${randomUUID22()}`,
27320
+ id: `${clipUnits(id, STEP_UNITS)}-${randomUUID23()}`,
26885
27321
  ...childRunId ? { childRunId } : {},
26886
27322
  kind,
26887
27323
  ...childRunId ? {
@@ -26950,7 +27386,7 @@ class Workflows {
26950
27386
  throw new ContractError("unavailable");
26951
27387
  if (cwd !== this.cwd)
26952
27388
  await assertWorktree(this.cwd, cwd);
26953
- const childRunId = randomUUID22(), op = randomUUID22();
27389
+ const childRunId = randomUUID23(), op = randomUUID23();
26954
27390
  const plan = live2.proposal?.plan;
26955
27391
  const request3 = decodeWorkerPublicRequest({
26956
27392
  protocol: 2,
@@ -27108,7 +27544,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
27108
27544
  const shell = "check" in operation;
27109
27545
  if (cwd !== this.cwd && shell)
27110
27546
  await assertWorktree(this.cwd, cwd);
27111
- const id = randomUUID22();
27547
+ const id = randomUUID23();
27112
27548
  this.write(this.path(live2.run.id, `operations/${id}-intent.json`), {
27113
27549
  cwd,
27114
27550
  args: shell ? operation.check : operation.git
@@ -27264,7 +27700,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
27264
27700
  async review(live2, cwd, p) {
27265
27701
  live2.run.phase = "reviewing";
27266
27702
  this.save(live2);
27267
- 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.
27703
+ 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.
27268
27704
  Files: ${p.plan.tasks.flatMap((t) => t.writes).join(", ")}`, true, p.model);
27269
27705
  this.success(result);
27270
27706
  const verdict = reviewVerdict(result.text);
@@ -27372,7 +27808,7 @@ ${changed.map((p) => `- ${p}`).join(`
27372
27808
  for (const directory of [dirname19(this.worktreeRoot), this.worktreeRoot]) {
27373
27809
  if (!safeDirectory(directory, true))
27374
27810
  throw new ContractError("forbidden");
27375
- const st = lstatSync19(directory);
27811
+ const st = lstatSync20(directory);
27376
27812
  if (process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
27377
27813
  throw new ContractError("forbidden");
27378
27814
  }
@@ -27675,13 +28111,16 @@ class Workbench {
27675
28111
  conversations: this.conversations,
27676
28112
  workflows: this.workflows
27677
28113
  });
27678
- if (this.conversations.list().entries.some((entry) => entry.status === "unknown"))
27679
- throw new ContractError("quarantine");
28114
+ this.conversations.assertSettled();
27680
28115
  this.files = new WorkbenchFiles(o.cwd, [o.coordination.files.namespace, o.agentDir], o.secrets);
27681
28116
  this.projectRoot = join31(o.coordination.files.namespace, "workbench-projects-v1");
27682
28117
  }
27683
28118
  closeReads() {
27684
- this.workflows.closeHistory();
28119
+ try {
28120
+ this.workflows.closeHistory();
28121
+ } finally {
28122
+ this.conversations.closeReads();
28123
+ }
27685
28124
  }
27686
28125
  read(value) {
27687
28126
  const request3 = decodeWorkbenchRead(value);
@@ -27706,8 +28145,11 @@ class Workbench {
27706
28145
  return this.workflows.view(request3.id);
27707
28146
  case "task-origin":
27708
28147
  return this.conversations.origin(request3.taskId);
28148
+ case "conversation-active":
27709
28149
  case "conversations": {
27710
- const value2 = this.conversations.list();
28150
+ const value2 = request3.kind === "conversation-active" ? this.conversations.activeConversations() : this.conversations.list(request3.after ?? null, request3.scan);
28151
+ if (value2.kind !== "conversations" && value2.kind !== "conversation-active")
28152
+ return value2;
27711
28153
  return {
27712
28154
  ...value2,
27713
28155
  entries: value2.entries.map((entry) => ({
@@ -27716,6 +28158,8 @@ class Workbench {
27716
28158
  }))
27717
28159
  };
27718
28160
  }
28161
+ case "conversation-transcript":
28162
+ return this.conversations.transcript(request3.id, request3.turnId, request3.page);
27719
28163
  case "conversation":
27720
28164
  return this.conversations.view(request3.id, request3.before);
27721
28165
  case "files":
@@ -27768,7 +28212,7 @@ class Workbench {
27768
28212
  const entries2 = [{ path: this.o.cwd, current: true }], files = this.o.coordination.files;
27769
28213
  if (!files.directory(this.projectRoot))
27770
28214
  return { kind: "projects", entries: entries2 };
27771
- const directory = opendirSync13(this.projectRoot);
28215
+ const directory = opendirSync14(this.projectRoot);
27772
28216
  try {
27773
28217
  for (let e = directory.readSync();e; e = directory.readSync()) {
27774
28218
  if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries2.length > 128)
@@ -27919,7 +28363,7 @@ function legacy(store, budget, reader) {
27919
28363
  throw new ContractError("capacity");
27920
28364
  }
27921
28365
  }
27922
- const dir = opendirSync14(store.tasks), records = [];
28366
+ const dir = opendirSync15(store.tasks), records = [];
27923
28367
  let entries2 = 0;
27924
28368
  try {
27925
28369
  for (let entry = dir.readSync();entry; entry = dir.readSync()) {
@@ -27929,7 +28373,7 @@ function legacy(store, budget, reader) {
27929
28373
  if (created.has(entry.name))
27930
28374
  continue;
27931
28375
  const path = join32(store.tasks, entry.name, "task.json");
27932
- const size2 = lstatSync20(path).size;
28376
+ const size2 = lstatSync21(path).size;
27933
28377
  if (size2 > 128 * 1024)
27934
28378
  throw new ContractError("corrupt-selected");
27935
28379
  budget.reserve(size2);
@@ -27982,7 +28426,7 @@ var processLifetime = {
27982
28426
  }
27983
28427
  };
27984
28428
  async function createServiceHost(value, sourceBuild, lifetime) {
27985
- const embedded = "b6935a8daa09f70de094136c18d8e3588fdd34fc24b9a8fe95e465de11ddae8d";
28429
+ const embedded = "45f3666b0fc0d853e95e618b50156819f6282ce648e9703b876d9658ae15b78f";
27986
28430
  if (embedded && sourceBuild)
27987
28431
  throw new ContractError("unsupported-context");
27988
28432
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);