@chosengeneration/light-code 0.50.0 → 0.59.0

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
@@ -39675,6 +39675,33 @@ var providerProfileSchema = external_exports.object({
39675
39675
  * a working fallback in the adapter rather than being mandatory here.
39676
39676
  */
39677
39677
  maxTokens: external_exports.number().int().positive().optional(),
39678
+ /**
39679
+ * Sampling, sent only when set.
39680
+ *
39681
+ * Absent means the server's default, which is what every request used before this existed. That
39682
+ * default is frequently 1.0, and on a mid-size model a high temperature is felt most sharply in
39683
+ * the one place it is least wanted: tool calls. A model that has to emit exactly
39684
+ * `{"path":"src/a.ts"}` and is sampling freely produces a plausible-looking argument that is
39685
+ * subtly wrong, and the failure surfaces as a tool error rather than as anything pointing at
39686
+ * sampling. Large models absorb this; smaller ones do not.
39687
+ *
39688
+ * Not given a default here, because a default would apply to every profile including the ones
39689
+ * that are fine, and silently changing how somebody's working model behaves is worse than
39690
+ * leaving a setting unset.
39691
+ */
39692
+ temperature: external_exports.number().min(0).max(2).optional(),
39693
+ topP: external_exports.number().min(0).max(1).optional(),
39694
+ /**
39695
+ * How hard this model should think, translated per wire format by `providers/thinking.ts`.
39696
+ *
39697
+ * Absent sends nothing, which is what every request did before this existed and the only
39698
+ * setting that cannot break a gateway nobody has tested against.
39699
+ */
39700
+ thinking: external_exports.object({
39701
+ level: external_exports.enum(["off", "low", "medium", "high"]),
39702
+ /** Only consulted for the OpenAI wire format, where the parameter is genuinely ambiguous. */
39703
+ style: external_exports.enum(["effort", "qwen"]).optional()
39704
+ }).optional(),
39678
39705
  /**
39679
39706
  * Per-profile corrections to the local capability table (§9). Needed because gateway
39680
39707
  * aliases hide the underlying model, so the table cannot recognise them.
@@ -39769,7 +39796,41 @@ var agentAssignmentSchema = external_exports.object({
39769
39796
  * has looked at the tab without editing anything. Storing the default verbatim would pin
39770
39797
  * every user to whatever it said the day they first opened it.
39771
39798
  */
39772
- prompt: external_exports.string().optional()
39799
+ prompt: external_exports.string().optional(),
39800
+ /**
39801
+ * Whether this specialist may read and search the workspace, overriding the role's default.
39802
+ *
39803
+ * On the assignment rather than the role because it depends on *who* is answering: a small
39804
+ * local model given five lookups can spend them all and answer worse, where a strong one
39805
+ * uses them well. Absent means the role's own default.
39806
+ */
39807
+ tools: external_exports.boolean().optional(),
39808
+ /**
39809
+ * Whether this specialist may change things, each change through the approval gate.
39810
+ *
39811
+ * Off by default everywhere. §12b's rule is that a consultant is read-only; this is the
39812
+ * deliberate exception, and it is per role because "the programmer may edit" and "the tester
39813
+ * may edit" are quite different decisions.
39814
+ */
39815
+ write: external_exports.boolean().optional(),
39816
+ /**
39817
+ * Whether this role is in play at all.
39818
+ *
39819
+ * Distinct from unassigning it, which is why both exist: unassigning forgets *who* answered,
39820
+ * and somebody switching a specialist off for one job does not want to lose the model, the
39821
+ * prompt and the flags they set up. Absent means on, so nothing changes for a config written
39822
+ * before this.
39823
+ */
39824
+ enabled: external_exports.boolean().optional(),
39825
+ /**
39826
+ * How hard this seat should think, overriding whatever its profile says.
39827
+ *
39828
+ * On the assignment because it belongs to the *job*, not to the model: the same Qwen is worth
39829
+ * thinking hard as the expert, where it is planning a change across files, and worth answering
39830
+ * quickly as the librarian, where it is reading back what is written down. One profile, two
39831
+ * seats, two settings.
39832
+ */
39833
+ thinking: external_exports.enum(["off", "low", "medium", "high"]).optional()
39773
39834
  }).strict();
