@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/server.js CHANGED
@@ -39652,6 +39652,53 @@ var pythonConfigSchema = external_exports.object({
39652
39652
  })
39653
39653
  ]))
39654
39654
  }).partial();
39655
+ var agentAssignmentSchema = external_exports.object({
39656
+ /** `cli` is the Claude command line; `profile` names one of the user's provider profiles. */
39657
+ kind: external_exports.enum(["cli", "profile"]),
39658
+ profileId: external_exports.string().optional(),
39659
+ /**
39660
+ * The role's system prompt, stored only when the user has edited it.
39661
+ *
39662
+ * Absent means "use the default", which is what lets an improved default reach somebody who
39663
+ * has looked at the tab without editing anything. Storing the default verbatim would pin
39664
+ * every user to whatever it said the day they first opened it.
39665
+ */
39666
+ prompt: external_exports.string().optional()
39667
+ }).strict();
39668
+ var customRoleSchema = external_exports.object({
39669
+ id: external_exports.string().min(1),
39670
+ name: external_exports.string().min(1),
39671
+ summary: external_exports.string(),
39672
+ prompt: external_exports.string()
39673
+ });
39674
+ var agentsConfigSchema = external_exports.object({
39675
+ roles: external_exports.record(external_exports.string(), agentAssignmentSchema),
39676
+ /**
39677
+ * Roles the user invented, beyond the five built in.
39678
+ *
39679
+ * A role *is* its prompt, and the ones people ask for next are nearly always a reviewer with
39680
+ * a different one — security, performance, accessibility. Defining them here answers that
39681
+ * whole family without a code change each time, and without growing the fixed roster the
39682
+ * expert has to allocate from.
39683
+ *
39684
+ * Covered by the same user-scope rule as the rest of this block, and it is the sharpest part
39685
+ * of it: this is prose injected into a model that is then asked to advise on this
39686
+ * repository, so a workspace able to write it could define a reviewer that approves anything.
39687
+ */
39688
+ definitions: external_exports.array(customRoleSchema),
39689
+ /** Whether what a consultation costs is worth managing. See `agents/team.ts`. */
39690
+ budgetMatters: external_exports.boolean(),
39691
+ /** The Agent team mode instruction, when edited. The roster is always generated. */
39692
+ teamGuidance: external_exports.string(),
39693
+ /**
39694
+ * A colour per role, for marking whose words a piece of advice is.
39695
+ *
39696
+ * Here rather than under `appearance` because it is keyed by role, and the roles are defined
39697
+ * here — splitting them would mean adding a role in one place and remembering to give it a
39698
+ * colour in another, which is the drift this project keeps paying for.
39699
+ */
39700
+ colors: external_exports.record(external_exports.string(), external_exports.string())
39701
+ }).partial();
39655
39702
  var autoApproveSchema = external_exports.object({
39656
39703
  read: external_exports.boolean(),
39657
39704
  edit: external_exports.boolean(),
@@ -40033,6 +40080,7 @@ var configSchema = external_exports.object({
40033
40080
  /** User-scope only: a workspace able to add a trusted root could enable interception. */
40034
40081
  tls: globalTlsSchema,
40035
40082
  expert: expertConfigSchema,
40083
+ agents: agentsConfigSchema,
40036
40084
  /**
40037
40085
  * User-scope only (invariant 5). A workspace able to name a cluster or repoint the
40038
40086
  * embedder would exfiltrate whatever gets indexed — sharper than the existing entries,
@@ -40689,6 +40737,11 @@ var USER_SCOPE_ONLY_KEYS = [
40689
40737
  // its choosing as soon as the panel opened — the same threat as `python.uvPath`.
40690
40738
  // `expert.enabled` is here too, so a repo cannot switch on paid API calls by itself.
40691
40739
  "expert",
40740
+ // Names provider profiles, so a workspace able to write it could route a consultation through a
40741
+ // gateway of its choosing — the same threat as `activeProfileId`. And it carries prompts, which
40742
+ // are prose injected into a model then asked to advise on this repository's own code: a hostile
40743
+ // repo could tell the reviewer what to approve.
40744
+ "agents",
40692
40745
  // Added for Phase 8b, and the sharpest entries on this list. A workspace able to name a
40693
40746
  // cluster, or repoint the embedder at a profile of its choosing, would exfiltrate
40694
40747
  // whatever gets indexed — and what gets indexed is the source code.
@@ -43194,6 +43247,373 @@ var Conversation = class {
43194
43247
  }
43195
43248
  };
43196
43249
 
43250
+ // ../../packages/core/dist/agents/roles.js
43251
+ var AGENT_ROLES = ["expert", "programmer", "reviewer", "tester", "librarian"];
43252
+ function isAgentRole(value, custom2 = []) {
43253
+ return AGENT_ROLES.includes(value) || custom2.some((role) => role.id === value);
43254
+ }
43255
+ function knownRoles(custom2 = []) {
43256
+ return [...AGENT_ROLES, ...custom2.map((role) => role.id)];
43257
+ }
43258
+ var SHARED_TAIL = [
43259
+ "Your reply is advice. The assistant will check it against the real code before acting, and it",
43260
+ "is responsible for the result. Be concrete, say what you are unsure about, and say plainly when",
43261
+ "something must be verified rather than assumed.",
43262
+ "",
43263
+ "Answer in prose and short lists. No preamble about being happy to help."
43264
+ ];
43265
+ var SHARED_WITH_TOOLS = [
43266
+ "You can read this workspace: open files, list them, and search. Use that rather than guessing,",
43267
+ "and rather than asking the assistant for something you can fetch yourself. You have a small",
43268
+ "budget of lookups, so go for what actually settles the question.",
43269
+ "",
43270
+ "You cannot edit anything, run anything, or reach the network. If something needs changing, say",
43271
+ "what and why \u2014 the assistant makes the change and is responsible for it.",
43272
+ "",
43273
+ ...SHARED_TAIL
43274
+ ].join("\n");
43275
+ var SHARED_BLIND = [
43276
+ "You have no tools and cannot see the workspace. Everything you have is in the question. If",
43277
+ "something essential is missing, say exactly what you need and why, then give the best answer you",
43278
+ "can without it \u2014 never refuse to answer.",
43279
+ "",
43280
+ ...SHARED_TAIL
43281
+ ].join("\n");
43282
+ function specialistPreamble(usesTools) {
43283
+ return usesTools ? SHARED_WITH_TOOLS : SHARED_BLIND;
43284
+ }
43285
+ var DEFINITIONS = {
43286
+ expert: {
43287
+ name: "Expert",
43288
+ summary: "Hard problems, architecture, and deciding what to do",
43289
+ /* Planning a change means knowing what is already there, and it spans files the asker
43290
+ * cannot paste all of. */
43291
+ usesTools: true,
43292
+ prompt: [
43293
+ "You are a senior engineer being consulted by another AI assistant that is doing the work.",
43294
+ "",
43295
+ "It has hit something hard: a change across several files to plan, a bug it has already",
43296
+ "failed to fix, or a design choice with no obvious answer. Give it your judgement.",
43297
+ "",
43298
+ "Decide *what* should happen and why. Leave the typing to the assistant \u2014 it is the one",
43299
+ "making the change and answering for it. Where there is a real trade-off, name both sides",
43300
+ "and then choose."
43301
+ ].join("\n")
43302
+ },
43303
+ programmer: {
43304
+ name: "Programmer",
43305
+ summary: "Writes the code once the plan is settled",
43306
+ /* It is handed a spec and the surrounding code and asked to write. Looking around buys
43307
+ * a slower answer that is no better. */
43308
+ usesTools: false,
43309
+ prompt: [
43310
+ "You are an experienced programmer writing code for another AI assistant to apply.",
43311
+ "",
43312
+ "You are given a requirement and the surrounding code. Produce the change, matching the",
43313
+ "conventions of what you were shown rather than your own preferences \u2014 the naming, the error",
43314
+ "handling, the comment density, the way the existing code does this sort of thing.",
43315
+ "",
43316
+ "Return the code and a short note on anything non-obvious in it. Do not narrate what you are",
43317
+ "about to do, and do not rewrite things you were not asked to change.",
43318
+ "",
43319
+ /*
43320
+ * The programmer is the role that gets its own work handed back, so it is the one that has
43321
+ * to be told what to do with a review — including that it may disagree. Requested in those
43322
+ * terms: it is classified as the programmer, so fixing it is its job, and it should be able
43323
+ * to challenge a reviewer rather than obey one.
43324
+ */
43325
+ "You may be given a review of code you wrote. Fix what is genuinely wrong and return the",
43326
+ "corrected code the same way. **Where the review is wrong, say so and say why** \u2014 a finding",
43327
+ "can be about a path that cannot happen, a convention this codebase does not follow, or a",
43328
+ "misreading of a fragment. Do not rewrite working code to satisfy an objection you think is",
43329
+ "mistaken; the assistant has the real file and will settle it. Changing something you believe",
43330
+ "is right, because you were told to, is the worse failure: it looks like agreement."
43331
+ ].join("\n")
43332
+ },
43333
+ reviewer: {
43334
+ name: "Reviewer",
43335
+ summary: "Reads a change and says what is wrong with it",
43336
+ /* Most of what a review turns on is *around* the diff — the callers, the neighbouring
43337
+ * function, whether this convention is really the convention. */
43338
+ usesTools: true,
43339
+ prompt: [
43340
+ "You are reviewing a change written by another AI assistant.",
43341
+ "",
43342
+ "Your job is to find what is wrong with it. Say so plainly when something is fine, but do",
43343
+ "not pad the review with praise \u2014 an approving review that missed a bug is worse than no",
43344
+ "review, because it was believed.",
43345
+ "",
43346
+ "Look for, in this order: does it do what was asked; does it break something that used to",
43347
+ "work; what happens at the edges \u2014 empty, missing, concurrent, already-exists, fails halfway;",
43348
+ "and does it match the conventions of the code around it.",
43349
+ "",
43350
+ "For each finding say what breaks and under what input. A concern you cannot make concrete is",
43351
+ "worth one sentence, flagged as a hunch, not a paragraph.",
43352
+ "",
43353
+ // Findings go back to whoever wrote the code, which may disagree. Concrete ones can be
43354
+ // settled against the file; vague ones turn into an argument nobody can end.
43355
+ "Your findings may be put to the person who wrote the code, who can disagree with them. That",
43356
+ "is why each one needs an input and an outcome: a finding stated concretely can be checked",
43357
+ "against the real file and settled, and one stated as a preference cannot."
43358
+ ].join("\n")
43359
+ },
43360
+ tester: {
43361
+ name: "Tester",
43362
+ summary: "Designs cases and finds what breaks it",
43363
+ /* The change is in front of it and the cases come from reasoning about it, not from
43364
+ * reading more of the codebase. */
43365
+ usesTools: false,
43366
+ prompt: [
43367
+ "You design tests for code written by another AI assistant.",
43368
+ "",
43369
+ "Given a change, say what should be tested and why each case earns its place. Prefer the",
43370
+ "cases that would actually fail: boundaries, empty and missing values, the error path, the",
43371
+ "second call, the concurrent one, the one that fails halfway and has to be recovered from.",
43372
+ "",
43373
+ "A test that cannot fail is worth nothing \u2014 for each case you propose, say what bug it would",
43374
+ "catch. If the change is untestable as written, say what would have to change to make it",
43375
+ "testable rather than proposing a test that only asserts the code was executed."
43376
+ ].join("\n")
43377
+ },
43378
+ librarian: {
43379
+ name: "Librarian",
43380
+ summary: "Skills, internal documentation and house conventions",
43381
+ /* Its whole job is what has been written down here, so being unable to go and read it
43382
+ * left it answering from whatever happened to be pasted in. This is the role the flag
43383
+ * exists for. */
43384
+ usesTools: true,
43385
+ prompt: [
43386
+ "You answer questions about how things are done here: internal libraries, house conventions,",
43387
+ "the shape of existing code, and what has already been written down.",
43388
+ "",
43389
+ "You are given whatever documentation, skills and code the assistant could find. Answer from",
43390
+ "that, and be explicit about the difference between what the material actually says and what",
43391
+ "you are inferring \u2014 a convention you guessed at, stated confidently, becomes the convention.",
43392
+ "",
43393
+ "If the material does not answer the question, say so and say what would. Do not fill the gap",
43394
+ "with how it is usually done elsewhere unless you label it as exactly that."
43395
+ ].join("\n")
43396
+ }
43397
+ };
43398
+ function roleInfo(role, custom2 = []) {
43399
+ const builtIn = DEFINITIONS[role];
43400
+ if (builtIn !== void 0)
43401
+ return { role, ...builtIn };
43402
+ const defined = custom2.find((candidate) => candidate.id === role);
43403
+ if (defined !== void 0) {
43404
+ return {
43405
+ role,
43406
+ name: defined.name,
43407
+ summary: defined.summary,
43408
+ prompt: defined.prompt.trim(),
43409
+ /*
43410
+ * Custom roles get tools by default.
43411
+ *
43412
+ * They are overwhelmingly reviewers of some particular kind — security, performance,
43413
+ * accessibility — and those all turn on code the asker did not think to paste. The flag is
43414
+ * there to turn it off for the ones that are really "write this to spec".
43415
+ */
43416
+ usesTools: defined.usesTools !== false
43417
+ };
43418
+ }
43419
+ return {
43420
+ role,
43421
+ name: role,
43422
+ summary: "This role is no longer defined.",
43423
+ prompt: "",
43424
+ usesTools: false
43425
+ };
43426
+ }
43427
+ function allRoles(custom2 = []) {
43428
+ return knownRoles(custom2).map((role) => roleInfo(role, custom2));
43429
+ }
43430
+ function defaultPromptFor(role, custom2 = []) {
43431
+ return roleInfo(role, custom2).prompt;
43432
+ }
43433
+ function buildAgentPrompt(options) {
43434
+ const lines = [options.prompt.trim(), "", specialistPreamble(options.usesTools)];
43435
+ if (options.briefing !== void 0 && options.briefing.trim().length > 0) {
43436
+ lines.push("", options.briefing);
43437
+ }
43438
+ lines.push("", "---", "", options.question);
43439
+ if (options.files !== void 0 && options.files.length > 0) {
43440
+ 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}`));
43441
+ }
43442
+ return lines.join("\n");
43443
+ }
43444
+
43445
+ // ../../packages/core/dist/agent/checkpoints.js
43446
+ var MAX_CHECKPOINTS = 50;
43447
+ var LIST_ITEM = /^(\s*)(?:([-*•])|(\d+)[.)])\s+(.+)$/;
43448
+ function idFor(text) {
43449
+ let hash2 = 2166136261;
43450
+ for (let index = 0; index < text.length; index += 1) {
43451
+ hash2 ^= text.charCodeAt(index);
43452
+ hash2 = Math.imul(hash2, 16777619) >>> 0;
43453
+ }
43454
+ return hash2.toString(36);
43455
+ }
43456
+ function normalise(text) {
43457
+ return text.trim().toLowerCase().replace(/\s+/g, " ").replace(/[.;,:]+$/, "");
43458
+ }
43459
+ function parseCheckpoints(plan) {
43460
+ const lines = (plan ?? "").split(/\r?\n/);
43461
+ const items = [];
43462
+ lines.forEach((line, index) => {
43463
+ const match = LIST_ITEM.exec(line);
43464
+ if (match === null)
43465
+ return;
43466
+ const text = match[4]?.trim() ?? "";
43467
+ if (text.length === 0)
43468
+ return;
43469
+ items.push({
43470
+ indent: (match[1] ?? "").replace(/\t/g, " ").length,
43471
+ ordered: match[3] !== void 0,
43472
+ text,
43473
+ line: index
43474
+ });
43475
+ });
43476
+ const ordered = items.filter((item) => item.ordered);
43477
+ const candidates = ordered.length > 0 ? ordered : items;
43478
+ const shallowest = candidates.reduce((least, item) => Math.min(least, item.indent), Number.POSITIVE_INFINITY);
43479
+ const steps = candidates.filter((item) => item.indent === shallowest);
43480
+ const texts = steps.length > 0 ? steps : (
43481
+ // No list at all: plenty of people write a plan as bare lines, and a progress view that
43482
+ // only worked for bullet-point authors would read as broken.
43483
+ lines.map((line, index) => ({ indent: 0, ordered: false, text: line.trim(), line: index })).filter((item) => item.text.length > 0)
43484
+ );
43485
+ const chosen = texts.slice(0, MAX_CHECKPOINTS);
43486
+ const seen = /* @__PURE__ */ new Map();
43487
+ return chosen.map((item, position) => {
43488
+ const key = normalise(item.text);
43489
+ const occurrence = (seen.get(key) ?? 0) + 1;
43490
+ seen.set(key, occurrence);
43491
+ const until = chosen[position + 1]?.line ?? lines.length;
43492
+ return {
43493
+ id: occurrence === 1 ? idFor(key) : `${idFor(key)}-${String(occurrence)}`,
43494
+ index: position + 1,
43495
+ text: item.text,
43496
+ /*
43497
+ * Who the plan says should be involved, read from the step *and everything under it* —
43498
+ * which is where the allocation actually lives, since a specialist is usually named on a
43499
+ * continuation line ("Owner: reviewer") or inside a sub-point rather than in the heading.
43500
+ */
43501
+ plannedRoles: rolesMentionedIn(lines.slice(item.line, until).join(" "))
43502
+ };
43503
+ });
43504
+ }
43505
+ function rolesMentionedIn(text) {
43506
+ const haystack = text.toLowerCase();
43507
+ return AGENT_ROLES.filter((role) => new RegExp(`\\b${role}\\b`).test(haystack));
43508
+ }
43509
+ function checkpointViews(plan, progress) {
43510
+ return parseCheckpoints(plan).map((checkpoint) => {
43511
+ const recorded = progress?.[checkpoint.id];
43512
+ return {
43513
+ ...checkpoint,
43514
+ status: recorded?.status ?? "todo",
43515
+ roles: recorded?.roles ?? []
43516
+ };
43517
+ });
43518
+ }
43519
+ function pruneProgress(plan, progress) {
43520
+ if (progress === void 0)
43521
+ return {};
43522
+ const live = new Set(parseCheckpoints(plan).map((checkpoint) => checkpoint.id));
43523
+ const kept = {};
43524
+ for (const [id, entry] of Object.entries(progress))
43525
+ if (live.has(id))
43526
+ kept[id] = entry;
43527
+ return kept;
43528
+ }
43529
+ function markCheckpoint(plan, progress, index, status) {
43530
+ const checkpoint = parseCheckpoints(plan).find((candidate) => candidate.index === index);
43531
+ if (checkpoint === void 0)
43532
+ return void 0;
43533
+ const existing = progress[checkpoint.id];
43534
+ return {
43535
+ ...progress,
43536
+ [checkpoint.id]: {
43537
+ status,
43538
+ // Kept across a start→done transition: the specialists consulted while the step was being
43539
+ // worked are exactly the ones that contributed to finishing it.
43540
+ roles: existing?.roles ?? [],
43541
+ at: Date.now()
43542
+ }
43543
+ };
43544
+ }
43545
+ function attributeConsultation(progress, role) {
43546
+ const entry = Object.entries(progress).find(([, value2]) => value2.status === "active");
43547
+ if (entry === void 0)
43548
+ return progress;
43549
+ const [id, value] = entry;
43550
+ if (value.roles.includes(role))
43551
+ return progress;
43552
+ return { ...progress, [id]: { ...value, roles: [...value.roles, role] } };
43553
+ }
43554
+ function progressSummary(views) {
43555
+ const done = views.filter((view) => view.status === "done").length;
43556
+ return `${String(done)}/${String(views.length)}`;
43557
+ }
43558
+
43559
+ // ../../packages/core/dist/agent/plan.js
43560
+ var PLAN_LIMIT = 4e3;
43561
+ function buildPlanGuidance(plan) {
43562
+ const trimmed = plan?.trim() ?? "";
43563
+ if (trimmed.length === 0)
43564
+ return "";
43565
+ const checkpoints = parseCheckpoints(trimmed);
43566
+ const numbered = checkpoints.length > 0 ? [
43567
+ "",
43568
+ "Its steps are numbered as follows. These numbers are what `plan_progress` takes, and",
43569
+ "they are what the user sees:",
43570
+ "",
43571
+ ...checkpoints.map((checkpoint) => `${String(checkpoint.index)}. ${checkpoint.text}`)
43572
+ ] : [];
43573
+ return [
43574
+ "# The plan for this conversation",
43575
+ "",
43576
+ "The user set this. It is what you are here to do:",
43577
+ "",
43578
+ trimmed,
43579
+ ...numbered,
43580
+ "",
43581
+ "## Reporting where you are",
43582
+ "",
43583
+ "- **Call `plan_progress` with `active` when you start a step**, and with `done` when it is",
43584
+ " actually finished. The user watches this rather than reading the whole transcript, so a",
43585
+ " step marked done that is not done is worse than one never marked at all.",
43586
+ "- Work one step at a time. Marking three done at the end tells the user nothing while it",
43587
+ " matters, which is the only time it is useful.",
43588
+ "",
43589
+ "## Changing the plan",
43590
+ "",
43591
+ "- **You may propose a different plan with `update_plan`, and the user must approve it.**",
43592
+ " They are shown a diff of the plan they have against the one you are proposing. This is",
43593
+ " the only way the plan changes on your side \u2014 never act on a plan the user has not agreed.",
43594
+ "- Use it when you have worked out a better plan, including one a specialist drafted for you.",
43595
+ " Put the whole plan in it: it replaces what is there rather than adding to it.",
43596
+ "- If they decline, the existing plan still stands and you carry on with it.",
43597
+ "",
43598
+ "## Working to it",
43599
+ "",
43600
+ "- **Before each step, check it serves the plan.** If it does not, do not take it.",
43601
+ "- **Work the plan in order** where it has an order, and say which part you are on when you",
43602
+ " start something substantial. A reader should never have to guess where you are.",
43603
+ "- **Noticing something else is useful; acting on it is not.** If you spot an unrelated bug,",
43604
+ " a refactor worth doing, or a file that could be tidied, *say so and carry on with the*",
43605
+ " *plan*. Do not fix it because you are there. The user will ask if they want it.",
43606
+ "- **If the plan turns out to be wrong**, say so and stop rather than quietly substituting a",
43607
+ " better one. A plan the user set and a plan you preferred are different things, and only",
43608
+ " one of them was agreed.",
43609
+ "- **If something the plan needs is missing or blocked**, say which part and why, finish what",
43610
+ " can be finished, and report what you left.",
43611
+ "",
43612
+ "When you finish, `attempt_completion` must account for the plan: what is done, what is not,",
43613
+ "and anything you did that the plan did not ask for."
43614
+ ].join("\n");
43615
+ }
43616
+
43197
43617
  // ../../packages/core/dist/agent/systemPrompt.js
43198
43618
  function buildSystemPrompt(workspaceRoot, options = {}) {
43199
43619
  const lines = [
@@ -43274,6 +43694,9 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
43274
43694
  if (options.modeGuidance !== void 0 && options.modeGuidance.length > 0) {
43275
43695
  lines.push("", options.modeGuidance);
43276
43696
  }
43697
+ const plan = buildPlanGuidance(options.plan);
43698
+ if (plan.length > 0)
43699
+ lines.push("", plan);
43277
43700
  return lines.join("\n");
43278
43701
  }
43279
43702
 
@@ -43534,7 +43957,21 @@ function createAskExpertTool(options) {
43534
43957
  return {
43535
43958
  name: "ask_expert",
43536
43959
  group: "read",
43537
- 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.",
43960
+ /*
43961
+ * The rationing is said only where somebody is counting.
43962
+ *
43963
+ * "Each call costs money, use it for genuinely difficult questions only" was unconditional,
43964
+ * and it is *advice about money* — so on a deployment where nobody is metering it, it buys
43965
+ * nothing and costs something real: a model told to hoard consultations asks fewer questions
43966
+ * than it should, which is the failure this whole feature exists to avoid. It was the right
43967
+ * default when every consultation was a metered cold start on a CLI, and it stopped being
43968
+ * right when the expert became a seat any model can sit in.
43969
+ *
43970
+ * Varying the description with a *setting* is the carve-out §12 already makes: the block stays
43971
+ * byte-stable for a whole session and changes only when the user changes their mind in
43972
+ * Settings, exactly as switching the dispatcher does.
43973
+ */
43974
+ 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.",
43538
43975
  parametersSchema: paramsSchema2,
43539
43976
  async preview(params) {
43540
43977
  return {
@@ -43551,7 +43988,10 @@ Suggested files: ${params.files.join(", ")}` : ""}`
43551
43988
  async execute(params, context) {
43552
43989
  const verdict = options.budget?.();
43553
43990
  if (verdict !== void 0 && !verdict.allowed) {
43554
- return { content: verdict.message ?? "The expert budget for this task is exhausted.", isError: true };
43991
+ return {
43992
+ content: verdict.message ?? "The expert budget for this task is exhausted.",
43993
+ isError: true
43994
+ };
43555
43995
  }
43556
43996
  const question = params.files !== void 0 && params.files.length > 0 ? `${params.question}
43557
43997
 
@@ -43613,46 +44053,66 @@ ${withBudget}` : withBudget;
43613
44053
  };
43614
44054
  }
43615
44055
 
43616
- // ../../packages/core/dist/tools/askProviderExpert.js
44056
+ // ../../packages/core/dist/tools/askAgent.js
43617
44057
  var paramsSchema3 = external_exports.object({
43618
- 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."),
43619
- 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.")
44058
+ role: external_exports.string().describe(`Which specialist to ask: ${AGENT_ROLES.join(", ")}. Only the ones assigned in Settings \u2192 Agents can answer.`),
44059
+ 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."),
44060
+ files: external_exports.array(external_exports.string()).optional().describe("Workspace-relative paths you are working in, so it knows what you are looking at.")
43620
44061
  });
43621
- function createAskProviderExpertTool(options) {
44062
+ function createAskAgentTool(options) {
43622
44063
  return {
43623
- name: "ask_expert",
44064
+ name: "ask_agent",
43624
44065
  group: "read",
43625
- 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.",
44066
+ 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.",
43626
44067
  parametersSchema: paramsSchema3,
43627
44068
  async preview(params) {
44069
+ const agent = find(options.agents(), params.role);
43628
44070
  return {
43629
44071
  kind: "text",
43630
- // Ground truth (invariant 8): the question that will actually be sent, in full. This
44072
+ // Ground truth (invariant 8): the question that will be sent, in full, and who to. This
43631
44073
  // puts the user's code in front of another model, which is the decision being approved.
43632
- text: `Consult the expert (${options.label}):
44074
+ text: `Ask the ${params.role}${agent === void 0 ? "" : ` (${agent.label})`}:
43633
44075
 
43634
- ${params.question}${params.files !== void 0 && params.files.length > 0 ? `
44076
+ ${params.question}` + (params.files !== void 0 && params.files.length > 0 ? `
43635
44077
 
43636
- Files named as relevant: ${params.files.join(", ")}` : ""}`
44078
+ Files named as relevant: ${params.files.join(", ")}` : "")
43637
44079
  };
43638
44080
  },
43639
44081
  async execute(params, context) {
44082
+ const team = options.agents();
44083
+ const role = params.role.trim().toLowerCase();
44084
+ if (!isAgentRole(role)) {
44085
+ return { content: unknownRole(role, team), isError: true };
44086
+ }
44087
+ const agent = find(team, role);
44088
+ if (agent === void 0) {
44089
+ return {
44090
+ content: `No ${role} is assigned. ${describeTeam(team)} Assign one in Settings \u2192 Agents, or ask a different role.`,
44091
+ isError: true
44092
+ };
44093
+ }
44094
+ if (!agent.available) {
44095
+ return {
44096
+ content: `The ${role} cannot be reached: ${agent.reason ?? "it is unavailable."}`,
44097
+ isError: true
44098
+ };
44099
+ }
43640
44100
  let result;
43641
44101
  try {
43642
- result = await options.consult({
44102
+ result = await options.consult(agent, {
43643
44103
  question: params.question,
43644
44104
  ...params.files !== void 0 ? { files: params.files } : {},
43645
44105
  ...context.signal !== void 0 ? { signal: context.signal } : {}
43646
44106
  });
43647
44107
  } catch (error51) {
43648
44108
  return {
43649
- content: `The expert could not be reached: ${error51 instanceof Error ? error51.message : String(error51)}`,
44109
+ content: `The ${role} could not be reached: ${error51 instanceof Error ? error51.message : String(error51)}`,
43650
44110
  isError: true
43651
44111
  };
43652
44112
  }
43653
44113
  if (result.advice.trim().length === 0) {
43654
44114
  return {
43655
- 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.",
44115
+ content: `The ${role} returned nothing. Check what is assigned to it in Settings \u2192 Agents.`,
43656
44116
  isError: true
43657
44117
  };
43658
44118
  }
@@ -43662,39 +44122,494 @@ Files named as relevant: ${params.files.join(", ")}` : ""}`
43662
44122
 
43663
44123
  ---
43664
44124
 
43665
- 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.`
44125
+ ${trailerFor(agent, team)}`
43666
44126
  };
43667
44127
  }
43668
44128
  };
43669
44129
  }
43670
-
43671
- // ../../packages/core/dist/expert/providerExpert.js
43672
- function buildExpertPrompt(request) {
44130
+ function find(team, role) {
44131
+ const wanted = role.trim().toLowerCase();
44132
+ return team.find((agent) => agent.role === wanted);
44133
+ }
44134
+ function unknownRole(role, team) {
44135
+ return `There is no "${role}" role. The roles are: ${AGENT_ROLES.join(", ")}. ${describeTeam(team)}`;
44136
+ }
44137
+ function describeTeam(team) {
44138
+ const usable = team.filter((agent) => agent.available).map((agent) => agent.role);
44139
+ return usable.length === 0 ? "None are assigned on this machine." : `Assigned here: ${usable.join(", ")}.`;
44140
+ }
44141
+ function trailerFor(agent, team) {
43673
44142
  const lines = [
43674
- "You are a senior engineer being consulted by another AI assistant that is doing the work.",
44143
+ `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."
44144
+ ];
44145
+ const programmer = team.find((candidate) => candidate.role === "programmer" && candidate.available);
44146
+ if (agent.role === "reviewer" && programmer !== void 0) {
44147
+ 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.");
44148
+ }
44149
+ if (agent.role === "programmer") {
44150
+ 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.");
44151
+ }
44152
+ return lines.join("\n");
44153
+ }
44154
+
44155
+ // ../../packages/core/dist/agents/team.js
44156
+ function defaultAssignment(role, context) {
44157
+ return role === "expert" && context.cliAvailable ? { kind: "cli" } : void 0;
44158
+ }
44159
+ function resolveTeam(context) {
44160
+ const resolved = [];
44161
+ const custom2 = context.config?.definitions ?? [];
44162
+ for (const role of knownRoles(custom2)) {
44163
+ const assignment = context.config?.roles?.[role] ?? defaultAssignment(role, context);
44164
+ if (assignment === void 0)
44165
+ continue;
44166
+ const info = roleInfo(role, custom2);
44167
+ const prompt = assignment.prompt ?? defaultPromptFor(role, custom2);
44168
+ const usesTools = assignment.tools ?? info.usesTools;
44169
+ if (assignment.kind === "cli") {
44170
+ resolved.push({
44171
+ role,
44172
+ name: info.name,
44173
+ summary: info.summary,
44174
+ kind: "cli",
44175
+ label: "Claude",
44176
+ prompt,
44177
+ usesTools,
44178
+ available: context.cliAvailable,
44179
+ ...context.cliAvailable ? {} : { reason: "The Claude CLI is not available on this machine." }
44180
+ });
44181
+ continue;
44182
+ }
44183
+ const profile = context.profiles.find((candidate) => candidate.id === assignment.profileId);
44184
+ resolved.push({
44185
+ role,
44186
+ name: info.name,
44187
+ summary: info.summary,
44188
+ kind: "profile",
44189
+ ...assignment.profileId !== void 0 ? { profileId: assignment.profileId } : {},
44190
+ label: profile?.label ?? assignment.profileId ?? "unassigned",
44191
+ prompt,
44192
+ usesTools,
44193
+ available: profile !== void 0,
44194
+ /*
44195
+ * A profile that has been deleted leaves the role unavailable and says so, rather than
44196
+ * falling back to the model already doing the work. A specialist that is quietly the
44197
+ * primary model gives advice with nothing to distrust about it, which is worse than none.
44198
+ */
44199
+ ...profile === void 0 ? { reason: `No profile "${assignment.profileId ?? ""}" exists any more.` } : {}
44200
+ });
44201
+ }
44202
+ return resolved;
44203
+ }
44204
+ function budgetMatters(context) {
44205
+ const stated = context.config?.budgetMatters;
44206
+ if (stated !== void 0)
44207
+ return stated;
44208
+ return resolveTeam(context).some((agent) => agent.kind === "cli" && agent.available);
44209
+ }
44210
+
44211
+ // ../../packages/core/dist/agents/guidance.js
44212
+ var BUDGET_ADVICE = [
44213
+ "",
44214
+ "## Consultations cost money here",
44215
+ "",
44216
+ "Each one is charged. Make the first count \u2014 gather what is needed and ask one full question",
44217
+ "rather than opening with something you could have settled yourself. If a per-task budget runs",
44218
+ "out the specialist stops being available, and you finish the work alone, so spend it on the",
44219
+ "parts where another reader genuinely changes what you do."
44220
+ ].join("\n");
44221
+ var PLAN_FIRST = [
44222
+ "",
44223
+ "## Start by planning. This comes before everything else.",
44224
+ "",
44225
+ "**This conversation has no plan yet, so making one is your first job.** Before reading widely,",
44226
+ "before editing anything, before running anything:",
44227
+ "",
44228
+ "1. **Look at almost nothing first.** One `list_files` of the workspace root is usually the",
44229
+ " whole of it, plus any file the user actually named. That is enough to ask a good question.",
44230
+ " Do **not** survey the codebase, search the documentation index, hunt for skills, or read",
44231
+ " files to get a feel for the style \u2014 not yet. The specialist cannot see any of it anyway,",
44232
+ " and if it needs something specific it will say so and you can fetch it and ask again.",
44233
+ ' Announcing that you are "getting a sense of the workspace before proposing anything" is',
44234
+ " this instruction being broken, however reasonable it sounds.",
44235
+ "2. **Ask the expert for the plan** \u2014 give the task, the little you found and the constraints,",
44236
+ " and ask for numbered steps. A plan is the one thing worth asking for before the work rather",
44237
+ " than after it, and it is what the expert is for. An expert asked early enough to change the",
44238
+ " shape of the work is worth several times one asked to bless a direction already taken.",
44239
+ " **Ask it to say which specialist should be involved in which step**, from the team it is",
44240
+ " given. It knows who is available; it will not volunteer the allocation unless asked.",
44241
+ "3. **Propose it with `update_plan`.** The user sees a diff and approves it. Do not skip this:",
44242
+ " a plan held only in the conversation is forgotten as the chat grows, and it is not",
44243
+ " something the user has agreed to.",
44244
+ "4. Only once it is approved, start the work, reporting each step with `plan_progress`.",
44245
+ "",
44246
+ "If the user declines, ask what they want changed and propose a revised plan. If no expert is",
44247
+ "assigned, draft it yourself and propose it the same way \u2014 and say that is what you did, so",
44248
+ "nobody believes it was reviewed by somebody else.",
44249
+ "",
44250
+ "The exception is a question rather than a job. If the user asked something you can simply",
44251
+ "answer, answer it \u2014 do not plan a conversation."
44252
+ ].join("\n");
44253
+ var PLAN_IN_PLACE = [
44254
+ "",
44255
+ "## This conversation already has a plan",
44256
+ "",
44257
+ "It is above, with its steps numbered. Work it, report each step with `plan_progress`, and if it",
44258
+ "turns out to be wrong, consult the expert and propose a replacement with `update_plan` rather",
44259
+ "than quietly working to a different one."
44260
+ ].join("\n");
44261
+ var DEFAULT_TEAM_GUIDANCE = [
44262
+ "You lead a small team. You do the work \u2014 reading, searching, editing, running things \u2014 and you",
44263
+ "consult specialists when another reader would genuinely change what you do.",
44264
+ "",
44265
+ "## Consult without being asked",
44266
+ "",
44267
+ "You do not need permission and you should not wait to be told. Ask when:",
44268
+ "",
44269
+ "- the task spans several files and you are not sure of the shape \u2014 ask the **expert** first,",
44270
+ " before you write anything;",
44271
+ "- you have finished a change of any substance \u2014 ask the **reviewer**, and say what you changed",
44272
+ " and why, not just what the diff looks like;",
44273
+ "- you are about to call something done that has no tests \u2014 ask the **tester** what would break",
44274
+ " it;",
44275
+ "- you are guessing at how this codebase does something \u2014 ask the **librarian** rather than",
44276
+ " inventing a convention;",
44277
+ /*
44278
+ * The programmer was missing from this list entirely, which is most of why it never got used.
44279
+ *
44280
+ * Every other bullet describes somebody *reading* what you have, and writing code is the one
44281
+ * thing the assistant can already do — so with no bullet of its own the role simply never came
44282
+ * up, and a plan drafted by the expert never allocated it either (the same omission, in the
44283
+ * briefing). Bounded deliberately: "hand everything to the programmer" would add a round trip
44284
+ * to every edit and put a second model's conventions into the file.
44285
+ */
44286
+ "- a step is a self-contained piece of code with a clear spec \u2014 a parser, a schema, a set of",
44287
+ " pure functions \u2014 hand it to the **programmer** rather than writing it yourself out of habit,",
44288
+ " then check what comes back against the real file before applying it. Not for a two-line",
44289
+ " change, and not where the spec is still moving.",
44290
+ "",
44291
+ 'The user can also ask directly ("ask the reviewer to look at this"), and then you consult that',
44292
+ "role whatever you would have chosen.",
44293
+ "",
44294
+ "## What makes a consultation worth it",
44295
+ "",
44296
+ /*
44297
+ * The last place still saying every specialist is blind.
44298
+ *
44299
+ * Some can read and search for themselves; the roster above marks which. But the advice does
44300
+ * not change much, because even one that can look things up starts from what you gave it — and
44301
+ * a question with nothing attached spends its whole lookup budget finding the file you already
44302
+ * had open.
44303
+ */
44304
+ "**Paste the code**, the error, the failing output \u2014 the actual text. Some of them can read the",
44305
+ "workspace and some cannot, and the roster says which; but even the ones that can start from",
44306
+ "what you give them, and a question with nothing attached spends their whole lookup budget",
44307
+ 'finding what you already had open. A question like "is my retry logic right?" with nothing',
44308
+ "attached comes back as a list of things retry logic usually gets wrong, which you already knew.",
44309
+ "",
44310
+ "Ask one full question rather than three thin ones. Each consultation is a fresh reader with no",
44311
+ "memory of the last, so a follow-up has to carry its own context.",
44312
+ "",
44313
+ "## What not to do",
44314
+ "",
44315
+ "- Do not consult on something you can settle by reading a file. Read it.",
44316
+ "- Do not relay advice you have not checked. You have the code open and the specialist does not;",
44317
+ " if it is wrong, say so and say why \u2014 to the user, and in your next question.",
44318
+ "- Do not consult the same role twice with the same question hoping for a better answer.",
44319
+ "",
44320
+ "## When a review finds something in code the programmer wrote",
44321
+ "",
44322
+ "**Take it back to the programmer.** It wrote the code, it is the role picked for writing, and",
44323
+ "the fix is its job rather than yours \u2014 you are the one holding the files, not the one whose",
44324
+ "judgement was hired for this. Fixing it silently yourself wastes the specialist and hides the",
44325
+ "exchange from the user.",
44326
+ "",
44327
+ "A consultation remembers nothing, so the question has to carry everything: **the code as it",
44328
+ "stands, the finding in the reviewer's own words, and what you have checked yourself.** A",
44329
+ 'programmer told only "the reviewer says this is wrong" will guess at which line and rewrite',
44330
+ "more than it should.",
44331
+ "",
44332
+ "**It may push back, and that is a real answer, not an obstacle.** Reviews are wrong often",
44333
+ "enough to matter \u2014 a finding can be about a path that cannot happen, a convention this",
44334
+ "codebase deliberately does not follow, or a misreading of code the reviewer only saw a fragment",
44335
+ "of. When the programmer disagrees, you settle it: you have the actual file and neither of them",
44336
+ "does. Say which way you went and why, in your reply, so the user sees the disagreement rather",
44337
+ "than only its outcome.",
44338
+ "",
44339
+ "**One lap, not a loop.** Review, fix, and re-review only when the fix was substantial enough",
44340
+ "that the first review no longer describes the code. If the two still disagree after that, stop",
44341
+ "and put it to the expert with both positions, or decide it yourself and say so. Ping-ponging a",
44342
+ "disagreement between two models that cannot see the file is how a turn is spent without",
44343
+ "anything being decided.",
44344
+ "",
44345
+ "## When the plan names a specialist",
44346
+ "",
44347
+ "Consult them **while that step is the active one**, not at the end in a batch. Two reasons, and",
44348
+ "the second is the one people notice: advice arriving after the work is done is a review nobody",
44349
+ "can act on without redoing it, and the progress panel attributes a consultation to whichever",
44350
+ "step was open when it happened \u2014 so a step worked in silence shows as nobody having helped with",
44351
+ "it, whatever you say afterwards.",
44352
+ "",
44353
+ "If a step names somebody and you decide against consulting them, say so and say why. A plan the",
44354
+ "user approved said that step would get another reader."
44355
+ ].join("\n");
44356
+ function buildTeamGuidance(agents, custom2, budgetMatters2, hasPlan) {
44357
+ const base = custom2 !== void 0 && custom2.trim().length > 0 ? custom2 : DEFAULT_TEAM_GUIDANCE;
44358
+ const advice = budgetMatters2 === true ? `${base}
44359
+ ${BUDGET_ADVICE}` : base;
44360
+ const planning = hasPlan === true ? PLAN_IN_PLACE : PLAN_FIRST;
44361
+ const usable = agents.filter((agent) => agent.available);
44362
+ const unusable = AGENT_ROLES.filter((role) => !usable.some((agent) => agent.role === role)).map((role) => {
44363
+ const assigned = agents.find((agent) => agent.role === role);
44364
+ return assigned === void 0 ? `- **${role}** \u2014 nobody assigned.` : `- **${role}** \u2014 ${assigned.reason ?? "assigned, but cannot be reached."}`;
44365
+ });
44366
+ const missing = unusable.length === 0 ? [] : [
43675
44367
  "",
43676
- "It has hit something hard: a multi-file change to plan, a bug it has already failed to fix,",
43677
- "or a design choice to make. Give it your judgement.",
44368
+ "**Not available, so do not ask for them and do not plan work for them:**",
43678
44369
  "",
43679
- "Two things about your position here:",
44370
+ ...unusable,
43680
44371
  "",
43681
- "- You cannot see the workspace and cannot read files, run commands or search. Everything you",
43682
- " have is below. If something essential is missing, say exactly what you need and why, then",
43683
- " give the best answer you can without it \u2014 do not refuse to answer.",
43684
- "- Your reply is advice. The assistant will check it against the real code before acting, and",
43685
- " it is responsible for the result. Be concrete, say what you are unsure about, and say when",
43686
- " a thing must be verified rather than assumed.",
44372
+ "If something genuinely needs one of these, say so and say that assigning it in",
44373
+ "Settings \u2192 Agents would let you consult it \u2014 then carry on without it rather than",
44374
+ "leaving that part of the job unaccounted for."
44375
+ ];
44376
+ if (usable.length === 0) {
44377
+ return [
44378
+ advice,
44379
+ planning,
44380
+ "",
44381
+ "## Your team",
44382
+ "",
44383
+ "**Nobody is assigned yet.** Until somebody is, do the work yourself and tell the user that",
44384
+ "assigning a specialist in Settings \u2192 Agents would let you consult one.",
44385
+ ...missing
44386
+ ].join("\n");
44387
+ }
44388
+ return [
44389
+ advice,
44390
+ planning,
43687
44391
  "",
43688
- "Answer in prose and short lists. No preamble about being happy to help.",
44392
+ "## Your team",
43689
44393
  "",
43690
- "---",
44394
+ "Reach any of them with `ask_agent`, naming the role. These are the only ones that exist:",
43691
44395
  "",
43692
- request.question
43693
- ];
43694
- if (request.files !== void 0 && request.files.length > 0) {
43695
- 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}`));
44396
+ ...usable.map((agent) => `- **${agent.role}** (${agent.label}) \u2014 ${agent.summary}`),
44397
+ ...missing
44398
+ ].join("\n");
44399
+ }
44400
+
44401
+ // ../../packages/core/dist/agents/briefing.js
44402
+ var DESCRIPTION_LIMIT = 110;
44403
+ function firstLine(text, limit = DESCRIPTION_LIMIT) {
44404
+ const line = text.split("\n").find((candidate) => candidate.trim().length > 0)?.trim() ?? "";
44405
+ return line.length > limit ? `${line.slice(0, limit - 1).trimEnd()}\u2026` : line;
44406
+ }
44407
+ function buildRoster(team, self) {
44408
+ const others = team.filter((agent) => agent.role !== self);
44409
+ const usable = others.filter((agent) => agent.available);
44410
+ const assigned = new Set(team.map((agent) => agent.role));
44411
+ const missing = [];
44412
+ for (const role of AGENT_ROLES) {
44413
+ if (role === self)
44414
+ continue;
44415
+ if (!assigned.has(role)) {
44416
+ missing.push(`- **${role}** \u2014 nobody is assigned to this role.`);
44417
+ continue;
44418
+ }
44419
+ const agent = others.find((candidate) => candidate.role === role);
44420
+ if (agent !== void 0 && !agent.available) {
44421
+ missing.push(`- **${role}** \u2014 ${agent.reason ?? "assigned, but cannot be reached."}`);
44422
+ }
44423
+ }
44424
+ const sections = ["## The rest of the team", ""];
44425
+ if (self !== void 0)
44426
+ sections.push(`You are the **${self}**.`, "");
44427
+ 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.");
44428
+ if (usable.length > 0) {
44429
+ sections.push(
44430
+ "",
44431
+ /*
44432
+ * What the others can actually do — and this was wrong once, in the expensive direction.
44433
+ *
44434
+ * It first said "None of them can see the workspace", written to stop the expert giving the
44435
+ * librarian a lookup job. That was false: `agents/consult.ts` gives a specialist the read
44436
+ * tool group, and the CLI expert holds Claude's own Read/Grep/Glob. The instruction was
44437
+ * therefore telling the expert *not* to allocate the librarian the one kind of work the
44438
+ * librarian is equipped for, which made the weakest role weaker.
44439
+ *
44440
+ * The real distinction is per role and the user controls it, so it is rendered from the
44441
+ * team rather than asserted about all of them — and it sits *above* the list, because it is
44442
+ * how to read the marks in it.
44443
+ */
44444
+ "**None of them can edit anything or run anything.** They read and advise; the assistant",
44445
+ "makes every change, and it is the one answerable for the result. Some can look things up",
44446
+ "for themselves, marked below; the rest know only what is in the question, so give those",
44447
+ "everything they need.",
44448
+ "",
44449
+ ...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
44450
+ // needs pointing at a file, one that cannot needs the file pasted in.
44451
+ (agent.usesTools ? " *(can read and search the workspace)*" : "")),
44452
+ "",
44453
+ /*
44454
+ * Knowing who exists is not the same as being asked to use them.
44455
+ *
44456
+ * Reported with a plan that allocated nobody, on a machine where all four other roles were
44457
+ * assigned. The briefing told the expert who was available and told it not to name anyone
44458
+ * who was not — and it dutifully named nobody at all, writing a plan for the assistant
44459
+ * working alone, down to "I'll show you the code before moving on" where a reviewer was
44460
+ * sitting right there. An instruction that only says what *not* to do gets obeyed by doing
44461
+ * nothing.
44462
+ *
44463
+ * Deliberately not "use every specialist": that is four extra round trips on a task that
44464
+ * may not want any, and a plan routing every step through the whole team is worse than one
44465
+ * routing none — it reads as ceremony and people stop reading it.
44466
+ */
44467
+ "**If you are asked for a plan, say who should be involved in which step.** Name the role in",
44468
+ 'the step itself \u2014 "have the tester say what would break this", "get the reviewer onto the',
44469
+ 'callback wiring", "hand the parser to the programmer" \u2014 so the assistant knows when to',
44470
+ "consult and the user can see who is doing what.",
44471
+ "",
44472
+ /*
44473
+ * Two kinds of specialist, said separately, because the first version only described one.
44474
+ *
44475
+ * It asked for allocation "where another reader would genuinely change the outcome" and
44476
+ * called it "another pair of eyes" — review framing throughout, with a reviewer and a
44477
+ * tester as the examples. The programmer does not read, it produces, so a plan written to
44478
+ * that instruction correctly never mentions it. Reported exactly that way: reviewer and
44479
+ * tester allocated across four steps, programmer nowhere, on a machine where it was
44480
+ * assigned. An instruction that names one mode of use gets obeyed in one mode.
44481
+ */
44482
+ "They divide into two kinds, and both are worth allocating:",
44483
+ "",
44484
+ "- **Readers** \u2014 the reviewer, the tester, the librarian. Worth a step where another pair of",
44485
+ " eyes changes what happens: risky or fiddly code, a step that finishes something, a",
44486
+ " convention you would otherwise be guessing at.",
44487
+ "- **The programmer writes.** Where a step is a self-contained piece of code with a spec",
44488
+ " clear enough to hand over \u2014 a parser, a schema, a set of pure functions \u2014 say so and give",
44489
+ " it to the programmer. The assistant checks what comes back against the real file and",
44490
+ " applies it, so this is delegation rather than trust.",
44491
+ "",
44492
+ "Only where it genuinely changes the outcome: a plan that routes every step through all of",
44493
+ "them is ceremony, and one that routes none wastes a team that is sitting there."
44494
+ );
44495
+ }
44496
+ if (missing.length > 0) {
44497
+ sections.push(
44498
+ "",
44499
+ // "Not set up" would be wrong for a role that *is* assigned and whose profile has since
44500
+ // gone: the user did set it up, and telling them otherwise sends them to fix the wrong
44501
+ // thing. "Not available" is true of both, and the reason beside each says which it is.
44502
+ "**Not available, so the assistant cannot use them:**",
44503
+ "",
44504
+ ...missing,
44505
+ "",
44506
+ "Do not give any of these work. Do not put them in a plan, a checklist or a next step \u2014 a",
44507
+ "plan naming a specialist who does not exist is a plan with a hole in it, and the user will",
44508
+ "have approved it without knowing. If a task genuinely needs one, say so in a sentence and",
44509
+ "say the user would have to assign it in Settings \u2192 Agents; then give the best advice you",
44510
+ "can for doing it without that role."
44511
+ );
44512
+ }
44513
+ return sections;
44514
+ }
44515
+ function buildAgentBriefing(input) {
44516
+ const tools = (input.tools ?? []).filter(
44517
+ // Telling a specialist it can consult a specialist is noise at best and a loop at worst.
44518
+ (tool) => tool.name !== "ask_agent" && tool.name !== "ask_expert"
44519
+ );
44520
+ const skills = input.skills ?? [];
44521
+ const team = input.team;
44522
+ if (tools.length === 0 && skills.length === 0 && team === void 0)
44523
+ return "";
44524
+ const sections = [];
44525
+ if (team !== void 0)
44526
+ sections.push(...buildRoster(team, input.self));
44527
+ if (tools.length > 0 || skills.length > 0) {
44528
+ if (sections.length > 0)
44529
+ sections.push("");
44530
+ 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.");
44531
+ }
44532
+ if (tools.length > 0) {
44533
+ sections.push("", "### Tools it can call", "", ...tools.map((tool) => `- \`${tool.name}\` \u2014 ${firstLine(tool.description)}`));
44534
+ }
44535
+ if (skills.length > 0) {
44536
+ 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)}`));
44537
+ }
44538
+ return sections.join("\n");
44539
+ }
44540
+
44541
+ // ../../packages/core/dist/agents/consult.js
44542
+ var CONSULT_MAX_STEPS = 5;
44543
+ var ALLOWED_GROUPS = /* @__PURE__ */ new Set(["read"]);
44544
+ function toolsForConsultation(all) {
44545
+ return all.filter((tool) => ALLOWED_GROUPS.has(tool.group) && tool.name !== "ask_agent" && tool.name !== "ask_expert");
44546
+ }
44547
+ async function runConsultation(options) {
44548
+ const limit = options.maxSteps ?? CONSULT_MAX_STEPS;
44549
+ const messages = [{ role: "user", content: options.prompt }];
44550
+ const byName = new Map(options.tools.map((tool) => [tool.name, tool]));
44551
+ let steps = 0;
44552
+ for (; ; ) {
44553
+ const atCap = steps >= limit;
44554
+ let text = "";
44555
+ let call;
44556
+ for await (const chunk of options.provider.streamChat(messages, {
44557
+ ...options.signal !== void 0 ? { signal: options.signal } : {},
44558
+ /*
44559
+ * The tools are withdrawn on the final pass, not merely discouraged.
44560
+ *
44561
+ * A model asked politely to stop looking things up will sometimes look one more thing up,
44562
+ * and then there is no turn left to answer in. Removing them makes answering the only
44563
+ * available move.
44564
+ */
44565
+ ...atCap || options.definitions.length === 0 ? {} : { tools: [...options.definitions] }
44566
+ })) {
44567
+ if (chunk.type === "text")
44568
+ text += chunk.text;
44569
+ else if (chunk.type === "toolCall" && call === void 0) {
44570
+ call = {
44571
+ id: chunk.toolCall.id,
44572
+ name: chunk.toolCall.name,
44573
+ arguments: chunk.toolCall.arguments
44574
+ };
44575
+ } else if (chunk.type === "error") {
44576
+ throw new Error(chunk.error);
44577
+ }
44578
+ }
44579
+ if (call === void 0)
44580
+ return { advice: text, steps, truncated: atCap && steps > 0 };
44581
+ messages.push({ role: "assistant", content: text, toolCalls: [call] });
44582
+ options.onStep?.(call.name);
44583
+ steps += 1;
44584
+ const tool = byName.get(call.name);
44585
+ if (tool === void 0) {
44586
+ messages.push({
44587
+ role: "tool",
44588
+ toolCallId: call.id,
44589
+ content: `You have no "${call.name}". You are read-only here: ${[...byName.keys()].join(", ")}. Anything else, recommend and the assistant will do it.`
44590
+ });
44591
+ continue;
44592
+ }
44593
+ try {
44594
+ const parsed = tool.parametersSchema.safeParse(JSON.parse(call.arguments || "{}"));
44595
+ const result = parsed.success ? await tool.execute(parsed.data, options.context) : {
44596
+ content: `Those arguments are not valid: ${parsed.error.issues.map((i) => i.message).join("; ")}`
44597
+ };
44598
+ messages.push({ role: "tool", toolCallId: call.id, content: String(result.content) });
44599
+ } catch (error51) {
44600
+ messages.push({
44601
+ role: "tool",
44602
+ toolCallId: call.id,
44603
+ content: `That failed: ${error51 instanceof Error ? error51.message : String(error51)}`
44604
+ });
44605
+ }
44606
+ if (steps >= limit) {
44607
+ messages.push({
44608
+ role: "user",
44609
+ content: "That is all the looking up you can do. Answer now with what you have, and say plainly what you could not check."
44610
+ });
44611
+ }
43696
44612
  }
43697
- return lines.join("\n");
43698
44613
  }
43699
44614
 
43700
44615
  // ../../packages/core/dist/tools/recallExpert.js
@@ -43823,8 +44738,8 @@ function assessmentForBriefing(assessment) {
43823
44738
  }
43824
44739
 
43825
44740
  // ../../packages/core/dist/expert/briefing.js
43826
- var DESCRIPTION_LIMIT = 110;
43827
- function firstLine(text, limit = DESCRIPTION_LIMIT) {
44741
+ var DESCRIPTION_LIMIT2 = 110;
44742
+ function firstLine2(text, limit = DESCRIPTION_LIMIT2) {
43828
44743
  const line = text.split("\n").find((candidate) => candidate.trim().length > 0)?.trim() ?? "";
43829
44744
  return line.length > limit ? `${line.slice(0, limit - 1).trimEnd()}\u2026` : line;
43830
44745
  }
@@ -43863,7 +44778,7 @@ function buildExpertBriefing(input) {
43863
44778
  const assessed = assessmentForBriefing(input.juniorAssessment);
43864
44779
  if (assessed !== void 0)
43865
44780
  sections.push("", assessed);
43866
- const listed = (tools) => [...tools].sort((a, b) => a.name.localeCompare(b.name)).map((tool) => `- ${tool.name} \u2014 ${firstLine(tool.description)}`);
44781
+ const listed = (tools) => [...tools].sort((a, b) => a.name.localeCompare(b.name)).map((tool) => `- ${tool.name} \u2014 ${firstLine2(tool.description)}`);
43867
44782
  const dispatchOnly = input.dispatchOnlyTools ?? [];
43868
44783
  const everyTool = [...input.promptTools, ...dispatchOnly];
43869
44784
  if (everyTool.length > 0) {
@@ -43880,7 +44795,7 @@ function buildExpertBriefing(input) {
43880
44795
  const skills = input.skills ?? [];
43881
44796
  if (skills.length > 0) {
43882
44797
  sections.push("", `### Project knowledge written down for the junior (${skills.length})`, "");
