pi-advisor-flow 0.15.1 → 0.15.2-dev.2

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 (72) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +17 -2
  3. package/dist/index.js +1194 -506
  4. package/docs/README.md +9 -0
  5. package/docs/benchmark.md +22 -0
  6. package/docs/configuration.md +194 -0
  7. package/docs/development.md +38 -0
  8. package/docs/herdr.md +169 -0
  9. package/docs/privacy.md +102 -0
  10. package/extensions/index.ts +23 -0
  11. package/locales/de.json +330 -0
  12. package/locales/en.json +331 -0
  13. package/locales/es.json +3 -0
  14. package/locales/fr.json +330 -0
  15. package/locales/pt-BR.json +3 -0
  16. package/locales/pt.json +3 -0
  17. package/locales/ru.json +3 -0
  18. package/locales/uk.json +3 -0
  19. package/locales/zh.json +3 -0
  20. package/package.json +15 -2
  21. package/skills/pi-advisor-flow/SKILL.md +62 -0
  22. package/src/commands/activation-preparation.ts +9 -2
  23. package/src/commands/activation.ts +28 -8
  24. package/src/commands/configuration-tool-models.ts +143 -0
  25. package/src/commands/configuration-tool-policy.ts +177 -0
  26. package/src/commands/configuration-tool-preview.ts +228 -0
  27. package/src/commands/configuration-tool-runtime.ts +40 -0
  28. package/src/commands/configuration-tool-transaction.ts +120 -0
  29. package/src/commands/configuration-tool-update.ts +230 -0
  30. package/src/commands/configuration-tool.ts +89 -0
  31. package/src/commands/lifecycle.ts +6 -1
  32. package/src/commands/manual-consultation.ts +6 -1
  33. package/src/commands/manual-progress.ts +4 -3
  34. package/src/commands/model-commands.ts +2 -1
  35. package/src/commands/model-options.ts +4 -6
  36. package/src/commands/model-picker.ts +16 -6
  37. package/src/commands/registration.ts +2 -0
  38. package/src/commands/runtime.ts +17 -4
  39. package/src/commands/settings-commands.ts +30 -7
  40. package/src/config/schema-validators.ts +104 -0
  41. package/src/config/schema.ts +35 -102
  42. package/src/config/storage.ts +160 -7
  43. package/src/i18n.ts +31 -0
  44. package/src/redaction.ts +64 -19
  45. package/src/scout-group-serialization.ts +66 -0
  46. package/src/scout-groups.ts +3 -66
  47. package/src/scout-selection.ts +99 -0
  48. package/src/scout.ts +6 -93
  49. package/src/session-state.ts +27 -137
  50. package/src/tool-input-normalization.ts +119 -0
  51. package/src/tools/gate-policy.ts +13 -5
  52. package/src/tools/jev-filter.ts +2 -1
  53. package/src/tools/jev-turn-gate.ts +2 -1
  54. package/src/tools/register-lifecycle.ts +5 -1
  55. package/src/tools/register-outcome.ts +5 -1
  56. package/src/tools/register-renderers.ts +5 -2
  57. package/src/tools/render-advisor-result.ts +20 -8
  58. package/src/tools/render-common.ts +16 -4
  59. package/src/tools/scout-status.ts +10 -2
  60. package/src/ui/jev-classifier-submenu.ts +143 -38
  61. package/src/ui/jev-filter-submenu.ts +52 -14
  62. package/src/ui/jev-provider-submenu-view.ts +72 -20
  63. package/src/ui/jev-provider-submenu.ts +40 -12
  64. package/src/ui/jev-setup-support.ts +48 -19
  65. package/src/ui/manual-dialog-render.ts +71 -25
  66. package/src/ui/searchable-model-list.ts +18 -4
  67. package/src/ui/settings-formatting.ts +5 -2
  68. package/src/ui/settings-items-jev.ts +216 -0
  69. package/src/ui/settings-items.ts +216 -259
  70. package/src/ui/settings-selector.ts +9 -2
  71. package/src/ui/text-setting-submenu.ts +8 -1
  72. package/src/usage.ts +9 -3
