@chosengeneration/light-code 0.46.0 → 0.56.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.
package/dist/cli.js CHANGED
@@ -39769,10 +39769,54 @@ var agentAssignmentSchema = external_exports.object({
39769
39769
  * has looked at the tab without editing anything. Storing the default verbatim would pin
39770
39770
  * every user to whatever it said the day they first opened it.
39771
39771
  */
39772
- prompt: external_exports.string().optional()
39772
+ prompt: external_exports.string().optional(),
39773
+ /**
39774
+ * Whether this specialist may read and search the workspace, overriding the role's default.
39775
+ *
39776
+ * On the assignment rather than the role because it depends on *who* is answering: a small
39777
+ * local model given five lookups can spend them all and answer worse, where a strong one
39778
+ * uses them well. Absent means the role's own default.
39779
+ */
39780
+ tools: external_exports.boolean().optional(),
39781
+ /**
39782
+ * Whether this specialist may change things, each change through the approval gate.
39783
+ *
39784
+ * Off by default everywhere. §12b's rule is that a consultant is read-only; this is the
39785
+ * deliberate exception, and it is per role because "the programmer may edit" and "the tester
39786
+ * may edit" are quite different decisions.
39787
+ */
39788
+ write: external_exports.boolean().optional(),
39789
+ /**
39790
+ * Whether this role is in play at all.
39791
+ *
39792
+ * Distinct from unassigning it, which is why both exist: unassigning forgets *who* answered,
39793
+ * and somebody switching a specialist off for one job does not want to lose the model, the
39794
+ * prompt and the flags they set up. Absent means on, so nothing changes for a config written
39795
+ * before this.
39796
+ */
39797
+ enabled: external_exports.boolean().optional()
39773
39798
  }).strict();
39799
+ var customRoleSchema = external_exports.object({
39800
+ id: external_exports.string().min(1),
39801
+ name: external_exports.string().min(1),
39802
+ summary: external_exports.string(),
39803
+ prompt: external_exports.string()
39804
+ });
39774
39805
  var agentsConfigSchema = external_exports.object({
39775
39806
  roles: external_exports.record(external_exports.string(), agentAssignmentSchema),
39807
+ /**
39808
+ * Roles the user invented, beyond the five built in.
39809
+ *
39810
+ * A role *is* its prompt, and the ones people ask for next are nearly always a reviewer with
39811
+ * a different one — security, performance, accessibility. Defining them here answers that
39812
+ * whole family without a code change each time, and without growing the fixed roster the
39813
+ * expert has to allocate from.
39814
+ *
39815
+ * Covered by the same user-scope rule as the rest of this block, and it is the sharpest part
39816
+ * of it: this is prose injected into a model that is then asked to advise on this
39817
+ * repository, so a workspace able to write it could define a reviewer that approves anything.
39818
+ */
39819
+ definitions: external_exports.array(customRoleSchema),
39776
39820
  /** Whether what a consultation costs is worth managing. See `agents/team.ts`. */
39777
39821
  budgetMatters: external_exports.boolean(),
39778
39822
  /** The Agent team mode instruction, when edited. The roster is always generated. */
@@ -43327,18 +43371,401 @@ var Conversation = class {
43327
43371
  }
43328
43372
  };
43329
43373
 
43374
+ // ../../packages/core/dist/agents/roles.js
43375
+ var AGENT_ROLES = ["expert", "programmer", "reviewer", "tester", "librarian"];
43376
+ var CUSTOM_ROLE_LIMIT = 5;
43377
+ var ROLE_ID = /^[a-z][a-z0-9-]{1,23}$/;
43378
+ function isValidRoleId(id) {
43379
+ return ROLE_ID.test(id) && !AGENT_ROLES.includes(id);
43380
+ }
43381
+ function isAgentRole(value, custom2 = []) {
43382
+ return AGENT_ROLES.includes(value) || custom2.some((role) => role.id === value);
43383
+ }
43384
+ function knownRoles(custom2 = []) {
43385
+ return [...AGENT_ROLES, ...custom2.map((role) => role.id)];
43386
+ }
43387
+ var SHARED_TAIL = [
43388
+ "Your reply is advice. The assistant will check it against the real code before acting, and it",
43389
+ "is responsible for the result. Be concrete, say what you are unsure about, and say plainly when",
43390
+ "something must be verified rather than assumed.",
43391
+ "",
43392
+ "Answer in prose and short lists. No preamble about being happy to help."
43393
+ ];
43394
+ var MAY_WRITE = [
43395
+ "",
43396
+ "You can also change this workspace: edit files, and record a skill. Every such change is shown",
43397
+ "to the user and approved by them before it happens, so make each one small enough to read and",
43398
+ "say what it is for. Prefer telling the assistant what to change where the change is large or",
43399
+ "spans files \u2014 it has the whole picture and you have only what you asked for."
43400
+ ].join("\n");
43401
+ var SHARED_WITH_TOOLS = [
43402
+ "You can read this workspace: open files, list them, and search. Use that rather than guessing,",
43403
+ "and rather than asking the assistant for something you can fetch yourself. You have a small",
43404
+ "budget of lookups, so go for what actually settles the question.",
43405
+ "",
43406
+ "You cannot edit anything, run anything, or reach the network. If something needs changing, say",
43407
+ "what and why \u2014 the assistant makes the change and is responsible for it.",
43408
+ "",
43409
+ ...SHARED_TAIL
43410
+ ].join("\n");
43411
+ var SHARED_BLIND = [
43412
+ "You have no tools and cannot see the workspace. Everything you have is in the question. If",
43413
+ "something essential is missing, say exactly what you need and why, then give the best answer you",
43414
+ "can without it \u2014 never refuse to answer.",
43415
+ "",
43416
+ ...SHARED_TAIL
43417
+ ].join("\n");
43418
+ function specialistPreamble(usesTools, canWrite = false) {
43419
+ const base = usesTools ? SHARED_WITH_TOOLS : SHARED_BLIND;
43420
+ return canWrite ? `${base}${MAY_WRITE}` : base;
43421
+ }
43422
+ var DEFINITIONS = {
43423
+ expert: {
43424
+ name: "Expert",
43425
+ summary: "Hard problems, architecture, and deciding what to do",
43426
+ /* Planning a change means knowing what is already there, and it spans files the asker
43427
+ * cannot paste all of. */
43428
+ usesTools: true,
43429
+ canWrite: false,
43430
+ prompt: [
43431
+ "You are a senior engineer being consulted by another AI assistant that is doing the work.",
43432
+ "",
43433
+ "It has hit something hard: a change across several files to plan, a bug it has already",
43434
+ "failed to fix, or a design choice with no obvious answer. Give it your judgement.",
43435
+ "",
43436
+ "Decide *what* should happen and why. Leave the typing to the assistant \u2014 it is the one",
43437
+ "making the change and answering for it. Where there is a real trade-off, name both sides",
43438
+ "and then choose."
43439
+ ].join("\n")
43440
+ },
43441
+ programmer: {
43442
+ name: "Programmer",
43443
+ summary: "Writes the code once the plan is settled",
43444
+ /* It is handed a spec and the surrounding code and asked to write. Looking around buys
43445
+ * a slower answer that is no better. */
43446
+ usesTools: false,
43447
+ canWrite: false,
43448
+ prompt: [
43449
+ "You are an experienced programmer writing code for another AI assistant to apply.",
43450
+ "",
43451
+ "You are given a requirement and the surrounding code. Produce the change, matching the",
43452
+ "conventions of what you were shown rather than your own preferences \u2014 the naming, the error",
43453
+ "handling, the comment density, the way the existing code does this sort of thing.",
43454
+ "",
43455
+ "Return the code and a short note on anything non-obvious in it. Do not narrate what you are",
43456
+ "about to do, and do not rewrite things you were not asked to change.",
43457
+ "",
43458
+ /*
43459
+ * The programmer is the role that gets its own work handed back, so it is the one that has
43460
+ * to be told what to do with a review — including that it may disagree. Requested in those
43461
+ * terms: it is classified as the programmer, so fixing it is its job, and it should be able
43462
+ * to challenge a reviewer rather than obey one.
43463
+ */
43464
+ "You may be given a review of code you wrote. Fix what is genuinely wrong and return the",
43465
+ "corrected code the same way. **Where the review is wrong, say so and say why** \u2014 a finding",
43466
+ "can be about a path that cannot happen, a convention this codebase does not follow, or a",
43467
+ "misreading of a fragment. Do not rewrite working code to satisfy an objection you think is",
43468
+ "mistaken; the assistant has the real file and will settle it. Changing something you believe",
43469
+ "is right, because you were told to, is the worse failure: it looks like agreement."
43470
+ ].join("\n")
43471
+ },
43472
+ reviewer: {
43473
+ name: "Reviewer",
43474
+ summary: "Reads a change and says what is wrong with it",
43475
+ /* Most of what a review turns on is *around* the diff — the callers, the neighbouring
43476
+ * function, whether this convention is really the convention. */
43477
+ usesTools: true,
43478
+ canWrite: false,
43479
+ prompt: [
43480
+ "You are reviewing a change written by another AI assistant.",
43481
+ "",
43482
+ "Your job is to find what is wrong with it. Say so plainly when something is fine, but do",
43483
+ "not pad the review with praise \u2014 an approving review that missed a bug is worse than no",
43484
+ "review, because it was believed.",
43485
+ "",
43486
+ "Look for, in this order: does it do what was asked; does it break something that used to",
43487
+ "work; what happens at the edges \u2014 empty, missing, concurrent, already-exists, fails halfway;",
43488
+ "and does it match the conventions of the code around it.",
43489
+ "",
43490
+ "For each finding say what breaks and under what input. A concern you cannot make concrete is",
43491
+ "worth one sentence, flagged as a hunch, not a paragraph.",
43492
+ "",
43493
+ // Findings go back to whoever wrote the code, which may disagree. Concrete ones can be
43494
+ // settled against the file; vague ones turn into an argument nobody can end.
43495
+ "Your findings may be put to the person who wrote the code, who can disagree with them. That",
43496
+ "is why each one needs an input and an outcome: a finding stated concretely can be checked",
43497
+ "against the real file and settled, and one stated as a preference cannot."
43498
+ ].join("\n")
43499
+ },
43500
+ tester: {
43501
+ name: "Tester",
43502
+ summary: "Designs cases and finds what breaks it",
43503
+ /* The change is in front of it and the cases come from reasoning about it, not from
43504
+ * reading more of the codebase. */
43505
+ usesTools: false,
43506
+ canWrite: false,
43507
+ prompt: [
43508
+ "You design tests for code written by another AI assistant.",
43509
+ "",
43510
+ "Given a change, say what should be tested and why each case earns its place. Prefer the",
43511
+ "cases that would actually fail: boundaries, empty and missing values, the error path, the",
43512
+ "second call, the concurrent one, the one that fails halfway and has to be recovered from.",
43513
+ "",
43514
+ "A test that cannot fail is worth nothing \u2014 for each case you propose, say what bug it would",
43515
+ "catch. If the change is untestable as written, say what would have to change to make it",
43516
+ "testable rather than proposing a test that only asserts the code was executed."
43517
+ ].join("\n")
43518
+ },
43519
+ librarian: {
43520
+ name: "Librarian",
43521
+ summary: "Skills, internal documentation and house conventions",
43522
+ /* Its whole job is what has been written down here, so being unable to go and read it
43523
+ * left it answering from whatever happened to be pasted in. This is the role the flag
43524
+ * exists for. */
43525
+ usesTools: true,
43526
+ canWrite: false,
43527
+ prompt: [
43528
+ "You answer questions about how things are done here: internal libraries, house conventions,",
43529
+ "the shape of existing code, and what has already been written down.",
43530
+ "",
43531
+ "You are given whatever documentation, skills and code the assistant could find. Answer from",
43532
+ "that, and be explicit about the difference between what the material actually says and what",
43533
+ "you are inferring \u2014 a convention you guessed at, stated confidently, becomes the convention.",
43534
+ "",
43535
+ "If the material does not answer the question, say so and say what would. Do not fill the gap",
43536
+ "with how it is usually done elsewhere unless you label it as exactly that.",
43537
+ "",
43538
+ /*
43539
+ * The one specialist that may write, and only this one thing.
43540
+ *
43541
+ * The objection was never that the librarian should not record what it knows — it is the
43542
+ * role that can see the gap. It was that a consultation asks nobody, so a skill written
43543
+ * there would be prose injected into every later prompt that no human had read (§13's
43544
+ * persistent prompt-injection vector). That was answered by making this path *ask*:
43545
+ * `runConsultation` routes anything in ALWAYS_ASK_TOOLS through the same approval gate the
43546
+ * agent loop uses, so the user sees the source exactly as they would for any other write.
43547
+ *
43548
+ * Everything else stays read-only. `consultBoundary.test.ts` holds that line, and pins the
43549
+ * rule that any name allowed past the group filter must be one the gate will stop on.
43550
+ */
43551
+ "When the answer is something worth writing down \u2014 a convention you had to piece together,",
43552
+ "a gotcha that will catch the next person, a procedure that is currently only in somebody's",
43553
+ "head \u2014 say so and **write it with `write_skill`**. The user is shown the text and",
43554
+ "approves it before anything is recorded, so write it as it should stand rather than",
43555
+ "describing what it would say. If they decline, say what you would have written and why.",
43556
+ "",
43557
+ "Say plainly when something already written down is **wrong or out of date**. A stale skill",
43558
+ "is worse than a missing one, because it is believed."
43559
+ ].join("\n")
43560
+ }
43561
+ };
43562
+ function roleInfo(role, custom2 = []) {
43563
+ const builtIn = DEFINITIONS[role];
43564
+ if (builtIn !== void 0)
43565
+ return { role, ...builtIn };
43566
+ const defined = custom2.find((candidate) => candidate.id === role);
43567
+ if (defined !== void 0) {
43568
+ return {
43569
+ role,
43570
+ name: defined.name,
43571
+ summary: defined.summary,
43572
+ prompt: defined.prompt.trim(),
43573
+ /*
43574
+ * Custom roles get tools by default.
43575
+ *
43576
+ * They are overwhelmingly reviewers of some particular kind — security, performance,
43577
+ * accessibility — and those all turn on code the asker did not think to paste. The flag is
43578
+ * there to turn it off for the ones that are really "write this to spec".
43579
+ */
43580
+ usesTools: defined.usesTools !== false,
43581
+ // Off unless asked for: a role invented in a hurry should not be able to edit the
43582
+ // repository because nobody thought about the box.
43583
+ canWrite: defined.canWrite === true
43584
+ };
43585
+ }
43586
+ return {
43587
+ role,
43588
+ name: role,
43589
+ summary: "This role is no longer defined.",
43590
+ prompt: "",
43591
+ usesTools: false,
43592
+ canWrite: false
43593
+ };
43594
+ }
43595
+ function allRoles(custom2 = []) {
43596
+ return knownRoles(custom2).map((role) => roleInfo(role, custom2));
43597
+ }
43598
+ function defaultPromptFor(role, custom2 = []) {
43599
+ return roleInfo(role, custom2).prompt;
43600
+ }
43601
+ function buildAgentPrompt(options) {
43602
+ const lines = [
43603
+ options.prompt.trim(),
43604
+ "",
43605
+ specialistPreamble(options.usesTools, options.canWrite === true)
43606
+ ];
43607
+ if (options.briefing !== void 0 && options.briefing.trim().length > 0) {
43608
+ lines.push("", options.briefing);
43609
+ }
43610
+ lines.push("", "---", "", options.question);
43611
+ if (options.files !== void 0 && options.files.length > 0) {
43612
+ lines.push("", options.usesTools ? "The assistant named these files as relevant. Start there \u2014 you can open them yourself:" : "The assistant named these files as relevant. You cannot open them \u2014 they are listed so you know what it is looking at:", ...options.files.map((file2) => `- ${file2}`));
43613
+ }
43614
+ return lines.join("\n");
43615
+ }
43616
+
43617
+ // ../../packages/core/dist/agent/checkpoints.js
43618
+ var MAX_CHECKPOINTS = 50;
43619
+ var LIST_ITEM = /^(\s*)(?:([-*•])|(\d+)[.)])\s+(.+)$/;
43620
+ function idFor(text) {
43621
+ let hash2 = 2166136261;
43622
+ for (let index = 0; index < text.length; index += 1) {
43623
+ hash2 ^= text.charCodeAt(index);
43624
+ hash2 = Math.imul(hash2, 16777619) >>> 0;
43625
+ }
43626
+ return hash2.toString(36);
43627
+ }
43628
+ function normalise(text) {
43629
+ return text.trim().toLowerCase().replace(/\s+/g, " ").replace(/[.;,:]+$/, "");
43630
+ }
43631
+ function parseCheckpoints(plan) {
43632
+ const lines = (plan ?? "").split(/\r?\n/);
43633
+ const items = [];
43634
+ lines.forEach((line, index) => {
43635
+ const match = LIST_ITEM.exec(line);
43636
+ if (match === null)
43637
+ return;
43638
+ const text = match[4]?.trim() ?? "";
43639
+ if (text.length === 0)
43640
+ return;
43641
+ items.push({
43642
+ indent: (match[1] ?? "").replace(/\t/g, " ").length,
43643
+ ordered: match[3] !== void 0,
43644
+ text,
43645
+ line: index
43646
+ });
43647
+ });
43648
+ const ordered = items.filter((item) => item.ordered);
43649
+ const candidates = ordered.length > 0 ? ordered : items;
43650
+ const shallowest = candidates.reduce((least, item) => Math.min(least, item.indent), Number.POSITIVE_INFINITY);
43651
+ const steps = candidates.filter((item) => item.indent === shallowest);
43652
+ const texts = steps.length > 0 ? steps : (
43653
+ // No list at all: plenty of people write a plan as bare lines, and a progress view that
43654
+ // only worked for bullet-point authors would read as broken.
43655
+ lines.map((line, index) => ({ indent: 0, ordered: false, text: line.trim(), line: index })).filter((item) => item.text.length > 0)
43656
+ );
43657
+ const chosen = texts.slice(0, MAX_CHECKPOINTS);
43658
+ const seen = /* @__PURE__ */ new Map();
43659
+ return chosen.map((item, position) => {
43660
+ const key = normalise(item.text);
43661
+ const occurrence = (seen.get(key) ?? 0) + 1;
43662
+ seen.set(key, occurrence);
43663
+ const until = chosen[position + 1]?.line ?? lines.length;
43664
+ return {
43665
+ id: occurrence === 1 ? idFor(key) : `${idFor(key)}-${String(occurrence)}`,
43666
+ index: position + 1,
43667
+ text: item.text,
43668
+ /*
43669
+ * Who the plan says should be involved, read from the step *and everything under it* —
43670
+ * which is where the allocation actually lives, since a specialist is usually named on a
43671
+ * continuation line ("Owner: reviewer") or inside a sub-point rather than in the heading.
43672
+ */
43673
+ plannedRoles: rolesMentionedIn(lines.slice(item.line, until).join(" "))
43674
+ };
43675
+ });
43676
+ }
43677
+ function rolesMentionedIn(text) {
43678
+ const haystack = text.toLowerCase();
43679
+ return AGENT_ROLES.filter((role) => new RegExp(`\\b${role}\\b`).test(haystack));
43680
+ }
43681
+ function checkpointViews(plan, progress) {
43682
+ return parseCheckpoints(plan).map((checkpoint) => {
43683
+ const recorded = progress?.[checkpoint.id];
43684
+ return {
43685
+ ...checkpoint,
43686
+ status: recorded?.status ?? "todo",
43687
+ roles: recorded?.roles ?? []
43688
+ };
43689
+ });
43690
+ }
43691
+ function pruneProgress(plan, progress) {
43692
+ if (progress === void 0)
43693
+ return {};
43694
+ const live = new Set(parseCheckpoints(plan).map((checkpoint) => checkpoint.id));
43695
+ const kept = {};
43696
+ for (const [id, entry] of Object.entries(progress))
43697
+ if (live.has(id))
43698
+ kept[id] = entry;
43699
+ return kept;
43700
+ }
43701
+ function markCheckpoint(plan, progress, index, status) {
43702
+ const checkpoint = parseCheckpoints(plan).find((candidate) => candidate.index === index);
43703
+ if (checkpoint === void 0)
43704
+ return void 0;
43705
+ const existing = progress[checkpoint.id];
43706
+ return {
43707
+ ...progress,
43708
+ [checkpoint.id]: {
43709
+ status,
43710
+ // Kept across a start→done transition: the specialists consulted while the step was being
43711
+ // worked are exactly the ones that contributed to finishing it.
43712
+ roles: existing?.roles ?? [],
43713
+ at: Date.now()
43714
+ }
43715
+ };
43716
+ }
43717
+ function attributeConsultation(progress, role) {
43718
+ const entry = Object.entries(progress).find(([, value2]) => value2.status === "active");
43719
+ if (entry === void 0)
43720
+ return progress;
43721
+ const [id, value] = entry;
43722
+ if (value.roles.includes(role))
43723
+ return progress;
43724
+ return { ...progress, [id]: { ...value, roles: [...value.roles, role] } };
43725
+ }
43726
+ function progressSummary(views) {
43727
+ const done = views.filter((view) => view.status === "done").length;
43728
+ return `${String(done)}/${String(views.length)}`;
43729
+ }
43730
+
43330
43731
  // ../../packages/core/dist/agent/plan.js