43883
- sections.push(...skills.map((skill) => `- ${skill.name} \u2014 ${firstLine(skill.description)}`));
44798
+ sections.push(...skills.map((skill) => `- ${skill.name} \u2014 ${firstLine2(skill.description)}`));
43884
44799
  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.");
43885
44800
  }
43886
44801
  return sections.join("\n");
@@ -47658,18 +48573,23 @@ var NEVER_AVAILABLE_TO_SCHEDULES = [
47658
48573
  // section 13 requires approval showing the source, which cannot happen with nobody there.
47659
48574
  "excel_write_macro",
47660
48575
  // And running one: unattended execution of arbitrary VBA, with nobody to read the source.
47661
- "excel_run_macro"
48576
+ "excel_run_macro",
48577
+ /*
48578
+ * Rewriting the plan it is being held to, with nobody there to approve the diff. Same ladder
48579
+ * as `schedule_prompt`: a run that can change its own instructions is bounded by nothing.
48580
+ */
48581
+ "update_plan"
47662
48582
  ];
47663
48583
  function scheduleAppliesHere(schedule, workspaceRoot) {
47664
48584
  if (schedule.workspaceRoot === void 0)
47665
48585
  return true;
47666
48586
  if (workspaceRoot === void 0)
47667
48587
  return false;
47668
- const normalise = (value) => {
48588
+ const normalise2 = (value) => {
47669
48589
  const resolved = nodePath.resolve(value);
47670
48590
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
47671
48591
  };
47672
- return normalise(schedule.workspaceRoot) === normalise(workspaceRoot);
48592
+ return normalise2(schedule.workspaceRoot) === normalise2(workspaceRoot);
47673
48593
  }
47674
48594
  function filterToolsForSchedule(all, schedule) {
47675
48595
  const named = new Set(schedule.allowedTools);
@@ -48873,7 +49793,14 @@ var ALWAYS_ASK_TOOLS = /* @__PURE__ */ new Set([
48873
49793
  * approval showing the actual source is the only thing standing between "run DoTheThing" and
48874
49794
  * whatever DoTheThing does.
48875
49795
  */
48876
- "excel_run_macro"
49796
+ "excel_run_macro",
49797
+ /*
49798
+ * The plan is what holds the assistant to work the user agreed, so a category toggle must
49799
+ * never stand in for reading the change. Auto-approving this would mean an agent could widen
49800
+ * its own instructions and then point at them as authority — and both the panel and the
49801
+ * prompt would look right afterwards, because both would be reading the new plan.
49802
+ */
49803
+ "update_plan"
48877
49804
  ]);
48878
49805
  function decideFromPolicy(request, approvals) {
48879
49806
  if (!requiresApproval(request.group))
@@ -48988,6 +49915,65 @@ var ShadowGit = class {
48988
49915
  }
48989
49916
  };
48990
49917
 
49918
+ // ../../packages/core/dist/tools/planTools.js
49919
+ var updateParams = external_exports.object({
49920
+ 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."),
49921
+ reason: external_exports.string().optional().describe("One line on why the plan should change, shown to the user with the diff.")
49922
+ });
49923
+ function createUpdatePlanTool(access) {
49924
+ return {
49925
+ name: "update_plan",
49926
+ group: "edit",
49927
+ 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.",
49928
+ parametersSchema: updateParams,
49929
+ async preview(params) {
49930
+ const before = access.current() ?? "";
49931
+ return {
49932
+ kind: "diff",
49933
+ // Not a file. The approval UI labels the diff with this, and naming it for what it is
49934
+ // beats a made-up path that implies something on disk is about to change.
49935
+ path: "the plan for this conversation",
49936
+ before,
49937
+ after: params.plan.slice(0, PLAN_LIMIT).trim(),
49938
+ ...params.reason !== void 0 && params.reason.trim().length > 0 ? { note: params.reason.trim() } : {}
49939
+ };
49940
+ },
49941
+ async execute(params) {
49942
+ const next = params.plan.slice(0, PLAN_LIMIT).trim();
49943
+ if (next.length === 0) {
49944
+ return { content: "A plan cannot be empty. To remove the plan, ask the user to clear it." };
49945
+ }
49946
+ await access.save(next);
49947
+ return {
49948
+ 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."
49949
+ };
49950
+ }
49951
+ };
49952
+ }
49953
+ var progressParams = external_exports.object({
49954
+ checkpoint: external_exports.number().int().describe("The step number, as numbered in the plan you were given."),
49955
+ status: external_exports.enum(["active", "done"]).describe("`active` when you start the step, `done` when it is genuinely finished.")
49956
+ });
49957
+ function createPlanProgressTool(access) {
49958
+ return {
49959
+ name: "plan_progress",
49960
+ /*
49961
+ * Control flow, not an action: it records where you are and touches nothing else. Gating it
49962
+ * would mean an approval prompt between every step of every planned task, which nobody would
49963
+ * keep switched on for long.
49964
+ */
49965
+ group: "always",
49966
+ 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.",
49967
+ parametersSchema: progressParams,
49968
+ async execute(params) {
49969
+ const outcome = await access.mark(params.checkpoint, params.status);
49970
+ if (!outcome.ok)
49971
+ return { content: outcome.reason, isError: true };
49972
+ return { content: outcome.summary };
49973
+ }
49974
+ };
49975
+ }
49976
+
48991
49977
  // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1_ed45788dfbfe808cc09dd7daea6bd385/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
48992
49978
  function isZ4Schema(s) {
48993
49979
  const schema2 = s;
@@ -55855,124 +56841,19 @@ var ASK_MODE = {
55855
56841
  description: "Read-only: inspect the workspace and answer questions. Cannot edit or run commands.",
55856
56842
  groups: ["read", "mcp", "always"]
55857
56843
  };
55858
- var JUNIOR_MODE = {
55859
- id: "junior",
55860
- name: "Junior",
55861
- description: "A cheap model does the work and consults Claude for the plan. Requires the expert.",
56844
+ var AGENT_TEAM_MODE = {
56845
+ id: "agent-team",
56846
+ name: "Agent team",
56847
+ description: "You lead; specialists you assign are consulted as needed. Requires at least one agent.",
55862
56848
  groups: ["read", "edit", "command", "mcp", "always"],
55863
- requiresExpert: true,
55864
- guidance: [
55865
- "# Junior mode",
55866
- "",
55867
- "You are the junior on this task. A stronger model (Claude) is available through",
55868
- "`ask_expert` and is the one that decides *what* to do; you decide *how* and carry it out.",
55869
- "You are the hands: reading, searching, editing, running commands, checking results.",
55870
- "",
55871
- "## The first consultation is expensive; the rest are cheap",
55872
- "",
55873
- "Consultations in one task continue **one conversation**. The first pays to establish it",
55874
- "and costs roughly twenty times a follow-up; every one after that is cheap and the expert",
55875
- "still remembers everything you have told it.",
55876
- "",
55877
- "Two things follow, and they matter more than any other instruction here:",
55878
- "",
55879
- "1. **Make the first consultation count.** Gather what is needed first and ask one full,",
55880
- ' well-formed question. Do not open with "hello" or a question you could answer yourself \u2014',
55881
- " you are paying the setup cost either way, so spend it on something real.",
55882
- "2. **Never repeat yourself afterwards.** The expert remembers the code you pasted, the plan",
55883
- ' it gave you and what you have tried. A follow-up is "step 3 failed with this error",',
55884
- " not the whole story again. Re-explaining throws away the entire saving.",
55885
- "",
55886
- "## Consulting is the default, not the exception",
55887
- "",
55888
- "On any request that is not trivial, **your first action is `ask_expert`** \u2014 before you plan,",
55889
- "before you edit, before you decide the task is straightforward. Do not wait to be told. If",
55890
- 'the user has to say "ask the expert", this mode has failed and is costing them the price of',
55891
- "a worse model for no benefit.",
55892
- "",
55893
- "A request is **not** trivial, and you must consult, if any of these is true:",
55894
- "",
55895
- "- it touches more than one file, or a file you have not read in this session;",
55896
- "- it asks you to design, refactor, choose an approach, or decide between options;",
55897
- "- it involves code you did not write in this conversation;",
55898
- "- you would have to guess at how something works to proceed;",
55899
- "- your first attempt failed, or a test or command reported an error;",
55900
- '- you are about to say "I think" or "probably" about anything load-bearing.',
55901
- "",
55902
- "When in doubt, consult. A consultation costs cents. Confidently doing the wrong thing costs",
55903
- "the user their afternoon.",
55904
- "",
55905
- "Ask for a concrete plan, the files involved, and the traps to avoid \u2014 **broken into",
55906
- "checkpoints**, as described below.",
55907
- "",
55908
- "**Genuinely trivial requests you simply do:** fixing a typo you can see, answering a",
55909
- "question about a file you have already read, running a command the user named. Asking about",
55910
- "those would waste the user\u2019s money on something you already know.",
55911
- "",
55912
- "## Checkpoints: implement, review, continue",
55913
- "",
55914
- "For anything larger than a single edit, ask the expert to split the plan into **checkpoints**.",
55915
- "Then work the loop: implement one checkpoint, go back to the expert with what you actually",
55916
- "did, take its feedback, and move to the next. Keep going until the work is complete.",
55917
- "",
55918
- "**This is a cost measure, not a quality ritual, and the distinction decides how you use it.**",
55919
- "The expensive failure in this arrangement is not a consultation \u2014 it is you building the",
55920
- "wrong thing for twenty turns and then needing the whole approach redone. A review after each",
55921
- "checkpoint costs about as much as one cheap follow-up and caps how far a wrong direction can",
55922
- "run before someone notices. It only pays if you keep it cheap:",
55923
- "",
55924
- "- **A checkpoint is a unit worth reviewing** \u2014 a coherent, working slice, typically a few",
55925
- " related edits. If a checkpoint is one line, the review costs more than the mistake it",
55926
- " could catch: fold it into the next one. If it is the entire feature, it is not a",
55927
- " checkpoint and defeats the point.",
55928
- '- **Report the delta, never the context.** "Checkpoint 2 done: added `retryWithBackoff` in',
55929
- " `http.ts`, wired it into `send()`, tests pass. Deviated from the plan by keeping the old",
55930
- ' signature, because three callers depend on it." The expert has the plan and remembers the',
55931
- "code \u2014 it can open anything it wants to see for itself.",
55932
- "- **Say what surprised you.** The parts worth a review are the deviations, the things that",
55933
- " did not match the plan, and anything you were unsure about. A checkpoint that went exactly",
55934
- " as planned needs a sentence, not a report.",
55935
- "- **Skip the review** when a checkpoint was mechanical and everything passed. Say so at the",
55936
- " next one instead. Two checkpoints in one review is cheaper than two reviews.",
55937
- '- **Run the tests before you report.** "Tests pass" is worth far more to the reviewer than a',
55938
- " description of the code, and finding it yourself is free where the expert finding it is not.",
55939
- "",
55940
- "If a budget is set the expert stops being available once it is reached, and you finish the",
55941
- "work alone. Spend the consultations you have on the checkpoints that carry the most risk.",
55942
- "",
55943
- "**Also consult again when:**",
55944
- "- the same step has failed twice and you do not understand why;",
55945
- "- the code contradicts the plan, so following it would be wrong;",
55946
- "- something is ambiguous in a way that changes *what* should be built, not merely how.",
55947
- "",
55948
- "## Gather the context before you ask",
55949
- "",
55950
- "The expert can open files itself, but doing so costs the user far more than it costs you.",
55951
- "So before consulting: find the relevant code, read it, and **include the actual code in",
55952
- "your question** along with what you have already tried and what happened.",
55953
- "",
55954
- "## You are its hands for tools, too",
55955
- "",
55956
- "The expert cannot call any of your tools \u2014 no MCP tool, no Python tool, no searching the",
55957
- "documentation index. It is told what you have, by name, but not the exact parameters. So",
55958
- "if it asks you to look up a tool\u2019s arguments or read a skill, do it and report back in the",
55959
- "same conversation; that round trip is cheap and stops it guessing a signature.",
55960
- "",
55961
- "## Carrying out the plan",
55962
- "",
55963
- "Follow it, but you are not a transcription service. The expert never ran anything and may",
55964
- "be wrong about the real code. If a step does not match what you find, say so and adapt \u2014",
55965
- "and if the mismatch is fundamental, that is one of the reasons to consult again.",
55966
- "",
55967
- "Tell the user which checkpoint you are on and what the expert said about the last one, so",
55968
- "they can see what they paid for and stop you if the direction is wrong. They are the only",
55969
- "reviewer whose approval actually gates anything."
55970
- ].join("\n")
56849
+ requiresExpert: true
55971
56850
  };
55972
- var BUILTIN_MODES = [CODE_MODE, ASK_MODE, JUNIOR_MODE];
56851
+ var BUILTIN_MODES = [CODE_MODE, ASK_MODE, AGENT_TEAM_MODE];
55973
56852
  var DEFAULT_MODE_ID = CODE_MODE.id;
56853
+ var RENAMED = { junior: AGENT_TEAM_MODE.id };
55974
56854
  function findMode(id) {
55975
- return BUILTIN_MODES.find((mode) => mode.id === id) ?? CODE_MODE;
56855
+ const resolved = id !== void 0 ? RENAMED[id] ?? id : id;
56856
+ return BUILTIN_MODES.find((mode) => mode.id === resolved) ?? CODE_MODE;
55976
56857
  }
55977
56858
 
55978
56859
  // ../../packages/core/dist/modes/resolve.js
@@ -56342,6 +57223,8 @@ async function truncateToolResult(content, store, maxChars = DEFAULT_MAX_CHARS)
56342
57223
 
56343
57224
  // ../../packages/core/dist/agent/loop.js
56344
57225
  var DEFAULT_MAX_ITERATIONS = 25;
57226
+ var BOOKKEEPING_TOOLS = /* @__PURE__ */ new Set(["plan_progress"]);
57227
+ var MAX_REFUNDED_STEPS = 20;
56345
57228
  var MAX_CONSECUTIVE_MISTAKES = 3;
56346
57229
  async function prepareModelMessages(conversation, provider, tools, options, events) {
56347
57230
  const contextWindow = options.contextWindow ?? 0;
@@ -56523,6 +57406,7 @@ async function runWithTimeout(tool, params, context, options) {
56523
57406
  async function runAgentTurn(provider, conversation, userMessage, toolRegistry, toolContext, events, options = {}) {
56524
57407
  conversation.addUserMessage(userMessage, options.images);
56525
57408
  const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
57409
+ let refunded = 0;
56526
57410
  const mistakeCounts = /* @__PURE__ */ new Map();
56527
57411
  let continueNudges = 0;
56528
57412
  const mode = options.mode ?? CODE_MODE;
@@ -56592,6 +57476,10 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
56592
57476
  events.onDone();
56593
57477
  return;
56594
57478
  }
57479
+ if (BOOKKEEPING_TOOLS.has(toolCall.name) && refunded < MAX_REFUNDED_STEPS) {
57480
+ refunded += 1;
57481
+ iteration -= 1;
57482
+ }
56595
57483
  if (result.path !== void 0) {
56596
57484
  if (result.isError === true) {
56597
57485
  const count = (mistakeCounts.get(result.path) ?? 0) + 1;
@@ -59643,6 +60531,8 @@ ${preview.text}` } : {}
59643
60531
  return [skillsDir, ...extraSkillDirs].filter((dir) => dir !== void 0);
59644
60532
  }
59645
60533
  let skills = [];
60534
+ let agentBriefingTools;
60535
+ let consultationContext;
59646
60536
  let skillIssues = [];
59647
60537
  const refreshSkills = async () => {
59648
60538
  const dirs = skillSearchPath();
@@ -59812,17 +60702,21 @@ ${preview.text}` } : {}
59812
60702
  const warnedExpiries = /* @__PURE__ */ new Set();
59813
60703
  let expertCli;
59814
60704
  let expertCliPath;
60705
+ async function detectCli(configured) {
60706
+ if (expertCli !== void 0 && expertCliPath === configured)
60707
+ return expertCli;
60708
+ expertCliPath = configured;
60709
+ expertCli = await detectClaudeCli(configured);
60710
+ if (!expertCli.available)
60711
+ logger.warn("expert unavailable", expertCli.reason ?? "");
60712
+ void postAgents();
60713
+ return expertCli;
60714
+ }
59815
60715
  async function resolveExpert(config2) {
59816
60716
  if (config2.expert?.enabled !== true)
59817
60717
  return void 0;
59818
- const configured = config2.expert.path ?? "claude";
59819
- if (expertCli === void 0 || expertCliPath !== configured) {
59820
- expertCliPath = configured;
59821
- expertCli = await detectClaudeCli(configured);
59822
- if (!expertCli.available)
59823
- logger.warn("expert unavailable", expertCli.reason ?? "");
59824
- }
59825
- return expertCli.available ? expertCli : void 0;
60718
+ const detected = await detectCli(config2.expert.path ?? "claude");
60719
+ return detected.available ? detected : void 0;
59826
60720
  }
59827
60721
  let queuedMessages = [];
59828
60722
  function postQueued() {
@@ -59832,7 +60726,47 @@ ${preview.text}` } : {}
59832
60726
  let taskCheckpoint;
59833
60727
  const ACTIVE_TASK_KEY = "lightCode.activeTaskId";
59834
60728
  let activeTaskId = services.workspaceState.get(ACTIVE_TASK_KEY);
60729
+ let activePlan;
60730
+ let activePlanProgress = {};
59835
60731
  let activeTaskCreatedAt = Date.now();
60732
+ function planViews() {
60733
+ return checkpointViews(activePlan, activePlanProgress);
60734
+ }
60735
+ function postPlanProgress() {
60736
+ post({ type: "planProgress", checkpoints: planViews() });
60737
+ }
60738
+ async function applyPlan(next) {
60739
+ const trimmed = next?.slice(0, PLAN_LIMIT).trim();
60740
+ activePlan = trimmed !== void 0 && trimmed.length > 0 ? trimmed : void 0;
60741
+ activePlanProgress = pruneProgress(activePlan, activePlanProgress);
60742
+ await persistActiveTask();
60743
+ post({ type: "plan", plan: activePlan ?? "" });
60744
+ postPlanProgress();
60745
+ }
60746
+ const planAccess = {
60747
+ current: () => activePlan,
60748
+ save: async (nextPlan) => {
60749
+ await applyPlan(nextPlan);
60750
+ },
60751
+ mark: async (index, status) => {
60752
+ const updated = markCheckpoint(activePlan, activePlanProgress, index, status);
60753
+ if (updated === void 0) {
60754
+ const total = planViews().length;
60755
+ return {
60756
+ ok: false,
60757
+ 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)}.`
60758
+ };
60759
+ }
60760
+ activePlanProgress = updated;
60761
+ await persistActiveTask();
60762
+ postPlanProgress();
60763
+ const views = planViews();
60764
+ return {
60765
+ ok: true,
60766
+ summary: `Step ${String(index)} is now ${status}. ${progressSummary(views)} steps complete.`
60767
+ };
60768
+ }
60769
+ };
59836
60770
  async function setActiveTaskId(id) {
59837
60771
  activeTaskId = id;
59838
60772
  await services.workspaceState.set(ACTIVE_TASK_KEY, id);
@@ -60074,7 +61008,9 @@ ${preview.text}` } : {}
60074
61008
  }
60075
61009
  let cachedModeId;
60076
61010
  let cachedCodeGenerator;
60077
- let cachedProviderExpert;
61011
+ let cachedTeam = [];
61012
+ let cachedTeamGuidance;
61013
+ let cachedBudgetMatters = false;
60078
61014
  let cachedMentionExcludes;
60079
61015
  let cachedReportsCost;
60080
61016
  let measuringStep;
@@ -60115,7 +61051,17 @@ ${preview.text}` } : {}
60115
61051
  const { config: config2 } = await configManager.load();
60116
61052
  cachedApprovals = approvalsFrom(config2.approvals);
60117
61053
  cachedCodeGenerator = codeGeneratorFor(config2);
60118
- cachedProviderExpert = providerExpertFor(config2);
61054
+ const teamContext = {
61055
+ config: config2.agents,
61056
+ profiles: (config2.profiles ?? []).map((profile) => ({
61057
+ id: profile.id,
61058
+ label: profile.label
61059
+ })),
61060
+ cliAvailable: expertCli?.available === true
61061
+ };
61062
+ cachedTeam = resolveTeam(teamContext);
61063
+ cachedTeamGuidance = config2.agents?.teamGuidance;
61064
+ cachedBudgetMatters = budgetMatters(teamContext);
60119
61065
  cachedProgrammingProfileId = config2.programmingProfileId;
60120
61066
  cachedOffice = config2.office ?? {};
60121
61067
  cachedMail = config2.mail ?? {};
@@ -60265,6 +61211,8 @@ ${preview.text}` } : {}
60265
61211
  }
60266
61212
  for (const tool of python.generatedTools())
60267
61213
  combined.register(tool, { dispatchOnly: dispatcher });
61214
+ combined.register(createUpdatePlanTool(planAccess), { dispatchOnly: dispatcher });
61215
+ combined.register(createPlanProgressTool(planAccess), { dispatchOnly: dispatcher });
60268
61216
  combined.register(createNotifyTool({
60269
61217
  notify: (message3, level, details) => {
60270
61218
  if (details !== void 0) {
@@ -60410,18 +61358,18 @@ ${preview.text}` } : {}
60410
61358
  observer: searchLog
60411
61359
  }));