@@ -0,0 +1,104 @@
1
+ import { isString } from "../content-utils.ts";
2
+ import { normalizeJevBaseUrl } from "../jev/base-url.ts";
3
+ import {
4
+ ADVISOR_TOOL_POLICIES,
5
+ GATE_FAILURE_MODES,
6
+ JEV_TRANSPORTS,
7
+ MAX_CONTEXT_MAX_CHARS,
8
+ MAX_SCOUT_TIMEOUT_MS,
9
+ } from "./types.ts";
10
+ import type { JevTransport } from "./types.ts";
11
+
12
+ const isNonEmptyModel = (model: unknown): model is string =>
13
+ typeof model === "string" && model.trim().length > 0;
14
+
15
+ export const isValidAdvisorModelWhitelist = (
16
+ value: unknown
17
+ ): value is string[] => Array.isArray(value) && value.every(isNonEmptyModel);
18
+
19
+ const ADVISOR_TOOL_POLICY_NAMES = new Set<string>(ADVISOR_TOOL_POLICIES);
20
+
21
+ export const isValidAdvisorToolPolicies = (
22
+ value: unknown
23
+ ): value is Record<string, (typeof ADVISOR_TOOL_POLICIES)[number]> => {
24
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
25
+ return false;
26
+ }
27
+
28
+ return Object.entries(value).every(
29
+ ([toolName, policy]) =>
30
+ toolName.trim().length > 0 &&
31
+ isString(policy) &&
32
+ ADVISOR_TOOL_POLICY_NAMES.has(policy)
33
+ );
34
+ };
35
+
36
+ export const isValidNonNegativeSafeInteger = (
37
+ value: unknown
38
+ ): value is number =>
39
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
40
+
41
+ export const isValidContextMaxChars = (value: unknown): value is number =>
42
+ typeof value === "number" &&
43
+ Number.isSafeInteger(value) &&
44
+ value >= 0 &&
45
+ value <= MAX_CONTEXT_MAX_CHARS;
46
+
47
+ export const isValidLoopThreshold = (value: unknown): value is number =>
48
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 2;
49
+
50
+ export const isValidMaxCallsPerSession = (value: unknown): value is number =>
51
+ isValidNonNegativeSafeInteger(value);
52
+
53
+ const GATE_FAILURE_MODE_NAMES = new Set<string>(GATE_FAILURE_MODES);
54
+
55
+ export const isValidGateFailureMode = (
56
+ value: unknown
57
+ ): value is (typeof GATE_FAILURE_MODES)[number] =>
58
+ isString(value) && GATE_FAILURE_MODE_NAMES.has(value);
59
+
60
+ export const isValidToolResultMaxLines = (value: unknown): value is number =>
61
+ isValidNonNegativeSafeInteger(value);
62
+
63
+ export const isValidToolResultMaxBytes = (value: unknown): value is number =>
64
+ isValidNonNegativeSafeInteger(value);
65
+
66
+ export const isValidJevTimeoutMs = (value: unknown): value is number =>
67
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
68
+
69
+ export const isValidScoutTimeoutMs = (value: unknown): value is number =>
70
+ typeof value === "number" &&
71
+ Number.isSafeInteger(value) &&
72
+ value >= 1 &&
73
+ value <= MAX_SCOUT_TIMEOUT_MS;
74
+
75
+ export const isValidJevDigestMaxChars = (value: unknown): value is number =>
76
+ isValidNonNegativeSafeInteger(value);
77
+
78
+ export const isValidJevPricePerMtok = (value: unknown): value is number =>
79
+ typeof value === "number" && Number.isFinite(value) && value > 0;
80
+
81
+ export const isValidJevSkipConfidence = (value: unknown): value is number =>
82
+ typeof value === "number" &&
83
+ Number.isFinite(value) &&
84
+ value >= 0.5 &&
85
+ value <= 1;
86
+
87
+ export const isValidJevNoulMargin = (value: unknown): value is number =>
88
+ typeof value === "number" &&
89
+ Number.isFinite(value) &&
90
+ value >= 0 &&
91
+ value <= 0.5;
92
+
93
+ const JEV_TRANSPORT_NAMES = new Set<string>(JEV_TRANSPORTS);
94
+
95
+ export const isValidJevTransport = (value: unknown): value is JevTransport =>
96
+ isString(value) && JEV_TRANSPORT_NAMES.has(value);
97
+
98
+ /** An empty value clears the endpoint; anything else must be a usable Base URL. */
99
+ export const isValidJevBaseUrl = (value: unknown): value is string =>
100
+ isString(value) &&
101
+ (value.trim() === "" || normalizeJevBaseUrl(value).baseUrl !== undefined);
102
+
103
+ export const isValidJevKeyProvider = (value: unknown): value is string =>
104
+ isString(value) && (value.trim() === "" || !/\s/u.test(value.trim()));
@@ -1,7 +1,26 @@
1
1
  import { isString } from "../content-utils.ts";
