pi-advisor-flow 0.17.1-dev.2 → 0.17.1-dev.4

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
@@ -14,10 +14,25 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
14
14
 
15
15
  - Preserve session entries proposed by earlier `turn_end` handlers when appending Advisor budget feedback.
16
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
+ - Git context collection now passes `--no-ext-diff --no-textconv` to every diff command, so external diff drivers and textconv filters configured in a repository no longer execute during consultations.
27
+
28
+ ### Fixed (benchmark harness)
29
+
30
+ - 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.
17
31
 
18
32
  ### Changed
19
33
 
20
- - 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.
34
+ - Upgraded the required Bun runtime to 1.4.5 across local development and CI.
35
+ - 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.
21
36
 
22
37
  ## 0.17.0 - 2026-11-20
23
38
 
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,29 @@ 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 diffArgs = (...rest) => [
434
+ "diff",
435
+ "--no-ext-diff",
436
+ "--no-textconv",
437
+ ...rest
438
+ ];
439
+ var diffBase = async (run, cwd) => {
424
440
  try {
425
- run(["rev-parse", "--verify", "--quiet", "HEAD"], cwd);
441
+ await run(["rev-parse", "--verify", "--quiet", "HEAD"], cwd);
426
442
  return "HEAD";
427
443
  } catch {
428
444
  return EMPTY_TREE;
429
445
  }
430
446
  };
