pi-advisor-flow 0.17.1-dev.1 → 0.17.1-dev.3

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/CHANGELOG.md CHANGED
@@ -10,9 +10,28 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
10
10
 
11
11
  - Added **Tracked file handoff** (`advisorTrackedFileHandoff`) in `/advisor-settings`. The default `advisor-named` keeps the current rule: `includeTrackedFiles` works only for files the latest Advisor answer names. `executor` lets the Executor attach tracked files on any consultation, without that extra round trip. Tracked file content consent, exact path checks, size limits, redaction, and untrusted-data labelling still apply.
12
12
 
13
+ ### Fixed
14
+
15
+ - Preserve session entries proposed by earlier `turn_end` handlers when appending Advisor budget feedback.
16
+ - Keep already-active Advisor tools in place during successful always-on activation so pending tools can still be restored.
17
+ - Write `advisor.json` updates atomically so a failed save cannot leave the config truncated or partially written.
18
+ - Store JEV API keys through an atomic 0600-from-creation key-file write in all four key stores, so a failed permission repair can no longer leave a replacement secret readable; removing a plaintext `typesafe_api_key` from `advisor.json` is now atomic too.
19
+ - Reject `advisorJevTimeoutMs` values above the 32-bit timer ceiling (2147483647 ms), which runtimes silently clamp to ~1 ms and thereby fail screening open.
20
+ - The Advisor thinking renderer now honors the effective Pi `hide_thinking` setting — including a trusted project's override — instead of only the global `settings.json`.
21
+ - Batch the Git membership queries behind tracked/untracked attachments into one `git ls-files` call per request list (chunked at 256 paths), so a long list of nonexistent paths no longer launches one synchronous Git process per path.
22
+ - A failed Jev provider save now restores the previously stored key (or clears the store when none existed) instead of leaving a freshly written key active under the old endpoint.
23
+ - Activation fixes: a failed Advisor authentication now also rolls back argument-provided model refs; a failed activation save restores Pi's host Executor model alongside the extension's refs; and an unchanged outcome-logging value no longer triggers a second `advisor.json` write whose failure could roll back runtime state after the main settings were already committed.
24
+ - Conversation image census now decodes and validates each image part once per walk instead of twice.
25
+ - Git context collection now runs through asynchronous subprocesses under the same shared five-second deadline, so it no longer blocks the event loop during consultations.
26
+
27
+ ### Fixed (benchmark harness)
28
+
29
+ - Reject repeated TOML answer keys in benchmark fixtures instead of silently replacing ground truth; require an explicit `--config` for live benchmark tiers; aggregate usage across an empty-response retry so cost and budget accounting includes both attempts; and re-read plus merge the Codex auth file before persisting a rotated refresh while activating rotated tokens only after the write succeeds.
30
+
13
31
  ### Changed
14
32
 
15
- - Updated development dependencies: Pi packages (`pi-ai`, `pi-coding-agent`, and `pi-tui`) to 1.6.0, Oxlint and plugins to 1.94.0, Bun types to 1.4.5, Knip to 6.47.0, lint-staged to 17.6.1, TypeBox to 1.4.7, and Ultracite to 8.3.1. Existing peer dependency ranges remain unchanged.
33
+ - Upgraded the required Bun runtime to 1.4.5 across local development and CI.
34
+ - Updated development dependencies: Pi packages (`pi-ai`, `pi-coding-agent`, and `pi-tui`) to 1.6.1, Oxlint and plugins to 1.95.0, `@types/node` to 26.6.11, Knip to 6.48.0, and lint-staged to 17.6.2. Bun types remain at 1.4.5, TypeBox at 1.4.7, and Ultracite at 8.3.1. Existing peer dependency ranges remain unchanged.
16
35
 
17
36
  ## 0.17.0 - 2026-11-20
18
37
 
package/README.md CHANGED
@@ -84,7 +84,9 @@ The Executor is whichever model your Pi session is using unless you pin one with
84
84
  /advisor executor=openai-codex/gpt-5.6-luna advisor=openai-codex/gpt-5.6-sol