60412
61360
  }
60413
- const providerExpert = cachedProviderExpert;
60414
- if (providerExpert !== void 0) {
60415
- combined.register(createRecallExpertTool({ history: () => expertAdvice }));
60416
- combined.register(createAskProviderExpertTool({
60417
- consult: providerExpert.consult,
60418
- label: providerExpert.label,
60419
- onAdvice: (record2) => expertAdvice.push(record2)
61361
+ if (cachedTeam.some((agent) => agent.available)) {
61362
+ combined.register(createAskAgentTool({
61363
+ agents: () => cachedTeam,
61364
+ onAdvice: (record2) => expertAdvice.push(record2),
61365
+ consult: async (agent, request) => consultAgent(agent, request)
60420
61366
  }));
60421
- } else if (expert !== void 0) {
61367
+ }
61368
+ if (expert !== void 0) {
60422
61369
  combined.register(createRecallExpertTool({ history: () => expertAdvice }));
60423
61370
  combined.register(createAskExpertTool({
60424
61371
  cli: expert.cli,
61372
+ budgetMatters: cachedBudgetMatters,
60425
61373
  ...expert.model !== void 0 ? { model: expert.model } : {},
60426
61374
  onConsultation: recordConsultation,
60427
61375
  onAdvice: (record2) => expertAdvice.push(record2),
@@ -60461,6 +61409,7 @@ ${preview.text}` } : {}
60461
61409
  })
60462
61410
  }));
60463
61411
  }
61412
+ agentBriefingTools = () => combined.list();
60464
61413
  return combined;
60465
61414
  }
60466
61415
  async function syncMcpFromConfig(config2) {
@@ -60537,7 +61486,9 @@ ${preview.text}` } : {}
60537
61486
  createdAt: activeTaskCreatedAt,
60538
61487
  updatedAt: Date.now(),
60539
61488
  messages,
60540
- resultHandles: truncationStore.spilledHandles()
61489
+ resultHandles: truncationStore.spilledHandles(),
61490
+ ...activePlan !== void 0 && activePlan.trim().length > 0 ? { plan: activePlan } : {},
61491
+ ...Object.keys(activePlanProgress).length > 0 ? { planProgress: activePlanProgress } : {}
60541
61492
  };
60542
61493
  try {
60543
61494
  await taskStore.save(redactTask(task, await knownSecretValues()));
@@ -60565,8 +61516,12 @@ ${preview.text}` } : {}
60565
61516
  taskCheckpoint = void 0;
60566
61517
  activeTaskCreatedAt = task.createdAt;
60567
61518
  truncationStore.startTask(task.resultHandles);
61519
+ activePlan = task.plan;
61520
+ activePlanProgress = pruneProgress(activePlan, task.planProgress);
60568
61521
  await setActiveTaskId(task.id);
60569
61522
  post({ type: "taskRestored", taskId: task.id, entries: toTranscript(task.messages) });
61523
+ post({ type: "plan", plan: activePlan ?? "" });
61524
+ postPlanProgress();
60570
61525
  await postTasks();
60571
61526
  }
60572
61527
  async function startNewTask() {
@@ -60576,8 +61531,12 @@ ${preview.text}` } : {}
60576
61531
  taskCheckpoint = void 0;
60577
61532
  activeTaskCreatedAt = Date.now();
60578
61533
  truncationStore.startTask();
61534
+ activePlan = void 0;
61535
+ activePlanProgress = {};
60579
61536
  await setActiveTaskId(void 0);
60580
61537
  post({ type: "taskRestored", taskId: void 0, entries: [] });
61538
+ post({ type: "plan", plan: "" });
61539
+ postPlanProgress();
60581
61540
  await postTasks();
60582
61541
  }
60583
61542
  async function deleteTask(id) {
@@ -60658,6 +61617,8 @@ ${preview.text}` } : {}
60658
61617
  ].filter((section) => section.length > 0).join("\n\n") : renderSkillsForPrompt(turnSkills),
60659
61618
  skillsSearchable,
60660
61619
  canWriteSkills: skillsDir !== void 0,
61620
+ // Last in the prompt, and the most specific thing in it — see `agent/plan.ts`.
61621
+ ...activePlan !== void 0 && activePlan.trim().length > 0 ? { plan: activePlan } : {},
60661
61622
  // Only when a pool actually exists: telling the model about a tool it has not been given
60662
61623
  // is how it comes to report that it looked somewhere it could not reach.
60663
61624
  teamSkillsAvailable: config2.embedder?.skillsAlias !== void 0,
@@ -60679,7 +61640,22 @@ ${preview.text}` } : {}
60679
61640
  */
60680
61641
  ...(() => {
60681
61642
  const parts = [];
60682
- if (activeMode.guidance !== void 0 && (activeMode.requiresExpert !== true || expertCliInfo !== void 0)) {
61643
+ if (activeMode.id === AGENT_TEAM_MODE.id) {
61644
+ parts.push(buildTeamGuidance(
61645
+ // The whole team, not only the available ones: the roster names what is missing
61646
+ // as well as what is there, and it cannot do that from a pre-filtered list.
61647
+ cachedTeam,
61648
+ cachedTeamGuidance,
61649
+ cachedBudgetMatters,
61650
+ /*
61651
+ * Whether a plan already exists, which decides whether this mode is told to go
61652
+ * and make one. Passed rather than inferred from the prompt: the plan section is
61653
+ * assembled separately, and a mode guessing at whether it is there would be a
61654
+ * second reading of the same fact.
61655
+ */
61656
+ activePlan !== void 0 && activePlan.trim().length > 0
61657
+ ));
61658
+ } else if (activeMode.guidance !== void 0 && (activeMode.requiresExpert !== true || expertCliInfo !== void 0)) {
60683
61659
  parts.push(activeMode.guidance);
60684
61660
  }
60685
61661
  if (scheduledGuidance !== void 0)
@@ -60715,6 +61691,7 @@ ${preview.text}` } : {}
60715
61691
  // lives in the VSIX, so resolving it is a host concern (§4).
60716
61692
  ...ripgrepPath !== void 0 ? { ripgrepPath } : {}
60717
61693
  };
61694
+ consultationContext = () => toolContext;
60718
61695
  pythonNestedContext = toolContext;
60719
61696
  pythonNestedCallsAllowed = schedule === void 0;
60720
61697
  const mentions = await resolveMentions(text, { fs: toolContext.fs, workspaceRoot, denylist });
@@ -60756,7 +61733,7 @@ ${preview.text}` } : {}
60756
61733
  }
60757
61734
  let cumulativeText = "";
60758
61735
  let cumulativeReasoning = "";
60759
- let expertInformed = false;
61736
+ let informedBy;
60760
61737
  const fullRegistry = currentToolRegistry(
60761
61738
  expertCliInfo !== void 0 ? {
60762
61739
  cli: expertCliInfo,
@@ -60840,7 +61817,7 @@ ${preview.text}` } : {}
60840
61817
  post({
60841
61818
  type: "textChunk",
60842
61819
  text: cumulativeText,
60843
- ...expertInformed ? { expertInformed } : {}
61820
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
60844
61821
  });
60845
61822
  },
60846
61823
  onReasoningChunk: (chunk) => {
@@ -60850,22 +61827,24 @@ ${preview.text}` } : {}
60850
61827
  onToolCall: (toolCall) => {
60851
61828
  cumulativeText = "";
60852
61829
  cumulativeReasoning = "";
60853
- if (toolCall.name === "ask_expert")
60854
- expertInformed = true;
61830
+ const consulting = consultationFromToolCall(toolCall.name, toolCall.arguments);
61831
+ if (consulting !== void 0) {
61832
+ informedBy = consulting;
61833
+ const attributed = attributeConsultation(activePlanProgress, consulting);
61834
+ if (attributed !== activePlanProgress) {
61835
+ activePlanProgress = attributed;
61836
+ postPlanProgress();
61837
+ }
61838
+ }
60855
61839
  if (CONTROL_TOOLS.has(toolCall.name))
60856
61840
  return;
60857
61841
  if (chartFromToolCall(toolCall.name, toolCall.arguments) !== void 0)
60858
61842
  return;
60859
- const summary = {
60860
- id: toolCall.id,
60861
- name: toolCall.name,
60862
- arguments: formatToolArguments(toolCall.arguments),
60863
- ...toolCallReason(toolCall.arguments) === void 0 ? {} : { why: toolCallReason(toolCall.arguments) }
60864
- };
61843
+ const summary = toolCallSummary(toolCall);
60865
61844
  post({
60866
61845
  type: "toolCall",
60867
61846
  toolCall: summary,
60868
- ...expertInformed ? { expertInformed } : {}
61847
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
60869
61848
  });
60870
61849
  },
60871
61850
  onToolResult: (toolCall, result) => {
@@ -60878,22 +61857,18 @@ ${preview.text}` } : {}
60878
61857
  post(chart.kind === "chart" ? {
60879
61858
  type: "chart",
60880
61859
  chart: chart.chart,
60881
- ...expertInformed ? { expertInformed } : {}
61860
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
60882
61861
  } : { type: "chartError", message: chart.message });
60883
61862
  return;
60884
61863
  }
60885
- const summary = {
60886
- id: toolCall.id,
60887
- name: toolCall.name,
60888
- arguments: formatToolArguments(toolCall.arguments),
60889
- ...toolCallReason(toolCall.arguments) === void 0 ? {} : { why: toolCallReason(toolCall.arguments) },
61864
+ const summary = toolCallSummary(toolCall, {
60890
61865
  result: result.content,
60891
61866
  ...result.isError === true ? { isError: true } : {}
60892
- };
61867
+ });
60893
61868
  post({
60894
61869
  type: "toolResult",
60895
61870
  toolCall: summary,
60896
- ...expertInformed ? { expertInformed } : {}
61871
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
60897
61872
  });
60898
61873
  },
60899
61874
  onCheckpoint: (checkpoint) => {
@@ -61042,6 +62017,7 @@ ${preview.text}` } : {}
61042
62017
  cachedAuth = void 0;
61043
62018
  post({ type: "profileSaved" });
61044
62019
  await postProfiles();
62020
+ await postAgents();
61045
62021
  } catch (error51) {
61046
62022
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
61047
62023
  }
@@ -61095,6 +62071,7 @@ ${preview.text}` } : {}
61095
62071
  };
61096
62072
  await configManager.save("user", { profiles: [...profiles, duplicate] });
61097
62073
  await postProfiles();
62074
+ await postAgents();
61098
62075
  } catch (error51) {
61099
62076
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
61100
62077
  }
@@ -61109,6 +62086,7 @@ ${preview.text}` } : {}
61109
62086
  const activeProfileId = config2.activeProfileId === id ? remaining[0]?.id : config2.activeProfileId;
61110
62087
  await configManager.save("user", { profiles: remaining, activeProfileId });
61111
62088
  await postProfiles();
62089
+ await postAgents();
61112
62090
  } catch (error51) {
61113
62091
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
61114
62092
  }
@@ -61127,6 +62105,7 @@ ${preview.text}` } : {}
61127
62105
  await configManager.save("user", { activeProfileId: id });
61128
62106
  await postProjectSettings();
61129
62107
  await postProfiles();
62108
+ await postAgents();
61130
62109
  } catch (error51) {
61131
62110
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
61132
62111
  }
@@ -61178,26 +62157,16 @@ ${preview.text}` } : {}
61178
62157
  // The whole thing, profiles included. Passing only half of what the constructor takes is
61179
62158
  // the same mistake as having two constructors, and this failure path is where the last
61180
62159
  // one hid: it runs rarely, so a field missing here is noticed much later than elsewhere.
61181
- ...expertMessageFrom(settings, loaded?.profiles),
62160
+ ...expertMessageFrom(settings),
61182
62161
  available: false,
61183
62162
  path: settings?.path ?? expertCliPath ?? "claude",
61184
62163
  reason: `Could not check whether the Claude CLI is available: ${reason}`
61185
62164
  });
61186
62165
  }
