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

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 (71) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +16 -1
  3. package/dist/index.js +1157 -502
  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/scout-group-serialization.ts +66 -0
  45. package/src/scout-groups.ts +3 -66
  46. package/src/scout-selection.ts +99 -0
  47. package/src/scout.ts +6 -93
  48. package/src/session-state.ts +27 -137
  49. package/src/tool-input-normalization.ts +119 -0
  50. package/src/tools/gate-policy.ts +13 -5
  51. package/src/tools/jev-filter.ts +2 -1
  52. package/src/tools/jev-turn-gate.ts +2 -1
  53. package/src/tools/register-lifecycle.ts +5 -1
  54. package/src/tools/register-outcome.ts +5 -1
  55. package/src/tools/register-renderers.ts +5 -2
  56. package/src/tools/render-advisor-result.ts +20 -8
  57. package/src/tools/render-common.ts +16 -4
  58. package/src/tools/scout-status.ts +10 -2
  59. package/src/ui/jev-classifier-submenu.ts +143 -38
  60. package/src/ui/jev-filter-submenu.ts +52 -14
  61. package/src/ui/jev-provider-submenu-view.ts +72 -20
  62. package/src/ui/jev-provider-submenu.ts +40 -12
  63. package/src/ui/jev-setup-support.ts +48 -19
  64. package/src/ui/manual-dialog-render.ts +71 -25
  65. package/src/ui/searchable-model-list.ts +18 -4
  66. package/src/ui/settings-formatting.ts +5 -2
  67. package/src/ui/settings-items-jev.ts +216 -0
  68. package/src/ui/settings-items.ts +216 -259
  69. package/src/ui/settings-selector.ts +9 -2
  70. package/src/ui/text-setting-submenu.ts +8 -1
  71. package/src/usage.ts +9 -3
@@ -0,0 +1,99 @@
1
+ import { isRecord, isString } from "./content-utils.ts";
2
+ import {
3
+ SCOUT_SELECTION_MAX_IDS,
4
+ SCOUT_SYNTHESIS_MAX_BYTES,
5
+ } from "./scout-types.ts";
6
+ import type { ScoutManifest } from "./scout-types.ts";
7
+
8
+ export interface ScoutSelection {
9
+ selectedIds: string[];
10
+ synthesis: string;
11
+ }
12
+
13
+ const byteLength = (value: string) => Buffer.byteLength(value, "utf-8");
14
+
15
+ const isStringArray = (value: unknown): value is string[] =>
16
+ Array.isArray(value) && value.every(isString);
17
+
18
+ export const parseScoutSelection = (
19
+ text: string,
20
+ manifest: ScoutManifest
21
+ ): ScoutSelection => {
22
+ if (!text.trim()) {
23
+ throw new Error("Scout returned an empty response.");
24
+ }
25
+
26
+ let value: unknown;
27
+
28
+ try {
29
+ value = JSON.parse(text);
30
+ } catch (error) {
31
+ throw new Error("Scout response is not a JSON object.", { cause: error });
32
+ }
33
+
34
+ if (!isRecord(value)) {
35
+ throw new Error("Scout response must be a JSON object.");
36
+ }
37
+
38
+ const keys = Object.keys(value).toSorted();
39
+
40
+ if (
41
+ keys.length !== 2 ||
42
+ keys[0] !== "selectedIds" ||
43
+ keys[1] !== "synthesis"
44
+ ) {
45
+ throw new Error(
46
+ "Scout response must contain only selectedIds and synthesis."
47
+ );
48
+ }
49
+
50
+ if (!isStringArray(value.selectedIds)) {
51
+ throw new Error("Scout selectedIds must be an array of strings.");
52
+ }
53
+
54
+ const { selectedIds } = value;
55
+
56
+ if (new Set(selectedIds).size !== selectedIds.length) {
57
+ throw new Error("Scout selected duplicate group IDs.");
58
+ }
59
+
60
+ const known = new Set(manifest.groups.map((group) => group.id));
61
+ const knownSelectedIds = selectedIds.filter((id) => known.has(id));
62
+
63
+ const requiredIds = manifest.groups
64
+ .filter((group) => group.required)
65
+ .map((group) => group.id);
66
+
67
+ if (requiredIds.length > SCOUT_SELECTION_MAX_IDS) {
68
+ throw new Error(
69
+ `Manifest contains more than ${SCOUT_SELECTION_MAX_IDS} required groups.`
70
+ );
71
+ }
72
+
73
+ const required = new Set(requiredIds);
74
+
75
+ const optionalIds = knownSelectedIds
76
+ .filter((id) => !required.has(id))
77
+ .slice(0, SCOUT_SELECTION_MAX_IDS - requiredIds.length);
78
+
79
+ const retained = new Set([...requiredIds, ...optionalIds]);
80
+
81
+ const normalizedIds = manifest.groups
82
+ .filter((group) => retained.has(group.id))
83
+ .map((group) => group.id);
84
+
85
+ if (!isString(value.synthesis)) {
86
+ throw new TypeError("Scout synthesis must be a string.");
87
+ }
88
+
89
+ if (byteLength(value.synthesis) > SCOUT_SYNTHESIS_MAX_BYTES) {
90
+ throw new Error(
91
+ `Scout synthesis exceeds ${SCOUT_SYNTHESIS_MAX_BYTES} UTF-8 bytes.`
92
+ );
93
+ }
94
+
95
+ return {
96
+ selectedIds: normalizedIds,
97
+ synthesis: knownSelectedIds.length > 0 ? value.synthesis : "",
98
+ };
99
+ };
package/src/scout.ts CHANGED
@@ -6,7 +6,6 @@ import {
6
6
  effectiveExecutorRef,
7
7
  } from "./child-session.ts";
