pi-advisor-flow 0.13.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 +4 -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
@@ -37,6 +37,7 @@ import {
37
37
 
38
38
  /** Maximum bytes for project preferences and the redacted draft. */
39
39
  const ATTACHMENT_TEXT_MAX_BYTES = 8 * 1024;
40
+
40
41
  /** Combined budget for untracked plus tracked file attachments. */
41
42
  const ATTACHMENTS_TOTAL_MAX_BYTES = 24 * 1024;
42
43
 
@@ -86,16 +87,19 @@ export const assembleConsultationContext = async (
86
87
  // The user setting is the ceiling; the Executor may only narrow it.
87
88
  const allowed = advisorGitContextRef;
88
89
  const level = clampGitContextLevel(options.gitContext ?? allowed, allowed);
90
+
89
91
  const gitBudget = advisorGitContextBudget(
90
92
  contextMaxCharsRef,
91
93
  advisorGitContextMaxCharsRef
92
94
  );
95
+
93
96
  const changes = collectGitContext(
94
97
  ctx.cwd,
95
98
  level,
96
99
  gitBudget,
97
100
  advisorRedactSecretsRef ? redactSecrets : undefined
98
101
  );
102
+
99
103
  // The disclosure warning is control metadata, not repository payload. Keep it
100
104
  // outside the zero-byte Git budget so disabling disclosure cannot erase it.
101
105
  const changeText = advisorRepositoryContext(
@@ -104,19 +108,23 @@ export const assembleConsultationContext = async (
104
108
  level,
105
109
  gitBudget
106
110
  );
111
+
107
112
  // Repository context spends part of the shared budget, so a large patch
108
113
  // cannot silently push the conversation past the model's context window.
109
114
  const conversationBudget = Math.max(
110
115
  0,
111
116
  contextMaxCharsRef - changeText.length
112
117
  );
118
+
113
119
  const imageNonce = randomUUID();
120
+
114
121
  const legacyConversation = advisorRequestConversation(
115
122
  ctx,
116
123
  conversationBudget,
117
124
  true,
118
125
  imageNonce
119
126
  );
127
+
120
128
  const curated = await curateAdvisorConversation(
121
129
  ctx,
122
130
  legacyConversation,
@@ -128,11 +136,13 @@ export const assembleConsultationContext = async (
128
136
  conversationBudget,
129
137
  imageNonce
130
138
  );
139
+
131
140
  const preferences = await readProjectPreferences(
132
141
  ctx,
133
142
  ATTACHMENT_TEXT_MAX_BYTES,
134
143
  advisorRedactSecretsRef
135
144
  );
145
+
136
146
  const projectRules = advisorAgentsMdContextRef
137
147
  ? await readProjectRules(
138
148
  ctx,
@@ -140,6 +150,7 @@ export const assembleConsultationContext = async (
140
150
  advisorRedactSecretsRef
141
151
  )
142
152
  : undefined;
153
+
143
154
  const draftText = options.draft
144
155
  ? redactAndCapText(
145
156
  options.draft,
@@ -147,12 +158,14 @@ export const assembleConsultationContext = async (
147
158
  advisorRedactSecretsRef
148
159
  )
149
160
  : undefined;
161
+
150
162
  const untracked = await readUntrackedFiles(
151
163
  ctx.cwd,
152
164
  options.includeUntracked ?? [],
153
165
  advisorUntrackedContentRef,
154
166
  advisorRedactSecretsRef
155
167
  );
168
+
156
169
  const tracked = await readTrackedFiles(
157
170
  ctx.cwd,
158
171
  options.includeTracked ?? [],
@@ -164,7 +177,9 @@ export const assembleConsultationContext = async (
164
177
  untracked.reduce((sum, item) => sum + item.bytes, 0)
165
178
  )
166
179
  );
180
+
167
181
  const supportsImages = options.supportsImages ?? false;
182
+
168
183
  const untrackedImages = await readImageFiles(
169
184
  ctx.cwd,
170
185
  options.includeUntracked ?? [],
@@ -173,6 +188,7 @@ export const assembleConsultationContext = async (
173
188
  ADVISOR_IMAGES_TOTAL_MAX_BYTES,
174
189
  ADVISOR_IMAGES_MAX_COUNT
175
190
  );
191
+
176
192
  const trackedImages = await readImageFiles(
177
193
  ctx.cwd,
178
194
  options.includeTracked ?? [],
@@ -182,19 +198,23 @@ export const assembleConsultationContext = async (
182
198
  untrackedImages.images.reduce((sum, item) => sum + item.bytes, 0),
183
199
  ADVISOR_IMAGES_MAX_COUNT - untrackedImages.images.length
184
200
  );
201
+
185
202
  const images = [...untrackedImages.images, ...trackedImages.images].map(
186
203
  (item) => ({
187
204
  image: item.image,
188
205
  label: `File ${JSON.stringify(item.path)}`,
189
206
  })
190
207
  );
208
+
191
209
  let remainingBytes =
192
210
  ADVISOR_IMAGES_TOTAL_MAX_BYTES -
193
211
  [...untrackedImages.images, ...trackedImages.images].reduce(
194
212
  (sum, item) => sum + item.bytes,
195
213
  0
196
214
  );
215
+
197
216
  let imageOmissions = untrackedImages.omitted + trackedImages.omitted;
217
+
198
218
  const census = selectedConversationImages(
199
219
  ctx,
200
220
  curated.conversation,
@@ -204,8 +224,10 @@ export const assembleConsultationContext = async (
204
224
  : undefined,
205
225
  imageNonce
206
226
  );
227
+
207
228
  for (const item of census.selected) {
208
229
  const bytes = Buffer.from(item.image.data, "base64").length;
230
+
209
231
  if (
210
232
  !supportsImages ||
211
233
  images.length >= ADVISOR_IMAGES_MAX_COUNT ||
@@ -214,9 +236,11 @@ export const assembleConsultationContext = async (
214
236
  imageOmissions += 1;
215
237
  continue;
216
238
  }
239
+
217
240
  remainingBytes -= bytes;
218
241
  images.push({ image: item.image, label: item.marker });
219
242
  }
243
+
220
244
  return {
221
245
  changeText,
222
246
  conversation: curated.conversation,
@@ -109,14 +109,17 @@ const advisorImageNotice = (context: ConsultationContext) => {
109
109
  ) {
110
110
  return "";
111
111
  }
112
+
112
113
  const disclosure = context.supportsImages
113
114
  ? `${context.images.length} image(s) attached below; ${context.imageOmissions} image(s) withheld by format, consent, or size/count limits`
114
115
  : "Advisor model does not support image input; no pixels were forwarded";
116
+
115
117
  return `\n\nImage disclosure: ${disclosure}. Only the images explicitly attached below have pixels available. Other image markers, image paths, and text descriptions are not visual evidence.`;
116
118
  };
117
119
 
118
120
  const advisorPrivacyKey = (ctx: ExtensionContext) => {
119
121
  const settings = getAdvisorSettings();
122
+
120
123
  return JSON.stringify({
121
124
  agentsMdContext: settings.agentsMdContext,
122
125
  contextMaxChars: settings.contextMaxChars,
@@ -155,11 +158,14 @@ const prepareFollowUp = (
155
158
  "Follow-up consultations require a non-empty question. Issue a fresh consultation if no question is needed."
156
159
  );
157
160
  }
161
+
158
162
  assertAdvisorFollowUpPrivacy(followUp.payload, ctx);
163
+
159
164
  const outboundQuestion =
160
165
  advisorRedactSecretsRef || followUp.payload.redacted
161
166
  ? redactSecrets(question)
162
167
  : question;
168
+
163
169
  const messages = structuredClone(followUp.payload.messages);
164
170
  messages.push({
165
171
  content: [
@@ -171,6 +177,7 @@ const prepareFollowUp = (
171
177
  role: "user",
172
178
  timestamp: Date.now(),
173
179
  });
180
+
174
181
  return {
175
182
  messages,
176
183
  privacyKey: followUp.payload.privacyKey,
@@ -184,15 +191,19 @@ const prepareFreshRequest = async (
184
191
  resolved: Awaited<ReturnType<typeof resolveConfiguredModel>>
185
192
  ): Promise<PreparedAdvisorRequest> => {
186
193
  const { question } = options;
194
+
187
195
  const context = await assembleConsultationContext({
188
196
  ...options,
189
197
  supportsImages: resolved.model.input.includes("image"),
190
198
  });
199
+
191
200
  const outboundQuestion =
192
201
  advisorRedactSecretsRef && question !== undefined
193
202
  ? redactSecrets(question)
194
203
  : question;
204
+
195
205
  const imageNotice = advisorImageNotice(context);
206
+
196
207
  const messages: Message[] = [
197
208
  {
198
209
  content: [
@@ -221,6 +232,7 @@ const prepareFreshRequest = async (
221
232
  timestamp: Date.now(),
222
233
  },
223
234
  ];
235
+
224
236
  return {
225
237
  context,
226
238
  messages,
@@ -275,10 +287,13 @@ const runAdvisorAttempt = async (
275
287
  signal: options.signal,
276
288
  systemPrompt: prepared.systemPrompt,
277
289
  });
290
+
278
291
  const { text: markdown } = streamed;
292
+
279
293
  if (!markdown.trim()) {
280
294
  throw new AdvisorNoAdviceError();
281
295
  }
296
+
282
297
  return {
283
298
  ...advisorContextDetails(prepared.context),
284
299
  followUp: Boolean(options.followUp),
@@ -305,10 +320,13 @@ const runFallbackAdvisorAttempt = async (
305
320
  ): Promise<CollectedAdvisorResponse> => {
306
321
  const { ctx } = options;
307
322
  let request = prepared;
323
+
308
324
  if (!advisorFallbackModelRef) {
309
325
  throw primaryError;
310
326
  }
327
+
311
328
  const fallbackModel = advisorFallbackModelRef;
329
+
312
330
  if (fallbackModel === primaryModel) {
313
331
  throw combinedFallbackError(
314
332
  primaryModel,
@@ -317,6 +335,7 @@ const runFallbackAdvisorAttempt = async (
317
335
  new Error("fallback is the same model as the primary Advisor")
318
336
  );
319
337
  }
338
+
320
339
  if (sameModelAdvisorDisabled(ctx, ctx.model, fallbackModel)) {
321
340
  throw combinedFallbackError(
322
341
  primaryModel,
@@ -325,7 +344,9 @@ const runFallbackAdvisorAttempt = async (
325
344
  new Error(fallbackSameModelAdvisorNotice)
326
345
  );
327
346
  }
347
+
328
348
  const fallbackAccessReason = advisorModelAccessReason(ctx);
349
+
329
350
  if (fallbackAccessReason) {
330
351
  throw combinedFallbackError(
331
352
  primaryModel,
@@ -334,7 +355,9 @@ const runFallbackAdvisorAttempt = async (
334
355
  new Error(fallbackAccessReason)
335
356
  );
336
357
  }
358
+
337
359
  let resolvedFallback: Awaited<ReturnType<typeof resolveConfiguredModel>>;
360
+
338
361
  try {
339
362
  resolvedFallback = await resolveConfiguredModel(
340
363
  ctx,
@@ -349,6 +372,7 @@ const runFallbackAdvisorAttempt = async (
349
372
  error instanceof Error ? error : new Error(String(error))
350
373
  );
351
374
  }
375
+
352
376
  if (!request) {
353
377
  try {
354
378
  request = options.followUp
@@ -363,6 +387,7 @@ const runFallbackAdvisorAttempt = async (
363
387
  );
364
388
  }
365
389
  }
390
+
366
391
  try {
367
392
  return await runAdvisorAttempt(
368
393
  options,
@@ -374,6 +399,7 @@ const runFallbackAdvisorAttempt = async (
374
399
  if (options.signal?.aborted) {
375
400
  throw error;
376
401
  }
402
+
377
403
  throw combinedFallbackError(
378
404
  primaryModel,
379
405
  primaryError,
@@ -389,6 +415,7 @@ const collectAdvisorResponse = async (
389
415
  const { ctx, signal } = options;
390
416
  loadConfig(ctx);
391
417
  const primaryModel = options.followUp?.payload.model ?? advisorRef;
418
+
392
419
  if (sameModelAdvisorDisabled(ctx, ctx.model, primaryModel)) {
393
420
  throw new Error(
394
421
  primaryModel === advisorRef
@@ -396,16 +423,20 @@ const collectAdvisorResponse = async (
396
423
  : fallbackSameModelAdvisorNotice
397
424
  );
398
425
  }
426
+
399
427
  const accessReason = advisorModelAccessReason(ctx);
428
+
400
429
  if (accessReason) {
401
430
  throw new Error(accessReason);
402
431
  }
403
432
 
404
433
  let primaryError: Error | undefined;
405
434
  let prepared: PreparedAdvisorRequest | undefined;
435
+
406
436
  let resolvedPrimary:
407
437
  | Awaited<ReturnType<typeof resolveConfiguredModel>>
408
438
  | undefined;
439
+
409
440
  try {
410
441
  resolvedPrimary = await resolveConfiguredModel(
411
442
  ctx,
@@ -415,10 +446,12 @@ const collectAdvisorResponse = async (
415
446
  } catch (error) {
416
447
  primaryError = error instanceof Error ? error : new Error(String(error));
417
448
  }
449
+
418
450
  if (resolvedPrimary) {
419
451
  prepared = options.followUp
420
452
  ? prepareFollowUp(options.followUp, options.question, options.ctx)
421
453
  : await prepareFreshRequest(options, resolvedPrimary);
454
+
422
455
  try {
423
456
  return await runAdvisorAttempt(
424
457
  options,
@@ -430,12 +463,15 @@ const collectAdvisorResponse = async (
430
463
  primaryError = error instanceof Error ? error : new Error(String(error));
431
464
  }
432
465
  }
466
+
433
467
  if (!primaryError) {
434
468
  throw new Error("Advisor request failed before an error was recorded.");
435
469
  }
470
+
436
471
  if (signal?.aborted) {
437
472
  throw primaryError;
438
473
  }
474
+
439
475
  return runFallbackAdvisorAttempt(
440
476
  options,
441
477
  primaryModel,
@@ -473,9 +509,11 @@ export const consultAdvisor = async (
473
509
  signal,
474
510
  systemPrompt: ADVISOR_SYSTEM,
475
511
  });
512
+
476
513
  const adviceId = randomUUID();
477
514
  const { followUpPayload, ...publicResult } = result;
478
515
  onFollowUpPayload?.(adviceId, followUpPayload, followUp?.adviceId);
516
+
479
517
  return { ...publicResult, adviceId, trigger };
480
518
  };
481
519
 
@@ -498,10 +536,13 @@ export const runAdvisorGate = async (
498
536
  signal,
499
537
  systemPrompt: ADVISOR_DECISION_SYSTEM,
500
538
  });
539
+
501
540
  const parsed = parseAutomaticDecision(result.markdown);
541
+
502
542
  if (!parsed.ok) {
503
543
  return { ...parsed, usage: result.usage };
504
544
  }
545
+
505
546
  return {
506
547
  ...parsed,
507
548
  agentRulesBytes: result.agentRulesBytes,
@@ -514,7 +555,9 @@ export const runAdvisorGate = async (
514
555
  if (signal?.aborted) {
515
556
  throw error;
516
557
  }
558
+
517
559
  const message = error instanceof Error ? error.message : String(error);
560
+
518
561
  return {
519
562
  category:
520
563
  error instanceof AdvisorNoAdviceError
@@ -45,6 +45,7 @@ export const gateFailureEffectForMode = (mode: GateFailureMode) => {
45
45
  if (mode === "warn-and-continue") {
46
46
  return "continued" as const;
47
47
  }
48
+
48
49
  return mode === "block-tool"
49
50
  ? ("tool-blocked" as const)
50
51
  : ("session-blocked" as const);
@@ -57,6 +58,7 @@ export const gateDecisionEffect = (
57
58
  if (decision === "proceed") {
58
59
  return "continued" as const;
59
60
  }
61
+
60
62
  return decision === "blocked"
61
63
  ? gateFailureEffectForMode(failureMode)
62
64
  : ("tool-blocked" as const);
@@ -73,17 +75,22 @@ export const failureEffect = (
73
75
  const reason = `Advisor gate ${category}: ${message}`;
74
76
  notifyLocalFailure(ctx, message, failureMode === "block-session");
75
77
  notifyHerdrAdvisorFailure("Advisor gate failure", reason);
78
+
76
79
  if (failureMode === "warn-and-continue") {
77
80
  return { block: false, effect: "continued" as const, reason };
78
81
  }
82
+
79
83
  if (failureMode === "block-tool") {
80
84
  return { block: true, effect: "tool-blocked" as const, reason };
81
85
  }
86
+
82
87
  session.block(reason);
83
88
  herdrBlock.set(reason);
89
+
84
90
  if (advisorBlockOnBlockedRef) {
85
91
  ctx.abort();
86
92
  }
93
+
87
94
  return { block: true, effect: "session-blocked" as const, reason };
88
95
  };
89
96
 
@@ -101,16 +108,21 @@ export const blockedDecisionEffect = (
101
108
  "warning"
102
109
  );
103
110
  }
111
+
104
112
  return { block: false, effect: "continued" as const, reason };
105
113
  }
114
+
106
115
  if (failureMode === "block-tool") {
107
116
  return { block: true, effect: "tool-blocked" as const, reason };
108
117
  }
118
+
109
119
  session.block(reason);
110
120
  herdrBlock.set(reason);
121
+
111
122
  if (advisorBlockOnBlockedRef) {
112
123
  ctx.abort();
113
124
  }
125
+
114
126
  return { block: true, effect: "session-blocked" as const, reason };
115
127
  };
116
128
 
@@ -123,14 +135,20 @@ export const reserveAdvisorCall = (
123
135
  if (event.toolName !== "ask_advisor" || isSimpleMode()) {
124
136
  return;
125
137
  }
138
+
126
139
  if (!session.reserveCall(event.toolCallId, getAdvisorMaxCallsPerSession())) {
127
140
  const message = "Advisor call budget exhausted for this session.";
141
+
128
142
  if (ctx.hasUI) {
129
143
  ctx.ui.notify(message, "warning");
130
144
  }
145
+
131
146
  notifyHerdrAdvisorFailure("Advisor budget exhausted", message);
147
+
132
148
  return { block: true, reason: message };
133
149
  }
150
+
134
151
  reservedCalls.add(event.toolCallId);
152
+
135
153
  return {};
136
154
  };
@@ -7,6 +7,7 @@ const namedGroups = (match: RegExpExecArray): Record<string, string> =>
7
7
 
8
8
  const DECISION_LINE =
9
9
  /^Decision\s*:\s*(?<decision>proceed|revise|blocked)\s*$/iu;
10
+
10
11
  const CODE_FENCE = /^ {0,3}(?<marker>`{3,}|~{3,})(?<suffix>.*)$/u;
11
12
  const LINE_BREAK = /\r?\n/u;
12
13
 
@@ -29,11 +30,13 @@ const advanceFence = (
29
30
  if (marker[0] === "`" && suffix.includes("`")) {
30
31
  return { closed: false, openingFence: undefined };
31
32
  }
33
+
32
34
  return {
33
35
  closed: false,
34
36
  openingFence: { character: marker[0], length: marker.length },
35
37
  };
36
38
  }
39
+
37
40
  if (
38
41
  suffix.trim().length > 0 ||
39
42
  marker[0] !== openingFence.character ||
@@ -41,6 +44,7 @@ const advanceFence = (
41
44
  ) {
42
45
  return { closed: false, openingFence };
43
46
  }
47
+
44
48
  return { closed: true, openingFence: undefined };
45
49
  };
46
50
 
@@ -49,6 +53,7 @@ export const parseAutomaticDecision = (
49
53
  ): AdvisorGateResult | AdvisorGateFailure => {
50
54
  const lines = text.split(LINE_BREAK);
51
55
  const nonEmpty = lines.findIndex((line) => line.trim().length > 0);
56
+
52
57
  if (nonEmpty === -1) {
53
58
  return {
54
59
  category: "empty-response",
@@ -56,8 +61,10 @@ export const parseAutomaticDecision = (
56
61
  ok: false,
57
62
  };
58
63
  }
64
+
59
65
  const first = lines[nonEmpty].trim();
60
66
  const match = DECISION_LINE.exec(first);
67
+
61
68
  if (!match) {
62
69
  return {
63
70
  category: first.toLowerCase().startsWith("decision:")
@@ -69,11 +76,13 @@ export const parseAutomaticDecision = (
69
76
  ok: false,
70
77
  };
71
78
  }
79
+
72
80
  // SAFETY: DECISION_LINE's decision group only matches proceed, revise, or blocked.
73
81
  const decision = namedGroups(match).decision.toLowerCase() as GateDecision;
74
82
  let openingFence: FenceState | undefined;
75
83
  const decisions: string[] = [];
76
84
  let pendingFencedDecisions: string[] = [];
85
+
77
86
  for (const line of lines.slice(nonEmpty + 1)) {
78
87
  const trimmed = line.trim();
79
88
  // Decisions in a balanced fenced example are illustrative. Remember the
@@ -82,34 +91,46 @@ export const parseAutomaticDecision = (
82
91
  // retain its decisions so malformed Markdown cannot make the gate fail
83
92
  // open.
84
93
  const fence = CODE_FENCE.exec(line);
94
+
85
95
  if (fence) {
86
96
  const groups = namedGroups(fence);
97
+
87
98
  const { closed, openingFence: nextOpeningFence } = advanceFence(
88
99
  openingFence,
89
100
  groups.marker,
90
101
  groups.suffix
91
102
  );
103
+
92
104
  openingFence = nextOpeningFence;
105
+
93
106
  if (closed) {
94
107
  pendingFencedDecisions = [];
95
108
  }
109
+
96
110
  continue;
97
111
  }
112
+
98
113
  const subsequent = DECISION_LINE.exec(trimmed);
114
+
99
115
  if (!subsequent) {
100
116
  continue;
101
117
  }
118
+
102
119
  const repeated = namedGroups(subsequent).decision.trim().toLowerCase();
120
+
103
121
  if (openingFence) {
104
122
  pendingFencedDecisions.push(repeated);
105
123
  } else {
106
124
  decisions.push(repeated);
107
125
  }
108
126
  }
127
+
109
128
  if (openingFence) {
110
129
  decisions.push(...pendingFencedDecisions);
111
130
  }
131
+
112
132
  const [repeated] = decisions;
133
+
113
134
  if (repeated !== undefined) {
114
135
  return repeated === decision
115
136
  ? {
@@ -126,6 +147,7 @@ export const parseAutomaticDecision = (
126
147
  ok: false,
127
148
  };
128
149
  }
150
+
129
151
  return {
130
152
  decision,
131
153
  markdown: text,
@@ -73,6 +73,7 @@ const bypassOutcome = (
73
73
  normalizedQuestion: string | undefined
74
74
  ): ScreeningOutcome | undefined => {
75
75
  const lastSkip = session.lastJevSkip;
76
+
76
77
  if (options.force) {
77
78
  if (
78
79
  lastSkip?.normalizedQuestion !== undefined &&
@@ -80,8 +81,10 @@ const bypassOutcome = (
80
81
  ) {
81
82
  session.recordJevFilterOverride();
82
83
  }
84
+
83
85
  return allow();
84
86
  }
87
+
85
88
  if (
86
89
  normalizedQuestion !== undefined &&
87
90
  lastSkip?.normalizedQuestion === normalizedQuestion &&
@@ -89,8 +92,10 @@ const bypassOutcome = (
89
92
  advisorJevFilterOverrideWindowRef
90
93
  ) {
91
94
  session.recordJevFilterOverride();
95
+
92
96
  return allow();
93
97
  }
98
+
94
99
  return undefined;
95
100
  };
96
101
 
@@ -102,6 +107,7 @@ const screenWithJev = async (
102
107
  normalizedQuestion: string | undefined
103
108
  ): Promise<ScreeningOutcome> => {
104
109
  const credentials = await (deps.resolveTransport ?? resolveJevTransport)(ctx);
110
+
105
111
  if (!credentials) {
106
112
  session.recordJevFilterFailure();
107
113
  notifyOutageOnce(
@@ -109,42 +115,54 @@ const screenWithJev = async (
109
115
  "missing-key",
110
116
  "No credentials resolved for the selected Jev/Decisions provider."
111
117
  );
118
+
112
119
  return allow();
113
120
  }
121
+
114
122
  if (credentials.source === "advisor-json") {
115
123
  const warning = consumePlaintextKeyWarning();
124
+
116
125
  if (warning && ctx.hasUI) {
117
126
  ctx.ui.notify(warning, "warning");
118
127
  }
119
128
  }
120
129
 
121
130
  const client = jevClientFromCredentials(credentials, deps.fetch);
131
+
122
132
  try {
123
133
  const result = await client.ask(
124
134
  buildJevState(ctx, options),
125
135
  screeningQuestions,
126
136
  options.signal
127
137
  );
138
+
128
139
  session.recordJevFilterUsage(result.usage);
140
+
129
141
  const verdict = composeScreeningVerdict(result.answers, {
130
142
  noulMargin: advisorJevFilterNoulMarginRef,
131
143
  skipConfidence: advisorJevFilterSkipConfidenceRef,
132
144
  });
145
+
133
146
  if (verdict.skip) {
134
147
  session.recordJevFilterSkipped(false, normalizedQuestion);
148
+
135
149
  return {
136
150
  decision: "skip",
137
151
  kind: "screened",
138
152
  reason: "low stakes and resolvable without a consultation",
139
153
  };
140
154
  }
155
+
141
156
  session.recordJevFilterAllowed();
157
+
142
158
  return allow();
143
159
  } catch (error) {
144
160
  if (options.signal?.aborted) {
145
161
  throw error;
146
162
  }
163
+
147
164
  session.recordJevFilterFailure();
165
+
148
166
  if (error instanceof JevFailure) {
149
167
  notifyOutageOnce(ctx, error.category, error.message);
150
168
  } else {
@@ -154,6 +172,7 @@ const screenWithJev = async (
154
172
  error instanceof Error ? error.message : String(error)
155
173
  );
156
174
  }
175
+
157
176
  return allow();
158
177
  }
159
178
  };
@@ -173,17 +192,22 @@ export const screenConsultation = (
173
192
  if (isSimpleMode()) {
174
193
  return Promise.resolve(allow());
175
194
  }
195
+
176
196
  // Repeat reattachment and its force/passthrough escape hatch are code-side
177
197
  // and free: they run regardless of the Jev enable flag, which only gates
178
198
  // the (paid, network) Jev screening call.
179
199
  const normalizedQuestion = normalizeScreeningQuestion(options.question);
180
200
  const bypass = bypassOutcome(session, options, normalizedQuestion);
201
+
181
202
  if (bypass) {
182
203
  return Promise.resolve(bypass);
183
204
  }
205
+
184
206
  const reattached = session.reattachedAdviceFor(normalizedQuestion);
207
+
185
208
  if (reattached) {
186
209
  session.recordJevFilterSkipped(true, normalizedQuestion);
210
+
187
211
  return Promise.resolve({
188
212
  decision: "skip",
189
213
  kind: "repeat",
@@ -191,9 +215,11 @@ export const screenConsultation = (
191
215
  reattachedAdvice: capUtf8Bytes(reattached, REATTACHED_ADVICE_CAP_BYTES),
192
216
  });
193
217
  }
218
+
194
219
  if (!advisorJevFilterEnabledRef) {
195
220
  return Promise.resolve(allow());
196
221
  }
222
+
197
223
  return screenWithJev(ctx, session, options, deps, normalizedQuestion);
198
224
  };
199
225