61187
62166
  }
61188
- function expertMessageFrom(settings, profiles) {
62167
+ function expertMessageFrom(settings) {
61189
62168
  return {
61190
62169
  type: "expert",
61191
- /*
61192
- * Sent from here and nowhere else. CLAUDE.md records what happened the last time two
61193
- * `expert` messages were built separately: measured pricing reached the success path and
61194
- * not the failure path, and the panel showed a dash for something that had been measured.
61195
- */
61196
- ...services.expertMode === "profile" ? {
61197
- mode: "profile",
61198
- profiles: (profiles ?? []).map((profile) => ({ id: profile.id, label: profile.label })),
61199
- ...settings?.profileId !== void 0 ? { profileId: settings.profileId } : {}
61200
- } : {},
61201
62170
  enabled: settings?.enabled === true,
61202
62171
  available: false,
61203
62172
  path: settings?.path ?? expertCliPath ?? "claude",
@@ -61214,24 +62183,81 @@ ${preview.text}` } : {}
61214
62183
  ...expertEvents !== void 0 ? { savings: summariseSavings(expertEvents, settings?.pricing) } : {}
61215
62184
  };
61216
62185
  }
61217
- async function postExpertInner(redetect) {
62186
+ async function postAgents() {
61218
62187
  const { config: config2 } = await configManager.load();
61219
- if (services.expertMode === "profile") {
61220
- post({
61221
- ...expertMessageFrom(config2.expert, config2.profiles),
61222
- // Usable when a profile is chosen, which is the only thing availability can mean here.
61223
- available: config2.expert?.enabled === true && config2.expert.profileId !== void 0 && config2.profiles?.some((profile) => profile.id === config2.expert?.profileId) === true
61224
- });
61225
- return;
62188
+ const cli = await detectCli(config2.expert?.path ?? "claude").catch(() => void 0);
62189
+ const teamContext = {
62190
+ config: config2.agents,
62191
+ profiles: (config2.profiles ?? []).map((profile) => ({
62192
+ id: profile.id,
62193
+ label: profile.label
62194
+ })),
62195
+ cliAvailable: cli?.available === true
62196
+ };
62197
+ const assigned = new Map(resolveTeam(teamContext).map((agent) => [agent.role, agent]));
62198
+ const roles = allRoles().map((info) => {
62199
+ const agent = assigned.get(info.role);
62200
+ const prompt = config2.agents?.roles?.[info.role]?.prompt;
62201
+ return {
62202
+ role: info.role,
62203
+ name: info.name,
62204
+ summary: info.summary,
62205
+ ...agent !== void 0 ? { kind: agent.kind } : {},
62206
+ ...agent?.profileId !== void 0 ? { profileId: agent.profileId } : {},
62207
+ label: agent?.label ?? "Nobody",
62208
+ available: agent?.available ?? false,
62209
+ ...agent?.reason !== void 0 ? { reason: agent.reason } : {},
62210
+ prompt: prompt ?? defaultPromptFor(info.role),
62211
+ promptIsDefault: prompt === void 0
62212
+ };
62213
+ });
62214
+ const guidance = config2.agents?.teamGuidance;
62215
+ post({
62216
+ type: "agents",
62217
+ roles,
62218
+ profiles: teamContext.profiles,
62219
+ cliAvailable: teamContext.cliAvailable,
62220
+ ...cli?.available === false && cli.reason !== void 0 ? { cliReason: cli.reason } : {},
62221
+ budgetMatters: budgetMatters(teamContext),
62222
+ teamGuidance: guidance ?? DEFAULT_TEAM_GUIDANCE,
62223
+ defaultTeamGuidance: DEFAULT_TEAM_GUIDANCE,
62224
+ teamGuidanceIsDefault: guidance === void 0,
62225
+ colors: {
62226
+ /*
62227
+ * The expert's colour comes from the control that has always owned it.
62228
+ *
62229
+ * It predates roles and lives under `ui.expertColor`, and the Agents work briefly gave it
62230
+ * a second home under `agents.colors.expert` — two pickers for one thing, backed by two
62231
+ * settings, which is the drift this project pays for most often. An explicit per-role
62232
+ * value still wins, so nothing is taken away; it is simply no longer the *default*
62233
+ * source for a colour that already had one.
62234
+ */
62235
+ expert: config2.ui?.expertColor ?? "#D97757",
62236
+ ...config2.agents?.colors ?? {}
62237
+ }
62238
+ });
62239
+ }
62240
+ async function saveAgents(change) {
62241
+ try {
62242
+ const { config: config2 } = await configManager.load();
62243
+ await configManager.save("user", { agents: change(config2.agents ?? {}) });
62244
+ await loadSettings();
62245
+ await postAgents();
62246
+ } catch (error51) {
62247
+ post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
61226
62248
  }
62249
+ }
62250
+ async function postExpertInner(redetect) {
62251
+ const { config: config2 } = await configManager.load();
61227
62252
  await loadExpertEvents();
61228
62253
  const configured = config2.expert?.path ?? "claude";
61229
62254
  const detected = !redetect && expertCli !== void 0 && expertCliPath === configured ? expertCli : await detectClaudeCli(configured);
61230
62255
  expertCli = detected;
61231
62256
  expertCliPath = configured;
62257
+ void postAgents();
61232
62258
  post({
61233
62259
  // Everything from settings comes from one place, so the two paths cannot drift again.
61234
- ...expertMessageFrom(config2.expert, config2.profiles),
62260
+ ...expertMessageFrom(config2.expert),
61235
62261
  available: detected.available,
61236
62262
  path: configured,
61237
62263
  ...detected.version !== void 0 ? { version: detected.version } : {},
@@ -63212,6 +64238,7 @@ ${preview.text}` } : {}
63212
64238
  }));
