github-router 0.3.377 → 0.3.379

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.
Files changed (61) hide show
  1. package/dist/ado-tools-CRkyU51J.js +1 -0
  2. package/dist/{attribution-settings-CD0_yLqf.js → attribution-settings-BWYL2b8N.js} +7 -7
  3. package/dist/{attribution-settings-CD0_yLqf.js.map → attribution-settings-BWYL2b8N.js.map} +1 -1
  4. package/dist/browser-ext/manifest.json +1 -1
  5. package/dist/{claude-Drda1tQL.js → claude-CSuIdaLV.js} +14 -14
  6. package/dist/{claude-Drda1tQL.js.map → claude-CSuIdaLV.js.map} +1 -1
  7. package/dist/{claude-md-injection-C0EQfdJo.js → claude-md-injection-Biq_Xhve.js} +4 -4
  8. package/dist/{claude-md-injection-C0EQfdJo.js.map → claude-md-injection-Biq_Xhve.js.map} +1 -1
  9. package/dist/{codex-BloFb0Da.js → codex-BG0pfud9.js} +5 -5
  10. package/dist/{codex-BloFb0Da.js.map → codex-BG0pfud9.js.map} +1 -1
  11. package/dist/{copilot-discount-CHNQLYDJ.js → copilot-discount-UXC6NQbN.js} +2 -1
  12. package/dist/copilot-discount-UXC6NQbN.js.map +1 -0
  13. package/dist/engine-V46un8Xl.js +1 -0
  14. package/dist/{gate-discovery-ByWG9xdK.js → gate-discovery-DjH9YXoN.js} +2 -2
  15. package/dist/{gate-discovery-ByWG9xdK.js.map → gate-discovery-DjH9YXoN.js.map} +1 -1
  16. package/dist/hooks.mjs +4 -2
  17. package/dist/hooks.sha256 +1 -1
  18. package/dist/{internal-aic-status-FQB1DQzX.js → internal-aic-status-B_hEeM37.js} +2 -2
  19. package/dist/{internal-aic-status-FQB1DQzX.js.map → internal-aic-status-B_hEeM37.js.map} +1 -1
  20. package/dist/{internal-max-dispatch-guard-D3L00YXj.js → internal-max-dispatch-guard-0teaxIc1.js} +2 -2
  21. package/dist/{internal-max-dispatch-guard-D3L00YXj.js.map → internal-max-dispatch-guard-0teaxIc1.js.map} +1 -1
  22. package/dist/{internal-max-dispatch-guard-fhBX_w49.js → internal-max-dispatch-guard-5LSaHN_y.js} +1 -1
  23. package/dist/{internal-prompt-submit-BbnaMF2R.js → internal-prompt-submit-BixNLmM3.js} +2 -2
  24. package/dist/{internal-prompt-submit-BbnaMF2R.js.map → internal-prompt-submit-BixNLmM3.js.map} +1 -1
  25. package/dist/{internal-prompt-submit-DKzCckz-.js → internal-prompt-submit-Ou8xtRXj.js} +2 -2
  26. package/dist/{internal-rebrief-aEvxp7jw.js → internal-rebrief-BBGM0PMv.js} +3 -3
  27. package/dist/{internal-rebrief-aEvxp7jw.js.map → internal-rebrief-BBGM0PMv.js.map} +1 -1
  28. package/dist/{internal-stop-hook-BC5__bNI.js → internal-stop-hook-DO9Iiaes.js} +2 -2
  29. package/dist/{internal-stop-hook-BC5__bNI.js.map → internal-stop-hook-DO9Iiaes.js.map} +1 -1
  30. package/dist/main.js +10 -10
  31. package/dist/{max-profile-contract-DLLTsSs2.js → max-profile-contract-DbHwiLTx.js} +2 -2
  32. package/dist/max-profile-contract-DbHwiLTx.js.map +1 -0
  33. package/dist/{peer-mcp-personas-B1prNNMJ.js → peer-mcp-personas-OWsSm6To.js} +20 -11
  34. package/dist/peer-mcp-personas-OWsSm6To.js.map +1 -0
  35. package/dist/{pi-CzDdGipf.js → pi-DmeBxzIo.js} +396 -71
  36. package/dist/pi-DmeBxzIo.js.map +1 -0
  37. package/dist/pi-foreign-artifacts-DZ4tioyO.js +660 -0
  38. package/dist/pi-foreign-artifacts-DZ4tioyO.js.map +1 -0
  39. package/dist/pi-memory-bridge-Bp9AnYw9.js +1 -0
  40. package/dist/{pi-memory-bridge-Dvj1T3e3.js → pi-memory-bridge-CICIdDVP.js} +15 -5
  41. package/dist/pi-memory-bridge-CICIdDVP.js.map +1 -0
  42. package/dist/{provision-DktDm-f0.js → provision-DPL8aGe2.js} +2 -2
  43. package/dist/{provision-DktDm-f0.js.map → provision-DPL8aGe2.js.map} +1 -1
  44. package/dist/{serve-CU3bV4e0.js → serve-zbQKfx1E.js} +7 -7
  45. package/dist/{serve-CU3bV4e0.js.map → serve-zbQKfx1E.js.map} +1 -1
  46. package/dist/{server-setup-DjHNoWhQ.js → server-setup-ClZdV33Q.js} +12 -12
  47. package/dist/{server-setup-DjHNoWhQ.js.map → server-setup-ClZdV33Q.js.map} +1 -1
  48. package/dist/{start-RJ2tOdL-.js → start-mnedD5cH.js} +3 -3
  49. package/dist/{start-RJ2tOdL-.js.map → start-mnedD5cH.js.map} +1 -1
  50. package/dist/{static-context-pack-DwC69_VA.js → static-context-pack-CtnBwHSd.js} +12 -11
  51. package/dist/static-context-pack-CtnBwHSd.js.map +1 -0
  52. package/dist/{workiq-tools-CQeCqmyX.js → workiq-tools-DL6rC4bP.js} +1 -1
  53. package/package.json +1 -1
  54. package/dist/ado-tools-aRld02_r.js +0 -1
  55. package/dist/copilot-discount-CHNQLYDJ.js.map +0 -1
  56. package/dist/engine-CtUZAPuu.js +0 -1
  57. package/dist/max-profile-contract-DLLTsSs2.js.map +0 -1
  58. package/dist/peer-mcp-personas-B1prNNMJ.js.map +0 -1
  59. package/dist/pi-CzDdGipf.js.map +0 -1
  60. package/dist/pi-memory-bridge-Dvj1T3e3.js.map +0 -1
  61. package/dist/static-context-pack-DwC69_VA.js.map +0 -1
@@ -1,13 +1,13 @@
1
- import { H as profileDescriptor, I as formatBalancedPrerequisiteFailure, S as enableFileLogging, U as resolveLaunchProfile, V as formatLocalPrerequisiteFailure, W as validateBalancedProfilePrerequisites, Y as validateLocalProfilePrerequisites, Z as runSelfUpdate, _ as sweepStalePiAgentMirrors, a as setupAndServe, c as PI_MIN_VERSION, d as meetsPiMinVersion, f as refreshPiInBackground, g as removeOwnPiAgentMirror, h as ensurePiAgentMirror, i as parseSharedArgs, l as ensurePiInstalled, m as updatePi, o as sharedServerArgs, p as resolvePiRegistry, q as validateCheapestProfilePrerequisites, r as getPiLaunchEnvVars, s as LAUNCH_SECRET_HEADER, u as getInstalledPiVersion, v as startKeepAwake, y as stopKeepAwake, z as formatCheapestPrerequisiteFailure } from "./server-setup-DjHNoWhQ.js";
1
+ import { H as profileDescriptor, I as formatBalancedPrerequisiteFailure, S as enableFileLogging, U as resolveLaunchProfile, V as formatLocalPrerequisiteFailure, W as validateBalancedProfilePrerequisites, Y as validateLocalProfilePrerequisites, Z as runSelfUpdate, _ as sweepStalePiAgentMirrors, a as setupAndServe, c as PI_MIN_VERSION, d as meetsPiMinVersion, f as refreshPiInBackground, g as removeOwnPiAgentMirror, h as ensurePiAgentMirror, i as parseSharedArgs, l as ensurePiInstalled, m as updatePi, o as sharedServerArgs, p as resolvePiRegistry, q as validateCheapestProfilePrerequisites, r as getPiLaunchEnvVars, s as LAUNCH_SECRET_HEADER, u as getInstalledPiVersion, v as startKeepAwake, y as stopKeepAwake, z as formatCheapestPrerequisiteFailure } from "./server-setup-ClZdV33Q.js";
2
2
  import { i as buildAicStatusHookCommand, n as AIC_STATUSLINE_DISABLE_ENV, t as AIC_LEDGER_ENV } from "./aic-statusline-settings-BKveu679.js";
