@vellumai/assistant 0.11.2-dev.202608042257.9e99b1d → 0.11.2-dev.202608042326.c3f0775

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 (32) hide show
  1. package/openapi.yaml +20 -8
  2. package/package.json +1 -1
  3. package/src/__tests__/conversation-error.test.ts +5 -2
  4. package/src/__tests__/conversation-inference-profile-route.test.ts +27 -1
  5. package/src/__tests__/inference-profile-session-handler.test.ts +95 -0
  6. package/src/__tests__/inference-profile-session-ipc.test.ts +25 -0
  7. package/src/__tests__/subagent-cron-run-attribution.test.ts +301 -0
  8. package/src/__tests__/usage-routes.test.ts +62 -0
  9. package/src/cli/commands/__tests__/inference-models.test.ts +14 -0
  10. package/src/cli/commands/__tests__/inference-profiles.test.ts +44 -1
  11. package/src/cli/commands/__tests__/inference-providers.test.ts +7 -0
  12. package/src/cli/commands/inference-profiles.ts +9 -3
  13. package/src/cli/commands/inference.help.ts +16 -2
  14. package/src/daemon/conversation-agent-loop.ts +6 -0
  15. package/src/daemon/conversation-error.ts +1 -1
  16. package/src/daemon/conversation-tool-setup.ts +1 -0
  17. package/src/daemon/conversation.ts +8 -0
  18. package/src/daemon/tool-setup-types.ts +7 -0
  19. package/src/providers/inference/connection-availability.ts +120 -5
  20. package/src/providers/model-catalog.ts +15 -0
  21. package/src/runtime/agent-wake.ts +5 -0
  22. package/src/runtime/routes/__tests__/inference-profiles-routes.test.ts +340 -3
  23. package/src/runtime/routes/conversation-query-routes.ts +8 -0
  24. package/src/runtime/routes/inference-profile-availability-guard.ts +165 -0
  25. package/src/runtime/routes/inference-profile-session-handler.ts +26 -2
  26. package/src/runtime/routes/inference-profile-session-routes.ts +2 -1
  27. package/src/runtime/routes/inference-profiles-routes.ts +149 -63
  28. package/src/subagent/manager.ts +16 -0
  29. package/src/subagent/types.ts +7 -0
  30. package/src/tools/subagent/message.ts +3 -1
  31. package/src/tools/subagent/spawn.ts +6 -0
  32. package/src/tools/types.ts +8 -0
package/openapi.yaml CHANGED
@@ -8422,7 +8422,8 @@ paths:
8422
8422
  summary: Open an inference-profile session
8423
8423
  description:
8424
8424
  Open (or replace) a session-backed inference-profile override for a conversation. Supports an optional TTL
8425
- — omit for a sticky (non-expiring) override.
8425
+ — omit for a sticky (non-expiring) override. A profile that provably cannot dispatch is rejected rather than
8426
+ pinned.
8426
8427
  tags:
8427
8428
  - conversations
8428
8429
  requestBody:
@@ -14342,7 +14343,8 @@ paths:
14342
14343
  description:
14343
14344
  Set llm.activeProfile after validating the name against the effective profile catalog (provider-aware
14344
14345
  default expansion included). Unknown or disabled profiles are rejected so the chat-model selection cannot be
14345
- silently stripped on the next config load.
14346
+ silently stripped on the next config load. A profile that provably cannot dispatch is also rejected — there is
14347
+ no escape hatch, because an unusable active profile locks the user out of chat.
14346
14348
  tags:
14347
14349
  - inference
14348
14350
  requestBody:
@@ -14375,7 +14377,7 @@ paths:
14375
14377
  - activeProfile
14376
14378
  additionalProperties: false
14377
14379
  "400":
14378
- description: Unknown or disabled profile name
14380
+ description: Unknown or disabled profile name, or a profile that cannot serve requests
14379
14381
  /v1/inference/callsites:
14380
14382
  get:
14381
14383
  operationId: inference_callsites_get
@@ -14550,7 +14552,9 @@ paths:
14550
14552
  summary: Create an inference profile
14551
14553
  description:
14552
14554
  Create a validated custom profile. The provider must be a known LLM provider, the model must be in the