85
85
  ```
86
86
 
87
- From the Executor, `ask_advisor({})` requests a general review. A targeted `question` or concise `draft` can focus the review on a particular decision. Advisor log feedback is off by default; enable **Advisor log feedback** in `/advisor-settings` to include budget and Scout status messages in session logs. Actual Advisor call and result messages remain visible either way, and call limits and enforcement are unchanged. `/advisor-settings` can restrict this tool and every automatic Advisor gate to a whitelist of exact `provider/model` Executor references; an empty whitelist preserves the default of allowing every model.
87
+ From the Executor, `ask_advisor({})` requests a general review. A targeted `question` or concise `draft` can focus the review on a particular decision. Advisor log feedback is off by default; enable **Advisor log feedback** in `/advisor-settings` to include budget and Scout status messages in session logs. Budget feedback preserves session entries proposed by other extensions. Actual Advisor call and result messages remain visible either way, and call limits and enforcement are unchanged. `/advisor-settings` can restrict this tool and every automatic Advisor gate to a whitelist of exact `provider/model` Executor references; an empty whitelist preserves the default of allowing every model.
88
+
89
+ With **Always on**, successful automatic activation leaves already-active Advisor tools in place, so Pi can still restore deferred tools when they become available. If automatic activation fails, the Advisor tools are disabled.
88
90
 
89
91
  In the Settings, enable Simple Mode for a quick start.
90
92
 
package/dist/index.js CHANGED
@@ -13,6 +13,7 @@ var JEV_API_KEY_CLASSIFIER = "jev-api-key";
13
13
  var DEFAULT_JEV_TIMEOUT_MS = 8000;
14
14
  var DEFAULT_SCOUT_TIMEOUT_MS = 30000;
15
15
  var MAX_SCOUT_TIMEOUT_MS = 2147483647;
16
+ var MAX_JEV_TIMEOUT_MS = 2147483647;
16
17
  var DEFAULT_JEV_DIGEST_MAX_CHARS = 4000;
17
18
  var DEFAULT_JEV_PRICE_PER_MTOK = 0.042;
18
19
  var DEFAULT_JEV_FILTER_SKIP_CONFIDENCE = 0.85;
@@ -376,7 +377,7 @@ var capUtf8Bytes = (value, maxBytes) => {
376
377
  };
377
378
 
378
379
  // src/git.ts
379
- import { execFileSync } from "node:child_process";
380
+ import { execFile } from "node:child_process";
380
381
  var GIT_CONTEXT_LEVELS = ["off", "summary", "full"];
381
382
  var GIT_CONTEXT_LEVEL_SET = new Set(GIT_CONTEXT_LEVELS);
382
383
  var isValidGitContextLevel = (value) => isString(value) && GIT_CONTEXT_LEVEL_SET.has(value);
@@ -402,6 +403,23 @@ var capRepositoryContext = (value, maxChars) => {
402
403
  var EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
403
404
  var GIT_TOTAL_TIMEOUT_MS = 5000;
404
405
  var GIT_MAX_BUFFER = 16 * 1024 * 1024;
406
+ var execFileText = (file, args, options) => new Promise((resolve, reject) => {
407
+ execFile(file, args, options, (error, stdout) => {
408
+ if (error) {
409
+ reject(error);
410
+ return;
411
+ }
412
+ resolve(String(stdout));
413
+ });
414
+ });
415
+ var execGit = (args, cwd, timeoutMs) => execFileText("git", args, {
416
+ cwd,
417
+ encoding: "utf-8",
418
+ maxBuffer: GIT_MAX_BUFFER,
419
+ shell: false,
420
+ timeout: timeoutMs,
421
+ windowsHide: true
422
+ });
405
423
  var deadlineRunner = () => {
406
424
  const expiresAt = Date.now() + GIT_TOTAL_TIMEOUT_MS;
407
425
  return (args, cwd) => {
@@ -409,31 +427,23 @@ var deadlineRunner = () => {
409
427
  if (remaining <= 0) {
410
428
  throw new Error("Git context collection exceeded its time budget.");
411
429
  }
412
- return execFileSync("git", args, {
413
- cwd,
414
- encoding: "utf-8",
415
- maxBuffer: GIT_MAX_BUFFER,
416
- shell: false,
417
- stdio: ["ignore", "pipe", "pipe"],
418
- timeout: remaining,
419
- windowsHide: true
420
- });
430
+ return execGit(args, cwd, remaining);
421
431
  };
422
432
  };
423
- var diffBase = (run, cwd) => {
433
+ var diffBase = async (run, cwd) => {
424
434
  try {
425
- run(["rev-parse", "--verify", "--quiet", "HEAD"], cwd);
435
+ await run(["rev-parse", "--verify", "--quiet", "HEAD"], cwd);
426
436
  return "HEAD";
427
437
  } catch {
428
438
  return EMPTY_TREE;
429
439
  }
430
440
  };
431
- var collectGitContext = (cwd, level, maxChars, redact = (value) => value, run = deadlineRunner()) => {
441
+ var collectGitContext = async (cwd, level, maxChars, redact = (value) => value, run = deadlineRunner()) => {
432
442
  if (level === "off" || maxChars <= 0) {
433
443
  return { level: "off", status: "disabled", text: "" };
434
444
  }
435
445
  try {
436
- run(["rev-parse", "--is-inside-work-tree"], cwd);
446
+ await run(["rev-parse", "--is-inside-work-tree"], cwd);
437
447
  } catch (error) {
438
448
  return {
439
449
  detail: error instanceof Error ? error.message : String(error),
@@ -443,10 +453,13 @@ var collectGitContext = (cwd, level, maxChars, redact = (value) => value, run =
443
453
  };
444
454
  }
445
455
  try {
446
- const base = diffBase(run, cwd);
447
- const nameStatus = run(["diff", "--name-status", base], cwd).trim();
448
- const shortstat = run(["diff", "--shortstat", base], cwd).trim();
449
- const untracked = run(["ls-files", "--others", "--exclude-standard"], cwd).trim();
456
+ const base = await diffBase(run, cwd);
457
+ const nameStatusOutput = await run(["diff", "--name-status", base], cwd);
458
+ const shortstatOutput = await run(["diff", "--shortstat", base], cwd);
459
+ const untrackedOutput = await run(["ls-files", "--others", "--exclude-standard"], cwd);
460
+ const nameStatus = nameStatusOutput.trim();
461
+ const shortstat = shortstatOutput.trim();
462
+ const untracked = untrackedOutput.trim();
450
463
  if (!(nameStatus || untracked)) {
451
464
  return { level, status: "no-changes", text: "" };
452
465
  }
@@ -459,7 +472,7 @@ ${nameStatus}` : "",
459
472
  ${untracked}` : ""
460
473
  ];
461
474
  if (level === "full") {
462
- const patch = run(["diff", base], cwd);
475
+ const patch = await run(["diff", base], cwd);
463
476
  sections.push(patch.trim() ? `Patch:
