@ziggs-ai/agent-sdk 0.1.12 → 0.2.0

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 (218) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +41 -2
  3. package/dist/AgentHost.d.ts +201 -0
  4. package/dist/AgentHost.js +652 -0
  5. package/dist/adapters/AnthropicAdapter.d.ts +39 -0
  6. package/dist/adapters/AnthropicAdapter.js +200 -0
  7. package/dist/adapters/McpAdapter.d.ts +199 -0
  8. package/dist/adapters/McpAdapter.js +468 -0
  9. package/dist/adapters/OpenAIAdapter.d.ts +26 -0
  10. package/dist/adapters/OpenAIAdapter.js +158 -0
  11. package/dist/adapters/index.js +2 -0
  12. package/dist/agent/Agent.d.ts +78 -0
  13. package/dist/agent/Agent.js +58 -0
  14. package/dist/agent/ClaudeSdkAgent.d.ts +38 -0
  15. package/dist/agent/ClaudeSdkAgent.js +322 -0
  16. package/dist/agent/claudeCognition.d.ts +67 -0
  17. package/dist/agent/claudeCognition.js +103 -0
  18. package/dist/agent/claudeSdkProtocol.d.ts +11 -0
  19. package/dist/agent/claudeSdkTools.d.ts +19 -0
  20. package/dist/agent/claudeSdkTools.js +57 -0
  21. package/dist/agent/hostedAgentConnection.d.ts +15 -0
  22. package/dist/agent/hostedAgentConnection.js +29 -0
  23. package/dist/agent/toolManagerToSdkMcp.d.ts +12 -0
  24. package/dist/agent/toolManagerToSdkMcp.js +123 -0
  25. package/dist/brain/index.d.ts +50 -0
  26. package/dist/brain/index.js +45 -0
  27. package/dist/cognition/validateContext.d.ts +11 -0
  28. package/dist/cognition/validateContext.js +117 -0
  29. package/dist/context/applyEffects.d.ts +2 -0
  30. package/dist/context/applyEffects.js +89 -0
  31. package/dist/context/batch.d.ts +2 -0
  32. package/dist/context/batch.js +18 -0
  33. package/dist/context/classifyEnvelope.d.ts +1 -0
  34. package/dist/context/classifyEnvelope.js +58 -0
  35. package/dist/context/routingLabels.d.ts +4 -0
  36. package/dist/context/routingLabels.js +48 -0
  37. package/dist/defineAgent.d.ts +14 -0
  38. package/dist/defineAgent.js +68 -0
  39. package/dist/formatters/AgreementFormatter.d.ts +18 -0
  40. package/dist/formatters/AgreementFormatter.js +130 -0
  41. package/dist/formatters/HistoryFormatter.d.ts +26 -0
  42. package/dist/formatters/HistoryFormatter.js +173 -0
  43. package/dist/formatters/index.js +2 -0
  44. package/{src/index.ts → dist/index.d.ts} +7 -53
  45. package/dist/index.js +66 -0
  46. package/dist/ingress/normalizeIncoming.d.ts +65 -0
  47. package/dist/ingress/normalizeIncoming.js +88 -0
  48. package/dist/memory/MemoryStore.d.ts +55 -0
  49. package/dist/memory/MemoryStore.js +78 -0
  50. package/dist/pricing/fleetDefaults.d.ts +46 -0
  51. package/dist/pricing/fleetDefaults.js +168 -0
  52. package/dist/pricing/fleetEvalFree.d.ts +7 -0
  53. package/dist/pricing/fleetEvalFree.js +24 -0
  54. package/dist/pricing/fleetFreeTierA.gen.d.ts +6 -0
  55. package/{src/pricing/fleetFreeTierA.gen.ts → dist/pricing/fleetFreeTierA.gen.js} +5 -6
  56. package/dist/pricing/fleetTierByAgentId.gen.d.ts +7 -0
  57. package/dist/pricing/fleetTierByAgentId.gen.js +768 -0
  58. package/dist/runtime/AgentMachine.d.ts +143 -0
  59. package/dist/runtime/AgentMachine.js +400 -0
  60. package/dist/runtime/PromptBuilder.d.ts +96 -0
  61. package/dist/runtime/PromptBuilder.js +439 -0
  62. package/{src/runtime/bootstrapCtx.ts → dist/runtime/bootstrapCtx.d.ts} +1 -22
  63. package/dist/runtime/bootstrapCtx.js +37 -0
  64. package/dist/runtime/buildOutcome.d.ts +68 -0
  65. package/dist/runtime/buildOutcome.js +464 -0
  66. package/dist/runtime/defaults.d.ts +54 -0
  67. package/dist/runtime/defaults.js +47 -0
  68. package/dist/runtime/deriveRespondsToProposals.d.ts +9 -0
  69. package/dist/runtime/deriveRespondsToProposals.js +38 -0
  70. package/dist/runtime/kickoff.d.ts +15 -0
  71. package/dist/runtime/kickoff.js +112 -0
  72. package/dist/runtime/runMechanical.d.ts +25 -0
  73. package/dist/runtime/runMechanical.js +74 -0
  74. package/dist/runtime/runTurn.d.ts +63 -0
  75. package/dist/runtime/runTurn.js +800 -0
  76. package/dist/runtime/validateWorkflow.d.ts +17 -0
  77. package/dist/runtime/validateWorkflow.js +209 -0
  78. package/dist/server/ConnectionPool.d.ts +68 -0
  79. package/dist/server/ConnectionPool.js +166 -0
  80. package/dist/server/EventQueue.d.ts +33 -0
  81. package/dist/server/EventQueue.js +98 -0
  82. package/dist/server/InboxCatchUp.d.ts +24 -0
  83. package/dist/server/InboxCatchUp.js +213 -0
  84. package/dist/server/OutboxBuffer.d.ts +33 -0
  85. package/dist/server/OutboxBuffer.js +68 -0
  86. package/dist/server/SeenMessages.d.ts +13 -0
  87. package/dist/server/SeenMessages.js +31 -0
  88. package/dist/server/StateTimers.d.ts +34 -0
  89. package/dist/server/StateTimers.js +70 -0
  90. package/dist/server/ZiggsEffectHandler.d.ts +79 -0
  91. package/dist/server/ZiggsEffectHandler.js +319 -0
  92. package/dist/server/agreements/AgreementService.d.ts +50 -0
  93. package/dist/server/agreements/AgreementService.js +85 -0
  94. package/dist/server/createHealthServer.d.ts +7 -0
  95. package/dist/server/createHealthServer.js +75 -0
  96. package/dist/server/proactive/ProactiveTrigger.d.ts +33 -0
  97. package/dist/server/proactive/ProactiveTrigger.js +71 -0
  98. package/dist/server/runLauncher.d.ts +28 -0
  99. package/dist/server/runLauncher.js +93 -0
  100. package/dist/server/tasks/TaskService.d.ts +25 -0
  101. package/dist/server/tasks/TaskService.js +103 -0
  102. package/dist/server/tasks/index.js +1 -0
  103. package/dist/server/telemetryIngest.d.ts +24 -0
  104. package/dist/server/telemetryIngest.js +62 -0
  105. package/dist/server/tools/index.d.ts +24 -0
  106. package/{src/server/tools/index.ts → dist/server/tools/index.js} +4 -24
  107. package/dist/server/tools/tier1/protocolRunner.d.ts +39 -0
  108. package/dist/server/tools/tier1/protocolRunner.js +288 -0
  109. package/dist/server/tools/tier1/protocolTools.d.ts +12 -0
  110. package/dist/server/tools/tier1/protocolTools.js +37 -0
  111. package/dist/server/tools/tier2/connectionTools.d.ts +4 -0
  112. package/dist/server/tools/tier2/connectionTools.js +63 -0
  113. package/dist/server/tools/tier2/contextTools.d.ts +4 -0
  114. package/dist/server/tools/tier2/contextTools.js +46 -0
  115. package/dist/server/tools/tier2/discoveryTools.d.ts +4 -0
  116. package/dist/server/tools/tier2/discoveryTools.js +25 -0
  117. package/dist/server/tools/tier2/marketplaceTools.d.ts +3 -0
  118. package/dist/server/tools/tier2/marketplaceTools.js +22 -0
  119. package/dist/server/tools/tier2/paymentTools.d.ts +12 -0
  120. package/dist/server/tools/tier2/paymentTools.js +165 -0
  121. package/dist/server/ziggsconnect/ZiggsConnectClient.d.ts +35 -0
  122. package/dist/server/ziggsconnect/ZiggsConnectClient.js +95 -0
  123. package/dist/server/ziggscontext/ZiggsContextClient.d.ts +48 -0
  124. package/dist/server/ziggscontext/ZiggsContextClient.js +90 -0
  125. package/dist/server/ziggspay/ZiggsPayClient.d.ts +82 -0
  126. package/dist/server/ziggspay/ZiggsPayClient.js +188 -0
  127. package/dist/shared/ids.d.ts +1 -0
  128. package/dist/shared/ids.js +3 -0
  129. package/dist/shared/runtimeLog.d.ts +18 -0
  130. package/dist/shared/runtimeLog.js +68 -0
  131. package/dist/shared/types.d.ts +22 -0
  132. package/dist/shared/types.js +23 -0
  133. package/dist/tasks/protocolRegistry.d.ts +16 -0
  134. package/dist/tasks/protocolRegistry.js +20 -0
  135. package/dist/tools/ToolManager.d.ts +12 -0
  136. package/dist/tools/ToolManager.js +74 -0
  137. package/dist/tools/ToolProvider.d.ts +6 -0
  138. package/dist/tools/ToolProvider.js +21 -0
  139. package/dist/tools/defineTool.d.ts +27 -0
  140. package/dist/tools/defineTool.js +62 -0
  141. package/{src/tools/index.ts → dist/tools/index.d.ts} +0 -1
  142. package/dist/tools/index.js +6 -0
  143. package/dist/tools/recordReport.d.ts +41 -0
  144. package/dist/tools/recordReport.js +30 -0
  145. package/dist/types.d.ts +466 -0
  146. package/dist/types.js +7 -0
  147. package/dist/utils/jsonExtractor.d.ts +2 -0
  148. package/dist/utils/jsonExtractor.js +111 -0
  149. package/package.json +13 -5
  150. package/src/AgentHost.ts +0 -814
  151. package/src/adapters/AnthropicAdapter.ts +0 -238
  152. package/src/adapters/McpAdapter.ts +0 -678
  153. package/src/adapters/OpenAIAdapter.ts +0 -194
  154. package/src/agent/Agent.ts +0 -112
  155. package/src/agent/ClaudeSdkAgent.ts +0 -401
  156. package/src/agent/claudeCognition.ts +0 -139
  157. package/src/agent/claudeSdkTools.ts +0 -81
  158. package/src/agent/hostedAgentConnection.ts +0 -41
  159. package/src/agent/toolManagerToSdkMcp.ts +0 -136
  160. package/src/cognition/validateContext.ts +0 -95
  161. package/src/context/applyEffects.ts +0 -80
  162. package/src/context/batch.ts +0 -19
  163. package/src/context/classifyEnvelope.ts +0 -38
  164. package/src/context/routingLabels.ts +0 -46
  165. package/src/defineAgent.ts +0 -77
  166. package/src/formatters/AgreementFormatter.ts +0 -111
  167. package/src/formatters/HistoryFormatter.ts +0 -172
  168. package/src/ingress/normalizeIncoming.ts +0 -162
  169. package/src/memory/MemoryStore.ts +0 -104
  170. package/src/pricing/fleetDefaults.ts +0 -225
  171. package/src/pricing/fleetEvalFree.ts +0 -24
  172. package/src/pricing/fleetTierByAgentId.gen.ts +0 -775
  173. package/src/runtime/AgentMachine.ts +0 -484
  174. package/src/runtime/PromptBuilder.ts +0 -522
  175. package/src/runtime/buildOutcome.ts +0 -563
  176. package/src/runtime/defaults.ts +0 -86
  177. package/src/runtime/deriveRespondsToProposals.ts +0 -35
  178. package/src/runtime/kickoff.ts +0 -117
  179. package/src/runtime/runMechanical.ts +0 -106
  180. package/src/runtime/runTurn.ts +0 -870
  181. package/src/runtime/validateWorkflow.ts +0 -221
  182. package/src/server/ConnectionPool.ts +0 -206
  183. package/src/server/EventQueue.ts +0 -133
  184. package/src/server/InboxCatchUp.ts +0 -291
  185. package/src/server/OutboxBuffer.ts +0 -90
  186. package/src/server/SeenMessages.ts +0 -27
  187. package/src/server/StateTimers.ts +0 -85
  188. package/src/server/ZiggsEffectHandler.ts +0 -427
  189. package/src/server/agreements/AgreementService.ts +0 -118
  190. package/src/server/createHealthServer.ts +0 -85
  191. package/src/server/proactive/ProactiveTrigger.ts +0 -83
  192. package/src/server/runLauncher.ts +0 -146
  193. package/src/server/tasks/TaskService.ts +0 -111
  194. package/src/server/telemetryIngest.ts +0 -91
  195. package/src/server/tools/tier1/protocolRunner.ts +0 -353
  196. package/src/server/tools/tier1/protocolTools.ts +0 -114
  197. package/src/server/tools/tier2/connectionTools.ts +0 -75
  198. package/src/server/tools/tier2/contextTools.ts +0 -63
  199. package/src/server/tools/tier2/discoveryTools.ts +0 -34
  200. package/src/server/tools/tier2/marketplaceTools.ts +0 -27
  201. package/src/server/tools/tier2/paymentTools.ts +0 -170
  202. package/src/server/ziggsconnect/ZiggsConnectClient.ts +0 -126
  203. package/src/server/ziggscontext/ZiggsContextClient.ts +0 -129
  204. package/src/server/ziggspay/ZiggsPayClient.ts +0 -193
  205. package/src/shared/ids.ts +0 -3
  206. package/src/shared/runtimeLog.ts +0 -72
  207. package/src/shared/types.ts +0 -29
  208. package/src/tasks/protocolRegistry.ts +0 -25
  209. package/src/tools/ToolManager.ts +0 -95
  210. package/src/tools/ToolProvider.ts +0 -19
  211. package/src/tools/defineTool.ts +0 -90
  212. package/src/tools/recordReport.ts +0 -82
  213. package/src/types.ts +0 -483
  214. package/src/utils/jsonExtractor.ts +0 -100
  215. /package/{src/adapters/index.ts → dist/adapters/index.d.ts} +0 -0
  216. /package/{src/agent/claudeSdkProtocol.ts → dist/agent/claudeSdkProtocol.js} +0 -0
  217. /package/{src/formatters/index.ts → dist/formatters/index.d.ts} +0 -0
  218. /package/{src/server/tasks/index.ts → dist/server/tasks/index.d.ts} +0 -0