63213
64239
  await configManager.save("user", { ...imported, profiles: reconciled });
63214
64240
  await postProfiles();
64241
+ await postAgents();
63215
64242
  ui.showInfo(needKeys.length > 0 ? `Config imported. Re-enter the API key for: ${needKeys.join(", ")} (exports never include secrets).` : "Config imported.");
63216
64243
  } catch (error51) {
63217
64244
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
@@ -63233,35 +64260,79 @@ ${preview.text}` } : {}
63233
64260
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
63234
64261
  }
63235
64262
  }
63236
- function providerExpertFor(config2) {
63237
- if (services.expertMode !== "profile")
63238
- return void 0;
63239
- if (config2.expert?.enabled !== true)
63240
- return void 0;
63241
- const id = config2.expert.profileId;
63242
- if (id === void 0 || id.length === 0)
63243
- return void 0;
63244
- const profile = config2.profiles?.find((candidate) => candidate.id === id);
64263
+ async function consultAgent(agent, request) {
64264
+ const prompt = buildAgentPrompt({
64265
+ prompt: agent.prompt,
64266
+ question: request.question,
64267
+ // Decides the preamble as well as whether tools are offered below, so the two can never
64268
+ // disagree — a specialist told it can read, and then given nothing to read with, wastes a
64269
+ // step discovering that.
64270
+ usesTools: agent.usesTools,
64271
+ ...request.files !== void 0 ? { files: request.files } : {},
64272
+ /*
64273
+ * What exists in this workspace.
64274
+ *
64275
+ * Without it a specialist advises as though the assistant were a bare shell — proposing by
64276
+ * hand what a configured tool already does, or inventing a procedure an existing skill
64277
+ * documents. See `agents/briefing.ts` for why names are worth the tokens and schemas are not.
64278
+ */
64279
+ briefing: buildAgentBriefing({
64280
+ tools: agentBriefingTools?.() ?? [],
64281
+ skills,
64282
+ /*
64283
+ * Who else exists, so a plan cannot name a specialist nobody set up.
64284
+ *
64285
+ * Built here, above the `kind` branch, which is the point: the Claude CLI expert and a
64286
+ * provider-profile expert are given byte-identical briefings, so making a different model
64287
+ * the expert cannot change what it knows about the team. `briefing.test.ts` pins that,
64288
+ * because the two paths diverging is invisible until somebody switches expert and gets a
64289
+ * worse plan for no reason they could name.
64290
+ */
64291
+ team: cachedTeam,
64292
+ self: agent.role
64293
+ })
64294
+ });
64295
+ if (agent.kind === "cli") {
64296
+ const cli = expertCli;
64297
+ if (cli === void 0 || !cli.available)
64298
+ throw new Error("The Claude CLI is not available.");
64299
+ const answer = await consultExpert(cli, {
64300
+ question: prompt,
64301
+ /*
64302
+ * The workspace, so Claude's own Read/Grep resolve against the project rather than
64303
+ * wherever this process was started. Falls back to the process directory when no folder
64304
+ * is open — the consultation is still worth having without one.
64305
+ */
64306
+ cwd: workspaceRoot ?? process.cwd(),
64307
+ ...request.signal !== void 0 ? { signal: request.signal } : {}
64308
+ });
64309
+ if (answer.isError)
64310
+ throw new Error(answer.text);
64311
+ return { advice: answer.text, label: agent.label };
64312
+ }
64313
+ const { config: config2 } = await configManager.load();
64314
+ const profile = config2.profiles?.find((candidate) => candidate.id === agent.profileId);
63245
64315
  if (profile === void 0) {
63246
- logger.warn(`the expert profile "${id}" is configured but no such profile exists; the expert is unavailable`);
63247
- return void 0;
64316
+ throw new Error(`No profile "${agent.profileId ?? ""}" exists any more.`);
64317
+ }
64318
+ const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger);
64319
+ const readOnly = agent.usesTools ? toolsForConsultation(agentBriefingTools?.() ?? []) : [];
64320
+ const context = consultationContext?.();
64321
+ const result = await runConsultation({
64322
+ provider,
64323
+ prompt,
64324
+ tools: readOnly,
64325
+ definitions: context === void 0 ? [] : toToolDefinitions(readOnly),
64326
+ // With no context there is nothing to read *with*, so it answers from the question alone
64327
+ // rather than being offered tools that would fail.
64328
+ context: context ?? {},
64329
+ ...request.signal !== void 0 ? { signal: request.signal } : {},
64330
+ onStep: (name) => logger.info(`${agent.role} looked up ${name}`)
64331
+ });
64332
+ if (result.truncated) {
64333
+ logger.info(`${agent.role} reached its lookup limit and answered with what it had`);
63248
64334
  }
63249
- return {
63250
- label: profile.label,
63251
- consult: async (request) => {
63252
- const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger);
63253
- let text = "";
63254
- for await (const chunk of provider.streamChat([{ role: "user", content: buildExpertPrompt(request) }], {
63255
- // No tools offered: it is being asked for judgement, and offering tools invites it to
63256
- // reach for one it has no way to run.
63257
- ...request.signal !== void 0 ? { signal: request.signal } : {}
63258
- })) {
63259
- if (chunk.type === "text")
63260
- text += chunk.text;
63261
- }
63262
- return { advice: text, producedBy: profile.label };
63263
- }
63264
- };
64335
+ return { advice: result.advice, label: agent.label };
63265
64336
  }
63266
64337
  function codeGeneratorFor(config2) {
63267
64338
  if (services.allowProgrammingProfile !== true)
@@ -64006,6 +65077,80 @@ ${preview.text}` } : {}
64006
65077
  void handleSaveNetwork(message3.settings);
