@abelxiaoxing/cadence 2.2.0 → 2.2.1

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.
@@ -5117,6 +5117,7 @@ var ASSET_MEMBER_BYTES = 16 * 1024 * 1024;
5117
5117
  var ASSET_TOTAL_BYTES = 64 * 1024 * 1024;
5118
5118
  var fixed = new Set([
5119
5119
  "index.html",
5120
+ "assets/start.js",
5120
5121
  "assets/cadence.js",
5121
5122
  "assets/cadence.css",
5122
5123
  "assets/react.js",
@@ -5127,6 +5128,7 @@ var fixed = new Set([
5127
5128
  "assets/vis-timeline.css"
5128
5129
  ]);
5129
5130
  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)$/;
5131
+ var webBuildBase = (buildId) => `/ui/${buildId}/`;
5130
5132
  function assetMime(name) {
5131
5133
  if (!fixed.has(name) && !font.test(name))
5132
5134
  throw new Error("asset-name-refused");
@@ -5227,7 +5229,7 @@ function loadWebAssets(directory = fileURLToPath(new URL("../web/dist/", import.
5227
5229
  if (!body || body.length !== a.bytes || createHash6("sha256").update(body).digest("hex") !== a.sha256)
5228
5230
  throw new Error("asset-body-refused");
5229
5231
  return {
5230
- path: a.name === "index.html" ? "/app" : `/${a.name}`,
5232
+ path: a.name === "index.html" ? "/app" : a.name === "assets/start.js" ? `/${a.name}` : `${webBuildBase(manifest.buildId)}${a.name}`,
5231
5233
  contentType: assetMime(a.name),
5232
5234
  bytes: body
5233
5235
  };
@@ -5326,141 +5328,6 @@ function validateImageBytes(bytes, mimeType) {
5326
5328
  return { width, height };
5327
5329
  }
5328
5330
 
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
5331
  // src/service/contracts/workflow.ts
5465
5332
  var WORKFLOW_LIMITS = {
5466
5333
  tasks: 16,
@@ -5592,8 +5459,8 @@ function workflowOrder(tasks) {
5592
5459
  }
5593
5460
  function workflowAncestors(tasks, id) {
5594
5461
  const needed = new Set;
5595
- const visit = (key2) => {
5596
- for (const dep of tasks.find((t) => t.id === key2)?.after ?? []) {
5462
+ const visit = (key) => {
5463
+ for (const dep of tasks.find((t) => t.id === key)?.after ?? []) {
5597
5464
  if (!needed.has(dep)) {
5598
5465
  needed.add(dep);
5599
5466
  visit(dep);
@@ -5772,9 +5639,9 @@ function workflowPlanInput(v) {
5772
5639
  return issue("plan", "must be an object");
5773
5640
  const completed = (source, defaults) => {
5774
5641
  const result = { ...defaults };
5775
- for (const [key2, value] of Object.entries(source))
5642
+ for (const [key, value] of Object.entries(source))
5776
5643
  if (value !== null && value !== undefined)
5777
- result[key2] = value;
5644
+ result[key] = value;
5778
5645
  return result;
5779
5646
  };
5780
5647
  const plan = completed(v, {
@@ -5796,7 +5663,7 @@ function workflowPlanInput(v) {
5796
5663
  function researchInput(v) {
5797
5664
  if (v === null || typeof v !== "object" || Array.isArray(v))
5798
5665
  return issue("request", "must be an object with a goal and questions");
5799
- const given = (key2) => Object.getOwnPropertyDescriptor(v, key2)?.value ?? undefined;
5666
+ const given = (key) => Object.getOwnPropertyDescriptor(v, key)?.value ?? undefined;
5800
5667
  const distinct = (name, value, maximum) => [
5801
5668
  ...new Set(entries(name, typeof value === "string" ? [value] : value, Number.MAX_SAFE_INTEGER, (entry, path) => words(path, entry, maximum).trim()).filter(Boolean))
5802
5669
  ];
@@ -6371,7 +6238,159 @@ function decodeWorkflowDiagnostics(v) {
6371
6238
  };
6372
6239
  }
6373
6240
 
6241
+ // src/service/contracts/design.ts
6242
+ var label = (v) => text(v, 1024, true);
6243
+ var key = (v, path = "id") => {
6244
+ const s = words(path, v, 48, true);
6245
+ if (!/^[a-z][a-z0-9-]*$/u.test(s))
6246
+ return issue(path, "start with a lowercase letter; use lowercase letters, digits and hyphens");
6247
+ return s;
6248
+ };
6249
+ function designQuestions(input, source) {
6250
+ const { questions } = fields2("design", input, ["questions"]);
6251
+ const seen = new Map;
6252
+ const rows = entries("questions", questions, 12, (raw, path) => {
6253
+ const q = fields2(path, raw, ["id", "question", "options", "recommended", "reason", "acceptance"], ["when"]);
6254
+ const id = key(q.id, `${path}.id`);
6255
+ if (seen.has(id))
6256
+ return issue(`${path}.id`, "use a distinct question ID");
6257
+ const ids = new Set;
6258
+ const options = entries(`${path}.options`, q.options, 6, (raw2, path2) => {
6259
+ const o = fields2(path2, raw2, ["id", "label", "cost"]);
6260
+ const id2 = key(o.id, `${path2}.id`);
6261
+ if (ids.has(id2))
6262
+ return issue(`${path2}.id`, "use a distinct option ID");
6263
+ ids.add(id2);
6264
+ return {
6265
+ id: id2,
6266
+ label: words(`${path2}.label`, o.label, 1024, true),
6267
+ cost: words(`${path2}.cost`, o.cost, 1024, true)
6268
+ };
6269
+ });
6270
+ if (options.length < 2)
6271
+ return issue(`${path}.options`, "supply at least two alternatives");
6272
+ const recommended = key(q.recommended, `${path}.recommended`);
6273
+ if (!ids.has(recommended))
6274
+ return issue(`${path}.recommended`, "name an option ID of this question");
6275
+ let when;
6276
+ if (q.when !== undefined && !(source === "tool" && q.when === null)) {
6277
+ const dep = fields2(`${path}.when`, q.when, ["question", "option"]);
6278
+ if (!(source === "tool" && dep.question === "" && dep.option === "")) {
6279
+ const question = key(dep.question, `${path}.when.question`);
6280
+ if (!seen.has(question))
6281
+ return issue(`${path}.when.question`, "name an earlier question, or omit when for an independent question");
6282
+ const option = key(dep.option, `${path}.when.option`);
6283
+ if (!seen.get(question)?.has(option))
6284
+ return issue(`${path}.when.option`, "name an option ID of the earlier question");
6285
+ when = { question, option };
6286
+ }
6287
+ }
6288
+ seen.set(id, ids);
6289
+ return {
6290
+ id,
6291
+ question: words(`${path}.question`, q.question, 1024, true),
6292
+ options,
6293
+ recommended,
6294
+ reason: words(`${path}.reason`, q.reason, 1024, true),
6295
+ acceptance: words(`${path}.acceptance`, q.acceptance, 1024, true),
6296
+ ...when ? { when } : {}
6297
+ };
6298
+ });
6299
+ if (!rows.length)
6300
+ throw new Error("questions: supply a material product decision");
6301
+ try {
6302
+ canonicalJson(rows, 24 * 1024);
6303
+ } catch (error) {
6304
+ if (!(error instanceof ContractError) || error.code !== "oversize")
6305
+ throw error;
6306
+ return issue("questions", "the complete batch must fit in 24 KiB of encoded JSON");
6307
+ }
6308
+ return rows;
6309
+ }
6310
+ function designAnswers(v) {
6311
+ return list(v, 12, (raw) => {
6312
+ const other = Object.hasOwn(raw ?? {}, "other");
6313
+ const a = closed(raw, ["question", other ? "other" : "option"]);
6314
+ const question = key(a.question);
6315
+ return other ? { question, other: label(a.other) } : { question, option: key(a.option) };
6316
+ });
6317
+ }
6318
+ function available(q, answers) {
6319
+ const dep = q.when;
6320
+ return !dep || answers.some((a) => a.question === dep.question && ("option" in a) && a.option === dep.option);
6321
+ }
6322
+ function selectDesign(questions, choices, fill = false) {
6323
+ const answers = [];
6324
+ const indexed = new Map(choices.map((a) => [a.question, a]));
6325
+ if (indexed.size !== choices.length || choices.some((a) => !questions.some((q) => q.id === a.question)))
6326
+ throw new ContractError("invalid");
6327
+ for (const q of questions) {
6328
+ if (!available(q, answers))
6329
+ continue;
6330
+ const a = indexed.get(q.id);
6331
+ if (a && "option" in a && !q.options.some((o) => o.id === a.option))
6332
+ throw new ContractError("invalid");
6333
+ if (a)
6334
+ answers.push(a);
6335
+ else if (fill)
6336
+ answers.push({ question: q.id, option: q.recommended });
6337
+ }
6338
+ return answers;
6339
+ }
6340
+ function decodeDesign(v) {
6341
+ const o = closed(v, ["id", "revision", "questions", "answers", "submitted"]);
6342
+ const questions = designQuestions({ questions: o.questions }, "record");
6343
+ const submitted = bool(o.submitted);
6344
+ const answers = designAnswers(o.answers);
6345
+ if (canonicalJson(selectDesign(questions, answers, submitted)) !== canonicalJson(answers))
6346
+ throw new ContractError("invalid");
6347
+ return {
6348
+ id: decodeId(o.id),
6349
+ revision: integer(o.revision, 1),
6350
+ questions,
6351
+ answers,
6352
+ submitted
6353
+ };
6354
+ }
6355
+ function newDesign(id, input, previous) {
6356
+ const questions = designQuestions(input, "tool");
6357
+ const retained = previous?.answers.filter((a) => {
6358
+ const before = previous.questions.find((q) => q.id === a.question);
6359
+ const after = questions.find((q) => q.id === a.question);
6360
+ return before && after && canonicalJson(before) === canonicalJson(after);
6361
+ }) ?? [];
6362
+ return {
6363
+ id,
6364
+ revision: 1,
6365
+ questions,
6366
+ answers: selectDesign(questions, retained),
6367
+ submitted: false
6368
+ };
6369
+ }
6370
+ function answerText(q, a) {
6371
+ return a && ("other" in a ? a.other : q.options.find((o) => o.id === a.option)?.label);
6372
+ }
6373
+ function designSummary(d) {
6374
+ return d.questions.filter((q) => available(q, d.answers)).map((q) => `- ${q.question} — ${answerText(q, d.answers.find((a) => a.question === q.id)) ?? "…"}
6375
+ Acceptance: ${q.acceptance}`).join(`
6376
+ `);
6377
+ }
6378
+ function designMessage(d, maximum) {
6379
+ const summary = designSummary(d);
6380
+ 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.`;
6381
+ }
6382
+ var recommendsDesign = (s) => /^(?:按你推荐的来|采用全部推荐|use (?:all |your )?recommendations)[。.!!]?$/iu.test(s.trim());
6383
+ function reviseDesign(d, answers, submit) {
6384
+ return {
6385
+ ...d,
6386
+ revision: d.revision + 1,
6387
+ answers: selectDesign(d.questions, answers, submit),
6388
+ submitted: submit
6389
+ };
6390
+ }
6391
+
6374
6392
  // src/service/contracts/workbench.ts
6393
+ var PROJECT_ASSOCIATION_HEADER = "x-cadence-project-association";
6375
6394
  function decodeCadenceConversation(v) {
6376
6395
  const degraded = v !== null && typeof v === "object" && Object.hasOwn(v, "notice");
6377
6396
  const o = closed(v, [
@@ -6434,6 +6453,17 @@ var RUN_INPUTS = 32;
6434
6453
  var WAITING_INPUTS = 8;
6435
6454
  var PENDING_TEXT_BYTES = 256;
6436
6455
  var UNDELIVERED_TEXT_BYTES = 2 * CONVERSATION_SEND_BYTES;
6456
+ var workflowTurnStatuses = [
6457
+ "queued",
6458
+ "running",
6459
+ "completed",
6460
+ "failed",
6461
+ "canceled",
6462
+ "timeout",
6463
+ "unknown"
6464
+ ];
6465
+ var CHAT_STATUSES = ["starting", ...workflowTurnStatuses];
6466
+ var isLiveChatStatus = (status) => status === "starting" || status === "queued" || status === "running";
6437
6467
  var TREE_NODES = 1000;
6438
6468
  var STEP_TEXT_BYTES = 16 * 1024;
6439
6469
  var TARGET_BYTES = 1024;
@@ -6492,15 +6522,6 @@ function decodeChatCursor(value) {
6492
6522
  const o = closed(value, ["id", "updatedAt"]);
6493
6523
  return { id: decodeSessionId(o.id), updatedAt: integer(o.updatedAt, 0) };
6494
6524
  }
6495
- var statuses = [
6496
- "queued",
6497
- "running",
6498
- "completed",
6499
- "failed",
6500
- "canceled",
6501
- "timeout",
6502
- "unknown"
6503
- ];
6504
6525
  function decodeWorkbenchRead(v) {
6505
6526
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
6506
6527
  switch (kind) {
@@ -6938,7 +6959,7 @@ function decodeChatTurn(v) {
6938
6959
  ...o.retry === undefined ? {} : { retry: decodeModelRetry(o.retry) },
6939
6960
  id: decodeId(o.id),
6940
6961
  epoch: decodeId(o.epoch),
6941
- status: oneOf(o.status, statuses),
6962
+ status: oneOf(o.status, workflowTurnStatuses),
6942
6963
  notice: text(o.notice, 1024),
6943
6964
  ...transcript ? { transcript: { pages: integer(transcript.pages, 0) } } : {},
6944
6965
  omitted: {
@@ -7099,7 +7120,7 @@ function decodeChatTurnHeader(v) {
7099
7120
  entry: nullable(o.entry, decodeEntryId),
7100
7121
  ...o.parent === undefined ? {} : { parent: nullable(o.parent, decodeEntryId) },
7101
7122
  at: integer(o.at, 0),
7102
- status: oneOf(o.status, statuses),
7123
+ status: oneOf(o.status, CHAT_STATUSES),
7103
7124
  notice: text(o.notice, 1024),
7104
7125
  omitted: {
7105
7126
  thinking: bool(omitted.thinking),
@@ -7130,7 +7151,7 @@ function decodeChatSummary(v) {
7130
7151
  id: decodeSessionId(o.id),
7131
7152
  title: text(o.title, 512, true),
7132
7153
  leaf: nullable(o.leaf, decodeEntryId),
7133
- status: oneOf(o.status, statuses),
7154
+ status: oneOf(o.status, CHAT_STATUSES),
7134
7155
  updatedAt: integer(o.updatedAt, 0),
7135
7156
  origin: oneOf(o.origin, ["terminal", "webui"]),
7136
7157
  ...has("cadence") ? { cadence: bool(o.cadence) } : {},
@@ -7148,7 +7169,7 @@ function decodeChatAttempt(v) {
7148
7169
  return {
7149
7170
  commandId: decodeId(o.commandId),
7150
7171
  text: text(o.text, 16 * 1024),
7151
- status: oneOf(o.status, statuses),
7172
+ status: oneOf(o.status, CHAT_STATUSES),
7152
7173
  notice: text(o.notice, 1024)
7153
7174
  };
7154
7175
  }
@@ -7512,6 +7533,17 @@ var pageReaders = [
7512
7533
  "changes",
7513
7534
  "reviews"
7514
7535
  ];
7536
+ var HISTORY_CSRF_HEADER = "x-cadence-history-csrf";
7537
+ var retainedReaders = [
7538
+ ...pageReaders,
7539
+ "entity",
7540
+ "graph",
7541
+ "detail",
7542
+ "search"
7543
+ ];
7544
+ function retainedHistoryBody(operation) {
7545
+ return retainedReaders.includes(operation);
7546
+ }
7515
7547
  function mutation(operation) {
7516
7548
  return [
7517
7549
  "preflight",
@@ -7631,16 +7663,12 @@ function decodeHttpOutput(operation, value) {
7631
7663
  }
7632
7664
  function readonlyBody(operation) {
7633
7665
  const operations = [
7634
- ...pageReaders,
7666
+ ...retainedReaders,
7635
7667
  "workbenchRead",
7636
7668
  "current",
7637
7669
  "currentChanges",
7638
7670
  "checkObligations",
7639
- "entity",
7640
- "graph",
7641
7671
  "snapshot",
7642
- "detail",
7643
- "search",
7644
7672
  "export",
7645
7673
  "download",
7646
7674
  "receipt"
@@ -7695,10 +7723,6 @@ function decodeSocketInput(value) {
7695
7723
  return { kind, scope: decodeScope(o.scope) };
7696
7724
  }
7697
7725
 
7698
- // src/service/activity-discovery.ts
7699
- import { hostname as hostname5 } from "node:os";
7700
- import { join as join9 } from "node:path";
7701
-
7702
7726
  // src/worker-redaction.mjs
7703
7727
  var marker = "[redacted]";
7704
7728
  var sensitive = /^(?:authorization|proxy-authorization|cookie|set-cookie|password|passwd|secret|token|api[-_]?key|access[-_]?token|refresh[-_]?token|credentials|headers|env)$/i;
@@ -8160,6 +8184,10 @@ class DetailSanitizer {
8160
8184
  }
8161
8185
  }
8162
8186
 
8187
+ // src/service/activity-discovery.ts
8188
+ import { hostname as hostname5 } from "node:os";
8189
+ import { join as join9 } from "node:path";
8190
+
8163
8191
  // src/service/activity-files.ts
8164
8192
  import { randomUUID as randomUUID3 } from "node:crypto";
8165
8193
  import { opendirSync as opendirSync2, renameSync as renameSync2 } from "node:fs";
@@ -8572,6 +8600,7 @@ class CheckoutStore {
8572
8600
  // src/service/contracts/activity.ts
8573
8601
  var ACTIVITY_PHASES = [
8574
8602
  "turn",
8603
+ "starting",
8575
8604
  "queued",
8576
8605
  "running",
8577
8606
  "research",
@@ -11127,18 +11156,41 @@ function requestBoundary(req, policy, directOrigin) {
11127
11156
  class HttpAuthentication {
11128
11157
  material;
11129
11158
  epoch;
11159
+ workspaceId;
11130
11160
  localCapability;
11131
- csrf = randomUUID7();
11161
+ executionCsrf = randomUUID7();
11162
+ get csrf() {
11163
+ return this.executionCsrf;
11164
+ }
11165
+ history;
11132
11166
  cookieName;
11133
11167
  constructor(material, epoch, workspaceId, localCapability) {
11134
11168
  this.material = material;
11135
11169
  this.epoch = epoch;
11170
+ this.workspaceId = workspaceId;
11136
11171
  this.localCapability = localCapability;
11137
11172
  decodeId(epoch);
11138
11173
  decodeId(workspaceId);
11139
11174
  if (!/^[A-Za-z0-9_-]{43}$/.test(localCapability))
11140
11175
  throw new ContractError("invalid");
11141
11176
  this.cookieName = `cadence_${workspaceId.replaceAll("-", "")}`;
11177
+ material.onRevoke(() => {
11178
+ this.history = undefined;
11179
+ this.executionCsrf = randomUUID7();
11180
+ });
11181
+ }
11182
+ historyChallenge(workspace) {
11183
+ if (workspace.workspaceId !== this.workspaceId || workspace.epoch !== this.epoch)
11184
+ throw new ContractError("stale");
11185
+ if (this.history?.storeId !== workspace.storeId)
11186
+ this.history = {
11187
+ storeId: decodeId(workspace.storeId),
11188
+ csrf: randomUUID7()
11189
+ };
11190
+ return this.history.csrf;
11191
+ }
11192
+ get historyStore() {
11193
+ return this.history?.storeId;
11142
11194
  }
11143
11195
  bootstrap(value, boundary) {
11144
11196
  this.material.assertCurrent();
@@ -11171,14 +11223,14 @@ class HttpAuthentication {
11171
11223
  }
11172
11224
  return false;
11173
11225
  }
11174
- authenticate(boundary, attachmentId, mutation2 = false, websocket = false) {
11226
+ authenticate(boundary, attachmentId, post = false, websocket = false) {
11175
11227
  this.material.assertCurrent();
11176
11228
  if (!this.material.available)
11177
11229
  throw new ContractError("quarantine");
11178
11230
  const h = boundary.headers;
11179
11231
  const local = h.get("x-cadence-local");
11180
11232
  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))
11233
+ 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
11234
  throw new ContractError("forbidden");
11183
11235
  } else {
11184
11236
  if (h.has("authorization") || h.has("x-cadence-token"))
@@ -11187,10 +11239,14 @@ class HttpAuthentication {
11187
11239
  throw new ContractError("unauthenticated");
11188
11240
  if (h.has("sec-fetch-site") && !["same-origin", "none"].includes(h.get("sec-fetch-site") ?? ""))
11189
11241
  throw new ContractError("forbidden");
11190
- if ((mutation2 || websocket) && h.get("origin") !== boundary.origin)
11242
+ if ((post || websocket) && h.get("origin") !== boundary.origin)
11191
11243
  throw new ContractError("forbidden");
11192
- if (mutation2 && h.get("x-cadence-csrf") !== this.csrf)
11244
+ if (post === "retained-history") {
11245
+ if (!this.history || h.get(HISTORY_CSRF_HEADER) !== this.history.csrf || h.has("x-cadence-attachment") || h.has("x-cadence-csrf"))
11246
+ throw new ContractError("forbidden");
11247
+ } else if (post && h.get("x-cadence-csrf") !== this.csrf) {
11193
11248
  throw new ContractError("forbidden");
11249
+ }
11194
11250
  }
11195
11251
  return {
11196
11252
  attachmentId: decodeId(attachmentId),
@@ -11249,27 +11305,24 @@ var styles = `
11249
11305
  :root {
11250
11306
  color-scheme: light dark;
11251
11307
  font-family:
11252
- Inter, Geist, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
11308
+ ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
11253
11309
  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));
11310
+ --page: light-dark(#f4f5f7, #090a0d);
11311
+ --text: light-dark(#111318, #f2f4f8);
11312
+ --muted: light-dark(#5e6675, #8a93a2);
11313
+ --glass: light-dark(rgba(255,255,255,.72), rgba(22,23,27,.9));
11314
+ --glass-line: light-dark(rgba(56,59,70,.16), rgba(208,214,227,.14));
11315
+ --rim: light-dark(#ffffff, #45464c);
11316
+ --field: light-dark(#f4f5f7, #101115);
11317
+ --field-line: light-dark(#777e89, #69707d);
11318
+ --primary-a: light-dark(#445065, #c0ccde);
11319
+ --primary-b: light-dark(#5c5069, #d1c6dc);
11320
+ --on-primary: light-dark(#ffffff, #141519);
11321
+ --focus: light-dark(#525964, #adb6c5);
11322
+ --glow: light-dark(rgba(62,65,80,.09), rgba(194,188,220,.05));
11323
+ --shadow: light-dark(rgba(31,32,39,.12), rgba(0,0,0,.46));
11324
+ --error: light-dark(#843f50, #e3a6ae);
11325
+ --error-bg: light-dark(#f8eaeb, #302125);
11273
11326
  }
11274
11327
  * {
11275
11328
  box-sizing: border-box;
@@ -11282,28 +11335,7 @@ body {
11282
11335
  place-items: center;
11283
11336
  padding: 28px 20px;
11284
11337
  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%);
11338
+ background: radial-gradient(ellipse at 50% 36%, var(--glow), transparent 46%), var(--page);
11307
11339
  }
11308
11340
  main {
11309
11341
  position: relative;
@@ -11312,7 +11344,8 @@ main {
11312
11344
  padding: 40px;
11313
11345
  overflow: hidden;
11314
11346
  border: 1px solid var(--glass-line);
11315
- border-radius: 28px;
11347
+ border-top-color: var(--rim);
11348
+ border-radius: 24px;
11316
11349
  background: var(--glass);
11317
11350
  box-shadow:
11318
11351
  0 28px 80px var(--shadow),
@@ -11321,7 +11354,7 @@ main {
11321
11354
  backdrop-filter: blur(24px) saturate(140%);
11322
11355
  -webkit-backdrop-filter: blur(24px) saturate(140%);
11323
11356
  text-align: center;
11324
- animation: arrive 0.45s ease-out both;
11357
+
11325
11358
  }
11326
11359
  main::before {
11327
11360
  content: "";
@@ -11393,13 +11426,15 @@ input[type="password"] {
11393
11426
  }
11394
11427
  input::placeholder {
11395
11428
  color: var(--muted);
11396
- font-family: Inter, Geist, ui-sans-serif, system-ui, sans-serif;
11429
+ font-family: ui-sans-serif, system-ui, sans-serif;
11397
11430
  letter-spacing: 0;
11398
11431
  }
11399
11432
  input:hover {
11400
11433
  border-color: var(--focus);
11401
11434
  }
11402
11435
  input:focus-visible {
11436
+ outline: 2px solid var(--focus);
11437
+ outline-offset: 2px;
11403
11438
  border-color: var(--focus);
11404
11439
  box-shadow: 0 0 0 4px var(--glow);
11405
11440
  }
@@ -11417,7 +11452,7 @@ button {
11417
11452
  border-radius: 14px;
11418
11453
  background: linear-gradient(135deg, var(--primary-a), var(--primary-b));
11419
11454
  color: var(--on-primary);
11420
- font: 600 14px Inter, Geist, ui-sans-serif, system-ui, sans-serif;
11455
+ font: 600 14px ui-sans-serif, system-ui, sans-serif;
11421
11456
  cursor: pointer;
11422
11457
  box-shadow: 0 10px 28px var(--glow);
11423
11458
  transition:
@@ -11446,7 +11481,7 @@ button:focus-visible {
11446
11481
  outline-offset: 4px;
11447
11482
  }
11448
11483
  .notice {
11449
- margin: 0 0 16px;
11484
+ margin: 16px 0;
11450
11485
  padding: 10px 12px;
11451
11486
  border: 1px solid var(--error);
11452
11487
  border-radius: 12px;
@@ -11467,12 +11502,6 @@ button:focus-visible {
11467
11502
  white-space: nowrap;
11468
11503
  border: 0;
11469
11504
  }
11470
- @keyframes arrive {
11471
- from {
11472
- opacity: 0;
11473
- transform: translateY(8px);
11474
- }
11475
- }
11476
11505
  @media (max-width: 420px) {
11477
11506
  body {
11478
11507
  padding: 18px 14px;
@@ -11491,11 +11520,12 @@ button:focus-visible {
11491
11520
  }
11492
11521
  }
11493
11522
  @media (forced-colors: active) {
11494
- body::before,
11495
- body::after,
11496
11523
  main::before {
11497
11524
  display: none;
11498
11525
  }
11526
+ body, main, .brand-mark, .notice { background:Canvas; color:CanvasText; box-shadow:none; backdrop-filter:none; }
11527
+ button { background:ButtonFace; color:ButtonText; }
11528
+ input[type="password"] { background:Field; color:FieldText; }
11499
11529
  main,
11500
11530
  input[type="password"],
11501
11531
  button,
@@ -11503,6 +11533,7 @@ button:focus-visible {
11503
11533
  .notice {
11504
11534
  border: 1px solid CanvasText;
11505
11535
  }
11536
+ :focus-visible { outline: 2px solid Highlight !important; outline-offset: 2px; }
11506
11537
  }
11507
11538
  `;
11508
11539
  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 +11553,7 @@ function renderAuthPage(options) {
11522
11553
  <body>
11523
11554
  <main aria-labelledby="welcome">
11524
11555
  <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>
11556
+ <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
11557
  <h1 id="welcome">Cadence</h1>
11527
11558
  </div>
11528
11559
  ${options.authError ? '<p id="auth-notice" class="notice" role="alert">Invalid access token.</p>' : ""}
@@ -11925,6 +11956,7 @@ function decodeMaintenanceJob(value) {
11925
11956
  function canUpgrade(route) {
11926
11957
  return route === "npm" || route === "bun" || route === "pi-npm" || route === "pi-bun" || route === "npm-local" || route === "bun-local";
11927
11958
  }
11959
+ var MAINTENANCE_WORK_LIMIT = 256;
11928
11960
 
11929
11961
  // src/service/doctor.ts
11930
11962
  import { createInterface } from "node:readline";
@@ -14747,7 +14779,7 @@ class MaintenanceRecord {
14747
14779
  this.write({ ...job2, state, reason, version, endedAt: Date.now() });
14748
14780
  }
14749
14781
  }
14750
- function launchJob(s, job2) {
14782
+ function launchJob(s, job2, confirmedWork) {
14751
14783
  const text2 = generatedUnit(s);
14752
14784
  if (typeof text2 !== "string")
14753
14785
  return false;
@@ -14770,7 +14802,9 @@ function launchJob(s, job2) {
14770
14802
  ...name ? ["--name", name] : [],
14771
14803
  ...job2.to ? ["--to", job2.to] : [],
14772
14804
  "--job",
14773
- job2.id
14805
+ job2.id,
14806
+ "--confirmed-work",
14807
+ confirmedWork
14774
14808
  ], { stdio: "ignore", timeout: 20000 });
14775
14809
  return !result.error && result.status === 0;
14776
14810
  }
@@ -14910,10 +14944,10 @@ async function serviceStatus(c, diagnose = false) {
14910
14944
  };
14911
14945
  }
14912
14946
  }
14913
- async function stopService(c) {
14947
+ async function stopService(c, confirmedWork) {
14914
14948
  let epoch;
14915
14949
  try {
14916
- const reply = closed(await nativeCall(c, "stop"), ["status", "epoch"]);
14950
+ const reply = closed(await nativeCall(c, "stop", false, confirmedWork ? { confirmedWork } : undefined), ["status", "epoch"]);
14917
14951
  if (reply.status !== "accepted")
14918
14952
  throw new ContractError("unavailable");
14919
14953
  epoch = decodeId(reply.epoch);
@@ -15300,9 +15334,8 @@ var INTERRUPTED = "Interrupted: Cadence stopped before this reply finished. Noth
15300
15334
  var NOT_DELIVERED = "Not delivered: the reply ended before this message reached the model. Nothing was replayed; send it again.";
15301
15335
  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
15336
  var WITHDRAWN = "Withdrawn before it was delivered.";
15303
- var LIVE = ["queued", "running"];
15304
15337
  function settledSteps(turn) {
15305
- if (LIVE.includes(turn.status) || !turn.items.some((item) => ["pending", "running", "streaming"].includes(item.state ?? "")))
15338
+ if (isLiveChatStatus(turn.status) || !turn.items.some((item) => ["pending", "running", "streaming"].includes(item.state ?? "")))
15306
15339
  return turn;
15307
15340
  return {
15308
15341
  ...turn,
@@ -15361,20 +15394,11 @@ function decodeAccepted(value) {
15361
15394
  offset: integer(o.offset, 0)
15362
15395
  };
15363
15396
  }
15364
- var statuses2 = [
15365
- "queued",
15366
- "running",
15367
- "completed",
15368
- "failed",
15369
- "canceled",
15370
- "timeout",
15371
- "unknown"
15372
- ];
15373
15397
  function decodeState(value) {
15374
15398
  const o = closed(value, ["status", "notice", "omitted", "user"]);
15375
15399
  const omitted = closed(o.omitted, ["thinking", "media", "other"]);
15376
15400
  return {
15377
- status: oneOf(o.status, statuses2),
15401
+ status: oneOf(o.status, CHAT_STATUSES),
15378
15402
  notice: text(o.notice, 4096),
15379
15403
  omitted: {
15380
15404
  thinking: omitted.thinking === true,
@@ -15458,7 +15482,7 @@ class ConversationRecords {
15458
15482
  if (value === undefined)
15459
15483
  throw new ContractError("corrupt-selected");
15460
15484
  const decoded2 = decodeState(value);
15461
- const state = LIVE.includes(decoded2.status) ? { ...decoded2, status: "unknown", notice: INTERRUPTED } : decoded2;
15485
+ const state = isLiveChatStatus(decoded2.status) ? { ...decoded2, status: "unknown", notice: INTERRUPTED } : decoded2;
15462
15486
  if (this.states.size >= COMMAND_STATES)
15463
15487
  this.states.clear();
15464
15488
  this.states.set(commandId, { key: key2, state });
@@ -15593,7 +15617,10 @@ class ConversationRecords {
15593
15617
  const run = this.recordedRun(id);
15594
15618
  return run ? {
15595
15619
  commandId: run.commandId,
15596
- settled: ![run, ...run.inputs].some((message2) => ["queued", "running", "unknown"].includes(this.state(message2.commandId).status))
15620
+ settled: ![run, ...run.inputs].some((message2) => {
15621
+ const { status } = this.state(message2.commandId);
15622
+ return status === "unknown" || isLiveChatStatus(status);
15623
+ })
15597
15624
  } : null;
15598
15625
  }
15599
15626
  summary(id, live2, archived = this.archived(id)) {
@@ -15946,7 +15973,7 @@ class ConversationRecords {
15946
15973
  });
15947
15974
  return {
15948
15975
  turn: { ...settledSteps(turn), execution: live2.execution },
15949
- stable: LIVE.includes(live2.state.status) ? extended.stable : turn.steps.length
15976
+ stable: isLiveChatStatus(live2.state.status) ? extended.stable : turn.steps.length
15950
15977
  };
15951
15978
  }
15952
15979
  turnSteps(id, leaf, ordinal, before) {
@@ -16780,7 +16807,7 @@ class ServiceHttpServer {
16780
16807
  let total = 0;
16781
16808
  for (const asset of options.assets ?? []) {
16782
16809
  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)
16810
+ 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
16811
  throw new ContractError("invalid");
16785
16812
  this.assets.set(asset.path, {
16786
16813
  ...asset,
@@ -17062,7 +17089,10 @@ Content-Length: 0\r
17062
17089
  unavailable();
17063
17090
  const route = readRoute(target, req.method ?? "");
17064
17091
  const attachmentId = boundary.headers.get("x-cadence-attachment") ?? randomUUID13();
17065
- const caller = this.options.auth.authenticate(boundary, attachmentId, route?.source === "body");
17092
+ const historyBody = route?.source === "body" && retainedHistoryBody(route.operation) && boundary.headers.has(HISTORY_CSRF_HEADER);
17093
+ const caller = this.options.auth.authenticate(boundary, attachmentId, historyBody ? "retained-history" : route?.source === "body");
17094
+ if (boundary.headers.has(HISTORY_CSRF_HEADER) && !historyBody)
17095
+ throw new ContractError("forbidden");
17066
17096
  if (!route || !mutation(route.operation)) {
17067
17097
  if (this.reads >= 32)
17068
17098
  throw new ContractError("capacity");
@@ -17076,6 +17106,8 @@ Content-Length: 0\r
17076
17106
  throw new ContractError("invalid");
17077
17107
  this.options.auth.current(caller);
17078
17108
  res.setHeader("Content-Type", asset.contentType);
17109
+ if (target === "/app" && this.options.build)
17110
+ res.setHeader("X-Cadence-Web-Build", this.options.build.assets.buildId);
17079
17111
  if (target !== "/app") {
17080
17112
  res.setHeader("Cache-Control", "private, no-cache");
17081
17113
  res.setHeader("ETag", asset.etag);
@@ -17104,12 +17136,14 @@ Content-Length: 0\r
17104
17136
  this.attachments.set(attachmentId, attachment);
17105
17137
  }
17106
17138
  res.setHeader("X-Cadence-Attachment", attachmentId);
17107
- } else if (route.source === "body" && (route.operation !== "detach" || this.attachments.has(attachmentId)))
17139
+ } else if (route.source === "body" && !historyBody && (route.operation !== "detach" || this.attachments.has(attachmentId)))
17108
17140
  attachment = this.attachment(caller);
17109
17141
  const input = route.source === "body" ? await this.body(req, abort.signal) : route.input === null ? null : parseWireJson(route.input);
17110
17142
  if (route.source !== "body" && (req.headers["content-encoding"] !== undefined || req.headers["transfer-encoding"] || req.headers["content-length"] && req.headers["content-length"] !== "0"))
17111
17143
  throw new ContractError("invalid");
17112
- decodeHttpInput(route.operation, input);
17144
+ const decodedInput = decodeHttpInput(route.operation, input);
17145
+ if (historyBody && (!decodedInput || typeof decodedInput !== "object" || !("storeId" in decodedInput) || decodedInput.storeId !== this.options.auth.historyStore))
17146
+ throw new ContractError("stale");
17113
17147
  this.options.auth.current(caller);
17114
17148
  if (abort.signal.aborted || !this.accepting)
17115
17149
  unavailable();
@@ -17126,7 +17160,14 @@ Content-Length: 0\r
17126
17160
  unavailable();
17127
17161
  if (route.operation === "session")
17128
17162
  this.attachment(caller);
17129
- const decoded2 = decodeHttpOutput(route.operation, value);
17163
+ let decoded2;
17164
+ if (route.operation === "workspace" && caller.authority === "browser") {
17165
+ const workspace = decodeReply(value, decodeWorkspaceBootstrap);
17166
+ if (workspace.kind === "ok")
17167
+ res.setHeader(HISTORY_CSRF_HEADER, this.options.auth.historyChallenge(workspace.value));
17168
+ decoded2 = workspace;
17169
+ } else
17170
+ decoded2 = decodeHttpOutput(route.operation, value);
17130
17171
  const status = value && typeof value === "object" && "kind" in value && value.kind === "error" && "error" in value ? errorStatus(decodePublicError(value.error).code) : 200;
17131
17172
  const compressible = route.operation === "workbenchRead";
17132
17173
  if (compressible)
@@ -17462,6 +17503,7 @@ Content-Length: 0\r
17462
17503
  sentBytes: 0,
17463
17504
  sentMessages: 0,
17464
17505
  reading: false,
17506
+ resyncPending: false,
17465
17507
  closed: false,
17466
17508
  lastPing: Date.now(),
17467
17509
  lastReconcile: Date.now()
@@ -17482,10 +17524,12 @@ Content-Length: 0\r
17482
17524
  viewer.lastPing = Date.now();
17483
17525
  if (command.kind === "ping")
17484
17526
  this.heartbeatViewer(viewer);
17485
- else if (viewer.reading)
17486
- this.closeViewer(viewer);
17487
- else
17527
+ else if (!viewer.reading)
17488
17528
  this.subscribe(viewer, command.scope);
17529
+ else if (command.kind === "resync" && viewer.scope?.kind === command.scope.kind && viewer.scope.id === command.scope.id)
17530
+ viewer.resyncPending = true;
17531
+ else
17532
+ this.closeViewer(viewer);
17489
17533
  } catch {
17490
17534
  this.closeViewer(viewer);
17491
17535
  }
@@ -17568,23 +17612,26 @@ Content-Length: 0\r
17568
17612
  viewer.unsubscribe();
17569
17613
  return;
17570
17614
  }
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);
17615
+ do {
17616
+ viewer.resyncPending = false;
17617
+ const snapshot = decodeSnapshot(await p.snapshot(scope));
17585
17618
  if (viewer.closed || viewer.subscription !== generation)
17586
- break;
17587
- }
17619
+ return;
17620
+ this.attachment(viewer.attachment.caller);
17621
+ if (snapshot.epoch !== this.options.auth.epoch || canonicalJson(snapshot.scope) !== canonicalJson(scope))
17622
+ throw new ContractError("stale");
17623
+ viewer.snapshot = snapshot;
17624
+ if (!this.sendViewer(viewer, { kind: "snapshot", snapshot }))
17625
+ return;
17626
+ viewer.lastReconcile = Date.now();
17627
+ for (const event of viewer.pending.splice(0)) {
17628
+ viewer.bytes -= Buffer.byteLength(canonicalJson(event));
17629
+ if (!this.deliver(viewer, event)) {
17630
+ viewer.bytes = 0;
17631
+ break;
17632
+ }
17633
+ }
17634
+ } while (!viewer.closed && viewer.resyncPending);
17588
17635
  } catch {
17589
17636
  this.closeViewer(viewer);
17590
17637
  } finally {
@@ -17596,26 +17643,30 @@ Content-Length: 0\r
17596
17643
  deliver(viewer, event) {
17597
17644
  const snapshot = viewer.snapshot;
17598
17645
  if (!snapshot || viewer.closed)
17599
- return;
17646
+ return false;
17600
17647
  if (event.epoch !== snapshot.epoch || event.storeId !== snapshot.storeId || canonicalJson(event.scope) !== canonicalJson(snapshot.scope)) {
17601
17648
  this.resync(viewer);
17602
- return;
17649
+ return false;
17603
17650
  }
17604
17651
  const cmp = compareSequence(event.committedSeq, snapshot.committedSeq);
17605
17652
  if (cmp < 0 || cmp === 0 && event.kind !== "heartbeat")
17606
- return;
17653
+ return true;
17607
17654
  if (event.kind === "update" && event.previousSeq !== snapshot.committedSeq || event.kind === "heartbeat" && cmp > 0) {
17608
17655
  this.resync(viewer);
17609
- return;
17656
+ return false;
17610
17657
  }
17611
- if (this.sendViewer(viewer, { kind: "event", event }))
17612
- snapshot.committedSeq = event.committedSeq;
17658
+ if (!this.sendViewer(viewer, { kind: "event", event }))
17659
+ return false;
17660
+ snapshot.committedSeq = event.committedSeq;
17661
+ return true;
17613
17662
  }
17614
17663
  resync(viewer) {
17615
- if (!viewer.reading && viewer.scope) {
17616
- this.sendViewer(viewer, { kind: "resync" });
17664
+ if (!viewer.scope || !this.sendViewer(viewer, { kind: "resync" }))
17665
+ return;
17666
+ if (viewer.reading)
17667
+ viewer.resyncPending = true;
17668
+ else
17617
17669
  this.subscribe(viewer, viewer.scope);
17618
- }
17619
17670
  }
17620
17671
  heartbeatViewer(viewer) {
17621
17672
  if (!viewer.scope || viewer.reading)
@@ -17633,7 +17684,7 @@ Content-Length: 0\r
17633
17684
  for (const viewer of this.viewers) {
17634
17685
  if (Date.now() - viewer.lastPing >= LIMITS.staleMs)
17635
17686
  this.closeViewer(viewer);
17636
- else if (Date.now() - viewer.lastReconcile >= LIMITS.reconcileMs)
17687
+ else if (!viewer.reading && Date.now() - viewer.lastReconcile >= LIMITS.reconcileMs)
17637
17688
  this.resync(viewer);
17638
17689
  else
17639
17690
  this.heartbeatViewer(viewer);
@@ -17823,6 +17874,10 @@ class ModelPreviewProcesses {
17823
17874
  }
17824
17875
 
17825
17876
  // src/service/gateway.ts
17877
+ function maintenanceWorkDigest(gatewayEpoch, work) {
17878
+ const keys2 = work.map((identity) => canonicalJson(identity)).sort();
17879
+ return hash(canonicalJson([gatewayEpoch, keys2]));
17880
+ }
17826
17881
  async function joinProjectStops(projects, stopProject) {
17827
17882
  const unconfirmed = [];
17828
17883
  const seen = new Set;
@@ -17843,7 +17898,7 @@ async function createGateway(value, hostUrl, source) {
17843
17898
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
17844
17899
  const web = loadWebAssets(source?.webDirectory);
17845
17900
  const build2 = {
17846
- contractHash: "1b833e54ac91fb9d8e570f43da35e3e2faf6c9e214bd9d1bd7cce19c2fe7f243",
17901
+ contractHash: "190a21e723f753a233225a9f4bcf12a99d71b294a58728961846cd110cd60a17",
17847
17902
  assets: {
17848
17903
  sourceHash: web.manifest.sourceHash,
17849
17904
  contractHash: web.manifest.contractHash,
@@ -17918,8 +17973,11 @@ Content-Length: 0\r
17918
17973
  conversations.close();
17919
17974
  const grouped = new Map;
17920
17975
  for (const [id, target2] of attachments) {
17921
- const key2 = `${target2.projectId}:${target2.epoch}`;
17922
- const group = grouped.get(key2) ?? { ...target2, ids: [] };
17976
+ if (target2.rejected)
17977
+ continue;
17978
+ const projectId = target2.project.id, epoch = target2.project.epoch;
17979
+ const key2 = `${projectId}:${epoch}`;
17980
+ const group = grouped.get(key2) ?? { projectId, epoch, ids: [] };
17923
17981
  group.ids.push(id);
17924
17982
  grouped.set(key2, group);
17925
17983
  }
@@ -17989,17 +18047,53 @@ Content-Length: 0\r
17989
18047
  const commands = packageCommands(packageSystem);
17990
18048
  let route, requesting = false;
17991
18049
  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);
18050
+ if (preparing)
18051
+ throw new ContractError("unavailable");
18052
+ const targets = () => [
18053
+ ...new Map(store.associatedProjects().map((p) => [canonicalJson([p.path, p.epoch]), p])).entries()
18054
+ ].sort(([a], [b]) => a < b ? -1 : a === b ? 0 : 1);
18055
+ const selected2 = targets();
18056
+ const secrets = acquired.access.redactionLiterals();
18057
+ const work = await Promise.all(selected2.map(async ([, p]) => {
18058
+ const c = new ServiceCoordination(p.path, input.stateHome);
18059
+ if (c.store.root !== p.path)
18060
+ throw new ContractError("stale");
18061
+ const observed = c.inspect();
18062
+ if (observed.status === "stopped" || observed.status === "absent")
18063
+ return [];
18064
+ const epoch = c.localAccess().epoch;
18065
+ if (epoch !== p.epoch)
18066
+ return [];
18067
+ const summary = decodeOwnerActivity(await nativeCall(c, "activity"));
18068
+ if (!summary.complete || summary.epoch !== epoch || c.localAccess().epoch !== epoch)
18069
+ throw new ContractError("unavailable");
18070
+ const project = sanitizeText(p.path, secrets).replace(/[\p{Cc}\p{Cf}]/gu, " ");
18071
+ return summary.activities.map((item) => {
18072
+ if (item.epoch !== epoch || item.source === "terminal")
18073
+ throw new ContractError("unavailable");
18074
+ return {
18075
+ key: [p.path, epoch, item.source, item.id],
18076
+ item: {
18077
+ project,
18078
+ id: item.id,
18079
+ source: item.source,
18080
+ sessionId: item.sessionId
18081
+ }
18082
+ };
18083
+ });
18084
+ })).then((lists) => lists.flat());
18085
+ if (preparing || canonicalJson(targets().map(([key2]) => key2)) !== canonicalJson(selected2.map(([key2]) => key2)) || work.length > MAINTENANCE_WORK_LIMIT)
18086
+ throw new ContractError("unavailable");
18087
+ const confirmed = {
18088
+ digest: maintenanceWorkDigest(auth.epoch, work.map(({ key: key2 }) => key2)),
18089
+ items: work.map(({ item }) => item)
18090
+ };
18091
+ canonicalJson(confirmed, LIMITS.controlBytes - 4096);
18092
+ return confirmed;
18093
+ }
18094
+ async function assertConfirmedWork(digest) {
18095
+ if ((await associatedWork()).digest !== digest)
18096
+ throw new ContractError("stale");
18003
18097
  }
18004
18098
  function latestJob() {
18005
18099
  const job2 = record3.read();
@@ -18012,13 +18106,13 @@ Content-Length: 0\r
18012
18106
  version,
18013
18107
  unit: managed ? { name: managed.unit, scope: managed.scope ?? "user" } : null,
18014
18108
  upgrade: await route,
18015
- work: await associatedWork(),
18109
+ work: managed ? await associatedWork().catch(() => null) : null,
18016
18110
  job: latestJob()
18017
18111
  };
18018
18112
  }
18019
18113
  async function requestJob(value2, current) {
18020
18114
  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);
18115
+ const action = oneOf(o.action, MAINTENANCE_ACTIONS), to = o.to === null ? null : decodeVersion(o.to), work = decodeHash(o.work);
18022
18116
  if (action === "upgrade" !== (to !== null))
18023
18117
  throw new ContractError("invalid");
18024
18118
  if (decodeId(o.epoch) !== auth.epoch || decodeVersion(o.from) !== version)
@@ -18032,8 +18126,7 @@ Content-Length: 0\r
18032
18126
  throw new ContractError("conflict");
18033
18127
  requesting = true;
18034
18128
  try {
18035
- if (await associatedWork() !== integer(o.work, 0, 1e6))
18036
- throw new ContractError("stale");
18129
+ await assertConfirmedWork(work);
18037
18130
  current();
18038
18131
  assert();
18039
18132
  const job2 = {
@@ -18048,7 +18141,7 @@ Content-Length: 0\r
18048
18141
  endedAt: null
18049
18142
  };
18050
18143
  record3.write(job2);
18051
- if (!launchJob(managed, job2)) {
18144
+ if (!launchJob(managed, job2, work)) {
18052
18145
  record3.finish(job2.id, "failed", "refused", version);
18053
18146
  throw new ContractError("unavailable");
18054
18147
  }
@@ -18176,7 +18269,10 @@ Content-Length: 0\r
18176
18269
  });
18177
18270
  return result;
18178
18271
  }
18179
- function binding(id) {
18272
+ function isAssociated(id) {
18273
+ return store.associatedProjects().some((project) => project.id === id);
18274
+ }
18275
+ function binding(id, allowBootstrap = true) {
18180
18276
  let project = store.projects().find((p) => p.id === id);
18181
18277
  if (!project)
18182
18278
  throw new ContractError("unavailable");
@@ -18185,12 +18281,14 @@ Content-Length: 0\r
18185
18281
  throw new ContractError("stale");
18186
18282
  if (local.epoch !== project.epoch) {
18187
18283
  project = { ...project, epoch: local.epoch };
18188
- if (store.associatedProjects().some((p) => p.id === id))
18284
+ if (isAssociated(id))
18189
18285
  store.saveProject(project);
18190
18286
  }
18191
18287
  const previous = bindings.get(id);
18192
18288
  if (previous?.epoch === local.epoch)
18193
18289
  return previous.result;
18290
+ if (!allowBootstrap)
18291
+ throw new ContractError("stale");
18194
18292
  const result = (async () => {
18195
18293
  const raw = closed(await nativeCall(c, "token-link", true), ["link"]), link = new URL(text(raw.link, 4096, true));
18196
18294
  const secret = link.searchParams.get("token");
@@ -18211,7 +18309,11 @@ Content-Length: 0\r
18211
18309
  });
18212
18310
  if (c.localAccess().epoch !== project.epoch)
18213
18311
  throw new ContractError("stale");
18214
- return { project, endpoint: local.endpoint, cookie };
18312
+ return {
18313
+ project: { ...project, epoch: local.epoch },
18314
+ endpoint: local.endpoint,
18315
+ cookie
18316
+ };
18215
18317
  })();
18216
18318
  const pending2 = { epoch: local.epoch, result };
18217
18319
  bindings.set(id, pending2);
@@ -18221,6 +18323,16 @@ Content-Length: 0\r
18221
18323
  });
18222
18324
  return result;
18223
18325
  }
18326
+ function rejectBinding(b, original) {
18327
+ b.rejected = true;
18328
+ if (bindings.get(b.project.id)?.result !== original)
18329
+ return;
18330
+ bindings.delete(b.project.id);
18331
+ for (const viewer of attachments.values()) {
18332
+ if (viewer.project.id === b.project.id && viewer.project.epoch === b.project.epoch && viewer.cookie === b.cookie)
18333
+ viewer.rejected = true;
18334
+ }
18335
+ }
18224
18336
  function stop() {
18225
18337
  if (stopping)
18226
18338
  return;
@@ -18416,8 +18528,14 @@ Content-Length: 0\r
18416
18528
  });
18417
18529
  return;
18418
18530
  }
18419
- closed(value2, []);
18420
18531
  if (operation === "stop") {
18532
+ if (value2 && typeof value2 === "object" && Object.hasOwn(value2, "confirmedWork")) {
18533
+ const { confirmedWork } = closed(value2, ["confirmedWork"]);
18534
+ await assertConfirmedWork(decodeHash(confirmedWork));
18535
+ auth.current(caller2);
18536
+ assert();
18537
+ } else
18538
+ closed(value2, []);
18421
18539
  reply(res, 200, {
18422
18540
  kind: "ok",
18423
18541
  value: { status: "accepted", epoch: auth.epoch }
@@ -18425,6 +18543,7 @@ Content-Length: 0\r
18425
18543
  stop();
18426
18544
  return;
18427
18545
  }
18546
+ closed(value2, []);
18428
18547
  if (operation === "token-rotate") {
18429
18548
  acquired.access.rotate();
18430
18549
  await Promise.all([...retirements]);
@@ -18447,6 +18566,10 @@ Content-Length: 0\r
18447
18566
  throw new ContractError("invalid");
18448
18567
  if (req.headers["content-encoding"] || req.headers["transfer-encoding"] || Number(req.headers["content-length"] ?? 0) > LIMITS.controlBytes)
18449
18568
  throw new ContractError("oversize");
18569
+ const attachment = boundary.headers.get("x-cadence-attachment");
18570
+ const historyCsrf = boundary.headers.get(HISTORY_CSRF_HEADER);
18571
+ if (historyCsrf !== undefined && (route2.source !== "body" || !retainedHistoryBody(route2.operation) || attachment !== undefined || boundary.headers.has("x-cadence-csrf")))
18572
+ throw new ContractError("forbidden");
18450
18573
  if (route2.operation === "workbenchRead" && req.method === "GET") {
18451
18574
  const selected2 = store.projects().find((p) => p.id === project.id);
18452
18575
  if (!selected2)
@@ -18462,22 +18585,26 @@ Content-Length: 0\r
18462
18585
  return;
18463
18586
  }
18464
18587
  }
18465
- if (route2.operation === "session" && !store.associatedProjects().some((p) => p.id === project.id))
18588
+ if (route2.operation === "session" && !isAssociated(project.id))
18466
18589
  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)
18590
+ if (attachment && (attachments.has(attachment) ? attachments.get(attachment)?.project.id !== project.id : route2.operation !== "session") || req.method === "POST" && !attachment && historyCsrf === undefined)
18469
18591
  throw new ContractError("stale");
18470
- if (route2.operation === "session" && (!attachment || !attachments.has(attachment)) && attachments.size >= 2048)
18471
- throw new ContractError("capacity");
18592
+ if (route2.operation === "session" && (!attachment || !attachments.has(attachment)) && attachments.size >= 2048) {
18593
+ for (const [id, previous] of attachments)
18594
+ if (previous.rejected)
18595
+ attachments.delete(id);
18596
+ if (attachments.size >= 2048)
18597
+ throw new ContractError("capacity");
18598
+ }
18472
18599
  if (req.method === "POST" && boundary.headers.get("origin") !== boundary.origin)
18473
18600
  throw new ContractError("forbidden");
18474
18601
  const attached = attachment ? attachments.get(attachment) : undefined;
18475
- if (route2.operation === "detach" && attachment && attached) {
18602
+ if (route2.operation === "detach" && attachment && attached && !attached.rejected) {
18476
18603
  const selected2 = store.projects().find((p) => p.id === project.id);
18477
18604
  if (!selected2)
18478
18605
  throw new ContractError("unavailable");
18479
18606
  const observed = new ServiceCoordination(selected2.path, input.stateHome).inspect();
18480
- if (observed.status === "stopped" && observed.epoch === attached.epoch) {
18607
+ if (observed.status === "stopped" && observed.epoch === attached.project.epoch) {
18481
18608
  auth.current(caller);
18482
18609
  assert();
18483
18610
  attachments.delete(attachment);
@@ -18492,10 +18619,31 @@ Content-Length: 0\r
18492
18619
  throw new ContractError("forbidden");
18493
18620
  commandBody = canonicalJson(command, LIMITS.controlBytes);
18494
18621
  }
18495
- const b = await binding(project.id);
18622
+ auth.current(caller);
18623
+ if (attached?.rejected) {
18624
+ if (attachment && route2.operation === "detach")
18625
+ attachments.delete(attachment);
18626
+ reply(res, 401, {
18627
+ kind: "error",
18628
+ error: publicError("unauthenticated")
18629
+ });
18630
+ return;
18631
+ }
18632
+ const original = binding(project.id, historyCsrf === undefined);
18633
+ const b = await original;
18496
18634
  auth.current(caller);
18497
18635
  assert();
18498
- if (attachment && attached && attached.epoch !== b.project.epoch) {
18636
+ if (bindings.get(project.id)?.result !== original)
18637
+ throw new ContractError("stale");
18638
+ if (attachment && attached && attached.project.epoch === b.project.epoch && attached.cookie !== b.cookie) {
18639
+ attached.rejected = true;
18640
+ reply(res, 401, {
18641
+ kind: "error",
18642
+ error: publicError("unauthenticated")
18643
+ });
18644
+ return;
18645
+ }
18646
+ if (attachment && attached && attached.project.epoch !== b.project.epoch) {
18499
18647
  attachments.delete(attachment);
18500
18648
  reply(res, route2.operation === "detach" ? 200 : 409, route2.operation === "detach" ? { kind: "ok", value: null } : {
18501
18649
  kind: "error",
@@ -18507,6 +18655,11 @@ Content-Length: 0\r
18507
18655
  Cookie: b.cookie,
18508
18656
  Origin: b.endpoint
18509
18657
  };
18658
+ if (historyCsrf !== undefined) {
18659
+ if (!b.history || b.history.browser !== historyCsrf)
18660
+ throw new ContractError("forbidden");
18661
+ headers2[HISTORY_CSRF_HEADER] = b.history.owner;
18662
+ }
18510
18663
  for (const key2 of [
18511
18664
  "accept-encoding",
18512
18665
  "content-type",
@@ -18525,19 +18678,35 @@ Content-Length: 0\r
18525
18678
  const upstream = request2(`${b.endpoint}${project.tail}`, { method: req.method, headers: headers2, agent: false }, (incoming) => {
18526
18679
  try {
18527
18680
  auth.current(caller);
18681
+ if (incoming.statusCode === 401) {
18682
+ const cookieName = b.cookie.split("=", 1)[0];
18683
+ if (incoming.headers["set-cookie"]?.some((line) => {
18684
+ const [cookie, ...attributes] = line.split(/;\s*/);
18685
+ return cookie === `${cookieName}=` && attributes.includes("Max-Age=0");
18686
+ }))
18687
+ rejectBinding(b, original);
18688
+ } else if (bindings.get(project.id)?.result !== original) {
18689
+ throw new ContractError("stale");
18690
+ }
18691
+ if (route2.operation === "workspace" && incoming.statusCode === 200 && incoming.headers[HISTORY_CSRF_HEADER] !== undefined) {
18692
+ const owner = decodeId(incoming.headers[HISTORY_CSRF_HEADER]);
18693
+ if (b.history?.owner !== owner)
18694
+ b.history = { owner, browser: randomUUID14() };
18695
+ res.setHeader(HISTORY_CSRF_HEADER, b.history.browser);
18696
+ }
18528
18697
  } catch {
18529
18698
  close();
18530
18699
  return;
18531
18700
  }
18532
18701
  if (route2.operation === "session" && incoming.statusCode === 200) {
18533
18702
  try {
18534
- attachments.set(decodeId(incoming.headers["x-cadence-attachment"]), { projectId: project.id, epoch: b.project.epoch });
18703
+ attachments.set(decodeId(incoming.headers["x-cadence-attachment"]), b);
18535
18704
  } catch {
18536
18705
  close();
18537
18706
  return;
18538
18707
  }
18539
18708
  }
18540
- if (route2.operation === "detach" && incoming.statusCode === 200 && attachment)
18709
+ if (route2.operation === "detach" && incoming.statusCode === 200 && attachment && attachments.get(attachment) === attached)
18541
18710
  attachments.delete(attachment);
18542
18711
  res.statusCode = incoming.statusCode ?? 502;
18543
18712
  for (const key2 of [
@@ -18598,12 +18767,14 @@ Content-Length: 0\r
18598
18767
  auth.current(caller);
18599
18768
  assert();
18600
18769
  const status = observed && typeof observed === "object" && "status" in observed ? observed.status : "unavailable";
18601
- reply(res, 200, {
18770
+ const value2 = {
18602
18771
  kind: "project-observation",
18603
18772
  status: status === "alive" ? "running" : status === "stopped" ? "stopped" : unpreparedDirectory(c, project2) ? "not-started" : "unavailable",
18604
18773
  epoch: observed && typeof observed === "object" && "epoch" in observed ? observed.epoch : null,
18605
18774
  workspaceId: HistoryFiles.open(c)?.format.workspaceId ?? null
18606
- });
18775
+ };
18776
+ res.setHeader(PROJECT_ASSOCIATION_HEADER, isAssociated(project2.id) ? "associated" : "unassociated");
18777
+ reply(res, 200, value2);
18607
18778
  return;
18608
18779
  }
18609
18780
  if (url.pathname === "/workbench/v1/models" && req.method === "GET") {
@@ -18644,7 +18815,10 @@ Content-Length: 0\r
18644
18815
  return;
18645
18816
  }
18646
18817
  if (raw === "/workbench/v1/service" && req.method === "GET") {
18647
- reply(res, 200, await serviceEntry());
18818
+ const service = await serviceEntry();
18819
+ auth.current(caller);
18820
+ assert();
18821
+ reply(res, 200, service);
18648
18822
  return;
18649
18823
  }
18650
18824
  if (raw === "/workbench/v1/service/release" && req.method === "GET") {
@@ -18695,6 +18869,8 @@ Content-Length: 0\r
18695
18869
  const asset = assets.get(app ? "/app" : raw);
18696
18870
  if (req.method !== "GET" || !asset)
18697
18871
  throw new ContractError("invalid");
18872
+ if (app)
18873
+ res.setHeader("X-Cadence-Web-Build", build2.assets.buildId);
18698
18874
  res.setHeader("Content-Type", asset.contentType);
18699
18875
  res.end(asset.bytes);
18700
18876
  } catch (error) {
@@ -18724,10 +18900,14 @@ Content-Length: 0\r
18724
18900
  if (req.method !== "GET" || !t)
18725
18901
  throw new ContractError("invalid");
18726
18902
  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}`)
18903
+ if (attachments.get(attachment)?.project.id !== t.id || t.tail !== `${WS_PATH}?attachment=${attachment}`)
18728
18904
  throw new ContractError("invalid");
18729
- const b = await binding(t.id);
18730
- if (attachments.get(attachment)?.epoch !== b.project.epoch)
18905
+ const attached = attachments.get(attachment);
18906
+ if (!attached || attached.rejected)
18907
+ throw new ContractError("unauthenticated");
18908
+ const original = binding(t.id);
18909
+ const b = await original;
18910
+ if (bindings.get(t.id)?.result !== original || attachments.get(attachment) !== attached || attached.project.epoch !== b.project.epoch || attached.cookie !== b.cookie)
18731
18911
  throw new ContractError("stale");
18732
18912
  auth.current(caller);
18733
18913
  assert();
@@ -18745,6 +18925,12 @@ Content-Length: 0\r
18745
18925
  };
18746
18926
  relays.add(abort);
18747
18927
  socket.once("close", abort);
18928
+ upstream.once("unexpected-response", (_request, response) => {
18929
+ if (response.statusCode === 401)
18930
+ rejectBinding(b, original);
18931
+ response.destroy();
18932
+ abort();
18933
+ });
18748
18934
  upstream.once("error", abort);
18749
18935
  upstream.once("close", abort);
18750
18936
  upstream.once("open", () => {
@@ -31269,7 +31455,7 @@ import { join as join39 } from "node:path";
31269
31455
  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
31456
  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
31457
  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.
31458
+ 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
31459
  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
31460
  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
31461
  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.
@@ -32915,25 +33101,25 @@ Current design ${design.id}, revision ${design.revision}, ${design.submitted ? "
32915
33101
  }
32916
33102
  }
32917
33103
  if (name === "cadence_design") {
33104
+ let design2;
32918
33105
  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
- };
33106
+ design2 = newDesign(randomUUID25(), args, current2.state.design);
32932
33107
  } catch (error) {
32933
- if (this.o.owner.state !== "idle")
32934
- throw error;
32935
33108
  return refusal3("invalid", diagnosticText(error instanceof Error ? error.message : "questions: invalid design", 512, this.o.secrets()));
32936
33109
  }
33110
+ const encoded2 = canonicalJson(design2);
33111
+ if (sanitizeText(encoded2, this.o.secrets()) !== encoded2)
33112
+ return refusal3("forbidden", "Design contains protected text.");
33113
+ this.save({
33114
+ ...current2.state,
33115
+ design: design2,
33116
+ proposal: null,
33117
+ revision: current2.state.revision + 1
33118
+ }, current2.file);
33119
+ return {
33120
+ designId: design2.id,
33121
+ notice: "Design choices published. Finish this turn and wait for the user's batch submission; do not ask for a typed answer."
33122
+ };
32937
33123
  }
32938
33124
  const epoch = this.o.owner.lease.registration.epoch;
32939
33125
  const model2 = c.model.conversation && this.o.contexts ? this.o.contexts.snapshot(c.model.conversation).version : this.o.choice.snapshot().version;
@@ -33508,7 +33694,7 @@ class Conversations {
33508
33694
  epoch: live2.epoch,
33509
33695
  now: Date.now(),
33510
33696
  leaf: live2.accepted.parent,
33511
- phase: live2.abort.signal.aborted ? "stopping" : live2.state.status === "queued" ? "queued" : live2.state.status === "running" ? "running" : "settling"
33697
+ phase: live2.abort.signal.aborted ? "stopping" : isLiveChatStatus(live2.state.status) ? live2.state.status : "settling"
33512
33698
  }));
33513
33699
  }
33514
33700
  constructor(o) {
@@ -33652,7 +33838,7 @@ class Conversations {
33652
33838
  epoch: input.model.epoch,
33653
33839
  title: listed ? summaryTitle(listed.summary) : [...command.text.trim()].slice(0, 100).join("") || "Conversation",
33654
33840
  state: {
33655
- status: "queued",
33841
+ status: control ? "queued" : "starting",
33656
33842
  notice: "",
33657
33843
  omitted: { thinking: false, media: false, other: false },
33658
33844
  user: null
@@ -33923,7 +34109,6 @@ class Conversations {
33923
34109
  async run(live2, control) {
33924
34110
  const { accepted: accepted2, abort, state } = live2;
33925
34111
  const commandId = live2.commandId;
33926
- let barrier;
33927
34112
  let authSettled;
33928
34113
  let uncertain = false;
33929
34114
  let native = {
@@ -33944,6 +34129,7 @@ class Conversations {
33944
34129
  };
33945
34130
  const current2 = () => !abort.signal.aborted && this.o.owner.state === "idle" && this.currentDirectory(live2.execution.cwd);
33946
34131
  try {
34132
+ this.o.owner.lease.assert();
33947
34133
  if (!current2())
33948
34134
  throw new ContractError("stale");
33949
34135
  if (control?.reply) {
@@ -33951,12 +34137,6 @@ class Conversations {
33951
34137
  state.notice = control.reply;
33952
34138
  return { status: "settled" };
33953
34139
  }
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
34140
  const selected2 = live2.execution.model;
33961
34141
  if (!selected2)
33962
34142
  throw new ContractError("stale");
@@ -34083,8 +34263,6 @@ CONVERSATION CONTEXT (data): cwd ${live2.execution.cwd}; checkout root ${live2.e
34083
34263
  }
34084
34264
  if (uncertain)
34085
34265
  this.o.owner.quarantine();
34086
- else if (this.o.owner.state === "idle")
34087
- barrier?.release();
34088
34266
  for (const input of live2.inputs)
34089
34267
  this.inputs.delete(input.commandId);
34090
34268
  this.active.delete(commandId);
@@ -35721,8 +35899,8 @@ function workflowResultDetail(value, secrets) {
35721
35899
  var runtimeSummary = (runtime) => `${describeWorkerRuntime(runtime)}
35722
35900
  ${RUN_ENVIRONMENT_POLICY}`;
35723
35901
  var OWNER_RUNTIME = Object.freeze({
35724
- version: "2.2.0",
35725
- build: "ddf9e9d35a3a7b928845d9b7bf1c122aa355e11810dc0066577290956bf6c793",
35902
+ version: "2.2.1",
35903
+ build: "a00e54093398520b297b4fa2a520c8519e5f947a49f61dae258493ec2903ab39",
35726
35904
  entry: fileURLToPath7(import.meta.url),
35727
35905
  pid: process.pid,
35728
35906
  node: process.versions.node,
@@ -38310,9 +38488,14 @@ class Workbench {
38310
38488
  opening = new Map;
38311
38489
  constructor(o) {
38312
38490
  this.o = o;
38313
- this.conversations = new Conversations(o);
38491
+ const { gate, ...common } = o;
38492
+ this.conversations = new Conversations(common);
38314
38493
  this.contexts = this.conversations.contexts;
38315
- this.workflows = new Workflows({ ...o, contexts: this.contexts });
38494
+ this.workflows = new Workflows({
38495
+ ...common,
38496
+ gate,
38497
+ contexts: this.contexts
38498
+ });
38316
38499
  this.files = new WorkbenchFiles(o.coordination.store.root, [o.coordination.files.namespace, o.agentDir], o.secrets);
38317
38500
  this.cadence = new ConversationWorkflow({
38318
38501
  ...o,
@@ -38742,7 +38925,7 @@ var processLifetime = {
38742
38925
  }
38743
38926
  };
38744
38927
  async function createServiceHost(value, sourceBuild, lifetime) {
38745
- const embedded = "1b833e54ac91fb9d8e570f43da35e3e2faf6c9e214bd9d1bd7cce19c2fe7f243";
38928
+ const embedded = "190a21e723f753a233225a9f4bcf12a99d71b294a58728961846cd110cd60a17";
38746
38929
  if (embedded && sourceBuild)
38747
38930
  throw new ContractError("unsupported-context");
38748
38931
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);