@chosengeneration/light-code 0.50.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,7 +39769,32 @@ 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();
39774
39799
  var customRoleSchema = external_exports.object({
39775
39800
  id: external_exports.string().min(1),
@@ -43348,6 +43373,11 @@ var Conversation = class {
43348
43373
 
43349
43374
  // ../../packages/core/dist/agents/roles.js
43350
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
+ }
43351
43381
  function isAgentRole(value, custom2 = []) {
43352
43382
  return AGENT_ROLES.includes(value) || custom2.some((role) => role.id === value);
43353
43383
  }
@@ -43361,6 +43391,13 @@ var SHARED_TAIL = [
43361
43391
  "",
43362
43392
  "Answer in prose and short lists. No preamble about being happy to help."
43363
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");
43364
43401
  var SHARED_WITH_TOOLS = [
43365
43402
  "You can read this workspace: open files, list them, and search. Use that rather than guessing,",
43366
43403
  "and rather than asking the assistant for something you can fetch yourself. You have a small",
@@ -43378,8 +43415,9 @@ var SHARED_BLIND = [
43378
43415
  "",
43379
43416
  ...SHARED_TAIL
43380
43417
  ].join("\n");
43381
- function specialistPreamble(usesTools) {
43382
- return usesTools ? SHARED_WITH_TOOLS : SHARED_BLIND;
43418
+ function specialistPreamble(usesTools, canWrite = false) {
43419
+ const base = usesTools ? SHARED_WITH_TOOLS : SHARED_BLIND;
43420
+ return canWrite ? `${base}${MAY_WRITE}` : base;
43383
43421
  }
43384
43422
  var DEFINITIONS = {
43385
43423
  expert: {
@@ -43388,6 +43426,7 @@ var DEFINITIONS = {
43388
43426
  /* Planning a change means knowing what is already there, and it spans files the asker
43389
43427
  * cannot paste all of. */
43390
43428
  usesTools: true,
43429
+ canWrite: false,
43391
43430
  prompt: [
43392
43431
  "You are a senior engineer being consulted by another AI assistant that is doing the work.",
43393
43432
  "",
@@ -43405,6 +43444,7 @@ var DEFINITIONS = {
43405
43444
  /* It is handed a spec and the surrounding code and asked to write. Looking around buys
43406
43445
  * a slower answer that is no better. */
43407
43446
  usesTools: false,
43447
+ canWrite: false,
43408
43448
  prompt: [
43409
43449
  "You are an experienced programmer writing code for another AI assistant to apply.",
43410
43450
  "",
@@ -43435,6 +43475,7 @@ var DEFINITIONS = {
43435
43475
  /* Most of what a review turns on is *around* the diff — the callers, the neighbouring
43436
43476
  * function, whether this convention is really the convention. */
43437
43477
  usesTools: true,
43478
+ canWrite: false,
43438
43479
  prompt: [
43439
43480
  "You are reviewing a change written by another AI assistant.",
43440
43481
  "",
@@ -43462,6 +43503,7 @@ var DEFINITIONS = {
43462
43503
  /* The change is in front of it and the cases come from reasoning about it, not from
43463
43504
  * reading more of the codebase. */
43464
43505
  usesTools: false,
43506
+ canWrite: false,
43465
43507
  prompt: [
43466
43508
  "You design tests for code written by another AI assistant.",
43467
43509
  "",
@@ -43481,6 +43523,7 @@ var DEFINITIONS = {
43481
43523
  * left it answering from whatever happened to be pasted in. This is the role the flag
43482
43524
  * exists for. */
43483
43525
  usesTools: true,
43526
+ canWrite: false,
43484
43527
  prompt: [
43485
43528
  "You answer questions about how things are done here: internal libraries, house conventions,",
43486
43529
  "the shape of existing code, and what has already been written down.",
@@ -43490,7 +43533,29 @@ var DEFINITIONS = {
43490
43533
  "you are inferring \u2014 a convention you guessed at, stated confidently, becomes the convention.",
43491
43534
  "",
43492
43535
  "If the material does not answer the question, say so and say what would. Do not fill the gap",
43493
- "with how it is usually done elsewhere unless you label it as exactly that."
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."
43494
43559
  ].join("\n")
43495
43560
  }
43496
43561
  };
@@ -43512,7 +43577,10 @@ function roleInfo(role, custom2 = []) {
43512
43577
  * accessibility — and those all turn on code the asker did not think to paste. The flag is
43513
43578
  * there to turn it off for the ones that are really "write this to spec".
43514
43579
  */
43515
- usesTools: defined.usesTools !== false
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
43516
43584
  };
43517
43585
  }
43518
43586
  return {
@@ -43520,7 +43588,8 @@ function roleInfo(role, custom2 = []) {
43520
43588
  name: role,
43521
43589
  summary: "This role is no longer defined.",
43522
43590
  prompt: "",
43523
- usesTools: false
43591
+ usesTools: false,
43592
+ canWrite: false
43524
43593
  };
43525
43594
  }
43526
43595
  function allRoles(custom2 = []) {
@@ -43530,7 +43599,11 @@ function defaultPromptFor(role, custom2 = []) {
43530
43599
  return roleInfo(role, custom2).prompt;
43531
43600
  }
43532
43601
  function buildAgentPrompt(options) {
43533
- const lines = [options.prompt.trim(), "", specialistPreamble(options.usesTools)];
43602
+ const lines = [
43603
+ options.prompt.trim(),
43604
+ "",
43605
+ specialistPreamble(options.usesTools, options.canWrite === true)
43606
+ ];
43534
43607
  if (options.briefing !== void 0 && options.briefing.trim().length > 0) {
43535
43608
  lines.push("", options.briefing);
43536
43609
  }
@@ -43759,6 +43832,7 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
43759
43832
  } else if (options.pythonToolsAvailable === true) {
43760
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.");
43761
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.");
43762
43836
  if (options.skills !== void 0 || options.skillsSearchable === true) {
43763
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 ? [
43764
43838
  "- `search_team_skills` searches what OTHER people have taught their assistants. Use it",
@@ -44245,6 +44319,9 @@ function trailerFor(agent, team) {
44245
44319
  if (agent.role === "reviewer" && programmer !== void 0) {
44246
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.");
44247
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
+ }
44248
44325
  if (agent.role === "programmer") {
44249
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.");
44250
44327
  }
@@ -44262,9 +44339,12 @@ function resolveTeam(context) {
44262
44339
  const assignment = context.config?.roles?.[role] ?? defaultAssignment(role, context);
44263
44340
  if (assignment === void 0)
44264
44341
  continue;
44342
+ if (assignment.enabled === false)
44343
+ continue;
44265
44344
  const info = roleInfo(role, custom2);
44266
44345
  const prompt = assignment.prompt ?? defaultPromptFor(role, custom2);
44267
44346
  const usesTools = assignment.tools ?? info.usesTools;
44347
+ const canWrite = assignment.write ?? info.canWrite;
44268
44348
  if (assignment.kind === "cli") {
44269
44349
  resolved.push({
44270
44350
  role,
@@ -44274,11 +44354,14 @@ function resolveTeam(context) {
44274
44354
  label: "Claude",
44275
44355
  prompt,
44276
44356
  usesTools,
44357
+ canWrite,
44277
44358
  available: context.cliAvailable,
44278
44359
  ...context.cliAvailable ? {} : { reason: "The Claude CLI is not available on this machine." }
44279
44360
  });
44280
44361
  continue;
44281
44362
  }
44363
+ if (assignment.profileId === void 0)
44364
+ continue;
44282
44365
  const profile = context.profiles.find((candidate) => candidate.id === assignment.profileId);
44283
44366
  resolved.push({
44284
44367
  role,
@@ -44289,6 +44372,7 @@ function resolveTeam(context) {
44289
44372
  label: profile?.label ?? assignment.profileId ?? "unassigned",
44290
44373
  prompt,
44291
44374
  usesTools,
44375
+ canWrite,
44292
44376
  available: profile !== void 0,
44293
44377
  /*
44294
44378
  * A profile that has been deleted leaves the role unavailable and says so, rather than
@@ -44583,11 +44667,26 @@ function buildRoster(team, self) {
44583
44667
  "- **Readers** \u2014 the reviewer, the tester, the librarian. Worth a step where another pair of",
44584
44668
  " eyes changes what happens: risky or fiddly code, a step that finishes something, a",
44585
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.",
44586
44673
  "- **The programmer writes.** Where a step is a self-contained piece of code with a spec",
44587
44674
  " clear enough to hand over \u2014 a parser, a schema, a set of pure functions \u2014 say so and give",
44588
44675
  " it to the programmer. The assistant checks what comes back against the real file and",
44589
44676
  " applies it, so this is delegation rather than trust.",
44590
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
+ "",
44591
44690
  "Only where it genuinely changes the outcome: a plan that routes every step through all of",
44592
44691
  "them is ceremony, and one that routes none wastes a team that is sitting there."
44593
44692
  );
@@ -44637,11 +44736,109 @@ function buildAgentBriefing(input) {
44637
44736
  return sections.join("\n");
44638
44737
  }
44639
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
+
44640
44837
  // ../../packages/core/dist/agents/consult.js
44641
44838
  var CONSULT_MAX_STEPS = 5;
44642
44839
  var ALLOWED_GROUPS = /* @__PURE__ */ new Set(["read"]);
44643
- function toolsForConsultation(all) {
44644
- 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");
44645
44842
  }
44646
44843
  async function runConsultation(options) {
44647
44844
  const limit = options.maxSteps ?? CONSULT_MAX_STEPS;
@@ -44691,7 +44888,10 @@ async function runConsultation(options) {
44691
44888
  }
44692
44889
  try {
44693
44890
  const parsed = tool.parametersSchema.safeParse(JSON.parse(call.arguments || "{}"));
44694
- 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) : {
44695
44895
  content: `Those arguments are not valid: ${parsed.error.issues.map((i) => i.message).join("; ")}`
44696
44896
  };
44697
44897
  messages.push({ role: "tool", toolCallId: call.id, content: String(result.content) });
@@ -48677,7 +48877,12 @@ var NEVER_AVAILABLE_TO_SCHEDULES = [
48677
48877
  * Rewriting the plan it is being held to, with nobody there to approve the diff. Same ladder
48678
48878
  * as `schedule_prompt`: a run that can change its own instructions is bounded by nothing.
48679
48879
  */
48680
- "update_plan"
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"
48681
48886
  ];
48682
48887
  function scheduleAppliesHere(schedule, workspaceRoot) {
48683
48888
  if (schedule.workspaceRoot === void 0)
@@ -49849,93 +50054,6 @@ async function indexWorkspace(options) {
49849
50054
  };
49850
50055
  }
49851
50056
 
49852
- // ../../packages/core/dist/approval/types.js
49853
- function requiresApproval(group) {
49854
- return group !== "always";
49855
- }
49856
-
49857
- // ../../packages/core/dist/approval/commands.js
49858
- function isCommandAllowlisted(command, allowlist) {
49859
- return allowlist.includes(command);
49860
- }
49861
- function addToAllowlist(command, allowlist) {
49862
- return allowlist.includes(command) ? [...allowlist] : [...allowlist, command];
49863
- }
49864
- function removeFromAllowlist(command, allowlist) {
49865
- return allowlist.filter((entry) => entry !== command);
49866
- }
49867
-
49868
- // ../../packages/core/dist/approval/policy.js
49869
- function isApprovableGroup(group) {
49870
- return group === "read" || group === "edit" || group === "command" || group === "mcp";
49871
- }
49872
- function categoryEnabled(group, settings) {
49873
- if (settings === void 0 || !isApprovableGroup(group))
49874
- return false;
49875
- return settings[group] === true;
49876
- }
49877
- var ALWAYS_ASK_TOOLS = /* @__PURE__ */ new Set([
49878
- "create_python_tool",
49879
- "update_python_tool",
49880
- "delete_python_tool",
49881
- "write_skill",
49882
- "delete_skill",
49883
- /*
49884
- * VBA installed into a workbook runs on this machine as this user, and nobody reviews a macro
49885
- * afterwards. That is the same act as creating a Python tool, so it gets the same rule: a
49886
- * human sees the source once, and no category toggle can stand in for that.
49887
- */
49888
- "excel_write_macro",
49889
- /*
49890
- * Running a macro executes somebody else's VBA as the user: it can rewrite the workbook, write
49891
- * files, or send mail. That is not something a category toggle should ever cover, and the
49892
- * approval showing the actual source is the only thing standing between "run DoTheThing" and
49893
- * whatever DoTheThing does.
49894
- */
49895
- "excel_run_macro",
49896
- /*
49897
- * The plan is what holds the assistant to work the user agreed, so a category toggle must
49898
- * never stand in for reading the change. Auto-approving this would mean an agent could widen
49899
- * its own instructions and then point at them as authority — and both the panel and the
49900
- * prompt would look right afterwards, because both would be reading the new plan.
49901
- */
49902
- "update_plan"
49903
- ]);
49904
- function decideFromPolicy(request, approvals) {
49905
- if (!requiresApproval(request.group))
49906
- return "approve";
49907
- if (ALWAYS_ASK_TOOLS.has(request.toolName))
49908
- return void 0;
49909
- if (approvals === void 0)
49910
- return void 0;
49911
- if (approvals.allowedTools?.includes(request.toolName) === true)
49912
- return "approve";
49913
- if (request.group === "command") {
49914
- const command = commandFromPreview(request.preview);
49915
- if (command !== void 0 && isCommandAllowlisted(command, approvals.allowedCommands ?? [])) {
49916
- return "approve";
49917
- }
49918
- }
49919
- return categoryEnabled(request.group, approvals.autoApprove) ? "approve" : void 0;
49920
- }
49921
- function commandFromPreview(preview) {
49922
- return preview.kind === "command" ? preview.command : void 0;
49923
- }
49924
- var PolicyApprovalGate = class {
49925
- inner;
49926
- getApprovals;
49927
- constructor(inner, getApprovals) {
49928
- this.inner = inner;
49929
- this.getApprovals = getApprovals;
49930
- }
49931
- async requestApproval(request) {
49932
- const decided = decideFromPolicy(request, this.getApprovals());
49933
- if (decided !== void 0)
49934
- return decided;
49935
- return this.inner.requestApproval(request);
49936
- }
49937
- };
49938
-
49939
50057
  // ../../packages/core/dist/checkpoints/shadowGit.js
49940
50058
  import { execFile as execFile2 } from "node:child_process";
49941
50059
  import fs7 from "node:fs/promises";
@@ -57230,6 +57348,29 @@ function looksUnfinished(text) {
57230
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.";
57231
57349
  var MAX_CONTINUE_NUDGES = 1;
57232
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
+
57233
57374
  // ../../packages/core/dist/agent/truncate.js
57234
57375
  import { randomUUID as randomUUID2 } from "node:crypto";
57235
57376
  import fs14 from "node:fs/promises";
@@ -57327,7 +57468,7 @@ var MAX_REFUNDED_STEPS = 20;
57327
57468
  var MAX_CONSECUTIVE_MISTAKES = 3;
57328
57469
  async function prepareModelMessages(conversation, provider, tools, options, events) {
57329
57470
  const contextWindow = options.contextWindow ?? 0;
57330
- let messages = conversation.toModelMessages();
57471
+ let messages = repairUnansweredToolCalls(conversation.toModelMessages());
57331
57472
  if (options.compactionEnabled !== false && contextWindow > 0) {
57332
57473
  const estimated = computeBreakdown(messages, tools, contextWindow).total;
57333
57474
  if (shouldCompact(messages, estimated, contextWindow, options.compaction ?? {})) {
@@ -57337,7 +57478,7 @@ async function prepareModelMessages(conversation, provider, tools, options, even
57337
57478
  if (summary !== void 0) {
57338
57479
  conversation.applyCompaction(summary, conversation.compactedCount() + result.summarisedCount);
57339
57480
  events.onCompacted?.(result.summarisedCount);
57340
- messages = conversation.toModelMessages();
57481
+ messages = repairUnansweredToolCalls(conversation.toModelMessages());
57341
57482
  }
57342
57483
  }
57343
57484
  }
@@ -57557,12 +57698,20 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
57557
57698
  }
57558
57699
  conversation.addAssistantMessage(assistantText, [toolCall]);
57559
57700
  events.onToolCall(toolCall);
57560
- const result = await runOneToolCall(toolCall, toolRegistry, toolContext, options, events, {
57561
- hasCheckpoint: () => checkpointTaken,
57562
- markCheckpointTaken: () => {
57563
- checkpointTaken = true;
57564
- }
57565
- }, 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
+ }
57566
57715
  const forModel = options.truncationStore !== void 0 ? (await truncateToolResult(result.content, options.truncationStore)).content : result.content;
57567
57716
  conversation.addToolResultMessage(toolCall.id, forModel);
57568
57717
  events.onToolResult(toolCall, result);
@@ -59646,6 +59795,232 @@ var OfficeBridge = class {
59646
59795
  }
59647
59796
  };
59648
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
+
59649
60024
  // ../../packages/core/dist/office/vbaCheck.js
59650
60025
  function splitLine(line) {
59651
60026
  let bare = "";
@@ -60842,6 +61217,54 @@ ${preview.text}` } : {}
60842
61217
  post({ type: "plan", plan: activePlan ?? "" });
60843
61218
  postPlanProgress();
60844
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
+ };
60845
61268
  const planAccess = {
60846
61269
  current: () => activePlan,
60847
61270
  save: async (nextPlan) => {
@@ -61109,6 +61532,8 @@ ${preview.text}` } : {}
61109
61532
  let cachedCodeGenerator;
61110
61533
  let cachedTeam = [];
61111
61534
  let cachedTeamGuidance;
61535
+ let cachedAgentRoles;
61536
+ let cachedAgentDefinitions = [];
61112
61537
  let cachedBudgetMatters = false;
61113
61538
  let cachedMentionExcludes;
61114
61539
  let cachedReportsCost;
@@ -61159,6 +61584,8 @@ ${preview.text}` } : {}
61159
61584
  cliAvailable: expertCli?.available === true
61160
61585
  };
61161
61586
  cachedTeam = resolveTeam(teamContext);
61587
+ cachedAgentRoles = config2.agents?.roles;
61588
+ cachedAgentDefinitions = config2.agents?.definitions ?? [];
61162
61589
  cachedTeamGuidance = config2.agents?.teamGuidance;
61163
61590
  cachedBudgetMatters = budgetMatters(teamContext);
61164
61591
  cachedProgrammingProfileId = config2.programmingProfileId;
@@ -61312,6 +61739,10 @@ ${preview.text}` } : {}
61312
61739
  combined.register(tool, { dispatchOnly: dispatcher });
61313
61740
  combined.register(createUpdatePlanTool(planAccess), { dispatchOnly: dispatcher });
61314
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 });
61315
61746
  combined.register(createNotifyTool({
61316
61747
  notify: (message3, level, details) => {
61317
61748
  if (details !== void 0) {
@@ -62056,7 +62487,7 @@ ${preview.text}` } : {}
62056
62487
  }
62057
62488
  if (input.authType === "none")
62058
62489
  return { type: "none" };
62059
- const typed = input.apiKey.trim();
62490
+ const typed = (input.apiKey ?? "").trim();
62060
62491
  if (describeSecretRef(typed).kind === "env") {
62061
62492
  await secrets.delete(apiKeyRefFor(id));
62062
62493
  return { type: "apiKey", apiKeyRef: typed };
@@ -62210,6 +62641,19 @@ ${preview.text}` } : {}
62210
62641
  }
62211
62642
  }
62212
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
+ }
62213
62657
  const baseUrl = input.baseUrl.trim();
62214
62658
  if (baseUrl.length === 0) {
62215
62659
  post({ type: "error", message: "Enter a base URL first." });
@@ -62294,7 +62738,9 @@ ${preview.text}` } : {}
62294
62738
  cliAvailable: cli?.available === true
62295
62739
  };
62296
62740
  const assigned = new Map(resolveTeam(teamContext).map((agent) => [agent.role, agent]));
62297
- 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) => {
62298
62744
  const agent = assigned.get(info.role);
62299
62745
  const prompt = config2.agents?.roles?.[info.role]?.prompt;
62300
62746
  return {
@@ -62306,8 +62752,14 @@ ${preview.text}` } : {}
62306
62752
  label: agent?.label ?? "Nobody",
62307
62753
  available: agent?.available ?? false,
62308
62754
  ...agent?.reason !== void 0 ? { reason: agent.reason } : {},
62309
- prompt: prompt ?? defaultPromptFor(info.role),
62310
- 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
62311
62763
  };
62312
62764
  });
62313
62765
  const guidance = config2.agents?.teamGuidance;
@@ -62336,6 +62788,51 @@ ${preview.text}` } : {}
62336
62788
  }
62337
62789
  });
62338
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
+ }
62339
62836
  async function saveAgents(change) {
62340
62837
  try {
62341
62838
  const { config: config2 } = await configManager.load();
@@ -64367,6 +64864,7 @@ ${preview.text}` } : {}
64367
64864
  // disagree — a specialist told it can read, and then given nothing to read with, wastes a
64368
64865
  // step discovering that.
64369
64866
  usesTools: agent.usesTools,
64867
+ canWrite: agent.canWrite,
64370
64868
  ...request.files !== void 0 ? { files: request.files } : {},
64371
64869
  /*
64372
64870
  * What exists in this workspace.
@@ -64395,6 +64893,11 @@ ${preview.text}` } : {}
64395
64893
  const cli = expertCli;
64396
64894
  if (cli === void 0 || !cli.available)
64397
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
+ }
64398
64901
  const answer = await consultExpert(cli, {
64399
64902
  question: prompt,
64400
64903
  /*
@@ -64405,6 +64908,10 @@ ${preview.text}` } : {}
64405
64908
  cwd: workspaceRoot ?? process.cwd(),
64406
64909
  ...request.signal !== void 0 ? { signal: request.signal } : {}
64407
64910
  });
64911
+ recordConsultation({
64912
+ isError: answer.isError,
64913
+ ...answer.costUsd !== void 0 ? { costUsd: answer.costUsd } : {}
64914
+ });
64408
64915
  if (answer.isError)
64409
64916
  throw new Error(answer.text);
64410
64917
  return { advice: answer.text, label: agent.label };
@@ -64415,7 +64922,13 @@ ${preview.text}` } : {}
64415
64922
  throw new Error(`No profile "${agent.profileId ?? ""}" exists any more.`);
64416
64923
  }
64417
64924
  const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger);
64418
- const readOnly = agent.usesTools ? 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) : [];
64419
64932
  const context = consultationContext?.();
64420
64933
  const result = await runConsultation({
64421
64934
  provider,
@@ -64425,6 +64938,24 @@ ${preview.text}` } : {}
64425
64938
  // With no context there is nothing to read *with*, so it answers from the question alone
64426
64939
  // rather than being offered tools that would fail.
64427
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
+ },
64428
64959
  ...request.signal !== void 0 ? { signal: request.signal } : {},
64429
64960
  onStep: (name) => logger.info(`${agent.role} looked up ${name}`)
64430
64961
  });
@@ -65188,7 +65719,7 @@ ${preview.text}` } : {}
65188
65719
  } else if (message3.type === "setAgentRole") {
65189
65720
  const assignment = message3.assignment;
65190
65721
  const role = message3.role;
65191
- if (!isAgentRole(role)) {
65722
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
65192
65723
  post({ type: "error", message: `There is no "${role}" role.` });
65193
65724
  return;
65194
65725
  }
@@ -65208,7 +65739,7 @@ ${preview.text}` } : {}
65208
65739
  } else if (message3.type === "setAgentPrompt") {
65209
65740
  const role = message3.role;
65210
65741
  const prompt = message3.prompt;
65211
- if (!isAgentRole(role)) {
65742
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
65212
65743
  post({ type: "error", message: `There is no "${role}" role.` });
65213
65744
  return;
65214
65745
  }
@@ -65239,10 +65770,50 @@ ${preview.text}` } : {}
65239
65770
  }
65240
65771
  return { ...current, teamGuidance: guidance };
65241
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
+ });
65242
65813
  } else if (message3.type === "setAgentColor") {
65243
65814
  const role = message3.role;
65244
65815
  const color = message3.color;
65245
- if (!isAgentRole(role)) {
65816
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
65246
65817
  post({ type: "error", message: `There is no "${role}" role.` });
65247
65818
  return;
65248
65819
  }
@@ -69341,7 +69912,7 @@ function respondJson(response, status, body) {
69341
69912
  }
69342
69913
 
69343
69914
  // src/cli.ts
69344
- var VERSION = true ? "0.50.0" : "unknown (not a packaged build)";
69915
+ var VERSION = true ? "0.56.1" : "unknown (not a packaged build)";
69345
69916
  var compat = installNodeCompat();
69346
69917
  function lastMeaningfulLine(problem) {
69347
69918
  const lines = problem.split(String.fromCharCode(10)).map((line) => line.trim()).filter((line) => line.length > 0 && !line.endsWith(":"));