@chosengeneration/light-code 0.44.0 → 0.50.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
@@ -39758,6 +39758,53 @@ var pythonConfigSchema = external_exports.object({
39758
39758
  })
39759
39759
  ]))
39760
39760
  }).partial();
39761
+ var agentAssignmentSchema = external_exports.object({
39762
+ /** `cli` is the Claude command line; `profile` names one of the user's provider profiles. */
39763
+ kind: external_exports.enum(["cli", "profile"]),
39764
+ profileId: external_exports.string().optional(),
39765
+ /**
39766
+ * The role's system prompt, stored only when the user has edited it.
39767
+ *
39768
+ * Absent means "use the default", which is what lets an improved default reach somebody who
39769
+ * has looked at the tab without editing anything. Storing the default verbatim would pin
39770
+ * every user to whatever it said the day they first opened it.
39771
+ */
39772
+ prompt: external_exports.string().optional()
39773
+ }).strict();
39774
+ var customRoleSchema = external_exports.object({
39775
+ id: external_exports.string().min(1),
39776
+ name: external_exports.string().min(1),
39777
+ summary: external_exports.string(),
39778
+ prompt: external_exports.string()
39779
+ });
39780
+ var agentsConfigSchema = external_exports.object({
39781
+ roles: external_exports.record(external_exports.string(), agentAssignmentSchema),
39782
+ /**
39783
+ * Roles the user invented, beyond the five built in.
39784
+ *
39785
+ * A role *is* its prompt, and the ones people ask for next are nearly always a reviewer with
39786
+ * a different one — security, performance, accessibility. Defining them here answers that
39787
+ * whole family without a code change each time, and without growing the fixed roster the
39788
+ * expert has to allocate from.
39789
+ *
39790
+ * Covered by the same user-scope rule as the rest of this block, and it is the sharpest part
39791
+ * of it: this is prose injected into a model that is then asked to advise on this
39792
+ * repository, so a workspace able to write it could define a reviewer that approves anything.
39793
+ */
39794
+ definitions: external_exports.array(customRoleSchema),
39795
+ /** Whether what a consultation costs is worth managing. See `agents/team.ts`. */
39796
+ budgetMatters: external_exports.boolean(),
39797
+ /** The Agent team mode instruction, when edited. The roster is always generated. */
39798
+ teamGuidance: external_exports.string(),
39799
+ /**
39800
+ * A colour per role, for marking whose words a piece of advice is.
39801
+ *
39802
+ * Here rather than under `appearance` because it is keyed by role, and the roles are defined
39803
+ * here — splitting them would mean adding a role in one place and remembering to give it a
39804
+ * colour in another, which is the drift this project keeps paying for.
39805
+ */
39806
+ colors: external_exports.record(external_exports.string(), external_exports.string())
39807
+ }).partial();
39761
39808
  var autoApproveSchema = external_exports.object({
39762
39809
  read: external_exports.boolean(),
39763
39810
  edit: external_exports.boolean(),
@@ -40139,6 +40186,7 @@ var configSchema = external_exports.object({
40139
40186
  /** User-scope only: a workspace able to add a trusted root could enable interception. */
40140
40187
  tls: globalTlsSchema,
40141
40188
  expert: expertConfigSchema,
40189
+ agents: agentsConfigSchema,
40142
40190
  /**
40143
40191
  * User-scope only (invariant 5). A workspace able to name a cluster or repoint the
40144
40192
  * embedder would exfiltrate whatever gets indexed — sharper than the existing entries,
@@ -40795,6 +40843,11 @@ var USER_SCOPE_ONLY_KEYS = [
40795
40843
  // its choosing as soon as the panel opened — the same threat as `python.uvPath`.
40796
40844
  // `expert.enabled` is here too, so a repo cannot switch on paid API calls by itself.
40797
40845
  "expert",
40846
+ // Names provider profiles, so a workspace able to write it could route a consultation through a
40847
+ // gateway of its choosing — the same threat as `activeProfileId`. And it carries prompts, which
40848
+ // are prose injected into a model then asked to advise on this repository's own code: a hostile
40849
+ // repo could tell the reviewer what to approve.
40850
+ "agents",
40798
40851
  // Added for Phase 8b, and the sharpest entries on this list. A workspace able to name a
40799
40852
  // cluster, or repoint the embedder at a profile of its choosing, would exfiltrate
40800
40853
  // whatever gets indexed — and what gets indexed is the source code.
@@ -43293,6 +43346,373 @@ var Conversation = class {
43293
43346
  }
43294
43347
  };
43295
43348
 
43349
+ // ../../packages/core/dist/agents/roles.js
43350
+ var AGENT_ROLES = ["expert", "programmer", "reviewer", "tester", "librarian"];
43351
+ function isAgentRole(value, custom2 = []) {
43352
+ return AGENT_ROLES.includes(value) || custom2.some((role) => role.id === value);
43353
+ }
43354
+ function knownRoles(custom2 = []) {
43355
+ return [...AGENT_ROLES, ...custom2.map((role) => role.id)];
43356
+ }
43357
+ var SHARED_TAIL = [
43358
+ "Your reply is advice. The assistant will check it against the real code before acting, and it",
43359
+ "is responsible for the result. Be concrete, say what you are unsure about, and say plainly when",
43360
+ "something must be verified rather than assumed.",
43361
+ "",
43362
+ "Answer in prose and short lists. No preamble about being happy to help."
43363
+ ];
43364
+ var SHARED_WITH_TOOLS = [
43365
+ "You can read this workspace: open files, list them, and search. Use that rather than guessing,",
43366
+ "and rather than asking the assistant for something you can fetch yourself. You have a small",
43367
+ "budget of lookups, so go for what actually settles the question.",
43368
+ "",
43369
+ "You cannot edit anything, run anything, or reach the network. If something needs changing, say",
43370
+ "what and why \u2014 the assistant makes the change and is responsible for it.",
43371
+ "",
43372
+ ...SHARED_TAIL
43373
+ ].join("\n");
43374
+ var SHARED_BLIND = [
43375
+ "You have no tools and cannot see the workspace. Everything you have is in the question. If",
43376
+ "something essential is missing, say exactly what you need and why, then give the best answer you",
43377
+ "can without it \u2014 never refuse to answer.",
43378
+ "",
43379
+ ...SHARED_TAIL
43380
+ ].join("\n");
43381
+ function specialistPreamble(usesTools) {
43382
+ return usesTools ? SHARED_WITH_TOOLS : SHARED_BLIND;
43383
+ }
43384
+ var DEFINITIONS = {
43385
+ expert: {
43386
+ name: "Expert",
43387
+ summary: "Hard problems, architecture, and deciding what to do",
43388
+ /* Planning a change means knowing what is already there, and it spans files the asker
43389
+ * cannot paste all of. */
43390
+ usesTools: true,
43391
+ prompt: [
43392
+ "You are a senior engineer being consulted by another AI assistant that is doing the work.",
43393
+ "",
43394
+ "It has hit something hard: a change across several files to plan, a bug it has already",
43395
+ "failed to fix, or a design choice with no obvious answer. Give it your judgement.",
43396
+ "",
43397
+ "Decide *what* should happen and why. Leave the typing to the assistant \u2014 it is the one",
43398
+ "making the change and answering for it. Where there is a real trade-off, name both sides",
43399
+ "and then choose."
43400
+ ].join("\n")
43401
+ },
43402
+ programmer: {
43403
+ name: "Programmer",
43404
+ summary: "Writes the code once the plan is settled",
43405
+ /* It is handed a spec and the surrounding code and asked to write. Looking around buys
43406
+ * a slower answer that is no better. */
43407
+ usesTools: false,
43408
+ prompt: [
43409
+ "You are an experienced programmer writing code for another AI assistant to apply.",
43410
+ "",
43411
+ "You are given a requirement and the surrounding code. Produce the change, matching the",
43412
+ "conventions of what you were shown rather than your own preferences \u2014 the naming, the error",
43413
+ "handling, the comment density, the way the existing code does this sort of thing.",
43414
+ "",
43415
+ "Return the code and a short note on anything non-obvious in it. Do not narrate what you are",
43416
+ "about to do, and do not rewrite things you were not asked to change.",
43417
+ "",
43418
+ /*
43419
+ * The programmer is the role that gets its own work handed back, so it is the one that has
43420
+ * to be told what to do with a review — including that it may disagree. Requested in those
43421
+ * terms: it is classified as the programmer, so fixing it is its job, and it should be able
43422
+ * to challenge a reviewer rather than obey one.
43423
+ */
43424
+ "You may be given a review of code you wrote. Fix what is genuinely wrong and return the",
43425
+ "corrected code the same way. **Where the review is wrong, say so and say why** \u2014 a finding",
43426
+ "can be about a path that cannot happen, a convention this codebase does not follow, or a",
43427
+ "misreading of a fragment. Do not rewrite working code to satisfy an objection you think is",
43428
+ "mistaken; the assistant has the real file and will settle it. Changing something you believe",
43429
+ "is right, because you were told to, is the worse failure: it looks like agreement."
43430
+ ].join("\n")
43431
+ },
43432
+ reviewer: {
43433
+ name: "Reviewer",
43434
+ summary: "Reads a change and says what is wrong with it",
43435
+ /* Most of what a review turns on is *around* the diff — the callers, the neighbouring
43436
+ * function, whether this convention is really the convention. */
43437
+ usesTools: true,
43438
+ prompt: [
43439
+ "You are reviewing a change written by another AI assistant.",
43440
+ "",
43441
+ "Your job is to find what is wrong with it. Say so plainly when something is fine, but do",
43442
+ "not pad the review with praise \u2014 an approving review that missed a bug is worse than no",
43443
+ "review, because it was believed.",
43444
+ "",
43445
+ "Look for, in this order: does it do what was asked; does it break something that used to",
43446
+ "work; what happens at the edges \u2014 empty, missing, concurrent, already-exists, fails halfway;",
43447
+ "and does it match the conventions of the code around it.",
43448
+ "",
43449
+ "For each finding say what breaks and under what input. A concern you cannot make concrete is",
43450
+ "worth one sentence, flagged as a hunch, not a paragraph.",
43451
+ "",
43452
+ // Findings go back to whoever wrote the code, which may disagree. Concrete ones can be
43453
+ // settled against the file; vague ones turn into an argument nobody can end.
43454
+ "Your findings may be put to the person who wrote the code, who can disagree with them. That",
43455
+ "is why each one needs an input and an outcome: a finding stated concretely can be checked",
43456
+ "against the real file and settled, and one stated as a preference cannot."
43457
+ ].join("\n")
43458
+ },
43459
+ tester: {
43460
+ name: "Tester",
43461
+ summary: "Designs cases and finds what breaks it",
43462
+ /* The change is in front of it and the cases come from reasoning about it, not from
43463
+ * reading more of the codebase. */
43464
+ usesTools: false,
43465
+ prompt: [
43466
+ "You design tests for code written by another AI assistant.",
43467
+ "",
43468
+ "Given a change, say what should be tested and why each case earns its place. Prefer the",
43469
+ "cases that would actually fail: boundaries, empty and missing values, the error path, the",
43470
+ "second call, the concurrent one, the one that fails halfway and has to be recovered from.",
43471
+ "",
43472
+ "A test that cannot fail is worth nothing \u2014 for each case you propose, say what bug it would",
43473
+ "catch. If the change is untestable as written, say what would have to change to make it",
43474
+ "testable rather than proposing a test that only asserts the code was executed."
43475
+ ].join("\n")
43476
+ },
43477
+ librarian: {
43478
+ name: "Librarian",
43479
+ summary: "Skills, internal documentation and house conventions",
43480
+ /* Its whole job is what has been written down here, so being unable to go and read it
43481
+ * left it answering from whatever happened to be pasted in. This is the role the flag
43482
+ * exists for. */
43483
+ usesTools: true,
43484
+ prompt: [
43485
+ "You answer questions about how things are done here: internal libraries, house conventions,",
43486
+ "the shape of existing code, and what has already been written down.",
43487
+ "",
43488
+ "You are given whatever documentation, skills and code the assistant could find. Answer from",
43489
+ "that, and be explicit about the difference between what the material actually says and what",
43490
+ "you are inferring \u2014 a convention you guessed at, stated confidently, becomes the convention.",
43491
+ "",
43492
+ "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."
43494
+ ].join("\n")
43495
+ }
43496
+ };
43497
+ function roleInfo(role, custom2 = []) {
43498
+ const builtIn = DEFINITIONS[role];
43499
+ if (builtIn !== void 0)
43500
+ return { role, ...builtIn };
43501
+ const defined = custom2.find((candidate) => candidate.id === role);
43502
+ if (defined !== void 0) {
43503
+ return {
43504
+ role,
43505
+ name: defined.name,
43506
+ summary: defined.summary,
43507
+ prompt: defined.prompt.trim(),
43508
+ /*
43509
+ * Custom roles get tools by default.
43510
+ *
43511
+ * They are overwhelmingly reviewers of some particular kind — security, performance,
43512
+ * accessibility — and those all turn on code the asker did not think to paste. The flag is
43513
+ * there to turn it off for the ones that are really "write this to spec".
43514
+ */
43515
+ usesTools: defined.usesTools !== false
43516
+ };
43517
+ }
43518
+ return {
43519
+ role,
43520
+ name: role,
43521
+ summary: "This role is no longer defined.",
43522
+ prompt: "",
43523
+ usesTools: false
43524
+ };
43525
+ }
43526
+ function allRoles(custom2 = []) {
43527
+ return knownRoles(custom2).map((role) => roleInfo(role, custom2));
43528
+ }
43529
+ function defaultPromptFor(role, custom2 = []) {
43530
+ return roleInfo(role, custom2).prompt;
43531
+ }
43532
+ function buildAgentPrompt(options) {
43533
+ const lines = [options.prompt.trim(), "", specialistPreamble(options.usesTools)];
43534
+ if (options.briefing !== void 0 && options.briefing.trim().length > 0) {
43535
+ lines.push("", options.briefing);
43536
+ }
43537
+ lines.push("", "---", "", options.question);
43538
+ if (options.files !== void 0 && options.files.length > 0) {
43539
+ lines.push("", options.usesTools ? "The assistant named these files as relevant. Start there \u2014 you can open them yourself:" : "The assistant named these files as relevant. You cannot open them \u2014 they are listed so you know what it is looking at:", ...options.files.map((file2) => `- ${file2}`));
43540
+ }
43541
+ return lines.join("\n");
43542
+ }
43543
+
43544
+ // ../../packages/core/dist/agent/checkpoints.js
43545
+ var MAX_CHECKPOINTS = 50;
43546
+ var LIST_ITEM = /^(\s*)(?:([-*•])|(\d+)[.)])\s+(.+)$/;
43547
+ function idFor(text) {
43548
+ let hash2 = 2166136261;
43549
+ for (let index = 0; index < text.length; index += 1) {
43550
+ hash2 ^= text.charCodeAt(index);
43551
+ hash2 = Math.imul(hash2, 16777619) >>> 0;
43552
+ }
43553
+ return hash2.toString(36);
43554
+ }
43555
+ function normalise(text) {
43556
+ return text.trim().toLowerCase().replace(/\s+/g, " ").replace(/[.;,:]+$/, "");
43557
+ }
43558
+ function parseCheckpoints(plan) {
43559
+ const lines = (plan ?? "").split(/\r?\n/);
43560
+ const items = [];
43561
+ lines.forEach((line, index) => {
43562
+ const match = LIST_ITEM.exec(line);
43563
+ if (match === null)
43564
+ return;
43565
+ const text = match[4]?.trim() ?? "";
43566
+ if (text.length === 0)
43567
+ return;
43568
+ items.push({
43569
+ indent: (match[1] ?? "").replace(/\t/g, " ").length,
43570
+ ordered: match[3] !== void 0,
43571
+ text,
43572
+ line: index
43573
+ });
43574
+ });
43575
+ const ordered = items.filter((item) => item.ordered);
43576
+ const candidates = ordered.length > 0 ? ordered : items;
43577
+ const shallowest = candidates.reduce((least, item) => Math.min(least, item.indent), Number.POSITIVE_INFINITY);
43578
+ const steps = candidates.filter((item) => item.indent === shallowest);
43579
+ const texts = steps.length > 0 ? steps : (
43580
+ // No list at all: plenty of people write a plan as bare lines, and a progress view that
43581
+ // only worked for bullet-point authors would read as broken.
43582
+ lines.map((line, index) => ({ indent: 0, ordered: false, text: line.trim(), line: index })).filter((item) => item.text.length > 0)
43583
+ );
43584
+ const chosen = texts.slice(0, MAX_CHECKPOINTS);
43585
+ const seen = /* @__PURE__ */ new Map();
43586
+ return chosen.map((item, position) => {
43587
+ const key = normalise(item.text);
43588
+ const occurrence = (seen.get(key) ?? 0) + 1;
43589
+ seen.set(key, occurrence);
43590
+ const until = chosen[position + 1]?.line ?? lines.length;
43591
+ return {
43592
+ id: occurrence === 1 ? idFor(key) : `${idFor(key)}-${String(occurrence)}`,
43593
+ index: position + 1,
43594
+ text: item.text,
43595
+ /*
43596
+ * Who the plan says should be involved, read from the step *and everything under it* —
43597
+ * which is where the allocation actually lives, since a specialist is usually named on a
43598
+ * continuation line ("Owner: reviewer") or inside a sub-point rather than in the heading.
43599
+ */
43600
+ plannedRoles: rolesMentionedIn(lines.slice(item.line, until).join(" "))
43601
+ };
43602
+ });
43603
+ }
43604
+ function rolesMentionedIn(text) {
43605
+ const haystack = text.toLowerCase();
43606
+ return AGENT_ROLES.filter((role) => new RegExp(`\\b${role}\\b`).test(haystack));
43607
+ }
43608
+ function checkpointViews(plan, progress) {
43609
+ return parseCheckpoints(plan).map((checkpoint) => {
43610
+ const recorded = progress?.[checkpoint.id];
43611
+ return {
43612
+ ...checkpoint,
43613
+ status: recorded?.status ?? "todo",
43614
+ roles: recorded?.roles ?? []
43615
+ };
43616
+ });
43617
+ }
43618
+ function pruneProgress(plan, progress) {
43619
+ if (progress === void 0)
43620
+ return {};
43621
+ const live = new Set(parseCheckpoints(plan).map((checkpoint) => checkpoint.id));
43622
+ const kept = {};
43623
+ for (const [id, entry] of Object.entries(progress))
43624
+ if (live.has(id))
43625
+ kept[id] = entry;
43626
+ return kept;
43627
+ }
43628
+ function markCheckpoint(plan, progress, index, status) {
43629
+ const checkpoint = parseCheckpoints(plan).find((candidate) => candidate.index === index);
43630
+ if (checkpoint === void 0)
43631
+ return void 0;
43632
+ const existing = progress[checkpoint.id];
43633
+ return {
43634
+ ...progress,
43635
+ [checkpoint.id]: {
43636
+ status,
43637
+ // Kept across a start→done transition: the specialists consulted while the step was being
43638
+ // worked are exactly the ones that contributed to finishing it.
43639
+ roles: existing?.roles ?? [],
43640
+ at: Date.now()
43641
+ }
43642
+ };
43643
+ }
43644
+ function attributeConsultation(progress, role) {
43645
+ const entry = Object.entries(progress).find(([, value2]) => value2.status === "active");
43646
+ if (entry === void 0)
43647
+ return progress;
43648
+ const [id, value] = entry;
43649
+ if (value.roles.includes(role))
43650
+ return progress;
43651
+ return { ...progress, [id]: { ...value, roles: [...value.roles, role] } };
43652
+ }
43653
+ function progressSummary(views) {
43654
+ const done = views.filter((view) => view.status === "done").length;
43655
+ return `${String(done)}/${String(views.length)}`;
43656
+ }
43657
+
43658
+ // ../../packages/core/dist/agent/plan.js
43659
+ var PLAN_LIMIT = 4e3;
43660
+ function buildPlanGuidance(plan) {
43661
+ const trimmed = plan?.trim() ?? "";
43662
+ if (trimmed.length === 0)
43663
+ return "";
43664
+ const checkpoints = parseCheckpoints(trimmed);
43665
+ const numbered = checkpoints.length > 0 ? [
43666
+ "",
43667
+ "Its steps are numbered as follows. These numbers are what `plan_progress` takes, and",
43668
+ "they are what the user sees:",
43669
+ "",
43670
+ ...checkpoints.map((checkpoint) => `${String(checkpoint.index)}. ${checkpoint.text}`)
43671
+ ] : [];
43672
+ return [
43673
+ "# The plan for this conversation",
43674
+ "",
43675
+ "The user set this. It is what you are here to do:",
43676
+ "",
43677
+ trimmed,
43678
+ ...numbered,
43679
+ "",
43680
+ "## Reporting where you are",
43681
+ "",
43682
+ "- **Call `plan_progress` with `active` when you start a step**, and with `done` when it is",
43683
+ " actually finished. The user watches this rather than reading the whole transcript, so a",
43684
+ " step marked done that is not done is worse than one never marked at all.",
43685
+ "- Work one step at a time. Marking three done at the end tells the user nothing while it",
43686
+ " matters, which is the only time it is useful.",
43687
+ "",
43688
+ "## Changing the plan",
43689
+ "",
43690
+ "- **You may propose a different plan with `update_plan`, and the user must approve it.**",
43691
+ " They are shown a diff of the plan they have against the one you are proposing. This is",
43692
+ " the only way the plan changes on your side \u2014 never act on a plan the user has not agreed.",
43693
+ "- Use it when you have worked out a better plan, including one a specialist drafted for you.",
43694
+ " Put the whole plan in it: it replaces what is there rather than adding to it.",
43695
+ "- If they decline, the existing plan still stands and you carry on with it.",
43696
+ "",
43697
+ "## Working to it",
43698
+ "",
43699
+ "- **Before each step, check it serves the plan.** If it does not, do not take it.",
43700
+ "- **Work the plan in order** where it has an order, and say which part you are on when you",
43701
+ " start something substantial. A reader should never have to guess where you are.",
43702
+ "- **Noticing something else is useful; acting on it is not.** If you spot an unrelated bug,",
43703
+ " a refactor worth doing, or a file that could be tidied, *say so and carry on with the*",
43704
+ " *plan*. Do not fix it because you are there. The user will ask if they want it.",
43705
+ "- **If the plan turns out to be wrong**, say so and stop rather than quietly substituting a",
43706
+ " better one. A plan the user set and a plan you preferred are different things, and only",
43707
+ " one of them was agreed.",
43708
+ "- **If something the plan needs is missing or blocked**, say which part and why, finish what",
43709
+ " can be finished, and report what you left.",
43710
+ "",
43711
+ "When you finish, `attempt_completion` must account for the plan: what is done, what is not,",
43712
+ "and anything you did that the plan did not ask for."
43713
+ ].join("\n");
43714
+ }
43715
+
43296
43716
  // ../../packages/core/dist/agent/systemPrompt.js
43297
43717
  function buildSystemPrompt(workspaceRoot, options = {}) {
43298
43718
  const lines = [
@@ -43373,6 +43793,9 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
43373
43793
  if (options.modeGuidance !== void 0 && options.modeGuidance.length > 0) {
43374
43794
  lines.push("", options.modeGuidance);
43375
43795
  }
43796
+ const plan = buildPlanGuidance(options.plan);
43797
+ if (plan.length > 0)
43798
+ lines.push("", plan);
43376
43799
  return lines.join("\n");
43377
43800
  }
43378
43801
 
@@ -43633,7 +44056,21 @@ function createAskExpertTool(options) {
43633
44056
  return {
43634
44057
  name: "ask_expert",
43635
44058
  group: "read",
43636
- description: "Consult a stronger expert model about a hard problem: planning a multi-file change, diagnosing a bug you have already failed to fix, or choosing between designs. Each call costs the user money, so use it for genuinely difficult questions only, and there may be a per-task budget after which it stops being available. The expert can read the workspace but cannot edit or run anything. Consultations within one task continue the same conversation, so after the first one it remembers what you already told it \u2014 a follow-up is far cheaper than a fresh explanation.",
44059
+ /*
44060
+ * The rationing is said only where somebody is counting.
44061
+ *
44062
+ * "Each call costs money, use it for genuinely difficult questions only" was unconditional,
44063
+ * and it is *advice about money* — so on a deployment where nobody is metering it, it buys
44064
+ * nothing and costs something real: a model told to hoard consultations asks fewer questions
44065
+ * than it should, which is the failure this whole feature exists to avoid. It was the right
44066
+ * default when every consultation was a metered cold start on a CLI, and it stopped being
44067
+ * right when the expert became a seat any model can sit in.
44068
+ *
44069
+ * Varying the description with a *setting* is the carve-out §12 already makes: the block stays
44070
+ * byte-stable for a whole session and changes only when the user changes their mind in
44071
+ * Settings, exactly as switching the dispatcher does.
44072
+ */
44073
+ description: "Consult a stronger expert model about a hard problem: planning a multi-file change, diagnosing a bug you have already failed to fix, or choosing between designs. " + (options.budgetMatters === true ? "Each call costs the user money, so use it for genuinely difficult questions only, and there may be a per-task budget after which it stops being available. " : "Consult it whenever another reader would genuinely change what you do. ") + "The expert can read the workspace but cannot edit or run anything. Consultations within one task continue the same conversation, so after the first one it remembers what you already told it \u2014 a follow-up is far cheaper than a fresh explanation.",
43637
44074
  parametersSchema: paramsSchema2,
43638
44075
  async preview(params) {
43639
44076
  return {
@@ -43650,7 +44087,10 @@ Suggested files: ${params.files.join(", ")}` : ""}`
43650
44087
  async execute(params, context) {
43651
44088
  const verdict = options.budget?.();
43652
44089
  if (verdict !== void 0 && !verdict.allowed) {
43653
- return { content: verdict.message ?? "The expert budget for this task is exhausted.", isError: true };
44090
+ return {
44091
+ content: verdict.message ?? "The expert budget for this task is exhausted.",
44092
+ isError: true
44093
+ };
43654
44094
  }
43655
44095
  const question = params.files !== void 0 && params.files.length > 0 ? `${params.question}
43656
44096
 
@@ -43712,46 +44152,66 @@ ${withBudget}` : withBudget;
43712
44152
  };
43713
44153
  }
43714
44154
 
43715
- // ../../packages/core/dist/tools/askProviderExpert.js
44155
+ // ../../packages/core/dist/tools/askAgent.js
43716
44156
  var paramsSchema3 = external_exports.object({
43717
- question: external_exports.string().min(1).describe("The question, with the code and context needed to answer it. The expert cannot see this conversation and cannot read files \u2014 paste what matters."),
43718
- files: external_exports.array(external_exports.string()).optional().describe("Workspace-relative paths you are working in, so the expert knows what you are looking at.")
44157
+ role: external_exports.string().describe(`Which specialist to ask: ${AGENT_ROLES.join(", ")}. Only the ones assigned in Settings \u2192 Agents can answer.`),
44158
+ question: external_exports.string().min(1).describe("The question, with the code, error or output needed to answer it. The specialist cannot see this conversation or read files \u2014 paste what matters."),
44159
+ files: external_exports.array(external_exports.string()).optional().describe("Workspace-relative paths you are working in, so it knows what you are looking at.")
43719
44160
  });
43720
- function createAskProviderExpertTool(options) {
44161
+ function createAskAgentTool(options) {
43721
44162
  return {
43722
- name: "ask_expert",
44163
+ name: "ask_agent",
43723
44164
  group: "read",
43724
- description: "Consult a stronger expert model about a hard problem: planning a multi-file change, diagnosing a bug you have already failed to fix, or choosing between designs. The expert cannot see this conversation, cannot read files and does not remember earlier consultations \u2014 put everything it needs in the question, including the relevant code. What comes back is advice: check it against the real code before acting on it.",
44165
+ description: "Consult a specialist model about the work: plan a hard change (expert), have a finished change reviewed (reviewer), find out what would break it (tester), write a piece of code (programmer), or ask how this codebase does something (librarian). The specialist cannot see this conversation, cannot read files and does not remember earlier consultations \u2014 put everything it needs in the question, including the actual code. What comes back is advice: check it against the real code before acting on it.",
43725
44166
  parametersSchema: paramsSchema3,
43726
44167
  async preview(params) {
44168
+ const agent = find(options.agents(), params.role);
43727
44169
  return {
43728
44170
  kind: "text",
43729
- // Ground truth (invariant 8): the question that will actually be sent, in full. This
44171
+ // Ground truth (invariant 8): the question that will be sent, in full, and who to. This
43730
44172
  // puts the user's code in front of another model, which is the decision being approved.
43731
- text: `Consult the expert (${options.label}):
44173
+ text: `Ask the ${params.role}${agent === void 0 ? "" : ` (${agent.label})`}:
43732
44174
 
43733
- ${params.question}${params.files !== void 0 && params.files.length > 0 ? `
44175
+ ${params.question}` + (params.files !== void 0 && params.files.length > 0 ? `
43734
44176
 
43735
- Files named as relevant: ${params.files.join(", ")}` : ""}`
44177
+ Files named as relevant: ${params.files.join(", ")}` : "")
43736
44178
  };
43737
44179
  },
43738
44180
  async execute(params, context) {
44181
+ const team = options.agents();
44182
+ const role = params.role.trim().toLowerCase();
44183
+ if (!isAgentRole(role)) {
44184
+ return { content: unknownRole(role, team), isError: true };
44185
+ }
44186
+ const agent = find(team, role);
44187
+ if (agent === void 0) {
44188
+ return {
44189
+ content: `No ${role} is assigned. ${describeTeam(team)} Assign one in Settings \u2192 Agents, or ask a different role.`,
44190
+ isError: true
44191
+ };
44192
+ }
44193
+ if (!agent.available) {
44194
+ return {
44195
+ content: `The ${role} cannot be reached: ${agent.reason ?? "it is unavailable."}`,
44196
+ isError: true
44197
+ };
44198
+ }
43739
44199
  let result;
43740
44200
  try {
43741
- result = await options.consult({
44201
+ result = await options.consult(agent, {
43742
44202
  question: params.question,
43743
44203
  ...params.files !== void 0 ? { files: params.files } : {},
43744
44204
  ...context.signal !== void 0 ? { signal: context.signal } : {}
43745
44205
  });
43746
44206
  } catch (error51) {
43747
44207
  return {
43748
- content: `The expert could not be reached: ${error51 instanceof Error ? error51.message : String(error51)}`,
44208
+ content: `The ${role} could not be reached: ${error51 instanceof Error ? error51.message : String(error51)}`,
43749
44209
  isError: true
43750
44210
  };
43751
44211
  }
43752
44212
  if (result.advice.trim().length === 0) {
43753
44213
  return {
43754
- content: "The expert returned nothing. That usually means the profile configured as the expert answered with an empty response \u2014 check it in Settings \u2192 Expert.",
44214
+ content: `The ${role} returned nothing. Check what is assigned to it in Settings \u2192 Agents.`,
43755
44215
  isError: true
43756
44216
  };
43757
44217
  }
@@ -43761,39 +44221,494 @@ Files named as relevant: ${params.files.join(", ")}` : ""}`
43761
44221
 
43762
44222
  ---
43763
44223
 
43764
- That is advice from ${result.producedBy}, which has not seen your workspace. Check it against the actual code before acting on it, and say so if it turns out to be wrong.`
44224
+ ${trailerFor(agent, team)}`
43765
44225
  };
43766
44226
  }
43767
44227
  };
43768
44228
  }
43769
-
43770
- // ../../packages/core/dist/expert/providerExpert.js
43771
- function buildExpertPrompt(request) {
44229
+ function find(team, role) {
44230
+ const wanted = role.trim().toLowerCase();
44231
+ return team.find((agent) => agent.role === wanted);
44232
+ }
44233
+ function unknownRole(role, team) {
44234
+ return `There is no "${role}" role. The roles are: ${AGENT_ROLES.join(", ")}. ${describeTeam(team)}`;
44235
+ }
44236
+ function describeTeam(team) {
44237
+ const usable = team.filter((agent) => agent.available).map((agent) => agent.role);
44238
+ return usable.length === 0 ? "None are assigned on this machine." : `Assigned here: ${usable.join(", ")}.`;
44239
+ }
44240
+ function trailerFor(agent, team) {
43772
44241
  const lines = [
43773
- "You are a senior engineer being consulted by another AI assistant that is doing the work.",
44242
+ `That is the ${agent.role}'s advice, from ${agent.label}. ` + (agent.usesTools ? "It could read this workspace but cannot change anything in it." : "It has not seen your workspace \u2014 it answered from what you pasted.") + " Check it against the actual code before acting on it, and say so if it turns out to be wrong."
44243
+ ];
44244
+ const programmer = team.find((candidate) => candidate.role === "programmer" && candidate.available);
44245
+ if (agent.role === "reviewer" && programmer !== void 0) {
44246
+ 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
+ }
44248
+ if (agent.role === "programmer") {
44249
+ 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
+ }
44251
+ return lines.join("\n");
44252
+ }
44253
+
44254
+ // ../../packages/core/dist/agents/team.js
44255
+ function defaultAssignment(role, context) {
44256
+ return role === "expert" && context.cliAvailable ? { kind: "cli" } : void 0;
44257
+ }
44258
+ function resolveTeam(context) {
44259
+ const resolved = [];
44260
+ const custom2 = context.config?.definitions ?? [];
44261
+ for (const role of knownRoles(custom2)) {
44262
+ const assignment = context.config?.roles?.[role] ?? defaultAssignment(role, context);
44263
+ if (assignment === void 0)
44264
+ continue;
44265
+ const info = roleInfo(role, custom2);
44266
+ const prompt = assignment.prompt ?? defaultPromptFor(role, custom2);
44267
+ const usesTools = assignment.tools ?? info.usesTools;
44268
+ if (assignment.kind === "cli") {
44269
+ resolved.push({
44270
+ role,
44271
+ name: info.name,
44272
+ summary: info.summary,
44273
+ kind: "cli",
44274
+ label: "Claude",
44275
+ prompt,
44276
+ usesTools,
44277
+ available: context.cliAvailable,
44278
+ ...context.cliAvailable ? {} : { reason: "The Claude CLI is not available on this machine." }
44279
+ });
44280
+ continue;
44281
+ }
44282
+ const profile = context.profiles.find((candidate) => candidate.id === assignment.profileId);
44283
+ resolved.push({
44284
+ role,
44285
+ name: info.name,
44286
+ summary: info.summary,
44287
+ kind: "profile",
44288
+ ...assignment.profileId !== void 0 ? { profileId: assignment.profileId } : {},
44289
+ label: profile?.label ?? assignment.profileId ?? "unassigned",
44290
+ prompt,
44291
+ usesTools,
44292
+ available: profile !== void 0,
44293
+ /*
44294
+ * A profile that has been deleted leaves the role unavailable and says so, rather than
44295
+ * falling back to the model already doing the work. A specialist that is quietly the
44296
+ * primary model gives advice with nothing to distrust about it, which is worse than none.
44297
+ */
44298
+ ...profile === void 0 ? { reason: `No profile "${assignment.profileId ?? ""}" exists any more.` } : {}
44299
+ });
44300
+ }
44301
+ return resolved;
44302
+ }
44303
+ function budgetMatters(context) {
44304
+ const stated = context.config?.budgetMatters;
44305
+ if (stated !== void 0)
44306
+ return stated;
44307
+ return resolveTeam(context).some((agent) => agent.kind === "cli" && agent.available);
44308
+ }
44309
+
44310
+ // ../../packages/core/dist/agents/guidance.js
44311
+ var BUDGET_ADVICE = [
44312
+ "",
44313
+ "## Consultations cost money here",
44314
+ "",
44315
+ "Each one is charged. Make the first count \u2014 gather what is needed and ask one full question",
44316
+ "rather than opening with something you could have settled yourself. If a per-task budget runs",
44317
+ "out the specialist stops being available, and you finish the work alone, so spend it on the",
44318
+ "parts where another reader genuinely changes what you do."
44319
+ ].join("\n");
44320
+ var PLAN_FIRST = [
44321
+ "",
44322
+ "## Start by planning. This comes before everything else.",
44323
+ "",
44324
+ "**This conversation has no plan yet, so making one is your first job.** Before reading widely,",
44325
+ "before editing anything, before running anything:",
44326
+ "",
44327
+ "1. **Look at almost nothing first.** One `list_files` of the workspace root is usually the",
44328
+ " whole of it, plus any file the user actually named. That is enough to ask a good question.",
44329
+ " Do **not** survey the codebase, search the documentation index, hunt for skills, or read",
44330
+ " files to get a feel for the style \u2014 not yet. The specialist cannot see any of it anyway,",
44331
+ " and if it needs something specific it will say so and you can fetch it and ask again.",
44332
+ ' Announcing that you are "getting a sense of the workspace before proposing anything" is',
44333
+ " this instruction being broken, however reasonable it sounds.",
44334
+ "2. **Ask the expert for the plan** \u2014 give the task, the little you found and the constraints,",
44335
+ " and ask for numbered steps. A plan is the one thing worth asking for before the work rather",
44336
+ " than after it, and it is what the expert is for. An expert asked early enough to change the",
44337
+ " shape of the work is worth several times one asked to bless a direction already taken.",
44338
+ " **Ask it to say which specialist should be involved in which step**, from the team it is",
44339
+ " given. It knows who is available; it will not volunteer the allocation unless asked.",
44340
+ "3. **Propose it with `update_plan`.** The user sees a diff and approves it. Do not skip this:",
44341
+ " a plan held only in the conversation is forgotten as the chat grows, and it is not",
44342
+ " something the user has agreed to.",
44343
+ "4. Only once it is approved, start the work, reporting each step with `plan_progress`.",
44344
+ "",
44345
+ "If the user declines, ask what they want changed and propose a revised plan. If no expert is",
44346
+ "assigned, draft it yourself and propose it the same way \u2014 and say that is what you did, so",
44347
+ "nobody believes it was reviewed by somebody else.",
44348
+ "",
44349
+ "The exception is a question rather than a job. If the user asked something you can simply",
44350
+ "answer, answer it \u2014 do not plan a conversation."
44351
+ ].join("\n");
44352
+ var PLAN_IN_PLACE = [
44353
+ "",
44354
+ "## This conversation already has a plan",
44355
+ "",
44356
+ "It is above, with its steps numbered. Work it, report each step with `plan_progress`, and if it",
44357
+ "turns out to be wrong, consult the expert and propose a replacement with `update_plan` rather",
44358
+ "than quietly working to a different one."
44359
+ ].join("\n");
44360
+ var DEFAULT_TEAM_GUIDANCE = [
44361
+ "You lead a small team. You do the work \u2014 reading, searching, editing, running things \u2014 and you",
44362
+ "consult specialists when another reader would genuinely change what you do.",
44363
+ "",
44364
+ "## Consult without being asked",
44365
+ "",
44366
+ "You do not need permission and you should not wait to be told. Ask when:",
44367
+ "",
44368
+ "- the task spans several files and you are not sure of the shape \u2014 ask the **expert** first,",
44369
+ " before you write anything;",
44370
+ "- you have finished a change of any substance \u2014 ask the **reviewer**, and say what you changed",
44371
+ " and why, not just what the diff looks like;",
44372
+ "- you are about to call something done that has no tests \u2014 ask the **tester** what would break",
44373
+ " it;",
44374
+ "- you are guessing at how this codebase does something \u2014 ask the **librarian** rather than",
44375
+ " inventing a convention;",
44376
+ /*
44377
+ * The programmer was missing from this list entirely, which is most of why it never got used.
44378
+ *
44379
+ * Every other bullet describes somebody *reading* what you have, and writing code is the one
44380
+ * thing the assistant can already do — so with no bullet of its own the role simply never came
44381
+ * up, and a plan drafted by the expert never allocated it either (the same omission, in the
44382
+ * briefing). Bounded deliberately: "hand everything to the programmer" would add a round trip
44383
+ * to every edit and put a second model's conventions into the file.
44384
+ */
44385
+ "- a step is a self-contained piece of code with a clear spec \u2014 a parser, a schema, a set of",
44386
+ " pure functions \u2014 hand it to the **programmer** rather than writing it yourself out of habit,",
44387
+ " then check what comes back against the real file before applying it. Not for a two-line",
44388
+ " change, and not where the spec is still moving.",
44389
+ "",
44390
+ 'The user can also ask directly ("ask the reviewer to look at this"), and then you consult that',
44391
+ "role whatever you would have chosen.",
44392
+ "",
44393
+ "## What makes a consultation worth it",
44394
+ "",
44395
+ /*
44396
+ * The last place still saying every specialist is blind.
44397
+ *
44398
+ * Some can read and search for themselves; the roster above marks which. But the advice does
44399
+ * not change much, because even one that can look things up starts from what you gave it — and
44400
+ * a question with nothing attached spends its whole lookup budget finding the file you already
44401
+ * had open.
44402
+ */
44403
+ "**Paste the code**, the error, the failing output \u2014 the actual text. Some of them can read the",
44404
+ "workspace and some cannot, and the roster says which; but even the ones that can start from",
44405
+ "what you give them, and a question with nothing attached spends their whole lookup budget",
44406
+ 'finding what you already had open. A question like "is my retry logic right?" with nothing',
44407
+ "attached comes back as a list of things retry logic usually gets wrong, which you already knew.",
44408
+ "",
44409
+ "Ask one full question rather than three thin ones. Each consultation is a fresh reader with no",
44410
+ "memory of the last, so a follow-up has to carry its own context.",
44411
+ "",
44412
+ "## What not to do",
44413
+ "",
44414
+ "- Do not consult on something you can settle by reading a file. Read it.",
44415
+ "- Do not relay advice you have not checked. You have the code open and the specialist does not;",
44416
+ " if it is wrong, say so and say why \u2014 to the user, and in your next question.",
44417
+ "- Do not consult the same role twice with the same question hoping for a better answer.",
44418
+ "",
44419
+ "## When a review finds something in code the programmer wrote",
44420
+ "",
44421
+ "**Take it back to the programmer.** It wrote the code, it is the role picked for writing, and",
44422
+ "the fix is its job rather than yours \u2014 you are the one holding the files, not the one whose",
44423
+ "judgement was hired for this. Fixing it silently yourself wastes the specialist and hides the",
44424
+ "exchange from the user.",
44425
+ "",
44426
+ "A consultation remembers nothing, so the question has to carry everything: **the code as it",
44427
+ "stands, the finding in the reviewer's own words, and what you have checked yourself.** A",
44428
+ 'programmer told only "the reviewer says this is wrong" will guess at which line and rewrite',
44429
+ "more than it should.",
44430
+ "",
44431
+ "**It may push back, and that is a real answer, not an obstacle.** Reviews are wrong often",
44432
+ "enough to matter \u2014 a finding can be about a path that cannot happen, a convention this",
44433
+ "codebase deliberately does not follow, or a misreading of code the reviewer only saw a fragment",
44434
+ "of. When the programmer disagrees, you settle it: you have the actual file and neither of them",
44435
+ "does. Say which way you went and why, in your reply, so the user sees the disagreement rather",
44436
+ "than only its outcome.",
44437
+ "",
44438
+ "**One lap, not a loop.** Review, fix, and re-review only when the fix was substantial enough",
44439
+ "that the first review no longer describes the code. If the two still disagree after that, stop",
44440
+ "and put it to the expert with both positions, or decide it yourself and say so. Ping-ponging a",
44441
+ "disagreement between two models that cannot see the file is how a turn is spent without",
44442
+ "anything being decided.",
44443
+ "",
44444
+ "## When the plan names a specialist",
44445
+ "",
44446
+ "Consult them **while that step is the active one**, not at the end in a batch. Two reasons, and",
44447
+ "the second is the one people notice: advice arriving after the work is done is a review nobody",
44448
+ "can act on without redoing it, and the progress panel attributes a consultation to whichever",
44449
+ "step was open when it happened \u2014 so a step worked in silence shows as nobody having helped with",
44450
+ "it, whatever you say afterwards.",
44451
+ "",
44452
+ "If a step names somebody and you decide against consulting them, say so and say why. A plan the",
44453
+ "user approved said that step would get another reader."
44454
+ ].join("\n");
44455
+ function buildTeamGuidance(agents, custom2, budgetMatters2, hasPlan) {
44456
+ const base = custom2 !== void 0 && custom2.trim().length > 0 ? custom2 : DEFAULT_TEAM_GUIDANCE;
44457
+ const advice = budgetMatters2 === true ? `${base}
44458
+ ${BUDGET_ADVICE}` : base;
44459
+ const planning = hasPlan === true ? PLAN_IN_PLACE : PLAN_FIRST;
44460
+ const usable = agents.filter((agent) => agent.available);
44461
+ const unusable = AGENT_ROLES.filter((role) => !usable.some((agent) => agent.role === role)).map((role) => {
44462
+ const assigned = agents.find((agent) => agent.role === role);
44463
+ return assigned === void 0 ? `- **${role}** \u2014 nobody assigned.` : `- **${role}** \u2014 ${assigned.reason ?? "assigned, but cannot be reached."}`;
44464
+ });
44465
+ const missing = unusable.length === 0 ? [] : [
43774
44466
  "",
43775
- "It has hit something hard: a multi-file change to plan, a bug it has already failed to fix,",
43776
- "or a design choice to make. Give it your judgement.",
44467
+ "**Not available, so do not ask for them and do not plan work for them:**",
43777
44468
  "",
43778
- "Two things about your position here:",
44469
+ ...unusable,
43779
44470
  "",
43780
- "- You cannot see the workspace and cannot read files, run commands or search. Everything you",
43781
- " have is below. If something essential is missing, say exactly what you need and why, then",
43782
- " give the best answer you can without it \u2014 do not refuse to answer.",
43783
- "- Your reply is advice. The assistant will check it against the real code before acting, and",
43784
- " it is responsible for the result. Be concrete, say what you are unsure about, and say when",
43785
- " a thing must be verified rather than assumed.",
44471
+ "If something genuinely needs one of these, say so and say that assigning it in",
44472
+ "Settings \u2192 Agents would let you consult it \u2014 then carry on without it rather than",
44473
+ "leaving that part of the job unaccounted for."
44474
+ ];
44475
+ if (usable.length === 0) {
44476
+ return [
44477
+ advice,
44478
+ planning,
44479
+ "",
44480
+ "## Your team",
44481
+ "",
44482
+ "**Nobody is assigned yet.** Until somebody is, do the work yourself and tell the user that",
44483
+ "assigning a specialist in Settings \u2192 Agents would let you consult one.",
44484
+ ...missing
44485
+ ].join("\n");
44486
+ }
44487
+ return [
44488
+ advice,
44489
+ planning,
43786
44490
  "",
43787
- "Answer in prose and short lists. No preamble about being happy to help.",
44491
+ "## Your team",
43788
44492
  "",
43789
- "---",
44493
+ "Reach any of them with `ask_agent`, naming the role. These are the only ones that exist:",
43790
44494
  "",
43791
- request.question
43792
- ];
43793
- if (request.files !== void 0 && request.files.length > 0) {
43794
- lines.push("", "The assistant named these files as relevant. You cannot open them \u2014 they are listed so you", "know what it is looking at:", ...request.files.map((file2) => `- ${file2}`));
44495
+ ...usable.map((agent) => `- **${agent.role}** (${agent.label}) \u2014 ${agent.summary}`),
44496
+ ...missing
44497
+ ].join("\n");
44498
+ }
44499
+
44500
+ // ../../packages/core/dist/agents/briefing.js
44501
+ var DESCRIPTION_LIMIT = 110;
44502
+ function firstLine(text, limit = DESCRIPTION_LIMIT) {
44503
+ const line = text.split("\n").find((candidate) => candidate.trim().length > 0)?.trim() ?? "";
44504
+ return line.length > limit ? `${line.slice(0, limit - 1).trimEnd()}\u2026` : line;
44505
+ }
44506
+ function buildRoster(team, self) {
44507
+ const others = team.filter((agent) => agent.role !== self);
44508
+ const usable = others.filter((agent) => agent.available);
44509
+ const assigned = new Set(team.map((agent) => agent.role));
44510
+ const missing = [];
44511
+ for (const role of AGENT_ROLES) {
44512
+ if (role === self)
44513
+ continue;
44514
+ if (!assigned.has(role)) {
44515
+ missing.push(`- **${role}** \u2014 nobody is assigned to this role.`);
44516
+ continue;
44517
+ }
44518
+ const agent = others.find((candidate) => candidate.role === role);
44519
+ if (agent !== void 0 && !agent.available) {
44520
+ missing.push(`- **${role}** \u2014 ${agent.reason ?? "assigned, but cannot be reached."}`);
44521
+ }
44522
+ }
44523
+ const sections = ["## The rest of the team", ""];
44524
+ if (self !== void 0)
44525
+ sections.push(`You are the **${self}**.`, "");
44526
+ sections.push(usable.length > 0 ? "The assistant can also consult these specialists, and only these:" : "The assistant has **no other specialists available**. Whatever you propose, it does alone.");
44527
+ if (usable.length > 0) {
44528
+ sections.push(
44529
+ "",
44530
+ /*
44531
+ * What the others can actually do — and this was wrong once, in the expensive direction.
44532
+ *
44533
+ * It first said "None of them can see the workspace", written to stop the expert giving the
44534
+ * librarian a lookup job. That was false: `agents/consult.ts` gives a specialist the read
44535
+ * tool group, and the CLI expert holds Claude's own Read/Grep/Glob. The instruction was
44536
+ * therefore telling the expert *not* to allocate the librarian the one kind of work the
44537
+ * librarian is equipped for, which made the weakest role weaker.
44538
+ *
44539
+ * The real distinction is per role and the user controls it, so it is rendered from the
44540
+ * team rather than asserted about all of them — and it sits *above* the list, because it is
44541
+ * how to read the marks in it.
44542
+ */
44543
+ "**None of them can edit anything or run anything.** They read and advise; the assistant",
44544
+ "makes every change, and it is the one answerable for the result. Some can look things up",
44545
+ "for themselves, marked below; the rest know only what is in the question, so give those",
44546
+ "everything they need.",
44547
+ "",
44548
+ ...usable.map((agent) => `- **${agent.role}** (${agent.label}) \u2014 ${agent.summary}` + // Marked per role because it decides what is worth asking them: one that can read
44549
+ // needs pointing at a file, one that cannot needs the file pasted in.
44550
+ (agent.usesTools ? " *(can read and search the workspace)*" : "")),
44551
+ "",
44552
+ /*
44553
+ * Knowing who exists is not the same as being asked to use them.
44554
+ *
44555
+ * Reported with a plan that allocated nobody, on a machine where all four other roles were
44556
+ * assigned. The briefing told the expert who was available and told it not to name anyone
44557
+ * who was not — and it dutifully named nobody at all, writing a plan for the assistant
44558
+ * working alone, down to "I'll show you the code before moving on" where a reviewer was
44559
+ * sitting right there. An instruction that only says what *not* to do gets obeyed by doing
44560
+ * nothing.
44561
+ *
44562
+ * Deliberately not "use every specialist": that is four extra round trips on a task that
44563
+ * may not want any, and a plan routing every step through the whole team is worse than one
44564
+ * routing none — it reads as ceremony and people stop reading it.
44565
+ */
44566
+ "**If you are asked for a plan, say who should be involved in which step.** Name the role in",
44567
+ 'the step itself \u2014 "have the tester say what would break this", "get the reviewer onto the',
44568
+ 'callback wiring", "hand the parser to the programmer" \u2014 so the assistant knows when to',
44569
+ "consult and the user can see who is doing what.",
44570
+ "",
44571
+ /*
44572
+ * Two kinds of specialist, said separately, because the first version only described one.
44573
+ *
44574
+ * It asked for allocation "where another reader would genuinely change the outcome" and
44575
+ * called it "another pair of eyes" — review framing throughout, with a reviewer and a
44576
+ * tester as the examples. The programmer does not read, it produces, so a plan written to
44577
+ * that instruction correctly never mentions it. Reported exactly that way: reviewer and
44578
+ * tester allocated across four steps, programmer nowhere, on a machine where it was
44579
+ * assigned. An instruction that names one mode of use gets obeyed in one mode.
44580
+ */
44581
+ "They divide into two kinds, and both are worth allocating:",
44582
+ "",
44583
+ "- **Readers** \u2014 the reviewer, the tester, the librarian. Worth a step where another pair of",
44584
+ " eyes changes what happens: risky or fiddly code, a step that finishes something, a",
44585
+ " convention you would otherwise be guessing at.",
44586
+ "- **The programmer writes.** Where a step is a self-contained piece of code with a spec",
44587
+ " clear enough to hand over \u2014 a parser, a schema, a set of pure functions \u2014 say so and give",
44588
+ " it to the programmer. The assistant checks what comes back against the real file and",
44589
+ " applies it, so this is delegation rather than trust.",
44590
+ "",
44591
+ "Only where it genuinely changes the outcome: a plan that routes every step through all of",
44592
+ "them is ceremony, and one that routes none wastes a team that is sitting there."
44593
+ );
44594
+ }
44595
+ if (missing.length > 0) {
44596
+ sections.push(
44597
+ "",
44598
+ // "Not set up" would be wrong for a role that *is* assigned and whose profile has since
44599
+ // gone: the user did set it up, and telling them otherwise sends them to fix the wrong
44600
+ // thing. "Not available" is true of both, and the reason beside each says which it is.
44601
+ "**Not available, so the assistant cannot use them:**",
44602
+ "",
44603
+ ...missing,
44604
+ "",
44605
+ "Do not give any of these work. Do not put them in a plan, a checklist or a next step \u2014 a",
44606
+ "plan naming a specialist who does not exist is a plan with a hole in it, and the user will",
44607
+ "have approved it without knowing. If a task genuinely needs one, say so in a sentence and",
44608
+ "say the user would have to assign it in Settings \u2192 Agents; then give the best advice you",
44609
+ "can for doing it without that role."
44610
+ );
44611
+ }
44612
+ return sections;
44613
+ }
44614
+ function buildAgentBriefing(input) {
44615
+ const tools = (input.tools ?? []).filter(
44616
+ // Telling a specialist it can consult a specialist is noise at best and a loop at worst.
44617
+ (tool) => tool.name !== "ask_agent" && tool.name !== "ask_expert"
44618
+ );
44619
+ const skills = input.skills ?? [];
44620
+ const team = input.team;
44621
+ if (tools.length === 0 && skills.length === 0 && team === void 0)
44622
+ return "";
44623
+ const sections = [];
44624
+ if (team !== void 0)
44625
+ sections.push(...buildRoster(team, input.self));
44626
+ if (tools.length > 0 || skills.length > 0) {
44627
+ if (sections.length > 0)
44628
+ sections.push("");
44629
+ sections.push("## What the assistant can do on your behalf", "", "You have no tools. The assistant asking you does, and will carry out whatever you recommend.", "Name the tool or skill you mean rather than describing a manual procedure that duplicates it.");
44630
+ }
44631
+ if (tools.length > 0) {
44632
+ sections.push("", "### Tools it can call", "", ...tools.map((tool) => `- \`${tool.name}\` \u2014 ${firstLine(tool.description)}`));
44633
+ }
44634
+ if (skills.length > 0) {
44635
+ sections.push("", "### Skills written for this workspace", "", "House conventions and internal knowledge, already documented. Point at one by name rather", "than restating it; the assistant can open it.", "", ...skills.map((skill) => `- **${skill.name}** \u2014 ${firstLine(skill.description)}`));
44636
+ }
44637
+ return sections.join("\n");
44638
+ }
44639
+
44640
+ // ../../packages/core/dist/agents/consult.js
44641
+ var CONSULT_MAX_STEPS = 5;
44642
+ 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");
44645
+ }
44646
+ async function runConsultation(options) {
44647
+ const limit = options.maxSteps ?? CONSULT_MAX_STEPS;
44648
+ const messages = [{ role: "user", content: options.prompt }];
44649
+ const byName = new Map(options.tools.map((tool) => [tool.name, tool]));
44650
+ let steps = 0;
44651
+ for (; ; ) {
44652
+ const atCap = steps >= limit;
44653
+ let text = "";
44654
+ let call;
44655
+ for await (const chunk of options.provider.streamChat(messages, {
44656
+ ...options.signal !== void 0 ? { signal: options.signal } : {},
44657
+ /*
44658
+ * The tools are withdrawn on the final pass, not merely discouraged.
44659
+ *
44660
+ * A model asked politely to stop looking things up will sometimes look one more thing up,
44661
+ * and then there is no turn left to answer in. Removing them makes answering the only
44662
+ * available move.
44663
+ */
44664
+ ...atCap || options.definitions.length === 0 ? {} : { tools: [...options.definitions] }
44665
+ })) {
44666
+ if (chunk.type === "text")
44667
+ text += chunk.text;
44668
+ else if (chunk.type === "toolCall" && call === void 0) {
44669
+ call = {
44670
+ id: chunk.toolCall.id,
44671
+ name: chunk.toolCall.name,
44672
+ arguments: chunk.toolCall.arguments
44673
+ };
44674
+ } else if (chunk.type === "error") {
44675
+ throw new Error(chunk.error);
44676
+ }
44677
+ }
44678
+ if (call === void 0)
44679
+ return { advice: text, steps, truncated: atCap && steps > 0 };
44680
+ messages.push({ role: "assistant", content: text, toolCalls: [call] });
44681
+ options.onStep?.(call.name);
44682
+ steps += 1;
44683
+ const tool = byName.get(call.name);
44684
+ if (tool === void 0) {
44685
+ messages.push({
44686
+ role: "tool",
44687
+ toolCallId: call.id,
44688
+ content: `You have no "${call.name}". You are read-only here: ${[...byName.keys()].join(", ")}. Anything else, recommend and the assistant will do it.`
44689
+ });
44690
+ continue;
44691
+ }
44692
+ try {
44693
+ const parsed = tool.parametersSchema.safeParse(JSON.parse(call.arguments || "{}"));
44694
+ const result = parsed.success ? await tool.execute(parsed.data, options.context) : {
44695
+ content: `Those arguments are not valid: ${parsed.error.issues.map((i) => i.message).join("; ")}`
44696
+ };
44697
+ messages.push({ role: "tool", toolCallId: call.id, content: String(result.content) });
44698
+ } catch (error51) {
44699
+ messages.push({
44700
+ role: "tool",
44701
+ toolCallId: call.id,
44702
+ content: `That failed: ${error51 instanceof Error ? error51.message : String(error51)}`
44703
+ });
44704
+ }
44705
+ if (steps >= limit) {
44706
+ messages.push({
44707
+ role: "user",
44708
+ content: "That is all the looking up you can do. Answer now with what you have, and say plainly what you could not check."
44709
+ });
44710
+ }
43795
44711
  }
43796
- return lines.join("\n");
43797
44712
  }
43798
44713
 
43799
44714
  // ../../packages/core/dist/tools/recallExpert.js
@@ -43922,8 +44837,8 @@ function assessmentForBriefing(assessment) {
43922
44837
  }
43923
44838
 
43924
44839
  // ../../packages/core/dist/expert/briefing.js
43925
- var DESCRIPTION_LIMIT = 110;
43926
- function firstLine(text, limit = DESCRIPTION_LIMIT) {
44840
+ var DESCRIPTION_LIMIT2 = 110;
44841
+ function firstLine2(text, limit = DESCRIPTION_LIMIT2) {
43927
44842
  const line = text.split("\n").find((candidate) => candidate.trim().length > 0)?.trim() ?? "";
43928
44843
  return line.length > limit ? `${line.slice(0, limit - 1).trimEnd()}\u2026` : line;
43929
44844
  }
@@ -43962,7 +44877,7 @@ function buildExpertBriefing(input) {
43962
44877
  const assessed = assessmentForBriefing(input.juniorAssessment);
43963
44878
  if (assessed !== void 0)
43964
44879
  sections.push("", assessed);
43965
- const listed = (tools) => [...tools].sort((a, b) => a.name.localeCompare(b.name)).map((tool) => `- ${tool.name} \u2014 ${firstLine(tool.description)}`);
44880
+ const listed = (tools) => [...tools].sort((a, b) => a.name.localeCompare(b.name)).map((tool) => `- ${tool.name} \u2014 ${firstLine2(tool.description)}`);
43966
44881
  const dispatchOnly = input.dispatchOnlyTools ?? [];
43967
44882
  const everyTool = [...input.promptTools, ...dispatchOnly];
43968
44883
  if (everyTool.length > 0) {
@@ -43979,7 +44894,7 @@ function buildExpertBriefing(input) {
43979
44894
  const skills = input.skills ?? [];
43980
44895
  if (skills.length > 0) {
43981
44896
  sections.push("", `### Project knowledge written down for the junior (${skills.length})`, "");
43982
- sections.push(...skills.map((skill) => `- ${skill.name} \u2014 ${firstLine(skill.description)}`));
44897
+ sections.push(...skills.map((skill) => `- ${skill.name} \u2014 ${firstLine2(skill.description)}`));
43983
44898
  sections.push("", "Only the summaries are here. Ask the junior to read the full text of any that looks", "relevant \u2014 these describe how this particular team does things, and they override your", "general knowledge where the two disagree.");
43984
44899
  }
43985
44900
  return sections.join("\n");
@@ -47757,18 +48672,23 @@ var NEVER_AVAILABLE_TO_SCHEDULES = [
47757
48672
  // section 13 requires approval showing the source, which cannot happen with nobody there.
47758
48673
  "excel_write_macro",
47759
48674
  // And running one: unattended execution of arbitrary VBA, with nobody to read the source.
47760
- "excel_run_macro"
48675
+ "excel_run_macro",
48676
+ /*
48677
+ * Rewriting the plan it is being held to, with nobody there to approve the diff. Same ladder
48678
+ * as `schedule_prompt`: a run that can change its own instructions is bounded by nothing.
48679
+ */
48680
+ "update_plan"
47761
48681
  ];
47762
48682
  function scheduleAppliesHere(schedule, workspaceRoot) {
47763
48683
  if (schedule.workspaceRoot === void 0)
47764
48684
  return true;
47765
48685
  if (workspaceRoot === void 0)
47766
48686
  return false;
47767
- const normalise = (value) => {
48687
+ const normalise2 = (value) => {
47768
48688
  const resolved = nodePath.resolve(value);
47769
48689
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
47770
48690
  };
47771
- return normalise(schedule.workspaceRoot) === normalise(workspaceRoot);
48691
+ return normalise2(schedule.workspaceRoot) === normalise2(workspaceRoot);
47772
48692
  }
47773
48693
  function filterToolsForSchedule(all, schedule) {
47774
48694
  const named = new Set(schedule.allowedTools);
@@ -48972,7 +49892,14 @@ var ALWAYS_ASK_TOOLS = /* @__PURE__ */ new Set([
48972
49892
  * approval showing the actual source is the only thing standing between "run DoTheThing" and
48973
49893
  * whatever DoTheThing does.
48974
49894
  */
48975
- "excel_run_macro"
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"
48976
49903
  ]);
48977
49904
  function decideFromPolicy(request, approvals) {
48978
49905
  if (!requiresApproval(request.group))
@@ -49087,6 +50014,65 @@ var ShadowGit = class {
49087
50014
  }
49088
50015
  };
49089
50016
 
50017
+ // ../../packages/core/dist/tools/planTools.js
50018
+ var updateParams = external_exports.object({
50019
+ plan: external_exports.string().describe("The complete new plan, as numbered steps. This replaces the whole plan rather than being added to it, so include the steps that are staying."),
50020
+ reason: external_exports.string().optional().describe("One line on why the plan should change, shown to the user with the diff.")
50021
+ });
50022
+ function createUpdatePlanTool(access) {
50023
+ return {
50024
+ name: "update_plan",
50025
+ group: "edit",
50026
+ description: "Propose a new plan for this conversation, replacing the current one. The user is shown a diff and must approve it before anything changes. Use this after working out a plan \u2014 for example one a specialist drafted \u2014 rather than carrying it only in the conversation, which is forgotten as the chat grows. Give the whole plan as numbered steps; each step becomes a checkpoint the user can watch you complete.",
50027
+ parametersSchema: updateParams,
50028
+ async preview(params) {
50029
+ const before = access.current() ?? "";
50030
+ return {
50031
+ kind: "diff",
50032
+ // Not a file. The approval UI labels the diff with this, and naming it for what it is
50033
+ // beats a made-up path that implies something on disk is about to change.
50034
+ path: "the plan for this conversation",
50035
+ before,
50036
+ after: params.plan.slice(0, PLAN_LIMIT).trim(),
50037
+ ...params.reason !== void 0 && params.reason.trim().length > 0 ? { note: params.reason.trim() } : {}
50038
+ };
50039
+ },
50040
+ async execute(params) {
50041
+ const next = params.plan.slice(0, PLAN_LIMIT).trim();
50042
+ if (next.length === 0) {
50043
+ return { content: "A plan cannot be empty. To remove the plan, ask the user to clear it." };
50044
+ }
50045
+ await access.save(next);
50046
+ return {
50047
+ content: "The plan is updated and the user approved it. It is now in front of you for the rest of this conversation, and its steps are the checkpoints to report against."
50048
+ };
50049
+ }
50050
+ };
50051
+ }
50052
+ var progressParams = external_exports.object({
50053
+ checkpoint: external_exports.number().int().describe("The step number, as numbered in the plan you were given."),
50054
+ status: external_exports.enum(["active", "done"]).describe("`active` when you start the step, `done` when it is genuinely finished.")
50055
+ });
50056
+ function createPlanProgressTool(access) {
50057
+ return {
50058
+ name: "plan_progress",
50059
+ /*
50060
+ * Control flow, not an action: it records where you are and touches nothing else. Gating it
50061
+ * would mean an approval prompt between every step of every planned task, which nobody would
50062
+ * keep switched on for long.
50063
+ */
50064
+ group: "always",
50065
+ description: "Say which step of the plan you are on. Call it with `active` when you start a step and `done` when it is finished, so the user can watch progress without reading the whole transcript. Mark `done` only when the step is actually complete \u2014 a step you gave up on or half did should be reported in your reply instead.",
50066
+ parametersSchema: progressParams,
50067
+ async execute(params) {
50068
+ const outcome = await access.mark(params.checkpoint, params.status);
50069
+ if (!outcome.ok)
50070
+ return { content: outcome.reason, isError: true };
50071
+ return { content: outcome.summary };
50072
+ }
50073
+ };
50074
+ }
50075
+
49090
50076
  // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1_ed45788dfbfe808cc09dd7daea6bd385/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
49091
50077
  function isZ4Schema(s) {
49092
50078
  const schema2 = s;
@@ -55954,124 +56940,19 @@ var ASK_MODE = {
55954
56940
  description: "Read-only: inspect the workspace and answer questions. Cannot edit or run commands.",
55955
56941
  groups: ["read", "mcp", "always"]
55956
56942
  };
55957
- var JUNIOR_MODE = {
55958
- id: "junior",
55959
- name: "Junior",
55960
- description: "A cheap model does the work and consults Claude for the plan. Requires the expert.",
56943
+ var AGENT_TEAM_MODE = {
56944
+ id: "agent-team",
56945
+ name: "Agent team",
56946
+ description: "You lead; specialists you assign are consulted as needed. Requires at least one agent.",
55961
56947
  groups: ["read", "edit", "command", "mcp", "always"],
55962
- requiresExpert: true,
55963
- guidance: [
55964
- "# Junior mode",
55965
- "",
55966
- "You are the junior on this task. A stronger model (Claude) is available through",
55967
- "`ask_expert` and is the one that decides *what* to do; you decide *how* and carry it out.",
55968
- "You are the hands: reading, searching, editing, running commands, checking results.",
55969
- "",
55970
- "## The first consultation is expensive; the rest are cheap",
55971
- "",
55972
- "Consultations in one task continue **one conversation**. The first pays to establish it",
55973
- "and costs roughly twenty times a follow-up; every one after that is cheap and the expert",
55974
- "still remembers everything you have told it.",
55975
- "",
55976
- "Two things follow, and they matter more than any other instruction here:",
55977
- "",
55978
- "1. **Make the first consultation count.** Gather what is needed first and ask one full,",
55979
- ' well-formed question. Do not open with "hello" or a question you could answer yourself \u2014',
55980
- " you are paying the setup cost either way, so spend it on something real.",
55981
- "2. **Never repeat yourself afterwards.** The expert remembers the code you pasted, the plan",
55982
- ' it gave you and what you have tried. A follow-up is "step 3 failed with this error",',
55983
- " not the whole story again. Re-explaining throws away the entire saving.",
55984
- "",
55985
- "## Consulting is the default, not the exception",
55986
- "",
55987
- "On any request that is not trivial, **your first action is `ask_expert`** \u2014 before you plan,",
55988
- "before you edit, before you decide the task is straightforward. Do not wait to be told. If",
55989
- 'the user has to say "ask the expert", this mode has failed and is costing them the price of',
55990
- "a worse model for no benefit.",
55991
- "",
55992
- "A request is **not** trivial, and you must consult, if any of these is true:",
55993
- "",
55994
- "- it touches more than one file, or a file you have not read in this session;",
55995
- "- it asks you to design, refactor, choose an approach, or decide between options;",
55996
- "- it involves code you did not write in this conversation;",
55997
- "- you would have to guess at how something works to proceed;",
55998
- "- your first attempt failed, or a test or command reported an error;",
55999
- '- you are about to say "I think" or "probably" about anything load-bearing.',
56000
- "",
56001
- "When in doubt, consult. A consultation costs cents. Confidently doing the wrong thing costs",
56002
- "the user their afternoon.",
56003
- "",
56004
- "Ask for a concrete plan, the files involved, and the traps to avoid \u2014 **broken into",
56005
- "checkpoints**, as described below.",
56006
- "",
56007
- "**Genuinely trivial requests you simply do:** fixing a typo you can see, answering a",
56008
- "question about a file you have already read, running a command the user named. Asking about",
56009
- "those would waste the user\u2019s money on something you already know.",
56010
- "",
56011
- "## Checkpoints: implement, review, continue",
56012
- "",
56013
- "For anything larger than a single edit, ask the expert to split the plan into **checkpoints**.",
56014
- "Then work the loop: implement one checkpoint, go back to the expert with what you actually",
56015
- "did, take its feedback, and move to the next. Keep going until the work is complete.",
56016
- "",
56017
- "**This is a cost measure, not a quality ritual, and the distinction decides how you use it.**",
56018
- "The expensive failure in this arrangement is not a consultation \u2014 it is you building the",
56019
- "wrong thing for twenty turns and then needing the whole approach redone. A review after each",
56020
- "checkpoint costs about as much as one cheap follow-up and caps how far a wrong direction can",
56021
- "run before someone notices. It only pays if you keep it cheap:",
56022
- "",
56023
- "- **A checkpoint is a unit worth reviewing** \u2014 a coherent, working slice, typically a few",
56024
- " related edits. If a checkpoint is one line, the review costs more than the mistake it",
56025
- " could catch: fold it into the next one. If it is the entire feature, it is not a",
56026
- " checkpoint and defeats the point.",
56027
- '- **Report the delta, never the context.** "Checkpoint 2 done: added `retryWithBackoff` in',
56028
- " `http.ts`, wired it into `send()`, tests pass. Deviated from the plan by keeping the old",
56029
- ' signature, because three callers depend on it." The expert has the plan and remembers the',
56030
- "code \u2014 it can open anything it wants to see for itself.",
56031
- "- **Say what surprised you.** The parts worth a review are the deviations, the things that",
56032
- " did not match the plan, and anything you were unsure about. A checkpoint that went exactly",
56033
- " as planned needs a sentence, not a report.",
56034
- "- **Skip the review** when a checkpoint was mechanical and everything passed. Say so at the",
56035
- " next one instead. Two checkpoints in one review is cheaper than two reviews.",
56036
- '- **Run the tests before you report.** "Tests pass" is worth far more to the reviewer than a',
56037
- " description of the code, and finding it yourself is free where the expert finding it is not.",
56038
- "",
56039
- "If a budget is set the expert stops being available once it is reached, and you finish the",
56040
- "work alone. Spend the consultations you have on the checkpoints that carry the most risk.",
56041
- "",
56042
- "**Also consult again when:**",
56043
- "- the same step has failed twice and you do not understand why;",
56044
- "- the code contradicts the plan, so following it would be wrong;",
56045
- "- something is ambiguous in a way that changes *what* should be built, not merely how.",
56046
- "",
56047
- "## Gather the context before you ask",
56048
- "",
56049
- "The expert can open files itself, but doing so costs the user far more than it costs you.",
56050
- "So before consulting: find the relevant code, read it, and **include the actual code in",
56051
- "your question** along with what you have already tried and what happened.",
56052
- "",
56053
- "## You are its hands for tools, too",
56054
- "",
56055
- "The expert cannot call any of your tools \u2014 no MCP tool, no Python tool, no searching the",
56056
- "documentation index. It is told what you have, by name, but not the exact parameters. So",
56057
- "if it asks you to look up a tool\u2019s arguments or read a skill, do it and report back in the",
56058
- "same conversation; that round trip is cheap and stops it guessing a signature.",
56059
- "",
56060
- "## Carrying out the plan",
56061
- "",
56062
- "Follow it, but you are not a transcription service. The expert never ran anything and may",
56063
- "be wrong about the real code. If a step does not match what you find, say so and adapt \u2014",
56064
- "and if the mismatch is fundamental, that is one of the reasons to consult again.",
56065
- "",
56066
- "Tell the user which checkpoint you are on and what the expert said about the last one, so",
56067
- "they can see what they paid for and stop you if the direction is wrong. They are the only",
56068
- "reviewer whose approval actually gates anything."
56069
- ].join("\n")
56948
+ requiresExpert: true
56070
56949
  };
56071
- var BUILTIN_MODES = [CODE_MODE, ASK_MODE, JUNIOR_MODE];
56950
+ var BUILTIN_MODES = [CODE_MODE, ASK_MODE, AGENT_TEAM_MODE];
56072
56951
  var DEFAULT_MODE_ID = CODE_MODE.id;
56952
+ var RENAMED = { junior: AGENT_TEAM_MODE.id };
56073
56953
  function findMode(id) {
56074
- return BUILTIN_MODES.find((mode) => mode.id === id) ?? CODE_MODE;
56954
+ const resolved = id !== void 0 ? RENAMED[id] ?? id : id;
56955
+ return BUILTIN_MODES.find((mode) => mode.id === resolved) ?? CODE_MODE;
56075
56956
  }
56076
56957
 
56077
56958
  // ../../packages/core/dist/modes/resolve.js
@@ -56441,6 +57322,8 @@ async function truncateToolResult(content, store, maxChars = DEFAULT_MAX_CHARS)
56441
57322
 
56442
57323
  // ../../packages/core/dist/agent/loop.js
56443
57324
  var DEFAULT_MAX_ITERATIONS = 25;
57325
+ var BOOKKEEPING_TOOLS = /* @__PURE__ */ new Set(["plan_progress"]);
57326
+ var MAX_REFUNDED_STEPS = 20;
56444
57327
  var MAX_CONSECUTIVE_MISTAKES = 3;
56445
57328
  async function prepareModelMessages(conversation, provider, tools, options, events) {
56446
57329
  const contextWindow = options.contextWindow ?? 0;
@@ -56622,6 +57505,7 @@ async function runWithTimeout(tool, params, context, options) {
56622
57505
  async function runAgentTurn(provider, conversation, userMessage, toolRegistry, toolContext, events, options = {}) {
56623
57506
  conversation.addUserMessage(userMessage, options.images);
56624
57507
  const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
57508
+ let refunded = 0;
56625
57509
  const mistakeCounts = /* @__PURE__ */ new Map();
56626
57510
  let continueNudges = 0;
56627
57511
  const mode = options.mode ?? CODE_MODE;
@@ -56691,6 +57575,10 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
56691
57575
  events.onDone();
56692
57576
  return;
56693
57577
  }
57578
+ if (BOOKKEEPING_TOOLS.has(toolCall.name) && refunded < MAX_REFUNDED_STEPS) {
57579
+ refunded += 1;
57580
+ iteration -= 1;
57581
+ }
56694
57582
  if (result.path !== void 0) {
56695
57583
  if (result.isError === true) {
56696
57584
  const count = (mistakeCounts.get(result.path) ?? 0) + 1;
@@ -59742,6 +60630,8 @@ ${preview.text}` } : {}
59742
60630
  return [skillsDir, ...extraSkillDirs].filter((dir) => dir !== void 0);
59743
60631
  }
59744
60632
  let skills = [];
60633
+ let agentBriefingTools;
60634
+ let consultationContext;
59745
60635
  let skillIssues = [];
59746
60636
  const refreshSkills = async () => {
59747
60637
  const dirs = skillSearchPath();
@@ -59911,17 +60801,21 @@ ${preview.text}` } : {}
59911
60801
  const warnedExpiries = /* @__PURE__ */ new Set();
59912
60802
  let expertCli;
59913
60803
  let expertCliPath;
60804
+ async function detectCli(configured) {
60805
+ if (expertCli !== void 0 && expertCliPath === configured)
60806
+ return expertCli;
60807
+ expertCliPath = configured;
60808
+ expertCli = await detectClaudeCli(configured);
60809
+ if (!expertCli.available)
60810
+ logger.warn("expert unavailable", expertCli.reason ?? "");
60811
+ void postAgents();
60812
+ return expertCli;
60813
+ }
59914
60814
  async function resolveExpert(config2) {
59915
60815
  if (config2.expert?.enabled !== true)
59916
60816
  return void 0;
59917
- const configured = config2.expert.path ?? "claude";
59918
- if (expertCli === void 0 || expertCliPath !== configured) {
59919
- expertCliPath = configured;
59920
- expertCli = await detectClaudeCli(configured);
59921
- if (!expertCli.available)
59922
- logger.warn("expert unavailable", expertCli.reason ?? "");
59923
- }
59924
- return expertCli.available ? expertCli : void 0;
60817
+ const detected = await detectCli(config2.expert.path ?? "claude");
60818
+ return detected.available ? detected : void 0;
59925
60819
  }
59926
60820
  let queuedMessages = [];
59927
60821
  function postQueued() {
@@ -59931,7 +60825,47 @@ ${preview.text}` } : {}
59931
60825
  let taskCheckpoint;
59932
60826
  const ACTIVE_TASK_KEY = "lightCode.activeTaskId";
59933
60827
  let activeTaskId = services.workspaceState.get(ACTIVE_TASK_KEY);
60828
+ let activePlan;
60829
+ let activePlanProgress = {};
59934
60830
  let activeTaskCreatedAt = Date.now();
60831
+ function planViews() {
60832
+ return checkpointViews(activePlan, activePlanProgress);
60833
+ }
60834
+ function postPlanProgress() {
60835
+ post({ type: "planProgress", checkpoints: planViews() });
60836
+ }
60837
+ async function applyPlan(next) {
60838
+ const trimmed = next?.slice(0, PLAN_LIMIT).trim();
60839
+ activePlan = trimmed !== void 0 && trimmed.length > 0 ? trimmed : void 0;
60840
+ activePlanProgress = pruneProgress(activePlan, activePlanProgress);
60841
+ await persistActiveTask();
60842
+ post({ type: "plan", plan: activePlan ?? "" });
60843
+ postPlanProgress();
60844
+ }
60845
+ const planAccess = {
60846
+ current: () => activePlan,
60847
+ save: async (nextPlan) => {
60848
+ await applyPlan(nextPlan);
60849
+ },
60850
+ mark: async (index, status) => {
60851
+ const updated = markCheckpoint(activePlan, activePlanProgress, index, status);
60852
+ if (updated === void 0) {
60853
+ const total = planViews().length;
60854
+ return {
60855
+ ok: false,
60856
+ reason: total === 0 ? "There is no plan set for this conversation, so there is nothing to report against." : `There is no step ${String(index)}. The plan has ${String(total)} steps, numbered 1 to ${String(total)}.`
60857
+ };
60858
+ }
60859
+ activePlanProgress = updated;
60860
+ await persistActiveTask();
60861
+ postPlanProgress();
60862
+ const views = planViews();
60863
+ return {
60864
+ ok: true,
60865
+ summary: `Step ${String(index)} is now ${status}. ${progressSummary(views)} steps complete.`
60866
+ };
60867
+ }
60868
+ };
59935
60869
  async function setActiveTaskId(id) {
59936
60870
  activeTaskId = id;
59937
60871
  await services.workspaceState.set(ACTIVE_TASK_KEY, id);
@@ -60173,7 +61107,9 @@ ${preview.text}` } : {}
60173
61107
  }
60174
61108
  let cachedModeId;
60175
61109
  let cachedCodeGenerator;
60176
- let cachedProviderExpert;
61110
+ let cachedTeam = [];
61111
+ let cachedTeamGuidance;
61112
+ let cachedBudgetMatters = false;
60177
61113
  let cachedMentionExcludes;
60178
61114
  let cachedReportsCost;
60179
61115
  let measuringStep;
@@ -60214,7 +61150,17 @@ ${preview.text}` } : {}
60214
61150
  const { config: config2 } = await configManager.load();
60215
61151
  cachedApprovals = approvalsFrom(config2.approvals);
60216
61152
  cachedCodeGenerator = codeGeneratorFor(config2);
60217
- cachedProviderExpert = providerExpertFor(config2);
61153
+ const teamContext = {
61154
+ config: config2.agents,
61155
+ profiles: (config2.profiles ?? []).map((profile) => ({
61156
+ id: profile.id,
61157
+ label: profile.label
61158
+ })),
61159
+ cliAvailable: expertCli?.available === true
61160
+ };
61161
+ cachedTeam = resolveTeam(teamContext);
61162
+ cachedTeamGuidance = config2.agents?.teamGuidance;
61163
+ cachedBudgetMatters = budgetMatters(teamContext);
60218
61164
  cachedProgrammingProfileId = config2.programmingProfileId;
60219
61165
  cachedOffice = config2.office ?? {};
60220
61166
  cachedMail = config2.mail ?? {};
@@ -60364,6 +61310,8 @@ ${preview.text}` } : {}
60364
61310
  }
60365
61311
  for (const tool of python.generatedTools())
60366
61312
  combined.register(tool, { dispatchOnly: dispatcher });
61313
+ combined.register(createUpdatePlanTool(planAccess), { dispatchOnly: dispatcher });
61314
+ combined.register(createPlanProgressTool(planAccess), { dispatchOnly: dispatcher });
60367
61315
  combined.register(createNotifyTool({
60368
61316
  notify: (message3, level, details) => {
60369
61317
  if (details !== void 0) {
@@ -60509,18 +61457,18 @@ ${preview.text}` } : {}
60509
61457
  observer: searchLog
60510
61458
  }));
60511
61459
  }
60512
- const providerExpert = cachedProviderExpert;
60513
- if (providerExpert !== void 0) {
60514
- combined.register(createRecallExpertTool({ history: () => expertAdvice }));
60515
- combined.register(createAskProviderExpertTool({
60516
- consult: providerExpert.consult,
60517
- label: providerExpert.label,
60518
- onAdvice: (record2) => expertAdvice.push(record2)
61460
+ if (cachedTeam.some((agent) => agent.available)) {
61461
+ combined.register(createAskAgentTool({
61462
+ agents: () => cachedTeam,
61463
+ onAdvice: (record2) => expertAdvice.push(record2),
61464
+ consult: async (agent, request) => consultAgent(agent, request)
60519
61465
  }));
60520
- } else if (expert !== void 0) {
61466
+ }
61467
+ if (expert !== void 0) {
60521
61468
  combined.register(createRecallExpertTool({ history: () => expertAdvice }));
60522
61469
  combined.register(createAskExpertTool({
60523
61470
  cli: expert.cli,
61471
+ budgetMatters: cachedBudgetMatters,
60524
61472
  ...expert.model !== void 0 ? { model: expert.model } : {},
60525
61473
  onConsultation: recordConsultation,
60526
61474
  onAdvice: (record2) => expertAdvice.push(record2),
@@ -60560,6 +61508,7 @@ ${preview.text}` } : {}
60560
61508
  })
60561
61509
  }));
60562
61510
  }
61511
+ agentBriefingTools = () => combined.list();
60563
61512
  return combined;
60564
61513
  }
60565
61514
  async function syncMcpFromConfig(config2) {
@@ -60636,7 +61585,9 @@ ${preview.text}` } : {}
60636
61585
  createdAt: activeTaskCreatedAt,
60637
61586
  updatedAt: Date.now(),
60638
61587
  messages,
60639
- resultHandles: truncationStore.spilledHandles()
61588
+ resultHandles: truncationStore.spilledHandles(),
61589
+ ...activePlan !== void 0 && activePlan.trim().length > 0 ? { plan: activePlan } : {},
61590
+ ...Object.keys(activePlanProgress).length > 0 ? { planProgress: activePlanProgress } : {}
60640
61591
  };
60641
61592
  try {
60642
61593
  await taskStore.save(redactTask(task, await knownSecretValues()));
@@ -60664,8 +61615,12 @@ ${preview.text}` } : {}
60664
61615
  taskCheckpoint = void 0;
60665
61616
  activeTaskCreatedAt = task.createdAt;
60666
61617
  truncationStore.startTask(task.resultHandles);
61618
+ activePlan = task.plan;
61619
+ activePlanProgress = pruneProgress(activePlan, task.planProgress);
60667
61620
  await setActiveTaskId(task.id);
60668
61621
  post({ type: "taskRestored", taskId: task.id, entries: toTranscript(task.messages) });
61622
+ post({ type: "plan", plan: activePlan ?? "" });
61623
+ postPlanProgress();
60669
61624
  await postTasks();
60670
61625
  }
60671
61626
  async function startNewTask() {
@@ -60675,8 +61630,12 @@ ${preview.text}` } : {}
60675
61630
  taskCheckpoint = void 0;
60676
61631
  activeTaskCreatedAt = Date.now();
60677
61632
  truncationStore.startTask();
61633
+ activePlan = void 0;
61634
+ activePlanProgress = {};
60678
61635
  await setActiveTaskId(void 0);
60679
61636
  post({ type: "taskRestored", taskId: void 0, entries: [] });
61637
+ post({ type: "plan", plan: "" });
61638
+ postPlanProgress();
60680
61639
  await postTasks();
60681
61640
  }
60682
61641
  async function deleteTask(id) {
@@ -60757,6 +61716,8 @@ ${preview.text}` } : {}
60757
61716
  ].filter((section) => section.length > 0).join("\n\n") : renderSkillsForPrompt(turnSkills),
60758
61717
  skillsSearchable,
60759
61718
  canWriteSkills: skillsDir !== void 0,
61719
+ // Last in the prompt, and the most specific thing in it — see `agent/plan.ts`.
61720
+ ...activePlan !== void 0 && activePlan.trim().length > 0 ? { plan: activePlan } : {},
60760
61721
  // Only when a pool actually exists: telling the model about a tool it has not been given
60761
61722
  // is how it comes to report that it looked somewhere it could not reach.
60762
61723
  teamSkillsAvailable: config2.embedder?.skillsAlias !== void 0,
@@ -60778,7 +61739,22 @@ ${preview.text}` } : {}
60778
61739
  */
60779
61740
  ...(() => {
60780
61741
  const parts = [];
60781
- if (activeMode.guidance !== void 0 && (activeMode.requiresExpert !== true || expertCliInfo !== void 0)) {
61742
+ if (activeMode.id === AGENT_TEAM_MODE.id) {
61743
+ parts.push(buildTeamGuidance(
61744
+ // The whole team, not only the available ones: the roster names what is missing
61745
+ // as well as what is there, and it cannot do that from a pre-filtered list.
61746
+ cachedTeam,
61747
+ cachedTeamGuidance,
61748
+ cachedBudgetMatters,
61749
+ /*
61750
+ * Whether a plan already exists, which decides whether this mode is told to go
61751
+ * and make one. Passed rather than inferred from the prompt: the plan section is
61752
+ * assembled separately, and a mode guessing at whether it is there would be a
61753
+ * second reading of the same fact.
61754
+ */
61755
+ activePlan !== void 0 && activePlan.trim().length > 0
61756
+ ));
61757
+ } else if (activeMode.guidance !== void 0 && (activeMode.requiresExpert !== true || expertCliInfo !== void 0)) {
60782
61758
  parts.push(activeMode.guidance);
60783
61759
  }
60784
61760
  if (scheduledGuidance !== void 0)
@@ -60814,6 +61790,7 @@ ${preview.text}` } : {}
60814
61790
  // lives in the VSIX, so resolving it is a host concern (§4).
60815
61791
  ...ripgrepPath !== void 0 ? { ripgrepPath } : {}
60816
61792
  };
61793
+ consultationContext = () => toolContext;
60817
61794
  pythonNestedContext = toolContext;
60818
61795
  pythonNestedCallsAllowed = schedule === void 0;
60819
61796
  const mentions = await resolveMentions(text, { fs: toolContext.fs, workspaceRoot, denylist });
@@ -60855,7 +61832,7 @@ ${preview.text}` } : {}
60855
61832
  }
60856
61833
  let cumulativeText = "";
60857
61834
  let cumulativeReasoning = "";
60858
- let expertInformed = false;
61835
+ let informedBy;
60859
61836
  const fullRegistry = currentToolRegistry(
60860
61837
  expertCliInfo !== void 0 ? {
60861
61838
  cli: expertCliInfo,
@@ -60939,7 +61916,7 @@ ${preview.text}` } : {}
60939
61916
  post({
60940
61917
  type: "textChunk",
60941
61918
  text: cumulativeText,
60942
- ...expertInformed ? { expertInformed } : {}
61919
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
60943
61920
  });
60944
61921
  },
60945
61922
  onReasoningChunk: (chunk) => {
@@ -60949,22 +61926,24 @@ ${preview.text}` } : {}
60949
61926
  onToolCall: (toolCall) => {
60950
61927
  cumulativeText = "";
60951
61928
  cumulativeReasoning = "";
60952
- if (toolCall.name === "ask_expert")
60953
- expertInformed = true;
61929
+ const consulting = consultationFromToolCall(toolCall.name, toolCall.arguments);
61930
+ if (consulting !== void 0) {
61931
+ informedBy = consulting;
61932
+ const attributed = attributeConsultation(activePlanProgress, consulting);
61933
+ if (attributed !== activePlanProgress) {
61934
+ activePlanProgress = attributed;
61935
+ postPlanProgress();
61936
+ }
61937
+ }
60954
61938
  if (CONTROL_TOOLS.has(toolCall.name))
60955
61939
  return;
60956
61940
  if (chartFromToolCall(toolCall.name, toolCall.arguments) !== void 0)
60957
61941
  return;
60958
- const summary = {
60959
- id: toolCall.id,
60960
- name: toolCall.name,
60961
- arguments: formatToolArguments(toolCall.arguments),
60962
- ...toolCallReason(toolCall.arguments) === void 0 ? {} : { why: toolCallReason(toolCall.arguments) }
60963
- };
61942
+ const summary = toolCallSummary(toolCall);
60964
61943
  post({
60965
61944
  type: "toolCall",
60966
61945
  toolCall: summary,
60967
- ...expertInformed ? { expertInformed } : {}
61946
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
60968
61947
  });
60969
61948
  },
60970
61949
  onToolResult: (toolCall, result) => {
@@ -60977,22 +61956,18 @@ ${preview.text}` } : {}
60977
61956
  post(chart.kind === "chart" ? {
60978
61957
  type: "chart",
60979
61958
  chart: chart.chart,
60980
- ...expertInformed ? { expertInformed } : {}
61959
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
60981
61960
  } : { type: "chartError", message: chart.message });
60982
61961
  return;
60983
61962
  }
60984
- const summary = {
60985
- id: toolCall.id,
60986
- name: toolCall.name,
60987
- arguments: formatToolArguments(toolCall.arguments),
60988
- ...toolCallReason(toolCall.arguments) === void 0 ? {} : { why: toolCallReason(toolCall.arguments) },
61963
+ const summary = toolCallSummary(toolCall, {
60989
61964
  result: result.content,
60990
61965
  ...result.isError === true ? { isError: true } : {}
60991
- };
61966
+ });
60992
61967
  post({
60993
61968
  type: "toolResult",
60994
61969
  toolCall: summary,
60995
- ...expertInformed ? { expertInformed } : {}
61970
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
60996
61971
  });
60997
61972
  },
60998
61973
  onCheckpoint: (checkpoint) => {
@@ -61141,6 +62116,7 @@ ${preview.text}` } : {}
61141
62116
  cachedAuth = void 0;
61142
62117
  post({ type: "profileSaved" });
61143
62118
  await postProfiles();
62119
+ await postAgents();
61144
62120
  } catch (error51) {
61145
62121
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
61146
62122
  }
@@ -61194,6 +62170,7 @@ ${preview.text}` } : {}
61194
62170
  };
61195
62171
  await configManager.save("user", { profiles: [...profiles, duplicate] });
61196
62172
  await postProfiles();
62173
+ await postAgents();
61197
62174
  } catch (error51) {
61198
62175
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
61199
62176
  }
@@ -61208,6 +62185,7 @@ ${preview.text}` } : {}
61208
62185
  const activeProfileId = config2.activeProfileId === id ? remaining[0]?.id : config2.activeProfileId;
61209
62186
  await configManager.save("user", { profiles: remaining, activeProfileId });
61210
62187
  await postProfiles();
62188
+ await postAgents();
61211
62189
  } catch (error51) {
61212
62190
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
61213
62191
  }
@@ -61226,6 +62204,7 @@ ${preview.text}` } : {}
61226
62204
  await configManager.save("user", { activeProfileId: id });
61227
62205
  await postProjectSettings();
61228
62206
  await postProfiles();
62207
+ await postAgents();
61229
62208
  } catch (error51) {
61230
62209
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
61231
62210
  }