3
3
  import { d as removeAicLedgerFile, f as sweepStaleAicLedgerFiles, n as aicSnapshot, o as formatAicExitSummary, t as aicLedgerPath } from "./aic-ledger-CeSXqTEE.js";
4
- import { n as formatDiscountedCostTable, t as discountedUsdForSnapshot } from "./copilot-discount-CHNQLYDJ.js";
4
+ import { n as formatDiscountedCostTable, t as discountedUsdForSnapshot } from "./copilot-discount-UXC6NQbN.js";
5
5
  import { r as resolveSelfInvocation } from "./self-invocation-DMUnXVGT.js";
6
6
  import { t as PATHS } from "./paths-CVEO8jEH.js";
7
- import { t as FRESH_CONSULT_CONTRACT } from "./claude-md-injection-C0EQfdJo.js";
8
- import { Bn as colbertDegradedWarning, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, Dt as artifactToolsEnabled, Gn as LOCAL_CONSULT_REDACTION_NOTE, Mn as provisionBrowserAssets, Nt as browserToolsEnabled, Qt as kustoToolsEnabled, Sn as unregisterLaunch, Tt as adoToolsEnabled, Vn as provisionAndIndexColbert, Wn as LOCAL_CONSULT_REDACTION_LINE, bn as registerLaunch, fn as configureLocalEgress, jt as browseAgentEnabled, pn as localBaseUrl, sn as workiqToolsEnabled } from "./peer-mcp-personas-B1prNNMJ.js";
9
- import { C as localContractFor, O as LOCAL_PROFILE_TIER_MODELS, S as local2AdvisorContract, _ as isBalancedFamily, b as isLocalFamily, f as balancedContractFor, h as consultIsLocalTransport, p as cheapestContractFor, v as isCheapestFamily, y as isCheaplocalProfile } from "./static-context-pack-DwC69_VA.js";
10
- import { i as launchChild, t as provisionToolbelt } from "./provision-DktDm-f0.js";
7
+ import { t as FRESH_CONSULT_CONTRACT } from "./claude-md-injection-Biq_Xhve.js";
8
+ import { Bn as colbertDegradedWarning, Bt as cloudAgentToolsEnabled, D as toolbeltEnabled, Dt as artifactToolsEnabled, Gn as LOCAL_CONSULT_REDACTION_NOTE, Mn as provisionBrowserAssets, Nt as browserToolsEnabled, Qt as kustoToolsEnabled, Sn as unregisterLaunch, Tt as adoToolsEnabled, Vn as provisionAndIndexColbert, Wn as LOCAL_CONSULT_REDACTION_LINE, bn as registerLaunch, fn as configureLocalEgress, jt as browseAgentEnabled, pn as localBaseUrl, sn as workiqToolsEnabled } from "./peer-mcp-personas-OWsSm6To.js";
9
+ import { C as localContractFor, O as LOCAL_PROFILE_TIER_MODELS, S as local2AdvisorContract, _ as isBalancedFamily, b as isLocalFamily, f as balancedContractFor, h as consultIsLocalTransport, p as cheapestContractFor, v as isCheapestFamily, y as isCheaplocalProfile } from "./static-context-pack-CtnBwHSd.js";
10
+ import { i as launchChild, t as provisionToolbelt } from "./provision-DPL8aGe2.js";
11
11
  import { t as state } from "./state-CCGDJ43X.js";
12
12
  import { t as getPackageVersion } from "./version-CTqwKr26.js";
13
13
  import { P as warmTreeSitterPool } from "./service-backend-Cdgz6WPx.js";
@@ -28,23 +28,25 @@ import process$1 from "node:process";
28
28
  * - gpt-5.6-sol: Default ≤ 272K ($4.00 in) vs Long > 272K ($8.00 in)
29
29
  * - gpt-6-sol: Default ≤ 272K ($2.00 in) vs Long > 272K ($4.00 in)
30
30
  * - gpt-6.1-sol: Default ≤ 272K ($2.00 in) vs Long > 272K ($4.00 in)
31
+ * - gpt-6.2-sol: Default ≤ 272K ($2.00 in) vs Long > 272K ($4.00 in)
31
32
  * - grok-4.6: Default ≤ 200K ($2.00 in) vs Long > 200K ($4.00 in)
32
33
  * - grok-4.7: Default ≤ 200K ($2.00 in) vs Long > 200K ($4.00 in)
33
34
  *
34
35
  * The live catalog carries no tier data (flat `billing.token_prices` +
35
36
  * single `limits.*` only), so this table is hardcoded by exact model id —
36
37
  * same precedent as `FALLBACK_TOKEN_PRICES`. Anything not listed here
37
- * runs at the 200K default window. LAST_VERIFIED 2026-10-21: the six
38
- * rows above were re-read from the billing doc, and the catalog input
39
- * prices for the two newest ids (`gpt-6.1-sol`, `grok-4.7`) were checked
40
- * against it the same day. Refresh the values (and the drift
41
- * expectations below) when the billing doc changes.
38
+ * runs at the 200K default window. LAST_VERIFIED 2026-11-20: `gpt-6.2-sol`
39
+ * was read from the billing doc (identical tier pair and prices to 6.1 Sol)
40
+ * and checked against the live catalog; the six earlier rows are the
41
+ * 2026-10-21 reading. Refresh the values (and the drift expectations
42
+ * below) when the billing doc changes.
42
43
  */
43
44
  const PI_TIER_THRESHOLDS = Object.freeze({
44
45
  "gpt-6-luna": 272e3,
45
46
  "gpt-5.6-sol": 272e3,
46
47
  "gpt-6-sol": 272e3,
47
48
  "gpt-6.1-sol": 272e3,
49
+ "gpt-6.2-sol": 272e3,
48
50
  "grok-4.6": 2e5,
49
51
  "grok-4.7": 2e5
50
52
  });
@@ -75,6 +77,7 @@ const EXPECTED_DEFAULT_INPUT_PER_1M = Object.freeze({
75
77
  "gpt-5.6-sol": 400,
76
78
  "gpt-6-sol": 200,
77
79
  "gpt-6.1-sol": 200,
80
+ "gpt-6.2-sol": 200,
78
81
  "grok-4.6": 200,
79
82
  "grok-4.7": 200
80
83
  });
@@ -465,6 +468,31 @@ function piThinkingLevelMapFor(efforts) {
465
468
  for (const level of PI_THINKING_LEVELS) map[level] = set.has(level) ? level : null;
466
469
  return map;
467
470
  }
