@vellumai/assistant 0.10.3-dev.202606292252.adea010 → 0.10.3-dev.202606292327.80883ab

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.10.3-dev.202606292252.adea010",
3
+ "version": "0.10.3-dev.202606292327.80883ab",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -130,6 +130,8 @@ const BASELINE: Record<string, readonly string[]> = {
130
130
  "../../../daemon/pkb-context-tracker.js",
131
131
  "../../../daemon/pkb-reminder-builder.js",
132
132
  "../../../daemon/trust-context.js",
133
+ "../../../memory/context-search/agent-runner.js",
134
+ "../../../memory/context-search/types.js",
133
135
  "../../../memory/graph/bootstrap.js",
134
136
  "../../../memory/graph/consolidation.js",
135
137
  "../../../memory/graph/conversation-graph-memory.js",
@@ -138,6 +140,8 @@ const BASELINE: Record<string, readonly string[]> = {
138
140
  "../../../memory/graph/graph-search.js",
139
141
  "../../../memory/graph/narrative.js",
140
142
  "../../../memory/graph/pattern-scan.js",
143
+ "../../../memory/graph/tool-handlers.js",
144
+ "../../../memory/graph/tools.js",
141
145
  "../../../memory/job-handlers/backfill.js",
142
146
  "../../../memory/job-handlers/embedding.js",
143
147
  "../../../memory/job-handlers/index-maintenance.js",
@@ -152,7 +156,10 @@ const BASELINE: Record<string, readonly string[]> = {
152
156
  "../../../memory/v2/consolidation-job.js",
153
157
  "../../../memory/v2/static-context.js",
154
158
  "../../../memory/v2/sweep-job.js",
159
+ "../../../permissions/types.js",
155
160
  "../../../persistence/jobs-store.js",
161
+ "../../../runtime/capabilities.js",
162
+ "../../../tools/types.js",
156
163
  "../../../types.js",
157
164
  "../../../util/logger.js",
158
165
  "../../../util/platform.js",
@@ -0,0 +1,33 @@
1
+ /**
2
+ * `injectLocalActorHeader` resolves the IPC caller's principal type. Routes
3
+ * that elevate trust gate on `"local"`, so a gateway-proxied remote request
4
+ * must never resolve to `local` — even when it arrives with no verified
5
+ * principal header (e.g. `runtimeProxyRequireAuth` disabled). The
6
+ * `x-vellum-proxy-server: ipc` marker (forwarded by the gateway, never sent by
7
+ * a direct CLI) distinguishes the two.
8
+ */
9
+
10
+ import { describe, expect, test } from "bun:test";
11
+
12
+ import { injectLocalActorHeader } from "../assistant-server.js";
13
+
14
+ describe("injectLocalActorHeader principal resolution", () => {
15
+ test("a forwarded verified principal wins", () => {
16
+ const out = injectLocalActorHeader({
17
+ headers: { "x-vellum-principal-type": "actor" },
18
+ });
19
+ expect(out.headers?.["x-vellum-principal-type"]).toBe("actor");
20
+ });
21
+
22
+ test("gateway-proxied IPC with no principal resolves to svc_gateway, not local", () => {
23
+ const out = injectLocalActorHeader({
24
+ headers: { "x-vellum-proxy-server": "ipc" },
25
+ });
26
+ expect(out.headers?.["x-vellum-principal-type"]).toBe("svc_gateway");
27
+ });
28
+
29
+ test("a direct IPC caller (no proxy marker, no principal) defaults to local", () => {
30
+ const out = injectLocalActorHeader({ headers: {} });
31
+ expect(out.headers?.["x-vellum-principal-type"]).toBe("local");
32
+ });
33
+ });
@@ -33,6 +33,7 @@ import { createServer, type Server, type Socket } from "node:net";
33
33
 
34
34
  import { ensureSocketDir, SocketWatchdog } from "@vellumai/ipc-server-utils";
35
35
 
36
+ import type { PrincipalType } from "../runtime/auth/types.js";
36
37
  import { findLocalGuardianPrincipalIdFromStore } from "../runtime/local-actor-identity.js";
37
38
  import { RouteError } from "../runtime/routes/errors.js";
38
39
  import { ROUTES } from "../runtime/routes/index.js";
@@ -608,52 +609,50 @@ export class AssistantIpcServer {
608
609
  // ---------------------------------------------------------------------------
609
610
 
610
611
  /**
611
- * Inject a synthetic `x-vellum-actor-principal-id` header from the local
612
- * guardian principal when the caller hasn't already provided one.
612
+ * Resolve an IPC caller's identity headers, mirroring what the HTTP adapter
613
+ * derives from the verified `AuthContext`: `x-vellum-principal-type` and a
614
+ * synthetic `x-vellum-actor-principal-id` for the local guardian. Handlers read
615
+ * the resolved identity from `headers` (the single source of truth across both
616
+ * transports); they never trust the request body.
613
617
  *
614
- * Local IPC is intra-process and owned by the same user as the daemon, so
615
- * routes that consume `headers["x-vellum-actor-principal-id"]` (e.g. the
616
- * same-user filter on `GET /v1/clients`) need an actor identity to function
617
- * over IPC. The HTTP adapter does this from the verified `AuthContext`
618
- * (`http-adapter.ts`); this helper mirrors that convention for IPC.
619
- *
620
- * Existing headers from the caller (e.g. the gateway's IPC runtime proxy,
621
- * which forwards real `x-vellum-*` headers from the authenticated HTTP
622
- * request) are preserved — we only fill in the gap for direct CLI/local
623
- * IPC callers.
618
+ * Principal type comes from the gateway-forwarded `x-vellum-principal-type`,
619
+ * else `svc_gateway` for a gateway-proxied request (marked by
620
+ * `x-vellum-proxy-server: ipc`, which a direct CLI never sends), else `local`.
621
+ * Routes that elevate trust gate on `local`, so a remote caller arriving with
622
+ * no verified principal must resolve to `svc_gateway`, never `local`.
624
623
  */
625
- function injectLocalActorHeader(
624
+ export function injectLocalActorHeader(
626
625
  params: Record<string, unknown> | undefined,
627
626
  ): RouteHandlerArgs {
628
627
  const args = (params ?? {}) as RouteHandlerArgs;
629
628
  const existingHeaders = args.headers;
630
- if (existingHeaders?.["x-vellum-actor-principal-id"]) {
631
- return args;
632
- }
629
+ const forwardedPrincipal = existingHeaders?.["x-vellum-principal-type"] as
630
+ | PrincipalType
631
+ | undefined;
632
+ const isGatewayProxied = existingHeaders?.["x-vellum-proxy-server"] === "ipc";
633
+ const headers: Record<string, string> = {
634
+ ...existingHeaders,
635
+ "x-vellum-principal-type":
636
+ forwardedPrincipal ?? (isGatewayProxied ? "svc_gateway" : "local"),
637
+ };
633
638
 
634
- // Defensive: the guardian lookup queries the contacts table, which may
635
- // not yet exist on a very early boot path or in test fixtures that don't
636
- // initialize the DB. A failure here must not block IPC dispatch — routes
637
- // that require the header will fail-closed on their own.
638
- let localActor: string | undefined;
639
- try {
640
- localActor = findLocalGuardianPrincipalIdFromStore();
641
- } catch (err) {
642
- log.debug(
643
- { err },
644
- "failed to resolve local actor principal for IPC header injection",
645
- );
646
- return args;
639
+ // Fill the local guardian's actor id for direct callers that lack one.
640
+ // Defensive: the lookup queries the contacts table, which may not exist on a
641
+ // very early boot path or in test fixtures without a DB — a failure must not
642
+ // block dispatch, so routes requiring the header fail-closed on their own.
643
+ if (!headers["x-vellum-actor-principal-id"]) {
644
+ try {
645
+ const localActor = findLocalGuardianPrincipalIdFromStore();
646
+ if (localActor) headers["x-vellum-actor-principal-id"] = localActor;
647
+ } catch (err) {
648
+ log.debug(
649
+ { err },
650
+ "failed to resolve local actor principal for IPC header injection",
651
+ );
652
+ }
647
653
  }
648
- if (!localActor) return args;
649
-
650
- return {
651
- ...args,
652
- headers: {
653
- ...existingHeaders,
654
- "x-vellum-actor-principal-id": localActor,
655
- },
656
- };
654
+
655
+ return { ...args, headers };
657
656
  }
658
657
 
659
658
  // ── Process-level singleton ───────────────────────────────────────────────
@@ -11,13 +11,13 @@ import {
11
11
  test,
12
12
  } from "bun:test";
13
13
 
14
- import { PKB_WORKSPACE_SCOPE } from "../../memory/pkb/types.js";
15
- import type { ToolContext } from "../types.js";
14
+ import { PKB_WORKSPACE_SCOPE } from "../../../memory/pkb/types.js";
15
+ import type { ToolContext } from "../../../tools/types.js";
16
16
 
17
17
  // This test exercises v1 PKB re-index enqueue. `config.memory.v2.enabled`
18
18
  // (default `true`) makes the enqueue path skipped — force it off so the
19
19
  // v1 PKB index path stays under test.
20
- mock.module("../../config/loader.js", () => ({
20
+ mock.module("../../../config/loader.js", () => ({
21
21
  getConfig: () => ({ memory: { v2: { enabled: false } } }),
22
22
  loadConfig: () => ({ memory: { v2: { enabled: false } } }),
23
23
  }));
@@ -41,7 +41,7 @@ const recallCalls: Array<{
41
41
  }> = [];
42
42
  let recallContent = "agentic recall answer";
43
43
 
44
- mock.module("../../memory/jobs/embed-pkb-file.js", () => ({
44
+ mock.module("../../../memory/jobs/embed-pkb-file.js", () => ({
45
45
  enqueuePkbIndexJob: (input: {
46
46
  pkbRoot: string;
47
47
  absPath: string;
@@ -55,7 +55,7 @@ mock.module("../../memory/jobs/embed-pkb-file.js", () => ({
55
55
  },
56
56
  }));
57
57
 
58
- mock.module("../../memory/context-search/agent-runner.js", () => ({
58
+ mock.module("../../../memory/context-search/agent-runner.js", () => ({
59
59
  runAgenticRecall: async (
60
60
  input: Record<string, unknown>,
61
61
  context: Record<string, unknown>,
@@ -86,8 +86,8 @@ afterAll(() => {
86
86
  });
87
87
 
88
88
  // Import after the env var is set so getWorkspaceDir() resolves to the tmpdir.
89
- const { recallTool, rememberTool } = await import("./register.js");
90
- const { getConfig } = await import("../../config/loader.js");
89
+ const { recallTool, rememberTool } = await import("./tools.js");
90
+ const { getConfig } = await import("../../../config/loader.js");
91
91
 
92
92
  function makeContext(overrides: Partial<ToolContext> = {}): ToolContext {
93
93
  return {
@@ -1,21 +1,30 @@
1
- import { getConfig } from "../../config/loader.js";
2
- import { runAgenticRecall } from "../../memory/context-search/agent-runner.js";
3
- import type { RecallInput } from "../../memory/context-search/types.js";
1
+ /**
2
+ * The memory feature's model-visible tools: `remember` and `recall`.
3
+ *
4
+ * Core, always-loaded tools registered via the host tool manifest
5
+ * (`tools/tool-manifest.ts`), so they carry core/workspace-override precedence
6
+ * and the `"memory"` tool category. Their implementations source from the
7
+ * memory feature (`src/memory/*`).
8
+ */
9
+
10
+ import { getConfig } from "../../../config/loader.js";
11
+ import { runAgenticRecall } from "../../../memory/context-search/agent-runner.js";
12
+ import type { RecallInput } from "../../../memory/context-search/types.js";
4
13
  import {
5
14
  handleRemember,
6
15
  type RememberInput,
7
- } from "../../memory/graph/tool-handlers.js";
16
+ } from "../../../memory/graph/tool-handlers.js";
8
17
  import {
9
18
  graphRecallDefinition,
10
19
  graphRememberDefinition,
11
- } from "../../memory/graph/tools.js";
12
- import { RiskLevel } from "../../permissions/types.js";
13
- import { resolveCapabilities } from "../../runtime/capabilities.js";
20
+ } from "../../../memory/graph/tools.js";
21
+ import { RiskLevel } from "../../../permissions/types.js";
22
+ import { resolveCapabilities } from "../../../runtime/capabilities.js";
14
23
  import type {
15
24
  ToolContext,
16
25
  ToolDefinition,
17
26
  ToolExecutionResult,
18
- } from "../types.js";
27
+ } from "../../../tools/types.js";
19
28
 
20
29
  // ── remember ────────────────────────────────────────────────────────
21
30
 
@@ -6,9 +6,9 @@
6
6
  * yields a live `Conversation`. These tests build a lightweight structural
7
7
  * double typed as `Conversation` (`makeWakeConversation`) that stubs only the
8
8
  * handful of members the wake touches — `getMessages`, `messages.push`,
9
- * `isProcessing`/`setProcessing`, `setTrustContext`, `setSubagentAllowedTools`,
10
- * `drainQueue`, `maybeCompact`, `contextWindowManager.estimateInputTokens`,
11
- * and a scripted `agentLoop.run()`.
9
+ * `isProcessing`/`setProcessing`, `currentTurnTrustContext`,
10
+ * `setSubagentAllowedTools`, `drainQueue`, `maybeCompact`,
11
+ * `contextWindowManager.estimateInputTokens`, and a scripted `agentLoop.run()`.
12
12
  *
13
13
  * The wake's side effects flow through the daemon boundary, so the
14
14
  * instrumentation is captured at that boundary: event emission and the
@@ -81,8 +81,12 @@ interface WakeConversationProbe {
81
81
  * scope. `undefined` means unrestricted.
82
82
  */
83
83
  allowedToolSnapshots: Array<string[] | undefined>;
84
- /** `setTrustContext` calls, with the value and a monotonic order tag. */
85
- setTrustContextCalls: Array<{ ctx: unknown; order: number }>;
84
+ /**
85
+ * Assignments to `conversation.currentTurnTrustContext`, with the value and
86
+ * a monotonic order tag. The wake elevates the turn's trust here (not via the
87
+ * persistent `setTrustContext`) and restores the prior value in its finally.
88
+ */
89
+ turnTrustContextSets: Array<{ ctx: unknown; order: number }>;
86
90
  /**
87
91
  * Every assignment to `conversation.wakePersonaOverride`, in order. A
88
92
  * wake that applies an override records `[override, undefined]` — the
@@ -392,7 +396,7 @@ function makeWakeConversation(options: {
392
396
  callSequence: [],
393
397
  processingDuringDrain: [],
394
398
  allowedToolSnapshots: [],
395
- setTrustContextCalls: [],
399
+ turnTrustContextSets: [],
396
400
  personaOverrideSets: [],
397
401
  persistedAtEachEmit: [],
398
402
  maybeCompactOrders: [],
@@ -404,6 +408,7 @@ function makeWakeConversation(options: {
404
408
  let order = 0;
405
409
  let activeAllowedTools = options.initialAllowedTools;
406
410
  let wakePersonaOverride: unknown;
411
+ let currentTurnTrustContext: unknown;
407
412
  const snapshotAllowedTools = (): string[] | undefined =>
408
413
  activeAllowedTools ? [...activeAllowedTools].sort() : undefined;
409
414
 
@@ -495,8 +500,12 @@ function makeWakeConversation(options: {
495
500
  probe.processingToggles.push(on);
496
501
  probe.callSequence.push(on ? "processing:true" : "processing:false");
497
502
  },
498
- setTrustContext: (ctx: unknown) => {
499
- probe.setTrustContextCalls.push({ ctx, order: order++ });
503
+ get currentTurnTrustContext() {
504
+ return currentTurnTrustContext;
505
+ },
506
+ set currentTurnTrustContext(value: unknown) {
507
+ currentTurnTrustContext = value;
508
+ probe.turnTrustContextSets.push({ ctx: value, order: order++ });
500
509
  },
501
510
  // Pre-run auto-compaction gate. The double only records the call (and
502
511
  // the sizing argument) — compaction side effects are exercised in the
@@ -715,6 +724,57 @@ describe("wakeAgentForOpportunity", () => {
715
724
  expect(conversation.personaOverrideSets).toEqual([override, undefined]);
716
725
  });
717
726
 
727
+ test("trustContext elevation is applied for the run and restored after", async () => {
728
+ const conversation = makeWakeConversation({
729
+ scriptedAssistant: {
730
+ role: "assistant",
731
+ content: [{ type: "text", text: "reviewed." }],
732
+ },
733
+ });
734
+
735
+ const result = await wakeAgentForOpportunity(
736
+ {
737
+ conversationId: conversation.conversationId,
738
+ hint: "scheduled triage",
739
+ source: "schedule",
740
+ trustContext: { sourceChannel: "vellum", trustClass: "guardian" },
741
+ },
742
+ { resolveTarget: async () => conversation },
743
+ );
744
+
745
+ expect(result.invoked).toBe(true);
746
+ const ctxs = conversation.turnTrustContextSets.map((c) => c.ctx);
747
+ // Elevated for the turn …
748
+ expect(ctxs).toContainEqual({
749
+ sourceChannel: "vellum",
750
+ trustClass: "guardian",
751
+ });
752
+ // … then restored to the prior value (unset → undefined) as the LAST write,
753
+ // so a later wake reusing this cached conversation can't inherit guardian.
754
+ expect(ctxs[ctxs.length - 1]).toBeUndefined();
755
+ });
756
+
757
+ test("trustContext elevation is restored even when the agent loop throws", async () => {
758
+ const conversation = makeWakeConversation({
759
+ runImpl: async () => {
760
+ throw new Error("loop exploded");
761
+ },
762
+ });
763
+
764
+ await wakeAgentForOpportunity(
765
+ {
766
+ conversationId: conversation.conversationId,
767
+ hint: "scheduled triage",
768
+ source: "schedule",
769
+ trustContext: { sourceChannel: "vellum", trustClass: "guardian" },
770
+ },
771
+ { resolveTarget: async () => conversation },
772
+ );
773
+
774
+ const ctxs = conversation.turnTrustContextSets.map((c) => c.ctx);
775
+ expect(ctxs[ctxs.length - 1]).toBeUndefined();
776
+ });
777
+
718
778
  test("personaOverride is cleared even when the agent loop throws", async () => {
719
779
  const conversation = makeWakeConversation({
720
780
  runImpl: async () => {
@@ -1413,11 +1473,11 @@ describe("wakeAgentForOpportunity", () => {
1413
1473
  expect(conversation.isProcessing()).toBe(false);
1414
1474
  });
1415
1475
 
1416
- test("applies caller-supplied trustContext to the target before the agent loop runs", async () => {
1417
- // Background system jobs (e.g. memory consolidation) need
1418
- // guardian trust to clear the side-effect approval gate. The wake must
1419
- // call setTrustContext BEFORE agentLoop.run so the per-turn snapshot
1420
- // captures the elevated trust.
1476
+ test("elevates the turn's trust context before the agent loop runs", async () => {
1477
+ // Background system jobs (e.g. memory consolidation) need guardian trust to
1478
+ // clear the side-effect approval gate. The wake must set
1479
+ // `currentTurnTrustContext` BEFORE agentLoop.run so the per-turn approval
1480
+ // check sees the elevated trust.
1421
1481
  const conversation = makeWakeConversation({
1422
1482
  conversationId: "conv-trust",
1423
1483
  });
@@ -1432,19 +1492,22 @@ describe("wakeAgentForOpportunity", () => {
1432
1492
  { resolveTarget: async () => conversation },
1433
1493
  );
1434
1494
 
1435
- expect(conversation.setTrustContextCalls).toHaveLength(1);
1436
- expect(conversation.setTrustContextCalls[0]!.ctx).toEqual({
1495
+ // Two writes: the elevation (before the run) and the turn-scoped restore
1496
+ // (after), so the guardian trust never lingers on the cached conversation.
1497
+ expect(conversation.turnTrustContextSets).toHaveLength(2);
1498
+ expect(conversation.turnTrustContextSets[0]!.ctx).toEqual({
1437
1499
  sourceChannel: "vellum",
1438
1500
  trustClass: "guardian",
1439
1501
  });
1440
- // setTrustContext fired strictly before agentLoop.run.
1502
+ expect(conversation.turnTrustContextSets[1]!.ctx).toBeUndefined();
1503
+ // The elevation fired strictly before agentLoop.run.
1441
1504
  expect(conversation.runCalls).toHaveLength(1);
1442
- expect(conversation.setTrustContextCalls[0]!.order).toBeLessThan(
1505
+ expect(conversation.turnTrustContextSets[0]!.order).toBeLessThan(
1443
1506
  conversation.runCalls[0]!.order,
1444
1507
  );
1445
1508
  });
1446
1509
 
1447
- test("does not call setTrustContext when no trustContext is supplied", async () => {
1510
+ test("does not elevate the turn's trust when no trustContext is supplied", async () => {
1448
1511
  const conversation = makeWakeConversation({
1449
1512
  conversationId: "conv-no-trust",
1450
1513
  });
@@ -1459,9 +1522,13 @@ describe("wakeAgentForOpportunity", () => {
1459
1522
  );
1460
1523
 
1461
1524
  // Inbound-message conversations populate trust via processMessage().
1462
- // Without an explicit opt-in from the caller, the wake must not
1463
- // overwrite whatever the conversation already holds.
1464
- expect(conversation.setTrustContextCalls).toHaveLength(0);
1525
+ // Without an explicit opt-in from the caller, the wake never elevates the
1526
+ // turn's trust — it only ever restores the prior value (here, unset), so it
1527
+ // can't overwrite whatever the conversation already holds.
1528
+ expect(
1529
+ conversation.turnTrustContextSets.filter((s) => s.ctx != null),
1530
+ ).toHaveLength(0);
1531
+ expect(conversation.currentTurnTrustContext).toBeUndefined();
1465
1532
  });
1466
1533
 
1467
1534
  test("two concurrent wakes on the same conversation are serialized", async () => {
@@ -325,6 +325,17 @@ export interface WakeOptions {
325
325
  * woken turn's cost is attributed to that firing.
326
326
  */
327
327
  cronRunId?: string;
328
+ /**
329
+ * Run the woken turn clientless: pin `hasNoClient = true` for the duration of
330
+ * the agent-loop run (restored after). Wakes bypass the orchestrator's
331
+ * turn-start interactivity setup, so a wake on a conversation with no client
332
+ * attached otherwise derives `isInteractive: true` (the default
333
+ * `hasNoClient = false`). Pinning it makes `conversation-tool-setup` derive
334
+ * `isInteractive: false`, which `policy-context` maps to `background`
335
+ * (guardian) / `headless` (unknown) — so a side-effecting tool that would
336
+ * prompt is denied instead of stalling on a client that isn't there.
337
+ */
338
+ clientless?: boolean;
328
339
  }
329
340
 
330
341
  /**
@@ -651,12 +662,8 @@ export async function wakeAgentForOpportunity(
651
662
  return { invoked: false, producedToolCalls: false, reason: "timeout" };
652
663
  }
653
664
 
654
- // Apply caller-supplied trust before the agent loop reads its per-turn
655
- // snapshot. Background jobs without an inbound message use this to
656
- // declare guardian trust so side-effect tools clear the approval gate.
657
- if (opts.trustContext) {
658
- conversation.setTrustContext(opts.trustContext);
659
- }
665
+ // Trust elevation is applied per-turn via `currentTurnTrustContext` right
666
+ // before the run (see below) — not on the persistent conversation trust.
660
667
 
661
668
  // Honor the conversation's pinned inference-profile override (if any).
662
669
  // Without this, scheduled-task wakes and other opportunity wakes bypass
@@ -1236,8 +1243,16 @@ export async function wakeAgentForOpportunity(
1236
1243
  // user turn or a later background read never inherits the wake's stamps.
1237
1244
  const priorCallSite = conversation.currentCallSite;
1238
1245
  const priorTurnOverrideProfile = conversation.currentTurnOverrideProfile;
1246
+ const priorHasNoClient = conversation.hasNoClient;
1247
+ const priorTurnTrust = conversation.currentTurnTrustContext;
1239
1248
  conversation.currentCallSite = callSite;
1240
1249
  conversation.currentTurnOverrideProfile = overrideProfile;
1250
+ if (opts.clientless) conversation.hasNoClient = true;
1251
+ // Per-turn guardian elevation for the wake's tools, set after the pre-run
1252
+ // reads so a pre-run failure can't leak it; restored in the finally.
1253
+ if (opts.trustContext) {
1254
+ conversation.currentTurnTrustContext = opts.trustContext;
1255
+ }
1241
1256
 
1242
1257
  let updatedHistory: Message[];
1243
1258
  try {
@@ -1298,6 +1313,8 @@ export async function wakeAgentForOpportunity(
1298
1313
  // at the start of the next normal turn regardless.)
1299
1314
  conversation.currentCallSite = priorCallSite;
1300
1315
  conversation.currentTurnOverrideProfile = priorTurnOverrideProfile;
1316
+ conversation.hasNoClient = priorHasNoClient;
1317
+ conversation.currentTurnTrustContext = priorTurnTrust;
1301
1318
  }
1302
1319
 
1303
1320
  // The loop swallows provider rejections into a graceful no-output
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Asserts the `wake_conversation` route elevates trust from the caller's
3
+ * verified principal type, never the request body: a `local` (CLI/IPC) caller
4
+ * runs the woken turn as a non-interactive guardian (clientless + guardian
5
+ * trustContext) and may attribute cost to a body-supplied `cronRunId`; a remote
6
+ * `actor` stays `unknown`/interactive and its body `cronRunId` is ignored.
7
+ */
8
+
9
+ import { describe, expect, mock, test } from "bun:test";
10
+
11
+ mock.module("../../../util/logger.js", () => ({
12
+ getLogger: () =>
13
+ new Proxy({} as Record<string, unknown>, {
14
+ get: () => () => {},
15
+ }),
16
+ }));
17
+
18
+ interface CapturedWake {
19
+ conversationId: string;
20
+ hint: string;
21
+ trustContext?: { sourceChannel: string; trustClass: string };
22
+ cronRunId?: string;
23
+ clientless?: boolean;
24
+ }
25
+ const wakeCalls: CapturedWake[] = [];
26
+ mock.module("../../agent-wake.js", () => ({
27
+ wakeAgentForOpportunity: (opts: CapturedWake) => {
28
+ wakeCalls.push(opts);
29
+ return { invoked: true, producedToolCalls: false };
30
+ },
31
+ }));
32
+
33
+ import { createConversation } from "../../../persistence/conversation-crud.js";
34
+ import { initializeDb } from "../../../persistence/db-init.js";
35
+ import { ROUTES } from "../wake-conversation-routes.js";
36
+
37
+ await initializeDb();
38
+
39
+ const handler = (() => {
40
+ const route = ROUTES.find((r) => r.operationId === "wake_conversation");
41
+ if (!route) throw new Error("wake_conversation route not found");
42
+ return route.handler;
43
+ })();
44
+
45
+ function makeConversation(): string {
46
+ return createConversation({ conversationType: "scheduled" }).id;
47
+ }
48
+
49
+ describe("wake_conversation principal-gated elevation", () => {
50
+ test("local principal → non-interactive guardian, honors body cronRunId", async () => {
51
+ wakeCalls.length = 0;
52
+ const conversationId = makeConversation();
53
+ const result = await handler({
54
+ body: { conversationId, hint: "poll result", cronRunId: "run-1" },
55
+ headers: { "x-vellum-principal-type": "local" },
56
+ });
57
+ expect(result).toEqual({ invoked: true, producedToolCalls: false });
58
+ expect(wakeCalls).toHaveLength(1);
59
+ expect(wakeCalls[0].trustContext).toEqual({
60
+ sourceChannel: "vellum",
61
+ trustClass: "guardian",
62
+ });
63
+ expect(wakeCalls[0].clientless).toBe(true);
64
+ expect(wakeCalls[0].cronRunId).toBe("run-1");
65
+ });
66
+
67
+ test("actor principal → interactive, no elevation, ignores body cronRunId", async () => {
68
+ wakeCalls.length = 0;
69
+ const conversationId = makeConversation();
70
+ await handler({
71
+ body: { conversationId, hint: "poll result", cronRunId: "attacker-run" },
72
+ headers: { "x-vellum-principal-type": "actor" },
73
+ });
74
+ expect(wakeCalls[0].trustContext).toBeUndefined();
75
+ expect(wakeCalls[0].clientless).toBeUndefined();
76
+ expect(wakeCalls[0].cronRunId).toBeUndefined();
77
+ });
78
+
79
+ test("missing principal type defaults to no elevation (fail-safe)", async () => {
80
+ wakeCalls.length = 0;
81
+ const conversationId = makeConversation();
82
+ await handler({
83
+ body: { conversationId, hint: "poll", cronRunId: "ignored-run" },
84
+ });
85
+ expect(wakeCalls[0].trustContext).toBeUndefined();
86
+ expect(wakeCalls[0].clientless).toBeUndefined();
87
+ expect(wakeCalls[0].cronRunId).toBeUndefined();
88
+ });
89
+ });
@@ -100,6 +100,13 @@ export interface RouteHandlerArgs {
100
100
  queryParams?: Record<string, string>;
101
101
  body?: Record<string, unknown>;
102
102
  rawBody?: Uint8Array;
103
+ /**
104
+ * Caller identity headers, including `x-vellum-principal-type` (the verified
105
+ * principal type) and `x-vellum-actor-principal-id`. Both adapters derive
106
+ * these from a trusted source — HTTP from the verified `AuthContext`, IPC
107
+ * from `injectLocalActorHeader` — never from caller-supplied values, so
108
+ * handlers that elevate trust can gate on the header (e.g. `"local"`).
109
+ */
103
110
  headers?: Record<string, string>;
104
111
  /**
105
112
  * Abort signal tied to the client connection. Fired when the client
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { z } from "zod";
8
8
 
9
+ import { INTERNAL_GUARDIAN_TRUST_CONTEXT } from "../../daemon/trust-context.js";
9
10
  import { getConversation } from "../../persistence/conversation-crud.js";
10
11
  import { wakeAgentForOpportunity } from "../agent-wake.js";
11
12
  import { ACTOR_PRINCIPALS } from "../auth/route-policy.js";
@@ -16,6 +17,8 @@ const WakeConversationBody = z.object({
16
17
  conversationId: z.string().min(1),
17
18
  hint: z.string().min(1),
18
19
  source: z.string().default("cli"),
20
+ // Honored only for a `local` caller (see handler) — a remote `actor` could
21
+ // otherwise attribute its wake's cost to an arbitrary firing.
19
22
  cronRunId: z.string().min(1).optional(),
20
23
  });
21
24
 
@@ -38,7 +41,7 @@ export const ROUTES: RouteDefinition[] = [
38
41
  producedToolCalls: z.boolean(),
39
42
  reason: z.string().optional(),
40
43
  }),
41
- handler: async ({ body }) => {
44
+ handler: async ({ body, headers }) => {
42
45
  const { conversationId, hint, source, cronRunId } =
43
46
  WakeConversationBody.parse(body);
44
47
 
@@ -47,11 +50,24 @@ export const ROUTES: RouteDefinition[] = [
47
50
  throw new NotFoundError(`Conversation not found: ${conversationId}`);
48
51
  }
49
52
 
53
+ // A local IPC caller is already guardian-capable, so its wake runs as a
54
+ // non-interactive guardian: `clientless` makes the turn derive
55
+ // `isInteractive: false` (mapped to the `background` policy context), so
56
+ // read-only/reasoning tools stay available while side-effecting tools are
57
+ // denied at the default threshold rather than stalling on an absent
58
+ // client. A remote `actor` (reachable via the gateway) stays
59
+ // `unknown`/interactive. The body's `cronRunId` is trusted only from a
60
+ // local caller.
61
+ const isLocal = headers?.["x-vellum-principal-type"] === "local";
62
+
50
63
  return wakeAgentForOpportunity({
51
64
  conversationId,
52
65
  hint,
53
66
  source,
54
- cronRunId,
67
+ ...(isLocal
68
+ ? { trustContext: INTERNAL_GUARDIAN_TRUST_CONTEXT, clientless: true }
69
+ : {}),
70
+ ...(isLocal && cronRunId ? { cronRunId } : {}),
55
71
  });
56
72
  },
57
73
  },
@@ -11,6 +11,7 @@ import {
11
11
  isCesSecureInstallEnabled,
12
12
  isCesToolsEnabled,
13
13
  } from "../credential-execution/feature-gates.js";
14
+ import { recallTool, rememberTool } from "../plugins/defaults/memory/tools.js";
14
15
  import { askQuestionTool } from "./ask-question/ask-question-tool.js";
15
16
  import { makeAuthenticatedRequestTool } from "./credential-execution/make-authenticated-request.js";
16
17
  import { manageSecureCommandTool } from "./credential-execution/manage-secure-command-tool.js";
@@ -20,7 +21,6 @@ import { fileListTool } from "./filesystem/list.js";
20
21
  import { fileReadTool } from "./filesystem/read.js";
21
22
  import { codeSearchTool } from "./filesystem/search.js";
22
23
  import { fileWriteTool } from "./filesystem/write.js";
23
- import { recallTool, rememberTool } from "./memory/register.js";
24
24
  import { webFetchTool } from "./network/web-fetch.js";
25
25
  import { webSearchTool } from "./network/web-search.js";
26
26
  import { skillExecuteTool } from "./skills/execute.js";