diacode 0.2.2 → 0.2.3

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.
package/bin/dcursed.js CHANGED
@@ -134,6 +134,10 @@ var isString = (v, min = 0, max = Infinity) => typeof v === "string" && v.length
134
134
  var FILES_MAX = 64;
135
135
  var FILE_MAX = 256;
136
136
  var DETAIL_MAX = 4e3;
137
+ var OPTIONS_MAX = 8;
138
+ var OPTION_MAX = 80;
139
+ var isOptionList = (v) => Array.isArray(v) && v.length >= 1 && v.length <= OPTIONS_MAX && v.every((o) => isString(o, 1, OPTION_MAX) && o.trim() === o);
140
+ var OPTIONS_PROBLEM = `options is 1-${OPTIONS_MAX} answers, each 1-${OPTION_MAX} characters with no space at either end`;
137
141
  var NOTE_MAX = 2e3;
138
142
  function upgradePlan(plan) {
139
143
  return isObject(plan) && OLDER.includes(plan.schema) ? { ...plan, schema: SCHEMA } : plan;
@@ -197,11 +201,12 @@ function validatePlan(plan) {
197
201
  problems.push(`${at}: not an object`);
198
202
  return;
199
203
  }
200
- onlyKeys(e, ["from", "to", "label", "kind", "question", "passed", "answer"], at, problems);
204
+ onlyKeys(e, ["from", "to", "label", "kind", "question", "options", "passed", "answer"], at, problems);
201
205
  if (e.label !== void 0 && !isString(e.label, 0, 120)) problems.push(`${at}: label is at most 120 characters`);
202
206
  if (e.kind !== void 0 && (e.kind === "needs" || !EDGE_KINDS.includes(e.kind))) problems.push(`${at}: kind is one of ${EDGE_KINDS.slice(1).join(", ")} (leave it out for needs)`);
203
207
  const checkpoint2 = CHECKPOINTS.has(e.kind);
204
208
  if (e.question !== void 0 && (e.kind !== "ask" || !isString(e.question, 1, NOTE_MAX))) problems.push(`${at}: only an "ask" checkpoint has a question, of 1-${NOTE_MAX} characters`);
209
+ if (e.options !== void 0 && (e.kind !== "ask" || !isOptionList(e.options))) problems.push(`${at}: only an "ask" checkpoint has options; ${OPTIONS_PROBLEM}`);
205
210
  if (e.passed !== void 0 && (!checkpoint2 || e.passed !== true)) problems.push(`${at}: only a checkpoint is passed, and passed is true`);
206
211
  if (e.answer !== void 0 && (e.passed !== true || !isString(e.answer, 0, NOTE_MAX))) problems.push(`${at}: only a passed checkpoint has an answer, of at most ${NOTE_MAX} characters`);
207
212
  if (!(e.from in plan.nodes)) problems.push(`${at}: "${e.from}" is not a step`);
@@ -237,15 +242,15 @@ var OPS = {
237
242
  "node.add": { required: ["label"], optional: ["id", "kind", "detail", "group", "files", "touches", "after"], ids: ["id"] },
238
243
  "node.set": { required: ["id"], optional: ["label", "kind", "detail", "group", "files", "touches"], ids: ["id"], oneOf: ["label", "kind", "detail", "group", "files", "touches"] },
239
244
  "node.remove": { required: ["id"], ids: ["id"] },
240
- "edge.add": { required: ["from", "to"], optional: ["label", "kind"], ids: ["from", "to"] },
245
+ "edge.add": { required: ["from", "to"], optional: ["label", "kind", "options"], ids: ["from", "to"] },
241
246
  "edge.remove": { required: ["from", "to"], ids: ["from", "to"] },
242
247
  "edge.rewire": { required: ["from", "to"], optional: ["newFrom", "newTo"], ids: ["from", "to", "newFrom", "newTo"], oneOf: ["newFrom", "newTo"] },
243
248
  "edge.reverse": { required: ["from", "to"], ids: ["from", "to"] },
244
- "edge.set": { required: ["from", "to"], optional: ["label", "kind"], ids: ["from", "to"], oneOf: ["label", "kind"] },
249
+ "edge.set": { required: ["from", "to"], optional: ["label", "kind", "options"], ids: ["from", "to"], oneOf: ["label", "kind", "options"] },
245
250
  // A checkpoint: you pass it (with your answer or input), an agent asks its question at an `ask`, and an approval
246
251
  // you withhold sends the step before it back.
247
252
  "gate.pass": { required: ["from", "to"], optional: ["answer"], ids: ["from", "to"] },
248
- "gate.ask": { required: ["from", "to", "question"], ids: ["from", "to"] },
253
+ "gate.ask": { required: ["from", "to", "question"], optional: ["options"], ids: ["from", "to"] },
249
254
  "gate.reject": { required: ["from", "to"], optional: ["reason"], ids: ["from", "to"] },
250
255
  "status.set": { required: ["id", "status"], optional: ["note"], ids: ["id"] },
251
256
  claim: { required: ["id"], ids: ["id"] },
@@ -279,6 +284,7 @@ function validateOp(op) {
279
284
  }
280
285
  if (op.question !== void 0 && !isString(op.question, 1, NOTE_MAX)) problems.push(`${op.op}: question is 1-${NOTE_MAX} characters`);
281
286
  if (op.answer !== void 0 && !isString(op.answer, 0, NOTE_MAX)) problems.push(`${op.op}: answer is at most ${NOTE_MAX} characters`);
287
+ if (op.options !== void 0 && !isOptionList(op.options)) problems.push(`${op.op}: ${OPTIONS_PROBLEM}`);
282
288
  if (op.files !== void 0 && !isFileList(op.files)) problems.push(`${op.op}: ${FILES_PROBLEM}`);
283
289
  if (op.touches !== void 0 && !isTouches(op.touches)) problems.push(`${op.op}: ${TOUCHES_PROBLEM}`);
284
290
  if (op.group !== void 0 && !(op.op === "node.set" && op.group === null) && !isString(op.group, 1, 80)) problems.push(`${op.op}: group is 1-80 characters`);
@@ -443,7 +449,7 @@ function step(p, op, ctx) {
443
449
  }
444
450
  case "edge.add":
445
451
  if (frozen(op.to)) refuse(`${op.to} is done; what it depended on is history`);
446
- addEdge(p, op.from, op.to, op.label, op.kind);
452
+ addEdge(p, op.from, op.to, op.label, op.kind, op.options);
447
453
  affectFrom(op.to, `now depends on ${op.from}`);
448
454
  return op;
449
455
  case "edge.remove": {
@@ -479,6 +485,10 @@ function step(p, op, ctx) {
479
485
  else e.kind = op.kind;
480
486
  clearCheckpoint(e);
481
487
  }
488
+ if (op.options !== void 0) {
489
+ if (e.kind !== "ask") refuse(`${op.from} \u2192 ${op.to} is not an "ask" checkpoint; only one has options`);
490
+ e.options = op.options;
491
+ }
482
492
  return op;
483
493
  }
484
494
  case "gate.pass": {
@@ -495,6 +505,7 @@ function step(p, op, ctx) {
495
505
  if (e.kind !== "ask") refuse(`${op.from} \u2192 ${op.to} is an "${e.kind}" checkpoint; only an "ask" one takes a question`);
496
506
  if (e.passed) refuse(`the checkpoint ${op.from} \u2192 ${op.to} is passed already: ${op.to} can start`);
497
507
  e.question = op.question;
508
+ if (op.options !== void 0) e.options = op.options;
498
509
  return op;
499
510
  }
500
511
  case "gate.reject": {
@@ -616,12 +627,13 @@ function checkEdge(p, from, to, ignore) {
616
627
  const without = ignore ? { ...p, edges: p.edges.filter((e) => e !== ignore) } : p;
617
628
  if (reaches(without, to, from)) refuse(`${from} \u2192 ${to} would make a loop`);
618
629
  }
619
- function addEdge(p, from, to, label, kind) {
630
+ function addEdge(p, from, to, label, kind, options) {
620
631
  checkEdge(p, from, to);
632
+ if (options && kind !== "ask") refuse('only an "ask" checkpoint has options');
621
633
  p.edges.push({ from, to, ...label ? { label } : {}, ...kind && kind !== "needs" ? { kind: (
622
634
  /** @type {Exclude<import('./types.js').EdgeKind, 'needs'>} */
623
635
  kind
624
- ) } : {} });
636
+ ) } : {}, ...options ? { options } : {} });
625
637
  }
626
638
  function checkpoint(p, from, to) {
627
639
  const e = findEdge(p, from, to);
@@ -630,6 +642,7 @@ function checkpoint(p, from, to) {
630
642
  }
631
643
  function clearCheckpoint(e) {
632
644
  delete e.question;
645
+ delete e.options;
633
646
  delete e.passed;
634
647
  delete e.answer;
635
648
  }
@@ -661,7 +674,7 @@ function derive(plan) {
661
674
  gates.push({ from: e.from, to: e.to, kind: (
662
675
  /** @type {Gate['kind']} */
663
676
  e.kind
664
- ), ...e.label ? { label: e.label } : {}, ...e.question ? { question: e.question } : {}, turn });
677
+ ), ...e.label ? { label: e.label } : {}, ...e.question ? { question: e.question } : {}, ...e.question && e.options ? { options: e.options } : {}, turn });
665
678
  }
666
679
  if (waiting.length) blocked.set(id, waiting);
667
680
  else if (at.length) held.set(id, at.map((e) => e.from));
@@ -781,7 +794,7 @@ function opposite(reason) {
781
794
  var ORDER = {
782
795
  plan: ["schema", "id", "title", "goal", "rev", "phase", "source", "nodes", "edges", "proposals"],
783
796
  node: ["label", "kind", "group", "detail", "status", "statusFrom", "statusBy", "note", "owner", "files", "touches"],
784
- edge: ["from", "to", "kind", "label", "question", "passed", "answer"],
797
+ edge: ["from", "to", "kind", "label", "question", "options", "passed", "answer"],
785
798
  proposal: ["id", "by", "at", "reason", "ops"],
786
799
  layout: ["schema", "plan", "direction", "canvas", "collapsed", "nodes"],
787
800
  place: ["x", "y", "pinned"]
@@ -927,7 +940,7 @@ function diffToOps(before, after, { bridge = false } = {}) {
927
940
  }
928
941
  }
929
942
  }