14553
- catalog (unless allowUnlisted), and a referenced connection must exist. Managed default names cannot be created.
14555
+ catalog (unless allowUnlisted), a referenced connection must exist, and the profile must be able to dispatch — a
14556
+ valid provider id with no credentialed connection behind it is rejected unless allowUnavailable is set, in which
14557
+ case it is created with a warning.
14554
14558
  tags:
14555
14559
  - inference
14556
14560
  requestBody:
@@ -14589,6 +14593,8 @@ paths:
14589
14593
  type: string
14590
14594
  allowUnlisted:
14591
14595
  type: boolean
14596
+ allowUnavailable:
14597
+ type: boolean
14592
14598
  required:
14593
14599
  - name
14594
14600
  - provider
@@ -14601,7 +14607,7 @@ paths:
14601
14607
  schema:
14602
14608
  $ref: "#/components/schemas/InferenceProfileWriteResult"
14603
14609
  "400":
14604
- description: Invalid provider, uncataloged model, or missing connection
14610
+ description: Invalid provider, uncataloged model, missing connection, or a profile that cannot serve requests
14605
14611
  "409":
14606
14612
  description: A profile with this name already exists
14607
14613
  /v1/inference/profiles/{name}:
@@ -14667,8 +14673,9 @@ paths:
14667
14673
  operationId: inference_profiles_by_name_patch
14668
14674
  summary: Update an inference profile
14669
14675
  description:
14670
- Partial update of a custom profile with the same write-time validation as create. Managed default profiles
14671
- are read-only.
14676
+ Partial update of a custom profile with the same write-time validation as create. The dispatch-availability
14677
+ guard (and its allowUnavailable escape hatch) applies when the update changes provider, model, or connection;
14678
+ metadata-only edits skip it. Managed default profiles are read-only.
14672
14679
  tags:
14673
14680
  - inference
14674
14681
  parameters:
@@ -14710,6 +14717,8 @@ paths:
14710
14717
  type: string
14711
14718
  allowUnlisted:
14712
14719
  type: boolean
14720
+ allowUnavailable:
14721
+ type: boolean
14713
14722
  responses:
14714
14723
  "200":
14715
14724
  description: Successful response
@@ -14718,7 +14727,7 @@ paths:
14718
14727
  schema:
14719
14728
  $ref: "#/components/schemas/InferenceProfileWriteResult"
14720
14729
  "400":
14721
- description: Invalid fields, or attempt to edit a managed profile
14730
+ description: Invalid fields, a profile that cannot serve requests, or attempt to edit a managed profile
14722
14731
  "404":
14723
14732
  description: Profile not found
14724
14733
  /v1/inference/provider-connections:
@@ -34774,11 +34783,14 @@ components:
34774
34783
  type: array
34775
34784
  items:
34776
34785
  type: string
34786
+ verify:
34787
+ type: string
34777
34788
  required:
34778
34789
  - ok
34779
34790
  - name
34780
34791
  - entry
34781
34792
  - warnings
34793
+ - verify
34782
34794
  additionalProperties: false
34783
34795
  InferenceProfileDetail:
34784
34796
  type: object
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.2-dev.202608042257.9e99b1d",
3
+ "version": "0.11.2-dev.202608042326.c3f0775",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1556,7 +1556,7 @@ describe("ConnectionResolutionError classification", () => {
1556
1556
  expect(result.profileName).toBe("custom-fast");
1557
1557
  });
1558
1558
 