@@ -1,238 +0,0 @@
1
- import Anthropic from '@anthropic-ai/sdk';
2
- import type { LlmMessage, LlmResponse, LlmToolCall, LlmToolSchema } from '../types.js';
3
- import { runtimeLog } from '../shared/runtimeLog.js';
4
-
5
- interface AdapterOptions {
6
- key?: string;
7
- model?: string;
8
- }
9
-
10
- // Claude 4.7+ models reject sampling params (temperature/top_p/top_k) with a
11
- // 400 and run without thinking when the `thinking` param is omitted. We omit
12
- // both on purpose: the SDK's LlmMessage history cannot round-trip thinking
13
- // blocks through the tool loop, so thinking must stay off.
14
- const MAX_COMPLETION_TOKENS = 16000;
15
-
16
- /**
17
- * Anthropic adapter satisfying the same LlmAdapter contract as OpenAIAdapter:
18
- * OpenAI-wire-shaped LlmMessage[] in, { content, tool_calls, usage } out.
19
- * Selected by AgentHost when the configured model id starts with "claude".
20
- */
21
- export class AnthropicAdapter {
22
- private client: Anthropic;
23
- model: string;
24
-
25
- constructor({ key, model = 'claude-opus-4-8' }: AdapterOptions) {
26
- this.client = new Anthropic({ apiKey: key });
27
- this.model = model;
28
- }
29
-
30
- async chat(
31
- prompt: string,
32
- tools: LlmToolSchema[] = [],
33
- _temperature = 0,
34
- systemHints: LlmMessage[] = [],
35
- options: Record<string, unknown> = {},
36
- ): Promise<LlmResponse> {
37
- const messages: LlmMessage[] = [
38
- { role: 'system', content: 'Respond with valid JSON.' },
39
- ...systemHints,
40
- { role: 'user', content: prompt },
41
- ];
42
- return this.chatMessages(messages, tools, options);
43
- }
44
-
45
- async chatMessages(
46
- messages: LlmMessage[],
47
- tools: LlmToolSchema[] = [],
48
- _options: Record<string, unknown> = {},
49
- ): Promise<LlmResponse> {
50
- const { system, anthropicMessages } = translateMessages(messages);
51
- const anthropicTools = toAnthropicTools(tools);
52
-
53
- try {
54
- const res = await this.client.messages.create({
55
- model: this.model,
56
- max_tokens: MAX_COMPLETION_TOKENS,
57
- ...(system ? { system } : {}),
58
- messages: anthropicMessages,
59
- ...(anthropicTools ? { tools: anthropicTools } : {}),
60
- });
61
-
62
- if (res.stop_reason === 'refusal') {
63
- throw new Error(`LLM refused the request (stop_reason=refusal)`);
64
- }
65
-
66
- const content = res.content
67
- .filter((b): b is Anthropic.TextBlock => b.type === 'text')
68
- .map(b => b.text)
69
- .join('')
70
- .trim() || null;
71
- const toolCalls: LlmToolCall[] | null = (() => {
72
- const uses = res.content.filter((b): b is Anthropic.ToolUseBlock => b.type === 'tool_use');
73
- if (!uses.length) return null;
74
- return uses.map(u => ({
75
- id: u.id,
76
- function: { name: u.name, arguments: JSON.stringify(u.input ?? {}) },
77
- }));
78
- })();
79
-
80
- if (!content && !toolCalls && res.stop_reason === 'max_tokens') {
81
- throw new Error(
82
- `LLM returned no usable output — completion token budget exhausted before any content (stop_reason=max_tokens)`,
83
- );
84
- }
85
-
86
- return {
87
- content: content ?? undefined,
88
- tool_calls: toolCalls ?? undefined,
89
- usage: res.usage
90
- ? {
91
- prompt_tokens: res.usage.input_tokens,
92
- completion_tokens: res.usage.output_tokens,
93
- total_tokens: res.usage.input_tokens + res.usage.output_tokens,
94
- }
95
- : undefined,
96
- };
97
- } catch (error) {
98
- const err = error as Error & { status?: number };
99
- runtimeLog.error('AnthropicAdapter', `LLM API call failed: ${err.message}`, {
100
- model: this.model,
101
- error: err.message,
102
- status: err.status ?? 'unknown',
103
- });
104
- throw error;
105
- }
106
- }
107
-
108
- async chatMessagesStream(
109
- messages: LlmMessage[],
110
- onChunk: (text: string) => void,
111
- ): Promise<{ text: string; usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number } | undefined }> {
112
- const { system, anthropicMessages } = translateMessages(messages);
113
- const stream = this.client.messages.stream({
114
- model: this.model,
115
- max_tokens: MAX_COMPLETION_TOKENS,
116
- ...(system ? { system } : {}),
117
- messages: anthropicMessages,
118
- });
119
- let text = '';
120
- stream.on('text', (delta) => {
121
- text += delta;
122
- onChunk(delta);
123
- });
124
- const final = await stream.finalMessage();
125
- const u = final.usage;
126
- // Fold cache read/creation into prompt tokens so the streamed reply is not
127
- // undercounted (cache traffic was the bulk of the ZIG-759 drain).
128
- const usage = u
129
- ? {
130
- prompt_tokens: (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0),
131
- completion_tokens: u.output_tokens ?? 0,
132
- total_tokens:
133
- (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) + (u.output_tokens ?? 0),
134
- }
135
- : undefined;
136
- return { text, usage };
137
- }
138
- }
139
-
140
- /**
141
- * Convert the runtime's tool list into Anthropic's `tools` param.
142
- *
143
- * The declared `LlmToolSchema` type (`{ type, function }`) is a lie at runtime:
144
- * `runTurn` launders `ToolDefinition[]` (shape `{ schema: { function } }`)
145
- * through an `as unknown as LlmToolSchema[]` cast before it reaches any adapter.
146
- * OpenAIAdapter already reads `t.schema.function || t.schema`; this must do the
147
- * same, or every claude-backed agent whose state exposes ≥1 tool crashes on
148
- * `t.function` being undefined ("Cannot read properties of undefined (reading
149
- * 'name')"). Both shapes are accepted so raw wire-shaped tools also work.
150
- */
151
- export function toAnthropicTools(tools: LlmToolSchema[] = []): Anthropic.Tool[] | undefined {
152
- if (!tools.length) return undefined;
153
- return tools.map(t => {
154
- const td = t as unknown as {
155
- schema?: { function?: Record<string, unknown> };
156
- function?: Record<string, unknown>;
157
- };
158
- const fn = (td.schema?.function ?? td.function ?? {}) as Record<string, unknown>;
159
- return {
160
- name: fn['name'] as string,
161
- description: (fn['description'] as string) ?? '',
162
- input_schema: (fn['parameters'] ?? { type: 'object' }) as Anthropic.Tool.InputSchema,
163
- };
164
- });
165
- }
166
-
167
- /**
168
- * OpenAI-wire-shaped LlmMessage[] → Anthropic { system, messages }.
169
- * - system messages concatenate into the top-level system param
170
- * - assistant tool_calls become tool_use blocks (arguments JSON-parsed)
171
- * - role:"tool" results become user-turn tool_result blocks
172
- * Consecutive same-role turns are merged (Anthropic requires alternation to
173
- * start with user; the API tolerates consecutive same-role, but tool_result
174
- * blocks must open the user turn that answers a tool_use turn).
175
- */
176
- function translateMessages(messages: LlmMessage[]): {
177
- system: string | undefined;
178
- anthropicMessages: Anthropic.MessageParam[];
179
- } {
180
- const systemParts: string[] = [];
181
- const out: Anthropic.MessageParam[] = [];
182
-
183
- for (const m of messages) {
184
- if (m.role === 'system') {
185
- if (m.content) systemParts.push(m.content);
186
- continue;
187
- }
188
- if (m.role === 'tool') {
189
- const block: Anthropic.ToolResultBlockParam = {
190
- type: 'tool_result',
191
- tool_use_id: m.tool_call_id ?? '',
192
- content: m.content ?? '',
193
- };
194
- const last = out[out.length - 1];
195
- if (last && last.role === 'user' && Array.isArray(last.content)) {
196
- (last.content as Anthropic.ContentBlockParam[]).push(block);
197
- } else {
198
- out.push({ role: 'user', content: [block] });
199
- }
200
- continue;
201
- }
202
- if (m.role === 'assistant' && m.tool_calls?.length) {
203
- const blocks: Anthropic.ContentBlockParam[] = [];
204
- if (m.content) blocks.push({ type: 'text', text: m.content });
205
- for (const tc of m.tool_calls) {
206
- blocks.push({
207
- type: 'tool_use',
208
- id: tc.id,
209
- name: tc.function.name,
210
- input: safeParseJson(tc.function.arguments),
211
- });
212
- }
213
- out.push({ role: 'assistant', content: blocks });
214
- continue;
215
- }
216
- out.push({ role: m.role, content: m.content ?? '' });
217
- }
218
-
219
- if (!out.length || out[0].role !== 'user') {
220
- out.unshift({ role: 'user', content: '(session start)' });
221
- }
222
-
223
- return {
224
- system: systemParts.length ? systemParts.join('\n\n') : undefined,
225
- anthropicMessages: out,
226
- };
227
- }
228
-
229
- function safeParseJson(s: string): Record<string, unknown> {
230
- try {
231
- const v = JSON.parse(s);
232
- return typeof v === 'object' && v !== null ? v : {};
233
- } catch {
234
- // Malformed arguments string from a prior turn's history: replaying it as
235
- // an empty input beats crashing the whole turn on someone else's output.
236
- return {};
237
- }
238
- }