pi-advisor-flow 0.13.1-dev.1 → 0.13.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 (105) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/index.js +14 -7
  3. package/extensions/index.ts +6 -0
  4. package/package.json +9 -9
  5. package/scripts/check-bun-version.mjs +9 -0
  6. package/src/attachments.ts +36 -0
  7. package/src/child-session.ts +1 -0
  8. package/src/commands/activation-preparation.ts +12 -0
  9. package/src/commands/activation.ts +43 -0
  10. package/src/commands/advisor-tools.ts +3 -0
  11. package/src/commands/lifecycle.ts +15 -0
  12. package/src/commands/manual-command.ts +19 -0
  13. package/src/commands/manual-consultation.ts +20 -0
  14. package/src/commands/manual-progress.ts +13 -0
  15. package/src/commands/model-commands.ts +4 -0
  16. package/src/commands/model-options.ts +18 -0
  17. package/src/commands/model-picker.ts +16 -0
  18. package/src/commands/outcome-stats.ts +9 -0
  19. package/src/commands/registration.ts +1 -0
  20. package/src/commands/renderers.ts +14 -0
  21. package/src/commands/runtime.ts +5 -0
  22. package/src/commands/settings-commands.ts +18 -0
  23. package/src/commands/settings-persistence.ts +2 -0
  24. package/src/commands.ts +1 -0
  25. package/src/config/args.ts +7 -0
  26. package/src/config/defaults.ts +1 -0
  27. package/src/config/schema.ts +1 -0
  28. package/src/config/state.ts +64 -1
  29. package/src/config/storage.ts +37 -0
  30. package/src/config/types.ts +9 -0
  31. package/src/config/validation.ts +7 -0
  32. package/src/config.ts +6 -0
  33. package/src/content-utils.ts +5 -0
  34. package/src/conversation.ts +39 -0
  35. package/src/follow-up.ts +8 -0
  36. package/src/git.ts +8 -0
  37. package/src/herdr-block.ts +7 -0
  38. package/src/herdr-shared.ts +23 -0
  39. package/src/herdr.ts +18 -0
  40. package/src/image-attachments.ts +24 -0
  41. package/src/image-validation.ts +58 -0
  42. package/src/images.ts +24 -0
  43. package/src/jev/base-url.ts +14 -0
  44. package/src/jev/client.ts +49 -0
  45. package/src/jev/decisions-client.ts +14 -0
  46. package/src/jev/decisions-response.ts +38 -0
  47. package/src/jev/endpoint-key-store.ts +18 -0
  48. package/src/jev/key-store.ts +28 -0
  49. package/src/jev/ledger.ts +30 -12
  50. package/src/jev/openai-key-store.ts +17 -0
  51. package/src/jev/questions.ts +15 -0
  52. package/src/jev/state.ts +5 -0
  53. package/src/jev/transport.ts +35 -0
  54. package/src/model-stream.ts +32 -0
  55. package/src/outcome-stats.ts +16 -0
  56. package/src/outcomes.ts +31 -0
  57. package/src/pi-settings.ts +9 -0
  58. package/src/preferences.ts +26 -0
  59. package/src/redaction.ts +8 -0
  60. package/src/scout-context.ts +17 -0
  61. package/src/scout-curation.ts +12 -0
  62. package/src/scout-groups.ts +47 -0
  63. package/src/scout-protocol.ts +17 -0
  64. package/src/scout-reconstruct.ts +12 -0
  65. package/src/scout.ts +47 -0
  66. package/src/session-context.ts +11 -0
  67. package/src/session-state.ts +73 -13
  68. package/src/tool-result-cap.ts +11 -0
  69. package/src/tools/consult-context.ts +24 -0
  70. package/src/tools/consultation.ts +43 -0
  71. package/src/tools/gate-policy.ts +18 -0
  72. package/src/tools/gate-protocol.ts +22 -0
  73. package/src/tools/jev-filter.ts +26 -0
  74. package/src/tools/jev-turn-gate.ts +17 -0
  75. package/src/tools/loop-gate.ts +25 -0
  76. package/src/tools/model-access.ts +12 -0
  77. package/src/tools/outage-notifier.ts +4 -0
  78. package/src/tools/prompts.ts +17 -0
  79. package/src/tools/register-ask-advisor.ts +44 -0
  80. package/src/tools/register-lifecycle.ts +32 -0
  81. package/src/tools/register-outcome.ts +7 -0
  82. package/src/tools/register-renderers.ts +14 -0
  83. package/src/tools/registration.ts +3 -0
  84. package/src/tools/render-advisor-result.ts +44 -0
  85. package/src/tools/render-common.ts +10 -0
  86. package/src/tools/scout-status.ts +34 -0
  87. package/src/tools/session.ts +3 -0
  88. package/src/tools.ts +8 -0
  89. package/src/ui/jev-filter-submenu.ts +21 -0
  90. package/src/ui/jev-provider-submenu-view.ts +22 -0
  91. package/src/ui/jev-provider-submenu.ts +81 -0
  92. package/src/ui/jev-setup-support.ts +26 -0
  93. package/src/ui/manual-dialog-render.ts +20 -0
  94. package/src/ui/manual-dialog.ts +38 -0
  95. package/src/ui/masked-input.ts +2 -0
  96. package/src/ui/searchable-model-list.ts +28 -0
  97. package/src/ui/settings-formatting.ts +26 -0
  98. package/src/ui/settings-items.ts +11 -0
  99. package/src/ui/settings-list-adapter.ts +13 -0
  100. package/src/ui/settings-mutations.ts +60 -0
  101. package/src/ui/settings-selector.ts +30 -0
  102. package/src/ui/text-setting-submenu.ts +9 -0
  103. package/src/ui-guard.ts +1 -0
  104. package/src/ui.ts +3 -0
  105. package/src/usage.ts +31 -0
