@abelxiaoxing/cadence 2.2.0 → 2.2.2

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.
@@ -516,6 +516,13 @@ function decodeId(v) {
516
516
  invalid();
517
517
  return s;
518
518
  }
519
+ var knowledgeFields = Object.freeze({
520
+ checkout: (v) => list(v, 8, (entry) => text(entry, 1024, true)),
521
+ path: (v) => text(v, 1024, true),
522
+ section: (v) => text(v, 512, true),
523
+ match: (v) => text(v, 256, true),
524
+ investigation: decodeId
525
+ });
519
526
  function decodeHash(v) {
520
527
  const s = text(v, 64);
521
528
  if (!/^[0-9a-f]{64}$/.test(s))
@@ -5117,6 +5124,7 @@ var ASSET_MEMBER_BYTES = 16 * 1024 * 1024;
5117
5124
  var ASSET_TOTAL_BYTES = 64 * 1024 * 1024;
5118
5125
  var fixed = new Set([
5119
5126
  "index.html",
5127
+ "assets/start.js",
5120
5128
  "assets/cadence.js",
5121
5129
  "assets/cadence.css",
5122
5130
  "assets/react.js",
@@ -5127,6 +5135,7 @@ var fixed = new Set([
5127
5135
  "assets/vis-timeline.css"
5128
5136
  ]);
5129
5137
  var font = /^assets\/KaTeX_(?:AMS-Regular|Caligraphic-(?:Bold|Regular)|Fraktur-(?:Bold|Regular)|Main-(?:Bold|BoldItalic|Italic|Regular)|Math-(?:BoldItalic|Italic)|SansSerif-(?:Bold|Italic|Regular)|Script-Regular|Size[1-4]-Regular|Typewriter-Regular)\.(?:woff2|woff|ttf)$/;
5138
+ var webBuildBase = (buildId) => `/ui/${buildId}/`;
5130
5139
  function assetMime(name) {
5131
5140
  if (!fixed.has(name) && !font.test(name))
5132
5141
  throw new Error("asset-name-refused");
@@ -5227,7 +5236,7 @@ function loadWebAssets(directory = fileURLToPath(new URL("../web/dist/", import.
5227
5236
  if (!body || body.length !== a.bytes || createHash6("sha256").update(body).digest("hex") !== a.sha256)
5228
5237
  throw new Error("asset-body-refused");
5229
5238
  return {
5230
- path: a.name === "index.html" ? "/app" : `/${a.name}`,
5239
+ path: a.name === "index.html" ? "/app" : a.name === "assets/start.js" ? `/${a.name}` : `${webBuildBase(manifest.buildId)}${a.name}`,
5231
5240
  contentType: assetMime(a.name),
5232
5241
  bytes: body
5233
5242
  };
@@ -5326,141 +5335,6 @@ function validateImageBytes(bytes, mimeType) {
5326
5335
  return { width, height };
5327
5336
  }
5328
5337
 
5329
- // src/service/contracts/design.ts
5330
- var label = (v) => text(v, 1024, true);
5331
- var key = (v) => {
5332
- const s = text(v, 48, true);
5333
- if (!/^[a-z][a-z0-9-]*$/u.test(s))
5334
- throw new Error("id: use lowercase letters, digits and hyphens");
5335
- return s;
5336
- };
5337
- function designQuestions(input) {
5338
- const { questions } = closed(input, ["questions"]);
5339
- const seen = new Map;
5340
- const rows = list(questions, 12, (raw) => {
5341
- const q = closed(raw, [
5342
- "id",
5343
- "question",
5344
- "options",
5345
- "recommended",
5346
- "reason",
5347
- "acceptance",
5348
- ...Object.hasOwn(raw ?? {}, "when") ? ["when"] : []
5349
- ]);
5350
- const id = key(q.id);
5351
- const options = list(q.options, 6, (raw2) => {
5352
- const o = closed(raw2, ["id", "label", "cost"]);
5353
- return { id: key(o.id), label: label(o.label), cost: label(o.cost) };
5354
- });
5355
- const ids = new Set(options.map((o) => o.id));
5356
- const recommended = key(q.recommended);
5357
- if (seen.has(id) || ids.size !== options.length || ids.size < 2 || !ids.has(recommended))
5358
- throw new Error("questions: use distinct question and option IDs and identify one recommended option");
5359
- const dep = q.when === undefined ? null : closed(q.when, ["question", "option"]);
5360
- const when = dep && {
5361
- question: key(dep.question),
5362
- option: key(dep.option)
5363
- };
5364
- if (when && !seen.get(when.question)?.has(when.option))
5365
- throw new Error("when: name an option of an earlier question");
5366
- seen.set(id, ids);
5367
- return {
5368
- id,
5369
- question: label(q.question),
5370
- options,
5371
- recommended,
5372
- reason: label(q.reason),
5373
- acceptance: label(q.acceptance),
5374
- ...when ? { when } : {}
5375
- };
5376
- });
5377
- if (!rows.length)
5378
- throw new Error("questions: supply a material product decision");
5379
- canonicalJson(rows, 24 * 1024);
5380
- return rows;
5381
- }
5382
- function designAnswers(v) {
5383
- return list(v, 12, (raw) => {
5384
- const other = Object.hasOwn(raw ?? {}, "other");
5385
- const a = closed(raw, ["question", other ? "other" : "option"]);
5386
- const question = key(a.question);
5387
- return other ? { question, other: label(a.other) } : { question, option: key(a.option) };
5388
- });
5389
- }
5390
- function available(q, answers) {
5391
- const dep = q.when;
5392
- return !dep || answers.some((a) => a.question === dep.question && ("option" in a) && a.option === dep.option);
5393
- }
5394
- function selectDesign(questions, choices, fill = false) {
5395
- const answers = [];
5396
- const indexed = new Map(choices.map((a) => [a.question, a]));
5397
- if (indexed.size !== choices.length || choices.some((a) => !questions.some((q) => q.id === a.question)))
5398
- throw new ContractError("invalid");
5399
- for (const q of questions) {
5400
- if (!available(q, answers))
5401
- continue;
5402
- const a = indexed.get(q.id);
5403
- if (a && "option" in a && !q.options.some((o) => o.id === a.option))
5404
- throw new ContractError("invalid");
5405
- if (a)
5406
- answers.push(a);
5407
- else if (fill)
5408
- answers.push({ question: q.id, option: q.recommended });
5409
- }
5410
- return answers;
5411
- }
5412
- function decodeDesign(v) {
5413
- const o = closed(v, ["id", "revision", "questions", "answers", "submitted"]);
5414
- const questions = designQuestions({ questions: o.questions });
5415
- const submitted = bool(o.submitted);
5416
- const answers = designAnswers(o.answers);
5417
- if (canonicalJson(selectDesign(questions, answers, submitted)) !== canonicalJson(answers))
5418
- throw new ContractError("invalid");
5419
- return {
5420
- id: decodeId(o.id),
5421
- revision: integer(o.revision, 1),
5422
- questions,
5423
- answers,
5424
- submitted
5425
- };
5426
- }
5427
- function newDesign(id, input, previous) {
5428
- const questions = designQuestions(input);
5429
- const retained = previous?.answers.filter((a) => {
5430
- const before = previous.questions.find((q) => q.id === a.question);
5431
- const after = questions.find((q) => q.id === a.question);
5432
- return before && after && canonicalJson(before) === canonicalJson(after);
5433
- }) ?? [];
5434
- return {
5435
- id,
5436
- revision: 1,
5437
- questions,
5438
- answers: selectDesign(questions, retained),
5439
- submitted: false
5440
- };
5441
- }
5442
- function answerText(q, a) {
5443
- return a && ("other" in a ? a.other : q.options.find((o) => o.id === a.option)?.label);
5444
- }
5445
- function designSummary(d) {
5446
- return d.questions.filter((q) => available(q, d.answers)).map((q) => `- ${q.question} — ${answerText(q, d.answers.find((a) => a.question === q.id)) ?? "…"}
5447
- Acceptance: ${q.acceptance}`).join(`
5448
- `);
5449
- }
5450
- function designMessage(d, maximum) {
5451
- const summary = designSummary(d);
5452
- return new TextEncoder().encode(summary).length <= maximum ? summary : `Submit design ${d.id}, revision ${d.revision}. Read the confirmed decisions in cadence_status and publish the implementation plan.`;
5453
- }
5454
- var recommendsDesign = (s) => /^(?:按你推荐的来|采用全部推荐|use (?:all |your )?recommendations)[。.!!]?$/iu.test(s.trim());
5455
- function reviseDesign(d, answers, submit) {
5456
- return {
5457
- ...d,
5458
- revision: d.revision + 1,
5459
- answers: selectDesign(d.questions, answers, submit),
5460
- submitted: submit
5461
- };
5462
- }
5463
-
5464
5338
  // src/service/contracts/workflow.ts
5465
5339
  var WORKFLOW_LIMITS = {
5466
5340
  tasks: 16,
@@ -5592,8 +5466,8 @@ function workflowOrder(tasks) {
5592
5466
  }
5593
5467
  function workflowAncestors(tasks, id) {
5594
5468
  const needed = new Set;
5595
- const visit = (key2) => {
5596
- for (const dep of tasks.find((t) => t.id === key2)?.after ?? []) {
5469
+ const visit = (key) => {
5470
+ for (const dep of tasks.find((t) => t.id === key)?.after ?? []) {
5597
5471
  if (!needed.has(dep)) {
5598
5472
  needed.add(dep);
5599
5473
  visit(dep);
@@ -5772,9 +5646,9 @@ function workflowPlanInput(v) {
5772
5646
  return issue("plan", "must be an object");
5773
5647
  const completed = (source, defaults) => {
5774
5648
  const result = { ...defaults };
5775
- for (const [key2, value] of Object.entries(source))
5649
+ for (const [key, value] of Object.entries(source))
5776
5650
  if (value !== null && value !== undefined)
5777
- result[key2] = value;
5651
+ result[key] = value;
5778
5652
  return result;
5779
5653
  };
5780
5654
  const plan = completed(v, {
@@ -5796,7 +5670,7 @@ function workflowPlanInput(v) {
5796
5670
  function researchInput(v) {
5797
5671
  if (v === null || typeof v !== "object" || Array.isArray(v))
5798
5672
  return issue("request", "must be an object with a goal and questions");
5799
- const given = (key2) => Object.getOwnPropertyDescriptor(v, key2)?.value ?? undefined;
5673
+ const given = (key) => Object.getOwnPropertyDescriptor(v, key)?.value ?? undefined;
5800
5674
  const distinct = (name, value, maximum) => [
5801
5675
  ...new Set(entries(name, typeof value === "string" ? [value] : value, Number.MAX_SAFE_INTEGER, (entry, path) => words(path, entry, maximum).trim()).filter(Boolean))
5802
5676
  ];
@@ -6371,7 +6245,159 @@ function decodeWorkflowDiagnostics(v) {
6371
6245
  };
6372
6246
  }
6373
6247
 
6248
+ // src/service/contracts/design.ts
6249
+ var label = (v) => text(v, 1024, true);
6250
+ var key = (v, path = "id") => {
6251
+ const s = words(path, v, 48, true);
6252
+ if (!/^[a-z][a-z0-9-]*$/u.test(s))
6253
+ return issue(path, "start with a lowercase letter; use lowercase letters, digits and hyphens");
6254
+ return s;
6255
+ };
6256
+ function designQuestions(input, source) {
6257
+ const { questions } = fields2("design", input, ["questions"]);
6258
+ const seen = new Map;
6259
+ const rows = entries("questions", questions, 12, (raw, path) => {
6260
+ const q = fields2(path, raw, ["id", "question", "options", "recommended", "reason", "acceptance"], ["when"]);
6261
+ const id = key(q.id, `${path}.id`);
6262
+ if (seen.has(id))
6263
+ return issue(`${path}.id`, "use a distinct question ID");
6264
+ const ids = new Set;
6265
+ const options = entries(`${path}.options`, q.options, 6, (raw2, path2) => {
6266
+ const o = fields2(path2, raw2, ["id", "label", "cost"]);
6267
+ const id2 = key(o.id, `${path2}.id`);
6268
+ if (ids.has(id2))
6269
+ return issue(`${path2}.id`, "use a distinct option ID");
6270
+ ids.add(id2);
6271
+ return {
6272
+ id: id2,
6273
+ label: words(`${path2}.label`, o.label, 1024, true),
6274
+ cost: words(`${path2}.cost`, o.cost, 1024, true)
6275
+ };
6276
+ });
6277
+ if (options.length < 2)
6278
+ return issue(`${path}.options`, "supply at least two alternatives");
6279
+ const recommended = key(q.recommended, `${path}.recommended`);
6280
+ if (!ids.has(recommended))
6281
+ return issue(`${path}.recommended`, "name an option ID of this question");
6282
+ let when;
6283
+ if (q.when !== undefined && !(source === "tool" && q.when === null)) {
6284
+ const dep = fields2(`${path}.when`, q.when, ["question", "option"]);
6285
+ if (!(source === "tool" && dep.question === "" && dep.option === "")) {
6286
+ const question = key(dep.question, `${path}.when.question`);
6287
+ if (!seen.has(question))
6288
+ return issue(`${path}.when.question`, "name an earlier question, or omit when for an independent question");
6289
+ const option = key(dep.option, `${path}.when.option`);
6290
+ if (!seen.get(question)?.has(option))
6291
+ return issue(`${path}.when.option`, "name an option ID of the earlier question");
6292
+ when = { question, option };
6293
+ }
6294
+ }
6295
+ seen.set(id, ids);
6296
+ return {
6297
+ id,
6298
+ question: words(`${path}.question`, q.question, 1024, true),
6299
+ options,
6300
+ recommended,
6301
+ reason: words(`${path}.reason`, q.reason, 1024, true),
6302
+ acceptance: words(`${path}.acceptance`, q.acceptance, 1024, true),
6303
+ ...when ? { when } : {}
6304
+ };
6305
+ });
6306
+ if (!rows.length)
6307
+ throw new Error("questions: supply a material product decision");
6308
+ try {
6309
+ canonicalJson(rows, 24 * 1024);
6310
+ } catch (error) {
6311
+ if (!(error instanceof ContractError) || error.code !== "oversize")
6312
+ throw error;
6313
+ return issue("questions", "the complete batch must fit in 24 KiB of encoded JSON");
6314
+ }
6315
+ return rows;
6316
+ }
6317
+ function designAnswers(v) {
6318
+ return list(v, 12, (raw) => {
6319
+ const other = Object.hasOwn(raw ?? {}, "other");
6320
+ const a = closed(raw, ["question", other ? "other" : "option"]);
6321
+ const question = key(a.question);
6322
+ return other ? { question, other: label(a.other) } : { question, option: key(a.option) };
6323
+ });
6324
+ }
6325
+ function available(q, answers) {
6326
+ const dep = q.when;
6327
+ return !dep || answers.some((a) => a.question === dep.question && ("option" in a) && a.option === dep.option);
6328
+ }
6329
+ function selectDesign(questions, choices, fill = false) {
6330
+ const answers = [];
6331
+ const indexed = new Map(choices.map((a) => [a.question, a]));
6332
+ if (indexed.size !== choices.length || choices.some((a) => !questions.some((q) => q.id === a.question)))
6333
+ throw new ContractError("invalid");
6334
+ for (const q of questions) {
6335
+ if (!available(q, answers))
6336
+ continue;
6337
+ const a = indexed.get(q.id);
6338
+ if (a && "option" in a && !q.options.some((o) => o.id === a.option))
6339
+ throw new ContractError("invalid");
6340
+ if (a)
6341
+ answers.push(a);
6342
+ else if (fill)
6343
+ answers.push({ question: q.id, option: q.recommended });
6344
+ }
6345
+ return answers;
6346
+ }
6347
+ function decodeDesign(v) {
6348
+ const o = closed(v, ["id", "revision", "questions", "answers", "submitted"]);
6349
+ const questions = designQuestions({ questions: o.questions }, "record");
6350
+ const submitted = bool(o.submitted);
6351
+ const answers = designAnswers(o.answers);
6352
+ if (canonicalJson(selectDesign(questions, answers, submitted)) !== canonicalJson(answers))
6353
+ throw new ContractError("invalid");
6354
+ return {
6355
+ id: decodeId(o.id),
6356
+ revision: integer(o.revision, 1),
6357
+ questions,
6358
+ answers,
6359
+ submitted
6360
+ };
6361
+ }
6362
+ function newDesign(id, input, previous) {
6363
+ const questions = designQuestions(input, "tool");
6364
+ const retained = previous?.answers.filter((a) => {
6365
+ const before = previous.questions.find((q) => q.id === a.question);
6366
+ const after = questions.find((q) => q.id === a.question);
6367
+ return before && after && canonicalJson(before) === canonicalJson(after);
6368
+ }) ?? [];
6369
+ return {
6370
+ id,
6371
+ revision: 1,
6372
+ questions,
6373
+ answers: selectDesign(questions, retained),
6374
+ submitted: false
6375
+ };
6376
+ }
6377
+ function answerText(q, a) {
6378
+ return a && ("other" in a ? a.other : q.options.find((o) => o.id === a.option)?.label);
6379
+ }
6380
+ function designSummary(d) {
6381
+ return d.questions.filter((q) => available(q, d.answers)).map((q) => `- ${q.question} — ${answerText(q, d.answers.find((a) => a.question === q.id)) ?? "…"}
6382
+ Acceptance: ${q.acceptance}`).join(`
6383
+ `);
6384
+ }
6385
+ function designMessage(d, maximum) {
6386
+ const summary = designSummary(d);
6387
+ return new TextEncoder().encode(summary).length <= maximum ? summary : `Submit design ${d.id}, revision ${d.revision}. Read the confirmed decisions in cadence_status and publish the implementation plan.`;
6388
+ }
6389
+ var recommendsDesign = (s) => /^(?:按你推荐的来|采用全部推荐|use (?:all |your )?recommendations)[。.!!]?$/iu.test(s.trim());
6390
+ function reviseDesign(d, answers, submit) {
6391
+ return {
6392
+ ...d,
6393
+ revision: d.revision + 1,
6394
+ answers: selectDesign(d.questions, answers, submit),
6395
+ submitted: submit
6396
+ };
6397
+ }
6398
+
6374
6399
  // src/service/contracts/workbench.ts
6400
+ var PROJECT_ASSOCIATION_HEADER = "x-cadence-project-association";
6375
6401
  function decodeCadenceConversation(v) {
6376
6402
  const degraded = v !== null && typeof v === "object" && Object.hasOwn(v, "notice");
6377
6403
  const o = closed(v, [
@@ -6404,17 +6430,17 @@ function decodeEntryId(v) {
6404
6430
  function decodeKnowledgeLookup(v) {
6405
6431
  if (Object.hasOwn(v ?? {}, "checkout")) {
6406
6432
  const { checkout } = closed(v, ["checkout"]);
6407
- return { checkout: list(checkout, 8, (path) => text(path, 1024, true)) };
6433
+ return { checkout: knowledgeFields.checkout(checkout) };
6408
6434
  }
6409
6435
  if (Object.hasOwn(v ?? {}, "investigation"))
6410
6436
  return {
6411
- investigation: decodeId(closed(v, ["investigation"]).investigation)
6437
+ investigation: knowledgeFields.investigation(closed(v, ["investigation"]).investigation)
6412
6438
  };
6413
6439
  if (Object.hasOwn(v ?? {}, "match")) {
6414
6440
  const raw2 = closed(v, ["path", "match"]);
6415
6441
  return {
6416
- path: text(raw2.path, 1024, true),
6417
- match: text(raw2.match, 256, true)
6442
+ path: knowledgeFields.path(raw2.path),
6443
+ match: knowledgeFields.match(raw2.match)
6418
6444
  };
6419
6445
  }
6420
6446
  const raw = closed(v, [
@@ -6422,8 +6448,8 @@ function decodeKnowledgeLookup(v) {
6422
6448
  ...Object.hasOwn(v ?? {}, "section") ? ["section"] : []
6423
6449
  ]);
6424
6450
  return {
6425
- path: text(raw.path, 1024, true),
6426
- ...raw.section === undefined ? {} : { section: text(raw.section, 512, true) }
6451
+ path: knowledgeFields.path(raw.path),
6452
+ ...raw.section === undefined ? {} : { section: knowledgeFields.section(raw.section) }
6427
6453
  };
6428
6454
  }
6429
6455
  var FILE_PART_BYTES = 192 * 1024;
@@ -6434,6 +6460,17 @@ var RUN_INPUTS = 32;
6434
6460
  var WAITING_INPUTS = 8;
6435
6461
  var PENDING_TEXT_BYTES = 256;
6436
6462
  var UNDELIVERED_TEXT_BYTES = 2 * CONVERSATION_SEND_BYTES;
6463
+ var workflowTurnStatuses = [
6464
+ "queued",
6465
+ "running",
6466
+ "completed",
6467
+ "failed",
6468
+ "canceled",
6469
+ "timeout",
6470
+ "unknown"
6471
+ ];
6472
+ var CHAT_STATUSES = ["starting", ...workflowTurnStatuses];
6473
+ var isLiveChatStatus = (status) => status === "starting" || status === "queued" || status === "running";
6437
6474
  var TREE_NODES = 1000;
6438
6475
  var STEP_TEXT_BYTES = 16 * 1024;
6439
6476
  var TARGET_BYTES = 1024;
@@ -6492,15 +6529,6 @@ function decodeChatCursor(value) {
6492
6529
  const o = closed(value, ["id", "updatedAt"]);
6493
6530
  return { id: decodeSessionId(o.id), updatedAt: integer(o.updatedAt, 0) };
6494
6531
  }
6495
- var statuses = [
6496
- "queued",
6497
- "running",
6498
- "completed",
6499
- "failed",
6500
- "canceled",
6501
- "timeout",
6502
- "unknown"
6503
- ];
6504
6532
  function decodeWorkbenchRead(v) {
6505
6533
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
6506
6534
  switch (kind) {
@@ -6938,7 +6966,7 @@ function decodeChatTurn(v) {
6938
6966
  ...o.retry === undefined ? {} : { retry: decodeModelRetry(o.retry) },
6939
6967
  id: decodeId(o.id),
6940
6968
  epoch: decodeId(o.epoch),
6941
- status: oneOf(o.status, statuses),
6969
+ status: oneOf(o.status, workflowTurnStatuses),
6942
6970
  notice: text(o.notice, 1024),
6943
6971
  ...transcript ? { transcript: { pages: integer(transcript.pages, 0) } } : {},
6944
6972
  omitted: {
@@ -7099,7 +7127,7 @@ function decodeChatTurnHeader(v) {
7099
7127
  entry: nullable(o.entry, decodeEntryId),
7100
7128
  ...o.parent === undefined ? {} : { parent: nullable(o.parent, decodeEntryId) },
7101
7129
  at: integer(o.at, 0),
7102
- status: oneOf(o.status, statuses),
7130
+ status: oneOf(o.status, CHAT_STATUSES),
7103
7131
  notice: text(o.notice, 1024),
7104
7132
  omitted: {
7105
7133
  thinking: bool(omitted.thinking),
@@ -7130,7 +7158,7 @@ function decodeChatSummary(v) {
7130
7158
  id: decodeSessionId(o.id),
7131
7159
  title: text(o.title, 512, true),
7132
7160
  leaf: nullable(o.leaf, decodeEntryId),
7133
- status: oneOf(o.status, statuses),
7161
+ status: oneOf(o.status, CHAT_STATUSES),
7134
7162
  updatedAt: integer(o.updatedAt, 0),
7135
7163
  origin: oneOf(o.origin, ["terminal", "webui"]),
7136
7164
  ...has("cadence") ? { cadence: bool(o.cadence) } : {},
@@ -7148,7 +7176,7 @@ function decodeChatAttempt(v) {
7148
7176
  return {
7149
7177
  commandId: decodeId(o.commandId),
7150
7178
  text: text(o.text, 16 * 1024),
7151
- status: oneOf(o.status, statuses),
7179
+ status: oneOf(o.status, CHAT_STATUSES),
7152
7180
  notice: text(o.notice, 1024)
7153
7181
  };
7154
7182
  }
@@ -7512,6 +7540,17 @@ var pageReaders = [
7512
7540
  "changes",
7513
7541
  "reviews"
7514
7542
  ];
7543
+ var HISTORY_CSRF_HEADER = "x-cadence-history-csrf";
7544
+ var retainedReaders = [
7545
+ ...pageReaders,
7546
+ "entity",
7547
+ "graph",
7548
+ "detail",
7549
+ "search"
7550
+ ];
7551
+ function retainedHistoryBody(operation) {
7552
+ return retainedReaders.includes(operation);
7553
+ }
7515
7554
  function mutation(operation) {
7516
7555
  return [
7517
7556
  "preflight",
@@ -7631,16 +7670,12 @@ function decodeHttpOutput(operation, value) {
7631
7670
  }
7632
7671
  function readonlyBody(operation) {
7633
7672
  const operations = [
7634
- ...pageReaders,
7673
+ ...retainedReaders,
7635
7674
  "workbenchRead",
7636
7675
  "current",
7637
7676
  "currentChanges",
7638
7677
  "checkObligations",
7639
- "entity",
7640
- "graph",
7641
7678
  "snapshot",
7642
- "detail",
7643
- "search",
7644
7679
  "export",
7645
7680
  "download",
7646
7681
  "receipt"
@@ -7695,10 +7730,6 @@ function decodeSocketInput(value) {
7695
7730
  return { kind, scope: decodeScope(o.scope) };
7696
7731
  }
7697
7732
 
7698
- // src/service/activity-discovery.ts
7699
- import { hostname as hostname5 } from "node:os";
7700
- import { join as join9 } from "node:path";
7701
-
7702
7733
  // src/worker-redaction.mjs
7703
7734
  var marker = "[redacted]";
7704
7735
  var sensitive = /^(?:authorization|proxy-authorization|cookie|set-cookie|password|passwd|secret|token|api[-_]?key|access[-_]?token|refresh[-_]?token|credentials|headers|env)$/i;
@@ -8160,6 +8191,10 @@ class DetailSanitizer {
8160
8191
  }
8161
8192
  }
8162
8193
 
8194
+ // src/service/activity-discovery.ts
8195
+ import { hostname as hostname5 } from "node:os";
8196
+ import { join as join9 } from "node:path";
8197
+
8163
8198
  // src/service/activity-files.ts
8164
8199
  import { randomUUID as randomUUID3 } from "node:crypto";
8165
8200
  import { opendirSync as opendirSync2, renameSync as renameSync2 } from "node:fs";
@@ -8572,6 +8607,7 @@ class CheckoutStore {
8572
8607
  // src/service/contracts/activity.ts
8573
8608
  var ACTIVITY_PHASES = [
8574
8609
  "turn",
8610
+ "starting",
8575
8611
  "queued",
8576
8612
  "running",
8577
8613
  "research",
@@ -11127,18 +11163,41 @@ function requestBoundary(req, policy, directOrigin) {
11127
11163
  class HttpAuthentication {
11128
11164
  material;
11129
11165
  epoch;
11166
+ workspaceId;
11130
11167
  localCapability;
11131
- csrf = randomUUID7();
11168
+ executionCsrf = randomUUID7();
11169
+ get csrf() {
11170
+ return this.executionCsrf;
11171
+ }
11172
+ history;
11132
11173
  cookieName;
11133
11174
  constructor(material, epoch, workspaceId, localCapability) {
11134
11175
  this.material = material;
11135
11176
  this.epoch = epoch;
11177
+ this.workspaceId = workspaceId;
11136
11178
  this.localCapability = localCapability;
11137
11179
  decodeId(epoch);
11138
11180
  decodeId(workspaceId);
11139
11181
  if (!/^[A-Za-z0-9_-]{43}$/.test(localCapability))
11140
11182
  throw new ContractError("invalid");
11141
11183
  this.cookieName = `cadence_${workspaceId.replaceAll("-", "")}`;
11184
+ material.onRevoke(() => {
11185
+ this.history = undefined;
11186
+ this.executionCsrf = randomUUID7();
11187
+ });
11188
+ }
11189
+ historyChallenge(workspace) {
11190
+ if (workspace.workspaceId !== this.workspaceId || workspace.epoch !== this.epoch)
11191
+ throw new ContractError("stale");
11192
+ if (this.history?.storeId !== workspace.storeId)
11193
+ this.history = {
11194
+ storeId: decodeId(workspace.storeId),
11195
+ csrf: randomUUID7()
11196
+ };
11197
+ return this.history.csrf;
11198
+ }
11199
+ get historyStore() {
11200
+ return this.history?.storeId;
11142
11201
  }
11143
11202
  bootstrap(value, boundary) {
11144
11203
  this.material.assertCurrent();
@@ -11171,14 +11230,14 @@ class HttpAuthentication {
11171
11230
  }
11172
11231
  return false;
11173
11232
  }
11174
- authenticate(boundary, attachmentId, mutation2 = false, websocket = false) {
11233
+ authenticate(boundary, attachmentId, post = false, websocket = false) {
11175
11234
  this.material.assertCurrent();
11176
11235
  if (!this.material.available)
11177
11236
  throw new ContractError("quarantine");
11178
11237
  const h = boundary.headers;
11179
11238
  const local = h.get("x-cadence-local");
11180
11239
  if (local !== undefined) {
11181
- if (!boundary.local || h.has("cookie") || [...h.keys()].some((name) => name.startsWith("sec-fetch-") && (name !== "sec-fetch-mode" || h.get(name) !== "cors")) || !sameSecret(local, this.localCapability))
11240
+ if (post === "retained-history" || !boundary.local || h.has("cookie") || [...h.keys()].some((name) => name.startsWith("sec-fetch-") && (name !== "sec-fetch-mode" || h.get(name) !== "cors")) || !sameSecret(local, this.localCapability))
11182
11241
  throw new ContractError("forbidden");
11183
11242
  } else {
11184
11243
  if (h.has("authorization") || h.has("x-cadence-token"))
@@ -11187,10 +11246,14 @@ class HttpAuthentication {
11187
11246
  throw new ContractError("unauthenticated");
11188
11247
  if (h.has("sec-fetch-site") && !["same-origin", "none"].includes(h.get("sec-fetch-site") ?? ""))
11189
11248
  throw new ContractError("forbidden");
11190
- if ((mutation2 || websocket) && h.get("origin") !== boundary.origin)
11249
+ if ((post || websocket) && h.get("origin") !== boundary.origin)
11191
11250
  throw new ContractError("forbidden");
11192
- if (mutation2 && h.get("x-cadence-csrf") !== this.csrf)
11251
+ if (post === "retained-history") {
11252
+ if (!this.history || h.get(HISTORY_CSRF_HEADER) !== this.history.csrf || h.has("x-cadence-attachment") || h.has("x-cadence-csrf"))
11253
+ throw new ContractError("forbidden");
11254
+ } else if (post && h.get("x-cadence-csrf") !== this.csrf) {
11193
11255
  throw new ContractError("forbidden");
11256
+ }
11194
11257
  }
11195
11258
  return {
11196
11259
  attachmentId: decodeId(attachmentId),
@@ -11249,27 +11312,24 @@ var styles = `
11249
11312
  :root {
11250
11313
  color-scheme: light dark;
11251
11314
  font-family:
11252
- Inter, Geist, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
11315
+ ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
11253
11316
  font-synthesis: none;
11254
- --page: light-dark(#f5f7ff, #020617);
11255
- --text: light-dark(#0f172a, #e6edf7);
11256
- --muted: light-dark(#536176, #94a3b8);
11257
- --glass: light-dark(rgba(255, 255, 255, 0.62), rgba(15, 23, 42, 0.62));
11258
- --glass-line: light-dark(rgba(255, 255, 255, 0.72), rgba(255, 255, 255, 0.1));
11259
- --field: light-dark(rgba(255, 255, 255, 0.5), rgba(2, 6, 23, 0.48));
11260
- --field-line: light-dark(rgba(100, 116, 139, 0.28), rgba(255, 255, 255, 0.12));
11261
- --primary-a: light-dark(#0e7490, #22d3ee);
11262
- --primary-b: light-dark(#1d4ed8, #60a5fa);
11263
- --on-primary: light-dark(#ffffff, #082f49);
11264
- --focus: light-dark(#2563eb, #22d3ee);
11265
- --glow: light-dark(rgba(37, 99, 235, 0.22), rgba(34, 211, 238, 0.2));
11266
- --shadow: light-dark(rgba(30, 64, 175, 0.14), rgba(0, 0, 0, 0.42));
11267
- --mesh-a: light-dark(rgba(147, 197, 253, 0.64), rgba(34, 211, 238, 0.1));
11268
- --mesh-b: light-dark(rgba(196, 181, 253, 0.58), rgba(37, 99, 235, 0.16));
11269
- --mesh-c: light-dark(rgba(165, 243, 252, 0.52), rgba(99, 102, 241, 0.1));
11270
- --grid: light-dark(rgba(37, 99, 235, 0.04), rgba(56, 189, 248, 0.055));
11271
- --error: light-dark(#b91c1c, #fda4af);
11272
- --error-bg: light-dark(rgba(254, 226, 226, 0.7), rgba(159, 18, 57, 0.12));
11317
+ --page: light-dark(#f4f5f7, #090a0d);
11318
+ --text: light-dark(#111318, #f2f4f8);
11319
+ --muted: light-dark(#5e6675, #8a93a2);
11320
+ --glass: light-dark(rgba(255,255,255,.72), rgba(22,23,27,.9));
11321
+ --glass-line: light-dark(rgba(56,59,70,.16), rgba(208,214,227,.14));
11322
+ --rim: light-dark(#ffffff, #45464c);
11323
+ --field: light-dark(#f4f5f7, #101115);
11324
+ --field-line: light-dark(#777e89, #69707d);
11325
+ --primary-a: light-dark(#445065, #c0ccde);
11326
+ --primary-b: light-dark(#5c5069, #d1c6dc);
11327
+ --on-primary: light-dark(#ffffff, #141519);
11328
+ --focus: light-dark(#525964, #adb6c5);
11329
+ --glow: light-dark(rgba(62,65,80,.09), rgba(194,188,220,.05));
11330
+ --shadow: light-dark(rgba(31,32,39,.12), rgba(0,0,0,.46));
11331
+ --error: light-dark(#843f50, #e3a6ae);
11332
+ --error-bg: light-dark(#f8eaeb, #302125);
11273
11333
  }
11274
11334
  * {
11275
11335
  box-sizing: border-box;
@@ -11282,28 +11342,7 @@ body {
11282
11342
  place-items: center;
11283
11343
  padding: 28px 20px;
11284
11344
  color: var(--text);
11285
- background: var(--page);
11286
- }
11287
- body::before,
11288
- body::after {
11289
- content: "";
11290
- position: fixed;
11291
- inset: 0;
11292
- z-index: 0;
11293
- pointer-events: none;
11294
- }
11295
- body::before {
11296
- background:
11297
- radial-gradient(circle at 12% 10%, var(--mesh-a), transparent 42%),
11298
- radial-gradient(circle at 90% 16%, var(--mesh-b), transparent 44%),
11299
- radial-gradient(circle at 52% 100%, var(--mesh-c), transparent 48%);
11300
- }
11301
- body::after {
11302
- background-image:
11303
- linear-gradient(var(--grid) 1px, transparent 1px),
11304
- linear-gradient(90deg, var(--grid) 1px, transparent 1px);
11305
- background-size: 48px 48px;
11306
- mask-image: radial-gradient(ellipse at center, #000, transparent 78%);
11345
+ background: radial-gradient(ellipse at 50% 36%, var(--glow), transparent 46%), var(--page);
11307
11346
  }
11308
11347
  main {
11309
11348
  position: relative;
@@ -11312,7 +11351,8 @@ main {
11312
11351
  padding: 40px;
11313
11352
  overflow: hidden;
11314
11353
  border: 1px solid var(--glass-line);
11315
- border-radius: 28px;
11354
+ border-top-color: var(--rim);
11355
+ border-radius: 24px;
11316
11356
  background: var(--glass);
11317
11357
  box-shadow:
11318
11358
  0 28px 80px var(--shadow),
@@ -11321,7 +11361,7 @@ main {
11321
11361
  backdrop-filter: blur(24px) saturate(140%);
11322
11362
  -webkit-backdrop-filter: blur(24px) saturate(140%);
11323
11363
  text-align: center;
11324
- animation: arrive 0.45s ease-out both;
11364
+
11325
11365
  }
11326
11366
  main::before {
11327
11367
  content: "";
@@ -11393,13 +11433,15 @@ input[type="password"] {
11393
11433
  }
11394
11434
  input::placeholder {
11395
11435
  color: var(--muted);
11396
- font-family: Inter, Geist, ui-sans-serif, system-ui, sans-serif;
11436
+ font-family: ui-sans-serif, system-ui, sans-serif;
11397
11437
  letter-spacing: 0;
11398
11438
  }
11399
11439
  input:hover {
11400
11440
  border-color: var(--focus);
11401
11441
  }
11402
11442
  input:focus-visible {
11443
+ outline: 2px solid var(--focus);
11444
+ outline-offset: 2px;
11403
11445
  border-color: var(--focus);
11404
11446
  box-shadow: 0 0 0 4px var(--glow);
11405
11447
  }
@@ -11417,7 +11459,7 @@ button {
11417
11459
  border-radius: 14px;
11418
11460
  background: linear-gradient(135deg, var(--primary-a), var(--primary-b));
11419
11461
  color: var(--on-primary);
11420
- font: 600 14px Inter, Geist, ui-sans-serif, system-ui, sans-serif;
11462
+ font: 600 14px ui-sans-serif, system-ui, sans-serif;
11421
11463
  cursor: pointer;
11422
11464
  box-shadow: 0 10px 28px var(--glow);
11423
11465
  transition:
@@ -11446,7 +11488,7 @@ button:focus-visible {
11446
11488
  outline-offset: 4px;
11447
11489
  }
11448
11490
  .notice {
11449
- margin: 0 0 16px;
11491
+ margin: 16px 0;
11450
11492
  padding: 10px 12px;
11451
11493
  border: 1px solid var(--error);
11452
11494
  border-radius: 12px;
@@ -11467,12 +11509,6 @@ button:focus-visible {
11467
11509
  white-space: nowrap;
11468
11510
  border: 0;
11469
11511
  }
11470
- @keyframes arrive {
11471
- from {
11472
- opacity: 0;
11473
- transform: translateY(8px);
11474
- }
11475
- }
11476
11512
  @media (max-width: 420px) {
11477
11513
  body {
11478
11514
  padding: 18px 14px;
@@ -11491,11 +11527,12 @@ button:focus-visible {
11491
11527
  }
11492
11528
  }
11493
11529
  @media (forced-colors: active) {
11494
- body::before,
11495
- body::after,
11496
11530
  main::before {
11497
11531
  display: none;
11498
11532
  }
11533
+ body, main, .brand-mark, .notice { background:Canvas; color:CanvasText; box-shadow:none; backdrop-filter:none; }
11534
+ button { background:ButtonFace; color:ButtonText; }
11535
+ input[type="password"] { background:Field; color:FieldText; }
11499
11536
  main,
11500
11537
  input[type="password"],
11501
11538
  button,
@@ -11503,6 +11540,7 @@ button:focus-visible {
11503
11540
  .notice {
11504
11541
  border: 1px solid CanvasText;
11505
11542
  }
11543
+ :focus-visible { outline: 2px solid Highlight !important; outline-offset: 2px; }
11506
11544
  }
11507
11545
  `;
11508
11546
  var AUTH_PAGE_CSP = `default-src 'none'; style-src 'sha256-${createHash9("sha256").update(styles).digest("base64")}'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'`;
@@ -11522,7 +11560,7 @@ function renderAuthPage(options) {
11522
11560
  <body>
11523
11561
  <main aria-labelledby="welcome">
11524
11562
  <div class="brand">
11525
- <span class="brand-mark" aria-hidden="true"><svg viewBox="0 0 36 36" fill="none"><path d="M25 11a9 9 0 1 0 0 14M12 18h12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></span>
11563
+ <span class="brand-mark" aria-hidden="true"><svg viewBox="0 0 36 36" fill="none"><path d="m18 2 13 9-4 16-9 7-9-7-4-16Zm-13 9 13 5 13-5M18 2v14l-9 11m9-11 9 11m-9-11v18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></span>
11526
11564
  <h1 id="welcome">Cadence</h1>
11527
11565
  </div>
11528
11566
  ${options.authError ? '<p id="auth-notice" class="notice" role="alert">Invalid access token.</p>' : ""}
@@ -11925,6 +11963,7 @@ function decodeMaintenanceJob(value) {
11925
11963
  function canUpgrade(route) {
11926
11964
  return route === "npm" || route === "bun" || route === "pi-npm" || route === "pi-bun" || route === "npm-local" || route === "bun-local";
11927
11965
  }
11966
+ var MAINTENANCE_WORK_LIMIT = 256;
11928
11967
 
11929
11968
  // src/service/doctor.ts
11930
11969
  import { createInterface } from "node:readline";
@@ -14747,7 +14786,7 @@ class MaintenanceRecord {
14747
14786
  this.write({ ...job2, state, reason, version, endedAt: Date.now() });
14748
14787
  }
14749
14788
  }
14750
- function launchJob(s, job2) {
14789
+ function launchJob(s, job2, confirmedWork) {
14751
14790
  const text2 = generatedUnit(s);
14752
14791
  if (typeof text2 !== "string")
14753
14792
  return false;
@@ -14770,7 +14809,9 @@ function launchJob(s, job2) {
14770
14809
  ...name ? ["--name", name] : [],
14771
14810
  ...job2.to ? ["--to", job2.to] : [],
14772
14811
  "--job",
14773
- job2.id
14812
+ job2.id,
14813
+ "--confirmed-work",
14814
+ confirmedWork
14774
14815
  ], { stdio: "ignore", timeout: 20000 });
14775
14816
  return !result.error && result.status === 0;
14776
14817
  }
@@ -14910,10 +14951,10 @@ async function serviceStatus(c, diagnose = false) {
14910
14951
  };
14911
14952
  }
14912
14953
  }
14913
- async function stopService(c) {
14954
+ async function stopService(c, confirmedWork) {
14914
14955
  let epoch;
14915
14956
  try {
14916
- const reply = closed(await nativeCall(c, "stop"), ["status", "epoch"]);
14957
+ const reply = closed(await nativeCall(c, "stop", false, confirmedWork ? { confirmedWork } : undefined), ["status", "epoch"]);
14917
14958
  if (reply.status !== "accepted")
14918
14959
  throw new ContractError("unavailable");
14919
14960
  epoch = decodeId(reply.epoch);
@@ -15300,9 +15341,8 @@ var INTERRUPTED = "Interrupted: Cadence stopped before this reply finished. Noth
15300
15341
  var NOT_DELIVERED = "Not delivered: the reply ended before this message reached the model. Nothing was replayed; send it again.";
15301
15342
  var UNOBSERVED = "Not observed: the session could not be read when the reply ended, so whether this message was delivered was not recorded. Nothing was replayed.";
15302
15343
  var WITHDRAWN = "Withdrawn before it was delivered.";
15303
- var LIVE = ["queued", "running"];
15304
15344
  function settledSteps(turn) {
15305
- if (LIVE.includes(turn.status) || !turn.items.some((item) => ["pending", "running", "streaming"].includes(item.state ?? "")))
15345
+ if (isLiveChatStatus(turn.status) || !turn.items.some((item) => ["pending", "running", "streaming"].includes(item.state ?? "")))
15306
15346
  return turn;
15307
15347
  return {
15308
15348
  ...turn,
@@ -15361,20 +15401,11 @@ function decodeAccepted(value) {
15361
15401
  offset: integer(o.offset, 0)
15362
15402
  };
15363
15403
  }
15364
- var statuses2 = [
15365
- "queued",
15366
- "running",
15367
- "completed",
15368
- "failed",
15369
- "canceled",
15370
- "timeout",
15371
- "unknown"
15372
- ];
15373
15404
  function decodeState(value) {
15374
15405
  const o = closed(value, ["status", "notice", "omitted", "user"]);
15375
15406
  const omitted = closed(o.omitted, ["thinking", "media", "other"]);
15376
15407
  return {
15377
- status: oneOf(o.status, statuses2),
15408
+ status: oneOf(o.status, CHAT_STATUSES),
15378
15409
  notice: text(o.notice, 4096),
15379
15410
  omitted: {
15380
15411
  thinking: omitted.thinking === true,
@@ -15458,7 +15489,7 @@ class ConversationRecords {
15458
15489
  if (value === undefined)
15459
15490
  throw new ContractError("corrupt-selected");
15460
15491
  const decoded2 = decodeState(value);
15461
- const state = LIVE.includes(decoded2.status) ? { ...decoded2, status: "unknown", notice: INTERRUPTED } : decoded2;
15492
+ const state = isLiveChatStatus(decoded2.status) ? { ...decoded2, status: "unknown", notice: INTERRUPTED } : decoded2;
15462
15493
  if (this.states.size >= COMMAND_STATES)
15463
15494
  this.states.clear();
15464
15495
  this.states.set(commandId, { key: key2, state });
@@ -15593,7 +15624,10 @@ class ConversationRecords {
15593
15624
  const run = this.recordedRun(id);
15594
15625
  return run ? {
15595
15626
  commandId: run.commandId,
15596
- settled: ![run, ...run.inputs].some((message2) => ["queued", "running", "unknown"].includes(this.state(message2.commandId).status))
15627
+ settled: ![run, ...run.inputs].some((message2) => {
15628
+ const { status } = this.state(message2.commandId);
15629
+ return status === "unknown" || isLiveChatStatus(status);
15630
+ })
15597
15631
  } : null;
15598
15632
  }
15599
15633
  summary(id, live2, archived = this.archived(id)) {
@@ -15946,7 +15980,7 @@ class ConversationRecords {
15946
15980
  });
15947
15981
  return {
15948
15982
  turn: { ...settledSteps(turn), execution: live2.execution },
15949
- stable: LIVE.includes(live2.state.status) ? extended.stable : turn.steps.length
15983
+ stable: isLiveChatStatus(live2.state.status) ? extended.stable : turn.steps.length
15950
15984
  };
15951
15985
  }
15952
15986
  turnSteps(id, leaf, ordinal, before) {
@@ -16780,7 +16814,7 @@ class ServiceHttpServer {
16780
16814
  let total = 0;
16781
16815
  for (const asset of options.assets ?? []) {
16782
16816
  total += asset.bytes.byteLength;
16783
- if (!/^\/(?:app|assets\/[a-zA-Z0-9_-]+\.(?:js|css|woff2|woff|ttf|svg))$/.test(asset.path) || this.assets.has(asset.path) || asset.bytes.byteLength > 16 * 1024 * 1024 || total > 64 * 1024 * 1024)
16817
+ if (!/^\/(?:app|assets\/start\.js|ui\/[a-f0-9]{64}\/assets\/[a-zA-Z0-9_-]+\.(?:js|css|woff2|woff|ttf))$/.test(asset.path) || this.assets.has(asset.path) || asset.bytes.byteLength > 16 * 1024 * 1024 || total > 64 * 1024 * 1024)
16784
16818
  throw new ContractError("invalid");
16785
16819
  this.assets.set(asset.path, {
16786
16820
  ...asset,
@@ -17062,7 +17096,10 @@ Content-Length: 0\r
17062
17096
  unavailable();
17063
17097
  const route = readRoute(target, req.method ?? "");
17064
17098
  const attachmentId = boundary.headers.get("x-cadence-attachment") ?? randomUUID13();
17065
- const caller = this.options.auth.authenticate(boundary, attachmentId, route?.source === "body");
17099
+ const historyBody = route?.source === "body" && retainedHistoryBody(route.operation) && boundary.headers.has(HISTORY_CSRF_HEADER);
17100
+ const caller = this.options.auth.authenticate(boundary, attachmentId, historyBody ? "retained-history" : route?.source === "body");
17101
+ if (boundary.headers.has(HISTORY_CSRF_HEADER) && !historyBody)
17102
+ throw new ContractError("forbidden");
17066
17103
  if (!route || !mutation(route.operation)) {
17067
17104
  if (this.reads >= 32)
17068
17105
  throw new ContractError("capacity");
@@ -17076,6 +17113,8 @@ Content-Length: 0\r
17076
17113
  throw new ContractError("invalid");
17077
17114
  this.options.auth.current(caller);
17078
17115
  res.setHeader("Content-Type", asset.contentType);
17116
+ if (target === "/app" && this.options.build)
17117
+ res.setHeader("X-Cadence-Web-Build", this.options.build.assets.buildId);
17079
17118
  if (target !== "/app") {
17080
17119
  res.setHeader("Cache-Control", "private, no-cache");
17081
17120
  res.setHeader("ETag", asset.etag);
@@ -17104,12 +17143,14 @@ Content-Length: 0\r
17104
17143
  this.attachments.set(attachmentId, attachment);
17105
17144
  }
17106
17145
  res.setHeader("X-Cadence-Attachment", attachmentId);
17107
- } else if (route.source === "body" && (route.operation !== "detach" || this.attachments.has(attachmentId)))
17146
+ } else if (route.source === "body" && !historyBody && (route.operation !== "detach" || this.attachments.has(attachmentId)))
17108
17147
  attachment = this.attachment(caller);
17109
17148
  const input = route.source === "body" ? await this.body(req, abort.signal) : route.input === null ? null : parseWireJson(route.input);
17110
17149
  if (route.source !== "body" && (req.headers["content-encoding"] !== undefined || req.headers["transfer-encoding"] || req.headers["content-length"] && req.headers["content-length"] !== "0"))
17111
17150
  throw new ContractError("invalid");
17112
- decodeHttpInput(route.operation, input);
17151
+ const decodedInput = decodeHttpInput(route.operation, input);
17152
+ if (historyBody && (!decodedInput || typeof decodedInput !== "object" || !("storeId" in decodedInput) || decodedInput.storeId !== this.options.auth.historyStore))
17153
+ throw new ContractError("stale");
17113
17154
  this.options.auth.current(caller);
17114
17155
  if (abort.signal.aborted || !this.accepting)
17115
17156
  unavailable();
@@ -17126,7 +17167,14 @@ Content-Length: 0\r
17126
17167
  unavailable();
17127
17168
  if (route.operation === "session")
17128
17169
  this.attachment(caller);
17129
- const decoded2 = decodeHttpOutput(route.operation, value);
17170
+ let decoded2;
17171
+ if (route.operation === "workspace" && caller.authority === "browser") {
17172
+ const workspace = decodeReply(value, decodeWorkspaceBootstrap);
17173
+ if (workspace.kind === "ok")
17174
+ res.setHeader(HISTORY_CSRF_HEADER, this.options.auth.historyChallenge(workspace.value));
17175
+ decoded2 = workspace;
17176
+ } else
17177
+ decoded2 = decodeHttpOutput(route.operation, value);
17130
17178
  const status = value && typeof value === "object" && "kind" in value && value.kind === "error" && "error" in value ? errorStatus(decodePublicError(value.error).code) : 200;
17131
17179
  const compressible = route.operation === "workbenchRead";
17132
17180
  if (compressible)
@@ -17462,6 +17510,7 @@ Content-Length: 0\r
17462
17510
  sentBytes: 0,
17463
17511
  sentMessages: 0,
17464
17512
  reading: false,
17513
+ resyncPending: false,
17465
17514
  closed: false,
17466
17515
  lastPing: Date.now(),
17467
17516
  lastReconcile: Date.now()
@@ -17482,10 +17531,12 @@ Content-Length: 0\r
17482
17531
  viewer.lastPing = Date.now();
17483
17532
  if (command.kind === "ping")
17484
17533
  this.heartbeatViewer(viewer);
17485
- else if (viewer.reading)
17486
- this.closeViewer(viewer);
17487
- else
17534
+ else if (!viewer.reading)
17488
17535
  this.subscribe(viewer, command.scope);
17536
+ else if (command.kind === "resync" && viewer.scope?.kind === command.scope.kind && viewer.scope.id === command.scope.id)
17537
+ viewer.resyncPending = true;
17538
+ else
17539
+ this.closeViewer(viewer);
17489
17540
  } catch {
17490
17541
  this.closeViewer(viewer);
17491
17542
  }
@@ -17568,23 +17619,26 @@ Content-Length: 0\r
17568
17619
  viewer.unsubscribe();
17569
17620
  return;
17570
17621
  }
17571
- const snapshot = decodeSnapshot(await p.snapshot(scope));
17572
- if (viewer.closed || viewer.subscription !== generation)
17573
- return;
17574
- this.attachment(viewer.attachment.caller);
17575
- if (snapshot.epoch !== this.options.auth.epoch || canonicalJson(snapshot.scope) !== canonicalJson(scope))
17576
- throw new ContractError("stale");
17577
- viewer.snapshot = snapshot;
17578
- if (!this.sendViewer(viewer, { kind: "snapshot", snapshot }))
17579
- return;
17580
- viewer.reading = false;
17581
- viewer.lastReconcile = Date.now();
17582
- for (const event of viewer.pending.splice(0)) {
17583
- viewer.bytes -= Buffer.byteLength(canonicalJson(event));
17584
- this.deliver(viewer, event);
17622
+ do {
17623
+ viewer.resyncPending = false;
17624
+ const snapshot = decodeSnapshot(await p.snapshot(scope));
17585
17625
  if (viewer.closed || viewer.subscription !== generation)
17586
- break;
17587
- }
17626
+ return;
17627
+ this.attachment(viewer.attachment.caller);
17628
+ if (snapshot.epoch !== this.options.auth.epoch || canonicalJson(snapshot.scope) !== canonicalJson(scope))
17629
+ throw new ContractError("stale");
17630
+ viewer.snapshot = snapshot;
17631
+ if (!this.sendViewer(viewer, { kind: "snapshot", snapshot }))
17632
+ return;
17633
+ viewer.lastReconcile = Date.now();
17634
+ for (const event of viewer.pending.splice(0)) {
17635
+ viewer.bytes -= Buffer.byteLength(canonicalJson(event));
17636
+ if (!this.deliver(viewer, event)) {
17637
+ viewer.bytes = 0;
17638
+ break;
17639
+ }
17640
+ }
17641
+ } while (!viewer.closed && viewer.resyncPending);
17588
17642
  } catch {
17589
17643
  this.closeViewer(viewer);
17590
17644
  } finally {
@@ -17596,26 +17650,30 @@ Content-Length: 0\r
17596
17650
  deliver(viewer, event) {
17597
17651
  const snapshot = viewer.snapshot;
17598
17652
  if (!snapshot || viewer.closed)
17599
- return;
17653
+ return false;
17600
17654
  if (event.epoch !== snapshot.epoch || event.storeId !== snapshot.storeId || canonicalJson(event.scope) !== canonicalJson(snapshot.scope)) {
17601
17655
  this.resync(viewer);
17602
- return;
17656
+ return false;
17603
17657
  }
17604
17658
  const cmp = compareSequence(event.committedSeq, snapshot.committedSeq);
17605
17659
  if (cmp < 0 || cmp === 0 && event.kind !== "heartbeat")
17606
- return;
17660
+ return true;
17607
17661
  if (event.kind === "update" && event.previousSeq !== snapshot.committedSeq || event.kind === "heartbeat" && cmp > 0) {
17608
17662
  this.resync(viewer);
17609
- return;
17663
+ return false;
17610
17664
  }
17611
- if (this.sendViewer(viewer, { kind: "event", event }))
17612
- snapshot.committedSeq = event.committedSeq;
17665
+ if (!this.sendViewer(viewer, { kind: "event", event }))
17666
+ return false;
17667
+ snapshot.committedSeq = event.committedSeq;
17668
+ return true;
17613
17669
  }
17614
17670
  resync(viewer) {
17615
- if (!viewer.reading && viewer.scope) {
17616
- this.sendViewer(viewer, { kind: "resync" });
17671
+ if (!viewer.scope || !this.sendViewer(viewer, { kind: "resync" }))
17672
+ return;
17673
+ if (viewer.reading)
17674
+ viewer.resyncPending = true;
17675
+ else
17617
17676
  this.subscribe(viewer, viewer.scope);
17618
- }
17619
17677
  }
17620
17678
  heartbeatViewer(viewer) {
17621
17679
  if (!viewer.scope || viewer.reading)
@@ -17633,7 +17691,7 @@ Content-Length: 0\r
17633
17691
  for (const viewer of this.viewers) {
17634
17692
  if (Date.now() - viewer.lastPing >= LIMITS.staleMs)
17635
17693
  this.closeViewer(viewer);
17636
- else if (Date.now() - viewer.lastReconcile >= LIMITS.reconcileMs)
17694
+ else if (!viewer.reading && Date.now() - viewer.lastReconcile >= LIMITS.reconcileMs)
17637
17695
  this.resync(viewer);
17638
17696
  else
17639
17697
  this.heartbeatViewer(viewer);
@@ -17823,6 +17881,10 @@ class ModelPreviewProcesses {
17823
17881
  }
17824
17882
 
17825
17883
  // src/service/gateway.ts
17884
+ function maintenanceWorkDigest(gatewayEpoch, work) {
17885
+ const keys2 = work.map((identity) => canonicalJson(identity)).sort();
17886
+ return hash(canonicalJson([gatewayEpoch, keys2]));
17887
+ }
17826
17888
  async function joinProjectStops(projects, stopProject) {
17827
17889
  const unconfirmed = [];
17828
17890
  const seen = new Set;
@@ -17843,7 +17905,7 @@ async function createGateway(value, hostUrl, source) {
17843
17905
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
17844
17906
  const web = loadWebAssets(source?.webDirectory);
17845
17907
  const build2 = {
17846
- contractHash: "1b833e54ac91fb9d8e570f43da35e3e2faf6c9e214bd9d1bd7cce19c2fe7f243",
17908
+ contractHash: "80875479add4b7830419060b7e5018a39de200665edfbdec20fc10d50861bfea",
17847
17909
  assets: {
17848
17910
  sourceHash: web.manifest.sourceHash,
17849
17911
  contractHash: web.manifest.contractHash,
@@ -17918,8 +17980,11 @@ Content-Length: 0\r
17918
17980
  conversations.close();
17919
17981
  const grouped = new Map;
17920
17982
  for (const [id, target2] of attachments) {
17921
- const key2 = `${target2.projectId}:${target2.epoch}`;
17922
- const group = grouped.get(key2) ?? { ...target2, ids: [] };
17983
+ if (target2.rejected)
17984
+ continue;
17985
+ const projectId = target2.project.id, epoch = target2.project.epoch;
17986
+ const key2 = `${projectId}:${epoch}`;
17987
+ const group = grouped.get(key2) ?? { projectId, epoch, ids: [] };
17923
17988
  group.ids.push(id);
17924
17989
  grouped.set(key2, group);
17925
17990
  }
@@ -17989,17 +18054,53 @@ Content-Length: 0\r
17989
18054
  const commands = packageCommands(packageSystem);
17990
18055
  let route, requesting = false;
17991
18056
  async function associatedWork() {
17992
- const counts = await Promise.all([
17993
- ...new Map(store.associatedProjects().map((p) => [p.path, p])).values()
17994
- ].map(async (p) => {
17995
- try {
17996
- const observed = await serviceStatus(new ServiceCoordination(p.path, input.stateHome));
17997
- return observed && typeof observed === "object" && "status" in observed && observed.status === "alive" && "work" in observed && typeof observed.work === "number" ? observed.work : 0;
17998
- } catch {
17999
- return 0;
18000
- }
18001
- }));
18002
- return counts.reduce((sum, count) => sum + count, 0);
18057
+ if (preparing)
18058
+ throw new ContractError("unavailable");
18059
+ const targets = () => [
18060
+ ...new Map(store.associatedProjects().map((p) => [canonicalJson([p.path, p.epoch]), p])).entries()
18061
+ ].sort(([a], [b]) => a < b ? -1 : a === b ? 0 : 1);
18062
+ const selected2 = targets();
18063
+ const secrets = acquired.access.redactionLiterals();
18064
+ const work = await Promise.all(selected2.map(async ([, p]) => {
18065
+ const c = new ServiceCoordination(p.path, input.stateHome);
18066
+ if (c.store.root !== p.path)
18067
+ throw new ContractError("stale");
18068
+ const observed = c.inspect();
18069
+ if (observed.status === "stopped" || observed.status === "absent")
18070
+ return [];
18071
+ const epoch = c.localAccess().epoch;
18072
+ if (epoch !== p.epoch)
18073
+ return [];
18074
+ const summary = decodeOwnerActivity(await nativeCall(c, "activity"));
18075
+ if (!summary.complete || summary.epoch !== epoch || c.localAccess().epoch !== epoch)
18076
+ throw new ContractError("unavailable");
18077
+ const project = sanitizeText(p.path, secrets).replace(/[\p{Cc}\p{Cf}]/gu, " ");
18078
+ return summary.activities.map((item) => {
18079
+ if (item.epoch !== epoch || item.source === "terminal")
18080
+ throw new ContractError("unavailable");
18081
+ return {
18082
+ key: [p.path, epoch, item.source, item.id],
18083
+ item: {
18084
+ project,
18085
+ id: item.id,
18086
+ source: item.source,
18087
+ sessionId: item.sessionId
18088
+ }
18089
+ };
18090
+ });
18091
+ })).then((lists) => lists.flat());
18092
+ if (preparing || canonicalJson(targets().map(([key2]) => key2)) !== canonicalJson(selected2.map(([key2]) => key2)) || work.length > MAINTENANCE_WORK_LIMIT)
18093
+ throw new ContractError("unavailable");
18094
+ const confirmed = {
18095
+ digest: maintenanceWorkDigest(auth.epoch, work.map(({ key: key2 }) => key2)),
18096
+ items: work.map(({ item }) => item)
18097
+ };
18098
+ canonicalJson(confirmed, LIMITS.controlBytes - 4096);
18099
+ return confirmed;
18100
+ }
18101
+ async function assertConfirmedWork(digest) {
18102
+ if ((await associatedWork()).digest !== digest)
18103
+ throw new ContractError("stale");
18003
18104
  }
18004
18105
  function latestJob() {
18005
18106
  const job2 = record3.read();
@@ -18012,13 +18113,13 @@ Content-Length: 0\r
18012
18113
  version,
18013
18114
  unit: managed ? { name: managed.unit, scope: managed.scope ?? "user" } : null,
18014
18115
  upgrade: await route,
18015
- work: await associatedWork(),
18116
+ work: managed ? await associatedWork().catch(() => null) : null,
18016
18117
  job: latestJob()
18017
18118
  };
18018
18119
  }
18019
18120
  async function requestJob(value2, current) {
18020
18121
  const o = closed(value2, ["action", "from", "to", "work", "epoch"]);
18021
- const action = oneOf(o.action, MAINTENANCE_ACTIONS), to = o.to === null ? null : decodeVersion(o.to);
18122
+ const action = oneOf(o.action, MAINTENANCE_ACTIONS), to = o.to === null ? null : decodeVersion(o.to), work = decodeHash(o.work);
18022
18123
  if (action === "upgrade" !== (to !== null))
18023
18124
  throw new ContractError("invalid");
18024
18125
  if (decodeId(o.epoch) !== auth.epoch || decodeVersion(o.from) !== version)
@@ -18032,8 +18133,7 @@ Content-Length: 0\r
18032
18133
  throw new ContractError("conflict");
18033
18134
  requesting = true;
18034
18135
  try {
18035
- if (await associatedWork() !== integer(o.work, 0, 1e6))
18036
- throw new ContractError("stale");
18136
+ await assertConfirmedWork(work);
18037
18137
  current();
18038
18138
  assert();
18039
18139
  const job2 = {
@@ -18048,7 +18148,7 @@ Content-Length: 0\r
18048
18148
  endedAt: null
18049
18149
  };
18050
18150
  record3.write(job2);
18051
- if (!launchJob(managed, job2)) {
18151
+ if (!launchJob(managed, job2, work)) {
18052
18152
  record3.finish(job2.id, "failed", "refused", version);
18053
18153
  throw new ContractError("unavailable");
18054
18154
  }
@@ -18176,7 +18276,10 @@ Content-Length: 0\r
18176
18276
  });
18177
18277
  return result;
18178
18278
  }
18179
- function binding(id) {
18279
+ function isAssociated(id) {
18280
+ return store.associatedProjects().some((project) => project.id === id);
18281
+ }
18282
+ function binding(id, allowBootstrap = true) {
18180
18283
  let project = store.projects().find((p) => p.id === id);
18181
18284
  if (!project)
18182
18285
  throw new ContractError("unavailable");
@@ -18185,12 +18288,14 @@ Content-Length: 0\r
18185
18288
  throw new ContractError("stale");
18186
18289
  if (local.epoch !== project.epoch) {
18187
18290
  project = { ...project, epoch: local.epoch };
18188
- if (store.associatedProjects().some((p) => p.id === id))
18291
+ if (isAssociated(id))
18189
18292
  store.saveProject(project);
18190
18293
  }
18191
18294
  const previous = bindings.get(id);
18192
18295
  if (previous?.epoch === local.epoch)
18193
18296
  return previous.result;
18297
+ if (!allowBootstrap)
18298
+ throw new ContractError("stale");
18194
18299
  const result = (async () => {
18195
18300
  const raw = closed(await nativeCall(c, "token-link", true), ["link"]), link = new URL(text(raw.link, 4096, true));
18196
18301
  const secret = link.searchParams.get("token");
@@ -18211,7 +18316,11 @@ Content-Length: 0\r
18211
18316
  });
18212
18317
  if (c.localAccess().epoch !== project.epoch)
18213
18318
  throw new ContractError("stale");
18214
- return { project, endpoint: local.endpoint, cookie };
18319
+ return {
18320
+ project: { ...project, epoch: local.epoch },
18321
+ endpoint: local.endpoint,
18322
+ cookie
18323
+ };
18215
18324
  })();
18216
18325
  const pending2 = { epoch: local.epoch, result };
18217
18326
  bindings.set(id, pending2);
@@ -18221,6 +18330,16 @@ Content-Length: 0\r
18221
18330
  });
18222
18331
  return result;
18223
18332
  }
18333
+ function rejectBinding(b, original) {
18334
+ b.rejected = true;
18335
+ if (bindings.get(b.project.id)?.result !== original)
18336
+ return;
18337
+ bindings.delete(b.project.id);
18338
+ for (const viewer of attachments.values()) {
18339
+ if (viewer.project.id === b.project.id && viewer.project.epoch === b.project.epoch && viewer.cookie === b.cookie)
18340
+ viewer.rejected = true;
18341
+ }
18342
+ }
18224
18343
  function stop() {
18225
18344
  if (stopping)
18226
18345
  return;
@@ -18416,8 +18535,14 @@ Content-Length: 0\r
18416
18535
  });
18417
18536
  return;
18418
18537
  }
18419
- closed(value2, []);
18420
18538
  if (operation === "stop") {
18539
+ if (value2 && typeof value2 === "object" && Object.hasOwn(value2, "confirmedWork")) {
18540
+ const { confirmedWork } = closed(value2, ["confirmedWork"]);
18541
+ await assertConfirmedWork(decodeHash(confirmedWork));
18542
+ auth.current(caller2);
18543
+ assert();
18544
+ } else
18545
+ closed(value2, []);
18421
18546
  reply(res, 200, {
18422
18547
  kind: "ok",
18423
18548
  value: { status: "accepted", epoch: auth.epoch }
@@ -18425,6 +18550,7 @@ Content-Length: 0\r
18425
18550
  stop();
18426
18551
  return;
18427
18552
  }
18553
+ closed(value2, []);
18428
18554
  if (operation === "token-rotate") {
18429
18555
  acquired.access.rotate();
18430
18556
  await Promise.all([...retirements]);
@@ -18447,6 +18573,10 @@ Content-Length: 0\r
18447
18573
  throw new ContractError("invalid");
18448
18574
  if (req.headers["content-encoding"] || req.headers["transfer-encoding"] || Number(req.headers["content-length"] ?? 0) > LIMITS.controlBytes)
18449
18575
  throw new ContractError("oversize");
18576
+ const attachment = boundary.headers.get("x-cadence-attachment");
18577
+ const historyCsrf = boundary.headers.get(HISTORY_CSRF_HEADER);
18578
+ if (historyCsrf !== undefined && (route2.source !== "body" || !retainedHistoryBody(route2.operation) || attachment !== undefined || boundary.headers.has("x-cadence-csrf")))
18579
+ throw new ContractError("forbidden");
18450
18580
  if (route2.operation === "workbenchRead" && req.method === "GET") {
18451
18581
  const selected2 = store.projects().find((p) => p.id === project.id);
18452
18582
  if (!selected2)
@@ -18462,22 +18592,26 @@ Content-Length: 0\r
18462
18592
  return;
18463
18593
  }
18464
18594
  }
18465
- if (route2.operation === "session" && !store.associatedProjects().some((p) => p.id === project.id))
18595
+ if (route2.operation === "session" && !isAssociated(project.id))
18466
18596
  throw new ContractError("unavailable");
18467
- const attachment = boundary.headers.get("x-cadence-attachment");
18468
- if (attachment && (attachments.has(attachment) ? attachments.get(attachment)?.projectId !== project.id : route2.operation !== "session") || req.method === "POST" && !attachment)
18597
+ if (attachment && (attachments.has(attachment) ? attachments.get(attachment)?.project.id !== project.id : route2.operation !== "session") || req.method === "POST" && !attachment && historyCsrf === undefined)
18469
18598
  throw new ContractError("stale");
18470
- if (route2.operation === "session" && (!attachment || !attachments.has(attachment)) && attachments.size >= 2048)
18471
- throw new ContractError("capacity");
18599
+ if (route2.operation === "session" && (!attachment || !attachments.has(attachment)) && attachments.size >= 2048) {
18600
+ for (const [id, previous] of attachments)
18601
+ if (previous.rejected)
18602
+ attachments.delete(id);
18603
+ if (attachments.size >= 2048)
18604
+ throw new ContractError("capacity");
18605
+ }
18472
18606
  if (req.method === "POST" && boundary.headers.get("origin") !== boundary.origin)
18473
18607
  throw new ContractError("forbidden");
18474
18608
  const attached = attachment ? attachments.get(attachment) : undefined;
18475
- if (route2.operation === "detach" && attachment && attached) {
18609
+ if (route2.operation === "detach" && attachment && attached && !attached.rejected) {
18476
18610
  const selected2 = store.projects().find((p) => p.id === project.id);
18477
18611
  if (!selected2)
18478
18612
  throw new ContractError("unavailable");
18479
18613
  const observed = new ServiceCoordination(selected2.path, input.stateHome).inspect();
18480
- if (observed.status === "stopped" && observed.epoch === attached.epoch) {
18614
+ if (observed.status === "stopped" && observed.epoch === attached.project.epoch) {
18481
18615
  auth.current(caller);
18482
18616
  assert();
18483
18617
  attachments.delete(attachment);
@@ -18492,10 +18626,31 @@ Content-Length: 0\r
18492
18626
  throw new ContractError("forbidden");
18493
18627
  commandBody = canonicalJson(command, LIMITS.controlBytes);
18494
18628
  }
18495
- const b = await binding(project.id);
18629
+ auth.current(caller);
18630
+ if (attached?.rejected) {
18631
+ if (attachment && route2.operation === "detach")
18632
+ attachments.delete(attachment);
18633
+ reply(res, 401, {
18634
+ kind: "error",
18635
+ error: publicError("unauthenticated")
18636
+ });
18637
+ return;
18638
+ }
18639
+ const original = binding(project.id, historyCsrf === undefined);
18640
+ const b = await original;
18496
18641
  auth.current(caller);
18497
18642
  assert();
18498
- if (attachment && attached && attached.epoch !== b.project.epoch) {
18643
+ if (bindings.get(project.id)?.result !== original)
18644
+ throw new ContractError("stale");
18645
+ if (attachment && attached && attached.project.epoch === b.project.epoch && attached.cookie !== b.cookie) {
18646
+ attached.rejected = true;
18647
+ reply(res, 401, {
18648
+ kind: "error",
18649
+ error: publicError("unauthenticated")
18650
+ });
18651
+ return;
18652
+ }
18653
+ if (attachment && attached && attached.project.epoch !== b.project.epoch) {
18499
18654
  attachments.delete(attachment);
18500
18655
  reply(res, route2.operation === "detach" ? 200 : 409, route2.operation === "detach" ? { kind: "ok", value: null } : {
18501
18656
  kind: "error",
@@ -18507,6 +18662,11 @@ Content-Length: 0\r
18507
18662
  Cookie: b.cookie,
18508
18663
  Origin: b.endpoint
18509
18664
  };
18665
+ if (historyCsrf !== undefined) {
18666
+ if (!b.history || b.history.browser !== historyCsrf)
18667
+ throw new ContractError("forbidden");
18668
+ headers2[HISTORY_CSRF_HEADER] = b.history.owner;
18669
+ }
18510
18670
  for (const key2 of [
18511
18671
  "accept-encoding",
18512
18672
  "content-type",
@@ -18525,19 +18685,35 @@ Content-Length: 0\r
18525
18685
  const upstream = request2(`${b.endpoint}${project.tail}`, { method: req.method, headers: headers2, agent: false }, (incoming) => {
18526
18686
  try {
18527
18687
  auth.current(caller);
18688
+ if (incoming.statusCode === 401) {
18689
+ const cookieName = b.cookie.split("=", 1)[0];
18690
+ if (incoming.headers["set-cookie"]?.some((line) => {
18691
+ const [cookie, ...attributes] = line.split(/;\s*/);
18692
+ return cookie === `${cookieName}=` && attributes.includes("Max-Age=0");
18693
+ }))
18694
+ rejectBinding(b, original);
18695
+ } else if (bindings.get(project.id)?.result !== original) {
18696
+ throw new ContractError("stale");
18697
+ }
18698
+ if (route2.operation === "workspace" && incoming.statusCode === 200 && incoming.headers[HISTORY_CSRF_HEADER] !== undefined) {
18699
+ const owner = decodeId(incoming.headers[HISTORY_CSRF_HEADER]);
18700
+ if (b.history?.owner !== owner)
18701
+ b.history = { owner, browser: randomUUID14() };
18702
+ res.setHeader(HISTORY_CSRF_HEADER, b.history.browser);
18703
+ }
18528
18704
  } catch {
18529
18705
  close();
18530
18706
  return;
18531
18707
  }
18532
18708
  if (route2.operation === "session" && incoming.statusCode === 200) {
18533
18709
  try {
18534
- attachments.set(decodeId(incoming.headers["x-cadence-attachment"]), { projectId: project.id, epoch: b.project.epoch });
18710
+ attachments.set(decodeId(incoming.headers["x-cadence-attachment"]), b);
18535
18711
  } catch {
18536
18712
  close();
18537
18713
  return;
18538
18714
  }
18539
18715
  }
18540
- if (route2.operation === "detach" && incoming.statusCode === 200 && attachment)
18716
+ if (route2.operation === "detach" && incoming.statusCode === 200 && attachment && attachments.get(attachment) === attached)
18541
18717
  attachments.delete(attachment);
18542
18718
  res.statusCode = incoming.statusCode ?? 502;
18543
18719
  for (const key2 of [
@@ -18598,12 +18774,14 @@ Content-Length: 0\r
18598
18774
  auth.current(caller);
18599
18775
  assert();
18600
18776
  const status = observed && typeof observed === "object" && "status" in observed ? observed.status : "unavailable";
18601
- reply(res, 200, {
18777
+ const value2 = {
18602
18778
  kind: "project-observation",
18603
18779
  status: status === "alive" ? "running" : status === "stopped" ? "stopped" : unpreparedDirectory(c, project2) ? "not-started" : "unavailable",
18604
18780
  epoch: observed && typeof observed === "object" && "epoch" in observed ? observed.epoch : null,
18605
18781
  workspaceId: HistoryFiles.open(c)?.format.workspaceId ?? null
18606
- });
18782
+ };
18783
+ res.setHeader(PROJECT_ASSOCIATION_HEADER, isAssociated(project2.id) ? "associated" : "unassociated");
18784
+ reply(res, 200, value2);
18607
18785
  return;
18608
18786
  }
18609
18787
  if (url.pathname === "/workbench/v1/models" && req.method === "GET") {
@@ -18644,7 +18822,10 @@ Content-Length: 0\r
18644
18822
  return;
18645
18823
  }
18646
18824
  if (raw === "/workbench/v1/service" && req.method === "GET") {
18647
- reply(res, 200, await serviceEntry());
18825
+ const service = await serviceEntry();
18826
+ auth.current(caller);
18827
+ assert();
18828
+ reply(res, 200, service);
18648
18829
  return;
18649
18830
  }
18650
18831
  if (raw === "/workbench/v1/service/release" && req.method === "GET") {
@@ -18695,6 +18876,8 @@ Content-Length: 0\r
18695
18876
  const asset = assets.get(app ? "/app" : raw);
18696
18877
  if (req.method !== "GET" || !asset)
18697
18878
  throw new ContractError("invalid");
18879
+ if (app)
18880
+ res.setHeader("X-Cadence-Web-Build", build2.assets.buildId);
18698
18881
  res.setHeader("Content-Type", asset.contentType);
18699
18882
  res.end(asset.bytes);
18700
18883
  } catch (error) {
@@ -18724,10 +18907,14 @@ Content-Length: 0\r
18724
18907
  if (req.method !== "GET" || !t)
18725
18908
  throw new ContractError("invalid");
18726
18909
  const url = new URL(t.tail, endpoint2), attachment = decodeId(url.searchParams.get("attachment"));
18727
- if (attachments.get(attachment)?.projectId !== t.id || t.tail !== `${WS_PATH}?attachment=${attachment}`)
18910
+ if (attachments.get(attachment)?.project.id !== t.id || t.tail !== `${WS_PATH}?attachment=${attachment}`)
18728
18911
  throw new ContractError("invalid");
18729
- const b = await binding(t.id);
18730
- if (attachments.get(attachment)?.epoch !== b.project.epoch)
18912
+ const attached = attachments.get(attachment);
18913
+ if (!attached || attached.rejected)
18914
+ throw new ContractError("unauthenticated");
18915
+ const original = binding(t.id);
18916
+ const b = await original;
18917
+ if (bindings.get(t.id)?.result !== original || attachments.get(attachment) !== attached || attached.project.epoch !== b.project.epoch || attached.cookie !== b.cookie)
18731
18918
  throw new ContractError("stale");
18732
18919
  auth.current(caller);
18733
18920
  assert();
@@ -18745,6 +18932,12 @@ Content-Length: 0\r
18745
18932
  };
18746
18933
  relays.add(abort);
18747
18934
  socket.once("close", abort);
18935
+ upstream.once("unexpected-response", (_request, response) => {
18936
+ if (response.statusCode === 401)
18937
+ rejectBinding(b, original);
18938
+ response.destroy();
18939
+ abort();
18940
+ });
18748
18941
  upstream.once("error", abort);
18749
18942
  upstream.once("close", abort);
18750
18943
  upstream.once("open", () => {
@@ -31269,7 +31462,7 @@ import { join as join39 } from "node:path";
31269
31462
  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.
31270
31463
  You are the sole user-facing coordinator. Understand the desired result, not a task-management form. Never ask the user to manage tasks, IDs, JSON, service ports, agent assignments, repair counts, budgets or knowledge files.
31271
31464
  Start with existing evidence. Use cadence_knowledge to read a named project document or heading directly (the route table, AGENTS.md and the project index identify sources). Reuse recorded investigation answers from this conversation by passing their investigation ID to cadence_knowledge, which rechecks their cited files; older conclusions are leads until checked against current sources. For a directly verifiable fact, use cadence_knowledge with path and match to read the actual source line and nearby context. Read the returned results before broadening an investigation. Surface material user choices as soon as the tradeoffs are understood. Exact implementation values, selectors and file inventories ordinarily belong to implementation workers and need not delay the design or plan. Zero research runs is appropriate when evidence suffices. Use cadence_research only for unresolved questions whose answers could change the design or acceptance. Ask focused independent questions together and reuse answered results by investigation ID.
31272
- For material choices about experience, scope or expensive tradeoffs, call cadence_design with one batch of real alternatives in the user's language before publishing a plan. Describe each option's cost, the recommendation and reason, and what acceptance it affects. Give stable lowercase IDs; use when for predictable dependencies on earlier options. Keep routine implementation decisions yourself. Do not invent a questionnaire for a settled task. The user can edit any question, enter other ideas, fill remaining recommendations and submit once. A submitted design or "按你推荐的来" calls for the final implementation card in the same conversation; it never authorizes execution. Respect the submitted decisions, including custom answers, throughout the plan and review.
31465
+ For material choices about experience, scope or expensive tradeoffs, call cadence_design with one batch of real alternatives in the user's language before publishing a plan. Describe each option's cost, the recommendation and reason, and what acceptance it affects. Give stable lowercase IDs; omit when (or use null) unless the question depends on an earlier option. Publish the choices through the tool, not a Markdown questionnaire asking for a typed reply. If publication is refused for invalid input, correct the named field and repeat the complete batch yourself. Keep routine implementation decisions yourself. Do not invent a questionnaire for a settled task. The user can edit any question, enter other ideas, fill remaining recommendations and submit once. A submitted design or "按你推荐的来" calls for the final implementation card in the same conversation; it never authorizes execution. Respect the submitted decisions, including custom answers, throughout the plan and review.
31273
31466
  Once the result is clear, use cadence_plan. Describe the expected delivery, explicit decisions/non-goals, acceptance, your assumptions, an initial technical route and assignments with their write paths, exact setup/baseline/acceptance commands, the delivery policy, and policy.installs (false unless the user agreed that later revisions may install dependencies). Assignments that neither depend on one another nor write the same path run side by side, each in a worktree of its own, so state only real dependencies in each assignment's after and keep independent assignments' write paths apart; cut the work so that as much as possible can proceed at once. Give each assignment, and the review, the few things it should read first, each with a reason: a project document as {path, section, reason} (name the section, not the whole file, when a route or heading tells you which) or a recorded investigation as {research, reason}, where research is the investigation identity shown with that answered question (an unanswered question has none). Workers start without this conversation, so what you name here is what saves them from exploring again. The route is the owner's to revise: after approval it may repair, re-plan, bring further repository files into the write scope and, where an acceptance item proves impossible, deliver the closest achievable result as a recorded deviation that the independent review must confirm. Goal, decisions, acceptance and assumptions stay as approved. Focus on the project, its implementation and its real checks. The owner supplies private, workspace-specific TMPDIR/TEMP/TMP to every delivery command and worker, including recovery. Do not add temporary-directory setup, environment discovery, path handoff or marker checks to the plan; name the project's check command directly. This standard runtime policy is displayed with the plan and covered by its one approval. For local preparation, use cadence_knowledge with checkout: [the needed dependency directory names] to observe the original checkout, Git placement and local entries directly. Use the original entry by path if the user authorizes sharing installed dependencies; the link target and its contents are unnecessary. cadence_plan checks the actual write targets and Git commit identity. Leave those checks to the owner. Do not send researchers to enumerate Git internals, ignored dependencies or private workflow records for these facts. Worktrees do not inherit ignored dependencies. Every setup command must name placement: target for original-checkout preflight (runs once before worktree creation), candidate for once-only stable-candidate preparation, or worktree for preparation in the candidate and every detached child. Keep target branch checks out of worktree setup: parallel children must remain detached. The owner already checks Git placement and target identity. Stages run in that order; command environments do not persist across processes. Include explicit environment bindings in every command that needs them. Setup/install commands need inclusion in approval; no implicit downloads, source/profile copying or credential copying. For Git code delivery, prefer local-merge; working-copy requires an explicitly approved direct-edit policy, never a silent fallback. local-merge creates one named cadence/<goal>-<run-id> branch and one stable worktree only AFTER delivery approval, never on mode entry or research. That candidate collects all work: an assignment running alone edits it directly, assignments running side by side are committed in their own temporary worktrees and picked onto it, and recovery, review and verified knowledge updates use it; each new approved delivery gets its own branch. The original conversation cwd stays unchanged. Checks and independent Agent review must bind the exact candidate before fast-forward delivery into the displayed target. Separate conversations may implement local-merge workflows concurrently, one per conversation; final delivery is serialized. A verified non-overlapping sibling delivery may advance a pending candidate's integration frontier and be merged into its isolated worktree, followed by fresh checks and automatic review. Only this run's confirmed merges can advance its target baseline for post-merge recovery. Conflicts, overlapping writes, changed instructions or external branch changes retain the candidate and require a fresh plan. Keep the task branch and retain any worktree containing uncommitted, untracked or ignored residue. No automatic rebase, reset, cleanup of user data or mutation replay. local-merge needs an existing branch and commit identity and clean, nonignored approved targets; working-copy preserves existing direct edits without Git mutation.
31274
31467
  The service maintains the project's knowledge store (.cadence/project.md and .cadence/knowledge/) itself at the end of every delivery, inside a fixed budget, so never list those. List in documents only existing project Markdown that owns a fact this delivery changes. Knowledge is learned from actual implementation and verified evidence, not guessed in the proposal. Avoid duplicate documentation systems.
31275
31468
  When a tool refuses your own call it names the field at fault: correct exactly that and call again in the same turn. There is one plan. Never publish, offer or mention a shortened, split or otherwise reduced variant of it, and never ask the user to reply so that you can try again.
@@ -31277,6 +31470,179 @@ Present a concise delivery expectation with the complete returned agreement avai
31277
31470
  During accepted work the service owns progress, recovery and revision, and finishes without the user. Report actual cadence_status observations; do not start replacement workflows or ask for 'continue' after an individual child fails. Child failure is not delivery failure. Report recorded plan revisions as progress and lead with any recorded deviation when the run completes. Agents have no total runtime deadline; explicit command timeouts and actual closure still apply. A run stops only for a condition outside the repository; then explain that condition and the preserved outcomes, not a generic request to continue.
31278
31471
  For follow-up to a settled or interrupted run, inspect retained outcomes first. Partial outputs are not unexplained user edits. Unknown results must be observed and reconciled, never blindly replayed; a new delivery requires fresh approval. No automatic replay after owner restart. cadence_cancel is explicit cancellation, not navigation or exit. Worker prose is not passing checks; automatic review is never human review. Completion leaves Cadence ON and ready. Tools operate on the host; this is not a sandbox.`;
31279
31472
 
31473
+ // src/coordinator-tools.mjs
31474
+ import { Type } from "typebox";
31475
+ var CHECK = Type.Object({
31476
+ name: Type.String(),
31477
+ command: Type.String(),
31478
+ timeoutMs: Type.Optional(Type.Integer({
31479
+ description: "Milliseconds, from 100. Leave out for no timeout."
31480
+ }))
31481
+ });
31482
+ var READING = Type.Union([
31483
+ Type.Object({
31484
+ path: Type.String({ description: "Project document to read first." }),
31485
+ section: Type.Optional(Type.String({ description: "One heading of that document." })),
31486
+ reason: Type.String()
31487
+ }),
31488
+ Type.Object({
31489
+ research: Type.String({
31490
+ description: 'A recorded investigation: the "investigation" value of a completed research step.'
31491
+ }),
31492
+ reason: Type.String()
31493
+ })
31494
+ ]);
31495
+ var RESEARCH_PARAMETERS = Type.Object({
31496
+ goal: Type.String(),
31497
+ questions: Type.Array(Type.String({
31498
+ description: "One focused, independent question."
31499
+ }), {
31500
+ description: "Split independent questions freely; the service runs as many at once as this machine is configured for and queues the rest."
31501
+ }),
31502
+ roots: Type.Optional(Type.Array(Type.String({
31503
+ description: "Specific investigation directories, relative to this conversation's cwd by default. Avoid filesystem roots and broad parent trees."
31504
+ })))
31505
+ });
31506
+ var lookupExample = 'Use {checkout:["node_modules"]}, {checkout:[]}, {path:"docs.md"} with optional section or match, or {investigation:"<retained UUID>"}.';
31507
+ function knowledgeToolInput(input) {
31508
+ const bad12 = (field, why) => {
31509
+ throw new Error(`${field}: ${why}. ${lookupExample}`);
31510
+ };
31511
+ const keys2 = Object.keys(input ?? {});
31512
+ let raw;
31513
+ try {
31514
+ raw = closed(input, keys2);
31515
+ } catch {
31516
+ bad12("cadence_knowledge", "expected an object with named lookup fields");
31517
+ }
31518
+ const fields3 = Object.create(null);
31519
+ for (const key3 of keys2) {
31520
+ if (!Object.hasOwn(knowledgeFields, key3))
31521
+ bad12(JSON.stringify(key3.slice(0, 80)), "unknown field; omit it");
31522
+ if (key3 !== "checkout" && raw[key3] === "")
31523
+ continue;
31524
+ try {
31525
+ fields3[key3] = knowledgeFields[key3](raw[key3]);
31526
+ } catch {
31527
+ bad12(key3, key3 === "checkout" ? "give an array of up to eight nonempty dependency paths (each at most 1024 bytes)" : key3 === "investigation" ? "give a retained investigation UUID" : "give a nonblank string within the field limit");
31528
+ }
31529
+ }
31530
+ const { checkout, path, section, match, investigation } = fields3;
31531
+ if ((section || match) && !path)
31532
+ bad12(section ? "section/path" : "match/path", "name the source file in path");
31533
+ if (section && match)
31534
+ bad12("section/match", "choose one selector");
31535
+ if (checkout?.length && (path || investigation))
31536
+ bad12("checkout", "cannot combine dependencies with path or investigation");
31537
+ if (investigation && path)
31538
+ bad12("investigation/path", "choose one source");
31539
+ const relative9 = (name) => !/[\\:\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(name) && name.split("/").every((part) => part && part !== "." && part !== ".." && part.toLowerCase() !== ".git");
31540
+ if (path && !relative9(path))
31541
+ bad12("path", "give a plain checkout-relative file path");
31542
+ if (checkout?.some((name) => !relative9(name) || name.split("/").some((part) => part.startsWith("."))))
31543
+ bad12("checkout", "give plain checkout-relative dependency names");
31544
+ if (investigation)
31545
+ return { investigation };
31546
+ if (path)
31547
+ return match ? { path, match } : section ? { path, section } : { path };
31548
+ if (checkout)
31549
+ return { checkout };
31550
+ bad12("path/checkout/investigation", "no lookup selected");
31551
+ }
31552
+ var KNOWLEDGE_PARAMETERS = Type.Object({
31553
+ checkout: Type.Optional(Type.Array(Type.String(), {
31554
+ description: "Instead of other fields, give up to eight checkout-relative dependency directory names (e.g. node_modules and web/node_modules), or [] for Git placement only. Observe the original checkout, Git branch and HEAD, and whether each named entry is a directory, symlink or absent. Never follows a dependency link."
31555
+ })),
31556
+ path: Type.Optional(Type.String({
31557
+ description: "One checkout-relative document, or the exact project source file containing a known fact."
31558
+ })),
31559
+ section: Type.Optional(Type.String({
31560
+ description: "Exact Markdown heading. Use either section or match."
31561
+ })),
31562
+ match: Type.Optional(Type.String({
31563
+ description: "A literal on a line of this source file (such as a token, assertion or build script). Return matching line numbers with short previews and context at the first occurrence, without a research worker."
31564
+ })),
31565
+ investigation: Type.Optional(Type.String({
31566
+ description: "Instead of path/section, supply a retained investigation ID to recheck its sources and reuse the answer."
31567
+ }))
31568
+ });
31569
+ var DESIGN_PARAMETERS = Type.Object({
31570
+ questions: Type.Array(Type.Object({
31571
+ id: Type.String(),
31572
+ question: Type.String(),
31573
+ options: Type.Array(Type.Object({
31574
+ id: Type.String(),
31575
+ label: Type.String(),
31576
+ cost: Type.String()
31577
+ })),
31578
+ recommended: Type.String({ description: "Recommended option ID" }),
31579
+ reason: Type.String(),
31580
+ acceptance: Type.String({
31581
+ description: "Acceptance item this decision affects"
31582
+ }),
31583
+ when: Type.Optional(Type.Union([
31584
+ Type.Null(),
31585
+ Type.Object({ question: Type.String(), option: Type.String() })
31586
+ ], {
31587
+ description: "Omit or use null for an independent question. For a conditional question give an earlier question ID and one of its option IDs."
31588
+ }))
31589
+ }))
31590
+ });
31591
+ var PLAN_PARAMETERS = Type.Object({
31592
+ goal: Type.String(),
31593
+ design: Type.String({ description: "The initial technical route." }),
31594
+ decisions: Type.Optional(Type.String({ description: "Explicit decisions and non-goals." })),
31595
+ acceptance: Type.String(),
31596
+ assumptions: Type.Optional(Type.String({
31597
+ description: "What you decided on the user's behalf without asking; approval confirms it. Leave out when there is none."
31598
+ })),
31599
+ documents: Type.Optional(Type.Array(Type.String({
31600
+ description: "Existing project Markdown this delivery may update."
31601
+ }))),
31602
+ reviewReads: Type.Optional(Type.Array(READING, {
31603
+ description: "What the independent review reads first."
31604
+ })),
31605
+ policy: Type.Optional(Type.Object({
31606
+ installs: Type.Optional(Type.Boolean({
31607
+ description: "Whether a later revision may add dependency-installation commands. False unless the user agreed."
31608
+ }))
31609
+ })),
31610
+ tasks: Type.Array(Type.Object({
31611
+ id: Type.String({
31612
+ description: "Lowercase letters, digits and hyphens, starting with a letter."
31613
+ }),
31614
+ title: Type.String(),
31615
+ instructions: Type.String({ description: "At most 8KiB." }),
31616
+ writes: Type.Array(Type.String()),
31617
+ after: Type.Optional(Type.Array(Type.String(), {
31618
+ description: "Ids of the assignments this one really depends on. Leave out when it depends on none."
31619
+ })),
31620
+ reads: Type.Optional(Type.Array(READING, {
31621
+ description: "The few things this assignment should read first."
31622
+ }))
31623
+ }), { description: "One to 16 assignments." }),
31624
+ checks: Type.Array(CHECK, {
31625
+ description: "The real acceptance commands: at least one, at most 16."
31626
+ }),
31627
+ setup: Type.Optional(Type.Array(Type.Object({
31628
+ ...CHECK.properties,
31629
+ placement: Type.Union([
31630
+ Type.Literal("target"),
31631
+ Type.Literal("candidate"),
31632
+ Type.Literal("worktree")
31633
+ ], {
31634
+ description: "target: preflight once in the original checkout before creating worktrees; candidate: once in the stable candidate; worktree: prepare the candidate and every detached child. Target branch checks belong to target, never worktree. Commands do not export environment into later processes."
31635
+ })
31636
+ }), {
31637
+ description: "Explicit preparation commands with their execution placement, at most four. Run in target, candidate, then worktree stages, preserving order within each stage."
31638
+ })),
31639
+ baselineChecks: Type.Optional(Type.Array(CHECK)),
31640
+ delivery: Type.Union([
31641
+ Type.Literal("local-merge"),
31642
+ Type.Literal("working-copy")
31643
+ ])
31644
+ });
31645
+
31280
31646
  // src/service/project-knowledge.ts
31281
31647
  import { isUtf8 } from "node:buffer";
31282
31648
  import { createHash as createHash31 } from "node:crypto";
@@ -31780,11 +32146,20 @@ function workflowObservation(cwd, plan) {
31780
32146
  identity: hash(JSON.stringify({ head, branch, contents }))
31781
32147
  };
31782
32148
  }
31783
- async function assertTarget(cwd, expected, scope) {
31784
- const head = await gitHead(cwd);
31785
- const branch = (await gitText(cwd, ["symbolic-ref", "HEAD"])).trim();
31786
- if (head !== expected.head || branch !== expected.branch)
31787
- throw new WorkflowRefusal("stale", `The target branch changed during the run (expected ${expected.branch} at ${expected.head.slice(0, 12)}); nothing was integrated.`);
32149
+ async function assertTargetPosition(cwd, expected, stage) {
32150
+ const [ref, oid] = await Promise.all([
32151
+ gitRun(cwd, ["symbolic-ref", "--quiet", "HEAD"]).catch(() => null),
32152
+ gitRun(cwd, ["rev-parse", "--verify", "HEAD"]).catch(() => null)
32153
+ ]);
32154
+ const branch = ref?.code === 0 ? ref.stdout.trim() : ref?.code === 1 ? "(detached HEAD)" : null;
32155
+ const head = oid?.code === 0 ? oid.stdout.trim() : null;
32156
+ if (head === expected.head && branch === expected.branch)
32157
+ return;
32158
+ const unreadable = !head || !branch;
32159
+ throw new WorkflowRefusal(unreadable ? "unavailable" : "stale", `${stage}: target ${unreadable ? "identity could not be verified" : "position changed"}; expected ${expected.branch} at ${expected.head}, observed ${branch || "(unreadable ref)"} at ${head || "(unreadable HEAD)"}. Refused to proceed; this check made no merge.`);
32160
+ }
32161
+ async function assertTarget(cwd, expected, scope, stage) {
32162
+ await assertTargetPosition(cwd, expected, stage);
31788
32163
  assertVisibleIndex(overlapping(scope, indexHidden(await gitText(cwd, INDEX_FLAGS))));
31789
32164
  const dirty = overlapping(scope, await changedPaths(cwd));
31790
32165
  if (dirty.length)
@@ -32908,32 +33283,42 @@ Current design ${design.id}, revision ${design.revision}, ${design.submitted ? "
32908
33283
  if (name === "cadence_knowledge") {
32909
33284
  if (!this.o.cwd)
32910
33285
  return refusal3("unavailable", "Project directory unavailable.");
33286
+ let source;
32911
33287
  try {
32912
- return await this.knowledge(decodeKnowledgeLookup(args));
32913
- } catch {
32914
- return refusal3("invalid", "checkout/path/section/match/investigation: supply checkout with a list of local dependency paths, a Markdown path and optional heading, a file path and literal match, or one retained investigation ID.");
33288
+ source = knowledgeToolInput(args);
33289
+ } catch (error) {
33290
+ return refusal3("invalid", diagnosticText(error instanceof Error ? error.message : "Expected a knowledge lookup.", 512, this.o.secrets()));
32915
33291
  }
32916
- }
32917
- if (name === "cadence_design") {
32918
33292
  try {
32919
- const design2 = newDesign(randomUUID25(), args, current2.state.design);
32920
- if (sanitizeText(canonicalJson(design2), this.o.secrets()) !== canonicalJson(design2))
32921
- return refusal3("forbidden", "Design contains protected text.");
32922
- this.save({
32923
- ...current2.state,
32924
- design: design2,
32925
- proposal: null,
32926
- revision: current2.state.revision + 1
32927
- }, current2.file);
32928
- return {
32929
- designId: design2.id,
32930
- notice: "Design choices displayed. Finish this turn and wait for the user's batch submission."
32931
- };
33293
+ return await this.knowledge(source);
32932
33294
  } catch (error) {
32933
33295
  if (this.o.owner.state !== "idle")
32934
33296
  throw error;
33297
+ const field = "checkout" in source ? "checkout" : ("investigation" in source) ? "investigation" : "path";
33298
+ const code2 = error instanceof ContractError ? error.code : "unavailable";
33299
+ return refusal3(code2, field === "checkout" ? "checkout: the owner could not observe that entry. Name an allowed dependency directly, not through a linked ancestor." : `${field}: the owner could not read that source; use an allowed project source.`);
33300
+ }
33301
+ }
33302
+ if (name === "cadence_design") {
33303
+ let design2;
33304
+ try {
33305
+ design2 = newDesign(randomUUID25(), args, current2.state.design);
33306
+ } catch (error) {
32935
33307
  return refusal3("invalid", diagnosticText(error instanceof Error ? error.message : "questions: invalid design", 512, this.o.secrets()));
32936
33308
  }
33309
+ const encoded2 = canonicalJson(design2);
33310
+ if (sanitizeText(encoded2, this.o.secrets()) !== encoded2)
33311
+ return refusal3("forbidden", "Design contains protected text.");
33312
+ this.save({
33313
+ ...current2.state,
33314
+ design: design2,
33315
+ proposal: null,
33316
+ revision: current2.state.revision + 1
33317
+ }, current2.file);
33318
+ return {
33319
+ designId: design2.id,
33320
+ notice: "Design choices published. Finish this turn and wait for the user's batch submission; do not ask for a typed answer."
33321
+ };
32937
33322
  }
32938
33323
  const epoch = this.o.owner.lease.registration.epoch;
32939
33324
  const model2 = c.model.conversation && this.o.contexts ? this.o.contexts.snapshot(c.model.conversation).version : this.o.choice.snapshot().version;
@@ -33508,7 +33893,7 @@ class Conversations {
33508
33893
  epoch: live2.epoch,
33509
33894
  now: Date.now(),
33510
33895
  leaf: live2.accepted.parent,
33511
- phase: live2.abort.signal.aborted ? "stopping" : live2.state.status === "queued" ? "queued" : live2.state.status === "running" ? "running" : "settling"
33896
+ phase: live2.abort.signal.aborted ? "stopping" : isLiveChatStatus(live2.state.status) ? live2.state.status : "settling"
33512
33897
  }));
33513
33898
  }
33514
33899
  constructor(o) {
@@ -33652,7 +34037,7 @@ class Conversations {
33652
34037
  epoch: input.model.epoch,
33653
34038
  title: listed ? summaryTitle(listed.summary) : [...command.text.trim()].slice(0, 100).join("") || "Conversation",
33654
34039
  state: {
33655
- status: "queued",
34040
+ status: control ? "queued" : "starting",
33656
34041
  notice: "",
33657
34042
  omitted: { thinking: false, media: false, other: false },
33658
34043
  user: null
@@ -33923,7 +34308,6 @@ class Conversations {
33923
34308
  async run(live2, control) {
33924
34309
  const { accepted: accepted2, abort, state } = live2;
33925
34310
  const commandId = live2.commandId;
33926
- let barrier;
33927
34311
  let authSettled;
33928
34312
  let uncertain = false;
33929
34313
  let native = {
@@ -33944,6 +34328,7 @@ class Conversations {
33944
34328
  };
33945
34329
  const current2 = () => !abort.signal.aborted && this.o.owner.state === "idle" && this.currentDirectory(live2.execution.cwd);
33946
34330
  try {
34331
+ this.o.owner.lease.assert();
33947
34332
  if (!current2())
33948
34333
  throw new ContractError("stale");
33949
34334
  if (control?.reply) {
@@ -33951,12 +34336,6 @@ class Conversations {
33951
34336
  state.notice = control.reply;
33952
34337
  return { status: "settled" };
33953
34338
  }
33954
- if (!control) {
33955
- barrier = await this.o.gate.acquire(commandId, abort.signal);
33956
- barrier.assertHeld();
33957
- }
33958
- if (!current2())
33959
- throw new ContractError("stale");
33960
34339
  const selected2 = live2.execution.model;
33961
34340
  if (!selected2)
33962
34341
  throw new ContractError("stale");
@@ -34083,8 +34462,6 @@ CONVERSATION CONTEXT (data): cwd ${live2.execution.cwd}; checkout root ${live2.e
34083
34462
  }
34084
34463
  if (uncertain)
34085
34464
  this.o.owner.quarantine();
34086
- else if (this.o.owner.state === "idle")
34087
- barrier?.release();
34088
34465
  for (const input of live2.inputs)
34089
34466
  this.inputs.delete(input.commandId);
34090
34467
  this.active.delete(commandId);
@@ -35080,7 +35457,7 @@ class WorkflowDelivery {
35080
35457
  await assertTarget(this.view.binding.target.checkoutRoot, {
35081
35458
  branch: this.view.binding.target.branch,
35082
35459
  head: targetHead
35083
- }, scope);
35460
+ }, scope, "integration preflight");
35084
35461
  if ((await gitRun(this.view.worktreeRoot, [
35085
35462
  "merge-base",
35086
35463
  "--is-ancestor",
@@ -35721,8 +36098,8 @@ function workflowResultDetail(value, secrets) {
35721
36098
  var runtimeSummary = (runtime) => `${describeWorkerRuntime(runtime)}
35722
36099
  ${RUN_ENVIRONMENT_POLICY}`;
35723
36100
  var OWNER_RUNTIME = Object.freeze({
35724
- version: "2.2.0",
35725
- build: "ddf9e9d35a3a7b928845d9b7bf1c122aa355e11810dc0066577290956bf6c793",
36101
+ version: "2.2.2",
36102
+ build: "9d8538776a8e8f204fa4ccffb749d41eee1ca010f56af92ef5d3e88038eb2910",
35726
36103
  entry: fileURLToPath7(import.meta.url),
35727
36104
  pid: process.pid,
35728
36105
  node: process.versions.node,
@@ -36432,6 +36809,8 @@ class Workflows {
36432
36809
  effect();
36433
36810
  if (request3.action === "execute")
36434
36811
  this.grants.delete(request3.grant);
36812
+ if (live2.run.delivery)
36813
+ live2.delivery = new WorkflowDelivery(live2.run.delivery, new RepositoryCoordination(this.o.coordination, this.cwd, live2.run.epoch, live2.run.id, () => this.o.owner.lease.assert(), () => this.o.owner.quarantine()), () => this.save(live2));
36435
36814
  this.active.set(commandId, live2);
36436
36815
  this.o.owner.trackConversation(live2.original, () => abort.abort({ source: "service", reason: "stop", target: commandId }));
36437
36816
  try {
@@ -37261,9 +37640,9 @@ ${diagnosticText(lines.join(`
37261
37640
  await assertTarget(this.cwd, {
37262
37641
  branch: live2.target.branch,
37263
37642
  head: live2.delivery?.targetHead() ?? live2.target.head
37264
- }, paths);
37643
+ }, paths, "scope revision");
37265
37644
  } catch (error) {
37266
- if (!(error instanceof WorkflowRefusal) || error.code === "stale")
37645
+ if (!(error instanceof WorkflowRefusal) || error.code === "stale" || error.code === "unavailable")
37267
37646
  throw error;
37268
37647
  throw new InvalidDecision(`These paths cannot join the write scope because the target checkout has its own changes to them or hides them: ${paths.join(", ")} (${error.detail})`);
37269
37648
  }
@@ -37574,8 +37953,10 @@ Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
37574
37953
  await assertTarget(this.cwd, {
37575
37954
  branch: live2.target.branch,
37576
37955
  head: live2.delivery?.targetHead() ?? live2.target.head
37577
- }, KNOWLEDGE_SCOPE);
37578
- } catch {
37956
+ }, KNOWLEDGE_SCOPE, "knowledge placement");
37957
+ } catch (error) {
37958
+ if (error instanceof WorkflowRefusal && (error.code === "stale" || error.code === "unavailable"))
37959
+ throw error;
37579
37960
  return skip("the target checkout has its own changes to the knowledge store.");
37580
37961
  }
37581
37962
  return true;
@@ -37929,6 +38310,17 @@ ${result.output}`}`);
37929
38310
  if (pathIdentity(this.cwd, "AGENTS.md") !== live2.guidance.agents)
37930
38311
  throw new WorkflowRefusal("conflict", "AGENTS.md changed during the run. The candidate is retained; review a fresh plan before integration.");
37931
38312
  }
38313
+ async assertSiblingScope(branch, base, frontier, scope, stage) {
38314
+ const changed = await committedPaths(this.cwd, base, frontier);
38315
+ const conflicts = [
38316
+ ...new Set([
38317
+ ...overlapping([...scope, "AGENTS.md"], changed),
38318
+ ...changed.filter((path) => path.endsWith("/AGENTS.md"))
38319
+ ])
38320
+ ].sort();
38321
+ if (conflicts.length)
38322
+ throw new WorkflowRefusal("conflict", `${stage}: verified sibling advanced ${branch} from ${base} to ${frontier} and changed approved inputs: ${conflicts.join(", ")}. Refused to integrate overlapping work.`);
38323
+ }
37932
38324
  async refreshCandidate(live2, integration, p) {
37933
38325
  const delivery = live2.delivery;
37934
38326
  const target2 = live2.target;
@@ -37936,21 +38328,13 @@ ${result.output}`}`);
37936
38328
  throw new ContractError("invalid");
37937
38329
  const scope = this.scope(live2, p);
37938
38330
  const frontier = delivery.frontierHead();
37939
- await assertTarget(this.cwd, { branch: target2.branch, head: frontier }, scope);
38331
+ await assertTarget(this.cwd, { branch: target2.branch, head: frontier }, scope, "candidate refresh");
37940
38332
  this.assertGuidance(live2);
37941
38333
  if (!delivery.needsRefresh())
37942
38334
  return;
37943
38335
  await delivery.assertAcceptedCandidate(p.digest, live2.execution, scope);
37944
38336
  const base = delivery.candidateBase();
37945
- const changed = await committedPaths(this.cwd, base, frontier);
37946
- const conflicts = [
37947
- ...new Set([
37948
- ...overlapping([...scope, "AGENTS.md"], changed),
37949
- ...changed.filter((path) => path.endsWith("/AGENTS.md"))
37950
- ])
37951
- ].sort();
37952
- if (conflicts.length)
37953
- throw new WorkflowRefusal("conflict", `A parallel workflow changed approved inputs: ${conflicts.join(", ")}. The isolated candidate is retained; review a fresh plan before integration.`);
38337
+ await this.assertSiblingScope(target2.branch, base, frontier, scope, "candidate refresh");
37954
38338
  let merged = "";
37955
38339
  await this.gitStep(live2, integration, "integrate-parallel-deliveries", async (git) => {
37956
38340
  await git(["merge", "--no-ff", "--no-edit", frontier]);
@@ -37985,7 +38369,7 @@ ${result.output}`}`);
37985
38369
  const integration = delivery?.view.worktreeRoot ?? this.cwd;
37986
38370
  if (plan.setup.some((c) => c.placement === "target")) {
37987
38371
  await this.setup(live2, this.cwd, p, "target");
37988
- await this.assertStartable(live2, p);
38372
+ await this.assertStartable(live2, p, "after target setup");
37989
38373
  }
37990
38374
  if (delivery) {
37991
38375
  delivery.prepareHome();
@@ -38067,7 +38451,7 @@ ${result.output}`}`);
38067
38451
  if (!expected)
38068
38452
  throw new ContractError("quarantine");
38069
38453
  assertRepository(delivery.view.binding.target);
38070
- await assertTarget(this.cwd, { head: expected, branch: target2.branch }, scope);
38454
+ await assertTarget(this.cwd, { head: expected, branch: target2.branch }, scope, "before post-merge checks");
38071
38455
  delivery.view.postChecks = "unknown";
38072
38456
  this.save(live2);
38073
38457
  const beforeSource = await sourceIdentityAsync(this.cwd, scope, live2.abort.signal);
@@ -38079,9 +38463,7 @@ ${result.output}`}`);
38079
38463
  const deliveredHead = live2.run.mergedCommit;
38080
38464
  if (!deliveredHead)
38081
38465
  throw new ContractError("quarantine");
38082
- await this.unchangedHead(this.cwd, deliveredHead);
38083
- if ((await gitText(this.cwd, ["symbolic-ref", "HEAD"])).trim() !== target2.branch)
38084
- throw new ContractError("stale");
38466
+ await assertTargetPosition(this.cwd, { head: deliveredHead, branch: target2.branch }, "after post-merge checks");
38085
38467
  delivery.view.postChecks = checked2 ? "passed" : "failed";
38086
38468
  this.save(live2);
38087
38469
  if (!checked2) {
@@ -38103,7 +38485,7 @@ ${result.output}`}`);
38103
38485
  });
38104
38486
  });
38105
38487
  }
38106
- async assertStartable(live2, p) {
38488
+ async assertStartable(live2, p, stage) {
38107
38489
  this.current();
38108
38490
  if (!live2.execution.model)
38109
38491
  throw new ContractError("stale");
@@ -38111,9 +38493,15 @@ ${result.output}`}`);
38111
38493
  if (p.epoch !== this.o.owner.lease.registration.epoch || p.cwd !== live2.execution.cwd)
38112
38494
  throw new ContractError("stale");
38113
38495
  const writes = workflowWrites(p.plan);
38114
- if (live2.target)
38115
- await assertTarget(this.cwd, live2.target, writes);
38116
- else if (await contentsIdentityAsync(this.cwd, writes) !== live2.declared)
38496
+ if (live2.target) {
38497
+ const { branch, head: base } = live2.target;
38498
+ const head = live2.delivery?.frontierHead() ?? base;
38499
+ await assertTarget(this.cwd, { branch, head }, writes, stage);
38500
+ if (base !== head) {
38501
+ await this.assertSiblingScope(branch, base, head, writes, stage);
38502
+ this.assertGuidance(live2);
38503
+ }
38504
+ } else if (await contentsIdentityAsync(this.cwd, writes) !== live2.declared)
38117
38505
  throw new WorkflowRefusal("stale", "Declared targets changed between approval and start; nothing was edited.");
38118
38506
  }
38119
38507
  async investigate(live2, request3) {
@@ -38208,7 +38596,7 @@ Read only. Cite paths and distinguish evidence, assumptions, user decisions and
38208
38596
  if (live2.run.diagnostics)
38209
38597
  live2.run.diagnostics.acquiredAt = Date.now();
38210
38598
  if (live2.proposal) {
38211
- await this.assertStartable(live2, live2.proposal);
38599
+ await this.assertStartable(live2, live2.proposal, "start preflight");
38212
38600
  let environmentFile;
38213
38601
  live2.environment = new RunEnvironment(this.o.coordination.stateHome, this.cwd, (directories) => {
38214
38602
  environmentFile = this.write(this.path(live2.run.id, "environment.json"), { directories }, environmentFile);
@@ -38218,8 +38606,6 @@ Read only. Cite paths and distinguish evidence, assumptions, user decisions and
38218
38606
  throw new ContractError("unavailable");
38219
38607
  });
38220
38608
  }
38221
- if (live2.run.delivery)
38222
- live2.delivery = new WorkflowDelivery(live2.run.delivery, new RepositoryCoordination(this.o.coordination, this.cwd, live2.run.epoch, live2.run.id, () => this.o.owner.lease.assert(), () => this.o.owner.quarantine()), () => this.save(live2));
38223
38609
  live2.run.status = "running";
38224
38610
  this.save(live2);
38225
38611
  if (request3.action === "research") {
@@ -38236,8 +38622,13 @@ Read only. Cite paths and distinguish evidence, assumptions, user decisions and
38236
38622
  } catch (error) {
38237
38623
  outcome = this.o.owner.state === "quarantined" ? "unknown" : live2.abort.signal.aborted ? "canceled" : error instanceof WorkflowFailure && error.outcome !== "completed" ? error.outcome : "failed";
38238
38624
  failure2 = this.describe(error);
38625
+ const integration = live2.run.delivery?.integration;
38626
+ if (error instanceof WorkflowRefusal && integration?.status === "pending") {
38627
+ integration.status = "blocked";
38628
+ integration.reason = this.notice(failure2);
38629
+ }
38239
38630
  } finally {
38240
- if (live2.delivery && this.o.owner.state === "idle") {
38631
+ if (live2.delivery && live2.environment && this.o.owner.state === "idle") {
38241
38632
  try {
38242
38633
  live2.delivery.finish();
38243
38634
  } catch {
@@ -38310,9 +38701,14 @@ class Workbench {
38310
38701
  opening = new Map;
38311
38702
  constructor(o) {
38312
38703
  this.o = o;
38313
- this.conversations = new Conversations(o);
38704
+ const { gate, ...common } = o;
38705
+ this.conversations = new Conversations(common);
38314
38706
  this.contexts = this.conversations.contexts;
38315
- this.workflows = new Workflows({ ...o, contexts: this.contexts });
38707
+ this.workflows = new Workflows({
38708
+ ...common,
38709
+ gate,
38710
+ contexts: this.contexts
38711
+ });
38316
38712
  this.files = new WorkbenchFiles(o.coordination.store.root, [o.coordination.files.namespace, o.agentDir], o.secrets);
38317
38713
  this.cadence = new ConversationWorkflow({
38318
38714
  ...o,
@@ -38742,7 +39138,7 @@ var processLifetime = {
38742
39138
  }
38743
39139
  };
38744
39140
  async function createServiceHost(value, sourceBuild, lifetime) {
38745
- const embedded = "1b833e54ac91fb9d8e570f43da35e3e2faf6c9e214bd9d1bd7cce19c2fe7f243";
39141
+ const embedded = "80875479add4b7830419060b7e5018a39de200665edfbdec20fc10d50861bfea";
38746
39142
  if (embedded && sourceBuild)
38747
39143
  throw new ContractError("unsupported-context");
38748
39144
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -38945,7 +39341,7 @@ async function createServiceHost(value, sourceBuild, lifetime) {
38945
39341
  authority: "local",
38946
39342
  csrf: null,
38947
39343
  capabilities: {
38948
- actions: !!workbench && !!choice.snapshot().selected,
39344
+ actions: ready2 && heldOwner.state === "idle" && !!workbench,
38949
39345
  manualChecks: false,
38950
39346
  history: true
38951
39347
  }