@vellumai/assistant 0.11.2-dev.202608071501.106e29e → 0.11.2-dev.202608071620.8afd4b3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.2-dev.202608071501.106e29e",
3
+ "version": "0.11.2-dev.202608071620.8afd4b3",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -27,6 +27,10 @@ let fakeGuardianPrincipalId: string | undefined = undefined;
27
27
  // exactly when the SSE self-heal lookup completes.
28
28
  const pendingAsyncResolutions: Array<(value: string | undefined) => void> = [];
29
29
 
30
+ /** Options each async resolution was called with, in the same order. */
31
+ const asyncResolutionOptions: Array<{ forceRefresh?: boolean } | undefined> =
32
+ [];
33
+
30
34
  mock.module("../config/env.js", () => ({
31
35
  isHttpAuthDisabled: () => fakeHttpAuthDisabled,
32
36
  hasUngatedHttpAuthDisabled: () => false,
@@ -42,10 +46,14 @@ mock.module("../runtime/local-actor-identity.js", () => ({
42
46
  }
43
47
  return fakeGuardianPrincipalId;
44
48
  },
45
- resolveActorPrincipalIdForLocalGuardian: (rawHeader: string | undefined) => {
49
+ resolveActorPrincipalIdForLocalGuardian: (
50
+ rawHeader: string | undefined,
51
+ options?: { forceRefresh?: boolean },
52
+ ) => {
46
53
  if (rawHeader !== "dev-bypass" || !fakeHttpAuthDisabled) {
47
54
  return Promise.resolve(rawHeader);
48
55
  }
56
+ asyncResolutionOptions.push(options);
49
57
  return new Promise<string | undefined>((resolve) => {
50
58
  pendingAsyncResolutions.push(resolve);
51
59
  });
@@ -57,6 +65,23 @@ async function flushMicrotasks(): Promise<void> {
57
65
  await new Promise((resolve) => setTimeout(resolve, 0));
58
66
  }
59
67
 
68
+ /**
69
+ * Poll until `predicate` holds, for assertions that depend on the heal's
70
+ * retry backoff timer rather than on promise settling alone.
71
+ */
72
+ async function waitFor(
73
+ predicate: () => boolean,
74
+ timeoutMs = 3_000,
75
+ ): Promise<void> {
76
+ const deadline = Date.now() + timeoutMs;
77
+ while (!predicate()) {
78
+ if (Date.now() >= deadline) {
79
+ throw new Error("waitFor timed out");
80
+ }
81
+ await new Promise((resolve) => setTimeout(resolve, 10));
82
+ }
83
+ }
84
+
60
85
  // ── Real imports (after mocks) ────────────────────────────────────────────
61
86
 
62
87
  import { AssistantEventHub } from "../runtime/assistant-event-hub.js";
@@ -69,6 +94,7 @@ afterAll(() => {
69
94
  describe("events SSE registration — dev-bypass actor translation", () => {
70
95
  beforeEach(() => {
71
96
  pendingAsyncResolutions.length = 0;
97
+ asyncResolutionOptions.length = 0;
72
98
  });
73
99
 
74
100
  test("translates 'dev-bypass' to the real guardian principalId when auth is disabled", () => {
@@ -261,6 +287,91 @@ describe("events SSE registration — dev-bypass actor translation", () => {
261
287
  ac2.abort();
262
288
  });
263
289
 
290
+ test("retries the heal after a failed lookup instead of giving up for the connection's lifetime", async () => {
291
+ // The gateway IPC returns null on any transport failure, so the first
292
+ // lookup can miss even when a guardian is bound. A subscription left
293
+ // principal-less rejects every host-proxy result it submits, so the heal
294
+ // has to outlive one miss rather than stopping there.
295
+ fakeHttpAuthDisabled = true;
296
+ fakeGuardianPrincipalId = undefined; // cold cache: sync resolution misses
297
+
298
+ const ac = new AbortController();
299
+ const hub = new AssistantEventHub();
300
+
301
+ handleSubscribeAssistantEvents(
302
+ {
303
+ headers: {
304
+ "x-vellum-client-id": "retry-client-001",
305
+ "x-vellum-interface-id": "chrome-extension",
306
+ "x-vellum-actor-principal-id": "dev-bypass",
307
+ },
308
+ abortSignal: ac.signal,
309
+ },
310
+ { hub },
311
+ );
312
+
313
+ // First attempt fails (gateway not reachable yet).
314
+ expect(pendingAsyncResolutions).toHaveLength(1);
315
+ pendingAsyncResolutions.shift()!(undefined);
316
+ await flushMicrotasks();
317
+ expect(
318
+ hub.getActorPrincipalIdForClient("retry-client-001"),
319
+ ).toBeUndefined();
320
+
321
+ // The retry fires on the backoff and succeeds this time.
322
+ await waitFor(() => pendingAsyncResolutions.length === 1);
323
+ pendingAsyncResolutions.shift()!("guardian-real-id");
324
+ await flushMicrotasks();
325
+
326
+ expect(hub.getActorPrincipalIdForClient("retry-client-001")).toBe(
327
+ "guardian-real-id",
328
+ );
329
+
330
+ // Every attempt must bypass the guardian-delivery cache. A successful read
331
+ // that finds no binding is cached for minutes, which outlives the retry
332
+ // schedule, so a cached read would spend all attempts on the same answer
333
+ // and never observe a binding created in between.
334
+ expect(asyncResolutionOptions).toEqual([
335
+ { forceRefresh: true },
336
+ { forceRefresh: true },
337
+ ]);
338
+
339
+ ac.abort();
340
+ });
341
+
342
+ test("needsActorPrincipalHeal reports only live, principal-less client subscriptions", () => {
343
+ const hub = new AssistantEventHub();
344
+ const bare = hub.subscribe({
345
+ type: "client",
346
+ clientId: "needs-heal-001",
347
+ interfaceId: "chrome-extension",
348
+ capabilities: [],
349
+ callback: () => {},
350
+ });
351
+ const withPrincipal = hub.subscribe({
352
+ type: "client",
353
+ clientId: "needs-heal-002",
354
+ interfaceId: "macos",
355
+ capabilities: [],
356
+ actorPrincipalId: "guardian-real-id",
357
+ callback: () => {},
358
+ });
359
+ const process = hub.subscribe({ type: "process", callback: () => {} });
360
+
361
+ expect(hub.needsActorPrincipalHeal(bare.connectionId)).toBe(true);
362
+ expect(hub.needsActorPrincipalHeal(withPrincipal.connectionId)).toBe(false);
363
+ expect(hub.needsActorPrincipalHeal(process.connectionId)).toBe(false);
364
+ expect(hub.needsActorPrincipalHeal("conn-does-not-exist")).toBe(false);
365
+
366
+ // A disposed connection stops needing a heal, which is what ends the
367
+ // retry loop when a client disconnects mid-backoff.
368
+ bare.dispose();
369
+ expect(hub.needsActorPrincipalHeal(bare.connectionId)).toBe(false);
370
+
371
+ withPrincipal.dispose();
372
+ process.dispose();
373
+ });
374
+
264
375
  test("fillClientActorPrincipalId never overwrites a present principal", () => {
265
376
  const hub = new AssistantEventHub();
266
377
  const sub = hub.subscribe({
@@ -101,17 +101,20 @@ import {
101
101
  getRegisteredKinds,
102
102
  getResolver,
103
103
  } from "../approvals/guardian-request-resolvers.js";
104
+ import { getConfig } from "../config/loader.js";
104
105
  import { getDb } from "../persistence/db-connection.js";
105
106
  import { getSqlite } from "../persistence/db-connection.js";
106
107
  import { initializeDb } from "../persistence/db-init.js";
107
108
  import { scopedApprovalGrants } from "../persistence/schema/index.js";
108
109
  import {
110
+ TC_GRANT_WAIT_MAX_MS,
109
111
  ToolApprovalHandler,
110
112
  waitForInlineGrant,
111
113
  } from "../tools/tool-approval-handler.js";
112
114
  import type { ToolContext } from "../tools/types.js";
115
+ import { setConfig } from "./helpers/set-config.js";
113
116
 
114
- /** Short wait config for tests — avoids blocking test suite on the 60s default. */
117
+ /** Short wait config for tests: keeps escalation cases off the real budget. */
115
118
  const TEST_INLINE_WAIT_CONFIG = { maxWaitMs: 100, intervalMs: 20 };
116
119
 
117
120
  await initializeDb();
@@ -490,6 +493,42 @@ describe("inline wait-and-resume", () => {
490
493
  expect(elapsed).toBeLessThan(500);
491
494
  });
492
495
 
496
+ test("waitForInlineGrant spends timeouts.permissionTimeoutSec when no explicit budget is given", async () => {
497
+ // The guardian's escalation window must track the configured approval
498
+ // budget rather than a compiled-in constant, so an operator raising
499
+ // permissionTimeoutSec actually widens the window a guardian has to
500
+ // answer in. Omitting maxWaitMs is what production does.
501
+ const priorTimeouts = getConfig().timeouts;
502
+ setConfig("timeouts", {
503
+ ...priorTimeouts,
504
+ permissionTimeoutSec: 0.15,
505
+ });
506
+ try {
507
+ const req = seedGrantRequest("sha256:configbudget");
508
+
509
+ const start = Date.now();
510
+ const result = await waitForInlineGrant(
511
+ req.id,
512
+ {
513
+ toolName: "bash",
514
+ inputDigest: "sha256:configbudget",
515
+ consumingRequestId: "consume-config-budget",
516
+ },
517
+ { intervalMs: 20 },
518
+ );
519
+ const elapsed = Date.now() - start;
520
+
521
+ expect(result.outcome).toBe("timeout");
522
+ // Bounded well under TC_GRANT_WAIT_MAX_MS: a regression that ignores
523
+ // config and falls back to the constant blows this ceiling by ~400x.
524
+ expect(elapsed).toBeGreaterThanOrEqual(120);
525
+ expect(elapsed).toBeLessThan(3_000);
526
+ expect(elapsed).toBeLessThan(TC_GRANT_WAIT_MAX_MS);
527
+ } finally {
528
+ setConfig("timeouts", priorTimeouts);
529
+ }
530
+ }, 10_000);
531
+
493
532
  test("waitForInlineGrant returns aborted when signal fires during wait", async () => {
494
533
  const req = seedGrantRequest("sha256:abortwait");
495
534
 
@@ -170,6 +170,7 @@ mock.module("../channels/gateway-guardian-requests.js", () => sim.module);
170
170
  import { applyGuardianDecision } from "../approvals/guardian-decision-primitive.js";
171
171
  import type { ActorContext } from "../approvals/guardian-request-resolvers.js";
172
172
  import { getResolver } from "../approvals/guardian-request-resolvers.js";
173
+ import { getConfig } from "../config/loader.js";
173
174
  import type { TrustContext } from "../daemon/trust-context-types.js";
174
175
  import { getDb } from "../persistence/db-connection.js";
175
176
  import { initializeDb } from "../persistence/db-init.js";
@@ -177,12 +178,14 @@ import { scopedApprovalGrants } from "../persistence/schema/index.js";
177
178
  import { bridgeConfirmationRequestToGuardian } from "../runtime/confirmation-request-guardian-bridge.js";
178
179
  import { resolveRoutingState } from "../runtime/trust-context-resolver.js";
179
180
  import {
181
+ resolveInlineGrantWaitMs,
180
182
  TC_GRANT_WAIT_MAX_MS,
181
183
  ToolApprovalHandler,
182
184
  waitForInlineGrant,
183
185
  } from "../tools/tool-approval-handler.js";
184
186
  import type { ToolContext } from "../tools/types.js";
185
187
  import { seedContactChannel } from "./helpers/seed-contact-channel.js";
188
+ import { setConfig } from "./helpers/set-config.js";
186
189
 
187
190
  await initializeDb();
188
191
 
@@ -754,7 +757,10 @@ describe("(f) timeout/stale flow: stale guardian decision after inline wait time
754
757
  test("inline_wait_active staleness guard: expired marker allows retry notification", async () => {
755
758
  // Create a guardian request with a stale inline_wait_active marker
756
759
  // that simulates a daemon crash during the wait.
757
- const staleTimestamp = Date.now() - TC_GRANT_WAIT_MAX_MS - 60_000;
760
+ // Age the marker past the real wait budget, which the resolver's
761
+ // staleness threshold tracks. Deriving it from the same helper the
762
+ // waiter uses keeps this case meaningful if the budget changes.
763
+ const staleTimestamp = Date.now() - resolveInlineGrantWaitMs() - 60_000;
758
764
  const req = sim.seedRequest({
759
765
  id: `req-stale-${Date.now()}`,
760
766
  kind: "tool_grant_request",
@@ -802,6 +808,67 @@ describe("(f) timeout/stale flow: stale guardian decision after inline wait time
802
808
  expect(retryNotifications.length).toBeGreaterThan(0);
803
809
  });
804
810
 
811
+ test("inline_wait_active marker older than the fallback constant but inside the real budget still suppresses retry", async () => {
812
+ // The staleness threshold must track the wait budget, not the fallback
813
+ // constant. A marker aged past TC_GRANT_WAIT_MAX_MS + buffer but still
814
+ // well inside the configured budget belongs to a waiter that is very
815
+ // much alive: telling the requester to retry would race a call that is
816
+ // about to resume, and the retry then fails against the one-time grant
817
+ // the live waiter consumes.
818
+ const priorTimeouts = getConfig().timeouts;
819
+ // Seed the budget rather than leaning on the ambient default, so the
820
+ // window this case probes exists no matter what the suite's config holds.
821
+ setConfig("timeouts", { ...priorTimeouts, permissionTimeoutSec: 300 });
822
+ try {
823
+ const budgetMs = resolveInlineGrantWaitMs();
824
+ // Comfortably past the old 90s threshold, comfortably short of the budget.
825
+ const markerAgeMs = TC_GRANT_WAIT_MAX_MS + 45_000;
826
+ const liveTimestamp = Date.now() - markerAgeMs;
827
+ expect(markerAgeMs).toBeLessThan(budgetMs);
828
+
829
+ const req = sim.seedRequest({
830
+ id: `req-live-${Date.now()}`,
831
+ kind: "tool_grant_request",
832
+ sourceType: "channel",
833
+ sourceChannel: "telegram",
834
+ sourceConversationId: "conv-live-1",
835
+ requesterExternalUserId: "requester-1",
836
+ requesterChatId: "requester-chat-1",
837
+ guardianExternalUserId: "guardian-1",
838
+ guardianPrincipalId: "test-principal-id",
839
+ toolName: "bash",
840
+ inputDigest: "sha256:livewait",
841
+ expiresAt: Date.now() + 60_000,
842
+ });
843
+
844
+ await sim.module.updateGuardianRequest(req.id, {
845
+ followupState: `inline_wait_active:${liveTimestamp}`,
846
+ });
847
+
848
+ deliveredReplies.length = 0;
849
+ const approvalResult = await applyGuardianDecision({
850
+ requestId: req.id,
851
+ action: "approve_once",
852
+ actorContext: guardianActor(),
853
+ channelDeliveryContext: {
854
+ replyCallbackUrl: "http://localhost:3000/reply",
855
+ guardianChatId: "guardian-chat-1",
856
+ assistantId: "self",
857
+ },
858
+ });
859
+ expect(approvalResult.applied).toBe(true);
860
+
861
+ const retryNotifications = deliveredReplies.filter(
862
+ (r) =>
863
+ typeof r.payload.text === "string" &&
864
+ (r.payload.text as string).includes("Please retry"),
865
+ );
866
+ expect(retryNotifications.length).toBe(0);
867
+ } finally {
868
+ setConfig("timeouts", priorTimeouts);
869
+ }
870
+ });
871
+
805
872
  test("fresh inline_wait_active marker suppresses retry notification", async () => {
806
873
  // Create a request with a FRESH inline_wait_active marker
807
874
  const freshTimestamp = Date.now();
@@ -54,7 +54,7 @@ import {
54
54
  readBatchMetadata,
55
55
  resolvePendingQuestion,
56
56
  } from "../runtime/question-resolution.js";
57
- import { TC_GRANT_WAIT_MAX_MS } from "../tools/tool-approval-handler.js";
57
+ import { resolveInlineGrantWaitMs } from "../tools/tool-approval-handler.js";
58
58
  import { getLogger } from "../util/logger.js";
59
59
  import {
60
60
  channelCanAddressOneReaderInBand,
@@ -1587,7 +1587,10 @@ const toolGrantRequestResolver: GuardianRequestResolver = {
1587
1587
  // outlive the actual waiter if the daemon crashes or restarts during
1588
1588
  // the wait. To avoid permanently suppressing the retry notification, we
1589
1589
  // treat the marker as stale if the encoded start timestamp is older than
1590
- // the maximum wait budget plus a 30s buffer.
1590
+ // the maximum wait budget plus a 30s buffer. The budget is read from the
1591
+ // same resolver the waiter itself uses, so a config change moves both
1592
+ // together; sizing this off a constant would let it fall below the real
1593
+ // wait and declare a live waiter dead.
1591
1594
  const INLINE_WAIT_STALENESS_BUFFER_MS = 30_000;
1592
1595
  const freshRequest = await getGuardianRequestOrNull(request.id);
1593
1596
  const followupState = freshRequest?.followupState ?? "";
@@ -1604,7 +1607,7 @@ const toolGrantRequestResolver: GuardianRequestResolver = {
1604
1607
  ? Date.now() - waitStartMs
1605
1608
  : Infinity; // Treat unparseable timestamps as stale for safety.
1606
1609
  const stalenessThresholdMs =
1607
- TC_GRANT_WAIT_MAX_MS + INLINE_WAIT_STALENESS_BUFFER_MS;
1610
+ resolveInlineGrantWaitMs() + INLINE_WAIT_STALENESS_BUFFER_MS;
1608
1611
  if (markerAgeMs > stalenessThresholdMs) {
1609
1612
  log.warn(
1610
1613
  {
@@ -26,7 +26,7 @@ export const TimeoutConfigSchema = z
26
26
  .positive("timeouts.permissionTimeoutSec must be a positive number")
27
27
  .default(300)
28
28
  .describe(
29
- "How long to wait for user permission approval before timing out (seconds)",
29
+ "How long to wait for a human to approve a tool call before timing out (seconds). Spent by both approval paths: the interactive permission prompt, and the inline wait when a contact's sensitive tool call is escalated to the guardian.",
30
30
  ),
31
31
  questionResponseTimeoutSec: z
32
32
  .number({ error: "timeouts.questionResponseTimeoutSec must be a number" })
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Tests for the cache-bypass option on the local guardian principal lookup.
3
+ *
4
+ * The guardian-delivery reader caches a successful read that finds no binding,
5
+ * and gateway-side binding writes do not invalidate the daemon's cache. A
6
+ * caller polling for a binding it expects to appear (the SSE actor-principal
7
+ * heal) therefore has to force the read, or every attempt re-reads the same
8
+ * empty answer until the TTL lapses.
9
+ */
10
+ import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
11
+
12
+ import type { GuardianDelivery } from "@vellumai/gateway-client";
13
+
14
+ let cachedResult: GuardianDelivery[] | null = null;
15
+ let freshResult: GuardianDelivery[] | null = null;
16
+ let cachedCalls = 0;
17
+ let freshCalls = 0;
18
+
19
+ mock.module("../../config/env.js", () => ({
20
+ isHttpAuthDisabled: () => true,
21
+ hasUngatedHttpAuthDisabled: () => false,
22
+ }));
23
+
24
+ mock.module("../../contacts/guardian-delivery-reader.js", () => ({
25
+ getGuardianDelivery: () => {
26
+ cachedCalls++;
27
+ return Promise.resolve(cachedResult);
28
+ },
29
+ getGuardianDeliveryFresh: () => {
30
+ freshCalls++;
31
+ return Promise.resolve(freshResult);
32
+ },
33
+ peekCachedGuardianDelivery: () => undefined,
34
+ guardianForChannel: (list: GuardianDelivery[]) => list[0],
35
+ }));
36
+
37
+ import {
38
+ findLocalGuardianPrincipalId,
39
+ resolveActorPrincipalIdForLocalGuardian,
40
+ } from "../local-actor-identity.js";
41
+
42
+ afterAll(() => {
43
+ mock.restore();
44
+ });
45
+
46
+ /** Minimal guardian row: only `principalId` is read here. */
47
+ function guardian(principalId: string): GuardianDelivery {
48
+ return { principalId } as unknown as GuardianDelivery;
49
+ }
50
+
51
+ describe("local guardian principal lookup — cache bypass", () => {
52
+ beforeEach(() => {
53
+ cachedCalls = 0;
54
+ freshCalls = 0;
55
+ cachedResult = [];
56
+ freshResult = [];
57
+ });
58
+
59
+ test("reads the cache by default", async () => {
60
+ cachedResult = [guardian("guardian-cached")];
61
+ freshResult = [guardian("guardian-fresh")];
62
+
63
+ expect(await findLocalGuardianPrincipalId()).toBe("guardian-cached");
64
+ expect(cachedCalls).toBe(1);
65
+ expect(freshCalls).toBe(0);
66
+ });
67
+
68
+ test("forceRefresh bypasses the cache and sees a binding the cache would miss", async () => {
69
+ // Cached read holds the empty result from before the binding existed.
70
+ cachedResult = [];
71
+ freshResult = [guardian("guardian-fresh")];
72
+
73
+ expect(await findLocalGuardianPrincipalId()).toBeUndefined();
74
+ expect(await findLocalGuardianPrincipalId({ forceRefresh: true })).toBe(
75
+ "guardian-fresh",
76
+ );
77
+ expect(freshCalls).toBe(1);
78
+ });
79
+
80
+ test("resolveActorPrincipalIdForLocalGuardian threads forceRefresh through", async () => {
81
+ cachedResult = [];
82
+ freshResult = [guardian("guardian-fresh")];
83
+
84
+ expect(
85
+ await resolveActorPrincipalIdForLocalGuardian("dev-bypass"),
86
+ ).toBeUndefined();
87
+ expect(
88
+ await resolveActorPrincipalIdForLocalGuardian("dev-bypass", {
89
+ forceRefresh: true,
90
+ }),
91
+ ).toBe("guardian-fresh");
92
+ expect(freshCalls).toBe(1);
93
+ });
94
+
95
+ test("a non-dev-bypass principal is passed through without any lookup", async () => {
96
+ expect(
97
+ await resolveActorPrincipalIdForLocalGuardian("actor-123", {
98
+ forceRefresh: true,
99
+ }),
100
+ ).toBe("actor-123");
101
+ expect(cachedCalls).toBe(0);
102
+ expect(freshCalls).toBe(0);
103
+ });
104
+ });
@@ -465,6 +465,29 @@ export class AssistantEventHub {
465
465
  return this.getClientById(clientId)?.actorPrincipalId;
466
466
  }
467
467
 
468
+ /**
469
+ * Whether the connection identified by `connectionId` is still an active
470
+ * client subscription that carries no `actorPrincipalId`.
471
+ *
472
+ * Drives the retrying SSE self-heal (`sse-actor-principal-heal.ts`): the loop
473
+ * re-checks before each attempt so it stops as soon as the connection closes,
474
+ * is replaced by a reconnect, or gets a principal from any path. Returns
475
+ * `false` for an unknown, inactive, or process-type connection.
476
+ */
477
+ needsActorPrincipalHeal(connectionId: string): boolean {
478
+ for (const entry of this.subscribers) {
479
+ if (entry.connectionId !== connectionId) {
480
+ continue;
481
+ }
482
+ return (
483
+ entry.active &&
484
+ entry.type === "client" &&
485
+ entry.actorPrincipalId == null
486
+ );
487
+ }
488
+ return false;
489
+ }
490
+
468
491
  /**
469
492
  * Fill a missing `actorPrincipalId` on a live client subscription.
470
493
  *
@@ -11,6 +11,7 @@
11
11
  import { isHttpAuthDisabled } from "../config/env.js";
12
12
  import {
13
13
  getGuardianDelivery,
14
+ getGuardianDeliveryFresh,
14
15
  guardianForChannel,
15
16
  peekCachedGuardianDelivery,
16
17
  } from "../contacts/guardian-delivery-reader.js";
@@ -52,11 +53,19 @@ export function buildLocalAuthContext(conversationId: string): AuthContext {
52
53
  * Returns `undefined` when no vellum guardian binding exists (e.g. fresh
53
54
  * install before bootstrap, or the gateway is unreachable). Callers should
54
55
  * treat that case as "not yet available" and proceed without a principalId.
56
+ *
57
+ * `forceRefresh` bypasses the reader's TTL cache. A successful read that finds
58
+ * no binding is itself cached, and gateway-side binding writes do not
59
+ * invalidate the daemon's cache, so a caller that polls for a binding it
60
+ * expects to appear (the SSE actor-principal heal) must force the read or it
61
+ * re-reads the same empty answer until the TTL lapses.
55
62
  */
56
- export async function findLocalGuardianPrincipalId(): Promise<
57
- string | undefined
58
- > {
59
- const list = await getGuardianDelivery({ channelTypes: ["vellum"] });
63
+ export async function findLocalGuardianPrincipalId(options?: {
64
+ forceRefresh?: boolean;
65
+ }): Promise<string | undefined> {
66
+ const list = options?.forceRefresh
67
+ ? await getGuardianDeliveryFresh({ channelTypes: ["vellum"] })
68
+ : await getGuardianDelivery({ channelTypes: ["vellum"] });
60
69
  if (!list) {
61
70
  return undefined;
62
71
  }
@@ -136,15 +145,19 @@ export function findLocalGuardianPrincipalIdFromStore(): string | undefined {
136
145
  * `undefined` when dev-bypass is set but no guardian binding has been created
137
146
  * yet (e.g. fresh install before bootstrap); callers must treat this the
138
147
  * same as a missing principal.
148
+ *
149
+ * `forceRefresh` bypasses the guardian-delivery cache, for callers that poll
150
+ * for a binding they expect to appear. See {@link findLocalGuardianPrincipalId}.
139
151
  */
140
152
  export async function resolveActorPrincipalIdForLocalGuardian(
141
153
  rawHeader: string | undefined,
154
+ options?: { forceRefresh?: boolean },
142
155
  ): Promise<string | undefined> {
143
156
  if (rawHeader !== "dev-bypass" || !isHttpAuthDisabled()) {
144
157
  return rawHeader;
145
158
  }
146
159
 
147
- const guardianPrincipalId = await findLocalGuardianPrincipalId();
160
+ const guardianPrincipalId = await findLocalGuardianPrincipalId(options);
148
161
  if (guardianPrincipalId) {
149
162
  return guardianPrincipalId;
150
163
  }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Tests for the retrying SSE actor-principal self-heal.
3
+ *
4
+ * The invariant they pin: a single empty or failed guardian lookup must not
5
+ * strand the subscription without a principal. The read goes over the gateway
6
+ * IPC and comes back empty both when the transport fails and when no binding
7
+ * exists yet, and a subscription that stays principal-less rejects every
8
+ * host-proxy result its client submits with "Submitting actor does not match
9
+ * the target client's actor for this request" until it reconnects.
10
+ */
11
+ import { describe, expect, mock, test } from "bun:test";
12
+
13
+ import { startActorPrincipalHeal } from "../sse-actor-principal-heal.js";
14
+
15
+ /** All-zero schedule so the retries run without real wall-clock delay. */
16
+ const NO_DELAYS = [0, 0, 0];
17
+
18
+ /** Minimal hub double: `needs` flips to false once a principal is filled. */
19
+ function fakeHub(options?: { needs?: boolean }) {
20
+ let needs = options?.needs ?? true;
21
+ const filled: string[] = [];
22
+ return {
23
+ filled,
24
+ setNeeds(value: boolean) {
25
+ needs = value;
26
+ },
27
+ needsActorPrincipalHeal: mock(() => needs),
28
+ fillClientActorPrincipalId: mock((_connectionId: string, id: string) => {
29
+ filled.push(id);
30
+ needs = false;
31
+ }),
32
+ };
33
+ }
34
+
35
+ /** Let the heal's async loop run to completion. */
36
+ async function settle(): Promise<void> {
37
+ for (let i = 0; i < 10; i++) {
38
+ await new Promise((resolve) => setTimeout(resolve, 0));
39
+ }
40
+ }
41
+
42
+ describe("startActorPrincipalHeal", () => {
43
+ test("fills the principal on the first successful attempt", async () => {
44
+ const hub = fakeHub();
45
+ startActorPrincipalHeal({
46
+ hub,
47
+ connectionId: "conn-1",
48
+ resolve: () => Promise.resolve("guardian-real-id"),
49
+ delaysMs: NO_DELAYS,
50
+ });
51
+ await settle();
52
+
53
+ expect(hub.filled).toEqual(["guardian-real-id"]);
54
+ expect(hub.needsActorPrincipalHeal).toHaveBeenCalledTimes(1);
55
+ });
56
+
57
+ test("retries after a lookup that resolves undefined (gateway unreachable)", async () => {
58
+ const hub = fakeHub();
59
+ let calls = 0;
60
+ startActorPrincipalHeal({
61
+ hub,
62
+ connectionId: "conn-1",
63
+ resolve: () => {
64
+ calls++;
65
+ // Two failed reads, then the gateway comes up.
66
+ return Promise.resolve(calls < 3 ? undefined : "guardian-real-id");
67
+ },
68
+ delaysMs: NO_DELAYS,
69
+ });
70
+ await settle();
71
+
72
+ expect(calls).toBe(3);
73
+ expect(hub.filled).toEqual(["guardian-real-id"]);
74
+ });
75
+
76
+ test("retries after a lookup that rejects", async () => {
77
+ const hub = fakeHub();
78
+ let calls = 0;
79
+ startActorPrincipalHeal({
80
+ hub,
81
+ connectionId: "conn-1",
82
+ resolve: () => {
83
+ calls++;
84
+ return calls === 1
85
+ ? Promise.reject(new Error("ipc timeout"))
86
+ : Promise.resolve("guardian-real-id");
87
+ },
88
+ delaysMs: NO_DELAYS,
89
+ });
90
+ await settle();
91
+
92
+ expect(calls).toBe(2);
93
+ expect(hub.filled).toEqual(["guardian-real-id"]);
94
+ });
95
+
96
+ test("stops retrying once the connection no longer needs healing", async () => {
97
+ // Models a disconnect (or a reconnect that replaced this subscription)
98
+ // between attempts: the loop must not keep polling the gateway for a
99
+ // connection that is gone.
100
+ const hub = fakeHub();
101
+ let calls = 0;
102
+ startActorPrincipalHeal({
103
+ hub,
104
+ connectionId: "conn-1",
105
+ resolve: () => {
106
+ calls++;
107
+ hub.setNeeds(false);
108
+ return Promise.resolve(undefined);
109
+ },
110
+ delaysMs: NO_DELAYS,
111
+ });
112
+ await settle();
113
+
114
+ expect(calls).toBe(1);
115
+ expect(hub.filled).toEqual([]);
116
+ });
117
+
118
+ test("never starts a lookup when the connection is already healed or gone", async () => {
119
+ const hub = fakeHub({ needs: false });
120
+ const resolve = mock(() => Promise.resolve("guardian-real-id"));
121
+ startActorPrincipalHeal({
122
+ hub,
123
+ connectionId: "conn-1",
124
+ resolve,
125
+ delaysMs: NO_DELAYS,
126
+ });
127
+ await settle();
128
+
129
+ expect(resolve).toHaveBeenCalledTimes(0);
130
+ expect(hub.filled).toEqual([]);
131
+ });
132
+
133
+ test("gives up after the schedule is exhausted without filling", async () => {
134
+ const hub = fakeHub();
135
+ let calls = 0;
136
+ startActorPrincipalHeal({
137
+ hub,
138
+ connectionId: "conn-1",
139
+ resolve: () => {
140
+ calls++;
141
+ return Promise.resolve(undefined);
142
+ },
143
+ delaysMs: NO_DELAYS,
144
+ });
145
+ await settle();
146
+
147
+ expect(calls).toBe(NO_DELAYS.length);
148
+ expect(hub.filled).toEqual([]);
149
+ });
150
+
151
+ test("dispatches the first attempt synchronously", () => {
152
+ const hub = fakeHub();
153
+ const resolve = mock(() => Promise.resolve("guardian-real-id"));
154
+ startActorPrincipalHeal({
155
+ hub,
156
+ connectionId: "conn-1",
157
+ resolve,
158
+ delaysMs: NO_DELAYS,
159
+ });
160
+
161
+ // No await: the leading zero delay must not cost a macrotask, so a
162
+ // warm-cache heal lands before the stream delivers its first event.
163
+ expect(resolve).toHaveBeenCalledTimes(1);
164
+ });
165
+ });
@@ -59,6 +59,8 @@ let mockReResolve: { trustClass: string; sourceChannel: string } | null = null;
59
59
  mock.module("../../../contacts/guardian-delivery-reader.js", () => ({
60
60
  getGuardianDelivery: (_input?: { channelTypes?: string[] }) =>
61
61
  Promise.resolve(mockGuardianList),
62
+ getGuardianDeliveryFresh: (_input?: { channelTypes?: string[] }) =>
63
+ Promise.resolve(mockGuardianList),
62
64
  peekCachedGuardianDelivery: () => mockGuardianList ?? undefined,
63
65
  guardianForChannel: (
64
66
  list: Array<Record<string, unknown>>,
@@ -52,6 +52,7 @@ import {
52
52
  ServiceUnavailableError,
53
53
  } from "./errors.js";
54
54
  import { parseBody } from "./parse-body.js";
55
+ import { startActorPrincipalHeal } from "./sse-actor-principal-heal.js";
55
56
  import type { RouteDefinition, RouteHandlerArgs } from "./types.js";
56
57
 
57
58
  const log = getLogger("events-routes");
@@ -455,28 +456,28 @@ export function handleSubscribeAssistantEvents(
455
456
  throw err;
456
457
  }
457
458
 
458
- // Self-heal for dev-bypass connections: the sync resolution above reads
459
- // only the guardian-delivery cache, which can be cold at connect time.
460
- // Without this, the subscription would carry no principal for its whole
461
- // lifetime and every host-proxy result would 403. Fire-and-forget so the
462
- // stream is not delayed; keyed by connectionId so a reconnect race cannot
463
- // patch the subscription that replaced this one.
459
+ // Self-heal for dev-bypass connections: the sync resolution above reads only
460
+ // the guardian-delivery cache, which can be cold at connect time, and a
461
+ // subscription that carries no principal for its lifetime 403s every
462
+ // host-proxy result it submits. The heal retries on a bounded backoff
463
+ // (`sse-actor-principal-heal.ts`), fire-and-forget so the stream is not
464
+ // delayed, keyed by connectionId so a reconnect race cannot patch the
465
+ // subscription that replaced this one. The lookup forces a fresh gateway read
466
+ // because a cached empty result outlives the retry schedule.
464
467
  if (
465
468
  clientId &&
466
469
  interfaceId &&
467
470
  actorPrincipalId == null &&
468
471
  rawActorPrincipalId?.trim() === "dev-bypass"
469
472
  ) {
470
- void resolveActorPrincipalIdForLocalGuardian("dev-bypass")
471
- .then((resolved) => {
472
- if (resolved) {
473
- hub.fillClientActorPrincipalId(sub.connectionId, resolved);
474
- }
475
- })
476
- .catch(() => {
477
- // Best-effort: an unreachable gateway leaves the record unhealed;
478
- // the next reconnect retries.
479
- });
473
+ startActorPrincipalHeal({
474
+ hub,
475
+ connectionId: sub.connectionId,
476
+ resolve: () =>
477
+ resolveActorPrincipalIdForLocalGuardian("dev-bypass", {
478
+ forceRefresh: true,
479
+ }),
480
+ });
480
481
  }
481
482
 
482
483
  const stream = new ReadableStream<Uint8Array>(
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Retrying self-heal for an SSE client subscription that registered without an
3
+ * actor principal.
4
+ *
5
+ * In `DISABLE_HTTP_AUTH` deployments the SSE subscribe path cannot await, so it
6
+ * resolves the dev-bypass actor principal from an IO-free peek at the
7
+ * guardian-delivery cache. A cold cache registers the subscription with
8
+ * `actorPrincipalId: undefined`, and every host-proxy result that client
9
+ * submits then fails the same-actor gate with `missing_target`: a 403 that only
10
+ * a fresh registration clears.
11
+ *
12
+ * The heal resolves the guardian asynchronously and patches the live hub
13
+ * record. Each attempt can come back empty, since the lookup goes over the
14
+ * gateway IPC and yields nothing both when the transport fails (unreachable
15
+ * gateway, its 2s timeout, a pod still starting) and when no guardian binding
16
+ * exists yet, so attempts repeat on a bounded backoff. The loop stops on the
17
+ * first success, when the connection is gone or already carries a principal, or
18
+ * when the schedule is exhausted.
19
+ *
20
+ * Callers must pass a cache-bypassing lookup: the guardian-delivery reader
21
+ * caches a successful empty result for minutes, which outlives the whole
22
+ * schedule, so a cached read would spend every attempt on the same stale
23
+ * answer.
24
+ */
25
+ import { getLogger } from "../../util/logger.js";
26
+
27
+ const log = getLogger("sse-actor-heal");
28
+
29
+ /**
30
+ * The hub surface this module needs: a liveness check and the fill. Narrow by
31
+ * design so tests can drive the loop without a real hub.
32
+ */
33
+ export interface ActorPrincipalHealHub {
34
+ needsActorPrincipalHeal(connectionId: string): boolean;
35
+ fillClientActorPrincipalId(
36
+ connectionId: string,
37
+ actorPrincipalId: string,
38
+ ): void;
39
+ }
40
+
41
+ /**
42
+ * Delay before each attempt, in milliseconds. The leading zero dispatches the
43
+ * first attempt inline with the subscribe; the rest back off to cover a gateway
44
+ * that is slow to come up, without holding a timer for the life of a long-lived
45
+ * stream. Total span is about 44s.
46
+ */
47
+ export const ACTOR_PRINCIPAL_HEAL_DELAYS_MS: readonly number[] = [
48
+ 0, 1_000, 3_000, 10_000, 30_000,
49
+ ];
50
+
51
+ /**
52
+ * Start the retrying heal for `connectionId`. Fire-and-forget: never awaited by
53
+ * the route, never delays the stream.
54
+ *
55
+ * `resolve` performs the daemon's own server-side guardian lookup, bypassing
56
+ * the guardian-delivery cache. The value must never come from client input. It
57
+ * may resolve `undefined` (no binding yet, or the gateway is unreachable) or
58
+ * reject; both count as a failed attempt.
59
+ */
60
+ export function startActorPrincipalHeal(args: {
61
+ hub: ActorPrincipalHealHub;
62
+ connectionId: string;
63
+ resolve: () => Promise<string | undefined>;
64
+ /** Override the backoff schedule. Tests pass all-zero delays. */
65
+ delaysMs?: readonly number[];
66
+ }): void {
67
+ const { hub, connectionId, resolve } = args;
68
+ const delays = args.delaysMs ?? ACTOR_PRINCIPAL_HEAL_DELAYS_MS;
69
+
70
+ void (async () => {
71
+ for (let attempt = 0; attempt < delays.length; attempt++) {
72
+ const delayMs = delays[attempt] ?? 0;
73
+ if (delayMs > 0) {
74
+ await sleep(delayMs);
75
+ }
76
+
77
+ // Re-check every pass: the connection may have closed, been replaced by a
78
+ // reconnect, or been healed by another path since the last one.
79
+ if (!hub.needsActorPrincipalHeal(connectionId)) {
80
+ return;
81
+ }
82
+
83
+ let resolved: string | undefined;
84
+ try {
85
+ resolved = await resolve();
86
+ } catch {
87
+ resolved = undefined;
88
+ }
89
+ if (resolved) {
90
+ hub.fillClientActorPrincipalId(connectionId, resolved);
91
+ return;
92
+ }
93
+ }
94
+
95
+ // Log the give-up so a principal-less subscription is greppable next to the
96
+ // same-actor rejections it causes, rather than surfacing only as opaque
97
+ // 403s on the client.
98
+ if (hub.needsActorPrincipalHeal(connectionId)) {
99
+ log.warn(
100
+ { connectionId, attempts: delays.length },
101
+ "gave up healing missing actorPrincipalId for client subscription; host-proxy results from this connection are rejected until it reconnects",
102
+ );
103
+ }
104
+ })();
105
+ }
106
+
107
+ function sleep(ms: number): Promise<void> {
108
+ return new Promise((resolve) => {
109
+ const timer = setTimeout(resolve, ms);
110
+ // Never hold the process (or a test runner) open on a pending backoff.
111
+ (timer as { unref?: () => void }).unref?.();
112
+ });
113
+ }
@@ -483,12 +483,13 @@ export const SUBAGENT_ROLE_REGISTRY: Record<SubagentRole, SubagentRoleConfig> =
483
483
  skillIds: [],
484
484
  systemPromptPreamble: [
485
485
  "You are a research subagent with read-only access: search the web, read and search files, and recall memories. There is no shell, and you cannot write or edit files.",
486
- // `file_read` takes no default line limit and its results are exempt
487
- // from result-time spooling, so a full body rides every LLM call until
488
- // the turn ends. Telling the role to read whole files makes that the
489
- // default shape of a research turn, and this role now covers the
490
- // traffic three roles used to. The anti-slicing intent stays: one pass
491
- // over the range that is needed rather than many small ones.
486
+ // `file_read` returns the first DEFAULT_READ_LINE_LIMIT (2000) lines
487
+ // unless a limit is passed, with a truncation notice naming the resume
488
+ // offset, and oversized results spool to .tool-results/ like any other
489
+ // tool's (only re-reads of spooled content stay inline). So a ranged
490
+ // read is both the cheap shape and the one that avoids a spool
491
+ // round-trip. The anti-slicing intent stays: one pass over the range
492
+ // that is needed rather than many small ones.
492
493
  "Working method: use code_search to search file contents across directories, file_list to enumerate paths, and file_read to read files and logs. Prefer broad code_search queries across a directory over one-symbol-at-a-time queries, and read the range you need in one pass rather than many small slices.",
493
494
  "Send notify_parent (urgency 'important') as soon as each finding is confirmed, so progress survives interruption.",
494
495
  "Your final message is the deliverable: a compact report that answers the objective, gives the evidence behind each claim (file:line references, URLs, or quotes), and names what you could not determine. For a root-cause investigation, use the sections Symptom, Root cause, Evidence, Suggested fix, Open questions.",
@@ -6,11 +6,18 @@ const TIMEOUT_SENTINEL = Symbol("tool-timeout");
6
6
  /**
7
7
  * Convert a config-provided seconds value to a safe milliseconds value,
8
8
  * falling back to the default if the input is NaN, non-finite, zero, or negative.
9
+ *
10
+ * `fallbackMs` lets callers governed by a different budget (e.g. the inline
11
+ * grant wait) keep their own floor instead of inheriting the tool-execution
12
+ * default.
9
13
  */
10
- export function safeTimeoutMs(sec: unknown): number {
14
+ export function safeTimeoutMs(
15
+ sec: unknown,
16
+ fallbackMs: number = DEFAULT_TOOL_EXECUTION_TIMEOUT_SEC * 1000,
17
+ ): number {
11
18
  const n = Number(sec);
12
19
  if (!Number.isFinite(n) || n <= 0) {
13
- return DEFAULT_TOOL_EXECUTION_TIMEOUT_SEC * 1000;
20
+ return fallbackMs;
14
21
  }
15
22
  return n * 1000;
16
23
  }
@@ -39,6 +39,7 @@ import { computeToolApprovalDigest } from "../security/tool-approval-digest.js";
39
39
  import { recordToolDenied, recordToolError } from "../telemetry/tool-audit.js";
40
40
  import { getLogger } from "../util/logger.js";
41
41
  import { resolveExecutionTarget } from "./execution-target.js";
42
+ import { safeTimeoutMs } from "./execution-timeout.js";
42
43
  import { channelCoordinatesFromToolContext } from "./policy-context.js";
43
44
  import { getAllTools, getTool, getToolOwner } from "./registry.js";
44
45
  import { isSideEffectTool } from "./side-effects.js";
@@ -127,9 +128,39 @@ export function buildInactiveToolMessage(args: {
127
128
 
128
129
  /** Default polling interval for inline grant wait (ms). */
129
130
  const TC_GRANT_WAIT_INTERVAL_MS = 500;
130
- /** Default maximum wait time for inline grant wait (ms). */
131
+ /**
132
+ * Fallback maximum wait for the inline grant wait (ms), used only when the
133
+ * deployed config cannot be read. The governing budget is
134
+ * `timeouts.permissionTimeoutSec` (see {@link resolveInlineGrantWaitMs}).
135
+ */
131
136
  export const TC_GRANT_WAIT_MAX_MS = 60_000;
132
137
 
138
+ /**
139
+ * Resolve the wait budget for an escalated tool grant.
140
+ *
141
+ * A guardian answering an escalated tool call is making the same decision as a
142
+ * local user answering a permission prompt, so both paths spend the same
143
+ * budget: `timeouts.permissionTimeoutSec` (read by `permissions/prompter.ts`).
144
+ * If anything, this path needs the larger share of it: the prompter's user
145
+ * already has the prompt on screen, while the guardian is notified
146
+ * out-of-band and has to context-switch before deciding.
147
+ *
148
+ * Falls back to {@link TC_GRANT_WAIT_MAX_MS} rather than the tool-execution
149
+ * default on a non-positive value, so a bad config can never collapse the
150
+ * window to zero and auto-deny every escalation.
151
+ *
152
+ * Exported because the grant resolver sizes its `inline_wait_active` staleness
153
+ * threshold off this same budget: if the two drift, an approval arriving while
154
+ * a waiter is still live gets misread as a dead waiter and the requester is
155
+ * told to retry a call that is about to resume on its own.
156
+ */
157
+ export function resolveInlineGrantWaitMs(): number {
158
+ return safeTimeoutMs(
159
+ getConfig().timeouts.permissionTimeoutSec,
160
+ TC_GRANT_WAIT_MAX_MS,
161
+ );
162
+ }
163
+
133
164
  /**
134
165
  * Inline wait result for trusted-contact grant polling.
135
166
  * - `granted`: a grant was minted and consumed within the wait window.
@@ -152,13 +183,16 @@ export type InlineGrantWaitOutcome =
152
183
  * and atomically consume the grant).
153
184
  *
154
185
  * Only called for trusted_contact actors with valid guardian bindings.
186
+ *
187
+ * `options.maxWaitMs` overrides the wait budget; omitting it spends the
188
+ * configured one from {@link resolveInlineGrantWaitMs}.
155
189
  */
156
190
  export async function waitForInlineGrant(
157
191
  escalationRequestId: string,
158
192
  consumeParams: Parameters<typeof consumeGrantForInvocation>[0],
159
193
  options?: { maxWaitMs?: number; intervalMs?: number; signal?: AbortSignal },
160
194
  ): Promise<InlineGrantWaitOutcome> {
161
- const maxWait = options?.maxWaitMs ?? TC_GRANT_WAIT_MAX_MS;
195
+ const maxWait = options?.maxWaitMs ?? resolveInlineGrantWaitMs();
162
196
  const interval = options?.intervalMs ?? TC_GRANT_WAIT_INTERVAL_MS;
163
197
  const signal = options?.signal;
164
198
  const deadline = Date.now() + maxWait;
@@ -592,9 +626,16 @@ export type PreExecutionGateResult =
592
626
  }
593
627
  | { allowed: false; result: ToolExecutionResult };
594
628
 
595
- /** Configuration for the inline grant wait behavior. */
629
+ /**
630
+ * Overrides for the inline grant wait behavior. Production leaves this empty
631
+ * so the wait spends the configured budget; tests inject short waits to keep
632
+ * escalation cases fast.
633
+ */
596
634
  export interface InlineGrantWaitConfig {
597
- /** Maximum time to wait for guardian approval (ms). Defaults to TC_GRANT_WAIT_MAX_MS. */
635
+ /**
636
+ * Maximum time to wait for guardian approval (ms). Defaults to the budget
637
+ * from {@link resolveInlineGrantWaitMs}.
638
+ */
598
639
  maxWaitMs?: number;
599
640
  /** Polling interval during the wait (ms). Defaults to TC_GRANT_WAIT_INTERVAL_MS. */
600
641
  intervalMs?: number;