471
+ /**
472
+ * Pi's own window for the LOCAL family (`-m local`, `-m local2`).
473
+ *
474
+ * 272K, not 200K, and deliberately NOT `LOCAL_PROFILE_LEAD_CONTEXT_TOKENS`:
475
+ * that constant is the *Claude Code client's* window, pinned at 200K by the
476
+ * seeded `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`, and nothing in this module can
477
+ * move it. Two clients, two windows, both true.
478
+ *
479
+ * The choice is policy, not measurement. Measured on the live endpoint this
480
+ * session: 105K–720K input is accepted verbatim, 730K+ is
481
+ * `400 prompt is too long`, so the real ceiling is ~720K and 272K sits at a
482
+ * 2.6× margin. 272K is also the Copilot Default-tier boundary the roster
483
+ * already uses (`PI_TIER_THRESHOLDS`), so every Pi profile in this repo now
484
+ * budgets against the same number instead of two conventions.
485
+ *
486
+ * Raising the window alone would make compaction WORSE, not better. Pi's
487
+ * clamp is `room = window − input − max(4096, 15% of input)`, and the
488
+ * summarization call's input is `trigger − keepRecentTokens`, not the trigger.
489
+ * Measured through Pi's own `clampMaxTokensToContext`, a 272K window only
490
+ * hands that call the full 65 536 once the trigger is at or under ~198.6K
491
+ * (reserve >= ~73.4K); at a 217 600 trigger it gets 43 736, and at 232 000 it
492
+ * gets 31 744 — today's truncating ceiling. The three constants move together
493
+ * or not at all.
494
+ */
495
+ const PI_LOCAL_CONTEXT_TOKENS = 272e3;
468
496
  /** Provider key used in models.json and agent `provider/model` references. */
469
497
  const PI_PROVIDER_NAME = "gh-router";
470
498
  const PI_MIN_VERSION_NOTE = `Requires Pi >= ${PI_MIN_VERSION} and Node >= 22.19.`;
@@ -583,7 +611,7 @@ function piOracleThinking(profileId) {
583
611
  /**
584
612
  * Advisor row. Cheapest-family launches carry one; `balanced` is advisor-free
585
613
  * by design and `local` mirrors that (no Advisor). `local2` is the one local
586
- * profile with an Advisor, and it is Copilot-served (`gpt-6.1-sol`) — the
614
+ * profile with an Advisor, and it is Copilot-served (`gpt-6.2-sol`) — the
587
615
  * Advisor always runs on a real Copilot model, never on the local endpoint.
588
616
  */
589
617
  function piAdvisorModel(profileId) {
@@ -795,7 +823,7 @@ function buildPiModelsJson(opts) {
795
823
  name: id,
796
824
  reasoning: true,
797
825
  input: entry?.vision === false ? ["text"] : ["text", "image"],
798
- contextWindow: piContextWindowFor(id, entry?.maxContextTokens),
826
+ contextWindow: local && isLocalTier ? PI_LOCAL_CONTEXT_TOKENS : piContextWindowFor(id, entry?.maxContextTokens),
799
827
  maxTokens,
800
828
  ...entry?.cost ? { cost: entry.cost } : {},
801
829
  ...isLocalTier && localHeaders ? { headers: localHeaders } : {},
@@ -808,7 +836,7 @@ function buildPiModelsJson(opts) {
808
836
  } } };
809
837
  }
810
838
  /**
811
- * Local-family compaction reserve: 80% of the 200K window.
839
+ * Local-family compaction reserve: a flat 81 600 tokens for the 272K window.
812
840
  *
813
841
  * The Copilot derivation below optimises for a price cliff; the local
814
842
  * endpoint has none, so the binding constraint there is the summarization
@@ -820,13 +848,38 @@ function buildPiModelsJson(opts) {
820
848
  * `getSummarizationFailure` refuses the truncated summary
821
849
  * (`generation hit the token cap and the summary is incomplete`).
822
850
  *
823
- * Triggering at 160K instead of Pi's 183K default leaves the clamp enough
824
- * room that the 32768 budget below is reachable: at a 160K estimate
825
- * `clampMaxTokensToContext` yields 32768, so the provider sends
826
- * `budget = min(32768, 32768 − 1024)`. Raised reserves alone are not enough
827
- * (the budget, not the trigger, is the ceiling) — both halves ship together.
828
- */
829
- const PI_LOCAL_COMPACTION_RESERVE_TOKENS = 4e4;
851
+ * The reserve is **flat**, not a ratio, so it is the half of this pairing
852
+ * that has to be recomputed whenever the window moves. 272 000 − 81 600 =
853
+ * 190 400 is the trigger (70% of the window, vs the 160K/80% it replaces —
854
+ * the absolute amount of conversation before compaction goes UP).
855
+ *
856
+ * The number is derived, not chosen. Pi clamps the summarization request to
857
+ * `room = window − input − max(4096, 15% · input)` and the summarizer sees
858
+ * `trigger − keepRecentTokens` (20 000). For the 65 536 budget below to
859
+ * survive that clamp, that input must stay at or under 178 642
860
+ * (`(272000 − 65536 − 1024) / 1.15` rounds down one token short). Read back
861
+ * as a reserve:
862
+ *
863
+ * | reserve | trigger | summarizer input | `budget_tokens` |
864
+ * |---------|---------|------------------|-----------------|
865
+ * | 40 000 | 232 000 | 212 000 | 31 744 |
866
+ * | 54 400 | 217 600 | 197 600 | 43 736 |
867
+ * | 73 357 | 198 643 | 178 643 | 65 535 |
868
+ * | 81 600 | 190 400 | 170 400 | 65 536 |
869
+ *
870
+ * 73 357 is the exact boundary and has zero slack: one token past it and the
871
+ * budget starts eroding, and a history that overshoots the trigger by 5%
872
+ * would get 55 264. 81 600 keeps ~8K of headroom, so that same 5% overshoot
873
+ * still receives 65 218. Ship the number with the slack, not the boundary.
874
+ *
875
+ * Both halves ship together: the budget is what the endpoint serves as
876
+ * `budget_tokens`, and the reserve is what keeps the clamp from eating it.
877
+ * The two rows above 40 000 are the ones that matter — a raised window with
878
+ * the OLD reserve leaves the summarizer at 31 744, and even the plan's
879
+ * original 54 400 caps it at 43 736, i.e. still short of the budget it asks
880
+ * for, from a launch that claims to have doubled its headroom.
881
+ */
882
+ const PI_LOCAL_COMPACTION_RESERVE_TOKENS = 81600;
830
883
  /**
831
884
  * Thinking budgets for LOCAL launches only.
832
885
  *
@@ -835,13 +888,23 @@ const PI_LOCAL_COMPACTION_RESERVE_TOKENS = 4e4;
835
888
  * carry no `thinkingLevelMap`, so `clampReasoning` walks `max`/`xhigh` down
836
889
  * to `high`). 16384 is the ceiling that truncates real summaries — 5 of the
837
890
  * 19 compactions in the reference session reported output above it, up to
838
- * 21643. 32768 roughly doubles the summarization headroom and costs nothing
839
- * on local inference.
891
+ * 21643. 65536 quadruples the summarization headroom and costs nothing on
892
+ * local inference.
893
+ *
894
+ * The doubling from 32768 is not a reflex: the endpoint serves the request as
895
+ * `budget_tokens`, and at the 190 400-token trigger the summarizer sees
896
+ * 170 400 (`trigger − keepRecentTokens`), where the clamp still affords the
897
+ * full 65 536 (measured: +5% historical overshoot → 65 218). A 32 768 budget
898
+ * would be the tight half of what the window now allows, and at the old
899
+ * 40 000 reserve the second clamp pinned the request back to 31 744 — the
900
+ * truncating ceiling this constant exists to remove. Both numbers are
901
+ * measured against Pi's own `clampMaxTokensToContext` in
902
+ * `tests/pi-models-settings.test.ts` rather than asserted here.
840
903
  *
841
904
  * Deliberately NOT emitted for Copilot profiles: there the thinking budget
842
905
  * is billed reasoning tokens on every turn, not a free local decode.
843
906
  */