@@ -61277,26 +62256,16 @@ ${preview.text}` } : {}
61277
62256
  // The whole thing, profiles included. Passing only half of what the constructor takes is
61278
62257
  // the same mistake as having two constructors, and this failure path is where the last
61279
62258
  // one hid: it runs rarely, so a field missing here is noticed much later than elsewhere.
61280
- ...expertMessageFrom(settings, loaded?.profiles),
62259
+ ...expertMessageFrom(settings),
61281
62260
  available: false,
61282
62261
  path: settings?.path ?? expertCliPath ?? "claude",
61283
62262
  reason: `Could not check whether the Claude CLI is available: ${reason}`
61284
62263
  });
61285
62264
  }
61286
62265
  }
61287
- function expertMessageFrom(settings, profiles) {
62266
+ function expertMessageFrom(settings) {
61288
62267
  return {
61289
62268
  type: "expert",
61290
- /*
61291
- * Sent from here and nowhere else. CLAUDE.md records what happened the last time two
61292
- * `expert` messages were built separately: measured pricing reached the success path and
61293
- * not the failure path, and the panel showed a dash for something that had been measured.
61294
- */
61295
- ...services.expertMode === "profile" ? {
61296
- mode: "profile",
61297
- profiles: (profiles ?? []).map((profile) => ({ id: profile.id, label: profile.label })),
61298
- ...settings?.profileId !== void 0 ? { profileId: settings.profileId } : {}
61299
- } : {},
61300
62269
  enabled: settings?.enabled === true,
61301
62270
  available: false,
61302
62271
  path: settings?.path ?? expertCliPath ?? "claude",
@@ -61313,24 +62282,81 @@ ${preview.text}` } : {}
61313
62282
  ...expertEvents !== void 0 ? { savings: summariseSavings(expertEvents, settings?.pricing) } : {}