8
8
  import { advisorScoutTimeoutMsRef } from "./config/state.ts";
9
- import { isRecord, isString } from "./content-utils.ts";
10
9
  import { collectTextStream, resolveConfiguredModel } from "./model-stream.ts";
11
10
  import type {
12
11
  CollectedTextStream,
@@ -14,6 +13,8 @@ import type {
14
13
  } from "./model-stream.ts";
15
14
  import { groupWire } from "./scout-groups.ts";
16
15
  import { reconstructScoutConversation } from "./scout-reconstruct.ts";
16
+ import { parseScoutSelection } from "./scout-selection.ts";
17
+ import type { ScoutSelection } from "./scout-selection.ts";
17
18
  import {
18
19
  SCOUT_SELECTION_MAX_IDS,
19
20
  SCOUT_SYNTHESIS_MAX_BYTES,
@@ -23,6 +24,10 @@ import { currentSessionId } from "./session-context.ts";
23
24
  import { snapshotAdvisorUsage } from "./usage.ts";
24
25
  import type { AdvisorUsageSnapshot } from "./usage.ts";
25
26
 
27
+ export { parseScoutSelection } from "./scout-selection.ts";
28
+
29
+ export type { ScoutSelection } from "./scout-selection.ts";
30
+
26
31
  export const SCOUT_SYSTEM = [
27
32
  "You are Scout, a context curator serving a separate engineering Advisor.",
28
33
  "Select only conversation groups materially relevant to the current request, unresolved decisions, attempted work, diagnostics, and validation.",
@@ -56,11 +61,6 @@ interface ScoutMetrics {
56
61
  usage?: AdvisorUsageSnapshot;
57
62
  }
58
63
 
59
- export interface ScoutSelection {
60
- selectedIds: string[];
61
- synthesis: string;
62
- }
63
-
64
64
  export type ScoutOutcome =
65
65
  | {
66
66
  conversation: string;
@@ -106,7 +106,6 @@ const defaultDependencies: ScoutDependencies = {
106
106
  resolve: resolveConfiguredModel,
107
107
  };
108
108
 
109
- const byteLength = (value: string) => Buffer.byteLength(value, "utf-8");
110
109
  const AUTH_ERROR_PATTERN = /api key|auth|login|credential/iu;
111
110
 
112
111
  const manifestMessage = (manifest: ScoutManifest): Message => ({
@@ -126,92 +125,6 @@ const manifestMessage = (manifest: ScoutManifest): Message => ({
126
125
  timestamp: Date.now(),
127
126
  });
128
127
 
129
- const isStringArray = (value: unknown): value is string[] =>
130
- Array.isArray(value) && value.every(isString);
131
-
132
- export const parseScoutSelection = (
133
- text: string,
134
- manifest: ScoutManifest
135
- ): ScoutSelection => {
136
- if (!text.trim()) {
137
- throw new Error("Scout returned an empty response.");
138
- }
139
-
140
- let value: unknown;
141
-
142
- try {
143
- value = JSON.parse(text);
144
- } catch (error) {
145
- throw new Error("Scout response is not a JSON object.", { cause: error });
146
- }
147
-
148
- if (!isRecord(value)) {
149
- throw new Error("Scout response must be a JSON object.");
150
- }
151
-
152
- const keys = Object.keys(value).toSorted();
153
-
154
- if (
155
- keys.length !== 2 ||
156
- keys[0] !== "selectedIds" ||
157
- keys[1] !== "synthesis"
158
- ) {
159
- throw new Error(
160
- "Scout response must contain only selectedIds and synthesis."
161
- );
162
- }
163
-
164
- if (!isStringArray(value.selectedIds)) {
165
- throw new Error("Scout selectedIds must be an array of strings.");
166
- }
167
-
168
- const { selectedIds } = value;
169
-
170
- if (new Set(selectedIds).size !== selectedIds.length) {
171
- throw new Error("Scout selected duplicate group IDs.");
172
- }
173
-
174
- const known = new Set(manifest.groups.map((group) => group.id));
175
- const knownSelectedIds = selectedIds.filter((id) => known.has(id));
176
-
177
- const requiredIds = manifest.groups
178
- .filter((group) => group.required)
179
- .map((group) => group.id);
180
-
181
- if (requiredIds.length > SCOUT_SELECTION_MAX_IDS) {
182
- throw new Error(
183
- `Manifest contains more than ${SCOUT_SELECTION_MAX_IDS} required groups.`
184
- );
185
- }
186
-
187
- const required = new Set(requiredIds);
188
-
189
- const optionalIds = knownSelectedIds
190
- .filter((id) => !required.has(id))
191
- .slice(0, SCOUT_SELECTION_MAX_IDS - requiredIds.length);
192
-
193
- const retained = new Set([...requiredIds, ...optionalIds]);
194
-
195
- const normalizedIds = manifest.groups
196
- .filter((group) => retained.has(group.id))
197
- .map((group) => group.id);
198
-
199
- if (!isString(value.synthesis)) {
200
- throw new TypeError("Scout synthesis must be a string.");
201
- }
202
-
203
- if (byteLength(value.synthesis) > SCOUT_SYNTHESIS_MAX_BYTES) {
204
- throw new Error(
205
- `Scout synthesis exceeds ${SCOUT_SYNTHESIS_MAX_BYTES} UTF-8 bytes.`
206
- );
207
- }
208
-
209
- return {
210
- selectedIds: normalizedIds,
211
- synthesis: knownSelectedIds.length > 0 ? value.synthesis : "",
212
- };
213
- };
214
-
215
128
  const baseMetrics = (
216
129
  manifest: ScoutManifest,
217
130
  startedAt: number
@@ -1,12 +1,12 @@
1
- import { isRecordOf, isString } from "./content-utils.ts";
2
- import type { JsonValue } from "./content-utils.ts";
3
1
  import { AdvisorFollowUpCache } from "./follow-up.ts";
4
2
  import type {
5
3
  AdvisorFollowUpLookup,
6
4
  AdvisorFollowUpPayload,
7
5
  } from "./follow-up.ts";
6
+ import { t } from "./i18n.ts";
8
7
  import { AdvisorJevLedgerState } from "./jev/ledger.ts";
9
8
  import type { AdvisorJevUsage } from "./jev/ledger.ts";
9
+ import { normalizedToolSignature } from "./tool-input-normalization.ts";
10
10
  import {
11
11
  addAdvisorUsage,
12
12
  emptyAdvisorUsageTotals,
@@ -15,6 +15,13 @@ import {
15
15
  } from "./usage.ts";
16
16
  import type { AdvisorUsageTotals } from "./usage.ts";
17
17
 
18
+ export {
19
+ normalizeToolInput,
20
+ normalizedToolSignature,
21
+ } from "./tool-input-normalization.ts";
22
+
23
+ export type { NormalizedToolInput } from "./tool-input-normalization.ts";
24
+
18
25
  export type GateDecision = "proceed" | "revise" | "blocked";
19
26
 
20
27
  export type ConsultationTrigger = "manual" | "executor-requested" | "turn-gate";
@@ -38,123 +45,6 @@ export interface AdvisorInvocationRecord {
38
45
  usage?: unknown;
39
46
  }
40
47
 
41
- const WHITESPACE = /\s/u;
42
-
43
- const TIMESTAMP_KEYS = new Set([
44
- "createdat",
45
- "date",
46
- "datetime",
47
- "time",
48
- "timestamp",
49
- "updatedat",
50
- ]);
51
-
52
- const REQUEST_ID_KEYS = new Set(["correlationid", "requestid", "traceid"]);
53
-
54
- const normalizedKey = (key: string) =>
55
- key.replaceAll(/[-_]/gu, "").toLowerCase();
56
-
57
- const isVolatileKey = (key: string, keys: Set<string>) =>
58
- keys.has(normalizedKey(key));
59
-
60
- const normalizeShellWhitespace = (command: string) => {
61
- let result = "";
62
- let quote: "'" | '"' | "`" | undefined;
63
- let pendingSpace = false;
64
-
65
- for (const char of command.trim()) {
66
- if (quote) {
67
- result += char;
68
-
69
- if (char === quote) {
70
- quote = undefined;
71
- }
72
-
73
- continue;
74
- }
75
-
76
- if (char === "'" || char === '"' || char === "`") {
77
- if (pendingSpace && result) {
78
- result += " ";
79
- }
80
-
81
- pendingSpace = false;
82
- quote = char;
83
- result += char;
84
- } else if (WHITESPACE.test(char)) {
85
- pendingSpace = true;
86
- } else {
87
- if (pendingSpace && result) {
88
- result += " ";
89
- }
90
-
91
- pendingSpace = false;
92
- result += char;
93
- }
94
- }
95
-
96
- return result;
97
- };
98
-
99
- const normalizeString = (value: string) =>
100
- value
101
- .replaceAll(/\/(?:private\/)?tmp\/[^\s/]+/gu, "/tmp/<temporary>")
102
- .replaceAll(/\/var\/folders\/[^\s/]+/gu, "/var/folders/<temporary>");
103
-
104
- export type NormalizedToolInput =
105
- | JsonValue
106
- | undefined
107
- | NormalizedToolInput[]
108
- | { [key: string]: NormalizedToolInput };
109
-
110
- export const normalizeToolInput = <Input>(
111
- toolName: string,
112
- input: Input
113
- ): NormalizedToolInput => {
114
- const visit = (
115
- value: NormalizedToolInput,
116
- key?: string
117
- ): NormalizedToolInput => {
118
- if (isString(value)) {
119
- if (key && isVolatileKey(key, TIMESTAMP_KEYS)) {
120
- return "<timestamp>";
121
- }
122
-
123
- if (key && isVolatileKey(key, REQUEST_ID_KEYS)) {
124
- return "<request-id>";
125
- }
126
-
127
- const normalized = normalizeString(value);
128
-
129
- return toolName === "bash" && key === "command"
130
- ? normalizeShellWhitespace(normalized)
131
- : normalized;
132
- }
133
-
134
- if (Array.isArray(value)) {
135
- return value.map((item) => visit(item));
136
- }
137
-
138
- if (isRecordOf(value)) {
139
- return Object.fromEntries(
140
- Object.keys(value)
141
- .toSorted()
142
- .map((childKey) => [childKey, visit(value[childKey], childKey)])
143
- );
144
- }
145
-
146
- return value;
147
- };
148
-
149
- // SAFETY: Pi tool inputs are JSON-decoded tool arguments, so the root value is already NormalizedToolInput-shaped.
150
- return visit(input as Input & NormalizedToolInput);
151
- };
152
-
153
- export const normalizedToolSignature = <Input>(
154
- toolName: string,
155
- input: Input
156
- ) => `${toolName}:${JSON.stringify(normalizeToolInput(toolName, input))}`;
157
-
158
48
  interface RepetitionState {
159
49
  count: number;
160
50
  interventions: number;
@@ -487,7 +377,7 @@ export class AdvisorSessionState {
487
377
  }
488
378
  }
489
379
 
490
- return parts.join(", ") || "none";
380
+ return parts.join(", ") || t("sessionSummary.none", "none");
491
381
  }
492
382
 
493
383
  #countTrigger(trigger: AdvisorTrigger) {
@@ -508,7 +398,7 @@ export class AdvisorSessionState {
508
398
  ] as const
509
399
  )
510
400
  .filter((trigger) => this.#countTrigger(trigger) > 0)
511
- .join(", ") || "none"
401
+ .join(", ") || t("sessionSummary.none", "none")
512
402
  );
513
403
  }
514
404
 
@@ -570,27 +460,27 @@ export class AdvisorSessionState {
570
460
  const models =
571
461
  [...new Set(invocations.map((item) => item.model).filter(Boolean))].join(
572
462
  ", "
573
- ) || "unknown";
463
+ ) || t("sessionSummary.models.unknown", "unknown");
574
464
 
575
465
  const budget =
576
466
  limit === undefined
577
- ? `${this.#consumedCalls} used; unlimited remaining`
578
- : `${this.#consumedCalls} / ${limit} used; ${Math.max(0, limit - this.#consumedCalls)} remaining`;
467
+ ? `${this.#consumedCalls} ${t("sessionSummary.budget.used", "used")}; ${t("sessionSummary.budget.unlimitedRemaining", "unlimited remaining")}`
468
+ : `${this.#consumedCalls} / ${limit} ${t("sessionSummary.budget.used", "used")}; ${Math.max(0, limit - this.#consumedCalls)} ${t("sessionSummary.budget.remaining", "remaining")}`;
579
469
 
580
470
  return [
581
- "[Session Advisor Summary]",
582
- `Consultations: ${markdown.length} Markdown (${this.#countTrigger("manual")} manual, ${this.#countTrigger("executor-requested")} executor-requested), automatic gates: ${gates.length}`,
583
- `Triggers: ${this.#triggersLine()}`,
584
- `Models: ${models}`,
585
- `Budget: ${budget}`,
586
- `Usage: ${formatAdvisorUsageTotals(totals)}`,
587
- `Markdown advice: ${markdown.length} responses (${this.#ledger.draftConsultations} with drafts)`,
588
- `Follow-ups: ${markdown.filter((item) => item.followUp).length}`,
589
- `Outcome reports: ${this.#ledger.outcomes}`,
590
- `Gate decisions: ${this.#decisionsLine()}`,
591
- `Loop matching: normalized tool signatures; ${this.#repetition.interventions} gate intervention${this.#repetition.interventions === 1 ? "" : "s"}`,
592
- `Execution effects: ${effects("tool-blocked")} tool blocked, ${effects("session-blocked")} sessions blocked, ${effects("continued")} continued`,
593
- `Failures: ${failures.length ? failures.join(", ") : "none"}`,
471
+ t("sessionSummary.title", "[Session Advisor Summary]"),
472
+ `${t("sessionSummary.consultations.label", "Consultations:")} ${markdown.length} ${t("sessionSummary.consultations.markdown", "Markdown")} (${this.#countTrigger("manual")} ${t("sessionSummary.consultations.manual", "manual")}, ${this.#countTrigger("executor-requested")} ${t("sessionSummary.consultations.executorRequested", "executor-requested")}), ${t("sessionSummary.consultations.automaticGates", "automatic gates:")} ${gates.length}`,
473
+ `${t("sessionSummary.triggers.label", "Triggers:")} ${this.#triggersLine()}`,
474
+ `${t("sessionSummary.models.label", "Models:")} ${models}`,
475
+ `${t("sessionSummary.budget.label", "Budget:")} ${budget}`,
476
+ `${t("sessionSummary.usage.label", "Usage:")} ${formatAdvisorUsageTotals(totals)}`,
477
+ `${t("sessionSummary.markdownAdvice.label", "Markdown advice:")} ${markdown.length} ${t("sessionSummary.markdownAdvice.responses", "responses")} (${this.#ledger.draftConsultations} ${t("sessionSummary.markdownAdvice.withDrafts", "with drafts")})`,
478
+ `${t("sessionSummary.followUps.label", "Follow-ups:")} ${markdown.filter((item) => item.followUp).length}`,
479
+ `${t("sessionSummary.outcomeReports.label", "Outcome reports:")} ${this.#ledger.outcomes}`,
480
+ `${t("sessionSummary.gateDecisions.label", "Gate decisions:")} ${this.#decisionsLine()}`,
481
+ `${t("sessionSummary.loopMatching.label", "Loop matching: normalized tool signatures;")} ${this.#repetition.interventions} ${t("sessionSummary.loopMatching.gateIntervention", "gate intervention")}${this.#repetition.interventions === 1 ? "" : "s"}`,
482
+ `${t("sessionSummary.executionEffects.label", "Execution effects:")} ${effects("tool-blocked")} ${t("sessionSummary.executionEffects.toolBlocked", "tool blocked")}, ${effects("session-blocked")} ${t("sessionSummary.executionEffects.sessionsBlocked", "sessions blocked")}, ${effects("continued")} ${t("sessionSummary.executionEffects.continued", "continued")}`,
483
+ `${t("sessionSummary.failures.label", "Failures:")} ${failures.length ? failures.join(", ") : t("sessionSummary.none", "none")}`,
594
484
  ...jevLines,
595
485
  ].join("\n");
596
486
  }
@@ -0,0 +1,119 @@
1
+ import { isRecordOf, isString } from "./content-utils.ts";
2
+ import type { JsonValue } from "./content-utils.ts";
3
+
4
+ const WHITESPACE = /\s/u;
5
+
6
+ const TIMESTAMP_KEYS = new Set([
7
+ "createdat",
8
+ "date",
9
+ "datetime",
10
+ "time",
11
+ "timestamp",
12
+ "updatedat",
13
+ ]);
14
+
15
+ const REQUEST_ID_KEYS = new Set(["correlationid", "requestid", "traceid"]);
16
+
17
+ const normalizedKey = (key: string) =>
18
+ key.replaceAll(/[-_]/gu, "").toLowerCase();
19
+
20
+ const isVolatileKey = (key: string, keys: Set<string>) =>
21
+ keys.has(normalizedKey(key));
22
+
23
+ const normalizeShellWhitespace = (command: string) => {
24
+ let result = "";
25
+ let quote: "'" | '"' | "`" | undefined;
26
+ let pendingSpace = false;
27
+
28
+ for (const char of command.trim()) {
29
+ if (quote) {
30
+ result += char;
31
+
32
+ if (char === quote) {
33
+ quote = undefined;
34
+ }
35
+
36
+ continue;
37
+ }
38
+
39
+ if (char === "'" || char === '"' || char === "`") {
40
+ if (pendingSpace && result) {
41
+ result += " ";
42
+ }
43
+
44
+ pendingSpace = false;
45
+ quote = char;
46
+ result += char;
47
+ } else if (WHITESPACE.test(char)) {
48
+ pendingSpace = true;
49
+ } else {
50
+ if (pendingSpace && result) {
51
+ result += " ";
52
+ }
53
+
54
+ pendingSpace = false;
55
+ result += char;
56
+ }
57
+ }
58
+
59
+ return result;
60
+ };
61
+
62
+ const normalizeString = (value: string) =>
63
+ value
64
+ .replaceAll(/\/(?:private\/)?tmp\/[^\s/]+/gu, "/tmp/<temporary>")
65
+ .replaceAll(/\/var\/folders\/[^\s/]+/gu, "/var/folders/<temporary>");
66
+
67
+ export type NormalizedToolInput =
68
+ | JsonValue
69
+ | undefined
70
+ | NormalizedToolInput[]
71
+ | { [key: string]: NormalizedToolInput };
72
+
73
+ export const normalizeToolInput = <Input>(
74
+ toolName: string,
75
+ input: Input
76
+ ): NormalizedToolInput => {
77
+ const visit = (
78
+ value: NormalizedToolInput,
79
+ key?: string
80
+ ): NormalizedToolInput => {
81
+ if (isString(value)) {
82
+ if (key && isVolatileKey(key, TIMESTAMP_KEYS)) {
83
+ return "<timestamp>";
84
+ }
85
+
86
+ if (key && isVolatileKey(key, REQUEST_ID_KEYS)) {
87
+ return "<request-id>";
88
+ }
89
+
90
+ const normalized = normalizeString(value);
91
+
92
+ return toolName === "bash" && key === "command"
93
+ ? normalizeShellWhitespace(normalized)
94
+ : normalized;
95
+ }
96
+
97
+ if (Array.isArray(value)) {
98
+ return value.map((item) => visit(item));
99
+ }
100
+
101
+ if (isRecordOf(value)) {
102
+ return Object.fromEntries(
103
+ Object.keys(value)
104
+ .toSorted()
105
+ .map((childKey) => [childKey, visit(value[childKey], childKey)])
106
+ );
107
+ }
108
+
109
+ return value;
110
+ };
111
+
112
+ // SAFETY: Pi tool inputs are JSON-decoded tool arguments, so the root value is already NormalizedToolInput-shaped.
113
+ return visit(input as Input & NormalizedToolInput);
114
+ };
115
+
116
+ export const normalizedToolSignature = <Input>(
117
+ toolName: string,
118
+ input: Input
119
+ ) => `${toolName}:${JSON.stringify(normalizeToolInput(toolName, input))}`;
@@ -13,6 +13,7 @@ import {
13
13
  import type { GateFailureMode } from "../config/types.ts";
14
14
  import type { HerdrAdvisorBlock } from "../herdr-block.ts";
15
15
  import { herdrAdvisorBlock, notifyHerdrAdvisorFailure } from "../herdr.ts";
16
+ import { t } from "../i18n.ts";
16
17
  import type { AdvisorSessionState } from "../session-state.ts";
17
18
  import type { AdvisorGateResult, GateFailureCategory } from "./types.ts";
18
19
 
@@ -34,10 +35,14 @@ export const notifyLocalFailure = (
34
35
  sessionBlocked = false
35
36
  ) => {
36
37
  if (ctx.hasUI) {
37
- ctx.ui.notify(
38
- `Advisor ${sessionBlocked ? "gate failure; session blocked" : "consultation failed"}: ${message}`,
39
- "error"
40
- );
38
+ const prefix = sessionBlocked
39
+ ? t(
40
+ "notify.localFailure.blockedPrefix",
41
+ "Advisor gate failure; session blocked:"
42
+ )
43
+ : t("notify.localFailure.failedPrefix", "Advisor consultation failed:");
44
+
45
+ ctx.ui.notify(`${prefix} ${message}`, "error");
41
46
  }
42
47
  };
43
48
 
@@ -104,7 +109,10 @@ export const blockedDecisionEffect = (
104
109
  if (failureMode === "warn-and-continue") {
105
110
  if (ctx.hasUI) {
106
111
  ctx.ui.notify(
107
- "Advisor gate returned blocked; continuing by configuration.",
112
+ t(
113
+ "notify.gateBlockedContinued.message",
114
+ "Advisor gate returned blocked; continuing by configuration."
115
+ ),
108
116
  "warning"
109
117
  );
110
118
  }
@@ -11,6 +11,7 @@ import {
11
11
  isSimpleMode,
12
12
  } from "../config/state.ts";
13
13
  import { capUtf8Bytes } from "../content-utils.ts";
14
+ import { t } from "../i18n.ts";
14
15
  import { consumeJevClassifierKey } from "../jev/classifier-key-store.ts";
15
16
  import { classifyScreening } from "../jev/classifier.ts";
16
17
  import { JevFailure } from "../jev/failure.ts";
@@ -65,7 +66,7 @@ const repeatSkipText = (advice: string) =>
65
66
 
66
67
  const outageNotifier = createOutageNotifier(
67
68
  (category, message) =>
68
- `Advisor Jev classifier failed (${category}); allowing consultations. ${message}`
69
+ `${t("notify.jevFilterOutage.prefix", "Advisor Jev classifier failed")} (${category}); ${t("notify.jevFilterOutage.allowing", "allowing consultations.")} ${message}`
69
70
  );
70
71
 
71
72
  const notifyOutageOnce = outageNotifier.notify;
@@ -13,6 +13,7 @@ import {
13
13
  } from "../config/state.ts";
14
14
  import { herdrAdvisorActivity } from "../herdr.ts";
15
15
  import type { HerdrAdvisorActivityScope } from "../herdr.ts";
16
+ import { t } from "../i18n.ts";
16
17
  import { consumeJevClassifierKey } from "../jev/classifier-key-store.ts";
17
18
  import { classifyTurnGate } from "../jev/classifier.ts";
18
19
  import { JevFailure } from "../jev/failure.ts";
@@ -60,7 +61,7 @@ export interface JevTurnGateRegistration {
60
61
 
61
62
  const outageNotifier = createOutageNotifier(
62
63
  (category, message) =>
63
- `Advisor Jev classifier turn gate failed (${category}); continuing without a proactive consultation. ${message}`
64
+ `${t("notify.jevTurnGateOutage.prefix", "Advisor Jev classifier turn gate failed")} (${category}); ${t("notify.jevTurnGateOutage.continuing", "continuing without a proactive consultation.")} ${message}`
64
65
  );
65
66
 
66
67
  const notifyFailureOnce = outageNotifier.notify;
@@ -6,6 +6,7 @@ import {
6
6
  isSimpleMode,
7
7
  } from "../config/state.ts";
8
8
  import { loadConfig } from "../config/storage.ts";
9
+ import { t } from "../i18n.ts";
9
10
  import { advisorBudgetMessage } from "./budget-feedback.ts";
10
11
  import { reserveAdvisorCall } from "./gate-policy.ts";
11
12
  import { handleAutomaticGate } from "./loop-gate.ts";
@@ -62,7 +63,10 @@ export const registerToolLifecycle = ({
62
63
 
63
64
  if (ctx.hasUI) {
64
65
  ctx.ui.notify(
65
- `Advisor gating skipped; configuration is invalid. ${message} Fix advisor.json.`,
66
+ `${t(
67
+ "notify.gatingSkipped.prefix",
68
+ "Advisor gating skipped; configuration is invalid."
69
+ )} ${message} ${t("notify.gatingSkipped.suffix", "Fix advisor.json.")}`,
66
70
  "error"
67
71
  );
68
72
  }
@@ -4,6 +4,7 @@ import { Type } from "typebox";
4
4
  import { advisorOutcomeLoggingRef } from "../config/state.ts";
5
5
  import { loadConfig } from "../config/storage.ts";
6
6
  import { textFrom } from "../conversation.ts";
7
+ import { t } from "../i18n.ts";
7
8
  import { ADOPTIONS, VALIDATIONS } from "../outcomes.ts";
8
9
  import type { ToolRegistrationContext } from "./types.ts";
9
10
 
@@ -55,7 +56,10 @@ export const registerOutcomeTool = ({
55
56
 
56
57
  if (ctx.hasUI) {
57
58
  ctx.ui.notify(
58
- "Advisor outcome could not be recorded locally.",
59
+ t(
60
+ "notify.outcomeRecordFailed.message",
61
+ "Advisor outcome could not be recorded locally."
62
+ ),
59
63
  "warning"
60
64
  );
61
65
  }