39774
39835
  var customRoleSchema = external_exports.object({
39775
39836
  id: external_exports.string().min(1),
@@ -39817,6 +39878,20 @@ var workspaceApprovalsSchema = external_exports.object({
39817
39878
  /** Exact command strings — never patterns. See approval/commands.ts and §8. */
39818
39879
  allowedCommands: external_exports.array(external_exports.string())
39819
39880
  }).partial();
39881
+ var juniorAssessmentSchema = external_exports.object({
39882
+ model: external_exports.string(),
39883
+ profileLabel: external_exports.string(),
39884
+ assessedAt: external_exports.number(),
39885
+ verdict: external_exports.string(),
39886
+ costUsd: external_exports.number().optional(),
39887
+ probes: external_exports.array(external_exports.object({
39888
+ id: external_exports.string(),
39889
+ measures: external_exports.string(),
39890
+ prompt: external_exports.string(),
39891
+ answer: external_exports.string(),
39892
+ error: external_exports.string().optional()
39893
+ }))
39894
+ });
39820
39895
  var expertConfigSchema = external_exports.object({
39821
39896
  /** Off unless explicitly enabled. Nothing is spawned or spent without this. */
39822
39897
  enabled: external_exports.boolean(),
@@ -39849,20 +39924,16 @@ var expertConfigSchema = external_exports.object({
39849
39924
  * there is one, for the model that was assessed, and it records which that was so a stale
39850
39925
  * one is recognisable rather than silently applied to a different model.
39851
39926
  */
39852
- assessment: external_exports.object({
39853
- model: external_exports.string(),
39854
- profileLabel: external_exports.string(),
39855
- assessedAt: external_exports.number(),
39856
- verdict: external_exports.string(),
39857
- costUsd: external_exports.number().optional(),
39858
- probes: external_exports.array(external_exports.object({
39859
- id: external_exports.string(),
39860
- measures: external_exports.string(),
39861
- prompt: external_exports.string(),
39862
- answer: external_exports.string(),
39863
- error: external_exports.string().optional()
39864
- }))
39865
- }).optional(),
39927
+ assessment: juniorAssessmentSchema.optional(),
39928
+ /**
39929
+ * Every model assessed, so several can be compared.
39930
+ *
39931
+ * One slot answers "is this model any good"; deciding which of four models reviews and which
39932
+ * writes needs them side by side, and assessing the second used to destroy the evidence about
39933
+ * the first. Read through `expert/assessments.ts`, never directly, so this and the single
39934
+ * `assessment` above cannot come apart.
39935
+ */
39936
+ assessments: external_exports.array(juniorAssessmentSchema).optional(),
39866
39937
  /**
39867
39938
  * Consultations allowed within one task. 0 means no limit.
39868
39939
  *
@@ -42279,6 +42350,98 @@ function normalizeObjectSchema(parameters) {
42279
42350
  return normalized;
42280
42351
  }
42281
42352
 
42353
+ // ../../packages/core/dist/providers/thinking.js
42354
+ var BUDGETS = {
42355
+ low: 2048,
42356
+ medium: 8192,
42357
+ high: 24576
42358
+ };
42359
+ function applyThinking(body, wireFormat, settings, maxTokens) {
42360
+ if (settings === void 0)
42361
+ return;
42362
+ if (wireFormat === "anthropic") {
42363
+ if (settings.level === "off")
42364
+ return;
42365
+ const ceiling = maxTokens !== void 0 ? Math.max(1024, maxTokens - 1024) : Infinity;
42366
+ body.thinking = {
42367
+ type: "enabled",
42368
+ budget_tokens: Math.min(BUDGETS[settings.level], ceiling)
42369
+ };
42370
+ return;
42371
+ }
42372
+ if (wireFormat === "gemini") {
42373
+ body.thinkingConfig = {
42374
+ thinkingBudget: settings.level === "off" ? 0 : BUDGETS[settings.level]
42375
+ };
42376
+ return;
42377
+ }
42378
+ if (settings.style === "qwen") {
42379
+ body.chat_template_kwargs = { enable_thinking: settings.level !== "off" };
42380
+ return;
42381
+ }
42382
+ if (settings.level === "off")
42383
+ return;
42384
+ body.reasoning_effort = settings.level;
42385
+ }
42386
+
42387
+ // ../../packages/core/dist/providers/thinkTags.js
42388
+ var OPEN = "<think>";
42389
+ var CLOSE = "</think>";
42390
+ var ThinkTagSplitter = class {
42391
+ inside = false;
42392
+ /** A partial tag held back until the next chunk says what it is. */
42393
+ pending = "";
42394
+ push(chunk) {
42395
+ let text = "";
42396
+ let reasoning = "";
42397
+ let buffer = this.pending + chunk;
42398
+ this.pending = "";
42399
+ for (; ; ) {
42400
+ const marker = this.inside ? CLOSE : OPEN;
42401
+ const at = buffer.indexOf(marker);
42402
+ if (at !== -1) {
42403
+ const before = buffer.slice(0, at);
42404
+ if (this.inside)
42405
+ reasoning += before;
42406
+ else
42407
+ text += before;
42408
+ this.inside = !this.inside;
42409
+ buffer = buffer.slice(at + marker.length);
42410
+ continue;
42411
+ }
42412
+ const keep = partialMarkerLength(buffer, marker);
42413
+ const usable = buffer.slice(0, buffer.length - keep);
42414
+ this.pending = buffer.slice(buffer.length - keep);
42415
+ if (this.inside)
42416
+ reasoning += usable;
42417
+ else
42418
+ text += usable;
42419
+ break;
42420
+ }
42421
+ return { text, reasoning };
42422
+ }
42423
+ /**
42424
+ * Whatever is still held back when the stream ends.
42425
+ *
42426
+ * A truncated stream can leave a partial tag, or an unclosed `<think>`. Emitting the remainder
42427
+ * rather than dropping it means a cut-off reply still shows what there was — losing the end of
42428
+ * an answer to a tag that never closed would be a worse failure than showing a stray `<`.
42429
+ */
42430
+ flush() {
42431
+ const rest = this.pending;
42432
+ this.pending = "";
42433
+ return this.inside ? { text: "", reasoning: rest } : { text: rest, reasoning: "" };
42434
+ }
42435
+ };
42436
+ function partialMarkerLength(buffer, marker) {
42437
+ const most = Math.min(marker.length - 1, buffer.length);
42438
+ for (let length = most; length > 0; length -= 1) {
42439
+ if (marker.startsWith(buffer.slice(buffer.length - length)))
42440
+ return length;
42441
+ }
42442
+ return 0;
42443
+ }
42444
+
42282
42445
  // ../../packages/core/dist/providers/openai.js
42283
42446
  function describeRequestError(error51, url2) {
42284
42447
  return `Could not reach ${url2}: ${describeTlsError(error51)}`;
@@ -42333,6 +42496,11 @@ var OpenAIProvider = class {
42333
42496
  body.tools = toOpenAITools(options.tools);
42334
42497
  body.tool_choice = "auto";
42335
42498
  }
42499
+ if (this.profile.temperature !== void 0)
42500
+ body.temperature = this.profile.temperature;
42501
+ if (this.profile.topP !== void 0)
42502
+ body.top_p = this.profile.topP;
42503
+ applyThinking(body, "openai", this.profile.thinking, this.profile.maxTokens);
42336
42504
  let response;
42337
42505
  try {
42338
42506
  await this.auth.ensureTokenForStream?.();
@@ -42417,6 +42585,7 @@ async function* parseSseStream(body, url2, signal, logger) {
42417
42585
  const reader = body.getReader();
42418
42586
  const decoder = new TextDecoder();
42419
42587
  let buffer = "";
42588
+ const thinking = new ThinkTagSplitter();
42420
42589
  const toolCallAccumulators = /* @__PURE__ */ new Map();
42421
42590
  try {
42422
42591
  while (true) {
@@ -42447,7 +42616,11 @@ async function* parseSseStream(body, url2, signal, logger) {
42447
42616
  yield { type: "reasoning", text: reasoning };
42448
42617
  }
42449
42618
  if (typeof choice.delta.content === "string" && choice.delta.content.length > 0) {
42450
- yield { type: "text", text: choice.delta.content };
42619
+ const split = thinking.push(choice.delta.content);
42620
+ if (split.reasoning.length > 0)
42621
+ yield { type: "reasoning", text: split.reasoning };
42622
+ if (split.text.length > 0)
42623
+ yield { type: "text", text: split.text };
42451
42624
  }
42452
42625
  accumulateToolCallDeltas(toolCallAccumulators, choice.delta.tool_calls);
42453
42626
  if (choice.finishReason === "tool_calls") {
@@ -42499,6 +42672,11 @@ var AnthropicProvider = class {
42499
42672
  };
42500
42673
  if (system !== void 0)
42501
42674
  body.system = system;
42675
+ if (this.profile.temperature !== void 0)
42676
+ body.temperature = this.profile.temperature;
42677
+ if (this.profile.topP !== void 0)
42678
+ body.top_p = this.profile.topP;
42679
+ applyThinking(body, "anthropic", this.profile.thinking, this.profile.maxTokens ?? DEFAULT_MAX_TOKENS);
42502
42680
  if (options.tools !== void 0 && options.tools.length > 0) {
42503
42681
  body.tools = toAnthropicTools(options.tools);
42504
42682
  }
@@ -42724,6 +42902,21 @@ var GeminiProvider = class {
42724
42902
  if (this.profile.maxTokens !== void 0) {
42725
42903
  body.generationConfig = { maxOutputTokens: this.profile.maxTokens };
42726
42904
  }
42905
+ if (this.profile.temperature !== void 0 || this.profile.topP !== void 0) {
42906
+ body.generationConfig = {
42907
+ ...body.generationConfig ?? {},
42908
+ ...this.profile.temperature !== void 0 ? { temperature: this.profile.temperature } : {},
42909
+ ...this.profile.topP !== void 0 ? { topP: this.profile.topP } : {}
42910
+ };
42911
+ }
42912
+ applyThinking(body, "gemini", this.profile.thinking, this.profile.maxTokens);
42913
+ if (body.thinkingConfig !== void 0) {
42914
+ body.generationConfig = {
42915
+ ...body.generationConfig ?? {},
42916
+ thinkingConfig: body.thinkingConfig
42917
+ };
42918
+ delete body.thinkingConfig;
42919
+ }
42727
42920
  let response;
42728
42921
  try {
42729
42922
  await this.auth.ensureTokenForStream?.();
@@ -43348,6 +43541,11 @@ var Conversation = class {
43348
43541
 
43349
43542
  // ../../packages/core/dist/agents/roles.js
43350
43543
  var AGENT_ROLES = ["expert", "programmer", "reviewer", "tester", "librarian"];
43544
+ var CUSTOM_ROLE_LIMIT = 5;
43545
+ var ROLE_ID = /^[a-z][a-z0-9-]{1,23}$/;
43546
+ function isValidRoleId(id) {
43547
+ return ROLE_ID.test(id) && !AGENT_ROLES.includes(id);
43548
+ }
43351
43549
  function isAgentRole(value, custom2 = []) {
43352
43550
  return AGENT_ROLES.includes(value) || custom2.some((role) => role.id === value);
43353
43551
  }
@@ -43361,6 +43559,13 @@ var SHARED_TAIL = [
43361
43559
  "",
43362
43560
  "Answer in prose and short lists. No preamble about being happy to help."
43363
43561
  ];
43562
+ var MAY_WRITE = [
43563
+ "",
43564
+ "You can also change this workspace: edit files, and record a skill. Every such change is shown",
43565
+ "to the user and approved by them before it happens, so make each one small enough to read and",
43566
+ "say what it is for. Prefer telling the assistant what to change where the change is large or",
43567
+ "spans files \u2014 it has the whole picture and you have only what you asked for."
43568
+ ].join("\n");
43364
43569
  var SHARED_WITH_TOOLS = [
43365
43570
  "You can read this workspace: open files, list them, and search. Use that rather than guessing,",
43366
43571
  "and rather than asking the assistant for something you can fetch yourself. You have a small",
@@ -43378,8 +43583,9 @@ var SHARED_BLIND = [
43378
43583
  "",
43379
43584
  ...SHARED_TAIL
43380
43585
  ].join("\n");
43381
- function specialistPreamble(usesTools) {
43382
- return usesTools ? SHARED_WITH_TOOLS : SHARED_BLIND;
43586
+ function specialistPreamble(usesTools, canWrite = false) {
43587
+ const base = usesTools ? SHARED_WITH_TOOLS : SHARED_BLIND;
43588
+ return canWrite ? `${base}${MAY_WRITE}` : base;
43383
43589
  }
43384
43590
  var DEFINITIONS = {
43385
43591
  expert: {
@@ -43388,6 +43594,7 @@ var DEFINITIONS = {
43388
43594
  /* Planning a change means knowing what is already there, and it spans files the asker
43389
43595
  * cannot paste all of. */
43390
43596
  usesTools: true,
43597
+ canWrite: false,
43391
43598
  prompt: [
43392
43599
  "You are a senior engineer being consulted by another AI assistant that is doing the work.",
43393
43600
  "",
@@ -43405,6 +43612,7 @@ var DEFINITIONS = {
43405
43612
  /* It is handed a spec and the surrounding code and asked to write. Looking around buys
43406
43613
  * a slower answer that is no better. */
43407
43614
  usesTools: false,
43615
+ canWrite: false,
43408
43616
  prompt: [
43409
43617
  "You are an experienced programmer writing code for another AI assistant to apply.",
43410
43618
  "",
@@ -43435,6 +43643,7 @@ var DEFINITIONS = {
43435
43643
  /* Most of what a review turns on is *around* the diff — the callers, the neighbouring
43436
43644
  * function, whether this convention is really the convention. */
43437
43645
  usesTools: true,
43646
+ canWrite: false,
43438
43647
  prompt: [
43439
43648
  "You are reviewing a change written by another AI assistant.",
43440
43649
  "",
@@ -43462,6 +43671,7 @@ var DEFINITIONS = {
43462
43671
  /* The change is in front of it and the cases come from reasoning about it, not from
43463
43672
  * reading more of the codebase. */
43464
43673
  usesTools: false,
43674
+ canWrite: false,
43465
43675
  prompt: [
43466
43676
  "You design tests for code written by another AI assistant.",
43467
43677
  "",
@@ -43481,6 +43691,7 @@ var DEFINITIONS = {
43481
43691
  * left it answering from whatever happened to be pasted in. This is the role the flag
43482
43692
  * exists for. */
43483
43693
  usesTools: true,
43694
+ canWrite: false,
43484
43695
  prompt: [
43485
43696
  "You answer questions about how things are done here: internal libraries, house conventions,",
43486
43697
  "the shape of existing code, and what has already been written down.",
@@ -43490,7 +43701,29 @@ var DEFINITIONS = {
43490
43701
  "you are inferring \u2014 a convention you guessed at, stated confidently, becomes the convention.",
43491
43702
  "",
43492
43703
  "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."
43704
+ "with how it is usually done elsewhere unless you label it as exactly that.",
43705
+ "",
43706
+ /*
43707
+ * The one specialist that may write, and only this one thing.
43708
+ *
43709
+ * The objection was never that the librarian should not record what it knows — it is the
43710
+ * role that can see the gap. It was that a consultation asks nobody, so a skill written
43711
+ * there would be prose injected into every later prompt that no human had read (§13's
43712
+ * persistent prompt-injection vector). That was answered by making this path *ask*:
43713
+ * `runConsultation` routes anything in ALWAYS_ASK_TOOLS through the same approval gate the
43714
+ * agent loop uses, so the user sees the source exactly as they would for any other write.
43715
+ *
43716
+ * Everything else stays read-only. `consultBoundary.test.ts` holds that line, and pins the
43717
+ * rule that any name allowed past the group filter must be one the gate will stop on.
43718
+ */
43719
+ "When the answer is something worth writing down \u2014 a convention you had to piece together,",
43720
+ "a gotcha that will catch the next person, a procedure that is currently only in somebody's",
43721
+ "head \u2014 say so and **write it with `write_skill`**. The user is shown the text and",
43722
+ "approves it before anything is recorded, so write it as it should stand rather than",
43723
+ "describing what it would say. If they decline, say what you would have written and why.",
43724
+ "",
43725
+ "Say plainly when something already written down is **wrong or out of date**. A stale skill",
43726
+ "is worse than a missing one, because it is believed."
43494
43727
  ].join("\n")
43495
43728
  }
43496
43729
  };
@@ -43512,7 +43745,10 @@ function roleInfo(role, custom2 = []) {
43512
43745
  * accessibility — and those all turn on code the asker did not think to paste. The flag is
43513
43746
  * there to turn it off for the ones that are really "write this to spec".
43514
43747
  */
43515
- usesTools: defined.usesTools !== false
43748
+ usesTools: defined.usesTools !== false,
43749
+ // Off unless asked for: a role invented in a hurry should not be able to edit the
43750
+ // repository because nobody thought about the box.
43751
+ canWrite: defined.canWrite === true
43516
43752
  };
43517
43753
  }
43518
43754
  return {
@@ -43520,7 +43756,8 @@ function roleInfo(role, custom2 = []) {
43520
43756
  name: role,
43521
43757
  summary: "This role is no longer defined.",
43522
43758
  prompt: "",
43523
- usesTools: false
43759
+ usesTools: false,
43760
+ canWrite: false
43524
43761
  };
43525
43762
  }
43526
43763
  function allRoles(custom2 = []) {
@@ -43530,7 +43767,11 @@ function defaultPromptFor(role, custom2 = []) {
43530
43767
  return roleInfo(role, custom2).prompt;
43531
43768
  }
43532
43769
  function buildAgentPrompt(options) {
43533
- const lines = [options.prompt.trim(), "", specialistPreamble(options.usesTools)];
43770
+ const lines = [
43771
+ options.prompt.trim(),
43772
+ "",
43773
+ specialistPreamble(options.usesTools, options.canWrite === true)
43774
+ ];
43534
43775
  if (options.briefing !== void 0 && options.briefing.trim().length > 0) {
43535
43776
  lines.push("", options.briefing);
43536
43777
  }
@@ -43759,6 +44000,7 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
43759
44000
  } else if (options.pythonToolsAvailable === true) {
43760
44001
  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
44002
  }
44003
+ 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
44004
  if (options.skills !== void 0 || options.skillsSearchable === true) {
43763
44005
  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
44006
  "- `search_team_skills` searches what OTHER people have taught their assistants. Use it",
@@ -44245,6 +44487,9 @@ function trailerFor(agent, team) {
44245
44487
  if (agent.role === "reviewer" && programmer !== void 0) {
44246
44488
  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
44489
  }
44490
+ if (agent.role === "librarian") {
44491
+ 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.");
44492
+ }
44248
44493
  if (agent.role === "programmer") {
44249
44494
  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
44495
  }
@@ -44262,9 +44507,13 @@ function resolveTeam(context) {
44262
44507
  const assignment = context.config?.roles?.[role] ?? defaultAssignment(role, context);
44263
44508
  if (assignment === void 0)
44264
44509
  continue;
44510
+ if (assignment.enabled === false)
44511
+ continue;
44265
44512
  const info = roleInfo(role, custom2);
44266
44513
  const prompt = assignment.prompt ?? defaultPromptFor(role, custom2);
44267
44514
  const usesTools = assignment.tools ?? info.usesTools;
44515
+ const canWrite = assignment.write ?? info.canWrite;
44516
+ const thinking = assignment.thinking;
44268
44517
  if (assignment.kind === "cli") {
44269
44518
  resolved.push({
44270
44519
  role,
@@ -44274,11 +44523,15 @@ function resolveTeam(context) {
44274
44523
  label: "Claude",
44275
44524
  prompt,
44276
44525
  usesTools,
44526
+ canWrite,
44527
+ ...thinking !== void 0 ? { thinking } : {},
44277
44528
  available: context.cliAvailable,
44278
44529
  ...context.cliAvailable ? {} : { reason: "The Claude CLI is not available on this machine." }
44279
44530
  });
44280
44531
  continue;
44281
44532
  }
44533
+ if (assignment.profileId === void 0)
44534
+ continue;
44282
44535
  const profile = context.profiles.find((candidate) => candidate.id === assignment.profileId);
44283
44536
  resolved.push({
44284
44537
  role,
@@ -44289,6 +44542,8 @@ function resolveTeam(context) {
44289
44542
  label: profile?.label ?? assignment.profileId ?? "unassigned",
44290
44543
  prompt,
44291
44544
  usesTools,
44545
+ canWrite,
44546
+ ...thinking !== void 0 ? { thinking } : {},
44292
44547
  available: profile !== void 0,
44293
44548
  /*
44294
44549
  * A profile that has been deleted leaves the role unavailable and says so, rather than
@@ -44583,11 +44838,26 @@ function buildRoster(team, self) {
44583
44838
  "- **Readers** \u2014 the reviewer, the tester, the librarian. Worth a step where another pair of",
44584
44839
  " eyes changes what happens: risky or fiddly code, a step that finishes something, a",
44585
44840
  " convention you would otherwise be guessing at.",
44841
+ '- **The librarian writes down what should be written down.** A step like "record how this',
44842
+ ' is set up" is a good one to allocate: it reads what already exists and records the skill',
44843
+ " itself. The user approves the text before it is saved, so word the step as recording.",
44586
44844
  "- **The programmer writes.** Where a step is a self-contained piece of code with a spec",
44587
44845
  " clear enough to hand over \u2014 a parser, a schema, a set of pure functions \u2014 say so and give",
44588
44846
  " it to the programmer. The assistant checks what comes back against the real file and",
44589
44847
  " applies it, so this is delegation rather than trust.",
44590
44848
  "",
44849
+ /*
44850
+ * A role invented by the user, which no fixed description can cover.
44851
+ *
44852
+ * The two bullets above name the built-in five, and a plan written only from them would
44853
+ * quietly skip a `db-reviewer` the user went to the trouble of creating — the same failure
44854
+ * as never allocating the programmer, arriving from the other direction. The summary is the
44855
+ * only thing that can describe it, so the instruction is to read it.
44856
+ */
44857
+ "- **A role you do not recognise is described by its summary above.** The user invented it",
44858
+ " and wrote that line, so treat it as the authority on what the role is for and allocate it",
44859
+ " where the summary says it helps.",
44860
+ "",
44591
44861
  "Only where it genuinely changes the outcome: a plan that routes every step through all of",
44592
44862
  "them is ceremony, and one that routes none wastes a team that is sitting there."
44593
44863
  );
@@ -44637,11 +44907,109 @@ function buildAgentBriefing(input) {
44637
44907
  return sections.join("\n");
44638
44908
  }
44639
44909
 
44910
+ // ../../packages/core/dist/approval/commands.js
44911
+ function isCommandAllowlisted(command, allowlist) {
44912
+ return allowlist.includes(command);
44913
+ }
44914
+ function addToAllowlist(command, allowlist) {
44915
+ return allowlist.includes(command) ? [...allowlist] : [...allowlist, command];
44916
+ }
44917
+ function removeFromAllowlist(command, allowlist) {
44918
+ return allowlist.filter((entry) => entry !== command);
44919
+ }
44920
+
44921
+ // ../../packages/core/dist/approval/types.js
44922
+ function requiresApproval(group) {
44923
+ return group !== "always";
44924
+ }
44925
+
44926
+ // ../../packages/core/dist/approval/policy.js
44927
+ function isApprovableGroup(group) {
44928
+ return group === "read" || group === "edit" || group === "command" || group === "mcp";
44929
+ }
44930
+ function categoryEnabled(group, settings) {
44931
+ if (settings === void 0 || !isApprovableGroup(group))
44932
+ return false;
44933
+ return settings[group] === true;
44934
+ }
44935
+ var ALWAYS_ASK_TOOLS = /* @__PURE__ */ new Set([
44936
+ "create_python_tool",
44937
+ "update_python_tool",
44938
+ "delete_python_tool",
44939
+ "write_skill",
44940
+ "delete_skill",
44941
+ /*
44942
+ * VBA installed into a workbook runs on this machine as this user, and nobody reviews a macro
44943
+ * afterwards. That is the same act as creating a Python tool, so it gets the same rule: a
44944
+ * human sees the source once, and no category toggle can stand in for that.
44945
+ */
44946
+ "excel_write_macro",
44947
+ /*
44948
+ * Running a macro executes somebody else's VBA as the user: it can rewrite the workbook, write
44949
+ * files, or send mail. That is not something a category toggle should ever cover, and the
44950
+ * approval showing the actual source is the only thing standing between "run DoTheThing" and
44951
+ * whatever DoTheThing does.
44952
+ */
44953
+ "excel_run_macro",
44954
+ /*
44955
+ * The plan is what holds the assistant to work the user agreed, so a category toggle must
44956
+ * never stand in for reading the change. Auto-approving this would mean an agent could widen
44957
+ * its own instructions and then point at them as authority — and both the panel and the
44958
+ * prompt would look right afterwards, because both would be reading the new plan.
44959
+ */
44960
+ "update_plan",
44961
+ /*
44962
+ * A role's prompt is prose injected into a model that then advises on this repository's code —
44963
+ * the reason `agents` is user-scope only. Softening a reviewer does not error; it approves
44964
+ * things, in the same tone as before. A category toggle must never stand in for reading that
44965
+ * diff.
44966
+ */
44967
+ "update_role",
44968
+ // Inventing one is the same act as rewriting one: a prompt that will advise on this code.
44969
+ "create_role",
44970
+ // And removing one takes a prompt somebody wrote with it.
44971
+ "delete_role"
44972
+ ]);
44973
+ function decideFromPolicy(request, approvals) {
44974
+ if (!requiresApproval(request.group))
44975
+ return "approve";
44976
+ if (ALWAYS_ASK_TOOLS.has(request.toolName))
44977
+ return void 0;
44978
+ if (approvals === void 0)
44979
+ return void 0;
44980
+ if (approvals.allowedTools?.includes(request.toolName) === true)
44981
+ return "approve";
44982
+ if (request.group === "command") {
44983
+ const command = commandFromPreview(request.preview);
44984
+ if (command !== void 0 && isCommandAllowlisted(command, approvals.allowedCommands ?? [])) {
44985
+ return "approve";
44986
+ }
44987
+ }
44988
+ return categoryEnabled(request.group, approvals.autoApprove) ? "approve" : void 0;
44989
+ }
44990
+ function commandFromPreview(preview) {
44991
+ return preview.kind === "command" ? preview.command : void 0;
44992
+ }
44993
+ var PolicyApprovalGate = class {
44994
+ inner;
44995
+ getApprovals;
44996
+ constructor(inner, getApprovals) {
44997
+ this.inner = inner;
44998
+ this.getApprovals = getApprovals;
44999
+ }
45000
+ async requestApproval(request) {
45001
+ const decided = decideFromPolicy(request, this.getApprovals());
45002
+ if (decided !== void 0)
45003
+ return decided;
45004
+ return this.inner.requestApproval(request);
45005
+ }
45006
+ };
45007
+
44640
45008
  // ../../packages/core/dist/agents/consult.js
44641
45009
  var CONSULT_MAX_STEPS = 5;
44642
45010
  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");
45011
+ function toolsForConsultation(all, extra = /* @__PURE__ */ new Set()) {
45012
+ return all.filter((tool) => (ALLOWED_GROUPS.has(tool.group) || extra.has(tool.name)) && tool.name !== "ask_agent" && tool.name !== "ask_expert");
44645
45013
  }
44646
45014
  async function runConsultation(options) {
44647
45015
  const limit = options.maxSteps ?? CONSULT_MAX_STEPS;
@@ -44691,7 +45059,10 @@ async function runConsultation(options) {
44691
45059
  }
44692
45060
  try {
44693
45061
  const parsed = tool.parametersSchema.safeParse(JSON.parse(call.arguments || "{}"));
44694
- const result = parsed.success ? await tool.execute(parsed.data, options.context) : {
45062
+ const permitted = tool.group === "read" && !ALWAYS_ASK_TOOLS.has(tool.name) || options.approve !== void 0 && await options.approve(tool, parsed.data);
45063
+ const result = !permitted ? {
45064
+ 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.`
45065
+ } : parsed.success ? await tool.execute(parsed.data, options.context) : {
44695
45066
  content: `Those arguments are not valid: ${parsed.error.issues.map((i) => i.message).join("; ")}`
44696
45067
  };
44697
45068
  messages.push({ role: "tool", toolCallId: call.id, content: String(result.content) });
@@ -44900,6 +45271,58 @@ function buildExpertBriefing(input) {
44900
45271
  return sections.join("\n");
44901
45272
  }
44902
45273
 
45274
+ // ../../packages/core/dist/expert/assessments.js
45275
+ function allAssessments(expert) {
45276
+ const list = [...expert.assessments ?? []];
45277
+ const legacy = expert.assessment;
45278
+ if (legacy !== void 0 && !list.some((entry) => sameSubject(entry, legacy))) {
45279
+ list.push(legacy);
45280
+ }
45281
+ return list.sort((a, b) => b.assessedAt - a.assessedAt);
45282
+ }
45283
+ function assessmentFor(all, model, profileLabel) {
45284
+ if (model.length === 0)
45285
+ return void 0;
45286
+ const exact = profileLabel === void 0 ? void 0 : all.find((entry) => entry.model === model && entry.profileLabel === profileLabel);
45287
+ return exact ?? all.find((entry) => entry.model === model);
45288
+ }
45289
+ function recordAssessment(all, entry, limit = MAX_ASSESSMENTS) {
45290
+ const kept = all.filter((existing) => !sameSubject(existing, entry));
45291
+ return [entry, ...kept].sort((a, b) => b.assessedAt - a.assessedAt).slice(0, limit);
45292
+ }
45293
+ function forgetAssessment(all, model, profileLabel) {
45294
+ return all.filter((entry) => !(entry.model === model && entry.profileLabel === profileLabel));
45295
+ }
45296
+ var MAX_ASSESSMENTS = 12;
45297
+ function sameSubject(a, b) {
45298
+ return a.model === b.model && a.profileLabel === b.profileLabel;
45299
+ }
45300
+
45301
+ // ../../packages/core/dist/agents/seats.js
45302
+ var SEAT_FITS = [
45303
+ {
45304
+ role: "programmer",
45305
+ probes: ["code", "instruction-following"],
45306
+ lookFor: "Code that is correct and *only* code \u2014 no preamble, no explanation you did not ask for, no rewriting of things it was not asked to change. A model that cannot hold an output format will produce diffs you have to unpick before you can apply them."
45307
+ },
45308
+ {
45309
+ role: "reviewer",
45310
+ probes: ["debugging", "instruction-conflict"],
45311
+ lookFor: "Finding the actual fault rather than the first plausible one, and saying when two instructions contradict instead of quietly obeying one. A model that agrees easily makes an approving reviewer, which is worse than none because it gets believed."
45312
+ },
45313
+ {
45314
+ role: "tester",
45315
+ probes: ["instruction-conflict", "debugging"],
45316
+ lookFor: "Noticing what does not add up. The tester earns its place by thinking of the case you did not, which is the same instinct as spotting a contradiction."
45317
+ },
45318
+ {
45319
+ role: "librarian",
45320
+ probes: ["honesty"],
45321
+ lookFor: "Admitting it does not know. This is the one seat where inventing is worse than silence \u2014 a convention guessed at and stated confidently becomes the convention."
45322
+ }
45323
+ ];
45324
+ var EXPERT_GUIDANCE = "Planning across files is the whole of what the expert does, and no short probe stands in for it. Give the seat the model you would trust with an unfamiliar codebase, turn its thinking up, and judge it on whether its first plan survives contact with the work.";
45325
+
44903
45326
  // ../../packages/core/dist/expert/budget.js
44904
45327
  function money2(value) {
44905
45328
  return `$${value.toFixed(value < 1 ? 4 : 2)}`;
@@ -48677,7 +49100,12 @@ var NEVER_AVAILABLE_TO_SCHEDULES = [
48677
49100
  * Rewriting the plan it is being held to, with nobody there to approve the diff. Same ladder
48678
49101
  * as `schedule_prompt`: a run that can change its own instructions is bounded by nothing.
48679
49102
  */
48680
- "update_plan"
49103
+ "update_plan",
49104
+ // Rewriting what a specialist is, unattended. The same ladder: a run that can redefine its own
49105
+ // reviewer can arrange to be reviewed favourably by the next one.
49106
+ "update_role",
49107
+ "create_role",
49108
+ "delete_role"
48681
49109
  ];
48682
49110
  function scheduleAppliesHere(schedule, workspaceRoot) {
48683
49111
  if (schedule.workspaceRoot === void 0)
@@ -49849,107 +50277,20 @@ async function indexWorkspace(options) {
49849
50277
  };
49850
50278
  }
49851
50279
 
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
- // ../../packages/core/dist/checkpoints/shadowGit.js
49940
- import { execFile as execFile2 } from "node:child_process";
49941
- import fs7 from "node:fs/promises";
49942
- import path14 from "node:path";
49943
- function runGit(args, cwd) {
49944
- return new Promise((resolve, reject2) => {
49945
- execFile2("git", args, { cwd, maxBuffer: 32 * 1024 * 1024 }, (error51, stdout, stderr) => {
49946
- if (error51 && typeof error51.code !== "number") {
49947
- reject2(error51);
49948
- return;
49949
- }
49950
- resolve({ stdout, stderr, code: error51?.code ?? 0 });
49951
- });
49952
- });
50280
+ // ../../packages/core/dist/checkpoints/shadowGit.js
50281
+ import { execFile as execFile2 } from "node:child_process";
50282
+ import fs7 from "node:fs/promises";
50283
+ import path14 from "node:path";
50284
+ function runGit(args, cwd) {
50285
+ return new Promise((resolve, reject2) => {
50286
+ execFile2("git", args, { cwd, maxBuffer: 32 * 1024 * 1024 }, (error51, stdout, stderr) => {
50287
+ if (error51 && typeof error51.code !== "number") {
50288
+ reject2(error51);
50289
+ return;
50290
+ }
50291
+ resolve({ stdout, stderr, code: error51?.code ?? 0 });
50292
+ });
50293
+ });
49953
50294
  }
49954
50295
  var ShadowGit = class {
49955
50296
  workspaceRoot;
@@ -57230,6 +57571,29 @@ function looksUnfinished(text) {
57230
57571
  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
57572
  var MAX_CONTINUE_NUDGES = 1;
57232
57573
 
57574
+ // ../../packages/core/dist/agent/repairHistory.js
57575
+ 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.";
57576
+ function repairUnansweredToolCalls(messages) {
57577
+ const answered = /* @__PURE__ */ new Set();
57578
+ for (const message3 of messages) {
57579
+ if (message3.role === "tool" && message3.toolCallId !== void 0)
57580
+ answered.add(message3.toolCallId);
57581
+ }
57582
+ const repaired = [];
57583
+ for (const message3 of messages) {
57584
+ repaired.push(message3);
57585
+ if (message3.role !== "assistant" || message3.toolCalls === void 0)
57586
+ continue;
57587
+ for (const call of message3.toolCalls) {
57588
+ if (answered.has(call.id))
57589
+ continue;
57590
+ repaired.push({ role: "tool", toolCallId: call.id, content: UNANSWERED });
57591
+ answered.add(call.id);
57592
+ }
57593
+ }
57594
+ return repaired;
57595
+ }
57596
+
57233
57597
  // ../../packages/core/dist/agent/truncate.js
57234
57598
  import { randomUUID as randomUUID2 } from "node:crypto";
57235
57599
  import fs14 from "node:fs/promises";
@@ -57327,7 +57691,7 @@ var MAX_REFUNDED_STEPS = 20;
57327
57691
  var MAX_CONSECUTIVE_MISTAKES = 3;
57328
57692
  async function prepareModelMessages(conversation, provider, tools, options, events) {
57329
57693
  const contextWindow = options.contextWindow ?? 0;
57330
- let messages = conversation.toModelMessages();
57694
+ let messages = repairUnansweredToolCalls(conversation.toModelMessages());
57331
57695
  if (options.compactionEnabled !== false && contextWindow > 0) {
57332
57696
  const estimated = computeBreakdown(messages, tools, contextWindow).total;
57333
57697
  if (shouldCompact(messages, estimated, contextWindow, options.compaction ?? {})) {
@@ -57337,7 +57701,7 @@ async function prepareModelMessages(conversation, provider, tools, options, even
57337
57701
  if (summary !== void 0) {
57338
57702
  conversation.applyCompaction(summary, conversation.compactedCount() + result.summarisedCount);
57339
57703
  events.onCompacted?.(result.summarisedCount);
57340
- messages = conversation.toModelMessages();
57704
+ messages = repairUnansweredToolCalls(conversation.toModelMessages());
57341
57705
  }
57342
57706
  }
57343
57707
  }
@@ -57557,12 +57921,20 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
57557
57921
  }
57558
57922
  conversation.addAssistantMessage(assistantText, [toolCall]);
57559
57923
  events.onToolCall(toolCall);
57560
- const result = await runOneToolCall(toolCall, toolRegistry, toolContext, options, events, {
57561
- hasCheckpoint: () => checkpointTaken,
57562
- markCheckpointTaken: () => {
57563
- checkpointTaken = true;
57564
- }
57565
- }, mode);
57924
+ let result;
57925
+ try {
57926
+ result = await runOneToolCall(toolCall, toolRegistry, toolContext, options, events, {
57927
+ hasCheckpoint: () => checkpointTaken,
57928
+ markCheckpointTaken: () => {
57929
+ checkpointTaken = true;
57930
+ }
57931
+ }, mode);
57932
+ } catch (error51) {
57933
+ result = {
57934
+ content: `"${toolCall.name}" failed: ${error51 instanceof Error ? error51.message : String(error51)}`,
57935
+ isError: true
57936
+ };
57937
+ }
57566
57938
  const forModel = options.truncationStore !== void 0 ? (await truncateToolResult(result.content, options.truncationStore)).content : result.content;
57567
57939
  conversation.addToolResultMessage(toolCall.id, forModel);
57568
57940
  events.onToolResult(toolCall, result);
@@ -59646,6 +60018,275 @@ var OfficeBridge = class {
59646
60018
  }
59647
60019
  };
59648
60020
 
60021
+ // ../../packages/core/dist/agents/direct.js
60022
+ var DIRECTED = /(?:^|\s)#([a-z][a-z0-9-]{1,23})\b/g;
60023
+ function findDirectedRoles(text, team) {
60024
+ const usable = new Set(team.filter((agent) => agent.available).map((agent) => agent.role));
60025
+ const addressed = [];
60026
+ const unknown2 = [];
60027
+ for (const match of text.matchAll(DIRECTED)) {
60028
+ const name = match[1];
60029
+ if (name === void 0)
60030
+ continue;
60031
+ if (usable.has(name)) {
60032
+ if (!addressed.includes(name))
60033
+ addressed.push(name);
60034
+ continue;
60035
+ }
60036
+ if (team.some((agent) => agent.role === name) && !unknown2.includes(name))
60037
+ unknown2.push(name);
60038
+ }
60039
+ return { addressed, unknown: unknown2 };
60040
+ }
60041
+ function describeDirectedRoles(directed, team) {
60042
+ const lines = [];
60043
+ if (directed.addressed.length > 0) {
60044
+ const names = directed.addressed.map((role) => `\`${role}\``).join(", ");
60045
+ lines.push(`The user addressed ${names} directly with #. Consult ${directed.addressed.length > 1 ? "each of them" : "it"} with \`ask_agent\` before you answer \u2014 this is not a judgement call about whether a consultation is worth it, they asked. Put the code, error or output they are referring to in the question, and say plainly in your reply what came back and whether you agree.`);
60046
+ }
60047
+ if (directed.unknown.length > 0) {
60048
+ const usable = team.filter((agent) => agent.available).map((agent) => agent.role);
60049
+ lines.push(`The user wrote ${directed.unknown.map((role) => `#${role}`).join(", ")}, which ${directed.unknown.length > 1 ? "are not roles" : "is not a role"} that can answer here. ${usable.length > 0 ? `Available: ${usable.join(", ")}. Say so and carry on with the request.` : "No specialists are assigned. Say so, mention Settings \u2192 Agents, and carry on."}`);
60050
+ }
60051
+ return lines.join("\n\n");
60052
+ }
60053
+
60054
+ // ../../packages/core/dist/tools/roleTools.js
60055
+ var readParams = external_exports.object({
60056
+ role: external_exports.string().describe("Which role to read \u2014 one of the roles configured here. Omit to list them all.").optional()
60057
+ });
60058
+ function createReadRolePromptTool(access) {
60059
+ return {
60060
+ name: "read_role_prompt",
60061
+ group: "read",
60062
+ 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.",
60063
+ parametersSchema: readParams,
60064
+ async execute(params) {
60065
+ const roles = access.list();
60066
+ if (params.role === void 0) {
60067
+ if (roles.length === 0)
60068
+ return { content: "No roles are configured." };
60069
+ return {
60070
+ content: roles.map((entry) => `- ${entry.role} (${entry.name})` + (entry.assigned ? "" : " \u2014 nobody assigned") + (entry.edited ? " \u2014 prompt edited" : " \u2014 default prompt")).join("\n")
60071
+ };
60072
+ }
60073
+ const role = params.role.trim().toLowerCase();
60074
+ const prompt = access.current(role);
60075
+ if (prompt === void 0) {
60076
+ return {
60077
+ content: `There is no "${role}" role. The roles here are: ${roles.map((entry) => entry.role).join(", ")}.`,
60078
+ isError: true
60079
+ };
60080
+ }
60081
+ const edited = roles.find((entry) => entry.role === role)?.edited === true;
60082
+ return {
60083
+ content: `The ${role}'s prompt${edited ? " (edited by the user)" : " (the default)"}:
60084
+
60085
+ ${prompt}`
60086
+ };
60087
+ }
60088
+ };
60089
+ }
60090
+ var updateParams2 = external_exports.object({
60091
+ role: external_exports.string().describe("Which role to change."),
60092
+ 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."),
60093
+ /*
60094
+ * Name and summary are editable for the same reason the prompt is: they are how the role
60095
+ * presents itself. The summary especially — it is the line every other specialist sees and the
60096
+ * one the expert allocates from, so a role whose summary is wrong gets used for the wrong work.
60097
+ * Only a user-defined role can change them; a built-in one is what it is.
60098
+ */
60099
+ name: external_exports.string().optional().describe("A new display name. Custom roles only."),
60100
+ 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."),
60101
+ usesTools: external_exports.boolean().optional().describe("Whether it may read and search the workspace. Omit to leave unchanged."),
60102
+ reason: external_exports.string().optional().describe("One line on what is changing and why, shown to the user above the diff.")
60103
+ });
60104
+ function createUpdateRolePromptTool(access) {
60105
+ return {
60106
+ name: "update_role",
60107
+ /*
60108
+ * `edit`, and deliberately not `always`: `decideFromPolicy` approves the `always` group
60109
+ * *before* it consults ALWAYS_ASK_TOOLS, so putting it there would silently auto-approve the
60110
+ * one thing this must always ask about. The same trap `update_plan` nearly fell into.
60111
+ */
60112
+ group: "edit",
60113
+ 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.',
60114
+ parametersSchema: updateParams2,
60115
+ async preview(params) {
60116
+ const role = params.role.trim().toLowerCase();
60117
+ const details = access.details(role);
60118
+ const before = describeRole(details, access.current(role) ?? "");
60119
+ const nextPrompt = params.prompt === void 0 ? access.current(role) ?? "" : (
60120
+ // Empty means reset, so the diff shows what the default actually says — otherwise the
60121
+ // approval reads as "delete this prompt" rather than "go back to the built-in one".
60122
+ params.prompt.trim().length === 0 ? access.fallback(role) ?? "" : params.prompt.trim()
60123
+ );
60124
+ const after = describeRole(details === void 0 ? void 0 : {
60125
+ ...details,
60126
+ ...params.name !== void 0 ? { name: params.name.trim() } : {},
60127
+ ...params.summary !== void 0 ? { summary: params.summary.trim() } : {},
60128
+ ...params.usesTools !== void 0 ? { usesTools: params.usesTools } : {}
60129
+ }, nextPrompt);
60130
+ return {
60131
+ kind: "diff",
60132
+ path: `the ${role} role`,
60133
+ before,
60134
+ after,
60135
+ ...params.reason !== void 0 && params.reason.trim().length > 0 ? { note: params.reason.trim() } : {}
60136
+ };
60137
+ },
60138
+ async execute(params) {
60139
+ const role = params.role.trim().toLowerCase();
60140
+ if (access.current(role) === void 0) {
60141
+ return {
60142
+ content: `There is no "${role}" role. The roles here are: ${access.list().map((entry) => entry.role).join(", ")}.`,
60143
+ isError: true
60144
+ };
60145
+ }
60146
+ const details = access.details(role);
60147
+ const changingIdentity = params.name !== void 0 || params.summary !== void 0 || params.usesTools !== void 0;
60148
+ if (changingIdentity && details?.custom !== true) {
60149
+ return {
60150
+ 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.`,
60151
+ isError: true
60152
+ };
60153
+ }
60154
+ if (changingIdentity && details !== void 0) {
60155
+ await access.create({
60156
+ id: details.id,
60157
+ name: params.name?.trim() ?? details.name,
60158
+ summary: params.summary?.trim() ?? details.summary,
60159
+ /*
60160
+ * The **original**, not the one in force.
60161
+ *
60162
+ * This path rewrites the role's definition, and for a custom role the definition's
60163
+ * prompt is what "reset to default" restores. Passing the effective prompt here would
60164
+ * quietly bake an edit into the definition: rename a role whose prompt had been changed,
60165
+ * and resetting it afterwards would hand back the edit, with the text it was created
60166
+ * with gone for good and nothing having reported a loss.
60167
+ *
60168
+ * An edit lives in its own store and is untouched by this, which is the point — the two
60169
+ * are separate so that one can be undone.
60170
+ */
60171
+ prompt: details.originalPrompt,
60172
+ usesTools: params.usesTools ?? details.usesTools
60173
+ });
60174
+ }
60175
+ if (params.prompt !== void 0) {
60176
+ const next = params.prompt.trim();
60177
+ await access.save(role, next.length === 0 ? void 0 : next);
60178
+ }
60179
+ return {
60180
+ content: `The ${role} is updated and the user approved it. Every consultation of that role from now on uses it.`
60181
+ };
60182
+ }
60183
+ };
60184
+ }
60185
+ var createParams2 = external_exports.object({
60186
+ 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.'),
60187
+ name: external_exports.string().describe('What to call it in the settings panel, e.g. "Security reviewer".'),
60188
+ 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."),
60189
+ 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."),
60190
+ 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.")
60191
+ });
60192
+ function createCreateRoleTool(access) {
60193
+ return {
60194
+ name: "create_role",
60195
+ // `edit`, never `always` — see the note on `update_role_prompt`.
60196
+ group: "edit",
60197
+ 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.",
60198
+ parametersSchema: createParams2,
60199
+ async preview(params) {
60200
+ const { used, limit } = access.capacity();
60201
+ return {
60202
+ kind: "text",
60203
+ text: [
60204
+ `Create the role "${params.id.trim().toLowerCase()}" (${used + 1} of ${limit}).`,
60205
+ "",
60206
+ `Name: ${params.name}`,
60207
+ `For: ${params.summary}`,
60208
+ `Reads: ${params.usesTools ? "yes \u2014 it can read and search the workspace" : "no \u2014 it answers from the question alone"}`,
60209
+ "",
60210
+ "What it is told:",
60211
+ "",
60212
+ params.prompt.trim()
60213
+ ].join("\n")
60214
+ };
60215
+ },
60216
+ async execute(params) {
60217
+ const id = params.id.trim().toLowerCase();
60218
+ if (access.current(id) !== void 0) {
60219
+ return {
60220
+ content: `There is already a "${id}" role. Change it with update_role_prompt rather than creating it again.`,
60221
+ isError: true
60222
+ };
60223
+ }
60224
+ try {
60225
+ await access.create({ ...params, id });
60226
+ } catch (error51) {
60227
+ return {
60228
+ content: error51 instanceof Error ? error51.message : String(error51),
60229
+ isError: true
60230
+ };
60231
+ }
60232
+ return {
60233
+ 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.`
60234
+ };
60235
+ }
60236
+ };
60237
+ }
60238
+ function describeRole(details, prompt) {
60239
+ if (details === void 0)
60240
+ return prompt;
60241
+ return [
60242
+ `Name: ${details.name}`,
60243
+ `For: ${details.summary}`,
60244
+ `Reads: ${details.usesTools ? "yes" : "no"}`,
60245
+ "",
60246
+ prompt
60247
+ ].join("\n");
60248
+ }
60249
+ var deleteParams3 = external_exports.object({
60250
+ role: external_exports.string().describe("Which custom role to remove. Built-in roles cannot be deleted.")
60251
+ });
60252
+ function createDeleteRoleTool(access) {
60253
+ return {
60254
+ name: "delete_role",
60255
+ group: "edit",
60256
+ 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.",
60257
+ parametersSchema: deleteParams3,
60258
+ async preview(params) {
60259
+ const role = params.role.trim().toLowerCase();
60260
+ const details = access.details(role);
60261
+ return {
60262
+ kind: "text",
60263
+ text: details === void 0 ? `There is no "${role}" role to delete.` : [
60264
+ `Delete the "${details.id}" role and its assignment.`,
60265
+ "",
60266
+ describeRole(details, details.prompt),
60267
+ "",
60268
+ "The prompt above is removed with it."
60269
+ ].join("\n")
60270
+ };
60271
+ },
60272
+ async execute(params) {
60273
+ const role = params.role.trim().toLowerCase();
60274
+ const details = access.details(role);
60275
+ if (details === void 0) {
60276
+ return { content: `There is no "${role}" role.`, isError: true };
60277
+ }
60278
+ if (!details.custom) {
60279
+ return {
60280
+ content: `"${role}" is one of the built-in roles and cannot be deleted. Leave it unassigned if it should not be used.`,
60281
+ isError: true
60282
+ };
60283
+ }
60284
+ await access.remove(role);
60285
+ return { content: `The ${role} role is gone, and so is its assignment.` };
60286
+ }
60287
+ };
60288
+ }
60289
+
59649
60290
  // ../../packages/core/dist/office/vbaCheck.js
59650
60291
  function splitLine(line) {
59651
60292
  let bare = "";
@@ -60842,6 +61483,57 @@ ${preview.text}` } : {}
60842
61483
  post({ type: "plan", plan: activePlan ?? "" });
60843
61484
  postPlanProgress();
60844
61485
  }
61486
+ const rolePromptAccess = {
61487
+ list: () => knownRoles(cachedAgentDefinitions).map((role) => ({
61488
+ role,
61489
+ name: roleInfo(role, cachedAgentDefinitions).name,
61490
+ assigned: cachedTeam.some((agent) => agent.role === role),
61491
+ edited: cachedAgentRoles?.[role]?.prompt !== void 0
61492
+ })),
61493
+ current: (role) => {
61494
+ if (!isAgentRole(role, cachedAgentDefinitions))
61495
+ return void 0;
61496
+ return cachedAgentRoles?.[role]?.prompt ?? defaultPromptFor(role, cachedAgentDefinitions);
61497
+ },
61498
+ fallback: (role) => isAgentRole(role, cachedAgentDefinitions) ? defaultPromptFor(role, cachedAgentDefinitions) : void 0,
61499
+ details: (role) => {
61500
+ if (!isAgentRole(role, cachedAgentDefinitions))
61501
+ return void 0;
61502
+ const info = roleInfo(role, cachedAgentDefinitions);
61503
+ return {
61504
+ id: role,
61505
+ name: info.name,
61506
+ summary: info.summary,
61507
+ prompt: cachedAgentRoles?.[role]?.prompt ?? info.prompt,
61508
+ // What a reset restores. `info.prompt` is the definition's for a custom role and the
61509
+ // shipped text for a built-in one, in both cases ignoring any edit on top.
61510
+ originalPrompt: info.prompt,
61511
+ usesTools: cachedAgentRoles?.[role]?.tools ?? info.usesTools,
61512
+ custom: cachedAgentDefinitions.some((definition) => definition.id === role)
61513
+ };
61514
+ },
61515
+ remove: async (role) => {
61516
+ await handleDeleteCustomRole(role);
61517
+ },
61518
+ create: async (role) => {
61519
+ await handleSaveCustomRole(role);
61520
+ },
61521
+ capacity: () => ({ used: cachedAgentDefinitions.length, limit: CUSTOM_ROLE_LIMIT }),
61522
+ save: async (role, prompt) => {
61523
+ await saveAgents((current) => {
61524
+ const roles = { ...current.roles ?? {} };
61525
+ const existing = roles[role] ?? { kind: "profile" };
61526
+ if (prompt === void 0) {
61527
+ const rest = { ...existing };
61528
+ delete rest.prompt;
61529
+ roles[role] = rest;
61530
+ } else {
61531
+ roles[role] = { ...existing, prompt };
61532
+ }
61533
+ return { ...current, roles };
61534
+ });
61535
+ }
61536
+ };
60845
61537
  const planAccess = {
60846
61538
  current: () => activePlan,
60847
61539
  save: async (nextPlan) => {
@@ -61109,6 +61801,8 @@ ${preview.text}` } : {}
61109
61801
  let cachedCodeGenerator;
61110
61802
  let cachedTeam = [];
61111
61803
  let cachedTeamGuidance;
61804
+ let cachedAgentRoles;
61805
+ let cachedAgentDefinitions = [];
61112
61806
  let cachedBudgetMatters = false;
61113
61807
  let cachedMentionExcludes;
61114
61808
  let cachedReportsCost;
@@ -61159,6 +61853,8 @@ ${preview.text}` } : {}
61159
61853
  cliAvailable: expertCli?.available === true
61160
61854
  };
61161
61855
  cachedTeam = resolveTeam(teamContext);
61856
+ cachedAgentRoles = config2.agents?.roles;
61857
+ cachedAgentDefinitions = config2.agents?.definitions ?? [];
61162
61858
  cachedTeamGuidance = config2.agents?.teamGuidance;
61163
61859
  cachedBudgetMatters = budgetMatters(teamContext);
61164
61860
  cachedProgrammingProfileId = config2.programmingProfileId;
@@ -61177,7 +61873,14 @@ ${preview.text}` } : {}
61177
61873
  cachedToolTimeoutSeconds = config2.tools?.timeoutSeconds;
61178
61874
  cachedToolTimeouts = config2.tools?.timeouts;
61179
61875
  cachedExpertColor = config2.ui?.expertColor ?? "#D97757";
61180
- cachedAssessment = config2.expert?.assessment;
61876
+ const junior = (() => {
61877
+ try {
61878
+ return resolveActiveProfile(config2);
61879
+ } catch {
61880
+ return void 0;
61881
+ }
61882
+ })();
61883
+ cachedAssessment = junior === void 0 ? void 0 : assessmentFor(allAssessments(config2.expert ?? {}), junior.model, junior.label ?? junior.model);
61181
61884
  cachedReportsCost = config2.expert?.reportsCost;
61182
61885
  cachedPricing = config2.expert?.pricing;
61183
61886
  cachedKeepAlive = config2.expert?.keepAlive === true;
@@ -61312,6 +62015,10 @@ ${preview.text}` } : {}
61312
62015
  combined.register(tool, { dispatchOnly: dispatcher });
61313
62016
  combined.register(createUpdatePlanTool(planAccess), { dispatchOnly: dispatcher });
61314
62017
  combined.register(createPlanProgressTool(planAccess), { dispatchOnly: dispatcher });
62018
+ combined.register(createReadRolePromptTool(rolePromptAccess), { dispatchOnly: dispatcher });
62019
+ combined.register(createUpdateRolePromptTool(rolePromptAccess), { dispatchOnly: dispatcher });
62020
+ combined.register(createCreateRoleTool(rolePromptAccess), { dispatchOnly: dispatcher });
62021
+ combined.register(createDeleteRoleTool(rolePromptAccess), { dispatchOnly: dispatcher });
61315
62022
  combined.register(createNotifyTool({
61316
62023
  notify: (message3, level, details) => {
61317
62024
  if (details !== void 0) {
@@ -61794,7 +62501,11 @@ ${preview.text}` } : {}
61794
62501
  pythonNestedContext = toolContext;
61795
62502
  pythonNestedCallsAllowed = schedule === void 0;
61796
62503
  const mentions = await resolveMentions(text, { fs: toolContext.fs, workspaceRoot, denylist });
61797
- const messageText = attachMentions(text, mentions);
62504
+ const directed = findDirectedRoles(text, cachedTeam);
62505
+ const direction = describeDirectedRoles(directed, cachedTeam);
62506
+ const messageText = direction.length > 0 ? `${attachMentions(text, mentions)}
62507
+
62508
+ ${direction}` : attachMentions(text, mentions);
61798
62509
  const turnOptions = {
61799
62510
  signal: activeAbortController.signal,
61800
62511
  truncationStore,
@@ -62056,7 +62767,7 @@ ${preview.text}` } : {}
62056
62767
  }
62057
62768
  if (input.authType === "none")
62058
62769
  return { type: "none" };
62059
- const typed = input.apiKey.trim();
62770
+ const typed = (input.apiKey ?? "").trim();
62060
62771
  if (describeSecretRef(typed).kind === "env") {
62061
62772
  await secrets.delete(apiKeyRefFor(id));
62062
62773
  return { type: "apiKey", apiKeyRef: typed };
@@ -62210,6 +62921,19 @@ ${preview.text}` } : {}
62210
62921
  }
62211
62922
  }
62212
62923
  async function profileFromForm(input) {
62924
+ const fieldErrors = validateProviderForm({
62925
+ label: input.label,
62926
+ wireFormat: input.wireFormat,
62927
+ baseUrl: input.baseUrl,
62928
+ model: input.model
62929
+ });
62930
+ if (fieldErrors.length > 0) {
62931
+ post({
62932
+ type: "error",
62933
+ message: fieldErrors.map((issue2) => `${issue2.path}: ${issue2.message}`).join("; ")
62934
+ });
62935
+ return void 0;
62936
+ }
62213
62937
  const baseUrl = input.baseUrl.trim();
62214
62938
  if (baseUrl.length === 0) {
62215
62939
  post({ type: "error", message: "Enter a base URL first." });
@@ -62273,7 +62997,25 @@ ${preview.text}` } : {}
62273
62997
  maxConsultations: settings?.maxConsultations ?? 0,
62274
62998
  keepAlive: settings?.keepAlive === true,
62275
62999
  ...settings?.model !== void 0 ? { model: settings.model } : {},
62276
- ...settings?.assessment !== void 0 ? { assessment: settings.assessment } : {},
63000
+ // The one that applies to the active junior, chosen through the module that owns both
63001
+ // config shapes - not `settings.assessment`, which is only the legacy slot.
63002
+ ...cachedAssessment !== void 0 ? { assessment: cachedAssessment } : {},
63003
+ assessments: allAssessments(settings ?? {}),
63004
+ /*
63005
+ * What the probes predict about each seat, and who grades them.
63006
+ *
63007
+ * Sent rather than duplicated in the UI: the mapping is reasoned about beside the probes,
63008
+ * in `agents/seats.ts`, and a copy in a React component is the second declaration of one
63009
+ * fact that this repository keeps paying for.
63010
+ */
63011
+ seatFits: SEAT_FITS.map((fit) => ({
63012
+ role: fit.role,
63013
+ name: roleInfo(fit.role, cachedAgentDefinitions).name,
63014
+ probes: [...fit.probes],
63015
+ lookFor: fit.lookFor
63016
+ })),
63017
+ expertGuidance: EXPERT_GUIDANCE,
63018
+ assessor: describeAssessor(),
62277
63019
  ...settings?.reportsCost !== void 0 ? { reportsCost: settings.reportsCost } : {},
62278
63020
  ...settings?.pricing !== void 0 ? { pricing: settings.pricing } : {},
62279
63021
  ...measuringStep !== void 0 ? { measuringStep } : {},
@@ -62294,7 +63036,9 @@ ${preview.text}` } : {}
62294
63036
  cliAvailable: cli?.available === true
62295
63037
  };
62296
63038
  const assigned = new Map(resolveTeam(teamContext).map((agent) => [agent.role, agent]));
62297
- const roles = allRoles().map((info) => {
63039
+ const definitions = config2.agents?.definitions ?? [];
63040
+ const customIds = new Set(definitions.map((definition) => definition.id));
63041
+ const roles = allRoles(definitions).map((info) => {
62298
63042
  const agent = assigned.get(info.role);
62299
63043
  const prompt = config2.agents?.roles?.[info.role]?.prompt;
62300
63044
  return {
@@ -62306,8 +63050,18 @@ ${preview.text}` } : {}
62306
63050
  label: agent?.label ?? "Nobody",
62307
63051
  available: agent?.available ?? false,
62308
63052
  ...agent?.reason !== void 0 ? { reason: agent.reason } : {},
62309
- prompt: prompt ?? defaultPromptFor(info.role),
62310
- promptIsDefault: prompt === void 0
63053
+ prompt: prompt ?? defaultPromptFor(info.role, definitions),
63054
+ promptIsDefault: prompt === void 0,
63055
+ ...customIds.has(info.role) ? { custom: true } : {},
63056
+ // The assignment's override where there is one, else the role's own default — the same
63057
+ // resolution `resolveTeam` does, so the switch in the tab shows what will actually happen.
63058
+ usesTools: config2.agents?.roles?.[info.role]?.tools ?? info.usesTools,
63059
+ canWrite: config2.agents?.roles?.[info.role]?.write ?? info.canWrite,
63060
+ enabled: config2.agents?.roles?.[info.role]?.enabled !== false,
63061
+ ...(() => {
63062
+ const level = config2.agents?.roles?.[info.role]?.thinking;
63063
+ return level !== void 0 ? { thinking: level } : {};
63064
+ })()
62311
63065
  };
62312
63066
  });
62313
63067
  const guidance = config2.agents?.teamGuidance;
@@ -62318,6 +63072,14 @@ ${preview.text}` } : {}
62318
63072
  cliAvailable: teamContext.cliAvailable,
62319
63073
  ...cli?.available === false && cli.reason !== void 0 ? { cliReason: cli.reason } : {},
62320
63074
  budgetMatters: budgetMatters(teamContext),
63075
+ /*
63076
+ * Assigned, rather than assigned *and* detected.
63077
+ *
63078
+ * Somebody who put Claude in a seat on a machine where it is momentarily missing has still
63079
+ * said they intend to spend money there, and taking the budget controls away from them
63080
+ * because a probe failed would be the panel arguing with the user.
63081
+ */
63082
+ claudeSeated: [...assigned.values()].some((agent) => agent.kind === "cli"),
62321
63083
  teamGuidance: guidance ?? DEFAULT_TEAM_GUIDANCE,
62322
63084
  defaultTeamGuidance: DEFAULT_TEAM_GUIDANCE,
62323
63085
  teamGuidanceIsDefault: guidance === void 0,
@@ -62336,6 +63098,51 @@ ${preview.text}` } : {}
62336
63098
  }
62337
63099
  });
62338
63100
  }
63101
+ async function handleSaveCustomRole(role) {
63102
+ const id = role.id.trim().toLowerCase();
63103
+ if (!isValidRoleId(id)) {
63104
+ post({
63105
+ type: "error",
63106
+ 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.`
63107
+ });
63108
+ return;
63109
+ }
63110
+ if (role.name.trim().length === 0) {
63111
+ post({ type: "error", message: "A role needs a name." });
63112
+ return;
63113
+ }
63114
+ await saveAgents((current) => {
63115
+ const definitions = [...current.definitions ?? []];
63116
+ const at = definitions.findIndex((candidate) => candidate.id === id);
63117
+ const next = {
63118
+ id,
63119
+ name: role.name.trim(),
63120
+ summary: role.summary.trim(),
63121
+ prompt: role.prompt.trim(),
63122
+ usesTools: role.usesTools,
63123
+ canWrite: role.canWrite === true
63124
+ };
63125
+ if (at === -1) {
63126
+ if (definitions.length >= CUSTOM_ROLE_LIMIT) {
63127
+ 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.`);
63128
+ }
63129
+ definitions.push(next);
63130
+ } else
63131
+ definitions[at] = next;
63132
+ return { ...current, definitions };
63133
+ });
63134
+ }
63135
+ async function handleDeleteCustomRole(id) {
63136
+ await saveAgents((current) => {
63137
+ const roles = { ...current.roles ?? {} };
63138
+ delete roles[id];
63139
+ return {
63140
+ ...current,
63141
+ roles,
63142
+ definitions: (current.definitions ?? []).filter((candidate) => candidate.id !== id)
63143
+ };
63144
+ });
63145
+ }
62339
63146
  async function saveAgents(change) {
62340
63147
  try {
62341
63148
  const { config: config2 } = await configManager.load();
@@ -62498,24 +63305,89 @@ ${preview.text}` } : {}
62498
63305
  await postExpert({ redetect: false });
62499
63306
  }
62500
63307
  }
62501
- async function handleAssessJunior() {
63308
+ function describeAssessor() {
63309
+ const expert = cachedTeam.find((agent) => agent.role === "expert");
63310
+ if (expert === void 0) {
63311
+ return { label: "Nobody is in the expert seat", available: false };
63312
+ }
63313
+ return { label: expert.label, available: expert.available };
63314
+ }
63315
+ async function askExpertSeat(question, config2, expert) {
63316
+ if (expert.kind === "cli") {
63317
+ const cli = await detectCli(config2.expert?.path ?? "claude");
63318
+ if (!cli.available)
63319
+ throw new Error("The Claude CLI is not available.");
63320
+ const graded = await consultExpert(cli, {
63321
+ question,
63322
+ cwd: workspaceRoot ?? process.cwd(),
63323
+ ...config2.expert?.model !== void 0 ? { model: config2.expert.model } : {}
63324
+ });
63325
+ recordConsultation({
63326
+ isError: graded.isError,
63327
+ ...graded.costUsd !== void 0 ? { costUsd: graded.costUsd } : {}
63328
+ });
63329
+ if (graded.isError)
63330
+ throw new Error(graded.text);
63331
+ return {
63332
+ text: graded.text,
63333
+ ...graded.costUsd !== void 0 ? { costUsd: graded.costUsd } : {}
63334
+ };
63335
+ }
63336
+ const profile = config2.profiles?.find((candidate) => candidate.id === expert.profileId);
63337
+ if (profile === void 0) {
63338
+ throw new Error(`No profile "${expert.profileId ?? ""}" exists any more.`);
63339
+ }
63340
+ const seatProfile = expert.thinking === void 0 ? profile : {
63341
+ ...profile,
63342
+ thinking: {
63343
+ ...profile.thinking ?? { level: expert.thinking },
63344
+ level: expert.thinking
63345
+ }
63346
+ };
63347
+ const provider = createChatProvider(seatProfile, httpClient, authStrategyFor(config2, profile), logger);
63348
+ let text = "";
63349
+ for await (const chunk of provider.streamChat([
63350
+ { role: "system", content: expert.prompt },
63351
+ { role: "user", content: question }
63352
+ ])) {
63353
+ if (chunk.type === "text")
63354
+ text += chunk.text;
63355
+ if (chunk.type === "error")
63356
+ throw new Error(chunk.error);
63357
+ }
63358
+ if (text.trim().length === 0)
63359
+ throw new Error("The expert replied with nothing.");
63360
+ return { text };
63361
+ }
63362
+ async function handleAssessJunior(profileId) {
62502
63363
  if (assessmentStep !== void 0)
62503
63364
  return;
62504
63365
  try {
62505
63366
  const { config: config2 } = await configManager.load();
62506
- const cli = await resolveExpert(config2);
62507
- if (cli === void 0) {
63367
+ const cli = await detectCli(config2.expert?.path ?? "claude").catch(() => void 0);
63368
+ const team = resolveTeam({
63369
+ config: config2.agents,
63370
+ profiles: (config2.profiles ?? []).map((entry) => ({ id: entry.id, label: entry.label })),
63371
+ cliAvailable: cli?.available === true
63372
+ });
63373
+ const expert = team.find((agent) => agent.role === "expert" && agent.available);
63374
+ if (expert === void 0) {
62508
63375
  post({
62509
63376
  type: "error",
62510
- message: "Enable the expert first \u2014 the assessment is its judgement, not ours."
63377
+ message: "Nothing is in the expert seat. Assign one in the Agents tab - the assessment is its judgement, not ours."
62511
63378
  });
62512
63379
  return;
62513
63380
  }
62514
- const profile = resolveActiveProfile(config2);
63381
+ const chosen = profileId === void 0 ? void 0 : config2.profiles?.find((candidate) => candidate.id === profileId);
63382
+ if (profileId !== void 0 && chosen === void 0) {
63383
+ post({ type: "error", message: "That profile no longer exists." });
63384
+ return;
63385
+ }
63386
+ const profile = chosen ?? resolveActiveProfile(config2);
62515
63387
  const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger);
62516
63388
  const results = [];
62517
63389
  for (const [index, probe2] of ASSESSMENT_PROBES.entries()) {
62518
- assessmentStep = `Asking the junior: ${probe2.measures} (${String(index + 1)}/${String(ASSESSMENT_PROBES.length)})`;
63390
+ assessmentStep = `Asking ${profile.label ?? profile.model}: ${probe2.measures} (${String(index + 1)}/${String(ASSESSMENT_PROBES.length)})`;
62519
63391
  await postExpert({ redetect: false });
62520
63392
  let answer = "";
62521
63393
  try {
@@ -62538,21 +63410,9 @@ ${preview.text}` } : {}
62538
63410
  });
62539
63411
  }
62540
63412
  }
62541
- assessmentStep = "Asking the expert to grade the answers";
63413
+ assessmentStep = `Asking ${expert.label} to grade the answers`;
62542
63414
  await postExpert({ redetect: false });
62543
- const graded = await consultExpert(cli, {
62544
- question: buildAssessmentQuestion(profile.model, results),
62545
- cwd: workspaceRoot ?? process.cwd(),
62546
- ...config2.expert?.model !== void 0 ? { model: config2.expert.model } : {}
62547
- });
62548
- recordConsultation({
62549
- isError: graded.isError,
62550
- ...graded.costUsd !== void 0 ? { costUsd: graded.costUsd } : {}
62551
- });
62552
- if (graded.isError) {
62553
- post({ type: "error", message: `The expert could not assess the junior: ${graded.text}` });
62554
- return;
62555
- }
63415
+ const graded = await askExpertSeat(buildAssessmentQuestion(profile.model, results), config2, expert);
62556
63416
  const assessment = {
62557
63417
  model: profile.model,
62558
63418
  profileLabel: profile.label ?? profile.model,
@@ -62562,7 +63422,12 @@ ${preview.text}` } : {}
62562
63422
  ...graded.costUsd !== void 0 ? { costUsd: graded.costUsd } : {}
62563
63423
  };
62564
63424
  const latest = (await configManager.load()).config;
62565
- await configManager.save("user", { expert: { ...latest.expert, assessment } });
63425
+ await configManager.save("user", {
63426
+ expert: {
63427
+ ...latest.expert,
63428
+ assessments: recordAssessment(allAssessments(latest.expert ?? {}), assessment)
63429
+ }
63430
+ });
62566
63431
  } catch (error51) {
62567
63432
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
62568
63433
  } finally {
@@ -62570,10 +63435,16 @@ ${preview.text}` } : {}
62570
63435
  await postExpert({ redetect: false });
62571
63436
  }
62572
63437
  }
62573
- async function handleClearAssessment() {
63438
+ async function handleClearAssessment(model, profileLabel) {
62574
63439
  const { config: config2 } = await configManager.load();
62575
63440
  const expert = { ...config2.expert };
62576
- delete expert.assessment;
63441
+ if (model === void 0 || profileLabel === void 0) {
63442
+ delete expert.assessment;
63443
+ delete expert.assessments;
63444
+ } else {
63445
+ expert.assessments = forgetAssessment(allAssessments(expert), model, profileLabel);
63446
+ delete expert.assessment;
63447
+ }
62577
63448
  await configManager.save("user", { expert });
62578
63449
  await postExpert();
62579
63450
  }
@@ -64367,6 +65238,7 @@ ${preview.text}` } : {}
64367
65238
  // disagree — a specialist told it can read, and then given nothing to read with, wastes a
64368
65239
  // step discovering that.
64369
65240
  usesTools: agent.usesTools,
65241
+ canWrite: agent.canWrite,
64370
65242
  ...request.files !== void 0 ? { files: request.files } : {},
64371
65243
  /*
64372
65244
  * What exists in this workspace.
@@ -64395,6 +65267,11 @@ ${preview.text}` } : {}
64395
65267
  const cli = expertCli;
64396
65268
  if (cli === void 0 || !cli.available)
64397
65269
  throw new Error("The Claude CLI is not available.");
65270
+ if (cachedBudgetMatters) {
65271
+ const verdict = checkExpertBudget(expertSpend, effectiveExpertLimits());
65272
+ if (!verdict.allowed)
65273
+ throw new Error(verdict.message);
65274
+ }
64398
65275
  const answer = await consultExpert(cli, {
64399
65276
  question: prompt,
64400
65277
  /*
@@ -64405,6 +65282,10 @@ ${preview.text}` } : {}
64405
65282
  cwd: workspaceRoot ?? process.cwd(),
64406
65283
  ...request.signal !== void 0 ? { signal: request.signal } : {}
64407
65284
  });
65285
+ recordConsultation({
65286
+ isError: answer.isError,
65287
+ ...answer.costUsd !== void 0 ? { costUsd: answer.costUsd } : {}
65288
+ });
64408
65289
  if (answer.isError)
64409
65290
  throw new Error(answer.text);
64410
65291
  return { advice: answer.text, label: agent.label };
@@ -64414,8 +65295,18 @@ ${preview.text}` } : {}
64414
65295
  if (profile === void 0) {
64415
65296
  throw new Error(`No profile "${agent.profileId ?? ""}" exists any more.`);
64416
65297
  }
64417
- const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger);
64418
- const readOnly = agent.usesTools ? toolsForConsultation(agentBriefingTools?.() ?? []) : [];
65298
+ const seatProfile = agent.thinking === void 0 ? profile : {
65299
+ ...profile,
65300
+ thinking: { ...profile.thinking ?? { level: agent.thinking }, level: agent.thinking }
65301
+ };
65302
+ const provider = createChatProvider(seatProfile, httpClient, authStrategyFor(config2, profile), logger);
65303
+ const extraTools = new Set(agent.role === "librarian" ? ["write_skill"] : []);
65304
+ if (agent.canWrite) {
65305
+ extraTools.add("write_to_file");
65306
+ extraTools.add("apply_diff");
65307
+ extraTools.add("write_skill");
65308
+ }
65309
+ const readOnly = agent.usesTools ? toolsForConsultation(agentBriefingTools?.() ?? [], extraTools) : [];
64419
65310
  const context = consultationContext?.();
64420
65311
  const result = await runConsultation({
64421
65312
  provider,
@@ -64425,6 +65316,24 @@ ${preview.text}` } : {}
64425
65316
  // With no context there is nothing to read *with*, so it answers from the question alone
64426
65317
  // rather than being offered tools that would fail.
64427
65318
  context: context ?? {},
65319
+ /*
65320
+ * The same gate the agent loop uses, so an approval raised by a specialist is
65321
+ * indistinguishable from one raised by the assistant — same prompt, same ground truth, same
65322
+ * always-ask rule. A second approval path would be a second place for the rule to be wrong.
65323
+ */
65324
+ approve: async (tool, args) => {
65325
+ const preview = await tool.preview?.(args, context ?? {}).catch(() => void 0);
65326
+ const decision = await approvalGate.requestApproval({
65327
+ id: `agent-${agent.role}-${String(Date.now())}-${tool.name}`,
65328
+ toolName: tool.name,
65329
+ group: tool.group,
65330
+ preview: preview ?? {
65331
+ kind: "text",
65332
+ text: `The ${agent.role} wants to run ${tool.name}.`
65333
+ }
65334
+ });
65335
+ return decision === "approve";
65336
+ },
64428
65337
  ...request.signal !== void 0 ? { signal: request.signal } : {},
64429
65338
  onStep: (name) => logger.info(`${agent.role} looked up ${name}`)
64430
65339
  });
@@ -65134,9 +66043,9 @@ ${preview.text}` } : {}
65134
66043
  await postExpert({ redetect: false });
65135
66044
  }).catch((error51) => post({ type: "error", message: String(error51) }));
65136
66045
  } else if (message3.type === "assessJunior") {
65137
- void handleAssessJunior();
66046
+ void handleAssessJunior(message3.profileId);
65138
66047
  } else if (message3.type === "clearAssessment") {
65139
- void handleClearAssessment();
66048
+ void handleClearAssessment(message3.model, message3.profileLabel);
65140
66049
  } else if (message3.type === "restartScheduler") {
65141
66050
  restartScheduleTimer();
65142
66051
  logger.info("schedule timer restarted by the user");
@@ -65188,7 +66097,7 @@ ${preview.text}` } : {}
65188
66097
  } else if (message3.type === "setAgentRole") {
65189
66098
  const assignment = message3.assignment;
65190
66099
  const role = message3.role;
65191
- if (!isAgentRole(role)) {
66100
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
65192
66101
  post({ type: "error", message: `There is no "${role}" role.` });
65193
66102
  return;
65194
66103
  }
@@ -65208,7 +66117,7 @@ ${preview.text}` } : {}
65208
66117
  } else if (message3.type === "setAgentPrompt") {
65209
66118
  const role = message3.role;
65210
66119
  const prompt = message3.prompt;
65211
- if (!isAgentRole(role)) {
66120
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
65212
66121
  post({ type: "error", message: `There is no "${role}" role.` });
65213
66122
  return;
65214
66123
  }
@@ -65239,10 +66148,68 @@ ${preview.text}` } : {}
65239
66148
  }
65240
66149
  return { ...current, teamGuidance: guidance };
65241
66150
  });
66151
+ } else if (message3.type === "saveCustomRole") {
66152
+ void handleSaveCustomRole(message3);
66153
+ } else if (message3.type === "deleteCustomRole") {
66154
+ void handleDeleteCustomRole(message3.id);
66155
+ } else if (message3.type === "setRoleThinking") {
66156
+ const role = message3.role;
66157
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
66158
+ post({ type: "error", message: `There is no "${role}" role.` });
66159
+ return;
66160
+ }
66161
+ void saveAgents((current) => {
66162
+ const roles = { ...current.roles ?? {} };
66163
+ const existing = roles[role] ?? { kind: "profile" };
66164
+ if (message3.level === void 0) {
66165
+ const rest = { ...existing };
66166
+ delete rest.thinking;
66167
+ roles[role] = rest;
66168
+ } else {
66169
+ roles[role] = { ...existing, thinking: message3.level };
66170
+ }
66171
+ return { ...current, roles };
66172
+ });
66173
+ } else if (message3.type === "setRoleEnabled") {
66174
+ const role = message3.role;
66175
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
66176
+ post({ type: "error", message: `There is no "${role}" role.` });
66177
+ return;
66178
+ }
66179
+ void saveAgents((current) => {
66180
+ const roles = { ...current.roles ?? {} };
66181
+ roles[role] = {
66182
+ ...roles[role] ?? { kind: "profile" },
66183
+ enabled: message3.enabled
66184
+ };
66185
+ return { ...current, roles };
66186
+ });
66187
+ } else if (message3.type === "setRoleWrite") {
66188
+ const role = message3.role;
66189
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
66190
+ post({ type: "error", message: `There is no "${role}" role.` });
66191
+ return;
66192
+ }
66193
+ void saveAgents((current) => {
66194
+ const roles = { ...current.roles ?? {} };
66195
+ roles[role] = { ...roles[role] ?? { kind: "profile" }, write: message3.canWrite };
66196
+ return { ...current, roles };
66197
+ });
66198
+ } else if (message3.type === "setRoleTools") {
66199
+ const role = message3.role;
66200
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
66201
+ post({ type: "error", message: `There is no "${role}" role.` });
66202
+ return;
66203
+ }
66204
+ void saveAgents((current) => {
66205
+ const roles = { ...current.roles ?? {} };
66206
+ roles[role] = { ...roles[role] ?? { kind: "profile" }, tools: message3.usesTools };
66207
+ return { ...current, roles };
66208
+ });
65242
66209
  } else if (message3.type === "setAgentColor") {
65243
66210
  const role = message3.role;
65244
66211
  const color = message3.color;
65245
- if (!isAgentRole(role)) {
66212
+ if (!isAgentRole(role, cachedAgentDefinitions)) {
65246
66213
  post({ type: "error", message: `There is no "${role}" role.` });
65247
66214
  return;
65248
66215
  }
@@ -69341,7 +70308,7 @@ function respondJson(response, status, body) {
69341
70308
  }
69342
70309
 
69343
70310
  // src/cli.ts
69344
- var VERSION = true ? "0.50.0" : "unknown (not a packaged build)";
70311
+ var VERSION = true ? "0.59.0" : "unknown (not a packaged build)";
69345
70312
  var compat = installNodeCompat();
69346
70313
  function lastMeaningfulLine(problem) {
69347
70314
  const lines = problem.split(String.fromCharCode(10)).map((line) => line.trim()).filter((line) => line.length > 0 && !line.endsWith(":"));