64007
65078
  } else if (message3.type === "requestExpert") {
64008
65079
  void postExpert();
65080
+ } else if (message3.type === "setPlan") {
65081
+ void applyPlan(message3.plan);
65082
+ } else if (message3.type === "requestPlan") {
65083
+ post({ type: "plan", plan: activePlan ?? "" });
65084
+ postPlanProgress();
65085
+ } else if (message3.type === "requestPlanProgress") {
65086
+ postPlanProgress();
65087
+ } else if (message3.type === "requestAgents") {
65088
+ void postAgents();
65089
+ } else if (message3.type === "setAgentRole") {
65090
+ const assignment = message3.assignment;
65091
+ const role = message3.role;
65092
+ if (!isAgentRole(role)) {
65093
+ post({ type: "error", message: `There is no "${role}" role.` });
65094
+ return;
65095
+ }
65096
+ void saveAgents((current) => {
65097
+ const roles = { ...current.roles ?? {} };
65098
+ if (assignment === void 0)
65099
+ delete roles[role];
65100
+ else {
65101
+ roles[role] = {
65102
+ kind: assignment.kind,
65103
+ ...assignment.profileId !== void 0 ? { profileId: assignment.profileId } : {},
65104
+ ...roles[role]?.prompt !== void 0 ? { prompt: roles[role].prompt } : {}
65105
+ };
65106
+ }
65107
+ return { ...current, roles };
65108
+ });
65109
+ } else if (message3.type === "setAgentPrompt") {
65110
+ const role = message3.role;
65111
+ const prompt = message3.prompt;
65112
+ if (!isAgentRole(role)) {
65113
+ post({ type: "error", message: `There is no "${role}" role.` });
65114
+ return;
65115
+ }
65116
+ void saveAgents((current) => {
65117
+ const roles = { ...current.roles ?? {} };
65118
+ const existing = roles[role];
65119
+ if (prompt === void 0 || prompt === defaultPromptFor(role)) {
65120
+ if (existing !== void 0) {
65121
+ const rest = { ...existing };
65122
+ delete rest.prompt;
65123
+ roles[role] = rest;
65124
+ }
65125
+ } else {
65126
+ roles[role] = { ...existing ?? { kind: "profile" }, prompt };
65127
+ }
65128
+ return { ...current, roles };
65129
+ });
65130
+ } else if (message3.type === "setAgentBudget") {
65131
+ const matters = message3.matters;
65132
+ void saveAgents((current) => ({ ...current, budgetMatters: matters }));
65133
+ } else if (message3.type === "setTeamGuidance") {
65134
+ const guidance = message3.guidance;
65135
+ void saveAgents((current) => {
65136
+ if (guidance === void 0 || guidance.trim().length === 0 || guidance === DEFAULT_TEAM_GUIDANCE) {
65137
+ const rest = { ...current };
65138
+ delete rest.teamGuidance;
65139
+ return rest;
65140
+ }
65141
+ return { ...current, teamGuidance: guidance };
65142
+ });
65143
+ } else if (message3.type === "setAgentColor") {
65144
+ const role = message3.role;
65145
+ const color = message3.color;
65146
+ if (!isAgentRole(role)) {
65147
+ post({ type: "error", message: `There is no "${role}" role.` });
65148
+ return;
65149
+ }
65150
+ void saveAgents((current) => ({
65151
+ ...current,
65152
+ colors: { ...current.colors ?? {}, [role]: color }
65153
+ }));
64009
65154
  } else if (message3.type === "setExpert") {
64010
65155
  void handleSetExpert(message3.enabled, message3.path, message3.model, {
64011
65156
  ...message3.maxSpendUsd !== void 0 ? { maxSpendUsd: message3.maxSpendUsd } : {},
@@ -64675,7 +65820,10 @@ function chartTotals(spec) {
64675
65820
  }
64676
65821
 
64677
65822
  // ../../packages/core/dist/history/transcript.js
64678
- var CONTROL_TOOLS = /* @__PURE__ */ new Set(["attempt_completion", "ask_followup_question"]);
65823
+ var CONTROL_TOOLS = /* @__PURE__ */ new Set([
65824
+ "attempt_completion",
65825
+ "ask_followup_question"
65826
+ ]);
64679
65827
  function formatToolArguments(raw) {
64680
65828
  try {
64681
65829
  const parsed = JSON.parse(raw.length > 0 ? raw : "{}");
@@ -64707,7 +65855,7 @@ function toTranscript(messages) {
64707
65855
  resultsByCallId.set(message3.toolCallId, message3.content);
64708
65856
  }
64709
65857
  const entries = [];
64710
- let expertInformed = false;
65858
+ let informedBy;
64711
65859
  for (const message3 of messages) {
64712
65860
  if (message3.role === "system" || message3.role === "tool")
64713
65861
  continue;
@@ -64716,13 +65864,22 @@ function toTranscript(messages) {
64716
65864
  continue;
64717
65865
  }
64718
65866
  if (message3.content.length > 0) {
64719
- entries.push({ kind: "text", role: "assistant", content: message3.content, ...expertInformed ? { expertInformed } : {} });
65867
+ entries.push({
65868
+ kind: "text",
65869
+ role: "assistant",
65870
+ content: message3.content,
65871
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
65872
+ });
64720
65873
  }
64721
65874
  for (const toolCall of message3.toolCalls ?? []) {
64722
65875
  const result = resultsByCallId.get(toolCall.id);
64723
65876
  const asChart = chartFromToolCall(toolCall.name, toolCall.arguments);
64724
65877
  if (asChart !== void 0) {
64725
- entries.push(asChart.kind === "chart" ? { kind: "chart", chart: asChart.chart, ...expertInformed ? { expertInformed: true } : {} } : asChart);
65878
+ entries.push(asChart.kind === "chart" ? {
65879
+ kind: "chart",
65880
+ chart: asChart.chart,
65881
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {}
65882
+ } : asChart);
64726
65883
  continue;
64727
65884
  }
64728
65885
  if (CONTROL_TOOLS.has(toolCall.name)) {
@@ -64730,26 +65887,46 @@ function toTranscript(messages) {
64730
65887
  entries.push({ kind: "text", role: "assistant", content: result });
64731
65888
  continue;
64732
65889
  }
64733
- if (toolCall.name === "ask_expert")
64734
- expertInformed = true;
65890
+ const consulting = consultationFromToolCall(toolCall.name, toolCall.arguments);
65891
+ if (consulting !== void 0)
65892
+ informedBy = consulting;
64735
65893
  entries.push({
64736
65894
  kind: "tool",
64737
- ...expertInformed ? { expertInformed: true } : {},
64738
- toolCall: {
64739
- id: toolCall.id,
64740
- name: toolCall.name,
64741
- arguments: formatToolArguments(toolCall.arguments),
64742
- ...toolCallReason(toolCall.arguments) === void 0 ? {} : { why: toolCallReason(toolCall.arguments) },
64743
- // A call with no matching result means the task ended mid-flight — a cancel, a
64744
- // crash, or a window closed. Leaving `result` unset renders it as unfinished,
64745
- // which is what actually happened.
64746
- ...result !== void 0 ? { result } : {}
64747
- }
65895
+ ...informedBy !== void 0 ? { expertInformed: true, informedBy } : {},
65896
+ /*
65897
+ * Built by the one builder, so a restored transcript and a live turn cannot differ about
65898
+ * what a call looked like. A call with no matching result means the task ended mid-flight
65899
+ * — a cancel, a crash, a window closed — and leaving `result` unset renders it as
65900
+ * unfinished, which is what actually happened.
65901
+ */
65902
+ toolCall: toolCallSummary(toolCall, { result })
64748
65903
  });
64749
65904
  }
64750
65905
  }
64751
65906
  return entries;
64752
65907
  }
65908
+ function toolCallSummary(call, outcome) {
65909
+ const why = toolCallReason(call.arguments);
65910
+ const consulting = consultationFromToolCall(call.name, call.arguments);
65911
+ return {
65912
+ id: call.id,
65913
+ name: call.name,
65914
+ arguments: formatToolArguments(call.arguments),
65915
+ ...why !== void 0 ? { why } : {},
65916
+ ...consulting !== void 0 ? { consultingRole: consulting } : {},
65917
+ ...outcome?.result !== void 0 ? { result: outcome.result } : {},
65918
+ ...outcome?.isError === true ? { isError: true } : {}
65919
+ };
65920
+ }
65921
+ function consultationFromToolCall(name, rawArguments) {
65922
+ if (name === "ask_expert")
65923
+ return "expert";
65924
+ if (name !== "ask_agent")
65925
+ return void 0;
65926
+ const decoded = decodeArguments(rawArguments);
65927
+ const role = typeof decoded === "object" && decoded !== null ? decoded.role : void 0;
65928
+ return typeof role === "string" && role.trim().length > 0 ? role.trim().toLowerCase() : "unknown";
65929
+ }
64753
65930
  function chartFromToolCall(name, rawArguments) {
64754
65931
  if (name !== "show_chart")
64755
65932
  return void 0;
@@ -67063,16 +68240,6 @@ async function createSession(options) {
67063
68240
  * The extension says nothing and keeps all of it — that is where the feature is used.
67064
68241
  */
67065
68242
  offersOffice: false,
67066
- /*
67067
- * The expert is a provider profile here, not the Claude CLI.
67068
- *
67069
- * Asked for directly: any configured model should be able to be the expert, and cost is no
67070
- * longer something to manage in the product. Both follow from where this runs — there is no
67071
- * `claude` binary on a server, and the gateway answering the chat already has a stronger
67072
- * model behind it. Everything about budgets, measured price and savings belongs to the CLI
67073
- * expert, which is what the extension still has.
67074
- */
67075
- expertMode: "profile",
67076
68243
  transport: options.transport,
67077
68244
  /*
67078
68245
  * A shared profile's API key belongs to the administrator and lives beside the shared config;