@@ -25,6 +25,7 @@ export const configPaths = (ctx: ExtensionContext) => [
25
25
  ];
26
26
 
27
27
  type SavedConfigKey = PersistedConfigKey;
28
+
28
29
  type ConfigState = {
29
30
  [Key in SavedConfigKey]: AdvisorConfig[Key];
30
31
  };
@@ -46,6 +47,7 @@ const RESERVED_ADVISOR_JSON_KEYS = new Set(["typesafe_api_key"]);
46
47
  export const readExistingConfig = (path: string): RecordValue => {
47
48
  try {
48
49
  const parsed: unknown = JSON.parse(readFileSync(path, "utf-8"));
50
+
49
51
  return isRecord(parsed) ? parsed : {};
50
52
  } catch {
51
53
  return {};
@@ -56,7 +58,9 @@ const readConfigForSave = (path: string): RecordValue => {
56
58
  if (!existsSync(path)) {
57
59
  return {};
58
60
  }
61
+
59
62
  let parsed: unknown;
63
+
60
64
  try {
61
65
  parsed = JSON.parse(readFileSync(path, "utf-8"));
62
66
  } catch (error) {
@@ -65,11 +69,13 @@ const readConfigForSave = (path: string): RecordValue => {
65
69
  { cause: error }
66
70
  );
67
71
  }
72
+
68
73
  if (!isRecord(parsed)) {
69
74
  throw new Error(
70
75
  `Cannot save Advisor configuration at ${path}: configuration must be a JSON object.`
71
76
  );
72
77
  }
78
+
73
79
  return parsed;
74
80
  };
75
81
 
@@ -90,27 +96,34 @@ const applyChangedConfigValues = (
90
96
  ): RecordValue => {
91
97
  const dropped = new Set<string>();
92
98
  const data: RecordValue = { ...existing };
99
+
93
100
  for (const key of changedKeys) {
94
101
  if (!shouldPersistConfigKey(key, persistAdvisor, persistExecutor)) {
95
102
  continue;
96
103
  }
104
+
97
105
  const value = current[key];
98
106
  const isEmptyModelRef = (key === "advisor" || key === "executor") && !value;
107
+
99
108
  if (value === undefined || isEmptyModelRef) {
100
109
  dropped.add(key);
101
110
  } else {
102
111
  data[key] = value;
103
112
  }
104
113
  }
114
+
105
115
  if (dropped.size === 0) {
106
116
  return data;
107
117
  }
118
+
108
119
  const retained: RecordValue = {};
120
+
109
121
  for (const key of Object.keys(data)) {
110
122
  if (!dropped.has(key)) {
111
123
  retained[key] = data[key];
112
124
  }
113
125
  }
126
+
114
127
  return retained;
115
128
  };
116
129
 
@@ -121,6 +134,7 @@ let loadedConfigPath: string | undefined;
121
134
  const readConfig = (path: string): AdvisorConfig => {
122
135
  const config = JSON.parse(readFileSync(path, "utf-8"));
123
136
  validateConfig(config, path);
137
+
124
138
  return config;
125
139
  };
126
140
 
@@ -130,6 +144,7 @@ const configCache = new Map<
130
144
  string,
131
145
  { config: AdvisorConfig; identity: string }
132
146
  >();
147
+
133
148
  const warnedUnknownConfigIdentities = new Set<string>();
134
149
 
135
150
  /** Drops the parsed-configuration cache; the next load re-reads from disk. */
@@ -146,6 +161,7 @@ export const resetConfigCache = () => {
146
161
  const configIdentity = (path: string): string => {
147
162
  try {
148
163
  const stats = statSync(path, { bigint: true });
164
+
149
165
  return `${stats.mtimeNs}:${stats.ctimeNs}:${stats.size}:${stats.ino}:${stats.dev}`;
150
166
  } catch {
151
167
  return `unstattable:${process.hrtime.bigint()}`;
@@ -155,30 +171,39 @@ const configIdentity = (path: string): string => {
155
171
  const readConfigCached = (path: string): AdvisorConfig => {
156
172
  const identity = configIdentity(path);
157
173
  const cached = configCache.get(path);
174
+
158
175
  if (cached?.identity === identity) {
159
176
  return cached.config;
160
177
  }
178
+
161
179
  const config = readConfig(path);
162
180
  configCache.set(path, { config, identity });
181
+
163
182
  return config;
164
183
  };
165
184
 
166
185
  export const loadConfig = (_ctx: ExtensionContext) => {
167
186
  resetDefaults();
168
187
  const global = join(getAgentDir(), "advisor.json");
188
+
169
189
  const globalConfig = existsSync(global)
170
190
  ? readConfigCached(global)
171
191
  : undefined;
192
+
172
193
  setPersistedModelRefs(
173
194
  configuredModelRef(globalConfig?.advisor),
174
195
  configuredModelRef(globalConfig?.executor)
175
196
  );
197
+
176
198
  if (globalConfig) {
177
199
  applyConfig(globalConfig);
200
+
178
201
  const unknownKeys = unknownConfigKeys(globalConfig).filter(
179
202
  (key) => !RESERVED_ADVISOR_JSON_KEYS.has(key)
180
203
  );
204
+
181
205
  const warningIdentity = `${global}:${configIdentity(global)}`;
206
+
182
207
  if (
183
208
  unknownKeys.length > 0 &&
184
209
  _ctx.hasUI &&
@@ -191,12 +216,14 @@ export const loadConfig = (_ctx: ExtensionContext) => {
191
216
  warnedUnknownConfigIdentities.add(warningIdentity);
192
217
  }
193
218
  }
219
+
194
220
  // Repository-controlled project configuration is never applied. Models,
195
221
  // prompts, gates, budgets, disclosure, redaction, integrations, and consent
196
222
  // remain under the user's global Pi configuration.
197
223
  setAdvisorOutcomeLoggingRef(globalConfig?.advisorOutcomeLogging === true);
198
224
  loadedConfigState = currentConfigState();
199
225
  loadedConfigPath = global;
226
+
200
227
  return existsSync(global) ? global : null;
201
228
  };
202
229
 
@@ -220,15 +247,19 @@ export const saveConfig = (
220
247
  const persistExecutor = options.persistExecutor ?? true;
221
248
  const current = currentConfigState();
222
249
  const baseline = loadedConfigPath === path ? loadedConfigState : undefined;
250
+
223
251
  const changedKeys = baseline
224
252
  ? SAVED_CONFIG_KEYS.filter(
225
253
  (key) => !sameConfigValue(current[key], baseline[key])
226
254
  )
227
255
  : [...SAVED_CONFIG_KEYS];
256
+
228
257
  if (changedKeys.length === 0) {
229
258
  return path;
230
259
  }
260
+
231
261
  const existing = readConfigForSave(path);
262
+
232
263
  const data = applyChangedConfigValues(
233
264
  existing,
234
265
  current,
@@ -236,9 +267,11 @@ export const saveConfig = (
236
267
  persistAdvisor,
237
268
  persistExecutor
238
269
  );
270
+
239
271
  writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`);
240
272
  resetConfigCache();
241
273
  const nextLoadedState = { ...current };
274
+
242
275
  if (!persistAdvisor) {
243
276
  nextLoadedState.advisor = baseline
244
277
  ? baseline.advisor
@@ -246,6 +279,7 @@ export const saveConfig = (
246
279
  isString(existing.advisor) ? existing.advisor : undefined
247
280
  );
248
281
  }
282
+
249
283
  if (!persistExecutor) {
250
284
  nextLoadedState.executor = baseline
251
285
  ? baseline.executor
@@ -253,8 +287,10 @@ export const saveConfig = (
253
287
  isString(existing.executor) ? existing.executor : undefined
254
288
  );
255
289
  }
290
+
256
291
  loadedConfigState = nextLoadedState;
257
292
  loadedConfigPath = path;
293
+
258
294
  return path;
259
295
  };
260
296
 
@@ -267,5 +303,6 @@ export const saveGlobalOutcomeLogging = (enabled: boolean) => {
267
303
  `${JSON.stringify({ ...existing, advisorOutcomeLogging: enabled }, null, 2)}\n`
268
304
  );
269
305
  resetConfigCache();
306
+
270
307
  return path;
271
308
  };
@@ -14,12 +14,15 @@ export const DEFAULT_CONTEXT_MAX_CHARS = 15_000;
14
14
  export const MAX_CONTEXT_MAX_CHARS = Number.MAX_SAFE_INTEGER;
15
15
  const DEFAULT_ADVISOR_TOOL_RESULT_MAX_LINES = PI_DEFAULT_MAX_LINES;
16
16
  const DEFAULT_ADVISOR_TOOL_RESULT_MAX_BYTES = PI_DEFAULT_MAX_BYTES;
17
+
17
18
  export {
18
19
  DEFAULT_ADVISOR_TOOL_RESULT_MAX_BYTES,
19
20
  DEFAULT_ADVISOR_TOOL_RESULT_MAX_LINES,
20
21
  };
22
+
21
23
  export const DEFAULT_ADVISOR_GIT_CONTEXT_MAX_CHARS = 20_000;
22
24
  export const DEFAULT_JEV_MODEL = "jev-latest";
25
+
23
26
  // Provisional: the latency benchmark was dropped from scope; revisit if live
24
27
  // measurements suggest a different bound.
25
28
  export const DEFAULT_JEV_TIMEOUT_MS = 8000;
@@ -32,13 +35,16 @@ export const DEFAULT_JEV_FILTER_NOUL_MARGIN = 0.35;
32
35
  export const DEFAULT_JEV_FILTER_OVERRIDE_WINDOW = 10;
33
36
  export const DEFAULT_JEV_TURN_GATE_EVERY_TURNS = 0;
34
37
  export const DEFAULT_JEV_TURN_GATE_NOUL_THRESHOLD = 0.8;
38
+
35
39
  export type JevTransport =
36
40
  | "auto"
37
41
  | "typesafe"
38
42
  | "openrouter"
39
43
  | "openai-decisions"
40
44
  | "typesafe-compatible";
45
+
41
46
  export const DEFAULT_JEV_TRANSPORT: JevTransport = "auto";
47
+
42
48
  export const JEV_TRANSPORTS: JevTransport[] = [
43
49
  "auto",
44
50
  "typesafe",
@@ -48,7 +54,9 @@ export const JEV_TRANSPORTS: JevTransport[] = [
48
54
  ];
49
55
 
50
56
  export type AdvisorToolPolicy = "full" | "summary" | "exclude";
57
+
51
58
  export type AdvisorToolPolicies = Record<string, AdvisorToolPolicy>;
59
+
52
60
  export const ADVISOR_TOOL_POLICIES: AdvisorToolPolicy[] = [
53
61
  "full",
54
62
  "summary",
@@ -59,6 +67,7 @@ export type GateFailureMode =
59
67
  | "block-session"
60
68
  | "block-tool"
61
69
  | "warn-and-continue";
70
+
62
71
  export const GATE_FAILURE_MODES: GateFailureMode[] = [
63
72
  "block-session",
64
73
  "block-tool",
@@ -43,17 +43,22 @@ const validateValues = (
43
43
  ) => {
44
44
  for (const key of keysOfType(type)) {
45
45
  const value = config[key];
46
+
46
47
  if (value === undefined) {
47
48
  continue;
48
49
  }
50
+
49
51
  const schema = SCHEMA_BY_KEY[key];
52
+
50
53
  if (type === "string" || type === "boolean") {
51
54
  const matchesType =
52
55
  type === "string" ? isString(value) : isBoolean(value);
56
+
53
57
  if (!matchesType) {
54
58
  invalidConfigValue(path, key, schema.accepted);
55
59
  }
56
60
  }
61
+
57
62
  if (schema.validate && !schema.validate(value)) {
58
63
  invalidConfigValue(path, key, schema.accepted);
59
64
  }
@@ -69,11 +74,13 @@ export const validateConfig = (
69
74
  `Invalid advisor configuration at ${path}: expected a JSON object.`
70
75
  );
71
76
  }
77
+
72
78
  validateValues(value, path, "string");
73
79
  validateValues(value, path, "boolean");
74
80
  validateValues(value, path, "number");
75
81
  validateValues(value, path, "object");
76
82
  validateValues(value, path, "array");
77
83
  validateValues(value, path, "enum");
84
+
78
85
  return true;
79
86
  };
package/src/config.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // biome-ignore lint/performance/noBarrelFile: this facade intentionally preserves the public config module contract.
2
2
  export { parseArgs } from "./config/args.ts";
3
+
3
4
  export {
4
5
  advisorAgentsMdContextRef,
5
6
  advisorAutoLoopGateRef,
@@ -75,7 +76,9 @@ export {
75
76
  simpleModeRef,
76
77
  splitRef,
77
78
  } from "./config/state.ts";
79
+
78
80
  export type { SaveConfigOptions } from "./config/storage.ts";
81
+
79
82
  export {
80
83
  configPaths,
81
84
  loadConfig,
@@ -83,12 +86,14 @@ export {
83
86
  saveConfig,
84
87
  saveGlobalOutcomeLogging,
85
88
  } from "./config/storage.ts";
89
+
86
90
  export type {
87
91
  AdvisorConfig,
88
92
  AdvisorToolPolicies,
89
93
  AdvisorToolPolicy,
90
94
  GateFailureMode,
91
95
  } from "./config/types.ts";
96
+
92
97
  export {
93
98
  ADVISOR_TOOL_POLICIES,
94
99
  DEFAULT_ADVISOR_GIT_CONTEXT_MAX_CHARS,
@@ -98,6 +103,7 @@ export {
98
103
  GATE_FAILURE_MODES,
99
104
  MAX_CONTEXT_MAX_CHARS,
100
105
  } from "./config/types.ts";
106
+
101
107
  export {
102
108
  isValidAdvisorModelWhitelist,
103
109
  isValidAdvisorToolPolicies,
@@ -31,6 +31,7 @@ export const contentParts = <Content>(content: Content): unknown[] => {
31
31
  if (isString(content)) {
32
32
  return [content];
33
33
  }
34
+
34
35
  return Array.isArray(content) ? content : [];
35
36
  };
36
37
 
@@ -38,13 +39,17 @@ export const contentParts = <Content>(content: Content): unknown[] => {
38
39
  export const capUtf8Bytes = (value: string, maxBytes: number): string => {
39
40
  let result = "";
40
41
  let used = 0;
42
+
41
43
  for (const character of value) {
42
44
  const characterBytes = byteLength(character);
45
+
43
46
  if (used + characterBytes > maxBytes) {
44
47
  break;
45
48
  }
49
+
46
50
  result += character;
47
51
  used += characterBytes;
48
52
  }
53
+
49
54
  return result;
50
55
  };
@@ -18,9 +18,11 @@ const textFromPart = <Part>(part: Part): string => {
18
18
  if (isString(part)) {
19
19
  return part;
20
20
  }
21
+
21
22
  if (!isRecordOf(part) || part.type !== "text") {
22
23
  return "";
23
24
  }
25
+
24
26
  return isString(part.text) ? part.text : "";
25
27
  };
26
28
 
@@ -39,30 +41,37 @@ const assistantEntry = (
39
41
  ): string | undefined => {
40
42
  const parts: string[] = [];
41
43
  const text = textFrom(message.content);
44
+
42
45
  if (text) {
43
46
  parts.push(redact ? redactSecrets(text) : text);
44
47
  }
48
+
45
49
  for (const part of contentParts(message.content)) {
46
50
  if (!isRecordOf(part) || part.type !== "toolCall") {
47
51
  continue;
48
52
  }
53
+
49
54
  const toolName = isString(part.name) ? part.name : "unknown";
50
55
  const policy = policies[toolName] ?? "full";
56
+
51
57
  if (policy === "exclude") {
52
58
  parts.push(`[Tool Call: ${toolName}] (excluded by Advisor tool policy)`);
53
59
  continue;
54
60
  }
61
+
55
62
  if (policy === "summary") {
56
63
  parts.push(
57
64
  `[Tool Call: ${toolName}] (arguments omitted by Advisor tool policy: summary)`
58
65
  );
59
66
  continue;
60
67
  }
68
+
61
69
  const argumentsText = JSON.stringify(part.arguments) ?? "undefined";
62
70
  parts.push(
63
71
  `[Tool Call: ${toolName}(${redact ? redactSecrets(argumentsText) : argumentsText})]`
64
72
  );
65
73
  }
74
+
66
75
  return parts.length > 0 ? `Executor: ${parts.join("\n")}` : undefined;
67
76
  };
68
77
 
@@ -79,26 +88,33 @@ const toolResultEntry = (
79
88
  const toolName = isString(message.toolName) ? message.toolName : "unknown";
80
89
  const policy = policies[toolName] ?? "full";
81
90
  const notes = describeImages ? imageNotes(message.content, imageNonce) : [];
91
+
82
92
  const source = [textFrom(message.content), ...notes]
83
93
  .filter(Boolean)
84
94
  .join("\n");
95
+
85
96
  if (policy === "exclude") {
86
97
  return `[Tool Result for ${toolName}] (excluded by Advisor tool policy)`;
87
98
  }
99
+
88
100
  if (policy === "summary") {
89
101
  const capped = capToolResult(
90
102
  source,
91
103
  toolResultMaxLines,
92
104
  toolResultMaxBytes
93
105
  );
106
+
94
107
  return `[Tool Result for ${toolName}] (output omitted by Advisor tool policy: summary; status: ${status}; ${capped.totalLines} lines, ${capped.totalBytes} bytes; source output was${capped.truncated ? "" : " not"} truncated)`;
95
108
  }
109
+
96
110
  const disclosed = redact ? redactSecrets(source) : source;
111
+
97
112
  const capped = capToolResult(
98
113
  disclosed,
99
114
  toolResultMaxLines,
100
115
  toolResultMaxBytes
101
116
  );
117
+
102
118
  return `[Tool Result for ${toolName}] (${message.isError ? "Error " : ""}output):\n${capped.content}`;
103
119
  };
104
120
 
@@ -114,23 +130,31 @@ export const conversationEntry = <Entry>(
114
130
  if (!isRecordOf(entry)) {
115
131
  return;
116
132
  }
133
+
117
134
  if (entry.type === "compaction" && isString(entry.summary)) {
118
135
  return `[System Compaction Summary]: ${redact ? redactSecrets(entry.summary) : entry.summary}`;
119
136
  }
137
+
120
138
  if (entry.type !== "message" || !isRecordOf(entry.message)) {
121
139
  return;
122
140
  }
141
+
123
142
  const { message } = entry;
143
+
124
144
  if (message.role === "user") {
125
145
  const notes = describeImages ? imageNotes(message.content, imageNonce) : [];
146
+
126
147
  const text = [textFrom(message.content), ...notes]
127
148
  .filter(Boolean)
128
149
  .join("\n");
150
+
129
151
  return text ? `User: ${redact ? redactSecrets(text) : text}` : undefined;
130
152
  }
153
+
131
154
  if (message.role === "assistant") {
132
155
  return assistantEntry(message, policies, redact);
133
156
  }
157
+
134
158
  if (message.role === "toolResult" || message.role === "tool") {
135
159
  return toolResultEntry(
136
160
  message,
@@ -150,42 +174,55 @@ const omissionMarker = (omitted: number) =>
150
174
  const selectRecentEntries = (entries: string[], maxChars: number): string => {
151
175
  const separator = "\n\n";
152
176
  const joined = entries.join(separator);
177
+
153
178
  if (joined.length <= maxChars || maxChars === Number.MAX_SAFE_INTEGER) {
154
179
  return joined;
155
180
  }
181
+
156
182
  const newestTruncated = "[Newest entry truncated]";
183
+
157
184
  if (entries.length === 1) {
158
185
  const prefix = `${newestTruncated}${separator}`;
186
+
159
187
  return `${prefix}${entries[0].slice(0, Math.max(0, maxChars - prefix.length))}`.slice(
160
188
  0,
161
189
  maxChars
162
190
  );
163
191
  }
192
+
164
193
  const selected: string[] = [];
165
194
  let selectedLength = 0;
195
+
166
196
  for (let index = entries.length - 1; index >= 0; index -= 1) {
167
197
  const entry = entries[index];
168
198
  const candidateCount = selected.length + 1;
169
199
  const omitted = entries.length - candidateCount;
200
+
170
201
  const candidateLength =
171
202
  selectedLength +
172
203
  entry.length +
173
204
  (selected.length > 0 ? separator.length : 0);
205
+
174
206
  if (
175
207
  omissionMarker(omitted).length + separator.length + candidateLength >
176
208
  maxChars
177
209
  ) {
178
210
  break;
179
211
  }
212
+
180
213
  selected.unshift(entry);
181
214
  selectedLength = candidateLength;
182
215
  }
216
+
183
217
  const omitted = entries.length - Math.max(1, selected.length);
184
218
  const marker = omissionMarker(omitted);
219
+
185
220
  if (selected.length > 0) {
186
221
  return `${marker}${separator}${selected.join(separator)}`;
187
222
  }
223
+
188
224
  const prefix = `${marker}${separator}${newestTruncated}${separator}`;
225
+
189
226
  return `${prefix}${entries.at(-1)?.slice(0, Math.max(0, maxChars - prefix.length)) ?? ""}`.slice(
190
227
  0,
191
228
  maxChars
@@ -205,6 +242,7 @@ export const recentConversation = (
205
242
  if (maxChars === 0) {
206
243
  return "";
207
244
  }
245
+
208
246
  const entries = sessionContextEntries(ctx)
209
247
  .map((entry) =>
210
248
  conversationEntry(
@@ -218,5 +256,6 @@ export const recentConversation = (
218
256
  )
219
257
  )
220
258
  .filter((entry): entry is string => entry !== undefined);
259
+
221
260
  return selectRecentEntries(entries, maxChars);
222
261
  };
package/src/follow-up.ts CHANGED
@@ -39,6 +39,7 @@ export class AdvisorFollowUpCache {
39
39
 
40
40
  advanceToolCall() {
41
41
  const now = this.#now();
42
+
42
43
  for (const [adviceId, entry] of this.#entries) {
43
44
  if (
44
45
  now >= entry.expiresAt ||
@@ -47,6 +48,7 @@ export class AdvisorFollowUpCache {
47
48
  this.#entries.delete(adviceId);
48
49
  continue;
49
50
  }
51
+
50
52
  entry.toolCallsSince += 1;
51
53
  }
52
54
  }
@@ -59,6 +61,7 @@ export class AdvisorFollowUpCache {
59
61
  if (replacesAdviceId) {
60
62
  this.#entries.delete(replacesAdviceId);
61
63
  }
64
+
62
65
  this.#entries.set(adviceId, {
63
66
  ...copy(payload),
64
67
  expiresAt: this.#now() + FOLLOW_UP_TTL_MS,
@@ -68,18 +71,23 @@ export class AdvisorFollowUpCache {
68
71
 
69
72
  get(adviceId: string): AdvisorFollowUpLookup {
70
73
  const entry = this.#entries.get(adviceId);
74
+
71
75
  if (!entry) {
72
76
  return { reason: "the adviceId is unknown or no longer cached" };
73
77
  }
78
+
74
79
  if (this.#now() >= entry.expiresAt) {
75
80
  this.#entries.delete(adviceId);
81
+
76
82
  return { reason: "the cached payload has expired" };
77
83
  }
84
+
78
85
  if (entry.depth >= FOLLOW_UP_MAX_DEPTH) {
79
86
  return {
80
87
  reason: `the follow-up chain is limited to ${FOLLOW_UP_MAX_DEPTH} follow-ups`,
81
88
  };
82
89
  }
90
+
83
91
  return { payload: copy(entry) };
84
92
  }
85
93
  }
package/src/git.ts CHANGED
@@ -64,7 +64,9 @@ export const capRepositoryContext = (value: string, maxChars: number) => {
64
64
  if (value.length <= maxChars) {
65
65
  return { text: value, truncated: false };
66
66
  }
67
+
67
68
  const contentChars = Math.max(0, maxChars - TRUNCATION_NOTICE.length);
69
+
68
70
  return {
69
71
  text:
70
72
  maxChars < TRUNCATION_NOTICE.length
@@ -84,11 +86,14 @@ export type GitRunner = (args: string[], cwd: string) => string;
84
86
  /** Shares one deadline across commands so a pathological repository cannot block for the sum of per-command timeouts. */
85
87
  const deadlineRunner = (): GitRunner => {
86
88
  const expiresAt = Date.now() + GIT_TOTAL_TIMEOUT_MS;
89
+
87
90
  return (args, cwd) => {
88
91
  const remaining = expiresAt - Date.now();
92
+
89
93
  if (remaining <= 0) {
90
94
  throw new Error("Git context collection exceeded its time budget.");
91
95
  }
96
+
92
97
  return execFileSync("git", args, {
93
98
  cwd,
94
99
  encoding: "utf-8",
@@ -106,6 +111,7 @@ const deadlineRunner = (): GitRunner => {
106
111
  const diffBase = (run: GitRunner, cwd: string): string => {
107
112
  try {
108
113
  run(["rev-parse", "--verify", "--quiet", "HEAD"], cwd);
114
+
109
115
  return "HEAD";
110
116
  } catch {
111
117
  return EMPTY_TREE;
@@ -123,6 +129,7 @@ export const collectGitContext = (
123
129
  if (level === "off" || maxChars <= 0) {
124
130
  return { level: "off", status: "disabled", text: "" };
125
131
  }
132
+
126
133
  try {
127
134
  run(["rev-parse", "--is-inside-work-tree"], cwd);
128
135
  } catch (error) {
@@ -138,6 +145,7 @@ export const collectGitContext = (
138
145
  const base = diffBase(run, cwd);
139
146
  const nameStatus = run(["diff", "--name-status", base], cwd).trim();
140
147
  const shortstat = run(["diff", "--shortstat", base], cwd).trim();
148
+
141
149
  const untracked = run(
142
150
  ["ls-files", "--others", "--exclude-standard"],
143
151
  cwd
@@ -28,12 +28,15 @@ export class HerdrAdvisorBlock {
28
28
  if (!this.enabled()) {
29
29
  return;
30
30
  }
31
+
31
32
  const label = cleanNotification(reason, 200);
32
33
  const wasBlocked: boolean = this.#blocked;
34
+
33
35
  if (!wasBlocked) {
34
36
  // The listener refcounts, so only the false → true edge may emit.
35
37
  this.safeEmitBlocked(true, label);
36
38
  }
39
+
37
40
  this.#blocked = true;
38
41
  this.safeReport({ blocked: label });
39
42
  }
@@ -41,12 +44,15 @@ export class HerdrAdvisorBlock {
41
44
  clear() {
42
45
  const wasBlocked: boolean = this.#blocked;
43
46
  this.#blocked = false;
47
+
44
48
  if (!wasBlocked) {
45
49
  return;
46
50
  }
51
+
47
52
  // Clearing previously reported state is a de-escalation and must still be
48
53
  // delivered if integration was disabled after the block was reported.
49
54
  this.safeEmitBlocked(false, "Advisor blocked");
55
+
50
56
  try {
51
57
  this.report({
52
58
  id: `${BLOCK_SOURCE}:${nextSequence()}`,
@@ -68,6 +74,7 @@ export class HerdrAdvisorBlock {
68
74
  private safeEmitBlocked(active: boolean, label: string): boolean {
69
75
  try {
70
76
  this.emitBlocked(active, label);
77
+
71
78
  return true;
72
79
  } catch {
73
80
  return false;