464
477
  ${patch}` : "Patch: (no tracked-file content changes)");
465
478
  } else {
@@ -552,7 +565,7 @@ var TRACKED_FILE_HANDOFF_MODE_NAMES = new Set(TRACKED_FILE_HANDOFF_MODES);
552
565
  var isValidTrackedFileHandoffMode = (value) => isString(value) && TRACKED_FILE_HANDOFF_MODE_NAMES.has(value);
553
566
  var isValidToolResultMaxLines = (value) => isValidNonNegativeSafeInteger(value);
554
567
  var isValidToolResultMaxBytes = (value) => isValidNonNegativeSafeInteger(value);
555
- var isValidJevTimeoutMs = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
568
+ var isValidJevTimeoutMs = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= MAX_JEV_TIMEOUT_MS;
556
569
  var isValidScoutTimeoutMs = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= MAX_SCOUT_TIMEOUT_MS;
557
570
  var isValidJevDigestMaxChars = (value) => isValidNonNegativeSafeInteger(value);
558
571
  var isValidJevPricePerMtok = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
@@ -728,7 +741,7 @@ var CONFIG_SCHEMA = {
728
741
  validate: isValidJevPricePerMtok
729
742
  },
730
743
  advisorJevTimeoutMs: {
731
- accepted: "a positive safe integer",
744
+ accepted: `a positive safe integer no greater than ${MAX_JEV_TIMEOUT_MS} milliseconds`,
732
745
  current: () => advisorJevTimeoutMsRef,
733
746
  persisted: true,
734
747
  type: "number",
@@ -1332,10 +1345,11 @@ var saveConfig = (_ctx, options = {}) => {
1332
1345
  if (changedKeys.length === 0) {
1333
1346
  return path;
1334
1347
  }
1348
+ const identity = configFileIdentity(path);
1335
1349
  const existing = readConfigForSave(path);
1336
1350
  const data = applyChangedConfigValues(existing, current, changedKeys, persistAdvisor, persistExecutor);
1337
- writeFileSync(path, `${JSON.stringify(data, null, 2)}
1338
- `);
1351
+ writeConfigAtomically(path, `${JSON.stringify(data, null, 2)}
1352
+ `, identity);
1339
1353
  resetConfigCache();
1340
1354
  const nextLoadedState = { ...current };
1341
1355
  if (!persistAdvisor) {
@@ -2489,7 +2503,7 @@ var sessionContextEntries = (ctx) => {
2489
2503
  import { randomUUID as randomUUID2 } from "node:crypto";
2490
2504
 
2491
2505
  // src/attachments.ts
2492
- import { execFileSync as execFileSync2 } from "node:child_process";
2506
+ import { execFileSync } from "node:child_process";
2493
2507
  import { constants } from "node:fs";
2494
2508
  import { lstat, open, realpath } from "node:fs/promises";
2495
2509
  import { isAbsolute, relative, resolve } from "node:path";
@@ -2516,7 +2530,7 @@ var normalizeRequestedPath = (root, value) => {
2516
2530
  }
2517
2531
  return normalizeRelativePath(root, value);
2518
2532
  };
2519
- var git = (cwd, args) => execFileSync2("git", args, {
2533
+ var git = (cwd, args) => execFileSync("git", args, {
2520
2534
  cwd,
2521
2535
  encoding: "utf-8",
2522
2536
  maxBuffer: 16 * 1024 * 1024,
@@ -2532,30 +2546,37 @@ var repositoryRoot = (cwd) => {
2532
2546
  return Promise.resolve();
2533
2547
  }
2534
2548
  };
2535
- var untracked = (cwd, path) => {
2536
- const output = git(cwd, [
2537
- "ls-files",
2538
- "--others",
2539
- "--exclude-standard",
2540
- "-z",
2541
- "--",
2542
- path
2543
- ]);
2544
- const expected = normalizeRelativePath(cwd, path);
2545
- return output.split("\x00").filter(Boolean).some((entry) => normalizeRelativePath(cwd, entry) === expected);
2546
- };
2547
- var tracked = (cwd, path) => {
2548
- const output = git(cwd, ["ls-files", "--stage", "-z", "--", path]);
2549
- const expected = normalizeRelativePath(cwd, path);
2550
- return output.split("\x00").some((entry) => {
2551
- if (!entry) {
2552
- return false;
2549
+ var MEMBERSHIP_QUERY_BATCH = 256;
2550
+ var normalizeAll = (root, paths) => new Set(paths.map((path) => normalizeRelativePath(root, path)));
2551
+ var permittedPaths = (root, paths, kind) => {
2552
+ const wanted = normalizeAll(root, paths);
2553
+ const permitted = new Set;
2554
+ for (let start = 0;start < paths.length; start += MEMBERSHIP_QUERY_BATCH) {
2555
+ const batch = paths.slice(start, start + MEMBERSHIP_QUERY_BATCH);
2556
+ const output = kind === "tracked" ? git(root, ["ls-files", "--stage", "-z", "--", ...batch]) : git(root, [
2557
+ "ls-files",
2558
+ "--others",
2559
+ "--exclude-standard",
2560
+ "-z",
2561
+ "--",
2562
+ ...batch
2563
+ ]);
2564
+ for (const entry of output.split("\x00")) {
2565
+ if (!entry) {
2566
+ continue;
2567
+ }
2568
+ const name = kind === "tracked" ? entry.split("\t")[1] ?? "" : entry;
2569
+ if (kind === "tracked" && entry.startsWith("160000 ")) {
2570
+ continue;
2571
+ }
2572
+ const normalized = normalizeRelativePath(root, name);
2573
+ if (wanted.has(normalized)) {
2574
+ permitted.add(normalized);
2575
+ }
2553
2576
  }
2554
- const [metadata, name] = entry.split("\t");
2555
- return name && normalizeRelativePath(cwd, name) === expected && !metadata.startsWith("160000 ");
2556
- });
2577
+ }
2578
+ return permitted;
2557
2579
  };
2558
- var isPermitted = (root, path, kind) => kind === "tracked" ? tracked(root, path) : untracked(root, path);
2559
2580
  var readAttachment = async (root, normalizedName, redact, available) => {
2560
2581
  const absolute = resolve(root, normalizedName);
2561
2582
  if (!(within(root, absolute) && available > 0)) {
@@ -2601,16 +2622,24 @@ var readFiles = async (cwd, requested, enabled, redact, kind, totalLimit = ADVIS
2601
2622
  return [];
2602
2623
  }
2603
2624
  const unique = new Set;
2604
- const attachments = [];
2605
- let total = 0;
2606
2625
  for (const name of requested) {
2607
2626
  const normalizedName = normalizeRequestedPath(root, name);
2608
2627
  if (!normalizedName || unique.has(normalizedName) || imageFileCandidate(normalizedName)) {
2609
2628
  continue;
2610
2629
  }
2611
2630
  unique.add(normalizedName);
2631
+ }
2632
+ let permitted;
2633
+ try {
2634
+ permitted = permittedPaths(root, [...unique], kind);
2635
+ } catch {
2636
+ return [];
2637
+ }
2638
+ const attachments = [];
2639
+ let total = 0;
2640
+ for (const normalizedName of unique) {
2612
2641
  try {
2613
- if (!isPermitted(root, normalizedName, kind)) {
2642
+ if (!permitted.has(normalizedName)) {
2614
2643
  continue;
2615
2644
  }
2616
2645
  const available = Math.min(ADVISOR_FILE_MAX_BYTES, totalLimit - total);
@@ -2891,16 +2920,17 @@ var imageFromPart = (part) => {
2891
2920
  }
2892
2921
  return imageFromBytes(bytes, part.mimeType);
2893
2922
  };
2923
+ var IMAGE_OMITTED_MARKER = "[Image omitted: unsupported format, invalid data, or over 4 MiB; pixels not reviewed]";
2924
+ var imageMarkerFromImage = (image, nonce = "") => {
2925
+ const id = createHash("sha256").update(nonce).update(image.data).digest("hex").slice(0, 24);
2926
+ return `[Image ref=img_${id}; pixels reviewed only if attached below]`;
2927
+ };
2894
2928
  var imageMarker = (part, nonce = "") => {
2895
2929
  if (part.type !== "image") {
2896
2930
  return;
2897
2931
  }
2898
2932
  const image = imageFromPart(part);
2899
- if (!image) {
2900
- return "[Image omitted: unsupported format, invalid data, or over 4 MiB; pixels not reviewed]";
2901
- }
2902
- const id = createHash("sha256").update(nonce).update(image.data).digest("hex").slice(0, 24);
2903
- return `[Image ref=img_${id}; pixels reviewed only if attached below]`;
2933
+ return image ? imageMarkerFromImage(image, nonce) : IMAGE_OMITTED_MARKER;
2904
2934
  };
2905
2935
  var eligibleImagePart = (part) => part.type === "image" && isString(part.data) && isString(part.mimeType);
2906
2936
  var entryImageCensus = (content, conversation, nonce, seen) => {
@@ -2913,15 +2943,16 @@ var entryImageCensus = (content, conversation, nonce, seen) => {
2913
2943
  if (eligibleImagePart(part)) {
2914
2944
  parts += 1;
2915
2945
  }
2916
- const marker = imageMarker(part, nonce);
2917
- if (!marker || seen.has(marker) || !conversation.includes(marker)) {
2946
+ if (part.type !== "image") {
2918
2947
  continue;
2919
2948
  }
2920
2949
  const image = imageFromPart(part);
2921
- if (image) {
2922
- seen.add(marker);
2923
- selected.push({ image, marker });
2950
+ const marker = image ? imageMarkerFromImage(image, nonce) : IMAGE_OMITTED_MARKER;
2951
+ if (!image || seen.has(marker) || !conversation.includes(marker)) {
2952
+ continue;
2924
2953
  }
2954
+ seen.add(marker);
2955
+ selected.push({ image, marker });
2925
2956
  }
2926
2957
  return { parts, selected };
2927
2958
  };
@@ -2995,20 +3026,30 @@ var readImageFiles = async (cwd, requested, enabled, kind, remainingBytes, remai
2995
3026
  return { images: [], omitted: names.length };
2996
3027
  }
2997
3028
  const seen = new Set;
2998
- const images = [];
2999
- let omitted = 0;
3000
- let bytes = 0;
3029
+ const candidates = [];
3001
3030
  for (const path of names) {
3002
3031
  const name = normalizeRequestedPath(root, path);
3003
- if (name && seen.has(name)) {
3032
+ if (!name || seen.has(name)) {
3004
3033
  continue;
3005
3034
  }
3006
- if (name) {
3007
- seen.add(name);
3035
+ seen.add(name);
3036
+ const mime = imageMime(name);
3037
+ if (mime) {
3038
+ candidates.push({ mime, name });
3008
3039
  }
3040
+ }
3041
+ let permitted;
3042
+ try {
3043
+ permitted = permittedPaths(root, candidates.map((candidate) => candidate.name), kind);
3044
+ } catch {
3045
+ return { images: [], omitted: names.length };
3046
+ }
3047
+ const images = [];
3048
+ let omitted = names.length - candidates.length;
3049
+ let bytes = 0;
3050
+ for (const { mime, name } of candidates) {
3009
3051
  try {
3010
- const mime = name && imageMime(name);
3011
- const image = name && mime && images.length < remainingCount && remainingBytes - bytes > 0 && isPermitted(root, name, kind) ? await readImageAttachment(root, name, mime, remainingBytes - bytes) : undefined;
3052
+ const image = images.length < remainingCount && remainingBytes - bytes > 0 && permitted.has(name) ? await readImageAttachment(root, name, mime, remainingBytes - bytes) : undefined;
3012
3053
  if (image) {
3013
3054
  images.push(image);
3014
3055
  bytes += image.bytes;
@@ -4327,7 +4368,7 @@ var assembleConsultationContext = async (options) => {
4327
4368
  const allowed = advisorGitContextRef;
4328
4369
  const level = clampGitContextLevel(options.gitContext ?? allowed, allowed);
4329
4370
  const gitBudget = advisorGitContextBudget(contextMaxCharsRef, advisorGitContextMaxCharsRef);
4330
- const changes = collectGitContext(ctx.cwd, level, gitBudget, advisorRedactSecretsRef ? redactSecrets : undefined);
4371
+ const changes = await collectGitContext(ctx.cwd, level, gitBudget, advisorRedactSecretsRef ? redactSecrets : undefined);
4331
4372
  const changeText = advisorRepositoryContext(changes, options.gitContext ?? allowed, level, gitBudget);
4332
4373
  const conversationBudget = Math.max(0, contextMaxCharsRef - changeText.length);
4333
4374
  const imageNonce = randomUUID2();
@@ -4793,6 +4834,12 @@ import {
4793
4834
  import { existsSync as existsSync2, readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
4794
4835
  import { join as join3 } from "node:path";
4795
4836
  import { getAgentDir as getAgentDir3 } from "@earendil-works/pi-coding-agent";
4837
+ var liveSettingsReader;
4838
+ var liveCache;
4839
+ var setLivePiSettings = (reader) => {
4840
+ liveSettingsReader = reader;
4841
+ liveCache = undefined;
4842
+ };
4796
4843
  var SETTING_RECHECK_INTERVAL_MS = 2000;
4797
4844
  var cache = new Map;
4798
4845
  var settingsIdentity = (path) => {
@@ -4812,6 +4859,19 @@ var readHideThinking = (path) => {
4812
4859
  }
4813
4860
  };
4814
4861
  var piHideThinkingEnabled = () => {
4862
+ if (liveSettingsReader) {
4863
+ const now = Date.now();
4864
+ if (!liveCache || now - liveCache.readAt >= SETTING_RECHECK_INTERVAL_MS) {
4865
+ const effective = liveSettingsReader();
4866
+ liveCache = {
4867
+ hidden: effective?.hideThinkingBlock,
4868
+ readAt: now
4869
+ };
4870
+ }
4871
+ if (liveCache.hidden !== undefined) {
4872
+ return liveCache.hidden;
4873
+ }
4874
+ }
4815
4875
  const path = join3(getAgentDir3(), "settings.json");
4816
4876
  if (!existsSync2(path)) {
4817
4877
  return false;
@@ -5823,7 +5883,9 @@ var resolveActivationModels = async (runtime, ctx, canContinue) => {
5823
5883
  error: `${t("activation.noExecutorApiKey.prefix", "No API key for Executor")} ${executorRef}`
5824
5884
  };
5825
5885
  }
5826
- return {};
5886
+ return {
5887
+ switchedExecutor: Boolean(executor) && !isMarkedSubagent()
5888
+ };
5827
5889
  };
5828
5890
  var restoreActivationRefsIfCurrent = (canContinue, restoreRefs) => {
5829
5891
  if (canContinue()) {
@@ -5858,7 +5920,7 @@ var restoreActivationRefs = (previous, attempted) => {
5858
5920
  setExecutorEffortRef(previous.executorEffort);
5859
5921
  }
5860
5922
  };
5861
- var persistSuccessfulActivation = (ctx, shouldSave, reenableTools, restoreRefs) => {
5923
+ var persistSuccessfulActivation = async (ctx, shouldSave, reenableTools, restoreRefs, restoreHostModel) => {
5862
5924
  if (!shouldSave) {
5863
5925
  return true;
5864
5926
  }
@@ -5866,10 +5928,12 @@ var persistSuccessfulActivation = (ctx, shouldSave, reenableTools, restoreRefs)
5866
5928
  saveConfig(ctx, { persistAdvisor: true, persistExecutor: true });
5867
5929
  } catch (saveError) {
5868
5930
  if (!reenableTools) {
5931
+ await restoreHostModel();
5869
5932
  throw saveError;
5870
5933
  }
5871
5934
  setAdvisorToolsEnabledRef(false);
5872
5935
  restoreRefs();
5936
+ await restoreHostModel();
5873
5937
  const message = saveError instanceof Error ? saveError.message : String(saveError);
5874
5938
  notify(ctx, `${t("activation.saveFailed.prefix", "Could not save Advisor activation:")} ${message}`, "error");
5875
5939
  return false;
@@ -5885,7 +5949,7 @@ ${t("activation.flow", "Advisor flow")} ${sameModelAdvisorDisabled(ctx, activeMo
5885
5949
  };
5886
5950
  var activateAdvisor = async (runtime, args, ctx, announce = true) => {
5887
5951
  if (!loadCommandConfig(ctx)) {
5888
- return;
5952
+ return false;
5889
5953
  }
5890
5954
  const { toolAvailabilityRevision } = runtime;
5891
5955
  const canContinue = () => runtime.toolAvailabilityRevision === toolAvailabilityRevision;
@@ -5899,22 +5963,24 @@ var activateAdvisor = async (runtime, args, ctx, announce = true) => {
5899
5963
  attempted = liveRefSnapshot();
5900
5964
  restoreRefs(attempted);
5901
5965
  notify(ctx, argumentError, "error");
5902
- return;
5966
+ return false;
5903
5967
  }
5968
+ attempted = liveRefSnapshot();
5904
5969
  const prepared = await prepareActivationModels(runtime, ctx, announce, executorOverride, advisorOverride, canContinue);
5905
5970
  if (!prepared) {
5906
5971
  attempted = liveRefSnapshot();
5907
5972
  restoreActivationRefsIfCurrent(canContinue, () => restoreRefs(attempted));
5908
- return;
5973
+ return false;
5909
5974
  }
5910
- const { cancelled, error } = await resolveActivationModels(runtime, ctx, canContinue);
5975
+ const entryModel = ctx.model;
5976
+ const { cancelled, error, switchedExecutor } = await resolveActivationModels(runtime, ctx, canContinue);
5911
5977
  if (cancelled || !canContinue()) {
5912
- return;
5978
+ return false;
5913
5979
  }
5914
5980
  if (error) {
5915
5981
  restoreRefs(attempted);
5916
5982
  notify(ctx, error, "error");
5917
- return;
5983
+ return false;
5918
5984
  }
5919
5985
  const sessionScoped = advisorActivationRef === "session";
5920
5986
  const reenableTools = !sessionScoped && !advisorToolsEnabledRef;
@@ -5922,8 +5988,9 @@ var activateAdvisor = async (runtime, args, ctx, announce = true) => {
5922
5988
  setAdvisorToolsEnabledRef(true);
5923
5989
  }
5924
5990
  const shouldSave = !sessionScoped && Boolean(args.trim() || prepared.pickedModels || reenableTools);
5925
- if (!persistSuccessfulActivation(ctx, shouldSave, reenableTools, () => restoreRefs(liveRefSnapshot()))) {
5926
- return;
5991
+ const restoreHostModel = () => switchedExecutor && entryModel ? runtime.setExecutorModel(entryModel) : Promise.resolve(false);
5992
+ if (!await persistSuccessfulActivation(ctx, shouldSave, reenableTools, () => restoreRefs(liveRefSnapshot()), restoreHostModel)) {
5993
+ return false;
5927
5994
  }
5928
5995
  if (executorEffortRef && !isMarkedSubagent()) {
5929
5996
  runtime.pi.setThinkingLevel(executorEffortRef);
@@ -5939,6 +6006,7 @@ var activateAdvisor = async (runtime, args, ctx, announce = true) => {
5939
6006
  if (announce) {
5940
6007
  announceActivation(ctx, activeModel);
5941
6008
  }
6009
+ return true;
5942
6010
  };
5943
6011
 
5944
6012
  // src/commands/configuration-tool.ts
@@ -6528,8 +6596,11 @@ var registerCommandLifecycle = (runtime, activateAdvisor) => {
6528
6596
  return;
6529
6597
  }
6530
6598
  if (alwaysOnRef) {
6531
- setAdvisorToolsActive(runtime.pi, false);
6532
- await activateAdvisor("", ctx, false);
6599
+ const { toolAvailabilityRevision } = runtime;
6600
+ const activated = await activateAdvisor("", ctx, false);
6601
+ if (!activated && runtime.toolAvailabilityRevision === toolAvailabilityRevision) {
6602
+ setAdvisorToolsActive(runtime.pi, false);
6603
+ }
6533
6604
  } else {
6534
6605
  runtime.updateSameModelNotice(ctx);
6535
6606
  }
@@ -6899,12 +6970,44 @@ class ManualAdvisorDialog {
6899
6970
  }
6900
6971
 
6901
6972
  // src/jev/classifier-key-store.ts
6902
- import { chmodSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
6973
+ import { readFileSync as readFileSync3, rmSync } from "node:fs";
6903
6974
  import { join as join4 } from "node:path";
6904
6975
  import { getAgentDir as getAgentDir4 } from "@earendil-works/pi-coding-agent";
6976
+
6977
+ // src/jev/key-file.ts
6978
+ import { randomUUID as randomUUID4 } from "node:crypto";
6979
+ import {
6980
+ closeSync as closeSync2,
6981
+ openSync as openSync2,
6982
+ renameSync as renameSync2,
6983
+ unlinkSync as unlinkSync2,
6984
+ writeFileSync as writeFileSync2
6985
+ } from "node:fs";
6986
+ var KEY_FILE_MODE = 384;
6987
+ var writeKeyFile = (path, key) => {
6988
+ const temporaryPath = `${path}.${process.pid}.${randomUUID4()}.tmp`;
6989
+ let fileDescriptor;
6990
+ try {
6991
+ fileDescriptor = openSync2(temporaryPath, "wx", KEY_FILE_MODE);
6992
+ writeFileSync2(fileDescriptor, `${key}
6993
+ `, "utf-8");
6994
+ closeSync2(fileDescriptor);
6995
+ fileDescriptor = undefined;
6996
+ renameSync2(temporaryPath, path);
6997
+ } catch (error) {
6998
+ if (fileDescriptor !== undefined) {
6999
+ closeSync2(fileDescriptor);
7000
+ }
7001
+ try {
7002
+ unlinkSync2(temporaryPath);
7003
+ } catch {}
7004
+ throw error;
7005
+ }
7006
+ };
7007
+
7008
+ // src/jev/classifier-key-store.ts
6905
7009
  var JEV_CLASSIFIER_KEY_SERVICE = "pi-advisor-jev-classifier";
6906
7010
  var JEV_CLASSIFIER_KEY_NAME = "classifier-api-key";
6907
- var KEY_FILE_MODE = 384;
6908
7011
  var keyFilePath = () => join4(getAgentDir4(), "jev_classifier_api_key");
6909
7012
  var classifierKeyFailClosed = false;
6910
7013
  var disableJevClassifierKeyForRuntime = () => {
@@ -6924,12 +7027,7 @@ var defaultReadFile = () => {
6924
7027
  return;
6925
7028
  }
6926
7029
  };
6927
- var defaultWriteFile = (key) => {
6928
- const path = keyFilePath();
6929
- writeFileSync2(path, `${key}
6930
- `, { mode: KEY_FILE_MODE });
6931
- chmodSync(path, KEY_FILE_MODE);
6932
- };
7030
+ var defaultWriteFile = (key) => writeKeyFile(keyFilePath(), key);
6933
7031
  var readJevClassifierKey = async (deps = {}) => {
6934
7032
  const secrets = deps.secrets === undefined ? runtimeSecrets() : deps.secrets;
6935
7033
  if (secrets) {
@@ -7663,7 +7761,9 @@ var MODEL_SETTINGS = [
7663
7761
  var registerModelCommands = (runtime) => {
7664
7762
  runtime.pi.registerCommand("advisor", {
7665
7763
  description: "Enable the Executor/Advisor flow and switch to the configured or explicitly selected Executor model; accepts contextMaxChars=N",
7666
- handler: (args, ctx) => activateAdvisor(runtime, args, ctx)
7764
+ handler: async (args, ctx) => {
7765
+ await activateAdvisor(runtime, args, ctx);
7766
+ }
7667
7767
  });
7668
7768
  runtime.pi.registerCommand("advisor-models", {
7669
7769
  description: "Select and persist the Executor, Advisor, and optional fallback models with reasoning levels",
@@ -9574,7 +9674,7 @@ var saveAdvisorSettings = (ctx, settings, options = {}) => {
9574
9674
  persistAdvisor: Boolean(persisted.advisor),
9575
9675
  persistExecutor: Boolean(persisted.executor)
9576
9676
  });
9577
- if (!options.skipOutcomeLogging) {
9677
+ if (!options.skipOutcomeLogging && (settings.outcomeLogging ?? false) !== previous.outcomeLogging) {
9578
9678
  saveGlobalOutcomeLogging(settings.outcomeLogging ?? false);
9579
9679
  }
9580
9680
  if (previous.advisorActivation === "session") {
@@ -9759,7 +9859,10 @@ var advisorBudgetUpdate = (event, ctx, pi, session) => {
9759
9859
  return;
9760
9860
  }
9761
9861
  return {
9762
- entries: [{ ...message, type: "custom_message" }]
9862
+ entries: [
9863
+ ...event.entries ?? [],
9864
+ { ...message, type: "custom_message" }
9865
+ ]
9763
9866
  };
9764
9867
  };
9765
9868
 
@@ -10860,6 +10963,7 @@ try {
10860
10963
  loader.registerLocalesFromDir(I18N_NAMESPACE, new URL("../", import.meta.url).href, { label: "pi-advisor" });
10861
10964
  } catch {}
10862
10965
  function registerPiAdvisor(pi) {
10966
+ setLivePiSettings(() => pi.getSettings?.());
10863
10967
  const sessionState = new AdvisorSessionState;
10864
10968
  const scoutStatus = new ScoutStatusManager;
10865
10969
  const herdrActivity = herdrAdvisorActivity.createScope();
@@ -9,7 +9,7 @@ bun install
9
9
  bun run build
10
10
  ```