930
- for (const c of came) ops.push(pick({ op: "edge.add", from: c.from, to: c.to, label: c.label, kind: c.kind }));
943
+ for (const c of came) ops.push(pick({ op: "edge.add", from: c.from, to: c.to, label: c.label, kind: c.kind, options: c.kind === "ask" ? c.options : void 0 }));
931
944
  for (const [k, e] of afterEdges) {
932
945
  const was = beforeEdges.get(k);
933
946
  const set = was && edgeChange(was, e);
@@ -950,7 +963,8 @@ function diffToOps(before, after, { bridge = false } = {}) {
950
963
  const was = beforeEdges.get(k) ?? /** @type {import('./types.js').Edge} */
951
964
  { from: e.from, to: e.to };
952
965
  const reset = kindOf(was) !== kindOf(e);
953
- if (e.question !== void 0 && (reset || e.question !== was.question) && !e.passed) ops.push({ op: "gate.ask", from: e.from, to: e.to, question: e.question });
966
+ if (e.question !== void 0 && (reset || e.question !== was.question || JSON.stringify(e.options) !== JSON.stringify(was.options)) && !e.passed) ops.push({ op: "gate.ask", from: e.from, to: e.to, question: e.question, ...e.options ? { options: e.options } : {} });
967
+ else if (e.options !== void 0 && e.question === void 0 && kindOf(e) === "ask" && (reset || JSON.stringify(e.options) !== JSON.stringify(was.options))) ops.push({ op: "edge.set", from: e.from, to: e.to, options: e.options });
954
968
  if (e.passed && (reset || !was.passed)) ops.push(pick({ op: "gate.pass", from: e.from, to: e.to, answer: e.answer }));
955
969
  else if (!e.passed && was.passed && !reset) ignored.push(`${e.from} \u2192 ${e.to}: passed (a checkpoint is not taken back; change the arrow's kind to reset it)`);
956
970
  }
@@ -1473,7 +1487,7 @@ function arrowIn(e) {
1473
1487
  if (!e.kind) return e.from;
1474
1488
  const bits = [KIND[e.kind]];
1475
1489
  if (e.kind === "input" && e.label) bits.push(quote(e.label, 80));
1476
- if (e.question) bits.push(`asked ${quote(e.question, 160)}`);
1490
+ if (e.question) bits.push(`asked ${quote(e.question, 160)}${e.options?.length ? `, offering ${e.options.map((o) => quote(o, 60)).join(" / ")}` : ""}`);
1477
1491
  if (e.passed) bits.push(e.answer ? `PASSED, the person said ${quote(e.answer, 300)}` : "PASSED");
1478
1492
  return `${e.from} (${bits.join("; ")})`;
1479
1493
  }
@@ -1510,7 +1524,7 @@ function describeOp(op) {
1510
1524
  case "gate.pass":
1511
1525
  return `the checkpoint ${op.from} \u2192 ${op.to} is passed${op.answer ? `: ${quote(op.answer, 300)}` : ""}; ${op.to} may start`;
1512
1526
  case "gate.ask":
1513
- return `asked the person before ${op.to}: ${quote(op.question, 300)}`;
1527
+ return `asked the person before ${op.to}: ${quote(op.question, 300)}${op.options?.length ? `, offering ${op.options.map((o) => quote(o, 60)).join(" / ")}` : ""}`;
1514
1528
  case "gate.reject":
1515
1529
  return `${op.from} was sent back, not approved${op.reason ? ` (${quote(op.reason, 300)})` : ""}: it is to be done again`;
1516
1530
  case "status.set":
@@ -3634,6 +3648,19 @@ var PlanStore = class extends EventEmitter {
3634
3648
  );
3635
3649
  this.emit("drift", { id });
3636
3650
  }
3651
+ /**
3652
+ * You said a file outside the plan needs no step (a scratch file, say): it is not offered again, unless an agent edits it again.
3653
+ * @param {string} id @param {string} [file] none: all of them
3654
+ * @returns {number} how many were let go
3655
+ */
3656
+ ignoreOutside(id, file) {
3657
+ const files = this.outside.get(id);
3658
+ if (!files) return 0;
3659
+ const gone = file === void 0 ? files.size : Number(files.delete(file));
3660
+ if (file === void 0) files.clear();
3661
+ if (gone) this.emit("drift", { id });
3662
+ return gone;
3663
+ }
3637
3664
  /**
3638
3665
  * The files agents have edited that no step lists *now* (a step that has since come to list one
3639
3666
  * covers it), newest first: what the plan has drifted from. @param {string} id
@@ -4154,7 +4181,7 @@ var GUIDE = `DiaCode keeps this repository's architecture and plans as files in
4154
4181
 
4155
4182
  THE ORDER. The person approves each stage in the editor before the next; do the stage you are in, then STOP and say it is ready.
4156
4183
  1. THE TASK. When the person gives you something to build or change, your first and only job is the ARCHITECTURE: call arch_draft with the system AS IT WILL BE (who uses it, the services, the parts inside them, the stores and queues, and how they use each other). Mark every part that does not exist yet planned: true. An empty repository is no excuse: draw what you are about to build. Then stop and say in a sentence that it is ready to review. Do not call plan_create, do not write code, and do not ask the person questions in your own window: assume what you need, say so in the architecture (the goal, a box's detail), and they correct the drawing.
4157
- 2. THEY APPROVE THE ARCHITECTURE. You are sent a message that starts with [DiaCode]. Draw the PLAN on it with plan_create, then stop and say it is ready to review. A question the task told you to ask before building (or at some point in the build) is an ask checkpoint on the arrow into the first step that needs the answer: that step gets after: [{ "id": "<a step before it>", "kind": "ask", "label": "<the question>" }] (a short first step such as "Set up the project" will do as the step before). When that step is next, you call step_ask on it, the step the arrow points at, and end your turn; the person answers in the editor, so do not ask it in your window and do not make a step of its own for asking. If you did ask in your window, write their answer into the detail of the step it concerns.
4184
+ 2. THEY APPROVE THE ARCHITECTURE. You are sent a message that starts with [DiaCode]. Draw the PLAN on it with plan_create, then stop and say it is ready to review. A question the task told you to ask before building (or at some point in the build) is an ask checkpoint on the arrow into the first step that needs the answer: that step gets after: [{ "id": "<a step before it>", "kind": "ask", "label": "<the question>" }] (a short first step such as "Set up the project" will do as the step before). When that step is next, you call step_ask on it, the step the arrow points at, and end your turn; the person answers in the editor, so do not ask it in your window and do not make a step of its own for asking. If you did ask in your window, write their answer into the detail of the step it concerns. ONE question per ask: never several numbered questions in one box (the person answers "1" and you cannot tell which). Write the question in a sentence, list its answers in its text, "(1) one vote each (2) several", and give the same answers as step_ask's \`options\`, so the person presses one; if you have two questions, ask the second after the first is answered.
4158
4185
  3. THEY APPROVE THE PLAN. You are sent a [DiaCode] message: the plan is NOT started. Check the architecture against it, once: every part the plan adds is a box (planned: true while it does not exist), every part it removes is marked retiring, each step lists the boxes it changes as touches. Fix what is missing with arch_edit; your changes to an approved architecture arrive as proposals the person accepts or rejects, so give each a plain reason. Then stop and say what you changed, or that nothing needed to change. Do not start any step.
4159
4186
  4. THEY PRESS START. You are sent a [DiaCode] message: carry the plan out, below.
4160
4187
  5. WHILE IT RUNS, and while it is approved and not started, what the person changes on one side is told to you as a [DiaCode] message. Make the other side agree: a change to the plan that adds, removes or reconnects a part of the system gets the matching arch_edit; a change to the architecture that a step no longer matches gets the matching plan_edit. Both arrive as proposals; say why. If nothing needs to change, say so.
@@ -4162,7 +4189,7 @@ Each DiaCode tool's answer ends with the stage you are at. When it says to wait,
4162
4189
 
4163
4190
  How to work with a plan
4164
4191
  - plan_list, then plan_read. A plan is a graph of steps; an arrow from A to B means B depends on A. A step marked READY has nothing left to wait for.
4165
- - Some arrows say more. "order only" (after): B comes later but does not use what A makes. A CHECKPOINT is where the person comes in before B starts: they approve A's result, they give input B needs, or (ask) you ask them first with step_ask and end your turn. A step that WAITS AT A CHECKPOINT cannot be started until the person passes it; you are sent their answer when they do.
4192
+ - Some arrows say more. "order only" (after): B comes later but does not use what A makes. A CHECKPOINT is where the person comes in before B starts: they approve A's result, they give input B needs, or (ask) you ask them first with step_ask and end your turn. When the task says to show them something before going on ("show me the page before the import"), that is an approve checkpoint (kind: "approve", with a label saying what to look at) on the arrow out of the step that shows it; a file you need from them is an input checkpoint on an arrow into the step that needs it, a different arrow, not folded into the approval's label. A step that WAITS AT A CHECKPOINT cannot be started until the person passes it; you are sent their answer when they do.
4166
4193
  - Every reply ends with what the person (or another agent) changed since you last looked. Read it before your next step: their edits win over what you remember.
4167
4194
  - If a reply (or a tool result) starts with HEADS UP, something happened to a step you hold: it was cancelled, removed, finished or reopened by the person, reworded, or has a new prerequisite. Deal with that before anything else: stop on a cancelled or removed step, re-read a reworded one, and if a new prerequisite blocks you, say so with step_wait or do the prerequisite if it is ready.
4168
4195
  - To start a step call step_start (refused until the person has pressed Start). When you finish it call step_done with a note saying what is true now (the tests that pass, the files you changed). Call step_failed if it failed and step_wait if you need the person, then end your turn: their answer is sent to you. Report as you go, not at the end.
@@ -4174,6 +4201,9 @@ How to work with a plan
4174
4201
  - When every step is done, say so in a sentence and stop: the person closes the plan in the editor, and is then asked whether to make the boxes it planned real.
4175
4202
  - Do not edit the files in .dcursed/plans/ by hand. The tools check the rules and keep the log.
4176
4203
 
4204
+ Showing the person something
4205
+ - A step that shows the person something (a page, a running app, a file to open) leaves it RUNNING when the step ends: do not stop the server or close the window until the person has approved. Put the full address in that step's note (step_done), such as "Running at http://localhost:3000", and say there what to try. A checkpoint that asks the person to look at something (an approve checkpoint, or the label you give it) says what to look at and where, never "try npm start". The editor turns an address in a note into a link and puts an Open button on the checkpoint.
4206
+
4177
4207
  Working while the person watches
4178
4208
  - Write and change files with your file tools, not with shell redirects or heredocs, and keep each shell command plain: one command, no loops, no variables. The person's tool asks them to approve every command it cannot check, and each such prompt holds the run until they come to its window.
4179
4209
 
@@ -4279,7 +4309,7 @@ var Calls = class extends EventEmitter3 {
4279
4309
  const archToo = was === "planning" && this.arch?.arch?.phase === "draft" && to !== void 0 && this.archDrafter() === to;
4280
4310
  if (archToo) this.acceptArch().catch(() => {
4281
4311
  });
4282
- this.make({ plan: id, rev: line.rev, kind: "planApproved", to, text: planApprovedText(plan, id, { archToo, hasArch: Boolean(this.arch?.exists) }) });
4312
+ this.make({ plan: id, rev: line.rev, kind: "planApproved", to, text: planApprovedText(plan, id, { archToo, hasArch: Boolean(this.arch?.exists), bare: this.bareSteps(id).map((b) => ({ id: b, label: plan.nodes[b]?.label ?? b })) }) });
4283
4313
  } else if (op.op === "plan.set" && op.phase) {
4284
4314
  phased = true;
4285
4315
  this.dropQueued(id);
@@ -4380,7 +4410,8 @@ var Calls = class extends EventEmitter3 {
4380
4410
  const since = Math.min(seen ?? from - 1, from - 1);
4381
4411
  const lines = arch_exports.describeChanges(this.arch?.since(since) ?? [], since, { not: actor });
4382
4412
  if (!lines.length) return;
4383
- this.make({ plan: ARCH_SCOPE, rev, kind: "archChanged", to: actor, text: archChangedText(plan, planId, a, lines) });
4413
+ const bare = this.bareBoxes(since);
4414
+ this.make({ plan: ARCH_SCOPE, rev, kind: "archChanged", to: actor, text: archChangedText(plan, planId, a, lines, { bare: bare.map((b) => ({ id: b, label: a.nodes[b]?.label ?? b })) }), ...bare.length ? { bare } : {} });
4384
4415
  }
4385
4416
  /**
4386
4417
  * What you changed on the plan and on the architecture since this agent last looked, for the message that wakes it when a
@@ -4607,7 +4638,82 @@ var Calls = class extends EventEmitter3 {
4607
4638
  const since = seen ?? from - 1;
4608
4639
  const changes = describeChanges(this.store.changesSince(id, since), since, { not: actor });
4609
4640
  const sync = this.store.changesSince(id, since).some((l) => l.actor === "you" && !l.proposed && (l.ops ?? []).some((o) => STRUCTURAL.has(o.op) || o.op === "plan.set" && (o.title !== void 0 || o.goal !== void 0)));
4610
- this.make({ plan: id, rev, kind: "changed", to: actor, text: changedText(plan, id, this.store.attentionFor(id, actor, since), changes, { sync }) });
4641
+ const bare = this.bareSteps(id, since);
4642
+ this.make({ plan: id, rev, kind: "changed", to: actor, text: changedText(plan, id, this.store.attentionFor(id, actor, since), changes, { sync, bare: bare.map((b) => ({ id: b, label: plan.nodes[b]?.label ?? b })) }), ...bare.length ? { bare } : {} });
4643
+ }
4644
+ /**
4645
+ * Steps you added by name only (no description, no files, no boxes): those you added since `since`, or with no `since`, every such
4646
+ * step of the plan. A step you filled in while the edit waited is not bare any more.
4647
+ * @param {string} id @param {number} [since]
4648
+ * @returns {string[]}
4649
+ */
4650
+ bareSteps(id, since) {
4651
+ const plan = this.store.get(id).plan;
4652
+ if (!plan) return [];
4653
+ const added = since === void 0 ? Object.keys(plan.nodes) : this.store.changesSince(id, since).filter((l) => l.actor === "you" && !l.proposed).flatMap((l) => (l.ops ?? []).filter((o) => o.op === "node.add").map((o) => (
4654
+ /** @type {string} */
4655
+ o.id
4656
+ )));
4657
+ return [...new Set(added)].filter((s) => {
4658
+ const n = plan.nodes[s];
4659
+ return n && n.kind !== "context" && !n.detail && !n.files?.length && !n.touches?.length && (n.status === void 0 || n.status === "not_started");
4660
+ });
4661
+ }
4662
+ /**
4663
+ * Boxes you added by name only (no description, technology or files) since `since`.
4664
+ * @param {number} since @returns {string[]}
4665
+ */
4666
+ bareBoxes(since) {
4667
+ const a = this.arch?.arch;
4668
+ if (!a) return [];
4669
+ const added = (this.arch?.since(since) ?? []).filter((l) => l.actor === "you" && !l.proposed).flatMap((l) => (l.ops ?? []).filter((o) => o.op === "box.add").map((o) => (
4670
+ /** @type {string} */
4671
+ o.id
4672
+ )));
4673
+ return [...new Set(added)].filter((b) => {
4674
+ const n = a.nodes[b];
4675
+ return n && n.kind !== "group" && !n.detail && !n.tech && !n.files?.length;
4676
+ });
4677
+ }
4678
+ /**
4679
+ * You asked your agent to look at something the plan does not cover or got wrong: files edited outside it (`drift`), steps whose
4680
+ * upstream changed (`review`), or a step that failed (`failure`). The agent is woken with what you pressed and what it is about.
4681
+ * Nobody to tell comes back as a call in the state `none`, which the editor says in words.
4682
+ * @param {string} id @param {{ kind: 'drift' | 'review' | 'failure', step?: string, steps?: string[] }} request
4683
+ * @returns {Call}
4684
+ */
4685
+ askAgent(id, { kind, step: step3, steps }) {
4686
+ const view = this.store.get(id);
4687
+ const plan = view.plan;
4688
+ if (!plan) throw new HttpError(409, `${id}.plan.json is not a valid plan yet`);
4689
+ let to;
4690
+ let text2;
4691
+ if (kind === "drift") {
4692
+ const drift = this.store.driftOf(id);
4693
+ if (!drift.length) throw new HttpError(409, "nothing is outside the plan");
4694
+ to = this.worker(id);
4695
+ text2 = driftText(plan, id, drift);
4696
+ } else if (kind === "failure") {
4697
+ const n = step3 ? plan.nodes[step3] : void 0;
4698
+ if (!step3 || !n) throw new HttpError(404, `there is no step ${step3 ?? ""} in ${id}`);
4699
+ if (n.status !== "failed") throw new HttpError(409, `${step3} has not failed`);
4700
+ const behind = Object.keys(view.derived?.atRisk ?? {}).filter((s) => (view.derived?.atRisk?.[s] ?? []).includes(step3));
4701
+ to = this.holder(id, step3) ?? this.worker(id);
4702
+ text2 = failureText(plan, id, step3, behind);
4703
+ } else {
4704
+ const waiting = (steps?.length ? steps : Object.keys(view.review ?? {})).filter((s) => plan.nodes[s]);
4705
+ if (!waiting.length) throw new HttpError(409, "nothing needs review");
4706
+ to = this.worker(id);
4707
+ text2 = reviewText(plan, id, waiting.map((s) => ({ id: s, because: view.review?.[s]?.because ?? [] })));
4708
+ }
4709
+ const call = (
4710
+ /** @type {Call} */
4711
+ this.make({ plan: id, rev: plan.rev, kind: "replan", ...kind === "failure" && step3 ? { step: step3 } : {}, ...to ? { to } : {}, text: text2 })
4712
+ );
4713
+ if (call.state === "queued" && to && !this.lastHeard.has(to) && ![...this.waiters].some((w) => w.actor === to) && !this.busy(to)) {
4714
+ this.settle(call, "none", "nothing is listening for the editor");
4715
+ }
4716
+ return { ...call };
4611
4717
  }
4612
4718
  /** The revision of a plan an agent was last shown, if it ever was. @param {string} actor @param {string} id */
4613
4719
  seen(actor, id) {
@@ -4641,7 +4747,7 @@ var Calls = class extends EventEmitter3 {
4641
4747
  if (this.calls.length > KEEP) this.calls.shift();
4642
4748
  if (call.state === "none") {
4643
4749
  this.emit("call", { ...call });
4644
- return;
4750
+ return call;
4645
4751
  }
4646
4752
  if (!this.offer(call)) {
4647
4753
  this.emit("call", { ...call });
@@ -4686,6 +4792,7 @@ var Calls = class extends EventEmitter3 {
4686
4792
  const plan = this.store.get(call.plan).plan;
4687
4793
  if (!plan) return false;
4688
4794
  if (call.kind === "started" || call.kind === "resumed") return plan.phase === "executing";
4795
+ if (call.kind === "replan") return plan.phase !== "done";
4689
4796
  if (call.kind === "planApproved") return plan.phase === "approved";
4690
4797
  if (call.kind === "stopped") return plan.phase === "approved" && call.to !== void 0 && this.stoppedFor(call.to) === call.plan;
4691
4798
  if (call.kind === "passed") {
@@ -4789,13 +4896,45 @@ var Calls = class extends EventEmitter3 {
4789
4896
  this.pending.clear();
4790
4897
  }
4791
4898
  };
4792
- function planApprovedText(plan, id, { archToo = false, hasArch = true } = {}) {
4899
+ var clipped = (s, max = 300) => s.length > max ? `${s.slice(0, max - 1)}\u2026` : s;
4900
+ function driftText(plan, id, drift) {
4901
+ return [
4902
+ `[DiaCode] The person asks whether the plan "${plan.title}" (${id}) should cover work that is outside it. These files were edited, and no step lists them:`,
4903
+ ...drift.slice(0, 20).map((d) => `- ${d.file} (edited ${d.count}\xD7 by ${d.by})`),
4904
+ "Read the plan with plan_read. Then answer with ONE of: (a) the matching change to the plan, proposed with plan_edit (propose: true and a plain reason): usually the file added to the step it belongs to (node.set with that step's whole files list plus this one), or a new step for work the plan does not have; (b) one sentence saying the plan needs no change (a scratch or generated file, say). Do not start a step, do not change the architecture, and stop when you have answered."
4905
+ ].join("\n");
4906
+ }
4907
+ function failureText(plan, id, step3, behind) {
4908
+ const n = plan.nodes[step3];
4909
+ return [
4910
+ `[DiaCode] The person asks you to re-plan from a failure. In the plan "${plan.title}" (${id}) the step ${step3}${n?.label ? ` ("${n.label}")` : ""} failed${n?.note ? `: ${clipped(n.note, 600)}` : "."}`,
4911
+ ...behind.length ? [`These wait behind it: ${behind.join(", ")}.`] : [],
4912
+ "Read the plan with plan_read. Then answer with ONE of: (a) the change the failure teaches, proposed with plan_edit (propose: true and a plain reason): typically a new step before it that removes the cause, the step reworded with what the failure showed or split, or a dependency that was never real removed; (b) one sentence saying no change is needed. Do not set a status: whether to try again is the person's call (Try again). Stop when you have answered."
4913
+ ].join("\n");
4914
+ }
4915
+ function reviewText(plan, id, steps) {
4916
+ return [
4917
+ `[DiaCode] The person asks you to review steps of the plan "${plan.title}" (${id}) that a change upstream of them may have made wrong:`,
4918
+ ...steps.slice(0, 20).map((s) => `- ${s.id}${plan.nodes[s.id]?.label ? ` ("${plan.nodes[s.id].label}")` : ""}${s.because.length ? `: ${clipped(s.because.join("; "), 240)}` : ""}`),
4919
+ "Read the plan with plan_read. For each step: if it needs a different label, detail or files, propose that with plan_edit (propose: true and a plain reason); if it is fine, say so in a sentence (and mark it reviewed with the review op). Do not start a step. Stop when you have answered."
4920
+ ].join("\n");
4921
+ }
4922
+ function planApprovedText(plan, id, { archToo = false, hasArch = true, bare = [] } = {}) {
4793
4923
  return [
4794
4924
  `[DiaCode] The person approved the plan "${plan.title}" (${id}) in the editor${archToo ? ", and with it the architecture you drew" : ""}. It is NOT started: do not start any step; they press Start when the architecture and the plan are final.`,
4795
4925
  hasArch ? 'Now check the architecture against the plan, once. arch_read it (they may have edited it). Every part the plan adds (a step that creates a service, page, store, queue or component) must be a box, marked planned: true while it does not exist yet; a part the plan removes is marked retiring: "' + id + '"; each step lists the boxes it changes as touches (plan_edit node.set). Then arch_edit whatever is missing or wrong: your changes arrive as proposals, so give each a plain reason.' : "There is no architecture yet. Draw one now with arch_draft: the system as the plan will make it, every part that does not exist yet marked planned: true.",
4926
+ ...bare.length ? [bareStepsWords(bare)] : [],
4796
4927
  "Then stop, and say in a sentence what you changed in the architecture (or that nothing needed to change). The person accepts or rejects each change, then presses Start; the Start is sent to you as another [DiaCode] message."
4797
4928
  ].join("\n");
4798
4929
  }
4930
+ function bareStepsWords(bare) {
4931
+ const list = bare.slice(0, 10).map((b) => `${b.id} ("${b.label}")`).join(", ");
4932
+ return `The person added ${bare.length === 1 ? "this step" : "these steps"} by name only, with no description, no files and no boxes: ${list}. For each, propose what is missing with plan_edit: node.set with detail (what done means, in a sentence or two), files (the paths it will touch) and touches (the ids of the architecture's boxes it changes), and \`propose: true\` with a plain reason, so it arrives as a card the person accepts. Read the steps around it and the architecture (arch_read) to say something specific. If you cannot tell what a step means, say what you need to know instead of guessing.`;
4933
+ }
4934
+ function bareBoxesWords(bare) {
4935
+ const list = bare.slice(0, 10).map((b) => `${b.id} ("${b.label}")`).join(", ");
4936
+ return `The person added ${bare.length === 1 ? "this box" : "these boxes"} by name only, with no description, technology or files: ${list}. For each, propose what is missing with arch_edit: box.set with detail (what it is for, in a sentence), tech and files (where its code is or will be), and the arrows to what it uses (arrow.add), with a plain reason: it arrives as a card the person accepts. If you cannot tell what a box is for, say what you need to know instead of guessing.`;
4937
+ }
4799
4938
  function startedText(plan, id, { archToo = false, again = false } = {}) {
4800
4939
  return [
4801
4940
  `[DiaCode] The person pressed Start${again ? " again" : ""} on the plan "${plan.title}" (${id}) in the editor${archToo ? ", and approved the architecture you drew with it (your changes to the architecture are proposals from now on)" : ""}. Carry it out now with the dcursed tools, one step at a time:`,
@@ -4838,22 +4977,24 @@ function answeredText(plan, id, step3, answer) {
4838
4977
  return `[DiaCode] The person answered your question on step ${step3}${label ? ` ("${label}")` : ""} in plan ${id}: ${answer}
4839
4978
  Carry on with ${step3} using that answer.`;
4840
4979
  }
4841
- function changedText(plan, id, attention, changes, { sync = true } = {}) {
4980
+ function changedText(plan, id, attention, changes, { sync = true, bare = [] } = {}) {
4842
4981
  const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4843
4982
  const waiting = plan.phase === "approved";
4844
4983
  return [
4845
4984
  `[DiaCode] While you were between turns, the person changed the plan "${plan.title}" (${id}) in the editor.`,
4846
4985
  ...attention.length ? ["HEADS UP, about your steps:", ...attention.map((a) => `- ${clip2(a)}`)] : [],
4847
4986
  ...changes.length ? ["What changed:", ...changes.slice(-20).map((c) => `- ${clip2(c)}`)] : [],
4987
+ ...bare.length ? [bareStepsWords(bare)] : [],
4848
4988
  sync ? "Read the plan with plan_read. Then make the architecture agree: if what they changed adds, removes or reconnects a part of the system (a box, an arrow, a service), propose the matching change with arch_edit, giving a plain reason; if the architecture needs nothing, say so." : "Read the plan with plan_read. If they settled a proposal of yours, adjust what depended on it.",
4849
4989
  waiting ? "The plan is not started: do not start any step, and stop when you have said what you changed or that nothing needed to." : "Then carry on with what is left for you. A finished step is the person's to reopen: if one of those changed, say whether it needs reopening. If nothing is left for you to do, say so and stop."
4850
4990
  ].join("\n");
4851
4991
  }
4852
- function archChangedText(plan, id, arch2, lines) {
4992
+ function archChangedText(plan, id, arch2, lines, { bare = [] } = {}) {
4853
4993
  const clip2 = (s) => s.length > 400 ? `${s.slice(0, 399)}\u2026` : s;
4854
4994
  return [
4855
4995
  `[DiaCode] The person changed the architecture ("${arch2.title}") in the editor:`,
4856
4996
  ...lines.slice(-20).map((l) => `- ${clip2(l)}`),
4997
+ ...bare.length ? [bareBoxesWords(bare)] : [],
4857
4998
  `Read it with arch_read, then make the plan "${plan.title}" (${id}) agree: if a step no longer matches (a box was removed that a step builds or changes, a part was added that no step builds, a step's files moved), propose the matching change with plan_edit, giving a plain reason. If the plan needs nothing, say so.`,
4858
4999
  plan.phase === "approved" ? "The plan is not started: do not start any step, and stop when you have said what you changed or that nothing needed to." : "Then carry on with what is left for you."
4859
5000
  ].join("\n");
@@ -5002,7 +5143,7 @@ var OP_EXAMPLES = {
5002
5143
  "edge.remove": '{"op":"edge.remove","from":"tests","to":"lint"}',
5003
5144
  "edge.rewire": '{"op":"edge.rewire","from":"a","to":"b","newTo":"c"} (or newFrom)',
5004
5145
  "edge.reverse": '{"op":"edge.reverse","from":"a","to":"b"}',
5005
- "edge.set": '{"op":"edge.set","from":"a","to":"b","label":"parsed rows"} (or "kind": needs, after, approve, ask or input)',
5146
+ "edge.set": '{"op":"edge.set","from":"a","to":"b","label":"parsed rows"} (or "kind": needs, after, approve, ask or input; or "options": ["one vote each", "several"] for the answers an ask checkpoint offers)',
5006
5147
  "group.rename": '{"op":"group.rename","from":"old name","to":"new name"}',
5007
5148
  "plan.set": '{"op":"plan.set","goal":"what the plan is for"} (or title)',
5008
5149
  review: '{"op":"review","ids":["tests"]}'
@@ -5030,6 +5171,13 @@ var FINISHERS = [
5030
5171
  { name: "step_failed", status: "failed", release: false, description: "Report that a step failed, and why. The person is asked to look at what depends on it." },
5031
5172
  { name: "step_wait", status: "waiting", release: false, description: "Stop on a step because you need the person (a decision, a missing fact). Say what you need, then end your turn: the answer is sent to you." }
5032
5173
  ];
5174
+ var OPTIONS = {
5175
+ type: "array",
5176
+ minItems: 1,
5177
+ maxItems: OPTIONS_MAX,
5178
+ items: { type: "string", maxLength: OPTION_MAX },
5179
+ description: `the answers you offer, each a few words (at most ${OPTIONS_MAX}): they are shown as buttons, so keep the question itself to ONE question that they answer`
5180
+ };
5033
5181
  var KIND2 = {
5034
5182
  type: "string",
5035
5183
  enum: ["needs", "after", "approve", "ask", "input"],
@@ -5086,8 +5234,8 @@ WARNING: the plan file has an edit that breaks a rule (${view.error}). Writes wa
5086
5234
  touches: { type: "array", items: { type: "string" }, description: "the ids of the architecture's boxes this step changes (see arch_read), besides the ones its files fall in" },
5087
5235
  after: {
5088
5236
  type: "array",
5089
- description: 'the steps this one depends on: an id, or { id, kind, label } for an arrow that is more than "needs" (such as a checkpoint the person asked for)',
5090
- items: { anyOf: [{ type: "string" }, { type: "object", required: ["id"], properties: { id: { type: "string" }, kind: KIND2, label: { type: "string" } } }] }
5237
+ description: 'the steps this one depends on: an id, or { id, kind, label, options } for an arrow that is more than "needs" (such as a checkpoint the person asked for; an ask checkpoint may list the answers it will offer)',
5238
+ items: { anyOf: [{ type: "string" }, { type: "object", required: ["id"], properties: { id: { type: "string" }, kind: KIND2, label: { type: "string" }, options: OPTIONS } }] }
5091
5239
  },
5092
5240
  kind: { type: "string", enum: ["task", "context"], description: "context: something that already exists, shown for reference" }
5093
5241
  }
@@ -5123,7 +5271,7 @@ ${next}`, data: { plan: made.id, rev: view.rev } };
5123
5271
  name: "plan_edit",
5124
5272
  description: [
5125
5273
  "Change a plan with a batch of operations, all or nothing. Operations:",
5126
- "node.add{label,id?,kind?,detail?,group?,files?,touches?,after?[]} \xB7 node.set{id,label?,kind?,detail?,group?,files?,touches?} \xB7 node.remove{id} \xB7 edge.add{from,to,label?,kind?} \xB7 edge.remove{from,to} \xB7 edge.rewire{from,to,newFrom?,newTo?} \xB7 edge.reverse{from,to} \xB7 edge.set{from,to,label?,kind?} \xB7 group.rename{from,to} \xB7 plan.set{title?,goal?} \xB7 review{ids[]} (these steps were looked at and need no change).",
5274
+ "node.add{label,id?,kind?,detail?,group?,files?,touches?,after?[]} \xB7 node.set{id,label?,kind?,detail?,group?,files?,touches?} \xB7 node.remove{id} \xB7 edge.add{from,to,label?,kind?,options?} \xB7 edge.remove{from,to} \xB7 edge.rewire{from,to,newFrom?,newTo?} \xB7 edge.reverse{from,to} \xB7 edge.set{from,to,label?,kind?,options?} \xB7 group.rename{from,to} \xB7 plan.set{title?,goal?} \xB7 review{ids[]} (these steps were looked at and need no change).",
5127
5275
  "An arrow from\u2192to means `to` depends on `from`. An arrow's kind: needs (the default), after (order only), or a checkpoint where the person comes in before `to` starts: approve, ask, input. Use the step_* tools for status. While the plan is being executed your structural changes become a proposal for the person to accept; pass propose:true to do that while planning too, which is the right thing for a change the person has not asked for."
5128
5276
  ].join("\n"),
5129
5277
  inputSchema: {
@@ -5168,17 +5316,18 @@ You have it, and it is in progress.` };
5168
5316
  },
5169
5317
  {
5170
5318
  name: "step_ask",
5171
- description: 'A step behind an "ask" checkpoint waits for you to ask the person something before it starts. Ask it here, then end your turn: the answer is sent to you, and the step can start.',
5172
- inputSchema: { type: "object", required: ["id", "question"], properties: { plan: PLAN, id: STEP2, question: { type: "string", description: "what you need to know before this step, in a sentence or two" } } },
5319
+ description: 'A step behind an "ask" checkpoint waits for you to ask the person something before it starts. Ask it here, then end your turn: the answer is sent to you, and the step can start. Ask ONE question per call (several questions are several asks, one after the other), and when it has a few answers, give them as `options`: the person presses one, or writes their own.',
5320
+ inputSchema: { type: "object", required: ["id", "question"], properties: { plan: PLAN, id: STEP2, question: { type: "string", description: "the one thing you need to know before this step, in a sentence or two" }, options: OPTIONS } },
5173
5321
  async run(args2, s, ctx) {
5174
5322
  const planId = planOf(ctx, args2.plan);
5175
5323
  const id = str(args2.id, "id");
5176
5324
  const question = str(args2.question, "question");
5325
+ const options = args2.options === void 0 ? void 0 : args2.options;
5177
5326
  const { plan } = viewOf(ctx, planId);
5178
5327
  if (!plan.nodes[id]) throw new HttpError(404, `there is no step ${id} in ${planId}`);
5179
5328
  const asks = plan.edges.filter((e) => e.to === id && e.kind === "ask" && !e.passed);
5180
5329
  if (!asks.length) return { error: true, text: `${id} has no "ask" checkpoint waiting. If you need the person anyway, use step_wait on the step you are on.` };
5181
- const { reply: _reply, ...outcome } = await send(ctx, s, planId, asks.map((e) => ({ op: "gate.ask", from: e.from, to: id, question })), { reason: `asked before ${id}` });
5330
+ const { reply: _reply, ...outcome } = await send(ctx, s, planId, asks.map((e) => ({ op: "gate.ask", from: e.from, to: id, question, ...options !== void 0 ? { options } : {} })), { reason: `asked before ${id}` });
5182
5331
  if (outcome.error) return outcome;
5183
5332
  return { ...outcome, text: `${outcome.text}
5184
5333
 
@@ -5460,7 +5609,7 @@ function stepsToOps(steps) {
5460
5609
  if (typeof a === "string") return { id: a };
5461
5610
  if (a && typeof a === "object" && typeof /** @type {any} */
5462
5611
  a.id === "string") return (
5463
- /** @type {{ id: string, kind?: unknown, label?: unknown }} */
5612
+ /** @type {{ id: string, kind?: unknown, label?: unknown, options?: unknown }} */
5464
5613
  a
5465
5614
  );
5466
5615
  throw new HttpError(400, 'each "after" entry is a step id, or { id, kind, label }');
@@ -5477,7 +5626,8 @@ function stepsToOps(steps) {
5477
5626
  place(a.id);
5478
5627
  const kind2 = typeof a.kind === "string" && a.kind !== "needs" ? a.kind : void 0;
5479
5628
  const label2 = typeof a.label === "string" && a.label.trim() ? a.label.trim() : void 0;
5480
- if (kind2 || label2) kinds.push({ op: "edge.set", from: a.id, to: id, ...kind2 ? { kind: kind2 } : {}, ...label2 ? { label: label2 } : {} });
5629
+ const options = Array.isArray(a.options) && a.options.length ? a.options : void 0;
5630
+ if (kind2 || label2 || options) kinds.push({ op: "edge.set", from: a.id, to: id, ...kind2 ? { kind: kind2 } : {}, ...label2 ? { label: label2 } : {}, ...options ? { options } : {} });
5481
5631
  }
5482
5632
  visiting.delete(id);
5483
5633
  placed.add(id);
@@ -5869,6 +6019,14 @@ Your last attempt tried "${r.refused}", which is refused here and ended the sess
5869
6019
  }
5870
6020
  };
5871
6021
  }
6022
+ function plainFailure(raw) {
6023
+ const t = raw.replace(ANSI, "");
6024
+ if (/api[ _-]?key|expired|unauthori[sz]ed|\b40[13]\b|invalid[^.]{0,30}(key|token)|credential|not configured|not (logged|signed) in|(sign|log)[ -]?in|authenticat/i.test(t)) return "OpenCode is not signed in (its key is missing or has expired, or no provider is set up). Run `opencode auth login` in a terminal, then ask again.";
6025
+ if (/could not run|ENOENT|installed/i.test(t)) return "OpenCode is not installed, or is not on the PATH.";
6026
+ if (/did not answer within/i.test(t)) return "OpenCode did not answer in time. A rate-limited model keeps trying in silence: ask again in a minute.";
6027
+ if (/rate.?limit|\b429\b|quota|overloaded/i.test(t)) return "OpenCode's model is busy or rate-limited right now. Ask again in a minute.";
6028
+ return "OpenCode could not answer. Run `opencode run hello` in a terminal to see why.";
6029
+ }
5872
6030
  function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs = 24e4 }, prompt) {
5873
6031
  return new Promise((resolve7, reject) => {
5874
6032
  const args2 = ["run", "--dir", root2, "--format", "json", "--agent", agent, ...model ? ["--model", model] : [], prompt];
@@ -5878,7 +6036,7 @@ function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs
5878
6036
  let err = "";
5879
6037
  const timer = setTimeout(() => {
5880
6038
  child.kill("SIGKILL");
5881
- reject(new Error(`OpenCode did not answer within ${Math.round(timeoutMs / 1e3)} seconds (a rate-limited model retries in silence)`));
6039
+ reject(new Error(plainFailure(`OpenCode did not answer within ${Math.round(timeoutMs / 1e3)} seconds`)));
5882
6040
  }, timeoutMs);
5883
6041
  child.stdout.on("data", (d) => {
5884
6042
  out += d;
@@ -5888,10 +6046,10 @@ function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs
5888
6046
  });
5889
6047
  child.on("error", (e) => {
5890
6048
  clearTimeout(timer);
5891
- reject(new Error(
6049
+ reject(new Error(plainFailure(
5892
6050
  /** @type {any} */
5893
6051
  e.code === "ENOENT" ? `could not run "${bin}": is OpenCode installed?` : e.message
5894
- ));
6052
+ )));
5895
6053
  });
5896
6054
  child.on("close", () => {
5897
6055
  clearTimeout(timer);
@@ -5899,14 +6057,14 @@ function once({ root: root2, model, agent = "plan", bin = "opencode", timeoutMs
5899
6057
  for (const line of out.split("\n")) {
5900
6058
  try {
5901
6059
  const e = JSON.parse(line);
5902
- if (e.type === "error") return reject(new Error(String(e.error?.data?.message ?? e.error?.name ?? "OpenCode reported an error")));
6060
+ if (e.type === "error") return reject(new Error(plainFailure(String(e.error?.data?.message ?? e.error?.name ?? "OpenCode reported an error"))));
5903
6061
  if (e.type === "text" && typeof e.part?.text === "string") texts.push(e.part.text);
5904
6062
  } catch {
5905
6063
  }
5906
6064
  }
5907
6065
  if (texts.length) return resolve7({ text: texts.join("\n") });
5908
6066
  const refused2 = /permission requested: (.+?); auto-rejecting/.exec(err.replace(ANSI, ""));
5909
- return refused2 ? resolve7({ refused: refused2[1] }) : reject(new Error(err.replace(ANSI, "").trim().split("\n").pop() || "OpenCode said nothing"));
6067
+ return refused2 ? resolve7({ refused: refused2[1] }) : reject(new Error(plainFailure(err.replace(ANSI, "").trim().split("\n").pop() || "OpenCode said nothing")));
5910
6068
  });
5911
6069
  });
5912
6070
  }
@@ -6743,6 +6901,44 @@ var EventRing = class {
6743
6901
  // packages/server/src/permissions.js
6744
6902
  import { EventEmitter as EventEmitter6 } from "node:events";
6745
6903
  import { randomBytes } from "node:crypto";
6904
+ function runsAnything(r) {
6905
+ if (r.toolName !== "Bash") return false;
6906
+ const c = (r.ruleContent ?? "").trim();
6907
+ if (!c || /^[*:\s]+$/.test(c)) return true;
6908
+ return /^(sudo|su|doas|eval|exec|xargs|env|ssh|nohup|watch|time|command)(\s|:|$)/.test(c) || /^(node|nodejs|deno|bun|python3?|ruby|perl|php|lua|bash|sh|zsh|fish|osascript|npx|pnpm dlx|yarn dlx|bunx|uvx)\s+(-e|-c|-r|-p|--eval|--print|--command|-i|exec|run|dlx|-x)\b/.test(c) || /^(npx|bunx|uvx|pnpx)(\s|:|$)/.test(c);
6909
+ }
6910
+ function alwaysFrom(suggestions) {
6911
+ if (!Array.isArray(suggestions)) return void 0;
6912
+ for (const s of suggestions) {
6913
+ if (!s || typeof s !== "object") continue;
6914
+ if (s.type === "setMode" && s.mode === "acceptEdits") return { label: "file edits", update: { type: "setMode", mode: "acceptEdits", destination: "session" } };
6915
+ if (s.type !== "addRules" || s.behavior !== "allow" || !Array.isArray(s.rules) || !s.rules.length || s.rules.length > 8) continue;
6916
+ if (s.rules.some((r) => r && typeof r.toolName === "string" && runsAnything({ toolName: r.toolName, ruleContent: typeof r.ruleContent === "string" ? r.ruleContent : void 0 }))) continue;
6917
+ if (s.rules.some((r) => r && r.toolName === "Bash" && typeof r.ruleContent === "string" && !/(:|\s)\*$/.test(r.ruleContent))) continue;
6918
+ const rules = [];
6919
+ for (const r of s.rules) {
6920
+ if (!r || typeof r.toolName !== "string" || !r.toolName || r.toolName.length > 200) break;
6921
+ if (r.ruleContent !== void 0 && (typeof r.ruleContent !== "string" || r.ruleContent.length > 500)) break;
6922
+ rules.push({ toolName: r.toolName, ...r.ruleContent !== void 0 ? { ruleContent: r.ruleContent } : {} });
6923
+ }
6924
+ if (rules.length !== s.rules.length) continue;
6925
+ const clip2 = (t) => {
6926
+ const one = t.replace(/\s+/g, " ").trim();
6927
+ return one.length > 50 ? `${one.slice(0, 49)}\u2026` : one;
6928
+ };
6929
+ const where = (r) => {
6930
+ const verb = { Read: "reading anything", Edit: "editing anything", Write: "writing anything", MultiEdit: "editing anything", Glob: "listing anything", Grep: "searching anything" }[
6931
+ /** @type {'Read'} */
6932
+ r.toolName
6933
+ ];
6934
+ const path = r.ruleContent?.match(/^(\/\/?[^*]*?)\/?\*\*$/)?.[1];
6935
+ return verb && path ? `${verb} under ${clip2(path.replace(/^\/\//, "/"))}` : void 0;
6936
+ };
6937
+ const words = [...new Set(rules.map((r) => where(r) ?? (r.toolName === "Bash" && r.ruleContent ? `${clip2(r.ruleContent.replace(/(:|\s)\*$/, ""))} commands` : r.ruleContent ? `${r.toolName}(${clip2(r.ruleContent)})` : /^mcp__/.test(r.toolName) ? `${r.toolName.replace(/^mcp__/, "").replace(/__/g, ": ")}` : `${r.toolName} calls`)))];
6938
+ return { label: words.join(", ").slice(0, 140), update: { type: "addRules", rules, behavior: "allow", destination: "session" } };
6939
+ }
6940
+ return void 0;
6941
+ }
6746
6942
  function describeRequest(tool, input2) {
6747
6943
  const clip2 = (s) => {
6748
6944
  const t = String(s ?? "").replace(/\s+/g, " ").trim();
@@ -6764,10 +6960,10 @@ var Permissions = class extends EventEmitter6 {
6764
6960
  /**
6765
6961
  * An agent asks. Resolves with your decision, or with nothing when it is answered elsewhere, `holdMs` passes, or the
6766
6962
  * request is cancelled (the hook went away). A newer prompt from the same session replaces an older one.
6767
- * @param {{ actor: string, session?: string, tool: string, input: Record<string, any>, holdMs: number }} ask
6963
+ * @param {{ actor: string, session?: string, tool: string, input: Record<string, any>, holdMs: number, suggestions?: unknown }} ask
6768
6964
  * @returns {{ permission: Permission, result: Promise<Decision | null>, cancel: () => void }}
6769
6965
  */
6770
- ask({ actor, session, tool, input: input2, holdMs }) {
6966
+ ask({ actor, session, tool, input: input2, holdMs, suggestions }) {
6771
6967
  this.heard(actor, session);
6772
6968
  const id = randomBytes(9).toString("base64url");
6773
6969
  let done = () => {
@@ -6776,14 +6972,15 @@ var Permissions = class extends EventEmitter6 {
6776
6972
  done = resolve7;
6777
6973
  });
6778
6974
  let timer;
6779
- const permission = { id, actor, ...session ? { session } : {}, tool, what: describeRequest(tool, input2), at: new Date(this.now()).toISOString() };
6975
+ const always = alwaysFrom(suggestions);
6976
+ const permission = { id, actor, ...session ? { session } : {}, tool, what: describeRequest(tool, input2), at: new Date(this.now()).toISOString(), ...always ? { always: { label: always.label } } : {} };
6780
6977
  const settle = (d) => {
6781
6978
  clearTimeout(timer);
6782
6979
  if (!this.pending.delete(id)) return;
6783
6980
  done(d);
6784
6981
  this.emit("change", { id, settled: d?.behavior ?? "released" });
6785
6982
  };
6786
- this.pending.set(id, { ...permission, settle });
6983
+ this.pending.set(id, { ...permission, settle, ...always ? { offer: always } : {} });
6787
6984
  timer = setTimeout(() => settle(null), holdMs);
6788
6985
  timer.unref?.();
6789
6986
  this.emit("change", { id, asked: true });
@@ -6791,16 +6988,18 @@ var Permissions = class extends EventEmitter6 {
6791
6988
  }
6792
6989
  /** The prompts waiting, oldest first, for one agent or all. @param {string} [actor] @returns {Permission[]} */
6793
6990
  list(actor) {
6794
- return [...this.pending.values()].filter((p) => !actor || p.actor === actor).map(({ settle: _s, ...p }) => p);
6991
+ return [...this.pending.values()].filter((p) => !actor || p.actor === actor).map(({ settle: _s, offer: _o, ...p }) => p);
6795
6992
  }
6796
6993
  /**
6797
6994
  * Your answer. @param {string} id @param {'allow' | 'deny'} decision @param {string} [reason] for a deny: the agent is told it
6798
- * @returns {boolean} whether it was still waiting
6995
+ * @param {boolean} [always] for an allow: and do not ask again for what Claude Code offered (this session only)
6996
+ * @returns {boolean | 'no-always'} whether it was still waiting; `no-always`: it was, but offered no such choice (nothing was answered)
6799
6997
  */
6800
- decide(id, decision, reason) {
6998
+ decide(id, decision, reason, always = false) {
6801
6999
  const p = this.pending.get(id);
6802
7000
  if (!p) return false;
6803
- p.settle(decision === "allow" ? { behavior: "allow" } : { behavior: "deny", message: reason?.trim() ? `The person denied this in the DiaCode editor: ${reason.trim().slice(0, 500)}` : "The person denied this in the DiaCode editor." });
7001
+ if (always && (decision !== "allow" || !p.offer)) return "no-always";
7002
+ p.settle(decision === "allow" ? { behavior: "allow", ...always && p.offer ? { updatedPermissions: [p.offer.update] } : {} } : { behavior: "deny", message: reason?.trim() ? `The person denied this in the DiaCode editor: ${reason.trim().slice(0, 500)}` : "The person denied this in the DiaCode editor." });
6804
7003
  return true;
6805
7004
  }
6806
7005
  /**
@@ -6836,6 +7035,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6836
7035
  const ring = new EventRing(100, { log: debug ? (line) => console.error(line) : void 0 });
6837
7036
  const store = new PlanStore(root2, { now });
6838
7037
  const archStore = new ArchStore(root2, { now });
7038
+ const opencodeReplans = rc.enabled ?? Boolean(rc.run || rc.auto || rc.model || rc.bin);
6839
7039
  const reconciler = new Reconciler(store, { run: rc.run ?? openCodeRunner({ root: root2, model: rc.model, bin: rc.bin }) });
6840
7040
  const presence = new Presence(presenceOptions);
6841
7041
  const repoFiles = new RepoFiles(root2);
@@ -6868,7 +7068,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6868
7068
  return agents2.map((a) => {
6869
7069
  const b = a.state === "gone" && on.has(a.actor) ? { ...a, state: "idle" } : a;
6870
7070
  const p = permissions.list(a.actor)[0];
6871
- return p ? { ...b, state: "asking", detail: `wants to ${p.what}`, permission: { id: p.id, what: p.what, tool: p.tool } } : b;
7071
+ return p ? { ...b, state: "asking", detail: `wants to ${p.what}`, permission: { id: p.id, what: p.what, tool: p.tool, ...p.always ? { always: p.always } : {} } } : b;
6872
7072
  });
6873
7073
  };
6874
7074
  const mcp = createMcp({ store, arch: archStore, presence, stopped: (actor) => calls.stoppedFor(actor), version: VERSION });
@@ -6890,7 +7090,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6890
7090
  (phase === "done" ? archStore.proposeLive(e.id) : archStore.proposeDrop(e.id)).catch((err) => ring.add("error", `architecture: the proposal for plan ${e.id} being ${phase}: ${err?.message ?? err}`));
6891
7091
  });
6892
7092
  const pending = /* @__PURE__ */ new Map();
6893
- if (rc.auto) {
7093
+ if (rc.auto && opencodeReplans) {
6894
7094
  store.on("change", (e) => {
6895
7095
  const failed = e.line?.actor !== "opencode:reconciler" && (e.line?.ops ?? []).find((o) => o.op === "status.set" && o.status === "failed");
6896
7096
  if (failed) {
@@ -6957,7 +7157,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
6957
7157
  }
6958
7158
  const url = new URL(req.url ?? "/", "http://localhost");
6959
7159
  const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
6960
- if (req.method === "GET" && url.pathname === "/api/health") return send2(res, 200, { ok: true, root: root2, version: VERSION, api: API_VERSION, schemas: [SCHEMA, "dcursed.plan/0", arch_exports.SCHEMA] });
7160
+ if (req.method === "GET" && url.pathname === "/api/health") return send2(res, 200, { ok: true, root: root2, version: VERSION, api: API_VERSION, schemas: [SCHEMA, "dcursed.plan/0", arch_exports.SCHEMA], replanner: opencodeReplans ? "opencode" : "agent" });
6961
7161
  if (req.method === "GET" && url.pathname === "/api/flow") {
6962
7162
  const f = flowNow({ store, arch: archStore, presence });
6963
7163
  const p2 = (
@@ -7047,12 +7247,13 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7047
7247
  if (parts.length === 2 && req.method === "GET") return send2(res, 200, { permissions: permissions.list() });
7048
7248
  if (parts.length === 3 && req.method === "POST") {
7049
7249
  if (whoOf(req).actor !== "you") throw new HttpError(403, "only you answer a permission prompt");
7050
- const { decision, reason } = (
7051
- /** @type {{ decision?: unknown, reason?: unknown }} */
7250
+ const { decision, reason, always } = (
7251
+ /** @type {{ decision?: unknown, reason?: unknown, always?: unknown }} */
7052
7252
  await body(req)
7053
7253
  );
7054
7254
  if (decision !== "allow" && decision !== "deny") throw new HttpError(400, "decision is allow or deny");
7055
- const ok2 = permissions.decide(parts[2], decision, typeof reason === "string" ? reason : void 0);
7255
+ const ok2 = permissions.decide(parts[2], decision, typeof reason === "string" ? reason : void 0, always === true);
7256
+ if (ok2 === "no-always") return send2(res, 409, { error: `Claude Code offered no "don't ask again" for this one: allow it once, or deny it` });
7056
7257
  return send2(res, ok2 ? 200 : 404, ok2 ? { ok: true } : { error: "that prompt is no longer waiting: it was answered in the agent's window, or it went away" });
7057
7258
  }
7058
7259
  }
@@ -7094,7 +7295,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7094
7295
  }
7095
7296
  if (req.method === "GET" && parts[0] === "api" && parts[1] === "events" && parts.length === 2) return listEvents(req, res);
7096
7297
  if (parts[0] === "api" && parts[1] === "architecture") {
7097
- if (parts.length === 2 && req.method === "GET") return send2(res, 200, archStore.exists ? { ...archStore.get(), listening: calls.listening(), calls: calls.list(ARCH_SCOPE).slice(0, 5) } : archStore.get());
7298
+ if (parts.length === 2 && req.method === "GET") return send2(res, 200, archStore.exists ? { ...archStore.get(), listening: calls.listening(), calls: calls.list(ARCH_SCOPE).slice(0, 8) } : archStore.get());
7098
7299
  if (parts.length === 2 && req.method === "POST") return send2(res, 201, await archStore.create(
7099
7300
  /** @type {any} */
7100
7301
  await body(req),
@@ -7155,6 +7356,12 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7155
7356
  /** @type {{ steps?: unknown, kind?: unknown, step?: unknown }} */
7156
7357
  await body(req)
7157
7358
  );
7359
+ if (!opencodeReplans) {
7360
+ if (kind !== void 0 && kind !== "review" && kind !== "failure" && kind !== "drift") throw new HttpError(400, "kind is review, failure or drift");
7361
+ if (kind === "failure" && typeof step3 !== "string") throw new HttpError(400, 'a failure re-plan names the step that failed: { kind: "failure", step }');
7362
+ if (steps !== void 0 && !(Array.isArray(steps) && steps.every((s) => typeof s === "string"))) throw new HttpError(400, "steps is a list of step ids");
7363
+ return send2(res, 202, { call: calls.askAgent(id, { kind: kind === "failure" || kind === "drift" ? kind : "review", ...typeof step3 === "string" ? { step: step3 } : {}, ...Array.isArray(steps) ? { steps } : {} }) });
7364
+ }
7158
7365
  if (kind === "failure") {
7159
7366
  if (typeof step3 !== "string") throw new HttpError(400, 'a failure re-plan names the step that failed: { kind: "failure", step }');
7160
7367
  return send2(res, 202, { job: reconciler.startFailure(id, step3) });
@@ -7164,6 +7371,16 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7164
7371
  if (steps !== void 0 && !(Array.isArray(steps) && steps.every((s) => typeof s === "string"))) throw new HttpError(400, "steps is a list of step ids");
7165
7372
  return send2(res, 202, { job: reconciler.start(id, steps) });
7166
7373
  }
7374
+ if (parts.length === 4 && parts[3] === "drift" && req.method === "POST") {
7375
+ if (whoOf(req).actor !== "you") throw new HttpError(403, "only you decide that a file outside the plan needs no step");
7376
+ const { ignore } = (
7377
+ /** @type {{ ignore?: unknown }} */
7378
+ await body(req)
7379
+ );
7380
+ if (ignore !== true && typeof ignore !== "string") throw new HttpError(400, "ignore is a file path, or true for all of them");
7381
+ store.get(id);
7382
+ return send2(res, 200, { ignored: store.ignoreOutside(id, ignore === true ? void 0 : ignore) });
7383
+ }
7167
7384
  if (parts.length === 4 && parts[3] === "observe" && req.method === "POST") {
7168
7385
  const who = whoOf(req);
7169
7386
  if (who.actor === "you") throw new HttpError(400, "observe is for a harness plugin: send x-dcursed-agent: <harness>:<agent>");
@@ -7199,7 +7416,7 @@ function createServer({ root: root2, port: port2 = 7300, host = "127.0.0.1", all
7199
7416
  function plan(id) {
7200
7417
  const view = store.get(id);
7201
7418
  const stalled = presence.stalled(view.plan);
7202
- return { ...view, reconcile: reconciler.job(id), presence: heard(presence.list(id)), reads: receipts(id), listening: calls.listening(), stopping: stoppingOn(id), calls: calls.list(id).slice(0, 5), drift: store.driftOf(id), ...view.derived ? { derived: { ...view.derived, stalled } } : {} };
7419
+ return { ...view, replanner: opencodeReplans ? "opencode" : "agent", ...opencodeReplans ? {} : { replanAgent: calls.worker(id) }, reconcile: reconciler.job(id), presence: heard(presence.list(id)), reads: receipts(id), listening: calls.listening(), stopping: stoppingOn(id), calls: calls.list(id).slice(0, 8), drift: store.driftOf(id), ...view.derived ? { derived: { ...view.derived, stalled } } : {} };
7203
7420
  }
7204
7421
  function stoppingOn(id) {
7205
7422
  return [...calls.stops.keys()].filter((actor) => calls.stoppedFor(actor) === id).sort();
@@ -7341,7 +7558,8 @@ data: ${JSON.stringify(data)}
7341
7558
  }
7342
7559
  const session = typeof payload.session_id === "string" ? payload.session_id : void 0;
7343
7560
  const input2 = payload.tool_input && typeof payload.tool_input === "object" ? payload.tool_input : {};
7344
- const asked = permissions.ask({ actor, session, tool, input: input2, holdMs: holdOf(url, HOLD.hook) });
7561
+ if (debug) ring.add("hook", `permission ${tool}: suggestions ${JSON.stringify(payload.permission_suggestions ?? null).slice(0, 600)}`);
7562
+ const asked = permissions.ask({ actor, session, tool, input: input2, holdMs: holdOf(url, HOLD.hook), suggestions: payload.permission_suggestions });
7345
7563
  const pid = Number(url.searchParams.get("pid"));
7346
7564
  agents.handle(actor, { event: "asking", session, detail: `wants to ${asked.permission.what}`, ...Number.isInteger(pid) && pid > 1 ? { pid } : {} }).catch(() => {
7347
7565
  });
@@ -7577,6 +7795,25 @@ var askHook = (port2, harness, hook, agent) => `curl -s --max-time 2 -X POST -H
7577
7795
  var ALLOW_TOOLS = "mcp__dcursed";
7578
7796
  var WAKE_SECONDS = 86400;
7579
7797
  var wakeHook = (port2, harness, agent) => `out=$(curl -sf --max-time ${WAKE_SECONDS - 30} -X POST -H 'content-type: application/json' --data-binary @- 'http://127.0.0.1:${port2}/hooks/${harness}/wake?agent=${agent}&hold=${(WAKE_SECONDS - 40) * 1e3}') && [ -n "$out" ] && { printf '%s' "$out" >&2; exit 2; }; exit 0`;
7798
+ var ACCEPT_EDITS_WORDS = [
7799
+ "Accept edits is on for this folder (you asked for it with --accept-edits): Claude Code now edits and writes files in it, and runs",
7800
+ "mkdir, touch, rm, rmdir, mv, cp and sed on files in it, without asking. Everything else (npm, node, git, curl\u2026) still asks, and so",
7801
+ "does anything outside this folder. It is in .claude/settings.local.json, which is not committed. `init claude-code --remove` takes it out again.",
7802
+ "Claude Code's folder-trust dialog lists the allow rule (mcp__dcursed) but does not mention this mode, so this message, `doctor` and that file are where it is written down."
7803
+ ];
7804
+ async function setAcceptEdits(root2) {
7805
+ const rel = ".claude/settings.local.json";
7806
+ const path = join4(root2, rel);
7807
+ const { data, ok: ok2 } = await readJson(path);
7808
+ if (!ok2) return [`NOT DONE ${rel}: it has comments or is not plain JSON, so add this yourself:
7809
+ "permissions": { "defaultMode": "acceptEdits" }`];
7810
+ const was = data?.permissions?.defaultMode;
7811
+ if (was !== void 0 && was !== "acceptEdits" && was !== "default") return [`NOT DONE ${rel}: "permissions.defaultMode" is "${was}" there, so it was left as it is. Set it to "acceptEdits" yourself if you want accept edits.`];
7812
+ data.permissions = data.permissions ?? {};
7813
+ data.permissions.defaultMode = "acceptEdits";
7814
+ return [await put(path, `${JSON.stringify(data, null, 2)}
7815
+ `, `${rel} (Claude Code's mode: accept edits)`), ...ACCEPT_EDITS_WORDS];
7816
+ }
7580
7817
  var PERMISSION_SECONDS = 600;
7581
7818
  var permissionHook = (port2, harness, agent) => `out=$(curl -sf --max-time ${PERMISSION_SECONDS - 10} -X POST -H 'content-type: application/json' --data-binary @- 'http://127.0.0.1:${port2}/hooks/${harness}/permission?agent=${agent}&hold=${(PERMISSION_SECONDS - 20) * 1e3}&pid='"$PPID") && printf '%s' "$out"; exit 0`;
7582
7819
  var ownRules = (root2, rel, text2, what) => put(join4(root2, rel), text2, `${rel} (${what})`);
@@ -7615,7 +7852,7 @@ async function letGitSeeAgain(root2, rel) {
7615
7852
  await writeFile2(file, rest);
7616
7853
  return `updated ${file.startsWith(`${root2}/`) ? file.slice(root2.length + 1) : file} (our line for ${rel} removed)`;
7617
7854
  }
7618
- async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main", shared = false }) {
7855
+ async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main", shared = false, acceptEdits = false }) {
7619
7856
  const p = String(port2);
7620
7857
  const said = [];
7621
7858
  const url = `http://127.0.0.1:${p}/mcp/claude-code?agent=${encodeURIComponent(agent)}`;
@@ -7656,6 +7893,13 @@ async function initClaudeCode({ root: root2, port: port2 = 7300, agent = "main",
7656
7893
  const kept = await keepOutOfGit(root2, ".claude/settings.local.json");
7657
7894
  if (kept) said.push(kept);
7658
7895
  }
7896
+ if (acceptEdits) {
7897
+ said.push(...await setAcceptEdits(root2));
7898
+ if (shared) {
7899
+ const kept = await keepOutOfGit(root2, ".claude/settings.local.json");
7900
+ if (kept) said.push(kept);
7901
+ }
7902
+ }
7659
7903
  said.push(await ownRules(root2, ".claude/rules/dcursed.md", `${RULES_BODY}`, "how to work with the plan"));
7660
7904
  said.push("", FLOW_HINT, "", serveHint(port2), "Then start a new Claude Code session in this folder (approve the dcursed MCP server when asked).");
7661
7905
  return said;
@@ -7725,7 +7969,7 @@ ${RULES_BODY}`, "how to work with the plan"));
7725
7969
  return said;
7726
7970
  }
7727
7971
  var HARNESS_INIT = (
7728
- /** @type {Record<string, (o: { root: string, port?: number, agent?: string, shared?: boolean }) => Promise<string[]>>} */
7972
+ /** @type {Record<string, (o: { root: string, port?: number, agent?: string, shared?: boolean, acceptEdits?: boolean }) => Promise<string[]>>} */
7729
7973
  {
7730
7974
  opencode: initOpenCode,
7731
7975
  "claude-code": initClaudeCode,
@@ -7825,7 +8069,11 @@ async function removeClaudeCode({ root: root2 }) {
7825
8069
  pruneEmpty(d.permissions, "allow");
7826
8070
  pruneEmpty(d, "permissions");
7827
8071
  }
7828
- }, (d) => onlyOurs(d), /\/hooks\/claude-code\/|mcp__dcursed/, 'the hooks whose address contains /hooks/claude-code/, and the "mcp__dcursed" allow rule'));
8072
+ if (rel === ".claude/settings.local.json" && d.permissions?.defaultMode === "acceptEdits") {
8073
+ delete d.permissions.defaultMode;
8074
+ pruneEmpty(d, "permissions");
8075
+ }
8076
+ }, (d) => onlyOurs(d), /\/hooks\/claude-code\/|mcp__dcursed|"defaultMode":\s*"acceptEdits"/, 'the hooks whose address contains /hooks/claude-code/, the "mcp__dcursed" allow rule, and "defaultMode": "acceptEdits" in settings.local.json'));
7829
8077
  }
7830
8078
  said.push(await drop(root2, ".claude/rules/dcursed.md", "the rules"));
7831
8079
  const unhidden = await letGitSeeAgain(root2, ".claude/settings.local.json");
@@ -8001,6 +8249,8 @@ async function claudeCode(root2) {
8001
8249
  if (hookText.includes("/hooks/claude-code/Stop") && !hookText.includes(ALLOW_TOOLS)) {
8002
8250
  findings.push(note(`Claude Code asks permission before each plan call; init adds one rule, "${ALLOW_TOOLS}", that covers only the plan tools (run init again to add it, or skip it if you want the prompts)`));
8003
8251
  }
8252
+ const local = present[1] ?? "";
8253
+ if (/"defaultMode":\s*"acceptEdits"/.test(local)) findings.push(note("Claude Code is in accept-edits mode for this folder (.claude/settings.local.json): it edits files in the folder, and runs mkdir, touch, rm, rmdir, mv, cp and sed there, without asking. Everything else still asks. `init claude-code --remove` takes it out."));
8004
8254
  return { harness: "claude-code", label: "Claude Code", ports: [...mcp.ports, ...hooks.ports], findings };
8005
8255
  }
8006
8256
  async function cursor(root2) {
@@ -8092,6 +8342,25 @@ async function liveChecks(port2, root2, connections) {
8092
8342
  }
8093
8343
  return out;
8094
8344
  }
8345
+ async function replannerFindings(port2, connections) {
8346
+ let health = null;
8347
+ try {
8348
+ health = await (await fetch(`http://127.0.0.1:${port2}/api/health`, { signal: AbortSignal.timeout(1500) })).json();
8349
+ } catch {
8350
+ }
8351
+ if (health?.replanner === "opencode") {
8352
+ return [
8353
+ note("the re-plan buttons run a separate OpenCode session (the plan server was started with --reconcile or --reconciler-model); each ask is a model call"),
8354
+ onPath("opencode") ? note("opencode is on the PATH. Whether it is signed in is not checked here: if a button says it is not, run `opencode auth login`") : problem("opencode is not on the PATH, so the re-plan buttons cannot run it", "install OpenCode, or start the plan server without --reconcile and --reconciler-model so the buttons ask your agent")
8355
+ ];
8356
+ }
8357
+ const wakes = connections.filter((c) => c.harness === "claude-code" || c.harness === "opencode").map((c) => c.label);
8358
+ const others = connections.filter((c) => c.harness === "cursor" || c.harness === "antigravity").map((c) => c.label);
8359
+ return [
8360
+ wakes.length ? ok(`the re-plan buttons ask ${wakes.join(" or ")} (the agent you connected): it is woken and proposes the change, or says none is needed`) : note("the re-plan buttons ask the agent you connected, but none here can be woken by the editor: the editor then says so, and offers to add the file to a step or ignore it"),
8361
+ ...others.length ? [note(`${others.join(" and ")} cannot be woken by the editor, so a re-plan button there only says so; ask it yourself in its window`)] : []
8362
+ ];
8363
+ }
8095
8364
  async function diagnose({ root: root2, port: port2 }) {
8096
8365
  root2 = resolve4(root2);
8097
8366
  const sections = [];
@@ -8121,7 +8390,7 @@ async function diagnose({ root: root2, port: port2 }) {
8121
8390
  }
8122
8391
  sections.push({ title: "The plan server", findings: await liveChecks(chosen, root2, connections) });
8123
8392
  for (const c of connections) sections.push({ title: c.label, findings: c.findings });
8124
- sections.push({ title: "The reconciler", findings: [onPath("opencode") ? ok('opencode is on the PATH, so "Ask the reconciler" can run (each ask is a model call)') : note(`opencode is not on the PATH: the Review panel's "Ask the reconciler" and "Re-plan from this" need it. Agents and the editor work without it.`)] });
8393
+ sections.push({ title: "The re-planner", findings: await replannerFindings(chosen, connections) });
8125
8394
  const flags = `${resolve4(root2) === process.cwd() ? "" : ` --root ${root2}`} --port ${chosen}`;
8126
8395
  for (const s of sections) {
8127
8396
  const harness = connections.find((c) => c.label === s.title)?.harness;
@@ -8254,12 +8523,16 @@ var cmd = invocation();
8254
8523
  var usage = [
8255
8524
  `diacode ${VERSION}: a plan you and your coding agents share`,
8256
8525
  "",
8257
- `usage: ${cmd} init <opencode|claude-code|cursor|antigravity|all> [--root <repo>] [--port 7300] [--agent <name>] [--shared] [--remove]`,
8526
+ `usage: ${cmd} init <opencode|claude-code|cursor|antigravity|all> [--root <repo>] [--port 7300] [--agent <name>] [--shared] [--accept-edits] [--remove]`,
8258
8527
  " connect a repository to an agent (its MCP entry, hooks or plugin, and rules);",
8259
- " --shared puts Claude Code's hooks in the committed .claude/settings.json, not your own settings.local.json",
8528
+ " --shared puts Claude Code's hooks in the committed .claude/settings.json, not your own settings.local.json;",
8529
+ " --accept-edits (Claude Code only, off unless you ask) sets its mode to accept edits in settings.local.json: it then edits files in",
8530
+ " the folder, and runs mkdir, touch, rm, rmdir, mv, cp and sed there, without asking; --remove takes it out again",
8260
8531
  " --remove takes out again only what init wrote, and leaves your plans and your own settings",
8261
8532
  ` ${cmd} serve [--root <repo>] [--port 7300] [--reconcile auto|manual] [--reconciler-model <provider/model>]`,
8262
- " the plan server, and the editor at http://127.0.0.1:<port>/",
8533
+ " the plan server, and the editor at http://127.0.0.1:<port>/;",
8534
+ ' "Should the plan cover this?" and the other re-plan buttons ask the agent you connected; --reconcile or --reconciler-model',
8535
+ " make them run a separate OpenCode session instead (OpenCode must be installed and signed in)",
8263
8536
  ` ${cmd} doctor [--root <repo>] [--port <n>] [--report]`,
8264
8537
  " check that the repository, the agents and the server fit together;",
8265
8538
  " --report prints the findings with what the server has noticed, paths replaced, to paste into an issue",
@@ -8301,7 +8574,8 @@ if (args[0] === "--version" || args[0] === "-v" || args[0] === "version") {
8301
8574
  // Itself and nothing else, unless told: any page on a port such as :8080 is some other program's.
8302
8575
  // (`npm run dev` needs no flag: Vite's proxy presents the server's own origin for the dev page.)
8303
8576
  allowedOrigins: origins,
8304
- reconciler: { auto: option("reconcile", "manual") === "auto", model: option("reconciler-model"), bin: option("opencode") },
8577
+ // The re-planner buttons ask the agent you connected. OpenCode does that job only when you set it up for it, here.
8578
+ reconciler: { enabled: args.includes("--reconcile") || args.includes("--reconciler-model") || args.includes("--opencode"), auto: option("reconcile", "manual") === "auto", model: option("reconciler-model"), bin: option("opencode") },
8305
8579
  ...option("editor") ? { editor: resolve6(
8306
8580
  /** @type {string} */
8307
8581
  option("editor")
@@ -8355,13 +8629,21 @@ Use that one, or stop it first (Ctrl-C in its terminal, or kill ${lock.held.pid}
8355
8629
  } else if (args[0] === "init" && args[1] && (args[1] === "all" || args[1] in HARNESS_INIT)) {
8356
8630
  const which = args[1] === "all" ? Object.keys(HARNESS_INIT) : [args[1]];
8357
8631
  const remove = args.includes("--remove");
8632
+ if (args.includes("--accept-edits") && !which.includes("claude-code")) {
8633
+ console.error("--accept-edits is for Claude Code: use it with `init claude-code` (or `init all`).");
8634
+ process.exit(1);
8635
+ }
8636
+ if (args.includes("--accept-edits") && remove) {
8637
+ console.error("--accept-edits is for adding it; `init claude-code --remove` takes it out again.");
8638
+ process.exit(1);
8639
+ }
8358
8640
  for (const h of which) {
8359
8641
  console.log(`\u2500\u2500 ${h}`);
8360
8642
  if (remove) {
8361
8643
  for (const line of await HARNESS_REMOVE[h]({ root })) console.log(line);
8362
8644
  continue;
8363
8645
  }
8364
- for (const line of await HARNESS_INIT[h]({ root, port, ...option("agent") ? { agent: option("agent") } : {}, shared: args.includes("--shared") })) console.log(line);
8646
+ for (const line of await HARNESS_INIT[h]({ root, port, ...option("agent") ? { agent: option("agent") } : {}, shared: args.includes("--shared"), ...h === "claude-code" && args.includes("--accept-edits") ? { acceptEdits: true } : {} })) console.log(line);
8365
8647
  }
8366
8648
  if (remove) console.log(`
8367
8649
  Plans stay where they are: ${plansDir(root)}`);