@ziggs-ai/agent-sdk 0.1.10 → 0.1.12

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 (35) hide show
  1. package/package.json +6 -3
  2. package/src/AgentHost.ts +347 -28
  3. package/src/adapters/AnthropicAdapter.ts +238 -0
  4. package/src/adapters/McpAdapter.ts +391 -15
  5. package/src/adapters/OpenAIAdapter.ts +20 -8
  6. package/src/adapters/index.ts +1 -0
  7. package/src/agent/Agent.ts +13 -2
  8. package/src/agent/ClaudeSdkAgent.ts +401 -0
  9. package/src/agent/claudeCognition.ts +139 -0
  10. package/src/agent/claudeSdkProtocol.ts +27 -0
  11. package/src/agent/claudeSdkTools.ts +81 -0
  12. package/src/agent/hostedAgentConnection.ts +41 -0
  13. package/src/agent/toolManagerToSdkMcp.ts +136 -0
  14. package/src/defineAgent.ts +22 -7
  15. package/src/index.ts +14 -5
  16. package/src/pricing/fleetTierByAgentId.gen.ts +53 -1
  17. package/src/runtime/AgentMachine.ts +143 -23
  18. package/src/runtime/PromptBuilder.ts +62 -6
  19. package/src/runtime/bootstrapCtx.ts +39 -0
  20. package/src/runtime/buildOutcome.ts +51 -6
  21. package/src/runtime/defaults.ts +12 -1
  22. package/src/runtime/deriveRespondsToProposals.ts +35 -0
  23. package/src/runtime/kickoff.ts +117 -0
  24. package/src/runtime/runMechanical.ts +106 -0
  25. package/src/runtime/runTurn.ts +236 -62
  26. package/src/runtime/validateWorkflow.ts +55 -15
  27. package/src/server/ConnectionPool.ts +56 -5
  28. package/src/server/InboxCatchUp.ts +37 -0
  29. package/src/server/StateTimers.ts +85 -0
  30. package/src/server/ZiggsEffectHandler.ts +198 -180
  31. package/src/server/agreements/AgreementService.ts +3 -3
  32. package/src/server/tasks/TaskService.ts +15 -3
  33. package/src/server/tools/tier1/protocolRunner.ts +221 -3
  34. package/src/server/tools/tier1/protocolTools.ts +19 -4
  35. package/src/types.ts +105 -29
@@ -8,7 +8,17 @@ import type { Workflow } from '../types.js';
8
8
 
9
9
  export type McpTransportConfig =
10
10
  | { type: 'stdio'; command: string; args?: string[]; env?: Record<string, string> }
11
- | { type: 'http'; url: string }
11
+ | {
12
+ type: 'http';
13
+ url: string;
14
+ /**
15
+ * Optional static request headers — e.g. a fixed API key the server is
16
+ * keyed by. Sent on every request to the server. Values are used as-is;
17
+ * `$VAR` interpolation (if any) is the caller's job, mirroring how the
18
+ * stdio path leaves `env` interpolation to the caller.
19
+ */
20
+ headers?: Record<string, string>;
21
+ }
12
22
  | {
13
23
  /**
14
24
  * Brokered connection through the Ziggs MCP gateway: the agent speaks
@@ -27,6 +37,32 @@ export type McpTransportConfig =
27
37
  baseUrl?: string;
28
38
  /** Agent to impersonate (X-Agent-Id) — defaults to the host agentId. */
29
39
  agentId?: string;
40
+ }
41
+ | {
42
+ /**
43
+ * Per-user brokered connection (ZIG-771): the agent holds NO
44
+ * connectionId/grantId. It speaks StreamableHTTP to
45
+ * `/connections/mcp/relay` and asserts the invoking end-user via
46
+ * `x-on-behalf-of-user`; the gateway resolves that user's own connection
47
+ * + grant and injects their token. One MCP client is created per invoking
48
+ * user so each keeps an isolated upstream session. Tool schemas cannot be
49
+ * discovered at boot (there is no connection yet) — pass `toolSchema`.
50
+ */
51
+ type: 'ziggs-per-user';
52
+ /** Operator key — defaults to ZIGGS_OPERATOR_KEY. */
53
+ operatorKey?: string;
54
+ /** Ziggs backend base URL — defaults to BACKEND_URL / ZIGGS_BACKEND_URL. */
55
+ baseUrl?: string;
56
+ /** Agent to impersonate (X-Agent-Id) — defaults to the host agentId. */
57
+ agentId?: string;
58
+ /**
59
+ * The MCP server URL this agent fronts. Not used for gateway calls (the
60
+ * gateway derives the server from the resolved connection), but needed to
61
+ * open a connection request when the invoking user hasn't connected yet
62
+ * (ZIG-771). Without it, a NO_USER_CONNECTION surfaces as an error rather
63
+ * than an auto-created consent prompt.
64
+ */
65
+ serverUrl?: string;
30
66
  };