431
- var collectGitContext = (cwd, level, maxChars, redact = (value) => value, run = deadlineRunner()) => {
447
+ var collectGitContext = async (cwd, level, maxChars, redact = (value) => value, run = deadlineRunner()) => {
432
448
  if (level === "off" || maxChars <= 0) {
433
449
  return { level: "off", status: "disabled", text: "" };
434
450
  }
435
451
  try {
436
- run(["rev-parse", "--is-inside-work-tree"], cwd);
452
+ await run(["rev-parse", "--is-inside-work-tree"], cwd);
437
453
  } catch (error) {
438
454
  return {
439
455
  detail: error instanceof Error ? error.message : String(error),
@@ -443,10 +459,13 @@ var collectGitContext = (cwd, level, maxChars, redact = (value) => value, run =
443
459
  };
444
460
  }
445
461
  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();
462
+ const base = await diffBase(run, cwd);
463
+ const nameStatusOutput = await run(diffArgs("--name-status", base), cwd);
464
+ const shortstatOutput = await run(diffArgs("--shortstat", base), cwd);
465
+ const untrackedOutput = await run(["ls-files", "--others", "--exclude-standard"], cwd);
466
+ const nameStatus = nameStatusOutput.trim();
467
+ const shortstat = shortstatOutput.trim();
468
+ const untracked = untrackedOutput.trim();
450
469
  if (!(nameStatus || untracked)) {
451
470
  return { level, status: "no-changes", text: "" };
452
471
  }
@@ -459,7 +478,7 @@ ${nameStatus}` : "",
459
478
  ${untracked}` : ""
460
479
  ];
461
480
  if (level === "full") {
462
- const patch = run(["diff", base], cwd);
481
+ const patch = await run(diffArgs(base), cwd);
463
482
  sections.push(patch.trim() ? `Patch:
464
483
  ${patch}` : "Patch: (no tracked-file content changes)");
465
484
  } else {
@@ -552,7 +571,7 @@ var TRACKED_FILE_HANDOFF_MODE_NAMES = new Set(TRACKED_FILE_HANDOFF_MODES);
552
571
  var isValidTrackedFileHandoffMode = (value) => isString(value) && TRACKED_FILE_HANDOFF_MODE_NAMES.has(value);
553
572
  var isValidToolResultMaxLines = (value) => isValidNonNegativeSafeInteger(value);
554
573
  var isValidToolResultMaxBytes = (value) => isValidNonNegativeSafeInteger(value);
555
- var isValidJevTimeoutMs = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
574
+ var isValidJevTimeoutMs = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= MAX_JEV_TIMEOUT_MS;
556
575
  var isValidScoutTimeoutMs = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= MAX_SCOUT_TIMEOUT_MS;
557
576
  var isValidJevDigestMaxChars = (value) => isValidNonNegativeSafeInteger(value);
558
577
  var isValidJevPricePerMtok = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
@@ -728,7 +747,7 @@ var CONFIG_SCHEMA = {
728
747
  validate: isValidJevPricePerMtok
729
748
  },
730
749
  advisorJevTimeoutMs: {
731
- accepted: "a positive safe integer",
750
+ accepted: `a positive safe integer no greater than ${MAX_JEV_TIMEOUT_MS} milliseconds`,
732
751
  current: () => advisorJevTimeoutMsRef,
733
752
  persisted: true,
734
753
  type: "number",
@@ -1332,10 +1351,11 @@ var saveConfig = (_ctx, options = {}) => {
1332
1351
  if (changedKeys.length === 0) {
1333
1352
  return path;
1334
1353
  }
1354
+ const identity = configFileIdentity(path);
1335
1355
  const existing = readConfigForSave(path);
1336
1356
  const data = applyChangedConfigValues(existing, current, changedKeys, persistAdvisor, persistExecutor);
1337
- writeFileSync(path, `${JSON.stringify(data, null, 2)}
1338
- `);
1357
+ writeConfigAtomically(path, `${JSON.stringify(data, null, 2)}
1358
+ `, identity);
1339
1359
  resetConfigCache();
1340
1360
  const nextLoadedState = { ...current };
1341
1361
  if (!persistAdvisor) {
@@ -2489,7 +2509,7 @@ var sessionContextEntries = (ctx) => {
2489
2509
  import { randomUUID as randomUUID2 } from "node:crypto";
2490
2510
 
2491
2511
  // src/attachments.ts
2492
- import { execFileSync as execFileSync2 } from "node:child_process";
2512
+ import { execFileSync } from "node:child_process";
2493
2513
  import { constants } from "node:fs";
2494
2514
  import { lstat, open, realpath } from "node:fs/promises";
2495
2515
  import { isAbsolute, relative, resolve } from "node:path";
@@ -2516,7 +2536,7 @@ var normalizeRequestedPath = (root, value) => {
2516
2536
  }
2517
2537
  return normalizeRelativePath(root, value);
2518
2538
  };
2519
- var git = (cwd, args) => execFileSync2("git", args, {
2539
+ var git = (cwd, args) => execFileSync("git", args, {
2520
2540
  cwd,
2521
2541
  encoding: "utf-8",
2522
2542
  maxBuffer: 16 * 1024 * 1024,
@@ -2532,30 +2552,37 @@ var repositoryRoot = (cwd) => {
2532
2552
  return Promise.resolve();
2533
2553
  }
2534
2554
  };
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;
2555
+ var MEMBERSHIP_QUERY_BATCH = 256;
2556
+ var normalizeAll = (root, paths) => new Set(paths.map((path) => normalizeRelativePath(root, path)));
2557
+ var permittedPaths = (root, paths, kind) => {
2558
+ const wanted = normalizeAll(root, paths);
2559
+ const permitted = new Set;
2560
+ for (let start = 0;start < paths.length; start += MEMBERSHIP_QUERY_BATCH) {
2561
+ const batch = paths.slice(start, start + MEMBERSHIP_QUERY_BATCH);
2562
+ const output = kind === "tracked" ? git(root, ["ls-files", "--stage", "-z", "--", ...batch]) : git(root, [
2563
+ "ls-files",
2564
+ "--others",
2565
+ "--exclude-standard",
2566
+ "-z",
2567
+ "--",
2568
+ ...batch
2569
+ ]);
2570
+ for (const entry of output.split("\x00")) {
2571
+ if (!entry) {
2572
+ continue;
2573
+ }
2574
+ const name = kind === "tracked" ? entry.split("\t")[1] ?? "" : entry;
2575
+ if (kind === "tracked" && entry.startsWith("160000 ")) {
2576
+ continue;
2577
+ }
2578
+ const normalized = normalizeRelativePath(root, name);
2579
+ if (wanted.has(normalized)) {
2580
+ permitted.add(normalized);
2581
+ }
2553
2582
  }
2554
- const [metadata, name] = entry.split("\t");
2555
- return name && normalizeRelativePath(cwd, name) === expected && !metadata.startsWith("160000 ");
2556
- });
2583
+ }
2584
+ return permitted;
2557
2585
  };
2558
- var isPermitted = (root, path, kind) => kind === "tracked" ? tracked(root, path) : untracked(root, path);
2559
2586
  var readAttachment = async (root, normalizedName, redact, available) => {
2560
2587
  const absolute = resolve(root, normalizedName);
2561
2588
  if (!(within(root, absolute) && available > 0)) {
@@ -2601,16 +2628,24 @@ var readFiles = async (cwd, requested, enabled, redact, kind, totalLimit = ADVIS
2601
2628
  return [];
2602
2629
  }
2603
2630
  const unique = new Set;
2604
- const attachments = [];
2605
- let total = 0;
2606
2631
  for (const name of requested) {
2607
2632
  const normalizedName = normalizeRequestedPath(root, name);
2608
2633
  if (!normalizedName || unique.has(normalizedName) || imageFileCandidate(normalizedName)) {
2609
2634
  continue;
2610
2635
  }
2611
2636
  unique.add(normalizedName);
2637
+ }
2638
+ let permitted;
2639
+ try {
2640
+ permitted = permittedPaths(root, [...unique], kind);
2641
+ } catch {
2642
+ return [];
2643
+ }
2644
+ const attachments = [];
2645
+ let total = 0;
2646
+ for (const normalizedName of unique) {
2612
2647
  try {
2613
- if (!isPermitted(root, normalizedName, kind)) {
2648
+ if (!permitted.has(normalizedName)) {
2614
2649
  continue;
2615
2650
  }
2616
2651
  const available = Math.min(ADVISOR_FILE_MAX_BYTES, totalLimit - total);
@@ -2891,16 +2926,17 @@ var imageFromPart = (part) => {
2891
2926
  }
2892
2927
  return imageFromBytes(bytes, part.mimeType);
2893
2928
  };
2929
+ var IMAGE_OMITTED_MARKER = "[Image omitted: unsupported format, invalid data, or over 4 MiB; pixels not reviewed]";
2930
+ var imageMarkerFromImage = (image, nonce = "") => {
2931
+ const id = createHash("sha256").update(nonce).update(image.data).digest("hex").slice(0, 24);
2932
+ return `[Image ref=img_${id}; pixels reviewed only if attached below]`;
2933
+ };
2894
2934
  var imageMarker = (part, nonce = "") => {
2895
2935
  if (part.type !== "image") {
2896
2936
  return;
2897
2937
  }
2898
2938
  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]`;
2939
+ return image ? imageMarkerFromImage(image, nonce) : IMAGE_OMITTED_MARKER;
2904
2940
  };
2905
2941
  var eligibleImagePart = (part) => part.type === "image" && isString(part.data) && isString(part.mimeType);
2906
2942
  var entryImageCensus = (content, conversation, nonce, seen) => {
@@ -2913,15 +2949,16 @@ var entryImageCensus = (content, conversation, nonce, seen) => {
2913
2949
  if (eligibleImagePart(part)) {
2914
2950
  parts += 1;
2915
2951
  }
2916
- const marker = imageMarker(part, nonce);
2917
- if (!marker || seen.has(marker) || !conversation.includes(marker)) {
2952
+ if (part.type !== "image") {
2918
2953
  continue;
2919
2954
  }
2920
2955
  const image = imageFromPart(part);
2921
- if (image) {
2922
- seen.add(marker);
2923
- selected.push({ image, marker });
2956
+ const marker = image ? imageMarkerFromImage(image, nonce) : IMAGE_OMITTED_MARKER;
2957
+ if (!image || seen.has(marker) || !conversation.includes(marker)) {
2958
+ continue;
2924
2959
  }
2960
+ seen.add(marker);
2961
+ selected.push({ image, marker });
2925
2962
  }
2926
2963
  return { parts, selected };
2927
2964
  };
@@ -2995,20 +3032,30 @@ var readImageFiles = async (cwd, requested, enabled, kind, remainingBytes, remai
2995
3032
  return { images: [], omitted: names.length };
2996
3033
  }
2997
3034
  const seen = new Set;
2998
- const images = [];
2999
- let omitted = 0;
3000
- let bytes = 0;
3035
+ const candidates = [];
3001
3036
  for (const path of names) {
3002
3037
  const name = normalizeRequestedPath(root, path);
3003
- if (name && seen.has(name)) {
3038
+ if (!name || seen.has(name)) {
3004
3039
  continue;
3005
3040
  }
3006
- if (name) {
3007
- seen.add(name);
3041
+ seen.add(name);
3042
+ const mime = imageMime(name);
3043
+ if (mime) {
3044
+ candidates.push({ mime, name });
3008
3045
  }
3046
+ }
3047
+ let permitted;
3048
+ try {
3049
+ permitted = permittedPaths(root, candidates.map((candidate) => candidate.name), kind);
3050
+ } catch {
3051
+ return { images: [], omitted: names.length };
3052
+ }
3053
+ const images = [];
3054
+ let omitted = names.length - candidates.length;
3055
+ let bytes = 0;
3056
+ for (const { mime, name } of candidates) {
3009
3057
  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;
3058
+ const image = images.length < remainingCount && remainingBytes - bytes > 0 && permitted.has(name) ? await readImageAttachment(root, name, mime, remainingBytes - bytes) : undefined;
3012
3059
  if (image) {
3013
3060
  images.push(image);
3014
3061
  bytes += image.bytes;
@@ -4327,7 +4374,7 @@ var assembleConsultationContext = async (options) => {
4327
4374
  const allowed = advisorGitContextRef;
4328
4375
  const level = clampGitContextLevel(options.gitContext ?? allowed, allowed);
4329
4376
  const gitBudget = advisorGitContextBudget(contextMaxCharsRef, advisorGitContextMaxCharsRef);
4330
- const changes = collectGitContext(ctx.cwd, level, gitBudget, advisorRedactSecretsRef ? redactSecrets : undefined);
4377
+ const changes = await collectGitContext(ctx.cwd, level, gitBudget, advisorRedactSecretsRef ? redactSecrets : undefined);
4331
4378
  const changeText = advisorRepositoryContext(changes, options.gitContext ?? allowed, level, gitBudget);
4332
4379
  const conversationBudget = Math.max(0, contextMaxCharsRef - changeText.length);
4333
4380
  const imageNonce = randomUUID2();
@@ -4793,6 +4840,12 @@ import {
4793
4840
  import { existsSync as existsSync2, readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
4794
4841
  import { join as join3 } from "node:path";
4795
4842
  import { getAgentDir as getAgentDir3 } from "@earendil-works/pi-coding-agent";
4843
+ var liveSettingsReader;
4844
+ var liveCache;
4845
+ var setLivePiSettings = (reader) => {
4846
+ liveSettingsReader = reader;
4847
+ liveCache = undefined;
4848
+ };
4796
4849
  var SETTING_RECHECK_INTERVAL_MS = 2000;
4797
4850
  var cache = new Map;
4798
4851
  var settingsIdentity = (path) => {
@@ -4812,6 +4865,19 @@ var readHideThinking = (path) => {
4812
4865
  }
4813
4866
  };
4814
4867
  var piHideThinkingEnabled = () => {
4868
+ if (liveSettingsReader) {
4869
+ const now = Date.now();
4870
+ if (!liveCache || now - liveCache.readAt >= SETTING_RECHECK_INTERVAL_MS) {
4871
+ const effective = liveSettingsReader();
4872
+ liveCache = {
4873
+ hidden: effective?.hideThinkingBlock,
4874
+ readAt: now
4875
+ };
4876
+ }
4877
+ if (liveCache.hidden !== undefined) {
4878
+ return liveCache.hidden;
4879
+ }
4880
+ }
4815
4881
  const path = join3(getAgentDir3(), "settings.json");
4816
4882
  if (!existsSync2(path)) {
4817
4883
  return false;
@@ -5823,7 +5889,9 @@ var resolveActivationModels = async (runtime, ctx, canContinue) => {
5823
5889
  error: `${t("activation.noExecutorApiKey.prefix", "No API key for Executor")} ${executorRef}`
5824
5890
  };
5825
5891
  }
5826
- return {};
5892
+ return {
5893
+ switchedExecutor: Boolean(executor) && !isMarkedSubagent()
5894
+ };
5827
5895
  };
5828
5896
  var restoreActivationRefsIfCurrent = (canContinue, restoreRefs) => {
5829
5897
  if (canContinue()) {
@@ -5858,7 +5926,7 @@ var restoreActivationRefs = (previous, attempted) => {
5858
5926
  setExecutorEffortRef(previous.executorEffort);
5859
5927
  }
5860
5928
  };
5861
- var persistSuccessfulActivation = (ctx, shouldSave, reenableTools, restoreRefs) => {
5929
+ var persistSuccessfulActivation = async (ctx, shouldSave, reenableTools, restoreRefs, restoreHostModel) => {
5862
5930
  if (!shouldSave) {
5863
5931
  return true;
5864
5932
  }
@@ -5866,10 +5934,12 @@ var persistSuccessfulActivation = (ctx, shouldSave, reenableTools, restoreRefs)
5866
5934
  saveConfig(ctx, { persistAdvisor: true, persistExecutor: true });
5867
5935
  } catch (saveError) {
5868
5936
  if (!reenableTools) {
5937
+ await restoreHostModel();
5869
5938
  throw saveError;
5870
5939
  }
5871
5940
  setAdvisorToolsEnabledRef(false);
5872
5941
  restoreRefs();
5942
+ await restoreHostModel();
5873
5943
  const message = saveError instanceof Error ? saveError.message : String(saveError);
5874
5944
  notify(ctx, `${t("activation.saveFailed.prefix", "Could not save Advisor activation:")} ${message}`, "error");
5875
5945
  return false;
@@ -5901,13 +5971,15 @@ var activateAdvisor = async (runtime, args, ctx, announce = true) => {
5901
5971
  notify(ctx, argumentError, "error");
5902
5972
  return false;
5903
5973
  }
5974
+ attempted = liveRefSnapshot();
5904
5975
  const prepared = await prepareActivationModels(runtime, ctx, announce, executorOverride, advisorOverride, canContinue);
5905
5976
  if (!prepared) {
5906
5977
  attempted = liveRefSnapshot();
5907
5978
  restoreActivationRefsIfCurrent(canContinue, () => restoreRefs(attempted));
5908
5979
  return false;
5909
5980
  }
5910
- const { cancelled, error } = await resolveActivationModels(runtime, ctx, canContinue);
5981
+ const entryModel = ctx.model;
5982
+ const { cancelled, error, switchedExecutor } = await resolveActivationModels(runtime, ctx, canContinue);
5911
5983
  if (cancelled || !canContinue()) {
5912
5984
  return false;
5913
5985
  }
@@ -5922,7 +5994,8 @@ var activateAdvisor = async (runtime, args, ctx, announce = true) => {
5922
5994
  setAdvisorToolsEnabledRef(true);
5923
5995
  }
5924
5996
  const shouldSave = !sessionScoped && Boolean(args.trim() || prepared.pickedModels || reenableTools);
5925
- if (!persistSuccessfulActivation(ctx, shouldSave, reenableTools, () => restoreRefs(liveRefSnapshot()))) {
5997
+ const restoreHostModel = () => switchedExecutor && entryModel ? runtime.setExecutorModel(entryModel) : Promise.resolve(false);
5998
+ if (!await persistSuccessfulActivation(ctx, shouldSave, reenableTools, () => restoreRefs(liveRefSnapshot()), restoreHostModel)) {
5926
5999
  return false;
5927
6000
  }
5928
6001
  if (executorEffortRef && !isMarkedSubagent()) {
@@ -6903,12 +6976,44 @@ class ManualAdvisorDialog {
6903
6976
  }
6904
6977
 
6905
6978
  // src/jev/classifier-key-store.ts
6906
- import { chmodSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
6979
+ import { readFileSync as readFileSync3, rmSync } from "node:fs";
6907
6980
  import { join as join4 } from "node:path";
6908
6981
  import { getAgentDir as getAgentDir4 } from "@earendil-works/pi-coding-agent";
6982
+
6983
+ // src/jev/key-file.ts
6984
+ import { randomUUID as randomUUID4 } from "node:crypto";
6985
+ import {
6986
+ closeSync as closeSync2,
6987
+ openSync as openSync2,
6988
+ renameSync as renameSync2,
6989
+ unlinkSync as unlinkSync2,
6990
+ writeFileSync as writeFileSync2
6991
+ } from "node:fs";
6992
+ var KEY_FILE_MODE = 384;
6993
+ var writeKeyFile = (path, key) => {
6994
+ const temporaryPath = `${path}.${process.pid}.${randomUUID4()}.tmp`;
6995
+ let fileDescriptor;
6996
+ try {
6997
+ fileDescriptor = openSync2(temporaryPath, "wx", KEY_FILE_MODE);
6998
+ writeFileSync2(fileDescriptor, `${key}
6999
+ `, "utf-8");
7000
+ closeSync2(fileDescriptor);
7001
+ fileDescriptor = undefined;
7002
+ renameSync2(temporaryPath, path);
7003
+ } catch (error) {
7004
+ if (fileDescriptor !== undefined) {
7005
+ closeSync2(fileDescriptor);
7006
+ }
7007
+ try {
7008
+ unlinkSync2(temporaryPath);
7009
+ } catch {}
7010
+ throw error;
7011
+ }
7012
+ };
7013
+
7014
+ // src/jev/classifier-key-store.ts
6909
7015
  var JEV_CLASSIFIER_KEY_SERVICE = "pi-advisor-jev-classifier";
6910
7016
  var JEV_CLASSIFIER_KEY_NAME = "classifier-api-key";
6911
- var KEY_FILE_MODE = 384;
6912
7017
  var keyFilePath = () => join4(getAgentDir4(), "jev_classifier_api_key");
6913
7018
  var classifierKeyFailClosed = false;
6914
7019
  var disableJevClassifierKeyForRuntime = () => {
@@ -6928,12 +7033,7 @@ var defaultReadFile = () => {
6928
7033
  return;
6929
7034
  }
6930
7035
  };
6931
- var defaultWriteFile = (key) => {
6932
- const path = keyFilePath();
6933
- writeFileSync2(path, `${key}
6934
- `, { mode: KEY_FILE_MODE });
6935
- chmodSync(path, KEY_FILE_MODE);
6936
- };
7036
+ var defaultWriteFile = (key) => writeKeyFile(keyFilePath(), key);
6937
7037
  var readJevClassifierKey = async (deps = {}) => {
6938
7038
  const secrets = deps.secrets === undefined ? runtimeSecrets() : deps.secrets;
6939
7039
  if (secrets) {
@@ -9580,7 +9680,7 @@ var saveAdvisorSettings = (ctx, settings, options = {}) => {
9580
9680
  persistAdvisor: Boolean(persisted.advisor),
9581
9681
  persistExecutor: Boolean(persisted.executor)
9582
9682
  });
9583
- if (!options.skipOutcomeLogging) {
9683
+ if (!options.skipOutcomeLogging && (settings.outcomeLogging ?? false) !== previous.outcomeLogging) {
9584
9684
  saveGlobalOutcomeLogging(settings.outcomeLogging ?? false);
9585
9685
  }
9586
9686
  if (previous.advisorActivation === "session") {
@@ -10869,6 +10969,7 @@ try {
10869
10969
  loader.registerLocalesFromDir(I18N_NAMESPACE, new URL("../", import.meta.url).href, { label: "pi-advisor" });
10870
10970
  } catch {}
10871
10971
  function registerPiAdvisor(pi) {
10972
+ setLivePiSettings(() => pi.getSettings?.());
10872
10973
  const sessionState = new AdvisorSessionState;
10873
10974
  const scoutStatus = new ScoutStatusManager;
10874
10975
  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
 
package/docs/privacy.md CHANGED
@@ -24,6 +24,7 @@ The `advisor_config` tool reads recognized effective settings and persisted glob
24
24
  - `advisorGitContextMaxChars` defaults to `20000`. Repository context may claim its own cap or half of `contextMaxChars`, whichever is smaller, so it cannot crowd out the conversation.
25
25
  - The Executor may pass `gitContext` to `ask_advisor` as `none`, `summary`, or `full`. `advisorGitContext` is the ceiling. A larger request is narrowed to the configured level, and the Advisor is told that a fuller view was withheld.
26
26
  - `summary` deliberately excludes diff hunk headers. Git derives those from surrounding file content, so a hunk header can reproduce a line the change never touched, including a credential.
27
+ - Collection runs every `git diff` with `--no-ext-diff --no-textconv`, so external diff drivers and textconv filters configured in a repository never execute and their output never reaches the Advisor.
27
28
  - Redaction runs before the region is capped. Repository content is labelled as untrusted data, and paths and patch text are escaped so a crafted path cannot close the region early and have the remainder read as instructions.
28
29
  - File names can be sensitive. `summary` withholds file contents, not file names; use `off` when names must not leave the machine.
29
30
  - Collection shares a single overall time budget across its Git commands and degrades to a stated failure rather than implying a clean tree.
@@ -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
  }
package/locales/fr.json CHANGED
@@ -333,5 +333,7 @@
333
333
  "usage.call": "appel",
334
334
  "usage.calls": "appels",
335
335
  "usage.unavailable": "indisponible",
336
- "usage.withoutData": "sans données d'utilisation"
336
+ "usage.withoutData": "sans données d'utilisation",
337
+ "jevSetup.providerKeyRestored": "Fournisseur vérifié, mais les réglages n'ont pas pu être enregistrés ; la clé précédente a été restaurée.",
338
+ "jevSetup.providerKeyNotRestored": "Fournisseur vérifié, mais les réglages n'ont pas pu être enregistrés et la clé précédente n'a pas pu être restaurée. Saisissez une clé valide avant de réessayer."
337
339
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-advisor-flow",
3
- "version": "0.17.1-dev.2",
3
+ "version": "0.17.1-dev.4",
4
4
  "description": "Advanced Executor/Advisor flow for Pi, fully configurable and extendable.",
5
5
  "keywords": [
6
6
  "advisor",
@@ -62,18 +62,18 @@
62
62
  "format:check": "bun fmt --no-script --print-width 80 --trailing-comma es5 --sort-imports --bracket-same-line --ignore-pattern 'bench/tasks/**/traps.toml' --ignore-pattern 'dist/**' --check"
63
63
  },
64
64
  "devDependencies": {
65
- "@earendil-works/pi-ai": "1.6.0",
66
- "@earendil-works/pi-coding-agent": "1.6.0",
67
- "@earendil-works/pi-tui": "1.6.0",
65
+ "@earendil-works/pi-ai": "1.6.1",
66
+ "@earendil-works/pi-coding-agent": "1.6.1",
67
+ "@earendil-works/pi-tui": "1.6.1",
68
68
  "@juicesharp/rpiv-i18n": "2.15.0",
69
- "@oxlint/plugins": "1.94.0",
70
- "@types/node": "^26.6.6",
69
+ "@oxlint/plugins": "1.95.0",
70
+ "@types/node": "^26.6.11",
71
71
  "@typesafe-ai/sdk": "^0.7.0",
72
72
  "bun-types": "1.4.5",
73
73
  "husky": "^9.1.7",
74
- "knip": "6.47.0",
75
- "lint-staged": "^17.6.1",
76
- "oxlint": "1.94.0",
74
+ "knip": "6.48.0",
75
+ "lint-staged": "^17.6.2",
76
+ "oxlint": "1.95.0",
77
77
  "typebox": "1.4.7",
78
78
  "typescript": "^7.0.2",
79
79
  "ultracite": "8.3.1"
@@ -110,7 +110,7 @@
110
110
  "safe-buffer": "npm:@socketregistry/safe-buffer@1.0.9",
111
111
  "undici": "8.12.2"
112
112
  },
113
- "packageManager": "bun@1.4.4",
113
+ "packageManager": "bun@1.4.5",
114
114
  "pi": {
115
115
  "extensions": [
116
116
  "./dist/index.js"
@@ -66,7 +66,7 @@ if (
66
66
  !isAtLeast(currentVersion, minimumVersion)
67
67
  ) {
68
68
  console.error(
69
- `This repository requires Bun ${minimumVersion ?? "1.4.4"} or newer; found ${currentVersion ?? "a non-Bun package manager"}.`
69
+ `This repository requires Bun ${minimumVersion ?? "1.4.5"} or newer; found ${currentVersion ?? "a non-Bun package manager"}.`
70
70
  );
71
71
  process.exitCode = 1;
72
72
  } else {