2
2
  import type { JsonValue } from "../content-utils.ts";
3
3
  import { GIT_CONTEXT_LEVELS, isValidGitContextLevel } from "../git.ts";
4
- import { normalizeJevBaseUrl } from "../jev/base-url.ts";
4
+ import {
5
+ isValidAdvisorModelWhitelist,
6
+ isValidAdvisorToolPolicies,
7
+ isValidContextMaxChars,
8
+ isValidGateFailureMode,
9
+ isValidJevBaseUrl,
10
+ isValidJevDigestMaxChars,
11
+ isValidJevKeyProvider,
12
+ isValidJevNoulMargin,
13
+ isValidJevPricePerMtok,
14
+ isValidJevSkipConfidence,
15
+ isValidJevTimeoutMs,
16
+ isValidJevTransport,
17
+ isValidLoopThreshold,
18
+ isValidMaxCallsPerSession,
19
+ isValidNonNegativeSafeInteger,
20
+ isValidScoutTimeoutMs,
21
+ isValidToolResultMaxBytes,
22
+ isValidToolResultMaxLines,
23
+ } from "./schema-validators.ts";
5
24
  import {
6
25
  advisorAgentsMdContextRef,
7
26
  advisorAutoLoopGateRef,
@@ -56,115 +75,29 @@ import {
56
75
  showUsageFooterRef,
57
76
  simpleModeRef,
58
77
  } from "./state.ts";
59
- import type {
60
- AdvisorConfig,
61
- AdvisorConfigValue,
62
- JevTransport,
63
- } from "./types.ts";
78
+ import type { AdvisorConfig, AdvisorConfigValue } from "./types.ts";
64
79
  import {
65
- ADVISOR_TOOL_POLICIES,
66
80
  GATE_FAILURE_MODES,
67
81
  JEV_TRANSPORTS,
68
82
  MAX_CONTEXT_MAX_CHARS,
69
83
  MAX_SCOUT_TIMEOUT_MS,
70
84
  } from "./types.ts";
71
85
 
86
+ export {
87
+ isValidAdvisorModelWhitelist,
88
+ isValidAdvisorToolPolicies,
89
+ isValidContextMaxChars,
90
+ isValidGateFailureMode,
91
+ isValidLoopThreshold,
92
+ isValidMaxCallsPerSession,
93
+ isValidToolResultMaxBytes,
94
+ isValidToolResultMaxLines,
95
+ } from "./schema-validators.ts";
96
+
72
97
  /** An empty ref means no model has been selected yet. */
73
98
  const configuredModelRef = (value: string | undefined): string | undefined =>
74
99
  value?.trim() || undefined;
75
100
 
76
- const isNonEmptyModel = (model: unknown): model is string =>
77
- typeof model === "string" && model.trim().length > 0;
78
-
79
- export const isValidAdvisorModelWhitelist = (
80
- value: unknown
81
- ): value is string[] => Array.isArray(value) && value.every(isNonEmptyModel);
82
-
83
- const ADVISOR_TOOL_POLICY_NAMES = new Set<string>(ADVISOR_TOOL_POLICIES);
84
-
85
- export const isValidAdvisorToolPolicies = (
86
- value: unknown
87
- ): value is Record<string, (typeof ADVISOR_TOOL_POLICIES)[number]> => {
88
- if (!value || typeof value !== "object" || Array.isArray(value)) {
89
- return false;
90
- }
91
-
92
- return Object.entries(value).every(
93
- ([toolName, policy]) =>
94
- toolName.trim().length > 0 &&
95
- isString(policy) &&
96
- ADVISOR_TOOL_POLICY_NAMES.has(policy)
97
- );
98
- };
99
-
100
- const nonNegativeSafeInteger = (value: unknown): value is number =>
101
- typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
102
-
103
- export const isValidContextMaxChars = (value: unknown): value is number =>
104
- typeof value === "number" &&
105
- Number.isSafeInteger(value) &&
106
- value >= 0 &&
107
- value <= MAX_CONTEXT_MAX_CHARS;
108
-
109
- export const isValidLoopThreshold = (value: unknown): value is number =>
110
- typeof value === "number" && Number.isSafeInteger(value) && value >= 2;
111
-
112
- export const isValidMaxCallsPerSession = (value: unknown): value is number =>
113
- nonNegativeSafeInteger(value);
114
-
115
- const GATE_FAILURE_MODE_NAMES = new Set<string>(GATE_FAILURE_MODES);
116
-
117
- export const isValidGateFailureMode = (
118
- value: unknown
119
- ): value is (typeof GATE_FAILURE_MODES)[number] =>
120
- isString(value) && GATE_FAILURE_MODE_NAMES.has(value);
121
-
122
- export const isValidToolResultMaxLines = (value: unknown): value is number =>
123
- nonNegativeSafeInteger(value);
124
-
125
- export const isValidToolResultMaxBytes = (value: unknown): value is number =>
126
- nonNegativeSafeInteger(value);
127
-
128
- const isValidJevTimeoutMs = (value: unknown): value is number =>
129
- typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
130
-
131
- const isValidScoutTimeoutMs = (value: unknown): value is number =>
132
- typeof value === "number" &&
133
- Number.isSafeInteger(value) &&
134
- value >= 1 &&
135
- value <= MAX_SCOUT_TIMEOUT_MS;
136
-
137
- const isValidJevDigestMaxChars = (value: unknown): value is number =>
138
- nonNegativeSafeInteger(value);
139
-
140
- const isValidJevPricePerMtok = (value: unknown): value is number =>
141
- typeof value === "number" && Number.isFinite(value) && value > 0;
142
-
143
- const isValidJevSkipConfidence = (value: unknown): value is number =>
144
- typeof value === "number" &&
145
- Number.isFinite(value) &&
146
- value >= 0.5 &&
147
- value <= 1;
148
-
149
- const isValidJevNoulMargin = (value: unknown): value is number =>
150
- typeof value === "number" &&
151
- Number.isFinite(value) &&
152
- value >= 0 &&
153
- value <= 0.5;
154
-
155
- const JEV_TRANSPORT_NAMES = new Set<string>(JEV_TRANSPORTS);
156
-
157
- const isValidJevTransport = (value: unknown): value is JevTransport =>
158
- isString(value) && JEV_TRANSPORT_NAMES.has(value);
159
-
160
- /** An empty value clears the endpoint; anything else must be a usable Base URL. */
161
- const isValidJevBaseUrl = (value: unknown): value is string =>
162
- isString(value) &&
163
- (value.trim() === "" || normalizeJevBaseUrl(value).baseUrl !== undefined);
164
-
165
- const isValidJevKeyProvider = (value: unknown): value is string =>
166
- isString(value) && (value.trim() === "" || !/\s/u.test(value.trim()));
167
-
168
101
  /** One declarative entry per AdvisorConfig key: JSON type, persistence, and
169
102
  * the live runtime value behind it. Validation and storage derive from this
170
103
  * table; adding a setting means adding exactly one entry here. */
@@ -260,7 +193,7 @@ export const CONFIG_SCHEMA = {
260
193
  current: () => advisorGitContextMaxCharsRef,
261
194
  persisted: true,
262
195
  type: "number",
263
- validate: nonNegativeSafeInteger,
196
+ validate: isValidNonNegativeSafeInteger,
264
197
  },
265
198
  advisorHerdrIntegration: {
266
199
  accepted: "true or false",
@@ -310,7 +243,7 @@ export const CONFIG_SCHEMA = {
310
243
  current: () => advisorJevFilterOverrideWindowRef,
311
244
  persisted: true,
312
245
  type: "number",
313
- validate: nonNegativeSafeInteger,
246
+ validate: isValidNonNegativeSafeInteger,
314
247
  },
315
248
  advisorJevFilterSkipConfidence: {
316
249
  accepted: "a number between 0.5 and 1 inclusive",
@@ -358,7 +291,7 @@ export const CONFIG_SCHEMA = {
358
291
  current: () => advisorJevTurnGateEveryTurnsRef,
359
292
  persisted: true,
360
293
  type: "number",
361
- validate: nonNegativeSafeInteger,
294
+ validate: isValidNonNegativeSafeInteger,
362
295
  },
363
296
  advisorJevTurnGateNoulThreshold: {
364
297
  accepted: "a number between 0.5 and 1 inclusive",
@@ -1,11 +1,23 @@
1
- import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ closeSync,
4
+ existsSync,
5
+ fsyncSync,
6
+ openSync,
7
+ readFileSync,
8
+ renameSync,
9
+ statSync,
10
+ unlinkSync,
11
+ writeFileSync,
12
+ } from "node:fs";
2
13
  import { join } from "node:path";
3
14
 
4
15
  import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
5
16
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
17
 
7
18
  import { isRecord, isString } from "../content-utils.ts";
8
- import type { RecordValue } from "../content-utils.ts";
19
+ import type { JsonValue, RecordValue } from "../content-utils.ts";
20
+ import { t } from "../i18n.ts";
9
21
  import { applyConfig, resetDefaults } from "./defaults.ts";
10
22
  import {
11
23
  CONFIG_SCHEMA,
@@ -44,6 +56,8 @@ const currentConfigState = (): ConfigState =>
44
56
  const sameConfigValue = <Value>(left: Value, right: Value) =>
45
57
  JSON.stringify(left) === JSON.stringify(right);
46
58
 
59
+ const CONFIG_KEY_SET = new Set<string>(Object.keys(CONFIG_SCHEMA));
60
+
47
61
  /** Keys advisor.json may hold that are not AdvisorConfig settings but are
48
62
  * still legitimate (hand-placed secrets). They stay out of CONFIG_SCHEMA, are
49
63
  * preserved like any unknown key, and never trigger the typo warning. */
@@ -175,6 +189,9 @@ const configIdentity = (path: string): string => {
175
189
  }
176
190
  };
177
191
 
192
+ const configFileIdentity = (path: string) =>
193
+ existsSync(path) ? configIdentity(path) : null;
194
+
178
195
  const readConfigCached = (path: string): AdvisorConfig => {
179
196
  const identity = configIdentity(path);
180
197
  const cached = configCache.get(path);
@@ -215,7 +232,10 @@ export const loadConfig = (_ctx: ExtensionContext) => {
215
232
  ) {
216
233
  warnedFilterWithoutClassifierIdentities.add(warningIdentity);
217
234
  _ctx.ui.notify(
218
- "The Jev consultation filter is enabled but no Jev classifier is selected; consultations are not screened until you pick one in /advisor-settings.",
235
+ t(
236
+ "notify.jevFilterNoClassifier.message",
237
+ "The Jev consultation filter is enabled but no Jev classifier is selected; consultations are not screened until you pick one in /advisor-settings."
238
+ ),
219
239
  "warning"
220
240
  );
221
241
  }
@@ -230,7 +250,7 @@ export const loadConfig = (_ctx: ExtensionContext) => {
230
250
  !warnedUnknownConfigIdentities.has(warningIdentity)
231
251
  ) {
232
252
  _ctx.ui.notify(
233
- `Advisor configuration at ${global} contains unrecognized key(s) ${unknownKeys.map((key) => JSON.stringify(key)).join(", ")}. They were preserved but ignored; check for typos or upgrade pi-advisor.`,
253
+ `${t("notify.unknownConfigKeys.at", "Advisor configuration at")} ${global} ${t("notify.unknownConfigKeys.contains", "contains unrecognized key(s)")} ${unknownKeys.map((key) => JSON.stringify(key)).join(", ")}. ${t("notify.unknownConfigKeys.preserved", "They were preserved but ignored; check for typos or upgrade pi-advisor.")}`,
234
254
  "warning"
235
255
  );
236
256
  warnedUnknownConfigIdentities.add(warningIdentity);
@@ -258,6 +278,12 @@ export interface SaveConfigOptions {
258
278
  persistExecutor?: boolean;
259
279
  }
260
280
 
281
+ /** Marks the current live state as the new diff baseline without writing it. */
282
+ export const rebaseConfigBaseline = () => {
283
+ loadedConfigState = currentConfigState();
284
+ loadedConfigPath = join(getAgentDir(), "advisor.json");
285
+ };
286
+
261
287
  export const saveConfig = (
262
288
  _ctx: ExtensionContext,
263
289
  options: SaveConfigOptions = {}
@@ -318,15 +344,142 @@ export const saveConfig = (
318
344
  return path;
319
345
  };
320
346
 
347
+ const writeConfigAtomically = (
348
+ path: string,
349
+ contents: string,
350
+ expectedIdentity?: string | null
351
+ ) => {
352
+ const mode = existsSync(path) ? statSync(path).mode % 0o1000 : 0o600;
353
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
354
+ let fileDescriptor: number | undefined;
355
+
356
+ try {
357
+ fileDescriptor = openSync(temporaryPath, "wx", mode);
358
+ writeFileSync(fileDescriptor, contents, "utf-8");
359
+ fsyncSync(fileDescriptor);
360
+ closeSync(fileDescriptor);
361
+ fileDescriptor = undefined;
362
+
363
+ if (
364
+ expectedIdentity !== undefined &&
365
+ configFileIdentity(path) !== expectedIdentity
366
+ ) {
367
+ throw new Error(
368
+ "Advisor configuration changed during the update; retry so unrelated edits are preserved."
369
+ );
370
+ }
371
+
372
+ renameSync(temporaryPath, path);
373
+ } catch (error) {
374
+ if (fileDescriptor !== undefined) {
375
+ closeSync(fileDescriptor);
376
+ }
377
+
378
+ try {
379
+ unlinkSync(temporaryPath);
380
+ } catch {
381
+ // The temporary file may not have been created.
382
+ }
383
+
384
+ throw error;
385
+ }
386
+ };
387
+
321
388
  /** Outcome logging is deliberately written only to the global Pi configuration. */
322
- export const saveGlobalOutcomeLogging = (enabled: boolean) => {
389
+ export const saveGlobalOutcomeLogging = (
390
+ enabled: boolean | null,
391
+ expected?: Readonly<Record<string, JsonValue>>,
392
+ expectedKeys: readonly string[] = ["advisorOutcomeLogging"]
393
+ ) => {
323
394
  const path = join(getAgentDir(), "advisor.json");
395
+ const identity = configFileIdentity(path);
324
396
  const existing = readConfigForSave(path);
325
- writeFileSync(
397
+
398
+ if (
399
+ expected &&
400
+ expectedKeys.some(
401
+ (key) =>
402
+ Object.hasOwn(existing, key) !== Object.hasOwn(expected, key) ||
403
+ !sameConfigValue(existing[key], expected[key])
404
+ )
405
+ ) {
406
+ throw new Error(
407
+ "Advisor settings changed during confirmation; read the settings again and retry."
408
+ );
409
+ }
410
+
411
+ if (enabled === null) {
412
+ Reflect.deleteProperty(existing, "advisorOutcomeLogging");
413
+ } else {
414
+ existing.advisorOutcomeLogging = enabled;
415
+ }
416
+
417
+ writeConfigAtomically(
326
418
  path,
327
- `${JSON.stringify({ ...existing, advisorOutcomeLogging: enabled }, null, 2)}\n`
419
+ `${JSON.stringify(existing, null, 2)}\n`,
420
+ identity
328
421
  );
329
422
  resetConfigCache();
330
423
 
331
424
  return path;
332
425
  };
426
+
427
+ /** Applies a validated sparse patch to global advisor.json while preserving
428
+ * unrelated and unknown fields. A null value removes that setting override. */
429
+ export const readGlobalAdvisorConfig = () => {
430
+ const path = join(getAgentDir(), "advisor.json");
431
+ const config = readConfigForSave(path);
432
+ validateConfig(config, path);
433
+
434
+ return config;
435
+ };
436
+
437
+ export const saveGlobalAdvisorConfigPatch = (
438
+ patch: Readonly<Record<string, JsonValue | null>>,
439
+ expected?: Readonly<Record<string, JsonValue>>,
440
+ expectedKeys?: readonly string[]
441
+ ) => {
442
+ const path = join(getAgentDir(), "advisor.json");
443
+
444
+ const unknownKeys = Object.keys(patch).filter(
445
+ (key) => !CONFIG_KEY_SET.has(key)
446
+ );
447
+
448
+ if (unknownKeys.length > 0) {
449
+ throw new Error(
450
+ `Cannot update Advisor configuration: unsupported key(s) ${unknownKeys.map((key) => JSON.stringify(key)).join(", ")}.`
451
+ );
452
+ }
453
+
454
+ const identity = configFileIdentity(path);
455
+ const next = readConfigForSave(path);
456
+
457
+ const checkedKeys = expectedKeys ?? Object.keys(patch);
458
+
459
+ if (
460
+ expected &&
461
+ checkedKeys.some(
462
+ (key) =>
463
+ Object.hasOwn(next, key) !== Object.hasOwn(expected, key) ||
464
+ !sameConfigValue(next[key], expected[key])
465
+ )
466
+ ) {
467
+ throw new Error(
468
+ "Advisor settings changed during confirmation; read the settings again and retry."
469
+ );
470
+ }
471
+
472
+ for (const [key, value] of Object.entries(patch)) {
473
+ if (value === null) {
474
+ Reflect.deleteProperty(next, key);
475
+ } else {
476
+ next[key] = value;
477
+ }
478
+ }
479
+
480
+ validateConfig(next, path);
481
+ writeConfigAtomically(path, `${JSON.stringify(next, null, 2)}\n`, identity);
482
+ resetConfigCache();
483
+
484
+ return path;
485
+ };
package/src/i18n.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * i18n bridge for pi-advisor.
3
+ *
4
+ * The SDK (@juicesharp/rpiv-i18n) is an optional peer: when absent, every
5
+ * t(key, fallback) returns the fallback verbatim and the extension stays
6
+ * English-only. Top-level await is required because t is consumed
7
+ * synchronously by downstream modules.
8
+ */
9
+
10
+ const I18N_NAMESPACE = "pi-advisor-flow";
11
+
12
+ type ScopeFn = (key: string, fallback: string) => string;
13
+
14
+ interface I18nSDK {
15
+ scope: (namespace: string) => ScopeFn;
16
+ }
17
+
18
+ let scopeImpl: ScopeFn;
19
+
20
+ try {
21
+ // SAFETY: the optional-peer contract pins scope(namespace) to the synchronous lookup; a mismatching module rejects the import below.
22
+ const sdk = (await import("@juicesharp/rpiv-i18n")) as I18nSDK;
23
+ scopeImpl = sdk.scope(I18N_NAMESPACE);
24
+ } catch {
25
+ // SDK not installed — every t(key, fallback) returns the fallback verbatim.
26
+ scopeImpl = (_key, fallback) => fallback;
27
+ }
28
+
29
+ export { I18N_NAMESPACE };
30
+
31
+ export const t: ScopeFn = scopeImpl;
package/src/redaction.ts CHANGED
@@ -1,44 +1,89 @@
1
1
  import { capUtf8Bytes, isString } from "./content-utils.ts";
2
2
 
3
3
  const REDACTION_MARKER = "[REDACTED SECRET]";
4
- const PEM_BEGIN_PATTERN = /-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----/giu;
5
- const PEM_END_PATTERN = /-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/iu;
4
+ const MAX_REDACTION_CHARS = 65_536;
5
+ const OVERSIZED_MARKER = "[Redaction omitted: input exceeds 65536 characters]";
6
+
7
+ const PEM_MARKER_PATTERN =
8
+ /-----(?<action>BEGIN|END)(?: (?<type>[A-Z0-9]+))? PRIVATE KEY-----/giu;
9
+
6
10
  const CREDENTIAL_NAME = String.raw`(?:api[_-]?key|token|secret|password|passwd)`;
11
+ const ASSIGNMENT_START = String.raw`(?:(?:"(?:[a-z0-9]+[_-])*?${CREDENTIAL_NAME}"|'(?:[a-z0-9]+[_-])*?${CREDENTIAL_NAME}')|(?:\b|_)${CREDENTIAL_NAME})[ \t]*[:=][ \t]*`;
7
12
 
8
13
  const SECRET_ASSIGNMENT_PATTERN = new RegExp(
9
- String.raw`(?:(?:"(?:[a-z0-9]+[_-])*?${CREDENTIAL_NAME}"|'(?:[a-z0-9]+[_-])*?${CREDENTIAL_NAME}')|(?:\b|_)${CREDENTIAL_NAME})[ \t]*[:=][ \t]*(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|"(?:\\.|[^"\r\n])*(?=\r?\n|$)|'(?:\\.|[^'\r\n])*(?=\r?\n|$)|[^\s"'&,;)}\]]+)`,
14
+ String.raw`${ASSIGNMENT_START}(?:"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|"(?:\\[^\r\n]|[^"\\\r\n]|\\(?=\r?\n|\r|$))*(?=\r?\n|\r|$)|'(?:\\[^\r\n]|[^'\\\r\n]|\\(?=\r?\n|\r|$))*(?=\r?\n|\r|$)|[^\s"'&,;)}\]]+)`,
10
15
  "giu"
11
16
  );
12
17
 
18
+ const ASSIGNMENT_START_PATTERN = new RegExp(ASSIGNMENT_START, "giu");
19
+
20
+ const BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/giu;
21
+
13
22
  const SECRET_PATTERNS = [
14
- /-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/giu,
15
- /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/giu,
16
- SECRET_ASSIGNMENT_PATTERN,
17
- /(?<scheme>[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/giu,
23
+ /(?<scheme>(?<![a-z0-9+.-])[a-z0-9+.-]+:\/\/)[^\s/@:]+:[^\s/@]+@/giu,
18
24
  /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/gu,
19
25
  /\b(?:aws_secret_access_key|aws_session_token)\s*[:=]\s*[^\s"'&,;)}\]]+/giu,
20
26
  ] as const;
21
27
 
22
- const redactUnterminatedPem = (value: string): string => {
23
- const begins = [...value.matchAll(PEM_BEGIN_PATTERN)];
24
- const lastBegin = begins.at(-1);
28
+ const redactPem = (value: string): string => {
29
+ const parts: string[] = [];
30
+ const stack: string[] = [];
31
+ let copied = 0;
25
32
 
26
- if (lastBegin?.index === undefined) {
27
- return value;
33
+ for (const match of value.matchAll(PEM_MARKER_PATTERN)) {
34
+ const type = (match.groups?.type ?? "").toUpperCase();
35
+
36
+ if (match.groups?.action.toUpperCase() === "BEGIN") {
37
+ if (stack.length === 0) {
38
+ parts.push(value.slice(copied, match.index));
39
+ }
40
+
41
+ stack.push(type);
42
+ } else if (stack.length > 0) {
43
+ if (stack.pop() !== type) {
44
+ return `${parts.join("")}${REDACTION_MARKER}`;
45
+ }
46
+
47
+ if (stack.length === 0) {
48
+ parts.push(REDACTION_MARKER);
49
+ copied = match.index + match[0].length;
50
+ }
51
+ }
28
52
  }
29
53
 
30
- const hasEnd = PEM_END_PATTERN.test(
31
- value.slice(lastBegin.index + lastBegin[0].length)
32
- );
54
+ return stack.length > 0
55
+ ? `${parts.join("")}${REDACTION_MARKER}`
56
+ : `${parts.join("")}${value.slice(copied)}`;
57
+ };
58
+
59
+ const redactAssignments = (value: string): string => {
60
+ const parts: string[] = [];
61
+ let copied = 0;
62
+
63
+ for (const match of value.matchAll(SECRET_ASSIGNMENT_PATTERN)) {
64
+ parts.push(value.slice(copied, match.index), REDACTION_MARKER);
65
+
66
+ const starts = match[0].matchAll(ASSIGNMENT_START_PATTERN);
67
+ starts.next();
68
+
69
+ if (!starts.next().done) {
70
+ return parts.join("");
71
+ }
33
72
 
34
- return hasEnd
35
- ? value
36
- : `${value.slice(0, lastBegin.index)}${REDACTION_MARKER}`;
73
+ copied = match.index + match[0].length;
74
+ }
75
+
76
+ return `${parts.join("")}${value.slice(copied)}`;
37
77
  };
38
78
 
39
79
  /** Redacts common credential forms locally; it is not a data-classification system. */
40
80
  export const redactSecrets = (value: string): string => {
41
- let redacted = redactUnterminatedPem(value);
81
+ if (value.length > MAX_REDACTION_CHARS) {
82
+ return OVERSIZED_MARKER;
83
+ }
84
+
85
+ let redacted = redactPem(value).replaceAll(BEARER_PATTERN, REDACTION_MARKER);
86
+ redacted = redactAssignments(redacted);
42
87
 
43
88
  for (const pattern of SECRET_PATTERNS) {
44
89
  redacted = redacted.replace(pattern, (_match, scheme) =>