31
67
 
32
68
  /**
@@ -113,6 +149,43 @@ export function resolveZiggsGatewayTarget(
113
149
  };
114
150
  }
115
151
 
152
+ /**
153
+ * Resolve the per-user gateway URL + headers (ZIG-771). No connectionId/grantId —
154
+ * the gateway resolves the invoking user's own connection + grant from
155
+ * `x-on-behalf-of-user` + the impersonated agent.
156
+ */
157
+ export function resolvePerUserGatewayTarget(
158
+ config: Extract<McpTransportConfig, { type: 'ziggs-per-user' }>,
159
+ agentId: string,
160
+ userId: string,
161
+ onBehalfOfAgreementId?: string,
162
+ ): { url: URL; headers: Record<string, string> } {
163
+ const operatorKey = config.operatorKey || process.env.ZIGGS_OPERATOR_KEY;
164
+ if (!operatorKey) {
165
+ throw new Error(
166
+ 'ziggs-per-user MCP transport requires an operatorKey (or ZIGGS_OPERATOR_KEY)',
167
+ );
168
+ }
169
+ const baseUrl = (
170
+ config.baseUrl ||
171
+ process.env.BACKEND_URL ||
172
+ process.env.ZIGGS_BACKEND_URL ||
173
+ 'http://localhost:3000'
174
+ ).replace(/\/$/, '');
175
+ return {
176
+ url: new URL(`${baseUrl}/connections/mcp/relay`),
177
+ headers: {
178
+ authorization: `Bearer ${operatorKey}`,
179
+ 'x-agent-id': agentId,
180
+ 'x-on-behalf-of-user': userId,
181
+ // ZIG-831: when this call runs under a delegation, userId is the delegating
182
+ // agent (senderId), not the end-user who owns the connection. The gateway
183
+ // uses this agreement to resolve the delegation root's user.
184
+ ...(onBehalfOfAgreementId ? { 'x-on-behalf-of-agreement': onBehalfOfAgreementId } : {}),
185
+ },
186
+ };
187
+ }
188
+
116
189
  export interface CreateMcpAgentOptions extends Omit<AgentHostOptions, 'tools' | 'workflow' | 'states' | 'initial'> {
117
190
  /** MCP server connection — stdio (local process) or HTTP (remote). */
118
191
  transport: McpTransportConfig;
@@ -120,6 +193,48 @@ export interface CreateMcpAgentOptions extends Omit<AgentHostOptions, 'tools' |
120
193
  extraTools?: ToolDefinition[];
121
194
  /** Override the default single-state thinking workflow. */
122
195
  workflow?: Workflow;
196
+ /**
197
+ * Max tools to bind to the LLM per turn. LLM providers cap the `tools` array
198
+ * (OpenAI: 128); an MCP server exposing more (e.g. PostHog: 146) makes every
199
+ * turn fail with `400 ... array too long`. When the server's tool count
200
+ * exceeds this budget the list is truncated (and logged). Defaults to 128.
201
+ * See ZIG-759; Phase 2 will replace truncation with query-aware selection.
202
+ */
203
+ maxTools?: number;
204
+ /**
205
+ * Restrict the bound tool set to only tools whose name matches one of these
206
+ * case-insensitive substrings, applied BEFORE the maxTools cap. Lets a large
207
+ * MCP server (e.g. PostHog's 146 tools) be narrowed to the handful this agent
208
+ * actually needs — cutting per-turn cost and stopping the model from thrashing
209
+ * across (or never binding) the tool it should call. Empty/undefined = bind
210
+ * all (unchanged behavior). ZIG-759 Phase 2 = name-based selection.
211
+ */
212
+ allowedTools?: string[];
213
+ /**
214
+ * Pre-discovered MCP tool schemas. REQUIRED for `type: 'ziggs-per-user'`
215
+ * (ZIG-771) — there is no boot connection to call `tools/list` on, so the
216
+ * schema is baked at provision time and passed here. Ignored for the other
217
+ * transports, which discover tools live at boot.
218
+ */
219
+ toolSchema?: Array<{
220
+ name: string;
221
+ description?: string;
222
+ inputSchema?: Record<string, unknown>;
223
+ }>;
224
+ }
225
+
226
+ /** Provider `tools` array cap (OpenAI's is 128). */
227
+ const DEFAULT_MAX_TOOLS = 128;
228
+ /** Headroom reserved for control actions (wait/respond) + future additions. */
229
+ const CONTROL_TOOL_RESERVE = 4;
230
+
231
+ /**
232
+ * How many MCP tools may be bound to the LLM, given the provider cap and the
233
+ * number of extra (non-MCP) tools the agent also carries. Always >= 1 so a
234
+ * pathological config still binds something rather than nothing. ZIG-759.
235
+ */
236
+ export function mcpToolBudget(maxTools: number, extraToolCount: number): number {
237
+ return Math.max(1, maxTools - CONTROL_TOOL_RESERVE - extraToolCount);
123
238
  }