11
11
 
12
- Use Bun 1.4.4 or newer; the repository's `preinstall` check rejects older versions unless lifecycle scripts are disabled. The check skips packed installs, so package consumers don't need Bun. `bun run typecheck` uses the `bun check` command.
12
+ Use Bun 1.4.5 or newer; the repository's `preinstall` check rejects older versions unless lifecycle scripts are disabled. The check skips packed installs, so package consumers don't need Bun. `bun run typecheck` uses the `bun check` command.
13
13
 
14
14
  Pi loads `dist/index.js`, which bundles internal modules so settings controls and persistence share the same runtime state. Run `bun run build` once after checkout, then reload Pi. The pre-commit hook rebuilds and stages the bundle after linting source changes; `prepack` also rebuilds it for npm packaging.
15
15
 
@@ -4,6 +4,7 @@ import { registerCommands } from "../src/commands/registration.ts";
4
4
  import { getAdvisorSettings } from "../src/config/state.ts";
5
5
  import { herdrAdvisorActivity, HerdrAdvisorBlock } from "../src/herdr.ts";
6
6
  import { I18N_NAMESPACE } from "../src/i18n.ts";
7
+ import { setLivePiSettings } from "../src/pi-settings.ts";
7
8
  import { AdvisorSessionState } from "../src/session-state.ts";