61314
62283
  };
61315
62284
  }
61316
- async function postExpertInner(redetect) {
62285
+ async function postAgents() {
61317
62286
  const { config: config2 } = await configManager.load();
61318
- if (services.expertMode === "profile") {
61319
- post({
61320
- ...expertMessageFrom(config2.expert, config2.profiles),
61321
- // Usable when a profile is chosen, which is the only thing availability can mean here.
61322
- available: config2.expert?.enabled === true && config2.expert.profileId !== void 0 && config2.profiles?.some((profile) => profile.id === config2.expert?.profileId) === true
61323
- });
61324
- return;
62287
+ const cli = await detectCli(config2.expert?.path ?? "claude").catch(() => void 0);
62288
+ const teamContext = {
62289
+ config: config2.agents,
62290
+ profiles: (config2.profiles ?? []).map((profile) => ({
62291
+ id: profile.id,
62292
+ label: profile.label
62293
+ })),
62294
+ cliAvailable: cli?.available === true
62295
+ };
62296
+ const assigned = new Map(resolveTeam(teamContext).map((agent) => [agent.role, agent]));
62297
+ const roles = allRoles().map((info) => {
62298
+ const agent = assigned.get(info.role);
62299
+ const prompt = config2.agents?.roles?.[info.role]?.prompt;
62300
+ return {
62301
+ role: info.role,
62302
+ name: info.name,
62303
+ summary: info.summary,
62304
+ ...agent !== void 0 ? { kind: agent.kind } : {},
62305
+ ...agent?.profileId !== void 0 ? { profileId: agent.profileId } : {},
62306
+ label: agent?.label ?? "Nobody",
62307
+ available: agent?.available ?? false,
62308
+ ...agent?.reason !== void 0 ? { reason: agent.reason } : {},
62309
+ prompt: prompt ?? defaultPromptFor(info.role),
62310
+ promptIsDefault: prompt === void 0
62311
+ };
62312
+ });
62313
+ const guidance = config2.agents?.teamGuidance;
62314
+ post({
62315
+ type: "agents",
62316
+ roles,
62317
+ profiles: teamContext.profiles,
62318
+ cliAvailable: teamContext.cliAvailable,
62319
+ ...cli?.available === false && cli.reason !== void 0 ? { cliReason: cli.reason } : {},
62320
+ budgetMatters: budgetMatters(teamContext),
62321
+ teamGuidance: guidance ?? DEFAULT_TEAM_GUIDANCE,
62322
+ defaultTeamGuidance: DEFAULT_TEAM_GUIDANCE,
62323
+ teamGuidanceIsDefault: guidance === void 0,
62324
+ colors: {
62325
+ /*
62326
+ * The expert's colour comes from the control that has always owned it.
62327
+ *
62328
+ * It predates roles and lives under `ui.expertColor`, and the Agents work briefly gave it
62329
+ * a second home under `agents.colors.expert` — two pickers for one thing, backed by two
62330
+ * settings, which is the drift this project pays for most often. An explicit per-role
62331
+ * value still wins, so nothing is taken away; it is simply no longer the *default*
62332
+ * source for a colour that already had one.
62333
+ */
62334
+ expert: config2.ui?.expertColor ?? "#D97757",
62335
+ ...config2.agents?.colors ?? {}
62336
+ }
62337
+ });
62338
+ }
62339
+ async function saveAgents(change) {
62340
+ try {
62341
+ const { config: config2 } = await configManager.load();
62342
+ await configManager.save("user", { agents: change(config2.agents ?? {}) });
62343
+ await loadSettings();
62344
+ await postAgents();
62345
+ } catch (error51) {
62346
+ post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
61325
62347
  }
62348
+ }
62349
+ async function postExpertInner(redetect) {
62350
+ const { config: config2 } = await configManager.load();
61326
62351
  await loadExpertEvents();
61327
62352
  const configured = config2.expert?.path ?? "claude";
61328
62353
  const detected = !redetect && expertCli !== void 0 && expertCliPath === configured ? expertCli : await detectClaudeCli(configured);
61329
62354
  expertCli = detected;
61330
62355
  expertCliPath = configured;
62356
+ void postAgents();
61331
62357
  post({
61332
62358
  // Everything from settings comes from one place, so the two paths cannot drift again.
61333
- ...expertMessageFrom(config2.expert, config2.profiles),
62359
+ ...expertMessageFrom(config2.expert),
61334
62360
  available: detected.available,
61335
62361
  path: configured,
61336
62362
  ...detected.version !== void 0 ? { version: detected.version } : {},
@@ -63311,6 +64337,7 @@ ${preview.text}` } : {}
63311
64337
  }));
63312
64338
  await configManager.save("user", { ...imported, profiles: reconciled });
63313
64339
  await postProfiles();
64340
+ await postAgents();
63314
64341
  ui.showInfo(needKeys.length > 0 ? `Config imported. Re-enter the API key for: ${needKeys.join(", ")} (exports never include secrets).` : "Config imported.");
63315
64342
  } catch (error51) {
63316
64343
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
@@ -63332,35 +64359,79 @@ ${preview.text}` } : {}
63332
64359
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
63333
64360
  }
63334
64361
  }
63335
- function providerExpertFor(config2) {
63336
- if (services.expertMode !== "profile")
63337
- return void 0;
63338
- if (config2.expert?.enabled !== true)
63339
- return void 0;
63340
- const id = config2.expert.profileId;
63341
- if (id === void 0 || id.length === 0)
63342
- return void 0;
63343
- const profile = config2.profiles?.find((candidate) => candidate.id === id);
64362
+ async function consultAgent(agent, request) {
64363
+ const prompt = buildAgentPrompt({
64364
+ prompt: agent.prompt,
64365
+ question: request.question,
64366
+ // Decides the preamble as well as whether tools are offered below, so the two can never
64367
+ // disagree — a specialist told it can read, and then given nothing to read with, wastes a
64368
+ // step discovering that.
64369
+ usesTools: agent.usesTools,
64370
+ ...request.files !== void 0 ? { files: request.files } : {},
64371
+ /*
64372
+ * What exists in this workspace.
64373
+ *
64374
+ * Without it a specialist advises as though the assistant were a bare shell — proposing by
64375
+ * hand what a configured tool already does, or inventing a procedure an existing skill
64376
+ * documents. See `agents/briefing.ts` for why names are worth the tokens and schemas are not.
64377
+ */
64378
+ briefing: buildAgentBriefing({
64379
+ tools: agentBriefingTools?.() ?? [],
64380
+ skills,
64381
+ /*
64382
+ * Who else exists, so a plan cannot name a specialist nobody set up.
64383
+ *
64384
+ * Built here, above the `kind` branch, which is the point: the Claude CLI expert and a
64385
+ * provider-profile expert are given byte-identical briefings, so making a different model
64386
+ * the expert cannot change what it knows about the team. `briefing.test.ts` pins that,
64387
+ * because the two paths diverging is invisible until somebody switches expert and gets a
64388
+ * worse plan for no reason they could name.
64389
+ */
64390
+ team: cachedTeam,
64391
+ self: agent.role
64392
+ })
64393
+ });
64394
+ if (agent.kind === "cli") {
64395
+ const cli = expertCli;
64396
+ if (cli === void 0 || !cli.available)
64397
+ throw new Error("The Claude CLI is not available.");
64398
+ const answer = await consultExpert(cli, {
64399
+ question: prompt,
64400
+ /*
64401
+ * The workspace, so Claude's own Read/Grep resolve against the project rather than
64402
+ * wherever this process was started. Falls back to the process directory when no folder
64403
+ * is open — the consultation is still worth having without one.
64404
+ */
64405
+ cwd: workspaceRoot ?? process.cwd(),
64406
+ ...request.signal !== void 0 ? { signal: request.signal } : {}
64407
+ });
64408
+ if (answer.isError)
64409
+ throw new Error(answer.text);
64410
+ return { advice: answer.text, label: agent.label };
64411
+ }
64412
+ const { config: config2 } = await configManager.load();
64413
+ const profile = config2.profiles?.find((candidate) => candidate.id === agent.profileId);
63344
64414
  if (profile === void 0) {
63345
- logger.warn(`the expert profile "${id}" is configured but no such profile exists; the expert is unavailable`);
63346
- return void 0;
64415
+ throw new Error(`No profile "${agent.profileId ?? ""}" exists any more.`);
64416
+ }
64417
+ const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger);
64418
+ const readOnly = agent.usesTools ? toolsForConsultation(agentBriefingTools?.() ?? []) : [];
64419
+ const context = consultationContext?.();
64420
+ const result = await runConsultation({
64421
+ provider,
64422
+ prompt,
64423
+ tools: readOnly,
64424
+ definitions: context === void 0 ? [] : toToolDefinitions(readOnly),
64425
+ // With no context there is nothing to read *with*, so it answers from the question alone
64426
+ // rather than being offered tools that would fail.
64427
+ context: context ?? {},
64428
+ ...request.signal !== void 0 ? { signal: request.signal } : {},
64429
+ onStep: (name) => logger.info(`${agent.role} looked up ${name}`)
64430
+ });
64431
+ if (result.truncated) {
64432
+ logger.info(`${agent.role} reached its lookup limit and answered with what it had`);
63347
64433
  }
63348
- return {
63349
- label: profile.label,
63350
- consult: async (request) => {
63351
- const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger);
63352
- let text = "";
63353
- for await (const chunk of provider.streamChat([{ role: "user", content: buildExpertPrompt(request) }], {
63354
- // No tools offered: it is being asked for judgement, and offering tools invites it to
63355
- // reach for one it has no way to run.
63356
- ...request.signal !== void 0 ? { signal: request.signal } : {}
63357
- })) {
63358
- if (chunk.type === "text")
63359
- text += chunk.text;
63360
- }
63361
- return { advice: text, producedBy: profile.label };
63362
- }
63363
- };
64434
+ return { advice: result.advice, label: agent.label };
63364
64435
  }
63365
64436
  function codeGeneratorFor(config2) {
63366
64437
  if (services.allowProgrammingProfile !== true)
@@ -64105,6 +65176,80 @@ ${preview.text}` } : {}
64105
65176
  void handleSaveNetwork(message3.settings);
64106
65177
  } else if (message3.type === "requestExpert") {
64107
65178
  void postExpert();
65179
+ } else if (message3.type === "setPlan") {
65180
+ void applyPlan(message3.plan);
65181
+ } else if (message3.type === "requestPlan") {
65182
+ post({ type: "plan", plan: activePlan ?? "" });
65183
+ postPlanProgress();
65184
+ } else if (message3.type === "requestPlanProgress") {
65185
+ postPlanProgress();
65186
+ } else if (message3.type === "requestAgents") {
65187
+ void postAgents();
65188
+ } else if (message3.type === "setAgentRole") {
65189
+ const assignment = message3.assignment;
65190
+ const role = message3.role;
65191
+ if (!isAgentRole(role)) {
65192
+ post({ type: "error", message: `There is no "${role}" role.` });
65193
+ return;
65194
+ }
65195
+ void saveAgents((current) => {
65196
+ const roles = { ...current.roles ?? {} };
65197
+ if (assignment === void 0)
65198
+ delete roles[role];
65199
+ else {
65200
+ roles[role] = {
65201
+ kind: assignment.kind,
65202
+ ...assignment.profileId !== void 0 ? { profileId: assignment.profileId } : {},
65203
+ ...roles[role]?.prompt !== void 0 ? { prompt: roles[role].prompt } : {}
65204
+ };
65205
+ }
65206
+ return { ...current, roles };
65207
+ });
65208
+ } else if (message3.type === "setAgentPrompt") {
65209
+ const role = message3.role;
65210
+ const prompt = message3.prompt;
65211
+ if (!isAgentRole(role)) {
65212
+ post({ type: "error", message: `There is no "${role}" role.` });
65213
+ return;
65214
+ }
65215
+ void saveAgents((current) => {
65216
+ const roles = { ...current.roles ?? {} };
65217
+ const existing = roles[role];
65218
+ if (prompt === void 0 || prompt === defaultPromptFor(role)) {
65219
+ if (existing !== void 0) {
65220
+ const rest = { ...existing };
65221
+ delete rest.prompt;
65222
+ roles[role] = rest;
65223
+ }
65224
+ } else {
65225
+ roles[role] = { ...existing ?? { kind: "profile" }, prompt };
65226
+ }
65227
+ return { ...current, roles };
65228
+ });
65229
+ } else if (message3.type === "setAgentBudget") {
65230
+ const matters = message3.matters;
65231
+ void saveAgents((current) => ({ ...current, budgetMatters: matters }));
65232
+ } else if (message3.type === "setTeamGuidance") {
65233
+ const guidance = message3.guidance;
65234
+ void saveAgents((current) => {
65235
+ if (guidance === void 0 || guidance.trim().length === 0 || guidance === DEFAULT_TEAM_GUIDANCE) {
65236
+ const rest = { ...current };
65237
+ delete rest.teamGuidance;
65238
+ return rest;
65239
+ }
65240
+ return { ...current, teamGuidance: guidance };
65241
+ });
65242
+ } else if (message3.type === "setAgentColor") {
65243
+ const role = message3.role;
65244
+ const color = message3.color;
65245
+ if (!isAgentRole(role)) {
65246
+ post({ type: "error", message: `There is no "${role}" role.` });
65247
+ return;
65248
+ }
65249
+ void saveAgents((current) => ({
65250
+ ...current,
65251
+ colors: { ...current.colors ?? {}, [role]: color }
65252
+ }));
64108
65253
  } else if (message3.type === "setExpert") {
64109
65254
  void handleSetExpert(message3.enabled, message3.path, message3.model, {
64110
65255
  ...message3.maxSpendUsd !== void 0 ? { maxSpendUsd: message3.maxSpendUsd } : {},
@@ -64774,7 +65919,10 @@ function chartTotals(spec) {
64774
65919
  }
64775
65920
 
64776
65921
  // ../../packages/core/dist/history/transcript.js
64777
- var CONTROL_TOOLS = /* @__PURE__ */ new Set(["attempt_completion", "ask_followup_question"]);
65922
+ var CONTROL_TOOLS = /* @__PURE__ */ new Set([
65923
+ "attempt_completion",
65924
+ "ask_followup_question"
65925
+ ]);
64778
65926
  function formatToolArguments(raw) {
64779
65927
  try {
64780
65928
  const parsed = JSON.parse(raw.length > 0 ? raw : "{}");
@@ -64806,7 +65954,7 @@ function toTranscript(messages) {
64806
65954
  resultsByCallId.set(message3.toolCallId, message3.content);
64807
65955
  }
64808
65956
  const entries = [];
64809
- let expertInformed = false;
65957
+ let informedBy;
64810
65958
  for (const message3 of messages) {
64811
65959
  if (message3.role === "system" || message3.role === "tool")
64812
65960
  continue;
@@ -64815,13 +65963,22 @@ function toTranscript(messages) {
64815
65963
  continue;
64816
65964
  }
64817
65965
  if (message3.content.length > 0) {
64818
- entries.push({ kind: "text", role: "assistant", content: message3.content, ...expertInformed ? { expertInformed } : {} });
65966
+ entries.push({
65967
+ kind: "text",
65968
+ role: "assistant",
65969
+ content: message3.content,
65970
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
65971
+ });
64819
65972
  }
64820
65973
  for (const toolCall of message3.toolCalls ?? []) {
64821
65974
  const result = resultsByCallId.get(toolCall.id);
64822
65975
  const asChart = chartFromToolCall(toolCall.name, toolCall.arguments);
64823
65976
  if (asChart !== void 0) {
64824
- entries.push(asChart.kind === "chart" ? { kind: "chart", chart: asChart.chart, ...expertInformed ? { expertInformed: true } : {} } : asChart);
65977
+ entries.push(asChart.kind === "chart" ? {
65978
+ kind: "chart",
65979
+ chart: asChart.chart,
65980
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
65981
+ } : asChart);
64825
65982
  continue;
64826
65983
  }
64827
65984
  if (CONTROL_TOOLS.has(toolCall.name)) {
@@ -64829,26 +65986,46 @@ function toTranscript(messages) {
64829
65986
  entries.push({ kind: "text", role: "assistant", content: result });
64830
65987
  continue;
64831
65988
  }
64832
- if (toolCall.name === "ask_expert")
64833
- expertInformed = true;
65989
+ const consulting = consultationFromToolCall(toolCall.name, toolCall.arguments);
65990
+ if (consulting !== void 0)
65991
+ informedBy = consulting;
64834
65992
  entries.push({
64835
65993
  kind: "tool",
64836
- ...expertInformed ? { expertInformed: true } : {},
64837
- toolCall: {
64838
- id: toolCall.id,
64839
- name: toolCall.name,
64840
- arguments: formatToolArguments(toolCall.arguments),
64841
- ...toolCallReason(toolCall.arguments) === void 0 ? {} : { why: toolCallReason(toolCall.arguments) },
64842
- // A call with no matching result means the task ended mid-flight — a cancel, a
64843
- // crash, or a window closed. Leaving `result` unset renders it as unfinished,
64844
- // which is what actually happened.
64845
- ...result !== void 0 ? { result } : {}
64846
- }
65994
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {},
65995
+ /*
65996
+ * Built by the one builder, so a restored transcript and a live turn cannot differ about
65997
+ * what a call looked like. A call with no matching result means the task ended mid-flight
65998
+ * — a cancel, a crash, a window closed — and leaving `result` unset renders it as
65999
+ * unfinished, which is what actually happened.
66000
+ */
66001
+ toolCall: toolCallSummary(toolCall, { result })
64847
66002
  });
64848
66003
  }
64849
66004
  }
64850
66005
  return entries;
64851
66006
  }
66007
+ function toolCallSummary(call, outcome) {
66008
+ const why = toolCallReason(call.arguments);
66009
+ const consulting = consultationFromToolCall(call.name, call.arguments);
66010
+ return {
66011
+ id: call.id,
66012
+ name: call.name,
66013
+ arguments: formatToolArguments(call.arguments),
66014
+ ...why !== void 0 ? { why } : {},
66015
+ ...consulting !== void 0 ? { consultingRole: consulting } : {},
66016
+ ...outcome?.result !== void 0 ? { result: outcome.result } : {},
66017
+ ...outcome?.isError === true ? { isError: true } : {}
66018
+ };
66019
+ }
66020
+ function consultationFromToolCall(name, rawArguments) {
66021
+ if (name === "ask_expert")
66022
+ return "expert";
66023
+ if (name !== "ask_agent")
66024
+ return void 0;
66025
+ const decoded = decodeArguments(rawArguments);
66026
+ const role = typeof decoded === "object" && decoded !== null ? decoded.role : void 0;
66027
+ return typeof role === "string" && role.trim().length > 0 ? role.trim().toLowerCase() : "unknown";
66028
+ }
64852
66029
  function chartFromToolCall(name, rawArguments) {
64853
66030
  if (name !== "show_chart")
64854
66031
  return void 0;
@@ -67580,16 +68757,6 @@ async function createSession(options) {
67580
68757
  * The extension says nothing and keeps all of it — that is where the feature is used.
67581
68758
  */
67582
68759
  offersOffice: false,
67583
- /*
67584
- * The expert is a provider profile here, not the Claude CLI.
67585
- *
67586
- * Asked for directly: any configured model should be able to be the expert, and cost is no
67587
- * longer something to manage in the product. Both follow from where this runs — there is no
67588
- * `claude` binary on a server, and the gateway answering the chat already has a stronger
67589
- * model behind it. Everything about budgets, measured price and savings belongs to the CLI
67590
- * expert, which is what the extension still has.
67591
- */
67592
- expertMode: "profile",
67593
68760
  transport: options.transport,
67594
68761
  /*
67595
68762
  * A shared profile's API key belongs to the administrator and lives beside the shared config;
@@ -68174,7 +69341,7 @@ function respondJson(response, status, body) {
68174
69341
  }
68175
69342
 
68176
69343
  // src/cli.ts
68177
- var VERSION = true ? "0.44.0" : "unknown (not a packaged build)";
69344
+ var VERSION = true ? "0.50.0" : "unknown (not a packaged build)";
68178
69345
  var compat = installNodeCompat();
68179
69346
  function lastMeaningfulLine(problem) {
68180
69347
  const lines = problem.split(String.fromCharCode(10)).map((line) => line.trim()).filter((line) => line.length > 0 && !line.endsWith(":"));