@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
@@ -0,0 +1,466 @@
1
+ /**
2
+ * Foundation types for the agent SDK workflow runtime.
3
+ *
4
+ * One outcome vocabulary, one ctx shape, one transition signature.
5
+ * Every state — parked or thinking — re-enters with exactly one Outcome.
6
+ */
7
+ export interface AgreementRef {
8
+ agreementId: string;
9
+ parties?: {
10
+ creator?: string;
11
+ provider?: string;
12
+ payer?: string;
13
+ proposedTo?: string;
14
+ };
15
+ proposal?: {
16
+ status?: 'pending' | 'approved' | 'rejected' | 'cancelled';
17
+ };
18
+ money?: {
19
+ price?: number;
20
+ paymentStatus?: string;
21
+ };
22
+ }
23
+ export interface TaskRef {
24
+ taskId: string;
25
+ agreementId?: string;
26
+ agreement?: AgreementRef;
27
+ state?: string;
28
+ description?: string;
29
+ parentTaskId?: string;
30
+ executorId?: string;
31
+ assigneeId?: string | null;
32
+ /** Work product set by task_update (safeJsonStringify'd string on the wire). */
33
+ result?: unknown;
34
+ proposal?: {
35
+ status?: 'pending' | 'approved' | 'rejected' | 'cancelled';
36
+ };
37
+ proposedToIsYou?: boolean;
38
+ providerIsYou?: boolean;
39
+ creatorIsYou?: boolean;
40
+ payerIsYou?: boolean;
41
+ }
42
+ export interface ProposalRef {
43
+ agreementId: string;
44
+ agreement?: AgreementRef;
45
+ }
46
+ export type OutcomeKind = 'enter' | 'wait' | 'state-timeout' | 'message-sent' | 'message-received' | 'task-assigned' | 'task-delegated' | 'task-closed' | 'subtask-finished' | 'proposal-made' | 'proposal-resolved' | 'tool-result' | 'error' | 'extension';
47
+ export type Outcome = {
48
+ kind: 'enter';
49
+ } | {
50
+ kind: 'wait';
51
+ } | {
52
+ kind: 'state-timeout';
53
+ state: string;
54
+ waitedMs: number;
55
+ } | {
56
+ kind: 'message-sent';
57
+ text?: string;
58
+ receiverId?: string;
59
+ } | {
60
+ kind: 'message-received';
61
+ text?: string;
62
+ senderId?: string;
63
+ senderType?: string;
64
+ } | {
65
+ kind: 'task-assigned';
66
+ task: TaskRef;
67
+ } | {
68
+ kind: 'task-delegated';
69
+ task: TaskRef;
70
+ } | {
71
+ kind: 'task-closed';
72
+ status: 'completed' | 'failed';
73
+ result?: unknown;
74
+ } | {
75
+ kind: 'subtask-finished';
76
+ status: 'completed' | 'failed';
77
+ task: TaskRef;
78
+ result?: unknown;
79
+ } | {
80
+ kind: 'proposal-made';
81
+ proposal: ProposalRef;
82
+ } | {
83
+ kind: 'proposal-resolved';
84
+ action: 'approve' | 'reject';
85
+ proposal: ProposalRef;
86
+ /**
87
+ * True when THIS agent made the proposal being resolved. Computed in
88
+ * AgentMachine._handleFrame by matching proposal.agreementId against
89
+ * ctx.pendingProposalAgreementId BEFORE applyOutcomeToCtx clears it —
90
+ * wire frames carry no trustworthy proposer field (agreement_lifecycle
91
+ * drops `parties` at ingress, and parties.creator is a principal id,
92
+ * not an agentId). Drives the injected agreement-kickoff default.
93
+ */
94
+ proposedByMe: boolean;
95
+ } | {
96
+ kind: 'tool-result';
97
+ tool: string;
98
+ result: unknown;
99
+ } | {
100
+ kind: 'error';
101
+ source: 'llm' | 'tool' | 'protocol' | 'validation' | 'unknown';
102
+ cause: unknown;
103
+ retryable: boolean;
104
+ } | {
105
+ kind: 'extension';
106
+ name: string;
107
+ payload: unknown;
108
+ };
109
+ /**
110
+ * A session is the Server-side abstraction the Agent operates against:
111
+ * `{ sessionId, ctx, queue, parked }`. `Identity` is the Agent's view of
112
+ * which session this tick belongs to. `sessionId` is opaque to the Agent —
113
+ * it's a string the Server uses to route inbound events and outbound
114
+ * effects. (Today, the Ziggs transport derives sessionId from `chatId` at
115
+ * the wire boundary; non-chat surfaces will produce sessionIds of other
116
+ * shapes.)
117
+ */
118
+ export interface Identity {
119
+ agentId: string;
120
+ sessionId: string;
121
+ laneKey: string;
122
+ }
123
+ export interface HistoryEntry {
124
+ entryType?: string;
125
+ text?: string;
126
+ sender?: {
127
+ id?: string;
128
+ type?: string;
129
+ };
130
+ receiver?: {
131
+ id?: string;
132
+ };
133
+ timestamp?: number;
134
+ [key: string]: unknown;
135
+ }
136
+ export interface ToolResultEntry {
137
+ tool: string;
138
+ result?: unknown;
139
+ error?: string;
140
+ }
141
+ export interface PendingSubtask {
142
+ /** Executor the task was placed with; null only when the spawn result carried
143
+ * no executor identity (open/broadcast agreement task not yet claimed). */
144
+ agentId: string | null;
145
+ spawnedAt: number;
146
+ }
147
+ export interface CollectedSubtaskResult {
148
+ taskId: string;
149
+ agentId: string | null;
150
+ status: 'completed' | 'failed';
151
+ /** task.result from the finishing event; null when the event carried none. */
152
+ result: unknown;
153
+ }
154
+ /**
155
+ * Per-lane runtime state. Outcome is "what just happened"; Ctx is "what I know."
156
+ *
157
+ * Persistent identifiers (activeAgreementId, pendingProposalAgreementId,
158
+ * pendingSubtasks) survive across outcomes — they're the memory of which
159
+ * agreement the agent is currently bound to and which subtasks it's awaiting.
160
+ */
161
+ export interface Ctx {
162
+ identity: Identity;
163
+ activeAgreementId: string | null;
164
+ activeTaskId: string | null;
165
+ pendingProposalAgreementId: string | null;
166
+ delegatedAgreementIds: string[];
167
+ /** Durable barrier for orchestration: every spawned-but-unfinished subtask, keyed by taskId. */
168
+ pendingSubtasks: Record<string, PendingSubtask>;
169
+ /** Every finished subtask of the current engagement, arrival order. Synthesis prompts render ALL of these. */
170
+ collectedResults: CollectedSubtaskResult[];
171
+ toolResults: ToolResultEntry[];
172
+ lastOutcome: Outcome;
173
+ /** Claude Agent SDK session id for resume across ticks (claude-sdk cognition only). */
174
+ claudeSessionId?: string;
175
+ /**
176
+ * Recent wake timestamps (epoch ms) for this lane (claude-sdk cognition
177
+ * only). Backstop circuit breaker: if a lane wakes faster than any real
178
+ * traffic could drive it, the brain skips the LLM instead of burning the
179
+ * fleet key on a wake storm.
180
+ */
181
+ recentWakes?: number[];
182
+ }
183
+ export interface PromptDef {
184
+ role?: string;
185
+ goal?: string;
186
+ context?: string;
187
+ constraints?: string;
188
+ }
189
+ export interface ActionPrompt {
190
+ instruction: string;
191
+ format?: string;
192
+ when?: string;
193
+ examples?: Array<{
194
+ scenario?: string;
195
+ input?: string;
196
+ output?: string;
197
+ query?: string;
198
+ }>;
199
+ }
200
+ /**
201
+ * `produces` is the outcome-kind contract for an action. Static form for
202
+ * actions that always emit the same kind (most common); function form for
203
+ * tool-bound actions where the result determines the kind (e.g. success vs
204
+ * error). The runtime composes the kind with action metadata to build the
205
+ * full Outcome.
206
+ */
207
+ export type ProducesFn = (result: unknown, args: unknown) => OutcomeKind;
208
+ export type Produces = OutcomeKind | ProducesFn;
209
+ export interface Action {
210
+ prompt: ActionPrompt;
211
+ tool?: string | null;
212
+ produces: Produces;
213
+ /**
214
+ * When true, the tool loop exits immediately after this action's tool result,
215
+ * even if the result is non-terminal. Prevents the LLM from issuing additional
216
+ * tool calls in the same turn (e.g. calling agreement_subcontract right after
217
+ * agent_search before the FSM can route to evaluatingCandidates).
218
+ */
219
+ terminatesLoop?: boolean;
220
+ }
221
+ export interface Transition {
222
+ to: string;
223
+ when?: (outcome: Outcome, ctx: Ctx) => boolean;
224
+ }
225
+ export interface ParkedState {
226
+ kind: 'parked';
227
+ /**
228
+ * Liveness timer. When the machine settles in this state and no event
229
+ * arrives on the lane within timeoutMs, the host wakes the lane with a
230
+ * { kind: 'state-timeout', state, waitedMs } outcome so a transition can
231
+ * route to a recovery/nudge state. If no transition matches, the machine
232
+ * parks loudly (runtimeLog.error) and the timer is NOT re-armed. Countdown
233
+ * starts when the tick settles and resets on any event for the lane.
234
+ * In-memory only: lost on process restart; re-armed by the next real event
235
+ * that ticks the lane.
236
+ */
237
+ timeoutMs?: number;
238
+ transitions: Transition[];
239
+ }
240
+ export interface ThinkingState {
241
+ kind: 'thinking';
242
+ prompt: PromptDef;
243
+ actions: Record<string, Action>;
244
+ transitions: Transition[];
245
+ /**
246
+ * Opt out of the validateWorkflow warning that flags thinking states
247
+ * missing a `wait` action / activeWait fallthrough. Use sparingly — silent
248
+ * states that loop on themselves are usually a bug.
249
+ */
250
+ allowNoWait?: boolean;
251
+ }
252
+ /**
253
+ * ZIG-764: fixed tool invoke with no LLM turn. Entered after transitions
254
+ * (e.g. task-assigned → executing); runs `tool` once and emits `produces`.
255
+ */
256
+ export interface MechanicalState {
257
+ kind: 'mechanical';
258
+ tool: string;
259
+ args?: Record<string, unknown>;
260
+ buildArgs?: (ctx: Ctx, outcome: Outcome) => Record<string, unknown>;
261
+ produces: Produces;
262
+ transitions: Transition[];
263
+ }
264
+ export type State = ParkedState | ThinkingState | MechanicalState;
265
+ export interface Workflow {
266
+ id: string;
267
+ description: string;
268
+ initial: string;
269
+ states: Record<string, State>;
270
+ }
271
+ export interface LlmToolCall {
272
+ id: string;
273
+ function: {
274
+ name: string;
275
+ arguments: string;
276
+ };
277
+ }
278
+ export interface LlmMessage {
279
+ role: 'system' | 'user' | 'assistant' | 'tool';
280
+ content?: string;
281
+ tool_calls?: LlmToolCall[];
282
+ tool_call_id?: string;
283
+ }
284
+ export interface LlmToolSchema {
285
+ type: 'function';
286
+ function: {
287
+ name: string;
288
+ description?: string;
289
+ parameters?: unknown;
290
+ };
291
+ }
292
+ export interface LlmResponse {
293
+ content?: string;
294
+ tool_calls?: LlmToolCall[];
295
+ usage?: {
296
+ total_tokens?: number;
297
+ prompt_tokens?: number;
298
+ completion_tokens?: number;
299
+ totalTokens?: number;
300
+ promptTokens?: number;
301
+ completionTokens?: number;
302
+ };
303
+ }
304
+ export interface ContextSnapshot {
305
+ history: HistoryEntry[];
306
+ agreements: unknown[];
307
+ agents: unknown[];
308
+ users: unknown[];
309
+ timelineSummary?: string | null;
310
+ latestSequence?: string | null;
311
+ unavailable?: boolean;
312
+ /**
313
+ * The session's chat no longer resolves on the backend (messages read
314
+ * 404'd) — deleted or never visible to this agent. Message-triggered wakes
315
+ * check this and skip the LLM instead of reasoning over a fabricated empty
316
+ * history. Agreement-keyed lanes also set it (their sessionId is not a
317
+ * chat), so it only gates message wakes, never task lanes.
318
+ */
319
+ chatMissing?: boolean;
320
+ /** Index signature so PromptBuilder's `ServerContext` can accept it directly. */
321
+ [key: string]: unknown;
322
+ }
323
+ export interface ReadContextOpts {
324
+ maxMessages?: number;
325
+ }
326
+ /**
327
+ * Result of executing a single tool. Tool execution may emit multiple
328
+ * "events" (terminal markers like `message_sent`, `waited`, etc.) that the
329
+ * cognition loop inspects to decide whether to keep looping. Those carry
330
+ * through here as `events`; `result` is the value returned to the LLM.
331
+ */
332
+ export interface ToolCallResult {
333
+ ok: boolean;
334
+ result?: unknown;
335
+ error?: string;
336
+ events?: unknown[];
337
+ /**
338
+ * Summed token usage of any nested LLM call the tool made (e.g. llmTool).
339
+ * Threaded up so the turn's authoritative token count (machine.tokens ->
340
+ * result.metrics) includes tool-internal spend rather than leaking it (ZIG-813).
341
+ */
342
+ usage?: LlmResponse['usage'];
343
+ }
344
+ export interface RecordedEntry {
345
+ kind: string;
346
+ text?: string;
347
+ [k: string]: unknown;
348
+ }
349
+ import type { MemoryStore } from './memory/MemoryStore.js';
350
+ export type EffectKind = 'read-context' | 'llm-call' | 'stream-text' | 'tool-call' | 'send-message' | 'record-event';
351
+ export type Effect = {
352
+ kind: 'read-context';
353
+ sessionId: string;
354
+ opts?: ReadContextOpts;
355
+ } | {
356
+ kind: 'llm-call';
357
+ messages: LlmMessage[];
358
+ tools: LlmToolSchema[];
359
+ /** Chat/session id for monitoring ingest (ZIG-360). */
360
+ sessionId?: string;
361
+ /** Per-turn UUID grouping all LLM + tool calls in one turn (ZIG-440). */
362
+ runId?: string;
363
+ /** FSM state name at the time of this call (ZIG-440). */
364
+ stateId?: string;
365
+ } | {
366
+ kind: 'stream-text';
367
+ sessionId: string;
368
+ receiverId: string;
369
+ /** Pre-allocated messageId shared across all chunks and the final send-message. */
370
+ messageId: string;
371
+ messages: LlmMessage[];
372
+ } | {
373
+ kind: 'tool-call';
374
+ sessionId: string;
375
+ name: string;
376
+ args: unknown;
377
+ memory?: MemoryStore;
378
+ senderId?: string;
379
+ senderType?: string;
380
+ /**
381
+ * Agreement this tool call is acting under (ZIG-831). For a delegated
382
+ * per-user MCP call, `senderId` is the delegating agent, not the end-user
383
+ * who owns the connection; this lets the gateway resolve the delegation
384
+ * root's user. Sourced from the waking task event's `result.agreementId`.
385
+ */
386
+ onBehalfOfAgreementId?: string;
387
+ /** Per-turn UUID (ZIG-440). */
388
+ runId?: string;
389
+ /** FSM state name (ZIG-440). */
390
+ stateId?: string;
391
+ } | {
392
+ kind: 'send-message';
393
+ sessionId: string;
394
+ receiverId: string;
395
+ text: string;
396
+ messageId?: string;
397
+ } | {
398
+ kind: 'record-event';
399
+ sessionId: string;
400
+ entry: RecordedEntry;
401
+ };
402
+ /**
403
+ * Typed result map. With this shape, `await eff({ kind: 'read-context', ... })`
404
+ * resolves to `ContextSnapshot`, not a union — the discriminant carries the
405
+ * result type. Tests and Server impls implement this map exhaustively.
406
+ */
407
+ export interface EffectResultMap {
408
+ 'read-context': ContextSnapshot;
409
+ 'llm-call': LlmResponse;
410
+ 'stream-text': {
411
+ text: string;
412
+ usage?: LlmResponse['usage'];
413
+ };
414
+ 'tool-call': ToolCallResult;
415
+ 'send-message': {
416
+ ok: true;
417
+ };
418
+ 'record-event': {
419
+ ok: true;
420
+ };
421
+ }
422
+ export type EffectResult<K extends EffectKind> = EffectResultMap[K];
423
+ /** The single side-channel between Agent and Server. */
424
+ export type EffectHandler = <K extends EffectKind>(effect: Extract<Effect, {
425
+ kind: K;
426
+ }>) => Promise<EffectResult<K>>;
427
+ export interface ServicesConfig {
428
+ llm?: {
429
+ model: string;
430
+ temperature?: number;
431
+ };
432
+ tools?: unknown[];
433
+ }
434
+ export interface DefineAgentInput {
435
+ agentId: string;
436
+ description: string;
437
+ specialization?: string;
438
+ initial: string;
439
+ states: Record<string, State>;
440
+ tools?: unknown[];
441
+ services?: ServicesConfig;
442
+ operatorKey?: string;
443
+ taskTools?: 'all' | 'none' | string[];
444
+ [key: string]: unknown;
445
+ }
446
+ /**
447
+ * Frozen output of defineAgent. Consumed directly by AgentHost / createAgent.
448
+ * defineAgent injects ONE default: the agreement-kickoff state `kickingOff`
449
+ * plus a last-position transition into it, added to states that don't already
450
+ * handle a proposer-side proposal-resolved/approve outcome (runtime/kickoff.ts).
451
+ * `wait` defaults remain the author's visible spread of `thinkingDefaults`.
452
+ */
453
+ export interface AgentConfig {
454
+ openaiKey: string | undefined;
455
+ anthropicKey: string | undefined;
456
+ operatorKey?: string;
457
+ agentId: string;
458
+ description: string;
459
+ specialization?: string;
460
+ tools: unknown[];
461
+ model: string;
462
+ workflow: Workflow;
463
+ services?: ServicesConfig;
464
+ taskTools?: 'all' | 'none' | string[];
465
+ [key: string]: unknown;
466
+ }
package/dist/types.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Foundation types for the agent SDK workflow runtime.
3
+ *
4
+ * One outcome vocabulary, one ctx shape, one transition signature.
5
+ * Every state — parked or thinking — re-enters with exactly one Outcome.
6
+ */
7
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare function extractJSON(content: string): string;
2
+ export declare function safeParseJSON<T = unknown>(content: string, fallback?: T | null): T | null;
@@ -0,0 +1,111 @@
1
+ import { runtimeLog } from '../shared/runtimeLog.js';
2
+ export function extractJSON(content) {
3
+ if (!content || typeof content !== 'string')
4
+ return '';
5
+ const trimmed = content.trim();
6
+ if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {
7
+ const jsonBlockMatch = content.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
8
+ if (jsonBlockMatch) {
9
+ content = jsonBlockMatch[1].trim();
10
+ }
11
+ }
12
+ const firstBrace = content.indexOf('{');
13
+ const firstBracket = content.indexOf('[');
14
+ let startIdx = -1;
15
+ let isArray = false;
16
+ if (firstBrace !== -1 && (firstBracket === -1 || firstBrace < firstBracket)) {
17
+ startIdx = firstBrace;
18
+ isArray = false;
19
+ }
20
+ else if (firstBracket !== -1) {
21
+ startIdx = firstBracket;
22
+ isArray = true;
23
+ }
24
+ if (startIdx === -1)
25
+ return content.trim();
26
+ const openChar = isArray ? '[' : '{';
27
+ const closeChar = isArray ? ']' : '}';
28
+ let depth = 0;
29
+ let endIdx = startIdx;
30
+ for (let i = startIdx; i < content.length; i++) {
31
+ const char = content[i];
32
+ if (char === openChar) {
33
+ depth++;
34
+ }
35
+ else if (char === closeChar) {
36
+ depth--;
37
+ if (depth === 0) {
38
+ endIdx = i + 1;
39
+ break;
40
+ }
41
+ }
42
+ else if (char === '"') {
43
+ i++;
44
+ while (i < content.length && content[i] !== '"') {
45
+ if (content[i] === '\\')
46
+ i++;
47
+ i++;
48
+ }
49
+ }
50
+ }
51
+ if (endIdx > startIdx)
52
+ content = content.substring(startIdx, endIdx);
53
+ content = content.trim();
54
+ content = content.replace(/(?<!:)\/\/.*$/gm, '');
55
+ content = content.replace(/\/\*[\s\S]*?\*\//g, '');
56
+ content = content.replace(/,(\s*[}\]])/g, '$1');
57
+ return content;
58
+ }
59
+ function repairJsonStrings(jsonText) {
60
+ if (!jsonText || typeof jsonText !== 'string')
61
+ return jsonText;
62
+ const validEscapes = new Set(['"', '\\', '/', 'b', 'f', 'n', 'r', 't', 'u']);
63
+ let out = '';
64
+ let inString = false;
65
+ for (let i = 0; i < jsonText.length; i++) {
66
+ const ch = jsonText[i];
67
+ if (!inString) {
68
+ if (ch === '"')
69
+ inString = true;
70
+ out += ch;
71
+ continue;
72
+ }
73
+ if (ch === '\\') {
74
+ const next = jsonText[i + 1];
75
+ out += (next && validEscapes.has(next)) ? ch : '\\\\';
76
+ continue;
77
+ }
78
+ if (ch === '"') {
79
+ inString = false;
80
+ out += ch;
81
+ continue;
82
+ }
83
+ if (ch === '\n') {
84
+ out += '\\n';
85
+ continue;
86
+ }
87
+ if (ch === '\r') {
88
+ out += '\\r';
89
+ continue;
90
+ }
91
+ out += ch;
92
+ }
93
+ return out;
94
+ }
95
+ export function safeParseJSON(content, fallback = null) {
96
+ try {
97
+ const extracted = extractJSON(content);
98
+ if (!extracted || extracted.trim().length === 0)
99
+ throw new Error('Empty JSON content');
100
+ try {
101
+ return JSON.parse(extracted);
102
+ }
103
+ catch {
104
+ return JSON.parse(repairJsonStrings(extracted));
105
+ }
106
+ }
107
+ catch {
108
+ runtimeLog.error('JSONExtractor', 'Error parsing JSON', content.length > 500 ? `${content.slice(0, 500)}…` : content);
109
+ return fallback ?? null;
110
+ }
111
+ }
package/package.json CHANGED
@@ -1,16 +1,23 @@
1
1
  {
2
2
  "name": "@ziggs-ai/agent-sdk",
3
- "version": "0.1.12",
3
+ "version": "0.2.0",
4
4
  "description": "Agent framework SDK for building autonomous agents on the Ziggs platform",
5
5
  "type": "module",
6
- "main": "src/index.ts",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
7
8
  "exports": {
8
- ".": "./src/index.ts"
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
9
14
  },
10
15
  "engines": {
11
16
  "node": ">=18"
12
17
  },
13
18
  "scripts": {
19
+ "build": "tsc -p tsconfig.json",
20
+ "prepack": "npm run build",
14
21
  "typecheck": "tsc -p tsconfig.json --noEmit",
15
22
  "test": "node --experimental-test-module-mocks --import tsx/esm --test --test-reporter=spec test/*.test.ts",
16
23
  "test:watch": "node --experimental-test-module-mocks --import tsx/esm --test --watch test/*.test.ts"
@@ -34,8 +41,9 @@
34
41
  ],
35
42
  "license": "MIT",
36
43
  "files": [
37
- "src",
38
- "README.md"
44
+ "dist",
45
+ "README.md",
46
+ "CHANGELOG.md"
39
47
  ],
40
48
  "publishConfig": {
41
49
  "access": "public",