844
- const PI_LOCAL_THINKING_BUDGETS = Object.freeze({ high: 32768 });
907
+ const PI_LOCAL_THINKING_BUDGETS = Object.freeze({ high: 65536 });
845
908
  /**
846
909
  * Derive Pi compaction budgets from live catalog `max_prompt_tokens`
847
910
  * ceilings AND each model's cheap-tier window — the Pi-native analogue
@@ -859,8 +922,8 @@ const PI_LOCAL_THINKING_BUDGETS = Object.freeze({ high: 32768 });
859
922
  * `PI_LOCAL_COMPACTION_RESERVE_TOKENS`): the local catalog carries no
860
923
  * `max_prompt_tokens`, so the price-cliff derivation has nothing to read,
861
924
  * and the constraint that matters is the endpoint's thinking-budget
862
- * ceiling. Every local row is the same 200K window, so one flat reserve
863
- * covers the whole roster.
925
+ * ceiling. Every local row is the same 272K window (see
926
+ * `PI_LOCAL_CONTEXT_TOKENS`), so one flat reserve covers the whole roster.
864
927
  */
865
928
  function derivePiCompactionSettings(catalog, modelIds, profileId) {
866
929
  const FALLBACK = {
@@ -1263,7 +1326,8 @@ function roleDescription(profileId, role) {
1263
1326
  const consultNote = piOracleEnabled(profileId) ? " May consult the oracle subagent when a decision feels risky." : "";
1264
1327
  if (role.name === "Explore") return "Fast read-only recon: locate code, answer evidence questions, return compressed context.";
1265
1328
  if (role.name === "General-Purpose") return `${isBalancedFamily(profileId) ? "General implementation and follow-through on scoped tasks. May hand the result to reviewer only when the change alters behavior." : "General implementation and follow-through on scoped tasks. May hand the result to reviewer for assessment."}${consultNote}`;
1266
- return isBalancedFamily(profileId) ? "Behavior-changing review only: assess a change, narrow scope with search first, delegate targeted discovery to Explore rather than sweeping the repo." : "Code review and assessment, including reproducing and root-causing a failure.";
1329
+ if (isBalancedFamily(profileId)) return "Behavior-changing review only: assess a change, narrow scope with search first, delegate targeted discovery to Explore rather than sweeping the repo.";
1330
+ return piAdvisorModel(profileId) ? "Code review and assessment, including reproducing and root-causing a failure. May consult its advisor subagent on uncertainty it cannot settle by evidence." : "Code review and assessment, including reproducing and root-causing a failure.";
1267
1331
  }
1268
1332
  /**
1269
1333
  * Build `.md` agent definitions for the mode's native roster, in the
@@ -1281,17 +1345,32 @@ function roleDescription(profileId, role) {
1281
1345
  * which is why `advisor` ships as its own file on cheapest.
1282
1346
  * Shadowing deliberately does NOT inherit `contact_supervisor` on
1283
1347
  * reviewer (leaf) or `defaultContext: fork` on oracle (fresh keeps
1284
- * the cold-start consultant contract).
1348
+ * the cold-start consultant contract). Note that a strict `tools`
1349
+ * allowlist is no longer the whole story for core tools: a live
1350
+ * cheapest reviewer run, whose file never lists `contact_supervisor`,
1351
+ * hit that tool anyway (`contact_supervisor` in its transcript), so the
1352
+ * runtime does hand core slots to a background child regardless of the
1353
+ * allowlist. Omitting it is still the right emission — the differentiator
1354
+ * is the body: our reviewer's prompt never asks the supervisor for
1355
+ * anything, which is what kept the paging noise away.
1285
1356
  * - `allowedAgents` only narrows an existing nesting grant, so every
1286
1357
  * delegating agent also sets `allowNestedSubagents: true` and lists
1287
- * `subagent` in `tools`. Depth reaches 3 on balanced
1358
+ * `subagent` in `tools`. Two edges exist: General-Purpose →
1359
+ * reviewer/oracle, and the reviewer → its consultant (balanced:
1360
+ * Explore; Advisor-bearing profiles: `advisor`, the cheapest-family
1361
+ * protege grant that mirrors the Claude path's capped reviewer
1362
+ * rounds). Depth reaches 3 on balanced
1288
1363
  * (lead → General-Purpose → reviewer → Explore), covered by
1289
1364
  * `PI_SUBAGENT_MAX_DEPTH=3` in the launch env (default guard is 2).
1290
- * - `async: false` on every file: foreground children run in-process
1291
- * with the parent's full tool registry. The detached background
1292
- * runner demonstrably drops read/bash from its registry (observed
1293
- * live as "requested unavailable child tools: [read, bash]"),
1294
- * failing every strict-allowlist child it touches.
1365
+ * - NO `async` key on any file, deliberately. pi-subagents runs a
1366
+ * single-agent launch in the background when the call omits `async`
1367
+ * (`asyncByDefault`, default true), and background children are the
1368
+ * ones that DO load the parent's ambient extensions
1369
+ * (`runs/shared/tool-availability.js`); foreground children are
1370
+ * in-process and never load them. Emitting `async: false` froze the
1371
+ * opposite policy and made parallel children impossible. Per-call
1372
+ * `async: false` still blocks the parent for one launch, and a host
1373
+ * `subagents.asyncByDefault` still wins over the default.
1295
1374
  * - Deliberately NO `output:`/`defaultReads`/`defaultProgress` file
1296
1375
  * bindings: single-shot launches resolve relative outputs under
1297
1376
  * per-run artifact dirs while `defaultReads` resolves against the
@@ -1309,10 +1388,12 @@ function roleDescription(profileId, role) {
1309
1388
  */
1310
1389
  function buildPiAgentFiles(profileId) {
1311
1390
  const files = {};
1391
+ const advisor = piAdvisorModel(profileId);
1312
1392
  for (const role of piNativeRoles(profileId)) {
1313
1393
  const isImplementer = role.name === "General-Purpose";
1314
1394
  const isReviewer = role.name === "reviewer";
1315
- const tools = isImplementer ? "read, grep, find, ls, bash, edit, write, subagent, contact_supervisor" : isReviewer ? isBalancedFamily(profileId) ? "read, grep, find, ls, watchdog_diff, subagent" : "read, grep, find, ls, watchdog_diff" : "read, grep, find, ls, bash";
1395
+ const reviewerDelegates = isBalancedFamily(profileId) || advisor !== void 0;
1396
+ const tools = isImplementer ? "read, grep, find, ls, bash, edit, write, subagent, contact_supervisor" : isReviewer ? reviewerDelegates ? "read, grep, find, ls, watchdog_diff, subagent" : "read, grep, find, ls, watchdog_diff" : "read, grep, find, ls, bash";
1316
1397
  const lines = [
1317
1398
  "---",
1318
1399
  `name: ${role.name}`,
@@ -1321,7 +1402,6 @@ function buildPiAgentFiles(profileId) {
1321
1402
  `model: ${PI_PROVIDER_NAME}/${role.model}`,
1322
1403
  `thinking: ${role.thinking}`,
1323
1404
  "advertise: true",
1324
- "async: false",
1325
1405
  "systemPromptMode: replace",
1326
1406
  "inheritProjectContext: true",
1327
1407
  "defaultContext: fresh"
@@ -1329,10 +1409,13 @@ function buildPiAgentFiles(profileId) {
1329
1409
  if (role.name === "Explore") lines.push("aliases: scout");
1330
1410
  if (isImplementer) lines.push("aliases: worker, developer, coder, implementer, develop", "acceptanceRole: writer", "allowNestedSubagents: true", piOracleEnabled(profileId) ? "allowedAgents: reviewer, oracle" : "allowedAgents: reviewer");
1331
1411
  if (isBalancedFamily(profileId) && isReviewer) lines.push("allowNestedSubagents: true", "allowedAgents: Explore");
1412
+ if (advisor && isReviewer) lines.push("allowNestedSubagents: true", "allowedAgents: advisor");
1332
1413
  lines.push("---", "");
1333
1414
  if (role.name === "Explore") lines.push("You are a read-only scout. Never modify files.", "Use bash only for non-interactive inspection.", "Search first, read second: return the smallest sufficient evidence — entry points,", "key types and functions, data flow, files likely to need changes, constraints and", "open questions — with exact file paths and line ranges.");
1334
- else if (isReviewer) lines.push("You are a disciplined review subagent. Inspect the actual change; verify from code,", "tests, and docs — never guess. Cover intent match, correctness and edge cases,", "test coverage, side effects, and minimality.", "Report findings with file:line evidence ranked P0 (blocker) / P1 (should fix) / P2 (nit),", "ending with one of: Merge verdict: BLOCK, Merge verdict: OK, Merge verdict: OK with notes.", "You have no shell: cite the test commands for the lead to run rather than executing them.", "Do not rewrite code outside small, clearly-marked suggestions.");
1335
- else lines.push("You are the single writer thread. Execute the assigned task with narrow, coherent edits;", "the lead remains the decision authority. Work from the brief's pasted context,", "then implement minimally and verify by running the relevant tests.", "If the work reveals an unapproved decision you cannot safely resolve, stop and escalate", "instead of guessing; never leave placeholders or TODOs.", "Hand behavior-changing results to reviewer when asked; otherwise summarize the diff,", "validation, risks, and next step.");
1415
+ else if (isReviewer) {
1416
+ lines.push("You are a disciplined review subagent. Inspect the actual change; verify from code,", "tests, and docs — never guess. Cover intent match, correctness and edge cases,", "test coverage, side effects, and minimality.", "Report findings with file:line evidence ranked P0 (blocker) / P1 (should fix) / P2 (nit),", "ending with one of: Merge verdict: BLOCK, Merge verdict: OK, Merge verdict: OK with notes.", "You have no shell: cite the test commands for the lead to run rather than executing them.", "Do not rewrite code outside small, clearly-marked suggestions.");
1417
+ if (advisor) lines.push("You may consult the `advisor` subagent, the profile's own consultant,", "on the Advisor contract the lead uses: it sees only the brief you write.", "You own the verdict; the advisor is counsel, never authority: it never", "approves, vetoes, or decides for you.", "Budget: at most 5 advisor rounds per review — one round is one back-and-forth", "exchange. Spend them only on consequential uncertainty that code, builds, or tests", "cannot settle: a changed assumption, conflicting evidence, an approach that will", "not converge, or a severity call with merge-blocking consequences. Never consult for", "routine verification, progress narration, or completion ritual — run the check", "yourself. State the question, your evidence with file:line citations, the credible", "alternatives, and what evidence would change your verdict. If the advisor disagrees,", "evaluate on the merits: adopt what is right with a one-line reason, defend what you", "verified with evidence, and record the disagreement in your report. Do not delegate", "to any other agent.");
1418
+ } else lines.push("You are the single writer thread. Execute the assigned task with narrow, coherent edits;", "the lead remains the decision authority. Work from the brief's pasted context,", "then implement minimally and verify by running the relevant tests.", "If the work reveals an unapproved decision you cannot safely resolve, stop and escalate", "instead of guessing; never leave placeholders or TODOs.", "Hand behavior-changing results to reviewer when asked; otherwise summarize the diff,", "validation, risks, and next step.");
1336
1419
  files[`agents/${agentFileName(role.name)}`] = `${lines.join("\n")}\n`;
1337
1420
  }
1338
1421
  const oracleModel = piOracleModel(profileId);
@@ -1345,7 +1428,6 @@ function buildPiAgentFiles(profileId) {
1345
1428
  `model: ${PI_PROVIDER_NAME}/${oracleModel}`,
1346
1429
  `thinking: ${piOracleThinking(profileId)}`,
1347
1430
  "advertise: true",
1348
- "async: false",
1349
1431
  "systemPromptMode: replace",
1350
1432
  "inheritProjectContext: true",
1351
1433
  "defaultContext: fresh",
@@ -1361,7 +1443,6 @@ function buildPiAgentFiles(profileId) {
1361
1443
  ].join("\n");
1362
1444
  files[`agents/${agentFileName("oracle")}`] = `${oracle}\n`;
1363
1445
  }
1364
- const advisor = piAdvisorModel(profileId);
1365
1446
  if (advisor) {
1366
1447
  const body = [
1367
1448
  "---",
@@ -1371,7 +1452,6 @@ function buildPiAgentFiles(profileId) {
1371
1452
  `model: ${PI_PROVIDER_NAME}/${advisor.model}`,
1372
1453
  `thinking: ${advisor.thinking}`,
1373
1454
  "advertise: true",
1374
- "async: false",
1375
1455
  "systemPromptMode: replace",
1376
1456
  "inheritProjectContext: true",
1377
1457
  "defaultContext: fresh",
@@ -1406,11 +1486,21 @@ function buildPiLaunchCard(opts) {
1406
1486
  opts.copilotVersion ? `copilot chat ${opts.copilotVersion}` : void 0,
1407
1487
  opts.vsCodeVersion ? `vscode ${opts.vsCodeVersion}` : void 0
1408
1488
  ].filter((part) => typeof part === "string" && part.length > 0);
1409
- return [
1489
+ const lines = [
1410
1490
  `github-router v${opts.version} · pi (${opts.profileId})`,
1411
1491
  ` ${identity.join(" · ")}`,
1412
1492
  ` lead ${opts.lead} · ${opts.modelCount} models · ${surface.join(" ")} · ${opts.serverUrl}`
1413
- ].join("\n");
1493
+ ];
1494
+ const foreign = opts.foreign;
1495
+ if (foreign) {
1496
+ const parts = [`${foreign.agents} foreign agents (lazy)`];
1497
+ if (foreign.prompts > 0) parts.push(`${foreign.prompts} prompts`);
1498
+ if (foreign.skills > 0) parts.push(`${foreign.skills} skills`);
1499
+ lines.push(` foreign: ${parts.join(" · ")}`);
1500
+ if (foreign.renamed.length > 0) lines.push(` renamed ${foreign.renamed.map((r) => `${r.from} → ${r.to}`).join(", ")}`);
1501
+ if (foreign.skipped.length > 0) lines.push(` skipped ${foreign.skipped.map((s) => s.name).join(", ")} (name taken by gh-router)`);
1502
+ } else if (opts.foreignAvailable !== void 0 && opts.foreignAvailable > 0) lines.push(` foreign: ${opts.foreignAvailable} agent definition(s) found, not bridged · add --foreign`);
1503
+ return lines.join("\n");
1414
1504
  }
1415
1505
  /**
1416
1506
  * Short operating digest appended to APPEND_SYSTEM.md (prompt-cache-stable).
@@ -1429,7 +1519,7 @@ function buildPiAppendSystem(profileId, opts = {}) {
1429
1519
  ];
1430
1520
  if (peers) {
1431
1521
  const oracle = piOracleEnabled(profileId);
1432
- lines.push(`- Delegate FREELY to Explore for discovery and General-Purpose for scoped work.`, `- Call subagent directly (agent + task); save workflows for genuinely parallel fanout.`, isBalancedFamily(profileId) ? `- Send work to reviewer ONLY when the change alters behavior.` : `- Send finished work to reviewer for assessment.`);
1522
+ lines.push(`- Delegate FREELY to Explore for discovery and General-Purpose for scoped work.`, `- Call subagent directly (agent + task). Children run in the background by default, so fan out independent work in one turn and collect the results; pass \`async: false\` only when you must block on that launch.`, isBalancedFamily(profileId) ? `- Send work to reviewer ONLY when the change alters behavior.` : `- Send finished work to reviewer for assessment.`);
1433
1523
  if (oracle) {
1434
1524
  lines.push(`- Ask oracle for a second opinion when the decision itself feels risky.`, advisor ? `- Review the final plan with advisor (advisory) before presenting it.` : `- There is no advisor in this mode: oracle is the only consultant.`, `- Verify, don't vote: consultant verdicts never substitute for running the tests.`);
1435
1525
  if (consultIsLocalTransport(profileId)) lines.push(`- ${LOCAL_CONSULT_REDACTION_LINE}`);
@@ -2458,6 +2548,159 @@ function buildPiStatuslineFooterSection() {
2458
2548
  ];
2459
2549
  }
2460
2550
  /**
2551
+ * Pinned pi-subagents event contract. The router cannot import the package, so
2552
+ * the event NAME and the request shape are literals here, exactly as the
2553
+ * upstream module defines them (`runtime-agent-events.js`:
2554
+ * `RUNTIME_AGENT_REGISTER_EVENT`, version 1). A version bump upstream leaves
2555
+ * this registration unanswered and the extension reports it — never a crash.
2556
+ */
2557
+ const PI_SUBAGENTS_REGISTER_EVENT = "pi-subagents:runtime-agent-register:v1";
2558
+ const PI_SUBAGENTS_REGISTER_VERSION = 1;
2559
+ /**
2560
+ * Foreign Claude/Copilot agents: one registry entry each, announced in a
2561
+ * compact prompt section, loaded on demand.
2562
+ *
2563
+ * Three seams, and the reasons each is the shape it is:
2564
+ *
2565
+ * 1. **Registration goes through the documented event**, not through pi's
2566
+ * `registerAgent` (there is none) and not through agent FILES. A file in
2567
+ * `<mirror>/agents/` would be a configured agent — a second identity that
2568
+ * `mergeRuntimeAgents` validates on EVERY discovery, so one collision breaks
2569
+ * every `subagent` call in the process. A runtime registration fails only
2570
+ * its own call, and can be removed at runtime.
2571
+ * 2. **The index is a prompt SECTION**, not a chat message. A custom message
2572
+ * is re-emitted on every run and reaches the model as a user turn; sections
2573
+ * are diff-patched by Pi (`diffSystemPromptSections`), so the index is sent
2574
+ * once and stays cache-stable.
2575
+ * 3. **The `tool_result` net is the backstop for what reservation cannot see**
2576
+ * (a user adding a colliding agent mid-session). It disposes exactly the
2577
+ * offender named in the registry's own error and lets the model retry;
2578
+ * every other error is passed through untouched.
2579
+ *
2580
+ * Fail-open everywhere: a Pi build without these events, a pi-subagents that
2581
+ * is not installed, or a rejected registration all degrade to "the foreign
2582
+ * agents are not available", never to a broken session.
2583
+ */
2584
+ function buildPiForeignAgentsSection(foreign) {
2585
+ return [
2586
+ ` // ---- foreign agents: Claude/Copilot, lazy, collision-reserved ----`,
2587
+ ` // No files: each spec is a RUNTIME agent in pi-subagents, so it participates`,
2588
+ ` // in discovery without becoming a configured identity every subagent call`,
2589
+ ` // re-validates. The index below is the only always-on context.`,
2590
+ ` {`,
2591
+ ` let FOREIGN = [];`,
2592
+ ` try { FOREIGN = ${JSON.stringify(foreign.agents.map((a) => ({
2593
+ name: a.name,
2594
+ description: a.description,
2595
+ body: a.body
2596
+ })))}; } catch { FOREIGN = []; }`,
2597
+ ` const FOREIGN_INDEX = ${JSON.stringify(foreign.index)};`,
2598
+ ` const FOREIGN_EVENT = ${JSON.stringify(PI_SUBAGENTS_REGISTER_EVENT)};`,
2599
+ ` const FOREIGN_VERSION = ${PI_SUBAGENTS_REGISTER_VERSION};`,
2600
+ ` const registrations = new Map();`,
2601
+ ` const failures = [];`,
2602
+ ` // Name of the offending runtime agent, from the registry's own throw text.`,
2603
+ ` // Deliberately parsed rather than inferred: the net must never dispose a`,
2604
+ ` // registration that is not the one the registry just named.`,
2605
+ ` const COLLISION_RE = /^Runtime agent '([^']+)' collides with configured agent/;`,
2606
+ ` function registerAll(ctx) {`,
2607
+ ` for (const spec of FOREIGN) {`,
2608
+ ` try {`,
2609
+ ` // Re-registering the same name throws ('collides with runtime agent'),`,
2610
+ ` // so a prior handle for this name is disposed first. Load-bearing on`,
2611
+ ` // /reload: the extension instance is recreated but the pi-subagents`,
2612
+ ` // registry it talks to is not necessarily torn down first.`,
2613
+ ` const prior = registrations.get(spec.name);`,
2614
+ ` if (prior) { try { prior.dispose(); } catch {} registrations.delete(spec.name); }`,
2615
+ ` const request: any = { version: FOREIGN_VERSION, name: spec.name, definition: {`,
2616
+ ` description: spec.description,`,
2617
+ ` systemPrompt: spec.body,`,
2618
+ ` systemPromptMode: "replace",`,
2619
+ ` inheritProjectContext: true,`,
2620
+ ` } };`,
2621
+ ` try { pi.events.emit(FOREIGN_EVENT, request); } catch {}`,
2622
+ ` const result = request.result;`,
2623
+ ` if (result && result.ok === true && result.registration && typeof result.registration.dispose === "function") {`,
2624
+ ` registrations.set(spec.name, result.registration);`,
2625
+ ` continue;`,
2626
+ ` }`,
2627
+ ` const reason = result && result.ok === false && result.error`,
2628
+ ` ? String(result.error.message || result.error)`,
2629
+ ` : "pi-subagents did not answer";`,
2630
+ ` failures.push(spec.name + ": " + reason);`,
2631
+ ` } catch (error) {`,
2632
+ ` failures.push(spec.name + ": " + String(error && error.message ? error.message : error));`,
2633
+ ` }`,
2634
+ ` }`,
2635
+ ` if (failures.length > 0 && ctx && ctx.ui && typeof ctx.ui.notify === "function") {`,
2636
+ ` try { ctx.ui.notify("gh-router: " + failures.length + " foreign agent(s) not bridged (" + failures.slice(0, 3).join("; ") + ")", "warning"); } catch {}`,
2637
+ ` }`,
2638
+ ` }`,
2639
+ ` pi.on("session_start", async (event, ctx) => {`,
2640
+ ` // Children must not pay for the roster: every subagent process loads`,
2641
+ ` // this extension too (background runners mark themselves, foreground`,
2642
+ ` // children load no ambient extensions). Registration there would also`,
2643
+ ` // fight the parent's names in a second registry.`,
2644
+ ` if (process.env.PI_SUBAGENT_CHILD === "1") return;`,
2645
+ ` registerAll(ctx);`,
2646
+ ` });`,
2647
+ ` pi.on("session_shutdown", async () => {`,
2648
+ ` // Load-bearing, not hygiene: a stale registration outliving this`,
2649
+ ` // instance makes the next session's registration of the same name`,
2650
+ ` // throw 'collides with runtime agent'.`,
2651
+ ` for (const registration of registrations.values()) {`,
2652
+ ` try { registration.dispose(); } catch {}`,
2653
+ ` }`,
2654
+ ` registrations.clear();`,
2655
+ ` });`,
2656
+ ` // Self-healing net: a colliding foreign agent fails EVERY subagent call in`,
2657
+ ` // the process, so leaving it registered until the user quits is not an`,
2658
+ ` // option. Only a registration this extension created is ever disposed,`,
2659
+ ` // keyed by the name the registry itself reported.`,
2660
+ ` pi.on("tool_result", async (event) => {`,
2661
+ ` try {`,
2662
+ ` if (!event || event.toolName !== "subagent" || event.isError !== true) return undefined;`,
2663
+ ` const text = Array.isArray(event.content)`,
2664
+ ` ? event.content.map((c) => (c && typeof c.text === "string" ? c.text : "")).join("\\n")`,
2665
+ ` : "";`,
2666
+ ` const match = COLLISION_RE.exec(text);`,
2667
+ ` if (!match) return undefined;`,
2668
+ ` const offender = match[1];`,
2669
+ ` // Reset lastIndex for the shared regex: a stale index would make the`,
2670
+ ` // next match start mid-string and silently miss.`,
2671
+ ` COLLISION_RE.lastIndex = 0;`,
2672
+ ` const registration = registrations.get(offender);`,
2673
+ ` if (!registration) return undefined;`,
2674
+ ` try { registration.dispose(); } catch {}`,
2675
+ ` registrations.delete(offender);`,
2676
+ ` return {`,
2677
+ ` content: [{ type: "text", text: "Foreign agent '" + offender + "' collided with an agent configured in this session and was unregistered. Retry the call, or use a roster agent." }],`,
2678
+ ` isError: false,`,
2679
+ ` };`,
2680
+ ` } catch {`,
2681
+ ` return undefined;`,
2682
+ ` }`,
2683
+ ` });`,
2684
+ ` // The compact index, as a system-prompt section. Skipped in children`,
2685
+ ` // (they never see the roster) and when nothing was bridged.`,
2686
+ ` if (FOREIGN_INDEX) {`,
2687
+ ` pi.on("before_agent_start", async (event) => {`,
2688
+ ` try {`,
2689
+ ` if (process.env.PI_SUBAGENT_CHILD === "1") return undefined;`,
2690
+ ` const options = event && event.systemPromptOptions;`,
2691
+ ` if (!options || typeof options !== "object") return undefined;`,
2692
+ ` if (!options.sections || typeof options.sections !== "object") options.sections = {};`,
2693
+ ` options.sections.foreign_agents = FOREIGN_INDEX;`,
2694
+ ` return undefined;`,
2695
+ ` } catch {`,
2696
+ ` return undefined;`,
2697
+ ` }`,
2698
+ ` });`,
2699
+ ` }`,
2700
+ ` }`
2701
+ ];
2702
+ }
2703
+ /**
2461
2704
  * Memory-bridge section for the generated extension: path-scoped rules
2462
2705
  * lazy-attach on `read/edit/write` tool results (once per rule per
2463
2706
  * session, mirroring `pi-code/claude-rules.ts`), plus `/memory` (bridge
@@ -2601,6 +2844,7 @@ function buildPiExtensionSource(opts) {
2601
2844
  ``
2602
2845
  ] : [], `export default function (pi) {`);
2603
2846
  if (opts.bridge && opts.bridge.scopedRules.length + opts.bridge.stats.staticFiles > 0) lines.push(...buildPiMemoryBridgeSection(opts.bridge));
2847
+ if (opts.foreign && opts.foreign.agents.length + opts.foreign.index.length > 0) lines.push(...buildPiForeignAgentsSection(opts.foreign));
2604
2848
  lines.push(...buildPiStatuslineFooterSection(), ...buildPiPlanModeSection(), ` // Route compaction summaries to the mode's cheap capable model;`, ` // ALWAYS fall back to Pi native (return undefined) on any failure.`, ` pi.on("session_before_compact", async (event) => {`, ` try {`, ` const preparation = event.preparation;`, ` if (!preparation || !Array.isArray(preparation.messagesToSummarize)) return undefined;`, ` return undefined; // v1: observe only; native pipeline stays authoritative.`, ` } catch {`, ` return undefined;`, ` }`, ` });`, ...promptBrief ? [
2605
2849
  ` // Cheapest-profile execution brief, injected ABOVE the model's turn.`,
2606
2850
  ` // Produced server-side; this only relays the prompt and re-emits the`,
@@ -2736,9 +2980,10 @@ function buildPiSkills(opts) {
2736
2980
  "into the `General-Purpose` brief to implement, `reviewer` to check,",
2737
2981
  "`General-Purpose` to apply feedback. Keep delegated tasks",
2738
2982
  "scoped with file:line evidence on return.",
2739
- "Call `subagent` directly (agent + task). Reserve `workflowScript`",
2740
- "workflows for genuinely parallel or scripted multi-step fanout —",
2741
- "our agents run foreground and background runs add spawn overhead.",
2983
+ "Call `subagent` directly (agent + task). Independent children run in",
2984
+ "the background by default, so fan them out in one turn and collect their",
2985
+ "results; pass `async: false` only when you must block on that launch.",
2986
+ "Reserve `workflowScript` workflows for scripted multi-step fanout.",
2742
2987
  "After any subagent work completes, always write the final answer",
2743
2988
  "yourself; never end on tool output or completion notices alone.",
2744
2989
  isBalancedFamily(opts.profileId) ? "Send work to reviewer ONLY when the change alters behavior." : "Send finished work to reviewer for assessment."
@@ -3147,6 +3392,11 @@ const piArgs = {
3147
3392
  type: "boolean",
3148
3393
  default: true,
3149
3394
  description: "Bridge Copilot (.github/copilot-instructions.md, .github/instructions/*.instructions.md) and Claude (.claude/rules/, .claude/CLAUDE.md, ~/.claude/CLAUDE.md) memory into Pi. Static repo-wide slice synthesizes into the mirror AGENTS.md; path-scoped rules lazy-attach. Set to false (--no-memory-bridge) for Pi-native discovery only."
3395
+ },
3396
+ foreign: {
3397
+ type: "boolean",
3398
+ default: false,
3399
+ description: "Bridge the project's and your Claude Code and Copilot artifacts: .claude/skills + .github/skills + .copilot/skills as Pi skills, .claude/commands + .github/prompts as prompt shortcuts, and .claude/agents + .github/agents as Pi subagents announced in one compact index and loaded on demand. Authored names are kept; a name already taken by the router, a pi-subagents builtin or your own agent/skill/command is renamed (skills, prompts) or reported (agents) rather than overwritten. Foreign `model:` is ignored — every bridged agent runs on the lead model. Off by default."
3150
3400
  }
3151
3401
  };
3152
3402
  /**
@@ -3304,6 +3554,7 @@ const pi = defineCommand({
3304
3554
  }
3305
3555
  const peersEnabled = args["peers"] !== false;
3306
3556
  const sweEnabled = args["swe"] === true;
3557
+ const foreignEnabled = args["foreign"] === true;
3307
3558
  const helpersEnabled = args["helpers"] !== false;
3308
3559
  const uiEnabled = args["ui"] !== false;
3309
3560
  const searchEnabled = parsed.searchEnabled || process$1.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
@@ -3339,6 +3590,8 @@ const pi = defineCommand({
3339
3590
  }
3340
3591
  enableFileLogging();
3341
3592
  let packagesForCache = [];
3593
+ let foreignAvailable;
3594
+ let foreignStats;
3342
3595
  const launchSecret = randomBytes(32).toString("hex");
3343
3596
  try {
3344
3597
  const catalog = state.models?.data.map((m) => {
@@ -3407,7 +3660,7 @@ const pi = defineCommand({
3407
3660
  if (!bridgeDisabled) {
3408
3661
  const passthrough = collectPiPassthroughArgs(rawArgs, piArgs);
3409
3662
  if (!(passthrough.includes("--no-context-files") || passthrough.includes("-nc"))) try {
3410
- const { collectBridgeInputs } = await import("./pi-memory-bridge-Dvj1T3e3.js");
3663
+ const { collectBridgeInputs } = await import("./pi-memory-bridge-Bp9AnYw9.js");
3411
3664
  const collected = await collectBridgeInputs(process$1.cwd());
3412
3665
  bridgeStats = {
3413
3666
  staticFiles: collected.copilotInstructions.length + collected.unscopedRules.length + collected.userGlobal.length,
@@ -3421,12 +3674,95 @@ const pi = defineCommand({
3421
3674
  consola.debug("Pi memory bridge collection skipped:", err);
3422
3675
  }
3423
3676
  }
3677
+ const routerAgentFiles = peersEnabled ? buildPiAgentFiles(profileId) : {};
3678
+ const routerSkills = buildPiSkills({
3679
+ profileId,
3680
+ peers: peersEnabled,
3681
+ swe: sweEnabled,
3682
+ search: searchEnabled
3683
+ });
3684
+ const routerPrompts = buildPiPrompts({
3685
+ profileId,
3686
+ swe: sweEnabled,
3687
+ peers: peersEnabled
3688
+ });
3689
+ for (const [rel, content] of Object.entries(routerAgentFiles)) await writeTextFile(path.join(mirror, rel), content);
3690
+ for (const skill of routerSkills) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
3691
+ for (const prompt of routerPrompts) await writeTextFile(path.join(mirror, "prompts", `${prompt.name}.md`), prompt.content);
3692
+ await writeTextFile(path.join(mirror, "APPEND_SYSTEM.md"), buildPiAppendSystem(profileId, {
3693
+ peers: peersEnabled,
3694
+ codeSearch: surfaces.codeSearch
3695
+ }));
3696
+ let foreign;
3697
+ if (foreignEnabled) try {
3698
+ const { buildForeignAgentIndex, buildReservedNames, piForeignHomeDir, piForeignRepoRoot, planForeignArtifacts, writeForeignArtifacts } = await import("./pi-foreign-artifacts-DZ4tioyO.js");
3699
+ const repoRoot = await piForeignRepoRoot(process$1.cwd());
3700
+ const homeDir = piForeignHomeDir();
3701
+ const reservedNames = await buildReservedNames({
3702
+ mirrorDir: mirror,
3703
+ repoRoot,
3704
+ homeDir,
3705
+ emittedAgents: Object.keys(routerAgentFiles).map((rel) => path.basename(rel, ".md")),
3706
+ emittedSkills: routerSkills.map((skill) => skill.dir),
3707
+ emittedPrompts: routerPrompts.map((prompt) => prompt.name)
3708
+ });
3709
+ const plan = await planForeignArtifacts({
3710
+ repoRoot,
3711
+ homeDir,
3712
+ mirrorDir: mirror,
3713
+ reservedNames
3714
+ });
3715
+ const written = await writeForeignArtifacts(mirror, plan);
3716
+ if (written.overwritten > 0) consola.warn(`Pi foreign bridge: ${written.overwritten} existing file(s) were replaced. That is a bug in the name reservation, not expected behavior.`);
3717
+ foreign = {
3718
+ agents: plan.agents.map(({ name, description, body }) => ({
3719
+ name,
3720
+ description,
3721
+ body
3722
+ })),
3723
+ index: buildForeignAgentIndex(plan.agents)
3724
+ };
3725
+ foreignStats = {
3726
+ agents: plan.agents.length,
3727
+ renamed: [
3728
+ ...plan.agents.filter((agent) => agent.renamedFrom).map((agent) => ({
3729
+ from: String(agent.renamedFrom),
3730
+ to: agent.name
3731
+ })),
3732
+ ...plan.skills.filter((skill) => skill.renamedFrom).map((skill) => ({
3733
+ from: String(skill.renamedFrom),
3734
+ to: skill.name
3735
+ })),
3736
+ ...plan.prompts.filter((prompt) => prompt.renamedFrom).map((prompt) => ({
3737
+ from: String(prompt.renamedFrom),
3738
+ to: prompt.name
3739
+ }))
3740
+ ],
3741
+ skipped: plan.skipped.map(({ name, reason }) => ({
3742
+ name,
3743
+ reason
3744
+ })),
3745
+ written
3746
+ };
3747
+ } catch (err) {
3748
+ consola.debug("Pi foreign bridge skipped:", err);
3749
+ }
3750
+ else try {
3751
+ const { countForeignAgentFiles, piForeignHomeDir, piForeignRepoRoot } = await import("./pi-foreign-artifacts-DZ4tioyO.js");
3752
+ foreignAvailable = await countForeignAgentFiles({
3753
+ repoRoot: await piForeignRepoRoot(process$1.cwd()),
3754
+ homeDir: piForeignHomeDir()
3755
+ });
3756
+ } catch (err) {
3757
+ consola.debug("Pi foreign artifact probe skipped:", err);
3758
+ }
3424
3759
  await writeTextFile(path.join(mirror, "extensions", "gh-router-pi", "index.ts"), buildPiExtensionSource({
3425
3760
  profileId,
3426
3761
  bridge: bridgeStats ? {
3427
3762
  stats: bridgeStats,
3428
3763
  scopedRules: bridgeScoped
3429
- } : void 0
3764
+ } : void 0,
3765
+ foreign
3430
3766
  }));
3431
3767
  if (surfaces.groups.length > 0) {
3432
3768
  const written = await writePiMcpJson({
@@ -3439,29 +3775,10 @@ const pi = defineCommand({
3439
3775
  if (written.skippedReason) consola.warn(`Pi MCP: left ${written.path} alone (${written.skippedReason}); the scoped groups are not exposed to Pi this launch.`);
3440
3776
  else for (const { key, file } of written.shadowed) consola.warn(`Pi MCP: ${file} declares "${key}" and outranks the mirror copy, so the router's version is not the one Pi will run. Rename that entry to keep both.`);
3441
3777
  }
3442
- if (peersEnabled) {
3443
- const agentFiles = buildPiAgentFiles(profileId);
3444
- for (const [rel, content] of Object.entries(agentFiles)) await writeTextFile(path.join(mirror, rel), content);
3445
- }
3446
- for (const skill of buildPiSkills({
3447
- profileId,
3448
- peers: peersEnabled,
3449
- swe: sweEnabled,
3450
- search: searchEnabled
3451
- })) await writeTextFile(path.join(mirror, "skills", skill.dir, "SKILL.md"), skill.content);
3452
- for (const prompt of buildPiPrompts({
3453
- profileId,
3454
- swe: sweEnabled,
3455
- peers: peersEnabled
3456
- })) await writeTextFile(path.join(mirror, "prompts", `${prompt.name}.md`), prompt.content);
3457
- await writeTextFile(path.join(mirror, "APPEND_SYSTEM.md"), buildPiAppendSystem(profileId, {
3458
- peers: peersEnabled,
3459
- codeSearch: surfaces.codeSearch
3460
- }));
3461
3778
  try {
3462
3779
  const collected = globalThis.__ghRouterBridgeCollected;
3463
3780
  if (collected) {
3464
- const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-Dvj1T3e3.js");
3781
+ const { buildMirrorBridgeSection, mergeBridgeIntoAgentsMd } = await import("./pi-memory-bridge-Bp9AnYw9.js");
3465
3782
  const { section } = buildMirrorBridgeSection(collected, { repoRoot: process$1.cwd() });
3466
3783
  const agentsPath = path.join(mirror, "AGENTS.md");
3467
3784
  let existing;
@@ -3539,11 +3856,19 @@ const pi = defineCommand({
3539
3856
  search: searchEnabled,
3540
3857
  browse: browseEnabled,
3541
3858
  mcpGroups: surfaces.groups.map((g) => g.group),
3859
+ foreign: foreignStats ? {
3860
+ agents: foreignStats.agents,
3861
+ skills: foreignStats.written.skills,
3862
+ prompts: foreignStats.written.prompts,
3863
+ renamed: foreignStats.renamed,
3864
+ skipped: foreignStats.skipped
3865
+ } : void 0,
3866
+ foreignAvailable,
3542
3867
  serverUrl
3543
3868
  })}\n`);
3544
3869
  if (sweEnabled && !peersEnabled) process$1.stderr.write("Note: --swe without --peers emits no delegate/review skills or prompts (no agents behind them in a peerless launch).\n");
3545
3870
  const { disposeBluebirdClients } = await import("./bluebird-client-BvoMTmEv.js");
3546
- const { disposeAdoClients } = await import("./ado-tools-aRld02_r.js");
3871
+ const { disposeAdoClients } = await import("./ado-tools-CRkyU51J.js");
3547
3872
  launchChild({
3548
3873
  kind: "pi",
3549
3874
  envVars: {
@@ -3580,4 +3905,4 @@ const pi = defineCommand({
3580
3905
  });
3581
3906
  export { pi };
3582
3907
 
3583
- //# sourceMappingURL=pi-CzDdGipf.js.map
3908
+ //# sourceMappingURL=pi-DmeBxzIo.js.map