124
239
 
125
240
  export interface McpAgentHandle {
@@ -130,7 +245,7 @@ export interface McpAgentHandle {
130
245
  toolNames: string[];
131
246
  }
132
247
 
133
- function buildTransport(config: McpTransportConfig, defaults: { agentId?: string }) {
248
+ export function buildTransport(config: McpTransportConfig, defaults: { agentId?: string } = {}) {
134
249
  if (config.type === 'stdio') {
135
250
  return new StdioClientTransport({
136
251
  command: config.command,
@@ -145,7 +260,17 @@ function buildTransport(config: McpTransportConfig, defaults: { agentId?: string
145
260
  fetch: wrapGatewayFetch(),
146
261
  });
147
262
  }
148
- return new StreamableHTTPClientTransport(new URL(config.url));
263
+ if (config.type === 'ziggs-per-user') {
264
+ // Per-user transports are built lazily per invoking user in createMcpAgent
265
+ // (each needs a different x-on-behalf-of-user header), not here.
266
+ throw new Error('ziggs-per-user transport is created per invoking user, not via buildTransport');
267
+ }
268
+ return new StreamableHTTPClientTransport(
269
+ new URL(config.url),
270
+ config.headers && Object.keys(config.headers).length > 0
271
+ ? { requestInit: { headers: config.headers } }
272
+ : undefined,
273
+ );
149
274
  }
150
275
 
151
276
  type McpTool = {
@@ -167,7 +292,17 @@ function mcpContentToResult(content: McpContent[]): unknown {
167
292
  }
168
293
  }
169
294
 
170
- function mapMcpTools(client: Client, tools: McpTool[]): ToolDefinition[] {
295
+ /**
296
+ * Calls one MCP tool. The single-client path closes over a fixed client; the
297
+ * per-user path (ZIG-771) uses `context.senderId` to pick that user's client.
298
+ */
299
+ type McpToolCaller = (
300
+ toolName: string,
301
+ args: Record<string, unknown>,
302
+ context: Record<string, unknown>,
303
+ ) => Promise<{ isError?: boolean; content: McpContent[] }>;
304
+
305
+ function mapMcpTools(callTool: McpToolCaller, tools: McpTool[]): ToolDefinition[] {
171
306
  return tools.map(tool => ({
172
307
  schema: {
173
308
  type: 'function' as const,
@@ -177,11 +312,11 @@ function mapMcpTools(client: Client, tools: McpTool[]): ToolDefinition[] {
177
312
  parameters: tool.inputSchema ?? { type: 'object', properties: {} },
178
313
  },
179
314
  },
180
- handler: async (args: Record<string, unknown>) => {
181
- const result = await client.callTool({ name: tool.name, arguments: args }) as {
182
- isError?: boolean;
183
- content: McpContent[];
184
- };
315
+ handler: async (
316
+ args: Record<string, unknown>,
317
+ context: Record<string, unknown>,
318
+ ) => {
319
+ const result = await callTool(tool.name, args, context);
185
320
  if (result.isError) {
186
321
  throw new Error(mcpContentToResult(result.content) as string);
187
322
  }
@@ -242,6 +377,90 @@ function buildDefaultWorkflow(description: string, mcpTools: McpTool[]): Workflo
242
377
  };
243
378
  }
244
379
 
380
+ /**
381
+ * Max chars for a single tool description bound to the LLM. Verbose MCP servers
382
+ * embed whole manuals in their descriptions (PostHog's `execute-sql` alone is
383
+ * ~30K chars of HogQL docs; its 146 tools total ~54K tokens of descriptions) and
384
+ * that full block rides every turn. Keep the lead — what the tool does + how to
385
+ * call it — and drop the embedded reference; agents fetch detail via dedicated
386
+ * schema/help tools at call time. Tunable; big enough to preserve real guidance.
387
+ * ZIG-759.
388
+ */
389
+ export const MAX_TOOL_DESC_CHARS = 2000;
390
+
391
+ /** Truncate one description at a sentence/newline boundary near the cap. */
392
+ export function trimDescription(desc: string | undefined): string | undefined {
393
+ if (!desc || desc.length <= MAX_TOOL_DESC_CHARS) return desc;
394
+ const slice = desc.slice(0, MAX_TOOL_DESC_CHARS);
395
+ const boundary = Math.max(slice.lastIndexOf('\n'), slice.lastIndexOf('. '));
396
+ const head = boundary > MAX_TOOL_DESC_CHARS * 0.6 ? slice.slice(0, boundary + 1) : slice;
397
+ return `${head.trimEnd()} […description truncated; use the server's schema/help tools for full detail]`;
398
+ }
399
+
400
+ /** Trim oversized descriptions across the tool set (cost control, ZIG-759). */
401
+ function trimToolDescriptions(tools: McpTool[], agentId: string | undefined): McpTool[] {
402
+ let trimmedCount = 0;
403
+ let savedChars = 0;
404
+ const out = tools.map((t) => {
405
+ const nextDesc = trimDescription(t.description);
406
+ if (nextDesc === t.description) return t;
407
+ trimmedCount += 1;
408
+ savedChars += (t.description?.length ?? 0) - (nextDesc?.length ?? 0);
409
+ return { ...t, description: nextDesc };
410
+ });
411
+ if (trimmedCount > 0) {
412
+ console.warn(
413
+ `[McpAdapter] ${agentId}: trimmed ${trimmedCount} oversized tool description(s) to ${MAX_TOOL_DESC_CHARS} chars, saving ~${Math.round(savedChars / 4 / 1000)}K tokens/turn. (ZIG-759)`,
414
+ );
415
+ }
416
+ return out;
417
+ }
418
+
419
+ /**
420
+ * Keep only tools whose name matches one of the allowlist substrings
421
+ * (case-insensitive). No allowlist → pass through unchanged. Applied before the
422
+ * maxTools cap so a targeted agent binds exactly the tools it needs. ZIG-759.
423
+ */
424
+ function filterToolsByAllowlist(
425
+ tools: McpTool[],
426
+ allowedTools: string[] | undefined,
427
+ agentId: string | undefined,
428
+ ): McpTool[] {
429
+ if (!allowedTools || allowedTools.length === 0) return tools;
430
+ const patterns = allowedTools.map((p) => p.toLowerCase());
431
+ const kept = tools.filter((t) =>
432
+ patterns.some((p) => t.name.toLowerCase().includes(p)),
433
+ );
434
+ console.warn(
435
+ `[McpAdapter] ${agentId}: tool allowlist active — bound ${kept.length}/${tools.length} tools matching [${allowedTools.join(', ')}]${kept.length === 0 ? ' ⚠️ NONE MATCHED — check patterns against the server\'s tool names' : ': ' + kept.map((t) => t.name).join(', ')}.`,
436
+ );
437
+ return kept;
438
+ }
439
+
440
+ /**
441
+ * Cap the tool set bound to the LLM at the provider limit (OpenAI 128) —
442
+ * truncate and log rather than crash — and trim oversized descriptions so the
443
+ * bound schema doesn't ship a manual every turn. ZIG-759 Phase 1. Shared by the
444
+ * boot-time (single-client) and per-user paths. When `allowedTools` is set the
445
+ * server's tools are narrowed by name first, so the cap rarely bites.
446
+ */
447
+ function capTools(
448
+ tools: McpTool[],
449
+ agentId: string | undefined,
450
+ maxTools: number,
451
+ extraToolCount: number,
452
+ allowedTools?: string[],
453
+ ): McpTool[] {
454
+ const allowed = filterToolsByAllowlist(tools, allowedTools, agentId);
455
+ const trimmed = trimToolDescriptions(allowed, agentId);
456
+ const budget = mcpToolBudget(maxTools, extraToolCount);
457
+ if (trimmed.length <= budget) return trimmed;
458
+ console.warn(
459
+ `[McpAdapter] ${agentId}: MCP server exposes ${trimmed.length} tools, over the ${maxTools}-tool LLM cap; binding the first ${budget}, dropping ${trimmed.length - budget}. (ZIG-759 Phase 2 will select per query.)`,
460
+ );
461
+ return trimmed.slice(0, budget);
462
+ }
463
+
245
464
  /**
246
465
  * Wraps any MCP server as a Ziggs AgentHost.
247
466
  *
@@ -276,18 +495,175 @@ function buildDefaultWorkflow(description: string, mcpTools: McpTool[]): Workflo
276
495
  * });
277
496
  */
278
497
  export async function createMcpAgent(options: CreateMcpAgentOptions): Promise<McpAgentHandle> {
279
- const { transport: transportConfig, extraTools = [], workflow, ...hostOptions } = options;
498
+ const { transport: transportConfig, extraTools = [], workflow, maxTools = DEFAULT_MAX_TOOLS, allowedTools, toolSchema, ...hostOptions } = options;
280
499
 
500
+ // ── Per-user path (ZIG-771): no boot connection; one MCP client per invoking
501
+ // user, each carrying that user's on-behalf-of header for an isolated session.
502
+ if (transportConfig.type === 'ziggs-per-user') {
503
+ const agentId = transportConfig.agentId || hostOptions.agentId;
504
+ if (!agentId) {
505
+ throw new Error('ziggs-per-user MCP transport requires an agentId to impersonate');
506
+ }
507
+ if (!toolSchema || toolSchema.length === 0) {
508
+ throw new Error('ziggs-per-user MCP transport requires toolSchema (no boot connection to discover tools)');
509
+ }
510
+ const tools = capTools(toolSchema as McpTool[], agentId, maxTools, extraTools.length, allowedTools);
511
+
512
+ const clients = new Map<string, Promise<Client>>();
513
+ const clientFor = (
514
+ userId: string,
515
+ onBehalfOfAgreementId?: string,
516
+ ): Promise<Client> => {
517
+ // Key by user + agreement: the gateway may resolve a different end-user
518
+ // per agreement (delegation), so sessions must not be shared across them.
519
+ const cacheKey = `${userId}|${onBehalfOfAgreementId ?? ''}`;
520
+ let p = clients.get(cacheKey);
521
+ if (!p) {
522
+ p = (async () => {
523
+ const target = resolvePerUserGatewayTarget(transportConfig, agentId, userId, onBehalfOfAgreementId);
524
+ const transport = new StreamableHTTPClientTransport(target.url, {
525
+ requestInit: { headers: target.headers },
526
+ fetch: wrapGatewayFetch(),
527
+ });
528
+ const c = new Client({ name: 'ziggs-mcp-agent', version: '1.0.0' });
529
+ await c.connect(transport);
530
+ return c;
531
+ })().catch((err: unknown) => {
532
+ // Don't cache a failed connect (e.g. NO_USER_CONNECTION before the
533
+ // user consents) — the next turn must be able to retry.
534
+ clients.delete(cacheKey);
535
+ throw err;
536
+ });
537
+ clients.set(cacheKey, p);
538
+ }
539
+ return p;
540
+ };
541
+
542
+ // When the invoking user hasn't connected this server, open a connection
543
+ // request targeting THEM (X-On-Behalf-Of-User) so the consent prompt lands
544
+ // in their inbox. The backend dedups pending requests, so retrying every
545
+ // turn is safe. ZIG-771.
546
+ const backendBase = (
547
+ transportConfig.baseUrl ||
548
+ process.env.BACKEND_URL ||
549
+ process.env.ZIGGS_BACKEND_URL ||
550
+ 'http://localhost:3000'
551
+ ).replace(/\/$/, '');
552
+ // App URL for the user-facing connect link (ZIG-790): api.ziggsai.com → ziggsai.com.
553
+ const appUrl = backendBase.includes('localhost')
554
+ ? 'http://localhost:1234'
555
+ : backendBase.replace(/\/\/api\./, '//');
556
+ const serverLabel = transportConfig.serverUrl
557
+ ? new URL(transportConfig.serverUrl).host
558
+ : 'the external service';
559
+ // Open a connection request for this user; returns its id so the caller can
560
+ // deep-link the user straight to it on the Connections page (ZIG-790).
561
+ const triggerConnectionRequest = async (userId: string): Promise<string | null> => {
562
+ if (!transportConfig.serverUrl) return null;
563
+ const operatorKey = transportConfig.operatorKey || process.env.ZIGGS_OPERATOR_KEY;
564
+ const res = await fetch(`${backendBase}/connections/mcp/requests`, {
565
+ method: 'POST',
566
+ headers: {
567
+ 'content-type': 'application/json',
568
+ authorization: `Bearer ${operatorKey}`,
569
+ 'x-agent-id': agentId,
570
+ 'x-on-behalf-of-user': userId,
571
+ },
572
+ body: JSON.stringify({
573
+ serverUrl: transportConfig.serverUrl,
574
+ tools: tools.map(t => t.name),
575
+ }),
576
+ });
577
+ const body = (await res.json().catch(() => null)) as { request?: { requestId?: string } } | null;
578
+ return body?.request?.requestId ?? null;
579
+ };
580
+
581
+ const caller: McpToolCaller = async (name, args, context) => {
582
+ const userId = typeof context.senderId === 'string' ? context.senderId : undefined;
583
+ if (!userId) {
584
+ throw new Error('per-user MCP tool call requires an invoking user (context.senderId is missing)');
585
+ }
586
+ // ZIG-831: for a delegated wake, senderId is the delegating agent, not the
587
+ // connection-owning end-user; pass the agreement so the gateway resolves
588
+ // the delegation root's user.
589
+ const onBehalfOfAgreementId =
590
+ typeof context.onBehalfOfAgreementId === 'string' ? context.onBehalfOfAgreementId : undefined;
591
+ // ZIG-832 (B): per-user resolution is intermittently flaky even when the
592
+ // connection is valid and resolvable — the same on-behalf call fails with
593
+ // NO_USER_CONNECTION on one wake and succeeds on the next. clientFor never
594
+ // caches a failed connect, so each attempt re-resolves from scratch. Retry
595
+ // a few times (with backoff) before surfacing the connect prompt, so a
596
+ // transient miss no longer fails the whole fetch step.
597
+ const MAX_ATTEMPTS = 3;
598
+ let lastErr: unknown;
599
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
600
+ try {
601
+ const c = await clientFor(userId, onBehalfOfAgreementId);
602
+ return (await c.callTool({ name, arguments: args })) as {
603
+ isError?: boolean;
604
+ content: McpContent[];
605
+ };
606
+ } catch (err) {
607
+ lastErr = err;
608
+ const resolutionMiss =
609
+ err instanceof ZiggsGatewayError && err.code === 'NO_USER_CONNECTION';
610
+ const transient = resolutionMiss || !(err instanceof ZiggsGatewayError);
611
+ if (attempt < MAX_ATTEMPTS && transient) {
612
+ console.warn(
613
+ `[McpAdapter] per-user ${name} attempt ${attempt}/${MAX_ATTEMPTS} failed (${(err as Error).message}); retrying with a fresh connection`,
614
+ );
615
+ await new Promise((r) => setTimeout(r, 500 * attempt));
616
+ continue;
617
+ }
618
+ break;
619
+ }
620
+ }
621
+ if (
622
+ lastErr instanceof ZiggsGatewayError &&
623
+ lastErr.code === 'NO_USER_CONNECTION' &&
624
+ transportConfig.serverUrl
625
+ ) {
626
+ const requestId = await triggerConnectionRequest(userId).catch(() => null);
627
+ const link = `${appUrl}/app/settings/connections${requestId ? `?request=${encodeURIComponent(requestId)}` : ''}`;
628
+ return {
629
+ content: [
630
+ {
631
+ type: 'text',
632
+ text: `ACTION NEEDED: the user has not connected ${serverLabel}. Ask them to approve the connection here: ${link} — then retry.`,
633
+ },
634
+ ],
635
+ };
636
+ }
637
+ throw lastErr;
638
+ };
639
+
640
+ const host = new AgentHost({
641
+ ...hostOptions,
642
+ workflow: workflow ?? buildDefaultWorkflow(hostOptions.description ?? '', tools),
643
+ tools: [...mapMcpTools(caller, tools), ...extraTools],
644
+ });
645
+ return {
646
+ host,
647
+ closeMcp: async () => {
648
+ await Promise.all(
649
+ [...clients.values()].map(p => p.then(c => c.close()).catch(() => {})),
650
+ );
651
+ },
652
+ toolNames: tools.map(t => t.name),
653
+ };
654
+ }
655
+
656
+ // ── Single-client path (stdio / http / brokered ziggs): discover tools at boot.
281
657
  const transport = buildTransport(transportConfig, { agentId: hostOptions.agentId });
282
658
  const client = new Client({ name: 'ziggs-mcp-agent', version: '1.0.0' });
283
-
284
659
  await client.connect(transport);
285
660
 
286
- const { tools: rawTools } = await client.listTools();
287
- const mcpTools = mapMcpTools(client, rawTools as McpTool[]);
288
-
289
- const resolvedWorkflow = workflow ?? buildDefaultWorkflow(hostOptions.description ?? '', rawTools as McpTool[]);
661
+ const rawTools = capTools((await client.listTools()).tools as McpTool[], hostOptions.agentId, maxTools, extraTools.length, allowedTools);
662
+ const caller: McpToolCaller = (name, args) =>
663
+ client.callTool({ name, arguments: args }) as Promise<{ isError?: boolean; content: McpContent[] }>;
664
+ const mcpTools = mapMcpTools(caller, rawTools);
290
665
 
666
+ const resolvedWorkflow = workflow ?? buildDefaultWorkflow(hostOptions.description ?? '', rawTools);
291
667
  const host = new AgentHost({
292
668
  ...hostOptions,
293
669
  workflow: resolvedWorkflow,
@@ -14,6 +14,13 @@ interface AdapterOptions {
14
14
  model?: string;
15
15
  }
16
16
 
17
+ /** OpenAI completion-token cap varies by model family (e.g. gpt-4o-mini max 16384). */
18
+ export function maxCompletionTokensForModel(model: string): number {
19
+ const m = model.toLowerCase();
20
+ if (m.includes('gpt-4o')) return 16384;
21
+ return 25000;
22
+ }
23
+
17
24
  export class OpenAIAdapter {
18
25
  private client: OpenAI;
19
26
  model: string;
@@ -99,11 +106,9 @@ export class OpenAIAdapter {
99
106
  model: this.model,
100
107
  messages: finalMessages,
101
108
  stream: false,
102
- // 25000 reserves room for hidden reasoning tokens on reasoning models
103
- // (gpt-5.x/o-series) — they're billed against this cap before any
104
- // visible content, so a low cap can exhaust the budget and return
105
- // empty content with finish_reason "length".
106
- max_completion_tokens: 25000,
109
+ // Reasoning models (gpt-5.x/o-series) need a high cap for hidden
110
+ // reasoning tokens; gpt-4o family is capped lower by the API.
111
+ max_completion_tokens: maxCompletionTokensForModel(this.model),
107
112
  response_format: responseFormat,
108
113
  ...(openAITools && { tools: openAITools }),
109
114
  ...restOptions,
@@ -162,21 +167,28 @@ export class OpenAIAdapter {
162
167
  async chatMessagesStream(
163
168
  messages: OpenAI.Chat.ChatCompletionMessageParam[],
164
169
  onChunk: (text: string) => void,
165
- ): Promise<string> {
170
+ ): Promise<{ text: string; usage: OpenAI.CompletionUsage | undefined }> {
166
171
  const stream = await this.client.chat.completions.create({
167
172
  model: this.model,
168
173
  messages,
169
174
  stream: true,
170
- max_completion_tokens: 25000,
175
+ // Without this, a streamed completion never returns a usage block — the
176
+ // streamed reply (often the largest output) would bill tokens that are
177
+ // counted nowhere (ZIG-813). The usage arrives on a final chunk whose
178
+ // `choices` is empty.
179
+ stream_options: { include_usage: true },
180
+ max_completion_tokens: maxCompletionTokensForModel(this.model),
171
181
  });
172
182
  let text = '';
183
+ let usage: OpenAI.CompletionUsage | undefined;
173
184
  for await (const chunk of stream) {
185
+ if (chunk.usage) usage = chunk.usage;
174
186
  const delta = chunk.choices[0]?.delta?.content;
175
187
  if (delta) {
176
188
  text += delta;
177
189
  onChunk(delta);
178
190
  }
179
191
  }
180
- return text;
192
+ return { text, usage };
181
193
  }
182
194
  }
@@ -1 +1,2 @@
1
1
  export { OpenAIAdapter } from './OpenAIAdapter.js';
2
+ export { AnthropicAdapter } from './AnthropicAdapter.js';
@@ -40,8 +40,18 @@ export interface TickOutput {
40
40
  state: string;
41
41
  /** Whether the machine settled at a parked state. */
42
42
  parked: boolean;
43
- /** Accumulated LLM call count and token usage for this tick. */
44
- metrics: { llmCalls: number; tokens: { total: number; input: number; output: number } };
43
+ /** True when a state-timeout outcome matched no transition this tick — the host must NOT re-arm. */
44
+ stateTimeoutUnhandled: boolean;
45
+ /**
46
+ * Accumulated LLM call count and token usage for this tick.
47
+ * `cacheRead` / `cacheCreation` are populated by the Claude brain (its usage
48
+ * exposes cache traffic, which is the bulk of real cost — ZIG-759/813); the
49
+ * FSM path leaves them undefined. `total` includes cache tokens when present.
50
+ */
51
+ metrics: {
52
+ llmCalls: number;
53
+ tokens: { total: number; input: number; output: number; cacheRead?: number; cacheCreation?: number };
54
+ };
45
55
  }
46
56
 
47
57
  /**
@@ -95,6 +105,7 @@ export class Agent {
95
105
  ctx: machine.ctx,
96
106
  state: machine.state,
97
107
  parked: machine.isParked,
108
+ stateTimeoutUnhandled: machine.stateTimeoutUnhandled,
98
109
  metrics: { llmCalls: machine.llmCalls, tokens: machine.tokens },
99
110
  };
100
111
  }