43331
43732
  var PLAN_LIMIT = 4e3;
43332
43733
  function buildPlanGuidance(plan) {
43333
43734
  const trimmed = plan?.trim() ?? "";
43334
43735
  if (trimmed.length === 0)
43335
43736
  return "";
43737
+ const checkpoints = parseCheckpoints(trimmed);
43738
+ const numbered = checkpoints.length > 0 ? [
43739
+ "",
43740
+ "Its steps are numbered as follows. These numbers are what `plan_progress` takes, and",
43741
+ "they are what the user sees:",
43742
+ "",
43743
+ ...checkpoints.map((checkpoint) => `${String(checkpoint.index)}. ${checkpoint.text}`)
43744
+ ] : [];
43336
43745
  return [
43337
43746
  "# The plan for this conversation",
43338
43747
  "",
43339
43748
  "The user set this. It is what you are here to do:",
43340
43749
  "",
43341
43750
  trimmed,
43751
+ ...numbered,
43752
+ "",
43753
+ "## Reporting where you are",
43754
+ "",
43755
+ "- **Call `plan_progress` with `active` when you start a step**, and with `done` when it is",
43756
+ " actually finished. The user watches this rather than reading the whole transcript, so a",
43757
+ " step marked done that is not done is worse than one never marked at all.",
43758
+ "- Work one step at a time. Marking three done at the end tells the user nothing while it",
43759
+ " matters, which is the only time it is useful.",
43760
+ "",
43761
+ "## Changing the plan",
43762
+ "",
43763
+ "- **You may propose a different plan with `update_plan`, and the user must approve it.**",
43764
+ " They are shown a diff of the plan they have against the one you are proposing. This is",
43765
+ " the only way the plan changes on your side \u2014 never act on a plan the user has not agreed.",
43766
+ "- Use it when you have worked out a better plan, including one a specialist drafted for you.",
43767
+ " Put the whole plan in it: it replaces what is there rather than adding to it.",
43768
+ "- If they decline, the existing plan still stands and you carry on with it.",
43342
43769
  "",
43343
43770
  "## Working to it",
43344
43771
  "",
@@ -43405,6 +43832,7 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
43405
43832
  } else if (options.pythonToolsAvailable === true) {
43406
43833
  lines.push("", "Python tools:", "- `create_python_tool` makes a real, registered, callable tool. Use it whenever the user", ' asks for a "tool", even if writing a script would be easier.', "- Writing a .py file with `write_to_file` does NOT create a tool. It is just a file, and", " nothing can call it. Never describe that as having created a tool.", "- `update_python_tool` edits one, `delete_python_tool` removes one.");
43407
43834
  }
43835
+ lines.push("", "Specialist roles:", "- The team of specialists is configurable, and you can change it. `read_role_prompt` shows", " what a role is told it is (no argument lists them all); `update_role` changes that, or a", " custom role's name, summary and workspace access.", "- `create_role` invents one \u2014 a security reviewer, say \u2014 and `delete_role` removes a custom", " one. The user approves each of these, seeing the whole role or a diff of it.", '- So "make the reviewer stricter" or "add a role that reviews SQL" is something to do, not', " something to explain how to do by hand.");
43408
43836
  if (options.skills !== void 0 || options.skillsSearchable === true) {
43409
43837
  lines.push("", "Skills, before anything else:", "- Check the skills for this workspace before you plan or answer. They record how *this*", " project works, and they exist because someone was tired of explaining it.", "- A skill that applies overrides your general knowledge. Do not restate a convention it", " contradicts.", ...options.teamSkillsAvailable === true ? [
43410
43838
  "- `search_team_skills` searches what OTHER people have taught their assistants. Use it",
@@ -43798,130 +44226,6 @@ ${withBudget}` : withBudget;
43798
44226
  };
43799
44227
  }
43800
44228
 
43801
- // ../../packages/core/dist/agents/roles.js
43802
- var AGENT_ROLES = ["expert", "programmer", "reviewer", "tester", "librarian"];
43803
- function isAgentRole(value) {
43804
- return AGENT_ROLES.includes(value);
43805
- }
43806
- var SHARED = [
43807
- "You cannot see the workspace and cannot read files, run commands or search. Everything you",
43808
- "have is in the question. If something essential is missing, say exactly what you need and why,",
43809
- "then give the best answer you can without it \u2014 never refuse to answer.",
43810
- "",
43811
- "Your reply is advice. The assistant will check it against the real code before acting, and it",
43812
- "is responsible for the result. Be concrete, say what you are unsure about, and say plainly when",
43813
- "something must be verified rather than assumed.",
43814
- "",
43815
- "Answer in prose and short lists. No preamble about being happy to help."
43816
- ].join("\n");
43817
- var DEFINITIONS = {
43818
- expert: {
43819
- name: "Expert",
43820
- summary: "Hard problems, architecture, and deciding what to do",
43821
- prompt: [
43822
- "You are a senior engineer being consulted by another AI assistant that is doing the work.",
43823
- "",
43824
- "It has hit something hard: a change across several files to plan, a bug it has already",
43825
- "failed to fix, or a design choice with no obvious answer. Give it your judgement.",
43826
- "",
43827
- "Decide *what* should happen and why. Leave the typing to the assistant \u2014 it has the files",
43828
- "open and you do not. Where there is a real trade-off, name both sides and then choose.",
43829
- "",
43830
- SHARED
43831
- ].join("\n")
43832
- },
43833
- programmer: {
43834
- name: "Programmer",
43835
- summary: "Writes the code once the plan is settled",
43836
- prompt: [
43837
- "You are an experienced programmer writing code for another AI assistant to apply.",
43838
- "",
43839
- "You are given a requirement and the surrounding code. Produce the change, matching the",
43840
- "conventions of what you were shown rather than your own preferences \u2014 the naming, the error",
43841
- "handling, the comment density, the way the existing code does this sort of thing.",
43842
- "",
43843
- "Return the code and a short note on anything non-obvious in it. Do not narrate what you are",
43844
- "about to do, and do not rewrite things you were not asked to change.",
43845
- "",
43846
- SHARED
43847
- ].join("\n")
43848
- },
43849
- reviewer: {
43850
- name: "Reviewer",
43851
- summary: "Reads a change and says what is wrong with it",
43852
- prompt: [
43853
- "You are reviewing a change written by another AI assistant.",
43854
- "",
43855
- "Your job is to find what is wrong with it. Say so plainly when something is fine, but do",
43856
- "not pad the review with praise \u2014 an approving review that missed a bug is worse than no",
43857
- "review, because it was believed.",
43858
- "",
43859
- "Look for, in this order: does it do what was asked; does it break something that used to",
43860
- "work; what happens at the edges \u2014 empty, missing, concurrent, already-exists, fails halfway;",
43861
- "and does it match the conventions of the code around it.",
43862
- "",
43863
- "For each finding say what breaks and under what input. A concern you cannot make concrete is",
43864
- "worth one sentence, flagged as a hunch, not a paragraph.",
43865
- "",
43866
- SHARED
43867
- ].join("\n")
43868
- },
43869
- tester: {
43870
- name: "Tester",
43871
- summary: "Designs cases and finds what breaks it",
43872
- prompt: [
43873
- "You design tests for code written by another AI assistant.",
43874
- "",
43875
- "Given a change, say what should be tested and why each case earns its place. Prefer the",
43876
- "cases that would actually fail: boundaries, empty and missing values, the error path, the",
43877
- "second call, the concurrent one, the one that fails halfway and has to be recovered from.",
43878
- "",
43879
- "A test that cannot fail is worth nothing \u2014 for each case you propose, say what bug it would",
43880
- "catch. If the change is untestable as written, say what would have to change to make it",
43881
- "testable rather than proposing a test that only asserts the code was executed.",
43882
- "",
43883
- SHARED
43884
- ].join("\n")
43885
- },
43886
- librarian: {
43887
- name: "Librarian",
43888
- summary: "Skills, internal documentation and house conventions",
43889
- prompt: [
43890
- "You answer questions about how things are done here: internal libraries, house conventions,",
43891
- "the shape of existing code, and what has already been written down.",
43892
- "",
43893
- "You are given whatever documentation, skills and code the assistant could find. Answer from",
43894
- "that, and be explicit about the difference between what the material actually says and what",
43895
- "you are inferring \u2014 a convention you guessed at, stated confidently, becomes the convention.",
43896
- "",
43897
- "If the material does not answer the question, say so and say what would. Do not fill the gap",
43898
- "with how it is usually done elsewhere unless you label it as exactly that.",
43899
- "",
43900
- SHARED
43901
- ].join("\n")
43902
- }
43903
- };
43904
- function roleInfo(role) {
43905
- return { role, ...DEFINITIONS[role] };
43906
- }
43907
- function allRoles() {
43908
- return AGENT_ROLES.map(roleInfo);
43909
- }
43910
- function defaultPromptFor(role) {
43911
- return DEFINITIONS[role].prompt;
43912
- }
43913
- function buildAgentPrompt(options) {
43914
- const lines = [options.prompt];
43915
- if (options.briefing !== void 0 && options.briefing.trim().length > 0) {
43916
- lines.push("", options.briefing);
43917
- }
43918
- lines.push("", "---", "", options.question);
43919
- if (options.files !== void 0 && options.files.length > 0) {
43920
- lines.push("", "The assistant named these files as relevant. You cannot open them \u2014 they are listed so you", "know what it is looking at:", ...options.files.map((file2) => `- ${file2}`));
43921
- }
43922
- return lines.join("\n");
43923
- }
43924
-
43925
44229
  // ../../packages/core/dist/tools/askAgent.js
43926
44230
  var paramsSchema3 = external_exports.object({
43927
44231
  role: external_exports.string().describe(`Which specialist to ask: ${AGENT_ROLES.join(", ")}. Only the ones assigned in Settings \u2192 Agents can answer.`),
@@ -43991,7 +44295,7 @@ Files named as relevant: ${params.files.join(", ")}` : "")
43991
44295
 
43992
44296
  ---
43993
44297
 
43994
- That is the ${role}'s advice, from ${result.label}, which has not seen your workspace. Check it against the actual code before acting on it, and say so if it turns out to be wrong.`
44298
+ ${trailerFor(agent, team)}`
43995
44299
  };
43996
44300
  }
43997
44301
  };
@@ -44007,6 +44311,22 @@ function describeTeam(team) {
44007
44311
  const usable = team.filter((agent) => agent.available).map((agent) => agent.role);
44008
44312
  return usable.length === 0 ? "None are assigned on this machine." : `Assigned here: ${usable.join(", ")}.`;
44009
44313
  }
44314
+ function trailerFor(agent, team) {
44315
+ const lines = [
44316
+ `That is the ${agent.role}'s advice, from ${agent.label}. ` + (agent.usesTools ? "It could read this workspace but cannot change anything in it." : "It has not seen your workspace \u2014 it answered from what you pasted.") + " Check it against the actual code before acting on it, and say so if it turns out to be wrong."
44317
+ ];
44318
+ const programmer = team.find((candidate) => candidate.role === "programmer" && candidate.available);
44319
+ if (agent.role === "reviewer" && programmer !== void 0) {
44320
+ lines.push("", "If the programmer wrote this code, take the findings back to it rather than fixing them yourself: paste the code as it stands, the findings in full, and anything you have already checked. It may disagree, and a disagreement is an answer \u2014 you have the real file and neither of them does, so you settle it and say which way you went. Re-review only if the fix was substantial enough that this review no longer describes the code.");
44321
+ }
44322
+ if (agent.role === "librarian") {
44323
+ lines.push("", "It can record a skill itself, and the user will have approved the text before it was written \u2014 so if it says it wrote one, that is done and not something to repeat. If it said something already written down is wrong or out of date, act on that: a stale skill is worse than a missing one, because it is believed.");
44324
+ }
44325
+ if (agent.role === "programmer") {
44326
+ lines.push("", "Check this against the real file before applying it \u2014 it was written from what you pasted, so it can miss a convention or a caller it was never shown.");
44327
+ }
44328
+ return lines.join("\n");
44329
+ }
44010
44330
 
44011
44331
  // ../../packages/core/dist/agents/team.js
44012
44332
  function defaultAssignment(role, context) {
@@ -44014,12 +44334,17 @@ function defaultAssignment(role, context) {
44014
44334
  }
44015
44335
  function resolveTeam(context) {
44016
44336
  const resolved = [];
44017
- for (const role of AGENT_ROLES) {
44337
+ const custom2 = context.config?.definitions ?? [];
44338
+ for (const role of knownRoles(custom2)) {
44018
44339
  const assignment = context.config?.roles?.[role] ?? defaultAssignment(role, context);
44019
44340
  if (assignment === void 0)
44020
44341
  continue;
44021
- const info = roleInfo(role);
44022
- const prompt = assignment.prompt ?? defaultPromptFor(role);
44342
+ if (assignment.enabled === false)
44343
+ continue;
44344
+ const info = roleInfo(role, custom2);
44345
+ const prompt = assignment.prompt ?? defaultPromptFor(role, custom2);
44346
+ const usesTools = assignment.tools ?? info.usesTools;
44347
+ const canWrite = assignment.write ?? info.canWrite;
44023
44348
  if (assignment.kind === "cli") {
44024
44349
  resolved.push({
44025
44350
  role,
@@ -44028,11 +44353,15 @@ function resolveTeam(context) {
44028
44353
  kind: "cli",
44029
44354
  label: "Claude",
44030
44355
  prompt,
44356
+ usesTools,
44357
+ canWrite,
44031
44358
  available: context.cliAvailable,
44032
44359
  ...context.cliAvailable ? {} : { reason: "The Claude CLI is not available on this machine." }
44033
44360
  });
44034
44361
  continue;
44035
44362
  }
44363
+ if (assignment.profileId === void 0)
44364
+ continue;
44036
44365
  const profile = context.profiles.find((candidate) => candidate.id === assignment.profileId);
44037
44366
  resolved.push({
44038
44367
  role,
@@ -44042,6 +44371,8 @@ function resolveTeam(context) {
44042
44371
  ...assignment.profileId !== void 0 ? { profileId: assignment.profileId } : {},
44043
44372
  label: profile?.label ?? assignment.profileId ?? "unassigned",
44044
44373
  prompt,
44374
+ usesTools,
44375
+ canWrite,
44045
44376
  available: profile !== void 0,
44046
44377
  /*
44047
44378
  * A profile that has been deleted leaves the role unavailable and says so, rather than
@@ -44063,12 +44394,52 @@ function budgetMatters(context) {
44063
44394
  // ../../packages/core/dist/agents/guidance.js
44064
44395
  var BUDGET_ADVICE = [
44065
44396
  "",
44066
- "## Consultations cost money here",
44397
+ "## Consultations cost money here",
44398
+ "",
44399
+ "Each one is charged. Make the first count \u2014 gather what is needed and ask one full question",
44400
+ "rather than opening with something you could have settled yourself. If a per-task budget runs",
44401
+ "out the specialist stops being available, and you finish the work alone, so spend it on the",
44402
+ "parts where another reader genuinely changes what you do."
44403
+ ].join("\n");
44404
+ var PLAN_FIRST = [
44405
+ "",
44406
+ "## Start by planning. This comes before everything else.",
44407
+ "",
44408
+ "**This conversation has no plan yet, so making one is your first job.** Before reading widely,",
44409
+ "before editing anything, before running anything:",
44410
+ "",
44411
+ "1. **Look at almost nothing first.** One `list_files` of the workspace root is usually the",
44412
+ " whole of it, plus any file the user actually named. That is enough to ask a good question.",
44413
+ " Do **not** survey the codebase, search the documentation index, hunt for skills, or read",
44414
+ " files to get a feel for the style \u2014 not yet. The specialist cannot see any of it anyway,",
44415
+ " and if it needs something specific it will say so and you can fetch it and ask again.",
44416
+ ' Announcing that you are "getting a sense of the workspace before proposing anything" is',
44417
+ " this instruction being broken, however reasonable it sounds.",
44418
+ "2. **Ask the expert for the plan** \u2014 give the task, the little you found and the constraints,",
44419
+ " and ask for numbered steps. A plan is the one thing worth asking for before the work rather",
44420
+ " than after it, and it is what the expert is for. An expert asked early enough to change the",
44421
+ " shape of the work is worth several times one asked to bless a direction already taken.",
44422
+ " **Ask it to say which specialist should be involved in which step**, from the team it is",
44423
+ " given. It knows who is available; it will not volunteer the allocation unless asked.",
44424
+ "3. **Propose it with `update_plan`.** The user sees a diff and approves it. Do not skip this:",
44425
+ " a plan held only in the conversation is forgotten as the chat grows, and it is not",
44426
+ " something the user has agreed to.",
44427
+ "4. Only once it is approved, start the work, reporting each step with `plan_progress`.",
44428
+ "",
44429
+ "If the user declines, ask what they want changed and propose a revised plan. If no expert is",
44430
+ "assigned, draft it yourself and propose it the same way \u2014 and say that is what you did, so",
44431
+ "nobody believes it was reviewed by somebody else.",
44432
+ "",
44433
+ "The exception is a question rather than a job. If the user asked something you can simply",
44434
+ "answer, answer it \u2014 do not plan a conversation."
44435
+ ].join("\n");
44436
+ var PLAN_IN_PLACE = [
44437
+ "",
44438
+ "## This conversation already has a plan",
44067
44439
  "",
44068
- "Each one is charged. Make the first count \u2014 gather what is needed and ask one full question",
44069
- "rather than opening with something you could have settled yourself. If a per-task budget runs",
44070
- "out the specialist stops being available, and you finish the work alone, so spend it on the",
44071
- "parts where another reader genuinely changes what you do."
44440
+ "It is above, with its steps numbered. Work it, report each step with `plan_progress`, and if it",
44441
+ "turns out to be wrong, consult the expert and propose a replacement with `update_plan` rather",
44442
+ "than quietly working to a different one."
44072
44443
  ].join("\n");
44073
44444
  var DEFAULT_TEAM_GUIDANCE = [
44074
44445
  "You lead a small team. You do the work \u2014 reading, searching, editing, running things \u2014 and you",
@@ -44085,17 +44456,39 @@ var DEFAULT_TEAM_GUIDANCE = [
44085
44456
  "- you are about to call something done that has no tests \u2014 ask the **tester** what would break",
44086
44457
  " it;",
44087
44458
  "- you are guessing at how this codebase does something \u2014 ask the **librarian** rather than",
44088
- " inventing a convention.",
44459
+ " inventing a convention;",
44460
+ /*
44461
+ * The programmer was missing from this list entirely, which is most of why it never got used.
44462
+ *
44463
+ * Every other bullet describes somebody *reading* what you have, and writing code is the one
44464
+ * thing the assistant can already do — so with no bullet of its own the role simply never came
44465
+ * up, and a plan drafted by the expert never allocated it either (the same omission, in the
44466
+ * briefing). Bounded deliberately: "hand everything to the programmer" would add a round trip
44467
+ * to every edit and put a second model's conventions into the file.
44468
+ */
44469
+ "- a step is a self-contained piece of code with a clear spec \u2014 a parser, a schema, a set of",
44470
+ " pure functions \u2014 hand it to the **programmer** rather than writing it yourself out of habit,",
44471
+ " then check what comes back against the real file before applying it. Not for a two-line",
44472
+ " change, and not where the spec is still moving.",
44089
44473
  "",
44090
44474
  'The user can also ask directly ("ask the reviewer to look at this"), and then you consult that',
44091
44475
  "role whatever you would have chosen.",
44092
44476
  "",
44093
44477
  "## What makes a consultation worth it",
44094
44478
  "",
44095
- "A specialist cannot see the workspace. It knows only what you put in the question, so **paste",
44096
- 'the code**, the error, the failing output \u2014 the actual text. A question like "is my retry logic',
44097
- 'right?" with nothing attached comes back as a list of things retry logic usually gets wrong,',
44098
- "which you already knew.",
44479
+ /*
44480
+ * The last place still saying every specialist is blind.
44481
+ *
44482
+ * Some can read and search for themselves; the roster above marks which. But the advice does
44483
+ * not change much, because even one that can look things up starts from what you gave it — and
44484
+ * a question with nothing attached spends its whole lookup budget finding the file you already
44485
+ * had open.
44486
+ */
44487
+ "**Paste the code**, the error, the failing output \u2014 the actual text. Some of them can read the",
44488
+ "workspace and some cannot, and the roster says which; but even the ones that can start from",
44489
+ "what you give them, and a question with nothing attached spends their whole lookup budget",
44490
+ 'finding what you already had open. A question like "is my retry logic right?" with nothing',
44491
+ "attached comes back as a list of things retry logic usually gets wrong, which you already knew.",
44099
44492
  "",
44100
44493
  "Ask one full question rather than three thin ones. Each consultation is a fresh reader with no",
44101
44494
  "memory of the last, so a follow-up has to carry its own context.",
@@ -44105,30 +44498,86 @@ var DEFAULT_TEAM_GUIDANCE = [
44105
44498
  "- Do not consult on something you can settle by reading a file. Read it.",
44106
44499
  "- Do not relay advice you have not checked. You have the code open and the specialist does not;",
44107
44500
  " if it is wrong, say so and say why \u2014 to the user, and in your next question.",
44108
- "- Do not consult the same role twice with the same question hoping for a better answer."
44501
+ "- Do not consult the same role twice with the same question hoping for a better answer.",
44502
+ "",
44503
+ "## When a review finds something in code the programmer wrote",
44504
+ "",
44505
+ "**Take it back to the programmer.** It wrote the code, it is the role picked for writing, and",
44506
+ "the fix is its job rather than yours \u2014 you are the one holding the files, not the one whose",
44507
+ "judgement was hired for this. Fixing it silently yourself wastes the specialist and hides the",
44508
+ "exchange from the user.",
44509
+ "",
44510
+ "A consultation remembers nothing, so the question has to carry everything: **the code as it",
44511
+ "stands, the finding in the reviewer's own words, and what you have checked yourself.** A",
44512
+ 'programmer told only "the reviewer says this is wrong" will guess at which line and rewrite',
44513
+ "more than it should.",
44514
+ "",
44515
+ "**It may push back, and that is a real answer, not an obstacle.** Reviews are wrong often",
44516
+ "enough to matter \u2014 a finding can be about a path that cannot happen, a convention this",
44517
+ "codebase deliberately does not follow, or a misreading of code the reviewer only saw a fragment",
44518
+ "of. When the programmer disagrees, you settle it: you have the actual file and neither of them",
44519
+ "does. Say which way you went and why, in your reply, so the user sees the disagreement rather",
44520
+ "than only its outcome.",
44521
+ "",
44522
+ "**One lap, not a loop.** Review, fix, and re-review only when the fix was substantial enough",
44523
+ "that the first review no longer describes the code. If the two still disagree after that, stop",
44524
+ "and put it to the expert with both positions, or decide it yourself and say so. Ping-ponging a",
44525
+ "disagreement between two models that cannot see the file is how a turn is spent without",
44526
+ "anything being decided.",
44527
+ "",
44528
+ "## When the plan names a specialist",
44529
+ "",
44530
+ "Consult them **while that step is the active one**, not at the end in a batch. Two reasons, and",
44531
+ "the second is the one people notice: advice arriving after the work is done is a review nobody",
44532
+ "can act on without redoing it, and the progress panel attributes a consultation to whichever",
44533
+ "step was open when it happened \u2014 so a step worked in silence shows as nobody having helped with",
44534
+ "it, whatever you say afterwards.",
44535
+ "",
44536
+ "If a step names somebody and you decide against consulting them, say so and say why. A plan the",
44537
+ "user approved said that step would get another reader."
44109
44538
  ].join("\n");
44110
- function buildTeamGuidance(agents, custom2, budgetMatters2) {
44539
+ function buildTeamGuidance(agents, custom2, budgetMatters2, hasPlan) {
44111
44540
  const base = custom2 !== void 0 && custom2.trim().length > 0 ? custom2 : DEFAULT_TEAM_GUIDANCE;
44112
44541
  const advice = budgetMatters2 === true ? `${base}
44113
44542
  ${BUDGET_ADVICE}` : base;
44114
- if (agents.length === 0) {
44543
+ const planning = hasPlan === true ? PLAN_IN_PLACE : PLAN_FIRST;
44544
+ const usable = agents.filter((agent) => agent.available);
44545
+ const unusable = AGENT_ROLES.filter((role) => !usable.some((agent) => agent.role === role)).map((role) => {
44546
+ const assigned = agents.find((agent) => agent.role === role);
44547
+ return assigned === void 0 ? `- **${role}** \u2014 nobody assigned.` : `- **${role}** \u2014 ${assigned.reason ?? "assigned, but cannot be reached."}`;
44548
+ });
44549
+ const missing = unusable.length === 0 ? [] : [
44550
+ "",
44551
+ "**Not available, so do not ask for them and do not plan work for them:**",
44552
+ "",
44553
+ ...unusable,
44554
+ "",
44555
+ "If something genuinely needs one of these, say so and say that assigning it in",
44556
+ "Settings \u2192 Agents would let you consult it \u2014 then carry on without it rather than",
44557
+ "leaving that part of the job unaccounted for."
44558
+ ];
44559
+ if (usable.length === 0) {
44115
44560
  return [
44116
44561
  advice,
44562
+ planning,
44117
44563
  "",
44118
44564
  "## Your team",
44119
44565
  "",
44120
44566
  "**Nobody is assigned yet.** Until somebody is, do the work yourself and tell the user that",
44121
- "assigning a specialist in Settings \u2192 Agents would let you consult one."
44567
+ "assigning a specialist in Settings \u2192 Agents would let you consult one.",
44568
+ ...missing
44122
44569
  ].join("\n");
44123
44570
  }
44124
44571
  return [
44125
44572
  advice,
44573
+ planning,
44126
44574
  "",
44127
44575
  "## Your team",
44128
44576
  "",
44129
- "Reach any of them with `ask_agent`, naming the role:",
44577
+ "Reach any of them with `ask_agent`, naming the role. These are the only ones that exist:",
44130
44578
  "",
44131
- ...agents.map((agent) => `- **${agent.role}** (${agent.label}) \u2014 ${agent.summary}`)
44579
+ ...usable.map((agent) => `- **${agent.role}** (${agent.label}) \u2014 ${agent.summary}`),
44580
+ ...missing
44132
44581
  ].join("\n");
44133
44582
  }
44134
44583
 
@@ -44138,20 +44587,146 @@ function firstLine(text, limit = DESCRIPTION_LIMIT) {
44138
44587
  const line = text.split("\n").find((candidate) => candidate.trim().length > 0)?.trim() ?? "";
44139
44588
  return line.length > limit ? `${line.slice(0, limit - 1).trimEnd()}\u2026` : line;
44140
44589
  }
44590
+ function buildRoster(team, self) {
44591
+ const others = team.filter((agent) => agent.role !== self);
44592
+ const usable = others.filter((agent) => agent.available);
44593
+ const assigned = new Set(team.map((agent) => agent.role));
44594
+ const missing = [];
44595
+ for (const role of AGENT_ROLES) {
44596
+ if (role === self)
44597
+ continue;
44598
+ if (!assigned.has(role)) {
44599
+ missing.push(`- **${role}** \u2014 nobody is assigned to this role.`);
44600
+ continue;
44601
+ }
44602
+ const agent = others.find((candidate) => candidate.role === role);
44603
+ if (agent !== void 0 && !agent.available) {
44604
+ missing.push(`- **${role}** \u2014 ${agent.reason ?? "assigned, but cannot be reached."}`);
44605
+ }
44606
+ }
44607
+ const sections = ["## The rest of the team", ""];
44608
+ if (self !== void 0)
44609
+ sections.push(`You are the **${self}**.`, "");
44610
+ sections.push(usable.length > 0 ? "The assistant can also consult these specialists, and only these:" : "The assistant has **no other specialists available**. Whatever you propose, it does alone.");
44611
+ if (usable.length > 0) {
44612
+ sections.push(
44613
+ "",
44614
+ /*
44615
+ * What the others can actually do — and this was wrong once, in the expensive direction.
44616
+ *
44617
+ * It first said "None of them can see the workspace", written to stop the expert giving the
44618
+ * librarian a lookup job. That was false: `agents/consult.ts` gives a specialist the read
44619
+ * tool group, and the CLI expert holds Claude's own Read/Grep/Glob. The instruction was
44620
+ * therefore telling the expert *not* to allocate the librarian the one kind of work the
44621
+ * librarian is equipped for, which made the weakest role weaker.
44622
+ *
44623
+ * The real distinction is per role and the user controls it, so it is rendered from the
44624
+ * team rather than asserted about all of them — and it sits *above* the list, because it is
44625
+ * how to read the marks in it.
44626
+ */
44627
+ "**None of them can edit anything or run anything.** They read and advise; the assistant",
44628
+ "makes every change, and it is the one answerable for the result. Some can look things up",
44629
+ "for themselves, marked below; the rest know only what is in the question, so give those",
44630
+ "everything they need.",
44631
+ "",
44632
+ ...usable.map((agent) => `- **${agent.role}** (${agent.label}) \u2014 ${agent.summary}` + // Marked per role because it decides what is worth asking them: one that can read
44633
+ // needs pointing at a file, one that cannot needs the file pasted in.
44634
+ (agent.usesTools ? " *(can read and search the workspace)*" : "")),
44635
+ "",
44636
+ /*
44637
+ * Knowing who exists is not the same as being asked to use them.
44638
+ *
44639
+ * Reported with a plan that allocated nobody, on a machine where all four other roles were
44640
+ * assigned. The briefing told the expert who was available and told it not to name anyone
44641
+ * who was not — and it dutifully named nobody at all, writing a plan for the assistant
44642
+ * working alone, down to "I'll show you the code before moving on" where a reviewer was
44643
+ * sitting right there. An instruction that only says what *not* to do gets obeyed by doing
44644
+ * nothing.
44645
+ *
44646
+ * Deliberately not "use every specialist": that is four extra round trips on a task that
44647
+ * may not want any, and a plan routing every step through the whole team is worse than one
44648
+ * routing none — it reads as ceremony and people stop reading it.
44649
+ */
44650
+ "**If you are asked for a plan, say who should be involved in which step.** Name the role in",
44651
+ 'the step itself \u2014 "have the tester say what would break this", "get the reviewer onto the',
44652
+ 'callback wiring", "hand the parser to the programmer" \u2014 so the assistant knows when to',
44653
+ "consult and the user can see who is doing what.",
44654
+ "",
44655
+ /*
44656
+ * Two kinds of specialist, said separately, because the first version only described one.
44657
+ *
44658
+ * It asked for allocation "where another reader would genuinely change the outcome" and
44659
+ * called it "another pair of eyes" — review framing throughout, with a reviewer and a
44660
+ * tester as the examples. The programmer does not read, it produces, so a plan written to
44661
+ * that instruction correctly never mentions it. Reported exactly that way: reviewer and
44662
+ * tester allocated across four steps, programmer nowhere, on a machine where it was
44663
+ * assigned. An instruction that names one mode of use gets obeyed in one mode.
44664
+ */
44665
+ "They divide into two kinds, and both are worth allocating:",
44666
+ "",
44667
+ "- **Readers** \u2014 the reviewer, the tester, the librarian. Worth a step where another pair of",
44668
+ " eyes changes what happens: risky or fiddly code, a step that finishes something, a",
44669
+ " convention you would otherwise be guessing at.",
44670
+ '- **The librarian writes down what should be written down.** A step like "record how this',
44671
+ ' is set up" is a good one to allocate: it reads what already exists and records the skill',
44672
+ " itself. The user approves the text before it is saved, so word the step as recording.",
44673
+ "- **The programmer writes.** Where a step is a self-contained piece of code with a spec",
44674
+ " clear enough to hand over \u2014 a parser, a schema, a set of pure functions \u2014 say so and give",
44675
+ " it to the programmer. The assistant checks what comes back against the real file and",
44676
+ " applies it, so this is delegation rather than trust.",
44677
+ "",
44678
+ /*
44679
+ * A role invented by the user, which no fixed description can cover.
44680
+ *
44681
+ * The two bullets above name the built-in five, and a plan written only from them would
44682
+ * quietly skip a `db-reviewer` the user went to the trouble of creating — the same failure
44683
+ * as never allocating the programmer, arriving from the other direction. The summary is the
44684
+ * only thing that can describe it, so the instruction is to read it.
44685
+ */
44686
+ "- **A role you do not recognise is described by its summary above.** The user invented it",
44687
+ " and wrote that line, so treat it as the authority on what the role is for and allocate it",
44688
+ " where the summary says it helps.",
44689
+ "",
44690
+ "Only where it genuinely changes the outcome: a plan that routes every step through all of",
44691
+ "them is ceremony, and one that routes none wastes a team that is sitting there."
44692
+ );
44693
+ }
44694
+ if (missing.length > 0) {
44695
+ sections.push(
44696
+ "",
44697
+ // "Not set up" would be wrong for a role that *is* assigned and whose profile has since
44698
+ // gone: the user did set it up, and telling them otherwise sends them to fix the wrong
44699
+ // thing. "Not available" is true of both, and the reason beside each says which it is.
44700
+ "**Not available, so the assistant cannot use them:**",
44701
+ "",
44702
+ ...missing,
44703
+ "",
44704
+ "Do not give any of these work. Do not put them in a plan, a checklist or a next step \u2014 a",
44705
+ "plan naming a specialist who does not exist is a plan with a hole in it, and the user will",
44706
+ "have approved it without knowing. If a task genuinely needs one, say so in a sentence and",
44707
+ "say the user would have to assign it in Settings \u2192 Agents; then give the best advice you",
44708
+ "can for doing it without that role."
44709
+ );
44710
+ }
44711
+ return sections;
44712
+ }
44141
44713
  function buildAgentBriefing(input) {
44142
44714
  const tools = (input.tools ?? []).filter(
44143
44715
  // Telling a specialist it can consult a specialist is noise at best and a loop at worst.
44144
44716
  (tool) => tool.name !== "ask_agent" && tool.name !== "ask_expert"
44145
44717
  );
44146
44718
  const skills = input.skills ?? [];
44147
- if (tools.length === 0 && skills.length === 0)
44719
+ const team = input.team;
44720
+ if (tools.length === 0 && skills.length === 0 && team === void 0)
44148
44721
  return "";
44149
- const sections = [
44150
- "## What the assistant can do on your behalf",
44151
- "",
44152
- "You have no tools. The assistant asking you does, and will carry out whatever you recommend.",
44153
- "Name the tool or skill you mean rather than describing a manual procedure that duplicates it."
44154
- ];
44722
+ const sections = [];
44723
+ if (team !== void 0)
44724
+ sections.push(...buildRoster(team, input.self));
44725
+ if (tools.length > 0 || skills.length > 0) {
44726
+ if (sections.length > 0)
44727
+ sections.push("");
44728
+ sections.push("## What the assistant can do on your behalf", "", "You have no tools. The assistant asking you does, and will carry out whatever you recommend.", "Name the tool or skill you mean rather than describing a manual procedure that duplicates it.");
44729
+ }
44155
44730
  if (tools.length > 0) {
44156
44731
  sections.push("", "### Tools it can call", "", ...tools.map((tool) => `- \`${tool.name}\` \u2014 ${firstLine(tool.description)}`));
44157
44732
  }
@@ -44161,11 +44736,109 @@ function buildAgentBriefing(input) {
44161
44736
  return sections.join("\n");
44162
44737
  }
44163
44738
 
44739
+ // ../../packages/core/dist/approval/commands.js
44740
+ function isCommandAllowlisted(command, allowlist) {
44741
+ return allowlist.includes(command);
44742
+ }
44743
+ function addToAllowlist(command, allowlist) {
44744
+ return allowlist.includes(command) ? [...allowlist] : [...allowlist, command];
44745
+ }
44746
+ function removeFromAllowlist(command, allowlist) {
44747
+ return allowlist.filter((entry) => entry !== command);
44748
+ }
44749
+
44750
+ // ../../packages/core/dist/approval/types.js
44751
+ function requiresApproval(group) {
44752
+ return group !== "always";
44753
+ }
44754
+
44755
+ // ../../packages/core/dist/approval/policy.js
44756
+ function isApprovableGroup(group) {
44757
+ return group === "read" || group === "edit" || group === "command" || group === "mcp";
44758
+ }
44759
+ function categoryEnabled(group, settings) {
44760
+ if (settings === void 0 || !isApprovableGroup(group))
44761
+ return false;
44762
+ return settings[group] === true;
44763
+ }
44764
+ var ALWAYS_ASK_TOOLS = /* @__PURE__ */ new Set([
44765
+ "create_python_tool",
44766
+ "update_python_tool",
44767
+ "delete_python_tool",
44768
+ "write_skill",
44769
+ "delete_skill",
44770
+ /*
44771
+ * VBA installed into a workbook runs on this machine as this user, and nobody reviews a macro
44772
+ * afterwards. That is the same act as creating a Python tool, so it gets the same rule: a
44773
+ * human sees the source once, and no category toggle can stand in for that.
44774
+ */
44775
+ "excel_write_macro",
44776
+ /*
44777
+ * Running a macro executes somebody else's VBA as the user: it can rewrite the workbook, write
44778
+ * files, or send mail. That is not something a category toggle should ever cover, and the
44779
+ * approval showing the actual source is the only thing standing between "run DoTheThing" and
44780
+ * whatever DoTheThing does.
44781
+ */
44782
+ "excel_run_macro",
44783
+ /*
44784
+ * The plan is what holds the assistant to work the user agreed, so a category toggle must
44785
+ * never stand in for reading the change. Auto-approving this would mean an agent could widen
44786
+ * its own instructions and then point at them as authority — and both the panel and the
44787
+ * prompt would look right afterwards, because both would be reading the new plan.
44788
+ */
44789
+ "update_plan",
44790
+ /*
44791
+ * A role's prompt is prose injected into a model that then advises on this repository's code —
44792
+ * the reason `agents` is user-scope only. Softening a reviewer does not error; it approves
44793
+ * things, in the same tone as before. A category toggle must never stand in for reading that
44794
+ * diff.
44795
+ */
44796
+ "update_role",
44797
+ // Inventing one is the same act as rewriting one: a prompt that will advise on this code.
44798
+ "create_role",
44799
+ // And removing one takes a prompt somebody wrote with it.
44800
+ "delete_role"
44801
+ ]);
44802
+ function decideFromPolicy(request, approvals) {
44803
+ if (!requiresApproval(request.group))
44804
+ return "approve";
44805
+ if (ALWAYS_ASK_TOOLS.has(request.toolName))
44806
+ return void 0;
44807
+ if (approvals === void 0)
44808
+ return void 0;
44809
+ if (approvals.allowedTools?.includes(request.toolName) === true)
44810
+ return "approve";
44811
+ if (request.group === "command") {
44812
+ const command = commandFromPreview(request.preview);
44813
+ if (command !== void 0 && isCommandAllowlisted(command, approvals.allowedCommands ?? [])) {
44814
+ return "approve";
44815
+ }
44816
+ }
44817
+ return categoryEnabled(request.group, approvals.autoApprove) ? "approve" : void 0;
44818
+ }
44819
+ function commandFromPreview(preview) {
44820
+ return preview.kind === "command" ? preview.command : void 0;
44821
+ }
44822
+ var PolicyApprovalGate = class {
44823
+ inner;
44824
+ getApprovals;
44825
+ constructor(inner, getApprovals) {
44826
+ this.inner = inner;
44827
+ this.getApprovals = getApprovals;
44828
+ }
44829
+ async requestApproval(request) {
44830
+ const decided = decideFromPolicy(request, this.getApprovals());
44831
+ if (decided !== void 0)
44832
+ return decided;
44833
+ return this.inner.requestApproval(request);
44834
+ }
44835
+ };
44836
+
44164
44837
  // ../../packages/core/dist/agents/consult.js
44165
44838
  var CONSULT_MAX_STEPS = 5;
44166
44839
  var ALLOWED_GROUPS = /* @__PURE__ */ new Set(["read"]);
44167
- function toolsForConsultation(all) {
44168
- return all.filter((tool) => ALLOWED_GROUPS.has(tool.group) && tool.name !== "ask_agent" && tool.name !== "ask_expert");
44840
+ function toolsForConsultation(all, extra = /* @__PURE__ */ new Set()) {
44841
+ return all.filter((tool) => (ALLOWED_GROUPS.has(tool.group) || extra.has(tool.name)) && tool.name !== "ask_agent" && tool.name !== "ask_expert");
44169
44842
  }
44170
44843
  async function runConsultation(options) {
44171
44844
  const limit = options.maxSteps ?? CONSULT_MAX_STEPS;
@@ -44215,7 +44888,10 @@ async function runConsultation(options) {
44215
44888
  }
44216
44889
  try {
44217
44890
  const parsed = tool.parametersSchema.safeParse(JSON.parse(call.arguments || "{}"));
44218
- const result = parsed.success ? await tool.execute(parsed.data, options.context) : {
44891
+ const permitted = tool.group === "read" && !ALWAYS_ASK_TOOLS.has(tool.name) || options.approve !== void 0 && await options.approve(tool, parsed.data);
44892
+ const result = !permitted ? {
44893
+ content: `The user did not approve ${tool.name}. Say what you would have written and why, and let the assistant put it to them instead.`
44894
+ } : parsed.success ? await tool.execute(parsed.data, options.context) : {
44219
44895
  content: `Those arguments are not valid: ${parsed.error.issues.map((i) => i.message).join("; ")}`
44220
44896
  };
44221
44897
  messages.push({ role: "tool", toolCallId: call.id, content: String(result.content) });
@@ -48196,18 +48872,28 @@ var NEVER_AVAILABLE_TO_SCHEDULES = [
48196
48872
  // section 13 requires approval showing the source, which cannot happen with nobody there.
48197
48873
  "excel_write_macro",
48198
48874
  // And running one: unattended execution of arbitrary VBA, with nobody to read the source.
48199
- "excel_run_macro"
48875
+ "excel_run_macro",
48876
+ /*
48877
+ * Rewriting the plan it is being held to, with nobody there to approve the diff. Same ladder
48878
+ * as `schedule_prompt`: a run that can change its own instructions is bounded by nothing.
48879
+ */
48880
+ "update_plan",
48881
+ // Rewriting what a specialist is, unattended. The same ladder: a run that can redefine its own
48882
+ // reviewer can arrange to be reviewed favourably by the next one.
48883
+ "update_role",
48884
+ "create_role",
48885
+ "delete_role"
48200
48886
  ];
48201
48887
  function scheduleAppliesHere(schedule, workspaceRoot) {
48202
48888
  if (schedule.workspaceRoot === void 0)
48203
48889
  return true;
48204
48890
  if (workspaceRoot === void 0)
48205
48891
  return false;
48206
- const normalise = (value) => {
48892
+ const normalise2 = (value) => {
48207
48893
  const resolved = nodePath.resolve(value);
48208
48894
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
48209
48895
  };
48210
- return normalise(schedule.workspaceRoot) === normalise(workspaceRoot);
48896
+ return normalise2(schedule.workspaceRoot) === normalise2(workspaceRoot);
48211
48897
  }
48212
48898
  function filterToolsForSchedule(all, schedule) {
48213
48899
  const named = new Set(schedule.allowedTools);
@@ -49368,86 +50054,6 @@ async function indexWorkspace(options) {
49368
50054
  };
49369
50055
  }
49370
50056
 
49371
- // ../../packages/core/dist/approval/types.js
49372
- function requiresApproval(group) {
49373
- return group !== "always";
49374
- }
49375
-
49376
- // ../../packages/core/dist/approval/commands.js
49377
- function isCommandAllowlisted(command, allowlist) {
49378
- return allowlist.includes(command);
49379
- }
49380
- function addToAllowlist(command, allowlist) {
49381
- return allowlist.includes(command) ? [...allowlist] : [...allowlist, command];
49382
- }
49383
- function removeFromAllowlist(command, allowlist) {
49384
- return allowlist.filter((entry) => entry !== command);
49385
- }
49386
-
49387
- // ../../packages/core/dist/approval/policy.js
49388
- function isApprovableGroup(group) {
49389
- return group === "read" || group === "edit" || group === "command" || group === "mcp";
49390
- }
49391
- function categoryEnabled(group, settings) {
49392
- if (settings === void 0 || !isApprovableGroup(group))
49393
- return false;
49394
- return settings[group] === true;
49395
- }
49396
- var ALWAYS_ASK_TOOLS = /* @__PURE__ */ new Set([
49397
- "create_python_tool",
49398
- "update_python_tool",
49399
- "delete_python_tool",
49400
- "write_skill",
49401
- "delete_skill",
49402
- /*
49403
- * VBA installed into a workbook runs on this machine as this user, and nobody reviews a macro
49404
- * afterwards. That is the same act as creating a Python tool, so it gets the same rule: a
49405
- * human sees the source once, and no category toggle can stand in for that.
49406
- */
49407
- "excel_write_macro",
49408
- /*
49409
- * Running a macro executes somebody else's VBA as the user: it can rewrite the workbook, write
49410
- * files, or send mail. That is not something a category toggle should ever cover, and the
49411
- * approval showing the actual source is the only thing standing between "run DoTheThing" and
49412
- * whatever DoTheThing does.
49413
- */
49414
- "excel_run_macro"
49415
- ]);
49416
- function decideFromPolicy(request, approvals) {
49417
- if (!requiresApproval(request.group))
49418
- return "approve";
49419
- if (ALWAYS_ASK_TOOLS.has(request.toolName))
49420
- return void 0;
49421
- if (approvals === void 0)
49422
- return void 0;
49423
- if (approvals.allowedTools?.includes(request.toolName) === true)
49424
- return "approve";
49425
- if (request.group === "command") {
49426
- const command = commandFromPreview(request.preview);
49427
- if (command !== void 0 && isCommandAllowlisted(command, approvals.allowedCommands ?? [])) {
49428
- return "approve";
49429
- }
49430
- }
49431
- return categoryEnabled(request.group, approvals.autoApprove) ? "approve" : void 0;
49432
- }
49433
- function commandFromPreview(preview) {
49434
- return preview.kind === "command" ? preview.command : void 0;
49435
- }
49436
- var PolicyApprovalGate = class {
49437
- inner;
49438
- getApprovals;
49439
- constructor(inner, getApprovals) {
49440
- this.inner = inner;
49441
- this.getApprovals = getApprovals;
49442
- }
49443
- async requestApproval(request) {
49444
- const decided = decideFromPolicy(request, this.getApprovals());
49445
- if (decided !== void 0)
49446
- return decided;
49447
- return this.inner.requestApproval(request);
49448
- }
49449
- };
49450
-
49451
50057
  // ../../packages/core/dist/checkpoints/shadowGit.js
49452
50058
  import { execFile as execFile2 } from "node:child_process";
49453
50059
  import fs7 from "node:fs/promises";
@@ -49513,18 +50119,77 @@ var ShadowGit = class {
49513
50119
  if (restore.code !== 0) {
49514
50120
  throw new Error(`Could not roll back to checkpoint: ${restore.stderr || restore.stdout}`);
49515
50121
  }
49516
- await runGit(this.gitArgs(["clean", "-fd"]), this.workspaceRoot);
49517
- }
49518
- /** Whether `git` is on PATH at all — checkpoints degrade to unavailable, not to a crash. */
49519
- static async isGitAvailable() {
49520
- try {
49521
- const result = await runGit(["--version"], process.cwd());
49522
- return result.code === 0;
49523
- } catch {
49524
- return false;
50122
+ await runGit(this.gitArgs(["clean", "-fd"]), this.workspaceRoot);
50123
+ }
50124
+ /** Whether `git` is on PATH at all — checkpoints degrade to unavailable, not to a crash. */
50125
+ static async isGitAvailable() {
50126
+ try {
50127
+ const result = await runGit(["--version"], process.cwd());
50128
+ return result.code === 0;
50129
+ } catch {
50130
+ return false;
50131
+ }
50132
+ }
50133
+ };
50134
+
50135
+ // ../../packages/core/dist/tools/planTools.js
50136
+ var updateParams = external_exports.object({
50137
+ plan: external_exports.string().describe("The complete new plan, as numbered steps. This replaces the whole plan rather than being added to it, so include the steps that are staying."),
50138
+ reason: external_exports.string().optional().describe("One line on why the plan should change, shown to the user with the diff.")
50139
+ });
50140
+ function createUpdatePlanTool(access) {
50141
+ return {
50142
+ name: "update_plan",
50143
+ group: "edit",
50144
+ description: "Propose a new plan for this conversation, replacing the current one. The user is shown a diff and must approve it before anything changes. Use this after working out a plan \u2014 for example one a specialist drafted \u2014 rather than carrying it only in the conversation, which is forgotten as the chat grows. Give the whole plan as numbered steps; each step becomes a checkpoint the user can watch you complete.",
50145
+ parametersSchema: updateParams,
50146
+ async preview(params) {
50147
+ const before = access.current() ?? "";
50148
+ return {
50149
+ kind: "diff",
50150
+ // Not a file. The approval UI labels the diff with this, and naming it for what it is
50151
+ // beats a made-up path that implies something on disk is about to change.
50152
+ path: "the plan for this conversation",
50153
+ before,
50154
+ after: params.plan.slice(0, PLAN_LIMIT).trim(),
50155
+ ...params.reason !== void 0 && params.reason.trim().length > 0 ? { note: params.reason.trim() } : {}
50156
+ };
50157
+ },
50158
+ async execute(params) {
50159
+ const next = params.plan.slice(0, PLAN_LIMIT).trim();
50160
+ if (next.length === 0) {
50161
+ return { content: "A plan cannot be empty. To remove the plan, ask the user to clear it." };
50162
+ }
50163
+ await access.save(next);
50164
+ return {
50165
+ content: "The plan is updated and the user approved it. It is now in front of you for the rest of this conversation, and its steps are the checkpoints to report against."
50166
+ };
50167
+ }
50168
+ };
50169
+ }
50170
+ var progressParams = external_exports.object({
50171
+ checkpoint: external_exports.number().int().describe("The step number, as numbered in the plan you were given."),
50172
+ status: external_exports.enum(["active", "done"]).describe("`active` when you start the step, `done` when it is genuinely finished.")
50173
+ });
50174
+ function createPlanProgressTool(access) {
50175
+ return {
50176
+ name: "plan_progress",
50177
+ /*
50178
+ * Control flow, not an action: it records where you are and touches nothing else. Gating it
50179
+ * would mean an approval prompt between every step of every planned task, which nobody would
50180
+ * keep switched on for long.
50181
+ */
50182
+ group: "always",
50183
+ description: "Say which step of the plan you are on. Call it with `active` when you start a step and `done` when it is finished, so the user can watch progress without reading the whole transcript. Mark `done` only when the step is actually complete \u2014 a step you gave up on or half did should be reported in your reply instead.",
50184
+ parametersSchema: progressParams,
50185
+ async execute(params) {
50186
+ const outcome = await access.mark(params.checkpoint, params.status);
50187
+ if (!outcome.ok)
50188
+ return { content: outcome.reason, isError: true };
50189
+ return { content: outcome.summary };
49525
50190
  }
49526
- }
49527
- };
50191
+ };
50192
+ }
49528
50193
 
49529
50194
  // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1_ed45788dfbfe808cc09dd7daea6bd385/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
49530
50195
  function isZ4Schema(s) {
@@ -56683,6 +57348,29 @@ function looksUnfinished(text) {
56683
57348
  var CONTINUE_PROMPT = "You described what you were about to do but did not call a tool, so nothing happened. If you meant to act, call the tool now. If you were already finished, call attempt_completion with a summary instead.";
56684
57349
  var MAX_CONTINUE_NUDGES = 1;
56685
57350
 
57351
+ // ../../packages/core/dist/agent/repairHistory.js
57352
+ var UNANSWERED = "This tool call never reported a result \u2014 the turn ended before it did. Nothing can be assumed about whether it ran or what it changed. If it still matters, call it again; otherwise carry on.";
57353
+ function repairUnansweredToolCalls(messages) {
57354
+ const answered = /* @__PURE__ */ new Set();
57355
+ for (const message3 of messages) {
57356
+ if (message3.role === "tool" && message3.toolCallId !== void 0)
57357
+ answered.add(message3.toolCallId);
57358
+ }
57359
+ const repaired = [];
57360
+ for (const message3 of messages) {
57361
+ repaired.push(message3);
57362
+ if (message3.role !== "assistant" || message3.toolCalls === void 0)
57363
+ continue;
57364
+ for (const call of message3.toolCalls) {
57365
+ if (answered.has(call.id))
57366
+ continue;
57367
+ repaired.push({ role: "tool", toolCallId: call.id, content: UNANSWERED });
57368
+ answered.add(call.id);
57369
+ }
57370
+ }
57371
+ return repaired;
57372
+ }
57373
+
56686
57374
  // ../../packages/core/dist/agent/truncate.js
56687
57375
  import { randomUUID as randomUUID2 } from "node:crypto";
56688
57376
  import fs14 from "node:fs/promises";
@@ -56775,10 +57463,12 @@ async function truncateToolResult(content, store, maxChars = DEFAULT_MAX_CHARS)
56775
57463
 
56776
57464
  // ../../packages/core/dist/agent/loop.js
56777
57465
  var DEFAULT_MAX_ITERATIONS = 25;
57466
+ var BOOKKEEPING_TOOLS = /* @__PURE__ */ new Set(["plan_progress"]);
57467
+ var MAX_REFUNDED_STEPS = 20;
56778
57468
  var MAX_CONSECUTIVE_MISTAKES = 3;
56779
57469
  async function prepareModelMessages(conversation, provider, tools, options, events) {
56780
57470
  const contextWindow = options.contextWindow ?? 0;
56781
- let messages = conversation.toModelMessages();
57471
+ let messages = repairUnansweredToolCalls(conversation.toModelMessages());
56782
57472
  if (options.compactionEnabled !== false && contextWindow > 0) {
56783
57473
  const estimated = computeBreakdown(messages, tools, contextWindow).total;
56784
57474
  if (shouldCompact(messages, estimated, contextWindow, options.compaction ?? {})) {
@@ -56788,7 +57478,7 @@ async function prepareModelMessages(conversation, provider, tools, options, even
56788
57478
  if (summary !== void 0) {
56789
57479
  conversation.applyCompaction(summary, conversation.compactedCount() + result.summarisedCount);
56790
57480
  events.onCompacted?.(result.summarisedCount);
56791
- messages = conversation.toModelMessages();
57481
+ messages = repairUnansweredToolCalls(conversation.toModelMessages());
56792
57482
  }
56793
57483
  }
56794
57484
  }
@@ -56956,6 +57646,7 @@ async function runWithTimeout(tool, params, context, options) {
56956
57646
  async function runAgentTurn(provider, conversation, userMessage, toolRegistry, toolContext, events, options = {}) {
56957
57647
  conversation.addUserMessage(userMessage, options.images);
56958
57648
  const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
57649
+ let refunded = 0;
56959
57650
  const mistakeCounts = /* @__PURE__ */ new Map();
56960
57651
  let continueNudges = 0;
56961
57652
  const mode = options.mode ?? CODE_MODE;
@@ -57007,12 +57698,20 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
57007
57698
  }
57008
57699
  conversation.addAssistantMessage(assistantText, [toolCall]);
57009
57700
  events.onToolCall(toolCall);
57010
- const result = await runOneToolCall(toolCall, toolRegistry, toolContext, options, events, {
57011
- hasCheckpoint: () => checkpointTaken,
57012
- markCheckpointTaken: () => {
57013
- checkpointTaken = true;
57014
- }
57015
- }, mode);
57701
+ let result;
57702
+ try {
57703
+ result = await runOneToolCall(toolCall, toolRegistry, toolContext, options, events, {
57704
+ hasCheckpoint: () => checkpointTaken,
57705
+ markCheckpointTaken: () => {
57706
+ checkpointTaken = true;
57707
+ }
57708
+ }, mode);
57709
+ } catch (error51) {
57710
+ result = {
57711
+ content: `"${toolCall.name}" failed: ${error51 instanceof Error ? error51.message : String(error51)}`,
57712
+ isError: true
57713
+ };
57714
+ }
57016
57715
  const forModel = options.truncationStore !== void 0 ? (await truncateToolResult(result.content, options.truncationStore)).content : result.content;
57017
57716
  conversation.addToolResultMessage(toolCall.id, forModel);
57018
57717
  events.onToolResult(toolCall, result);
@@ -57025,6 +57724,10 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
57025
57724
  events.onDone();
57026
57725
  return;
57027
57726
  }
57727
+ if (BOOKKEEPING_TOOLS.has(toolCall.name) && refunded < MAX_REFUNDED_STEPS) {
57728
+ refunded += 1;
57729
+ iteration -= 1;
57730
+ }
57028
57731
  if (result.path !== void 0) {
57029
57732
  if (result.isError === true) {
57030
57733
  const count = (mistakeCounts.get(result.path) ?? 0) + 1;
@@ -59092,6 +59795,232 @@ var OfficeBridge = class {
59092
59795
  }
59093
59796
  };
59094
59797
 
59798
+ // ../../packages/core/dist/tools/roleTools.js
59799
+ var readParams = external_exports.object({
59800
+ role: external_exports.string().describe("Which role to read \u2014 one of the roles configured here. Omit to list them all.").optional()
59801
+ });
59802
+ function createReadRolePromptTool(access) {
59803
+ return {
59804
+ name: "read_role_prompt",
59805
+ group: "read",
59806
+ description: "Read a specialist role's current system prompt \u2014 what it is told it is. Call this before changing one, so the change is an edit to what the user wrote rather than a replacement for it. With no role, lists the roles that exist here.",
59807
+ parametersSchema: readParams,
59808
+ async execute(params) {
59809
+ const roles = access.list();
59810
+ if (params.role === void 0) {
59811
+ if (roles.length === 0)
59812
+ return { content: "No roles are configured." };
59813
+ return {
59814
+ content: roles.map((entry) => `- ${entry.role} (${entry.name})` + (entry.assigned ? "" : " \u2014 nobody assigned") + (entry.edited ? " \u2014 prompt edited" : " \u2014 default prompt")).join("\n")
59815
+ };
59816
+ }
59817
+ const role = params.role.trim().toLowerCase();
59818
+ const prompt = access.current(role);
59819
+ if (prompt === void 0) {
59820
+ return {
59821
+ content: `There is no "${role}" role. The roles here are: ${roles.map((entry) => entry.role).join(", ")}.`,
59822
+ isError: true
59823
+ };
59824
+ }
59825
+ const edited = roles.find((entry) => entry.role === role)?.edited === true;
59826
+ return {
59827
+ content: `The ${role}'s prompt${edited ? " (edited by the user)" : " (the default)"}:
59828
+
59829
+ ${prompt}`
59830
+ };
59831
+ }
59832
+ };
59833
+ }
59834
+ var updateParams2 = external_exports.object({
59835
+ role: external_exports.string().describe("Which role to change."),
59836
+ prompt: external_exports.string().optional().describe("The complete new prompt. It replaces the current one rather than being added to it, so include what is staying. An empty string resets the role to its default prompt; omit it entirely to leave the prompt alone."),
59837
+ /*
59838
+ * Name and summary are editable for the same reason the prompt is: they are how the role
59839
+ * presents itself. The summary especially — it is the line every other specialist sees and the
59840
+ * one the expert allocates from, so a role whose summary is wrong gets used for the wrong work.
59841
+ * Only a user-defined role can change them; a built-in one is what it is.
59842
+ */
59843
+ name: external_exports.string().optional().describe("A new display name. Custom roles only."),
59844
+ summary: external_exports.string().optional().describe("A new one-line summary of what it is for. Custom roles only. This is what the expert allocates from, so it matters more than the name."),
59845
+ usesTools: external_exports.boolean().optional().describe("Whether it may read and search the workspace. Omit to leave unchanged."),
59846
+ reason: external_exports.string().optional().describe("One line on what is changing and why, shown to the user above the diff.")
59847
+ });
59848
+ function createUpdateRolePromptTool(access) {
59849
+ return {
59850
+ name: "update_role",
59851
+ /*
59852
+ * `edit`, and deliberately not `always`: `decideFromPolicy` approves the `always` group
59853
+ * *before* it consults ALWAYS_ASK_TOOLS, so putting it there would silently auto-approve the
59854
+ * one thing this must always ask about. The same trap `update_plan` nearly fell into.
59855
+ */
59856
+ group: "edit",
59857
+ description: 'Change a specialist role: its system prompt, and for a role the user invented, its name, its summary, or whether it may read the workspace. Use it when the user says a specialist should behave differently ("make the reviewer stricter about error handling"). Read the role first and edit what is there rather than writing a new prompt from scratch. Only what you pass is changed. The user is shown a diff and must approve it, and it applies to every future consultation of that role.',
59858
+ parametersSchema: updateParams2,
59859
+ async preview(params) {
59860
+ const role = params.role.trim().toLowerCase();
59861
+ const details = access.details(role);
59862
+ const before = describeRole(details, access.current(role) ?? "");
59863
+ const nextPrompt = params.prompt === void 0 ? access.current(role) ?? "" : (
59864
+ // Empty means reset, so the diff shows what the default actually says — otherwise the
59865
+ // approval reads as "delete this prompt" rather than "go back to the built-in one".
59866
+ params.prompt.trim().length === 0 ? access.fallback(role) ?? "" : params.prompt.trim()
59867
+ );
59868
+ const after = describeRole(details === void 0 ? void 0 : {
59869
+ ...details,
59870
+ ...params.name !== void 0 ? { name: params.name.trim() } : {},
59871
+ ...params.summary !== void 0 ? { summary: params.summary.trim() } : {},
59872
+ ...params.usesTools !== void 0 ? { usesTools: params.usesTools } : {}
59873
+ }, nextPrompt);
59874
+ return {
59875
+ kind: "diff",
59876
+ path: `the ${role} role`,
59877
+ before,
59878
+ after,
59879
+ ...params.reason !== void 0 && params.reason.trim().length > 0 ? { note: params.reason.trim() } : {}
59880
+ };
59881
+ },
59882
+ async execute(params) {
59883
+ const role = params.role.trim().toLowerCase();
59884
+ if (access.current(role) === void 0) {
59885
+ return {
59886
+ content: `There is no "${role}" role. The roles here are: ${access.list().map((entry) => entry.role).join(", ")}.`,
59887
+ isError: true
59888
+ };
59889
+ }
59890
+ const details = access.details(role);
59891
+ const changingIdentity = params.name !== void 0 || params.summary !== void 0 || params.usesTools !== void 0;
59892
+ if (changingIdentity && details?.custom !== true) {
59893
+ return {
59894
+ content: `Only the prompt can be changed on a built-in role. "${role}" is built in, so its name, summary and workspace access are fixed. Create a role of your own if you need a different one.`,
59895
+ isError: true
59896
+ };
59897
+ }
59898
+ if (changingIdentity && details !== void 0) {
59899
+ await access.create({
59900
+ id: details.id,
59901
+ name: params.name?.trim() ?? details.name,
59902
+ summary: params.summary?.trim() ?? details.summary,
59903
+ // Carried over rather than re-sent: this path is about identity, and the prompt has its
59904
+ // own store. Passing the old one back keeps the two from disagreeing.
59905
+ prompt: details.prompt,
59906
+ usesTools: params.usesTools ?? details.usesTools
59907
+ });
59908
+ }
59909
+ if (params.prompt !== void 0) {
59910
+ const next = params.prompt.trim();
59911
+ await access.save(role, next.length === 0 ? void 0 : next);
59912
+ }
59913
+ return {
59914
+ content: `The ${role} is updated and the user approved it. Every consultation of that role from now on uses it.`
59915
+ };
59916
+ }
59917
+ };
59918
+ }
59919
+ var createParams2 = external_exports.object({
59920
+ id: external_exports.string().describe('Short id the assistant will use to reach it, e.g. "security". Lowercase letters, digits and hyphens. It cannot be changed afterwards.'),
59921
+ name: external_exports.string().describe('What to call it in the settings panel, e.g. "Security reviewer".'),
59922
+ summary: external_exports.string().describe("One line on what it is for. Every other specialist sees this, and the expert allocates from it when writing a plan \u2014 so say what it is good for, not what it is."),
59923
+ prompt: external_exports.string().describe("Its system prompt: what it is told it is and how to answer. What it may and may not do is added automatically, so do not write rules about tools or permissions."),
59924
+ usesTools: external_exports.boolean().describe("Whether it may read and search the workspace. True where the answer depends on code the asker cannot paste; false where the question carries everything it needs.")
59925
+ });
59926
+ function createCreateRoleTool(access) {
59927
+ return {
59928
+ name: "create_role",
59929
+ // `edit`, never `always` — see the note on `update_role_prompt`.
59930
+ group: "edit",
59931
+ description: "Create a new specialist role beyond the built-in ones, when the user wants a kind of reviewer or helper the team does not have \u2014 a security reviewer, a performance reviewer, one that knows a particular part of this codebase. A role is its prompt, so write that carefully. The user is shown the whole role and must approve it, and then assigns a model to it in Settings \u2192 Agents before it can answer.",
59932
+ parametersSchema: createParams2,
59933
+ async preview(params) {
59934
+ const { used, limit } = access.capacity();
59935
+ return {
59936
+ kind: "text",
59937
+ text: [
59938
+ `Create the role "${params.id.trim().toLowerCase()}" (${used + 1} of ${limit}).`,
59939
+ "",
59940
+ `Name: ${params.name}`,
59941
+ `For: ${params.summary}`,
59942
+ `Reads: ${params.usesTools ? "yes \u2014 it can read and search the workspace" : "no \u2014 it answers from the question alone"}`,
59943
+ "",
59944
+ "What it is told:",
59945
+ "",
59946
+ params.prompt.trim()
59947
+ ].join("\n")
59948
+ };
59949
+ },
59950
+ async execute(params) {
59951
+ const id = params.id.trim().toLowerCase();
59952
+ if (access.current(id) !== void 0) {
59953
+ return {
59954
+ content: `There is already a "${id}" role. Change it with update_role_prompt rather than creating it again.`,
59955
+ isError: true
59956
+ };
59957
+ }
59958
+ try {
59959
+ await access.create({ ...params, id });
59960
+ } catch (error51) {
59961
+ return {
59962
+ content: error51 instanceof Error ? error51.message : String(error51),
59963
+ isError: true
59964
+ };
59965
+ }
59966
+ return {
59967
+ content: `The ${id} role exists and the user approved it. Nobody answers it yet \u2014 it needs a model assigned in Settings \u2192 Agents before it can be consulted. Tell the user that.`
59968
+ };
59969
+ }
59970
+ };
59971
+ }
59972
+ function describeRole(details, prompt) {
59973
+ if (details === void 0)
59974
+ return prompt;
59975
+ return [
59976
+ `Name: ${details.name}`,
59977
+ `For: ${details.summary}`,
59978
+ `Reads: ${details.usesTools ? "yes" : "no"}`,
59979
+ "",
59980
+ prompt
59981
+ ].join("\n");
59982
+ }
59983
+ var deleteParams3 = external_exports.object({
59984
+ role: external_exports.string().describe("Which custom role to remove. Built-in roles cannot be deleted.")
59985
+ });
59986
+ function createDeleteRoleTool(access) {
59987
+ return {
59988
+ name: "delete_role",
59989
+ group: "edit",
59990
+ description: "Remove a role the user invented, along with whatever model was assigned to it. Built-in roles cannot be removed. The user is shown the role, including its prompt, and must approve. Nothing else refers to it afterwards, so any plan step naming it should be revised in the same turn.",
59991
+ parametersSchema: deleteParams3,
59992
+ async preview(params) {
59993
+ const role = params.role.trim().toLowerCase();
59994
+ const details = access.details(role);
59995
+ return {
59996
+ kind: "text",
59997
+ text: details === void 0 ? `There is no "${role}" role to delete.` : [
59998
+ `Delete the "${details.id}" role and its assignment.`,
59999
+ "",
60000
+ describeRole(details, details.prompt),
60001
+ "",
60002
+ "The prompt above is removed with it."
60003
+ ].join("\n")
60004
+ };
60005
+ },
60006
+ async execute(params) {
60007
+ const role = params.role.trim().toLowerCase();
60008
+ const details = access.details(role);
60009
+ if (details === void 0) {
60010
+ return { content: `There is no "${role}" role.`, isError: true };
60011
+ }
60012
+ if (!details.custom) {
60013
+ return {
60014
+ content: `"${role}" is one of the built-in roles and cannot be deleted. Leave it unassigned if it should not be used.`,
60015
+ isError: true
60016
+ };
60017
+ }
60018
+ await access.remove(role);
60019
+ return { content: `The ${role} role is gone, and so is its assignment.` };
60020
+ }
60021
+ };
60022
+ }
60023
+
59095
60024
  // ../../packages/core/dist/office/vbaCheck.js
59096
60025
  function splitLine(line) {
59097
60026
  let bare = "";
@@ -60272,7 +61201,94 @@ ${preview.text}` } : {}
60272
61201
  const ACTIVE_TASK_KEY = "lightCode.activeTaskId";
60273
61202
  let activeTaskId = services.workspaceState.get(ACTIVE_TASK_KEY);
60274
61203
  let activePlan;
61204
+ let activePlanProgress = {};
60275
61205
  let activeTaskCreatedAt = Date.now();
61206
+ function planViews() {
61207
+ return checkpointViews(activePlan, activePlanProgress);
61208
+ }
61209
+ function postPlanProgress() {
61210
+ post({ type: "planProgress", checkpoints: planViews() });
61211
+ }
61212
+ async function applyPlan(next) {
61213
+ const trimmed = next?.slice(0, PLAN_LIMIT).trim();
61214
+ activePlan = trimmed !== void 0 && trimmed.length > 0 ? trimmed : void 0;
61215
+ activePlanProgress = pruneProgress(activePlan, activePlanProgress);
61216
+ await persistActiveTask();
61217
+ post({ type: "plan", plan: activePlan ?? "" });
61218
+ postPlanProgress();
61219
+ }
61220
+ const rolePromptAccess = {
61221
+ list: () => knownRoles(cachedAgentDefinitions).map((role) => ({
61222
+ role,
61223
+ name: roleInfo(role, cachedAgentDefinitions).name,
61224
+ assigned: cachedTeam.some((agent) => agent.role === role),
61225
+ edited: cachedAgentRoles?.[role]?.prompt !== void 0
61226
+ })),
61227
+ current: (role) => {
61228
+ if (!isAgentRole(role, cachedAgentDefinitions))
61229
+ return void 0;
61230
+ return cachedAgentRoles?.[role]?.prompt ?? defaultPromptFor(role, cachedAgentDefinitions);
61231
+ },
61232
+ fallback: (role) => isAgentRole(role, cachedAgentDefinitions) ? defaultPromptFor(role, cachedAgentDefinitions) : void 0,
61233
+ details: (role) => {
61234
+ if (!isAgentRole(role, cachedAgentDefinitions))
61235
+ return void 0;
61236
+ const info = roleInfo(role, cachedAgentDefinitions);
61237
+ return {
61238
+ id: role,
61239
+ name: info.name,
61240
+ summary: info.summary,
61241
+ prompt: cachedAgentRoles?.[role]?.prompt ?? info.prompt,
61242
+ usesTools: cachedAgentRoles?.[role]?.tools ?? info.usesTools,
61243
+ custom: cachedAgentDefinitions.some((definition) => definition.id === role)
61244
+ };
61245
+ },
61246
+ remove: async (role) => {
61247
+ await handleDeleteCustomRole(role);
61248
+ },
61249
+ create: async (role) => {
61250
+ await handleSaveCustomRole(role);
61251
+ },
61252
+ capacity: () => ({ used: cachedAgentDefinitions.length, limit: CUSTOM_ROLE_LIMIT }),
61253
+ save: async (role, prompt) => {
61254
+ await saveAgents((current) => {
61255
+ const roles = { ...current.roles ?? {} };
61256
+ const existing = roles[role] ?? { kind: "profile" };
61257
+ if (prompt === void 0) {
61258
+ const rest = { ...existing };
61259
+ delete rest.prompt;
61260
+ roles[role] = rest;
61261
+ } else {
61262
+ roles[role] = { ...existing, prompt };
61263
+ }
61264
+ return { ...current, roles };
61265
+ });
61266
+ }
61267
+ };
61268
+ const planAccess = {
61269
+ current: () => activePlan,
61270
+ save: async (nextPlan) => {
61271
+ await applyPlan(nextPlan);
61272
+ },
61273
+ mark: async (index, status) => {
61274
+ const updated = markCheckpoint(activePlan, activePlanProgress, index, status);
61275
+ if (updated === void 0) {
61276
+ const total = planViews().length;
61277
+ return {
61278
+ ok: false,
61279
+ reason: total === 0 ? "There is no plan set for this conversation, so there is nothing to report against." : `There is no step ${String(index)}. The plan has ${String(total)} steps, numbered 1 to ${String(total)}.`
61280
+ };
61281
+ }
61282
+ activePlanProgress = updated;
61283
+ await persistActiveTask();
61284
+ postPlanProgress();
61285
+ const views = planViews();
61286
+ return {
61287
+ ok: true,
61288
+ summary: `Step ${String(index)} is now ${status}. ${progressSummary(views)} steps complete.`
61289
+ };
61290
+ }
61291
+ };
60276
61292
  async function setActiveTaskId(id) {
60277
61293
  activeTaskId = id;
60278
61294
  await services.workspaceState.set(ACTIVE_TASK_KEY, id);
@@ -60516,6 +61532,8 @@ ${preview.text}` } : {}
60516
61532
  let cachedCodeGenerator;
60517
61533
  let cachedTeam = [];
60518
61534
  let cachedTeamGuidance;
61535
+ let cachedAgentRoles;
61536
+ let cachedAgentDefinitions = [];
60519
61537
  let cachedBudgetMatters = false;
60520
61538
  let cachedMentionExcludes;
60521
61539
  let cachedReportsCost;
@@ -60566,6 +61584,8 @@ ${preview.text}` } : {}
60566
61584
  cliAvailable: expertCli?.available === true
60567
61585
  };
60568
61586
  cachedTeam = resolveTeam(teamContext);
61587
+ cachedAgentRoles = config2.agents?.roles;
61588
+ cachedAgentDefinitions = config2.agents?.definitions ?? [];
60569
61589
  cachedTeamGuidance = config2.agents?.teamGuidance;
60570
61590
  cachedBudgetMatters = budgetMatters(teamContext);
60571
61591
  cachedProgrammingProfileId = config2.programmingProfileId;
@@ -60717,6 +61737,12 @@ ${preview.text}` } : {}
60717
61737
  }
60718
61738
  for (const tool of python.generatedTools())
60719
61739
  combined.register(tool, { dispatchOnly: dispatcher });
61740
+ combined.register(createUpdatePlanTool(planAccess), { dispatchOnly: dispatcher });
61741
+ combined.register(createPlanProgressTool(planAccess), { dispatchOnly: dispatcher });
61742
+ combined.register(createReadRolePromptTool(rolePromptAccess), { dispatchOnly: dispatcher });
61743
+ combined.register(createUpdateRolePromptTool(rolePromptAccess), { dispatchOnly: dispatcher });
61744
+ combined.register(createCreateRoleTool(rolePromptAccess), { dispatchOnly: dispatcher });
61745
+ combined.register(createDeleteRoleTool(rolePromptAccess), { dispatchOnly: dispatcher });
60720
61746
  combined.register(createNotifyTool({
60721
61747
  notify: (message3, level, details) => {
60722
61748
  if (details !== void 0) {
@@ -60991,7 +62017,8 @@ ${preview.text}` } : {}
60991
62017
  updatedAt: Date.now(),
60992
62018
  messages,
60993
62019
  resultHandles: truncationStore.spilledHandles(),
60994
- ...activePlan !== void 0 && activePlan.trim().length > 0 ? { plan: activePlan } : {}
62020
+ ...activePlan !== void 0 && activePlan.trim().length > 0 ? { plan: activePlan } : {},
62021
+ ...Object.keys(activePlanProgress).length > 0 ? { planProgress: activePlanProgress } : {}
60995
62022
  };
60996
62023
  try {
60997
62024
  await taskStore.save(redactTask(task, await knownSecretValues()));
@@ -61020,9 +62047,11 @@ ${preview.text}` } : {}
61020
62047
  activeTaskCreatedAt = task.createdAt;
61021
62048
  truncationStore.startTask(task.resultHandles);
61022
62049
  activePlan = task.plan;
62050
+ activePlanProgress = pruneProgress(activePlan, task.planProgress);
61023
62051
  await setActiveTaskId(task.id);
61024
62052
  post({ type: "taskRestored", taskId: task.id, entries: toTranscript(task.messages) });
61025
62053
  post({ type: "plan", plan: activePlan ?? "" });
62054
+ postPlanProgress();
61026
62055
  await postTasks();
61027
62056
  }
61028
62057
  async function startNewTask() {
@@ -61033,9 +62062,11 @@ ${preview.text}` } : {}
61033
62062
  activeTaskCreatedAt = Date.now();
61034
62063
  truncationStore.startTask();
61035
62064
  activePlan = void 0;
62065
+ activePlanProgress = {};
61036
62066
  await setActiveTaskId(void 0);
61037
62067
  post({ type: "taskRestored", taskId: void 0, entries: [] });
61038
62068
  post({ type: "plan", plan: "" });
62069
+ postPlanProgress();
61039
62070
  await postTasks();
61040
62071
  }
61041
62072
  async function deleteTask(id) {
@@ -61140,7 +62171,20 @@ ${preview.text}` } : {}
61140
62171
  ...(() => {
61141
62172
  const parts = [];
61142
62173
  if (activeMode.id === AGENT_TEAM_MODE.id) {
61143
- parts.push(buildTeamGuidance(cachedTeam.filter((agent) => agent.available), cachedTeamGuidance, cachedBudgetMatters));
62174
+ parts.push(buildTeamGuidance(
62175
+ // The whole team, not only the available ones: the roster names what is missing
62176
+ // as well as what is there, and it cannot do that from a pre-filtered list.
62177
+ cachedTeam,
62178
+ cachedTeamGuidance,
62179
+ cachedBudgetMatters,
62180
+ /*
62181
+ * Whether a plan already exists, which decides whether this mode is told to go
62182
+ * and make one. Passed rather than inferred from the prompt: the plan section is
62183
+ * assembled separately, and a mode guessing at whether it is there would be a
62184
+ * second reading of the same fact.
62185
+ */
62186
+ activePlan !== void 0 && activePlan.trim().length > 0
62187
+ ));
61144
62188
  } else if (activeMode.guidance !== void 0 && (activeMode.requiresExpert !== true || expertCliInfo !== void 0)) {
61145
62189
  parts.push(activeMode.guidance);
61146
62190
  }
@@ -61314,8 +62358,14 @@ ${preview.text}` } : {}
61314
62358
  cumulativeText = "";
61315
62359
  cumulativeReasoning = "";
61316
62360
  const consulting = consultationFromToolCall(toolCall.name, toolCall.arguments);
61317
- if (consulting !== void 0)
62361
+ if (consulting !== void 0) {
61318
62362
  informedBy = consulting;
62363
+ const attributed = attributeConsultation(activePlanProgress, consulting);
62364
+ if (attributed !== activePlanProgress) {
62365
+ activePlanProgress = attributed;
62366
+ postPlanProgress();
62367
+ }
62368
+ }
61319
62369
  if (CONTROL_TOOLS.has(toolCall.name))
61320
62370
  return;
61321
62371
  if (chartFromToolCall(toolCall.name, toolCall.arguments) !== void 0)
@@ -61437,7 +62487,7 @@ ${preview.text}` } : {}
61437
62487
  }
61438
62488
  if (input.authType === "none")
61439
62489
  return { type: "none" };
61440
- const typed = input.apiKey.trim();
62490
+ const typed = (input.apiKey ?? "").trim();
61441
62491
  if (describeSecretRef(typed).kind === "env") {
61442
62492
  await secrets.delete(apiKeyRefFor(id));
61443
62493
  return { type: "apiKey", apiKeyRef: typed };
@@ -61591,6 +62641,19 @@ ${preview.text}` } : {}
61591
62641
  }
61592
62642
  }
61593
62643
  async function profileFromForm(input) {
62644
+ const fieldErrors = validateProviderForm({
62645
+ label: input.label,
62646
+ wireFormat: input.wireFormat,
62647
+ baseUrl: input.baseUrl,
62648
+ model: input.model
62649
+ });
62650
+ if (fieldErrors.length > 0) {
62651
+ post({
62652
+ type: "error",
62653
+ message: fieldErrors.map((issue2) => `${issue2.path}: ${issue2.message}`).join("; ")
62654
+ });
62655
+ return void 0;
62656
+ }
61594
62657
  const baseUrl = input.baseUrl.trim();
61595
62658
  if (baseUrl.length === 0) {
61596
62659
  post({ type: "error", message: "Enter a base URL first." });
@@ -61675,7 +62738,9 @@ ${preview.text}` } : {}
61675
62738
  cliAvailable: cli?.available === true
61676
62739
  };
61677
62740
  const assigned = new Map(resolveTeam(teamContext).map((agent) => [agent.role, agent]));
61678
- const roles = allRoles().map((info) => {
62741
+ const definitions = config2.agents?.definitions ?? [];
62742
+ const customIds = new Set(definitions.map((definition) => definition.id));
62743
+ const roles = allRoles(definitions).map((info) => {
61679
62744
  const agent = assigned.get(info.role);
61680
62745
  const prompt = config2.agents?.roles?.[info.role]?.prompt;
61681
62746
  return {
@@ -61687,8 +62752,14 @@ ${preview.text}` } : {}
61687
62752
  label: agent?.label ?? "Nobody",
61688
62753
  available: agent?.available ?? false,
61689
62754
  ...agent?.reason !== void 0 ? { reason: agent.reason } : {},
61690
- prompt: prompt ?? defaultPromptFor(info.role),
61691
- promptIsDefault: prompt === void 0
62755
+ prompt: prompt ?? defaultPromptFor(info.role, definitions),
62756
+ promptIsDefault: prompt === void 0,
62757
+ ...customIds.has(info.role) ? { custom: true } : {},
62758
+ // The assignment's override where there is one, else the role's own default — the same
62759
+ // resolution `resolveTeam` does, so the switch in the tab shows what will actually happen.
62760
+ usesTools: config2.agents?.roles?.[info.role]?.tools ?? info.usesTools,
62761
+ canWrite: config2.agents?.roles?.[info.role]?.write ?? info.canWrite,
62762
+ enabled: config2.agents?.roles?.[info.role]?.enabled !== false
61692
62763
  };
61693
62764
  });
61694
62765
  const guidance = config2.agents?.teamGuidance;
@@ -61717,6 +62788,51 @@ ${preview.text}` } : {}
61717
62788
  }
61718
62789
  });
61719
62790
  }
62791
+ async function handleSaveCustomRole(role) {
62792
+ const id = role.id.trim().toLowerCase();
62793
+ if (!isValidRoleId(id)) {
62794
+ post({
62795
+ type: "error",
62796
+ message: `"${id}" is not a usable role id. Use lowercase letters, digits and hyphens, starting with a letter, and not the name of a built-in role.`
62797
+ });
62798
+ return;
62799
+ }
62800
+ if (role.name.trim().length === 0) {
62801
+ post({ type: "error", message: "A role needs a name." });
62802
+ return;
62803
+ }
62804
+ await saveAgents((current) => {
62805
+ const definitions = [...current.definitions ?? []];
62806
+ const at = definitions.findIndex((candidate) => candidate.id === id);
62807
+ const next = {
62808
+ id,
62809
+ name: role.name.trim(),
62810
+ summary: role.summary.trim(),
62811
+ prompt: role.prompt.trim(),
62812
+ usesTools: role.usesTools,
62813
+ canWrite: role.canWrite === true
62814
+ };
62815
+ if (at === -1) {
62816
+ if (definitions.length >= CUSTOM_ROLE_LIMIT) {
62817
+ throw new Error(`That would be ${String(definitions.length + 1)} custom roles. The limit is ${String(CUSTOM_ROLE_LIMIT)}: the expert allocates from this list, and its judgement is what a longer one costs.`);
62818
+ }
62819
+ definitions.push(next);
62820
+ } else
62821
+ definitions[at] = next;
62822
+ return { ...current, definitions };
62823
+ });
62824
+ }
62825
+ async function handleDeleteCustomRole(id) {
62826
+ await saveAgents((current) => {
62827
+ const roles = { ...current.roles ?? {} };
62828
+ delete roles[id];
62829
+ return {
62830
+ ...current,
62831
+ roles,
62832
+ definitions: (current.definitions ?? []).filter((candidate) => candidate.id !== id)
62833
+ };
62834
+ });
62835
+ }
61720
62836
  async function saveAgents(change) {
61721
62837
  try {
61722
62838
  const { config: config2 } = await configManager.load();
@@ -63744,6 +64860,11 @@ ${preview.text}` } : {}
63744
64860
  const prompt = buildAgentPrompt({
63745
64861
  prompt: agent.prompt,
63746
64862
  question: request.question,
64863
+ // Decides the preamble as well as whether tools are offered below, so the two can never
64864
+ // disagree — a specialist told it can read, and then given nothing to read with, wastes a
64865
+ // step discovering that.
64866
+ usesTools: agent.usesTools,
64867
+ canWrite: agent.canWrite,
63747
64868
  ...request.files !== void 0 ? { files: request.files } : {},
63748
64869
  /*
63749
64870
  * What exists in this workspace.
@@ -63754,13 +64875,29 @@ ${preview.text}` } : {}
63754
64875
  */
63755
64876
  briefing: buildAgentBriefing({
63756
64877
  tools: agentBriefingTools?.() ?? [],
63757
- skills
64878
+ skills,
64879
+ /*
64880
+ * Who else exists, so a plan cannot name a specialist nobody set up.
64881
+ *
64882
+ * Built here, above the `kind` branch, which is the point: the Claude CLI expert and a
64883
+ * provider-profile expert are given byte-identical briefings, so making a different model
64884
+ * the expert cannot change what it knows about the team. `briefing.test.ts` pins that,
64885
+ * because the two paths diverging is invisible until somebody switches expert and gets a
64886
+ * worse plan for no reason they could name.
64887
+ */
64888
+ team: cachedTeam,
64889
+ self: agent.role
63758
64890
  })
63759
64891
  });
63760
64892
  if (agent.kind === "cli") {
63761
64893
  const cli = expertCli;
63762
64894
  if (cli === void 0 || !cli.available)
63763
64895
  throw new Error("The Claude CLI is not available.");
64896
+ if (cachedBudgetMatters) {
64897
+ const verdict = checkExpertBudget(expertSpend, effectiveExpertLimits());
64898
+ if (!verdict.allowed)
64899
+ throw new Error(verdict.message);
64900
+ }
63764
64901
  const answer = await consultExpert(cli, {
63765
64902
  question: prompt,
63766
64903
  /*
@@ -63771,6 +64908,10 @@ ${preview.text}` } : {}
63771
64908
  cwd: workspaceRoot ?? process.cwd(),
63772
64909
  ...request.signal !== void 0 ? { signal: request.signal } : {}
63773
64910
  });
64911
+ recordConsultation({
64912
+ isError: answer.isError,
64913
+ ...answer.costUsd !== void 0 ? { costUsd: answer.costUsd } : {}
64914
+ });
63774
64915
  if (answer.isError)
63775
64916
  throw new Error(answer.text);
63776
64917
  return { advice: answer.text, label: agent.label };
@@ -63781,7 +64922,13 @@ ${preview.text}` } : {}
63781
64922
  throw new Error(`No profile "${agent.profileId ?? ""}" exists any more.`);
63782
64923
  }
63783
64924
  const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger);
63784
- const readOnly = toolsForConsultation(agentBriefingTools?.() ?? []);
64925
+ const extraTools = new Set(agent.role === "librarian" ? ["write_skill"] : []);
64926
+ if (agent.canWrite) {
64927
+ extraTools.add("write_to_file");
64928
+ extraTools.add("apply_diff");
64929
+ extraTools.add("write_skill");
64930
+ }
64931
+ const readOnly = agent.usesTools ? toolsForConsultation(agentBriefingTools?.() ?? [], extraTools) : [];
63785
64932
  const context = consultationContext?.();
63786
64933
  const result = await runConsultation({
63787
64934
  provider,
@@ -63791,6 +64938,24 @@ ${preview.text}` } : {}
63791
64938
  // With no context there is nothing to read *with*, so it answers from the question alone
63792
64939
  // rather than being offered tools that would fail.
63793
64940
  context: context ?? {},
64941
+ /*
64942
+ * The same gate the agent loop uses, so an approval raised by a specialist is
64943
+ * indistinguishable from one raised by the assistant — same prompt, same ground truth, same
64944
+ * always-ask rule. A second approval path would be a second place for the rule to be wrong.
64945
+ */
64946
+ approve: async (tool, args) => {
64947
+ const preview = await tool.preview?.(args, context ?? {}).catch(() => void 0);
64948
+ const decision = await approvalGate.requestApproval({
64949
+ id: `agent-${agent.role}-${String(Date.now())}-${tool.name}`,
64950
+ toolName: tool.name,
64951
+ group: tool.group,
64952
+ preview: preview ?? {
64953
+ kind: "text",
64954
+ text: `The ${agent.role} wants to run ${tool.name}.`
64955
+ }
64956
+ });
64957
+ return decision === "approve";
64958
+ },
63794
64959
  ...request.signal !== void 0 ? { signal: request.signal } : {},
63795
64960
  onStep: (name) => logger.info(`${agent.role} looked up ${name}`)
63796
64961
  });
@@ -64543,18 +65708,18 @@ ${preview.text}` } : {}
64543
65708
  } else if (message3.type === "requestExpert") {
64544
65709
  void postExpert();
64545
65710
  } else if (message3.type === "setPlan") {
64546
- const plan = message3.plan.slice(0, PLAN_LIMIT).trim();
64547
- activePlan = plan.length > 0 ? plan : void 0;
64548
- void persistActiveTask();
64549
- post({ type: "plan", plan: activePlan ?? "" });
65711
+ void applyPlan(message3.plan);
64550
65712
  } else if (message3.type === "requestPlan") {
64551
65713
  post({ type: "plan", plan: activePlan ?? "" });
65714
+ postPlanProgress();
65715
+ } else if (message3.type === "requestPlanProgress") {
65716
+ postPlanProgress();
64552
65717
  } else if (message3.type === "requestAgents") {
64553
65718
  void postAgents();
64554
65719
  } else if (message3.type === "setAgentRole") {
64555
65720
  const assignment = message3.assignment;
64556
65721
  const role = message3.role;
64557
- if (!isAgentRole(role)) {
65722
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
64558
65723
  post({ type: "error", message: `There is no "${role}" role.` });
64559
65724
  return;
64560
65725
  }
@@ -64574,7 +65739,7 @@ ${preview.text}` } : {}
64574
65739
  } else if (message3.type === "setAgentPrompt") {
64575
65740
  const role = message3.role;
64576
65741
  const prompt = message3.prompt;
64577
- if (!isAgentRole(role)) {
65742
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
64578
65743
  post({ type: "error", message: `There is no "${role}" role.` });
64579
65744
  return;
64580
65745
  }
@@ -64605,10 +65770,50 @@ ${preview.text}` } : {}
64605
65770
  }
64606
65771
  return { ...current, teamGuidance: guidance };
64607
65772
  });
65773
+ } else if (message3.type === "saveCustomRole") {
65774
+ void handleSaveCustomRole(message3);
65775
+ } else if (message3.type === "deleteCustomRole") {
65776
+ void handleDeleteCustomRole(message3.id);
65777
+ } else if (message3.type === "setRoleEnabled") {
65778
+ const role = message3.role;
65779
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
65780
+ post({ type: "error", message: `There is no "${role}" role.` });
65781
+ return;
65782
+ }
65783
+ void saveAgents((current) => {
65784
+ const roles = { ...current.roles ?? {} };
65785
+ roles[role] = {
65786
+ ...roles[role] ?? { kind: "profile" },
65787
+ enabled: message3.enabled
65788
+ };
65789
+ return { ...current, roles };
65790
+ });
65791
+ } else if (message3.type === "setRoleWrite") {
65792
+ const role = message3.role;
65793
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
65794
+ post({ type: "error", message: `There is no "${role}" role.` });
65795
+ return;
65796
+ }
65797
+ void saveAgents((current) => {
65798
+ const roles = { ...current.roles ?? {} };
65799
+ roles[role] = { ...roles[role] ?? { kind: "profile" }, write: message3.canWrite };
65800
+ return { ...current, roles };
65801
+ });
65802
+ } else if (message3.type === "setRoleTools") {
65803
+ const role = message3.role;
65804
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
65805
+ post({ type: "error", message: `There is no "${role}" role.` });
65806
+ return;
65807
+ }
65808
+ void saveAgents((current) => {
65809
+ const roles = { ...current.roles ?? {} };
65810
+ roles[role] = { ...roles[role] ?? { kind: "profile" }, tools: message3.usesTools };
65811
+ return { ...current, roles };
65812
+ });
64608
65813
  } else if (message3.type === "setAgentColor") {
64609
65814
  const role = message3.role;
64610
65815
  const color = message3.color;
64611
- if (!isAgentRole(role)) {
65816
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
64612
65817
  post({ type: "error", message: `There is no "${role}" role.` });
64613
65818
  return;
64614
65819
  }
@@ -68707,7 +69912,7 @@ function respondJson(response, status, body) {
68707
69912
  }
68708
69913
 
68709
69914
  // src/cli.ts
68710
- var VERSION = true ? "0.46.0" : "unknown (not a packaged build)";
69915
+ var VERSION = true ? "0.56.1" : "unknown (not a packaged build)";
68711
69916
  var compat = installNodeCompat();
68712
69917
  function lastMeaningfulLine(problem) {
68713
69918
  const lines = problem.split(String.fromCharCode(10)).map((line) => line.trim()).filter((line) => line.length > 0 && !line.endsWith(":"));