8
9
  import {
9
10
  consultAdvisor as consultAdvisorImplementation,
@@ -60,6 +61,7 @@ try {
60
61
  }
61
62
 
62
63
  export default function registerPiAdvisor(pi: ExtensionAPI) {
64
+ setLivePiSettings(() => pi.getSettings?.());
63
65
  const sessionState = new AdvisorSessionState();
64
66
  const scoutStatus = new ScoutStatusManager();
65
67
  const herdrActivity = herdrAdvisorActivity.createScope();
package/locales/de.json CHANGED
@@ -333,5 +333,7 @@
333
333
  "usage.call": "Aufruf",
334
334
  "usage.calls": "Aufrufe",
335
335
  "usage.unavailable": "nicht verfügbar",
336
- "usage.withoutData": "ohne Nutzungsdaten"
336
+ "usage.withoutData": "ohne Nutzungsdaten",
337
+ "jevSetup.providerKeyRestored": "Provider verifiziert, aber Einstellungen konnten nicht gespeichert werden; der vorherige Schlüssel wurde wiederhergestellt.",
338
+ "jevSetup.providerKeyNotRestored": "Provider verifiziert, aber Einstellungen konnten nicht gespeichert werden und der vorherige Schlüssel konnte nicht wiederhergestellt werden. Gib vor dem erneuten Versuch einen gültigen Schlüssel ein."
337
339
  }
package/locales/en.json CHANGED
@@ -334,5 +334,7 @@
334
334
  "usage.call": "call",
335
335
  "usage.calls": "calls",
336
336
  "usage.unavailable": "unavailable",
337
- "usage.withoutData": "without usage data"
337
+ "usage.withoutData": "without usage data",
338
+ "jevSetup.providerKeyRestored": "Provider verified, but settings could not be saved; the previous key was restored.",
339
+ "jevSetup.providerKeyNotRestored": "Provider verified, but settings could not be saved and the previous key could not be restored. Re-enter a valid key before retrying."
338
340
  }