1559
- it("classifies missing_connection with an add-a-key fix and no sentinel name", () => {
1559
+ it("classifies missing_connection offering inline recovery and no sentinel name", () => {
1560
1560
  const err = new ConnectionResolutionError(
1561
1561
  "<llm.default>",
1562
1562
  "missing_connection",
@@ -1566,7 +1566,10 @@ describe("ConnectionResolutionError classification", () => {
1566
1566
  expect(result.userMessage).toContain(
1567
1567
  "No provider connection is configured",
1568
1568
  );
1569
- expect(result.userMessage).toContain("Add an API key or log in");
1569
+ // The user is locked out of chat here, so the copy must offer recovery in
1570
+ // the conversation itself, not only a settings detour.
1571
+ expect(result.userMessage).toContain("Ask me to set one up right here");
1572
+ expect(result.userMessage).toContain("Settings → Models & Services");
1570
1573
  expect(result.userMessage).not.toContain("<llm.default>");
1571
1574
  expect(result.connectionName).toBeUndefined();
1572
1575
  });
@@ -1,4 +1,16 @@
1
- import { afterAll, beforeEach, describe, expect, test } from "bun:test";
1
+ import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
2
+
3
+ // The profiles pinned below are managed presets judged for real by the
4
+ // session handler's availability guard. Stand in for a signed-in platform
5
+ // session so the pin path under test is the healthy one — same pattern as
6
+ // inference-profile-session-handler.test.ts.
7
+ mock.module("../providers/platform-proxy/context.js", () => ({
8
+ resolveManagedProxyContext: async () => ({
9
+ enabled: true,
10
+ platformBaseUrl: "https://platform.example",
11
+ assistantApiKey: "key",
12
+ }),
13
+ }));
2
14
 
3
15
  import {
4
16
  conversationMetadataSyncTag,
@@ -10,6 +22,7 @@ import {
10
22
  } from "../persistence/conversation-crud.js";
11
23
  import { getDb } from "../persistence/db-connection.js";
12
24
  import { initializeDb } from "../persistence/db-init.js";
25
+ import { providerConnections } from "../persistence/schema/inference.js";
13
26
  import { assistantEventHub } from "../runtime/assistant-event-hub.js";
14
27
  import { ROUTES } from "../runtime/routes/conversation-management-routes.js";
15
28
  import { BadRequestError, NotFoundError } from "../runtime/routes/errors.js";
@@ -18,6 +31,19 @@ import { waitFor } from "./helpers/wait-for.js";
18
31
 
19
32
  await initializeDb();
20
33
 
34
+ // The Vellum-managed connection row the managed presets resolve to.
35
+ getDb()
36
+ .insert(providerConnections)
37
+ .values({
38
+ name: "vellum",
39
+ provider: "vellum",
40
+ auth: JSON.stringify({ type: "platform" }),
41
+ createdAt: Date.now(),
42
+ updatedAt: Date.now(),
43
+ })
44
+ .onConflictDoNothing()
45
+ .run();
46
+
21
47
  const profileRoute = ROUTES.find(
22
48
  (r) => r.operationId === "setConversationInferenceProfile",
23
49
  )!;
@@ -24,6 +24,30 @@ mock.module("../runtime/assistant-event.js", () => ({
24
24
  buildAssistantEvent: (event: unknown) => event,
25
25
  }));
26
26
 
27
+ // The default profiles used below (`balanced`, `cost-optimized`) route through
28
+ // the Vellum-managed connection, and the handler's availability guard judges
29
+ // that route for real. Stand in for a signed-in platform session so the pin
30
+ // path under test is the healthy one; `managedProxyEnabled` is flipped by the
31
+ // guard test.
32
+ let managedProxyEnabled = true;
33
+ mock.module("../providers/platform-proxy/context.js", () => ({
34
+ resolveManagedProxyContext: async () => ({
35
+ enabled: managedProxyEnabled,
36
+ platformBaseUrl: "https://platform.example",
37
+ assistantApiKey: managedProxyEnabled ? "key" : "",
38
+ }),
39
+ }));
40
+
41
+ // Vault stand-in: tests that exercise BYOK availability drop the credential
42
+ // they need into this map and clean it up after.
43
+ const storedKeys: Record<string, string> = {};
44
+ mock.module("../security/secure-keys.js", () => ({
45
+ getSecureKeyResultAsync: async (key: string) => ({
46
+ value: storedKeys[key],
47
+ unreachable: false,
48
+ }),
49
+ }));
50
+
27
51
  // The handler reads the real config: the "balanced" and "cost-optimized"
28
52
  // profiles used below are code-default catalog entries that always resolve,
29
53
  // and llm.profileSession's schema defaults (1800/43200) are what the TTL
@@ -44,9 +68,24 @@ import {
44
68
  } from "../persistence/conversation-crud.js";
45
69
  import { getDb } from "../persistence/db-connection.js";
46
70
  import { initializeDb } from "../persistence/db-init.js";
71
+ import { providerConnections } from "../persistence/schema/inference.js";
72
+ import { setConfig } from "./helpers/set-config.js";
47
73
 
48
74
  await initializeDb();
49
75
 
76
+ // The Vellum-managed connection row the default profiles resolve to.
77
+ getDb()
78
+ .insert(providerConnections)
79
+ .values({
80
+ name: "vellum",
81
+ provider: "vellum",
82
+ auth: JSON.stringify({ type: "platform" }),
83
+ createdAt: Date.now(),
84
+ updatedAt: Date.now(),
85
+ })
86
+ .onConflictDoNothing()
87
+ .run();
88
+
50
89
  import {
51
90
  closeInferenceProfileSession,
52
91
  listInferenceProfileSessionsWithRemaining,
@@ -344,6 +383,62 @@ describe("setInferenceProfileSession", () => {
344
383
  );
345
384
  });
346
385
 
386
+ test("open with an unavailable profile — refuses the pin and names the fix", async () => {
387
+ const conv = createConversation("sess-handler-unavailable-profile");
388
+ managedProxyEnabled = false;
389
+ try {
390
+ const promise = setInferenceProfileSession({
391
+ conversationId: conv.id,
392
+ profile: "balanced",
393
+ ttlSeconds: 300,
394
+ });
395
+ await expect(promise).rejects.toThrow(/Not signed in to Vellum/);
396
+ await expect(promise).rejects.toThrow(
397
+ /assistant inference send --profile balanced "Reply with OK"/,
398
+ );
399
+ // Nothing was pinned.
400
+ expect(getConversation(conv.id)?.inferenceProfile).toBeNull();
401
+ } finally {
402
+ managedProxyEnabled = true;
403
+ }
404
+ });
405
+
406
+ test("BYOK default provider — pins a managed preset without a Vellum sign-in", async () => {
407
+ const conv = createConversation("sess-handler-byok-preset");
408
+ // Signed out of Vellum, but llm.defaultProvider points the managed
409
+ // presets at the user's own anthropic connection — the pin must judge
410
+ // that body, not the Vellum column.
411
+ managedProxyEnabled = false;
412
+ storedKeys["credential/anthropic/api_key"] = "test-key";
413
+ getDb()
414
+ .insert(providerConnections)
415
+ .values({
416
+ name: "anthropic-personal",
417
+ provider: "anthropic",
418
+ auth: JSON.stringify({
419
+ type: "api_key",
420
+ credential: "credential/anthropic/api_key",
421
+ }),
422
+ createdAt: Date.now(),
423
+ updatedAt: Date.now(),
424
+ })
425
+ .onConflictDoNothing()
426
+ .run();
427
+ setConfig("llm", { defaultProvider: { provider: "anthropic" } });
428
+ try {
429
+ const result = await setInferenceProfileSession({
430
+ conversationId: conv.id,
431
+ profile: "balanced",
432
+ ttlSeconds: 300,
433
+ });
434
+ expect(result.profile).toBe("balanced");
435
+ } finally {
436
+ managedProxyEnabled = true;
437
+ delete storedKeys["credential/anthropic/api_key"];
438
+ setConfig("llm", {});
439
+ }
440
+ });
441
+
347
442
  test("open with ttlSeconds=null — expiresAt=null, sessionId=null, profile kept", async () => {
348
443
  const conv = createConversation("sess-handler-null-ttl");
349
444
 
@@ -16,6 +16,17 @@ mock.module("../runtime/assistant-event.js", () => ({
16
16
  buildAssistantEvent: (event: unknown) => event,
17
17
  }));
18
18
 
19
+ // "balanced"/"cost-optimized" route through the Vellum-managed connection, and
20
+ // the open handler's availability guard judges that route for real. Stand in
21
+ // for a signed-in platform session so these tests exercise the healthy path.
22
+ mock.module("../providers/platform-proxy/context.js", () => ({
23
+ resolveManagedProxyContext: async () => ({
24
+ enabled: true,
25
+ platformBaseUrl: "https://platform.example",
26
+ assistantApiKey: "key",
27
+ }),
28
+ }));
29
+
19
30
  // The handler resolves "balanced"/"cost-optimized" through the code-defined
20
31
  // default profile catalog and reads `llm.profileSession` schema defaults
21
32
  // (1800/43200), so real config with no seeding covers these tests.
@@ -23,11 +34,25 @@ mock.module("../runtime/assistant-event.js", () => ({
23
34
  import { createConversation } from "../persistence/conversation-crud.js";
24
35
  import { getDb } from "../persistence/db-connection.js";
25
36
  import { initializeDb } from "../persistence/db-init.js";
37
+ import { providerConnections } from "../persistence/schema/inference.js";
26
38
  import { ROUTES } from "../runtime/routes/inference-profile-session-routes.js";
27
39
  import { resetDbForTesting } from "./db-test-helpers.js";
28
40
 
29
41
  await initializeDb();
30
42
 
43
+ // The Vellum-managed connection row the default profiles resolve to.
44
+ getDb()
45
+ .insert(providerConnections)
46
+ .values({
47
+ name: "vellum",
48
+ provider: "vellum",
49
+ auth: JSON.stringify({ type: "platform" }),
50
+ createdAt: Date.now(),
51
+ updatedAt: Date.now(),
52
+ })
53
+ .onConflictDoNothing()
54
+ .run();
55
+
31
56
  const openRoute = ROUTES.find(
32
57
  (r) => r.operationId === "inference_profile_open",
33
58
  )!;
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Verifies that the schedule firing's `cron_runs.id` reaches the LLM work a
3
+ * scheduled turn delegates to subagents.
4
+ *
5
+ * A scheduled turn stamps every usage row it records with `cronRunId`, and
6
+ * schedule cost reporting attributes by that stamp. A subagent runs as its own
7
+ * child conversation, so unless the firing id is threaded through
8
+ * `ToolContext` → `SubagentConfig` → the child's `runAgentLoop`, the delegated
9
+ * spend records a null `cron_run_id` and drops out of the schedule's cost.
10
+ *
11
+ * The threading mirrors `overrideProfile`; the plumbing for that field is
12
+ * pinned by `agent-loop-override-profile.test.ts`.
13
+ */
14
+
15
+ import { describe, expect, mock, test } from "bun:test";
16
+
17
+ import type { ToolContext } from "../tools/types.js";
18
+ import { setConfig } from "./helpers/set-config.js";
19
+
20
+ interface CapturedRunAgentLoopOptions {
21
+ callSite?: string;
22
+ overrideProfile?: string;
23
+ forceOverrideProfile?: boolean;
24
+ cronRunId?: string | null;
25
+ }
26
+
27
+ const capturedRunAgentLoopOptions: CapturedRunAgentLoopOptions[] = [];
28
+
29
+ // When set, `runAgentLoop` never settles, so the spawned subagent stays in a
30
+ // non-terminal state and can accept a follow-up `sendMessage`.
31
+ let holdRunAgentLoop = false;
32
+
33
+ class FakeConversation {
34
+ constructor() {}
35
+ updateClient() {}
36
+
37
+ setTrustContext() {}
38
+ setAuthContext() {}
39
+ getAuthContext() {
40
+ return undefined;
41
+ }
42
+ setAssistantId() {}
43
+ setEnabledPlugins() {}
44
+ hasSystemPromptOverride = false;
45
+ setSubagentAllowedTools() {}
46
+ setSubagentDenySideEffects() {}
47
+ setSubagentSuppressParentNotifications() {}
48
+ setPreactivatedSkillIds() {}
49
+ preactivateSkills() {}
50
+ preactivateSkillsAsync() {}
51
+ setSpawnHints() {}
52
+ injectInheritedContext() {}
53
+ setActiveBranchId() {}
54
+ setBranchTag() {}
55
+ setForkPolicy() {}
56
+ setForkParentMessageCount() {}
57
+ setForkParentSystemPrompt() {}
58
+ enqueueMessage() {
59
+ return { rejected: false, queued: false };
60
+ }
61
+ abort() {}
62
+ dispose() {}
63
+ messages = [];
64
+ subagentDeniedToolNames: string[] = [];
65
+ usageStats = { inputTokens: 0, outputTokens: 0, estimatedCost: 0 };
66
+ sendToClient() {}
67
+ loadFromDb() {
68
+ return Promise.resolve();
69
+ }
70
+ persistUserMessage() {
71
+ return Promise.resolve({ id: "msg-id", deduplicated: false });
72
+ }
73
+ runAgentLoop(
74
+ _content: string,
75
+ _userMessageId: string,
76
+ options?: CapturedRunAgentLoopOptions,
77
+ ) {
78
+ capturedRunAgentLoopOptions.push({ ...(options ?? {}) });
79
+ if (holdRunAgentLoop) {
80
+ return new Promise<void>(() => {});
81
+ }
82
+ return Promise.resolve();
83
+ }
84
+ getCurrentSystemPrompt() {
85
+ return "system";
86
+ }
87
+ }
88
+
89
+ mock.module("../daemon/conversation.js", () => ({
90
+ Conversation: FakeConversation,
91
+ }));
92
+
93
+ mock.module("../persistence/conversation-bootstrap.js", () => ({
94
+ bootstrapConversation: () => ({ id: "conv-id" }),
95
+ }));
96
+
97
+ mock.module("../prompts/system-prompt.js", () => ({
98
+ buildSystemPrompt: () => "system prompt",
99
+ buildSubagentSystemPrompt: () => "subagent system",
100
+ }));
101
+
102
+ mock.module("../persistence/conversation-crud.js", () => ({
103
+ setConversationProcessingStartedAt: () => {},
104
+ getConversationOverrideProfile: () => undefined,
105
+ reserveMessage: mock(async () => ({ id: "msg-reserve" })),
106
+ }));
107
+
108
+ const anthropicStub = { name: "anthropic" };
109
+
110
+ mock.module("../providers/registry.js", () => ({
111
+ getProvider: () => anthropicStub,
112
+ listProviders: () => ["anthropic"],
113
+ initializeProviders: async () => {},
114
+ resolveProviderFromConnection: async () => anthropicStub,
115
+ }));
116
+
117
+ mock.module("../providers/inference/connections.js", () => ({
118
+ getConnection: (_db: unknown, name: string) => ({
119
+ id: 1,
120
+ name,
121
+ provider: "anthropic",
122
+ auth_strategy: "user_managed_credential",
123
+ credential_alias: null,
124
+ metadata_json: null,
125
+ created_at: new Date().toISOString(),
126
+ updated_at: new Date().toISOString(),
127
+ }),
128
+ }));
129
+
130
+ setConfig("llm", {
131
+ profiles: {
132
+ fast: {
133
+ source: "user",
134
+ provider: "anthropic",
135
+ model: "claude-haiku-4-5-20251001",
136
+ },
137
+ },
138
+ callSites: {},
139
+ });
140
+
141
+ // ── Imports (after mocks) ───────────────────────────────────────────────────
142
+
143
+ import { getSubagentManager } from "../subagent/index.js";
144
+ import { SubagentManager } from "../subagent/manager.js";
145
+ import { executeSubagentSpawn } from "../tools/subagent/spawn.js";
146
+
147
+ function toolContext(overrides: Partial<ToolContext>): ToolContext {
148
+ return {
149
+ workingDir: "/tmp",
150
+ conversationId: "conv-scheduled",
151
+ trustClass: "guardian",
152
+ sendToClient: () => {},
153
+ ...overrides,
154
+ } as ToolContext;
155
+ }
156
+
157
+ describe("executeSubagentSpawn: cronRunId forwarding", () => {
158
+ test("forwards the turn's cronRunId into the SubagentConfig", async () => {
159
+ const manager = getSubagentManager();
160
+ const originalSpawn = manager.spawn.bind(manager);
161
+ let capturedConfig: Record<string, unknown> | undefined;
162
+ manager.spawn = async (config: never) => {
163
+ capturedConfig = config;
164
+ return "subagent-cron-1";
165
+ };
166
+
167
+ try {
168
+ const result = await executeSubagentSpawn(
169
+ { label: "scheduled-child", objective: "do the delegated work" },
170
+ toolContext({ cronRunId: "cron-run-abc" }),
171
+ );
172
+
173
+ expect(result.isError).toBe(false);
174
+ expect(capturedConfig?.cronRunId).toBe("cron-run-abc");
175
+ } finally {
176
+ manager.spawn = originalSpawn;
177
+ }
178
+ });
179
+
180
+ test("omits cronRunId when the invoking turn was not triggered by a schedule", async () => {
181
+ const manager = getSubagentManager();
182
+ const originalSpawn = manager.spawn.bind(manager);
183
+ let capturedConfig: Record<string, unknown> | undefined;
184
+ manager.spawn = async (config: never) => {
185
+ capturedConfig = config;
186
+ return "subagent-cron-2";
187
+ };
188
+
189
+ try {
190
+ await executeSubagentSpawn(
191
+ { label: "interactive-child", objective: "do the delegated work" },
192
+ toolContext({ conversationId: "conv-interactive" }),
193
+ );
194
+
195
+ expect(capturedConfig).toBeDefined();
196
+ expect("cronRunId" in capturedConfig!).toBe(false);
197
+ } finally {
198
+ manager.spawn = originalSpawn;
199
+ }
200
+ });
201
+ });
202
+
203
+ describe("SubagentManager: cronRunId reaches the child's agent loop", () => {
204
+ test("passes the config's cronRunId into the spawned subagent's runAgentLoop", async () => {
205
+ capturedRunAgentLoopOptions.length = 0;
206
+
207
+ const manager = new SubagentManager();
208
+ await manager.spawn(
209
+ {
210
+ parentConversationId: "parent-cron-1",
211
+ label: "child",
212
+ objective: "do the thing",
213
+ cronRunId: "cron-run-abc",
214
+ },
215
+ () => {},
216
+ );
217
+
218
+ expect(capturedRunAgentLoopOptions).toHaveLength(1);
219
+ const captured = capturedRunAgentLoopOptions[0]!;
220
+ expect(captured.callSite).toBe("subagentSpawn");
221
+ expect(captured.cronRunId).toBe("cron-run-abc");
222
+ });
223
+
224
+ test("omits cronRunId when the SubagentConfig does not carry one", async () => {
225
+ capturedRunAgentLoopOptions.length = 0;
226
+
227
+ const manager = new SubagentManager();
228
+ await manager.spawn(
229
+ {
230
+ parentConversationId: "parent-cron-2",
231
+ label: "child",
232
+ objective: "do the thing",
233
+ },
234
+ () => {},
235
+ );
236
+
237
+ expect(capturedRunAgentLoopOptions).toHaveLength(1);
238
+ expect("cronRunId" in capturedRunAgentLoopOptions[0]!).toBe(false);
239
+ });
240
+
241
+ test("a continuation turn carries the messaging turn's cronRunId, not the spawn's", async () => {
242
+ capturedRunAgentLoopOptions.length = 0;
243
+ holdRunAgentLoop = true;
244
+
245
+ try {
246
+ const manager = new SubagentManager();
247
+ const subagentId = await manager.spawn(
248
+ {
249
+ parentConversationId: "parent-cron-3",
250
+ label: "child",
251
+ objective: "do the thing",
252
+ cronRunId: "cron-run-spawn",
253
+ },
254
+ () => {},
255
+ );
256
+ // The initial run is fire-and-forget; let it reach runAgentLoop.
257
+ await Promise.resolve();
258
+ await Promise.resolve();
259
+
260
+ const result = await manager.sendMessage(subagentId, "keep going", {
261
+ cronRunId: "cron-run-message",
262
+ });
263
+ expect(result).toBe("sent");
264
+
265
+ expect(capturedRunAgentLoopOptions).toHaveLength(2);
266
+ expect(capturedRunAgentLoopOptions[0]!.cronRunId).toBe("cron-run-spawn");
267
+ expect(capturedRunAgentLoopOptions[1]!.cronRunId).toBe(
268
+ "cron-run-message",
269
+ );
270
+ } finally {
271
+ holdRunAgentLoop = false;
272
+ }
273
+ });
274
+
275
+ test("omits cronRunId on a continuation turn no schedule triggered", async () => {
276
+ capturedRunAgentLoopOptions.length = 0;
277
+ holdRunAgentLoop = true;
278
+
279
+ try {
280
+ const manager = new SubagentManager();
281
+ const subagentId = await manager.spawn(
282
+ {
283
+ parentConversationId: "parent-cron-4",
284
+ label: "child",
285
+ objective: "do the thing",
286
+ cronRunId: "cron-run-spawn",
287
+ },
288
+ () => {},
289
+ );
290
+ await Promise.resolve();
291
+ await Promise.resolve();
292
+
293
+ await manager.sendMessage(subagentId, "keep going", { cronRunId: null });
294
+
295
+ expect(capturedRunAgentLoopOptions).toHaveLength(2);
296
+ expect("cronRunId" in capturedRunAgentLoopOptions[1]!).toBe(false);
297
+ } finally {
298
+ holdRunAgentLoop = false;
299
+ }
300
+ });
301
+ });