@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,563 +0,0 @@
1
- import type {
2
- Action,
3
- AgreementRef,
4
- Ctx,
5
- Outcome,
6
- OutcomeKind,
7
- ProposalRef,
8
- TaskRef,
9
- ToolResultEntry,
10
- } from '../types.js';
11
- import { isProtocolToolName, mapProtocolToolToOperation } from '../tasks/protocolRegistry.js';
12
- import { getBatchEvents, isTaskResultRelevantToAgent } from '../context/batch.js';
13
-
14
- // ── Event shape (untyped wire payload normalized into a small set of types) ──
15
-
16
- /** Wire payload from the backend for task/agreement state. */
17
- export interface WireResult {
18
- taskId?: string;
19
- state?: string;
20
- status?: string;
21
- agreement?: AgreementRef;
22
- agreementId?: string;
23
- proposal?: { status?: 'pending' | 'approved' | 'rejected' | 'cancelled' };
24
- task?: TaskRef;
25
- success?: boolean;
26
- error?: string;
27
- providerIsYou?: boolean;
28
- [key: string]: unknown;
29
- }
30
-
31
- export interface RawEvent {
32
- type?: string;
33
- result?: WireResult;
34
- receiverId?: string;
35
- senderId?: string;
36
- text?: string;
37
- events?: RawEvent[];
38
- [key: string]: unknown;
39
- }
40
-
41
- export interface EmittedEvent {
42
- type: string;
43
- tool?: string;
44
- result?: WireResult;
45
- error?: string;
46
- receiverId?: string;
47
- chatId?: string;
48
- message?: string;
49
- text?: string;
50
- operation?: string;
51
- senderId?: string;
52
- [key: string]: unknown;
53
- }
54
-
55
- // ── outcomeFromEvent: incoming wire event → Outcome ──────────────────────────
56
-
57
- /**
58
- * Converts a raw incoming event into the single Outcome that re-enters the
59
- * machine.
60
- *
61
- * For batched events, returns the *most significant* outcome (task assignments
62
- * win over messages). EventQueue already flattened multiple distinct events
63
- * via re-entry, so a batch here usually means events that arrived together
64
- * within a single backend frame.
65
- */
66
- export function outcomeFromEvent(
67
- rawEvent: RawEvent | null | undefined,
68
- ownAgentId: string | null,
69
- ): Outcome {
70
- if (!rawEvent) return { kind: 'enter' };
71
-
72
- const events: RawEvent[] = getBatchEvents(rawEvent) as RawEvent[];
73
- let best: Outcome | null = null;
74
-
75
- for (const ev of events) {
76
- if (!ev) continue;
77
- const candidate = singleEventToOutcome(ev, ownAgentId);
78
- if (!candidate) continue;
79
- if (!best || outcomeRank(candidate) > outcomeRank(best)) best = candidate;
80
- }
81
-
82
- return best ?? { kind: 'enter' };
83
- }
84
-
85
- function singleEventToOutcome(ev: RawEvent, ownAgentId: string | null): Outcome | null {
86
- if (ev.type === 'agreement_lifecycle') {
87
- const operation = ev.operation as string | undefined;
88
- const agreementId = (ev.agreementId as string | undefined) ?? '';
89
- const action =
90
- operation === 'proposal_rejected'
91
- ? 'reject'
92
- : operation === 'proposal_approved' || operation === 'proposal_approved_execute'
93
- ? 'approve'
94
- : null;
95
- if (action && agreementId) {
96
- return {
97
- kind: 'proposal-resolved',
98
- action,
99
- proposal: { agreementId },
100
- proposedByMe: false, // real value stamped in AgentMachine._handleFrame from ctx (needs pendingProposalAgreementId, unavailable here)
101
- };
102
- }
103
- return null;
104
- }
105
-
106
- if (ev.type === 'task_result') {
107
- const result = ev.result || {};
108
- if (
109
- ownAgentId &&
110
- !isTaskResultRelevantToAgent(result, ownAgentId) &&
111
- ev.receiverId !== ownAgentId
112
- ) {
113
- return null;
114
- }
115
-
116
- // Agreement lifecycle notification routed as task_result by normalizeIncomingEvent.
117
- // _operation is set to the backend operation name (e.g. 'proposal_approved').
118
- const inboundOp = result._operation as string | undefined;
119
- if (inboundOp) {
120
- const proposalAction = inboundOp === 'proposal_approved' ? 'approve'
121
- : inboundOp === 'proposal_rejected' ? 'reject'
122
- : null;
123
- if (proposalAction) {
124
- const agId = result.agreementId;
125
- const proposal: ProposalRef = agId
126
- ? { agreementId: agId, agreement: result as unknown as AgreementRef }
127
- : { agreementId: '' };
128
- return { kind: 'proposal-resolved', action: proposalAction as 'approve' | 'reject', proposal, proposedByMe: false }; // real value stamped in AgentMachine._handleFrame from ctx
129
- }
130
- // Other lifecycle ops (countered, expired) treated as enter — no FSM action needed here.
131
- return null;
132
- }
133
-
134
- // Tasks are born active in the new model — no `proposal` task state.
135
- // The wire shape `task_result` always carries an active or terminal task.
136
- const task: TaskRef = result as unknown as TaskRef;
137
- const ag: AgreementRef | undefined = result.agreement;
138
- const parties = ag?.parties || {};
139
- const state = result.state;
140
-
141
- // Direct assignment to me (provider) — task spawned, citing an active agreement.
142
- const isAssignedToMe =
143
- (result.providerIsYou || parties.provider === ownAgentId) &&
144
- (state === 'active' || state === 'in-progress');
145
- if (isAssignedToMe) {
146
- return { kind: 'task-assigned', task };
147
- }
148
-
149
- if (state === 'active' || state === 'in-progress') {
150
- return { kind: 'task-assigned', task };
151
- }
152
-
153
- if (state === 'completed' || state === 'failed') {
154
- return {
155
- kind: 'subtask-finished',
156
- status: state === 'completed' ? 'completed' : 'failed',
157
- task,
158
- result,
159
- };
160
- }
161
-
162
- if (state === 'cancelled') {
163
- return {
164
- kind: 'subtask-finished',
165
- status: 'failed',
166
- task,
167
- result,
168
- };
169
- }
170
-
171
- // Fallback: addressed to us with no clear state.
172
- if (ownAgentId && ev.receiverId === ownAgentId) {
173
- return { kind: 'task-assigned', task };
174
- }
175
-
176
- return { kind: 'subtask-finished', status: 'completed', task, result };
177
- }
178
-
179
- if (ev.type === 'resource_changed') {
180
- const resource = ((ev as { resource?: Record<string, unknown> }).resource ?? ev) as {
181
- kind?: string;
182
- reason?: string;
183
- resourceId?: string;
184
- agreementId?: string;
185
- taskId?: string;
186
- };
187
- const reason = resource.reason;
188
- if (
189
- resource.kind === 'agreement' &&
190
- (reason === 'proposal_approved' || reason === 'proposal_rejected')
191
- ) {
192
- const agreementId = resource.agreementId ?? resource.resourceId ?? '';
193
- const proposal: ProposalRef = { agreementId };
194
- return {
195
- kind: 'proposal-resolved',
196
- action: reason === 'proposal_approved' ? 'approve' : 'reject',
197
- proposal,
198
- proposedByMe: false, // real value stamped in AgentMachine._handleFrame from ctx
199
- };
200
- }
201
- if (resource.kind === 'task-state' && reason === 'subtask_completed') {
202
- const taskId = resource.taskId ?? resource.resourceId ?? '';
203
- const task = { taskId, state: 'completed' } as TaskRef;
204
- return { kind: 'subtask-finished', status: 'completed', task, result: task };
205
- }
206
- return null;
207
- }
208
-
209
- if (ev.type === 'state-timeout') {
210
- // Synthetic frame from AgentHost's StateTimers — host-constructed, fields always present.
211
- return { kind: 'state-timeout', state: ev.state as string, waitedMs: ev.waitedMs as number };
212
- }
213
-
214
- // Only real inbound chat messages should drive the FSM. Backend bookkeeping
215
- // (presence/heartbeat, raw `batch` outer frames, etc.) are NOT chat traffic.
216
- if (ev.type !== 'message') return null;
217
-
218
- // Suppress our own messages echoed back through the chat fanout.
219
- if (ownAgentId && ev.senderId && ev.senderId === ownAgentId) return null;
220
-
221
- const text = typeof ev.text === 'string' ? ev.text : undefined;
222
- const senderType = typeof ev.senderType === 'string' ? ev.senderType : undefined;
223
- return { kind: 'message-received', text, senderId: ev.senderId, senderType };
224
- }
225
-
226
- // Higher rank wins when collapsing batched events into one outcome.
227
- function outcomeRank(o: Outcome): number {
228
- switch (o.kind) {
229
- case 'task-assigned': return 100;
230
- case 'proposal-resolved': return 90;
231
- case 'subtask-finished': return 80;
232
- case 'message-received': return 10;
233
- // Any real event coalesced into the same batch supersedes the timer —
234
- // waking to "nothing happened" is moot when something did. Must stay below
235
- // message-received (10).
236
- case 'state-timeout': return 1;
237
- default: return 50;
238
- }
239
- }
240
-
241
- // ── outcomeFromActionResult: turn output → Outcome ───────────────────────────
242
-
243
- /**
244
- * Builds the single Outcome that ends a thinking-state turn from the
245
- * action that ran and the events it emitted.
246
- *
247
- * Action's `produces` declares the outcome kind — runtime fills in payload.
248
- * - static string: kind is fixed; runtime constructs payload from events.
249
- * - function: receives the tool result and args, returns the kind.
250
- *
251
- * If `produces` is missing or doesn't match the events, falls back to a
252
- * best-effort inference.
253
- */
254
- export function outcomeFromActionResult(
255
- actionName: string | null,
256
- action: Action | null,
257
- args: unknown,
258
- emittedEvents: EmittedEvent[],
259
- toolResultsOut: ToolResultEntry[],
260
- ): Outcome {
261
- if (!emittedEvents.length) {
262
- return { kind: 'error', source: 'unknown', cause: `action "${actionName}" emitted nothing`, retryable: false };
263
- }
264
-
265
- // Collect tool results in caller's accumulator (used in prompts and ctx).
266
- for (const e of emittedEvents) {
267
- if (e?.type === 'tool_result') toolResultsOut.push({ tool: e.tool || '', result: e.result });
268
- if (e?.type === 'tool_error') toolResultsOut.push({ tool: e.tool || '', error: e.error });
269
- }
270
-
271
- // Pick the "primary" event the outcome describes.
272
- //
273
- // Protocol-level state changes (agreement creation, task assignment/closure,
274
- // proposal response) outrank EVERYTHING else, including message_sent and
275
- // waited. Why: when the LLM batches `delegate` + `wait` in one round, the
276
- // sub-agreement DOES get created server-side, but if `waited` wins the FSM
277
- // sees `wait` and bounces back to `idle` instead of transitioning to
278
- // `awaitingSubAgreementApproval` — and the chain stalls. The meaningful
279
- // turn outcome is the work that landed, not the LLM's terminal decision.
280
- //
281
- // Among non-protocol events: message_sent / waited still outrank pure
282
- // query tool_results (e.g. agent_network search) and tool_errors, because
283
- // those are the LLM's explicit final intent in turns that did no protocol
284
- // work.
285
- const primary =
286
- emittedEvents.find(e => e.type === 'task_result' && isStateChangingProtocolEvent(e)) ??
287
- emittedEvents.find(e => e.type === 'tool_result' && isStateChangingProtocolEvent(e)) ??
288
- emittedEvents.find(e => e.type === 'message_sent') ??
289
- emittedEvents.find(e => e.type === 'message_duplicate_skipped') ??
290
- emittedEvents.find(e => e.type === 'waited') ??
291
- emittedEvents.find(e => e.type === 'tool_result') ??
292
- emittedEvents.find(e => e.type === 'tool_error') ??
293
- emittedEvents.find(e => e.type === 'task_result') ??
294
- emittedEvents.find(e => e.type === 'task_error') ??
295
- emittedEvents[0];
296
-
297
- // Resolve the kind via produces (preferred) or by inferring from primary.
298
- let kind: OutcomeKind | null = null;
299
- if (action?.produces) {
300
- const p = action.produces;
301
- const result = primary?.type === 'tool_result' ? primary.result : undefined;
302
- kind = typeof p === 'function' ? p(result, args) : p;
303
- }
304
- if (!kind) kind = inferKindFromEvent(primary);
305
-
306
- return buildOutcomeOfKind(kind, primary, action);
307
- }
308
-
309
- /**
310
- * Whether a tool_result / task_result represents a protocol state change
311
- * (agreement creation, task assignment / closure, proposal response). Used
312
- * to outrank pure query tool_results (e.g. `agent_network search`) when the
313
- * same turn batches multiple tools.
314
- */
315
- function isStateChangingProtocolEvent(ev: EmittedEvent): boolean {
316
- const op = ev.type === 'task_result'
317
- ? ev.operation
318
- : (ev.tool && isProtocolToolName(ev.tool) ? mapProtocolToolToOperation(ev.tool) : null);
319
- if (!op) return false;
320
- const r: WireResult = ev.result ?? ({} as WireResult);
321
- if (r.success === false || r.error) return false;
322
- const ag = r.agreement ?? (r.agreementId ? r : null);
323
- const task = r.task || (r.taskId ? r : null);
324
- const proposalStatus = ag?.proposal?.status;
325
- const state = task?.state || r.state;
326
- if (op === 'agreement-propose' || op === 'agreement-subcontract') {
327
- return proposalStatus === 'pending' || proposalStatus === 'approved' || !!ag?.agreementId;
328
- }
329
- if (op === 'agreement-respond') return true;
330
- if (op === 'task-update') {
331
- return state === 'completed' || state === 'failed' || state === 'cancelled';
332
- }
333
- if (op === 'task-spawn') return !!task?.taskId;
334
- return false;
335
- }
336
-
337
- function inferKindFromEvent(primary: EmittedEvent | undefined): OutcomeKind {
338
- if (!primary) return 'error';
339
- switch (primary.type) {
340
- case 'message_sent': return 'message-sent';
341
- case 'message_duplicate_skipped': return 'message-sent';
342
- case 'waited': return 'wait';
343
- case 'tool_error': return 'error';
344
- case 'task_error': return 'error';
345
- case 'tool_result': return inferKindFromToolResult(primary);
346
- case 'task_result': return inferKindFromTaskResult(primary);
347
- default: return 'tool-result';
348
- }
349
- }
350
-
351
- function inferKindFromToolResult(ev: EmittedEvent): OutcomeKind {
352
- if (!isProtocolToolName(ev.tool ?? '')) return 'tool-result';
353
- const op = mapProtocolToolToOperation(ev.tool ?? '');
354
- return inferKindFromProtocolOp(op ?? undefined, ev.result);
355
- }
356
-
357
- function inferKindFromTaskResult(ev: EmittedEvent): OutcomeKind {
358
- return inferKindFromProtocolOp(ev.operation, ev.result);
359
- }
360
-
361
- function inferKindFromProtocolOp(op: string | undefined, result: unknown): OutcomeKind {
362
- const r: WireResult = (result as WireResult) || ({} as WireResult);
363
- const ag: AgreementRef | undefined = r.agreement ?? (r.agreementId ? r as unknown as AgreementRef : undefined);
364
- const task: TaskRef | undefined = r.task || (r.taskId ? r as unknown as TaskRef : undefined);
365
-
366
- // Agreement creation verbs no longer create paired tasks. The caller (creator)
367
- // has made a proposal awaiting response from the proposedTo party.
368
- if (
369
- op === 'agreement-propose' ||
370
- op === 'agreement-subcontract'
371
- ) {
372
- return 'proposal-made';
373
- }
374
- if (op === 'task-spawn') {
375
- // A task was just spawned under an active agreement. From the spawner's
376
- // side this is a delegation; the executor sees `task-assigned` via the
377
- // task_result event channel.
378
- return 'task-delegated';
379
- }
380
- if (op === 'task-update') {
381
- const status = task?.state || r.state || r.status;
382
- if (status === 'completed' || status === 'failed') return 'task-closed';
383
- return 'tool-result';
384
- }
385
- if (op === 'agreement-respond') {
386
- // The responder's tool result is the agreement after approve/reject.
387
- return 'proposal-resolved';
388
- }
389
- void ag;
390
- return 'tool-result';
391
- }
392
-
393
- function buildOutcomeOfKind(
394
- kind: OutcomeKind,
395
- primary: EmittedEvent | undefined,
396
- action: Action | null,
397
- ): Outcome {
398
- const tool = action?.tool || primary?.tool || '';
399
- const result = primary?.type === 'tool_result' ? primary.result : primary?.result;
400
-
401
- switch (kind) {
402
- case 'enter':
403
- case 'wait':
404
- return { kind };
405
-
406
- case 'state-timeout':
407
- // Runtime-generated only (validateWorkflow rejects produces:'state-timeout').
408
- // Break-fast backstop if an action somehow declares it.
409
- throw new Error(`action produced reserved outcome kind "state-timeout" — runtime-generated only`);
410
-
411
- case 'message-sent':
412
- return { kind, text: primary?.message, receiverId: primary?.receiverId };
413
-
414
- case 'message-received':
415
- return { kind, text: primary?.text };
416
-
417
- case 'task-assigned': {
418
- const task: TaskRef = (result?.task || result || {}) as unknown as TaskRef;
419
- return { kind, task };
420
- }
421
- case 'task-delegated': {
422
- const task: TaskRef = (result?.task || result || {}) as unknown as TaskRef;
423
- return { kind, task };
424
- }
425
- case 'task-closed': {
426
- const raw = result?.task?.state || result?.state;
427
- const status: 'completed' | 'failed' = raw === 'failed' ? 'failed' : 'completed';
428
- return { kind, status, result };
429
- }
430
- case 'subtask-finished': {
431
- const task: TaskRef = (result?.task || result || {}) as unknown as TaskRef;
432
- const status = (task.state === 'failed' ? 'failed' : 'completed') as 'completed' | 'failed';
433
- return { kind, status, task, result };
434
- }
435
- case 'proposal-made': {
436
- const ag: AgreementRef | undefined = result?.agreement ?? (result?.agreementId ? result as unknown as AgreementRef : undefined);
437
- const proposal: ProposalRef = ag
438
- ? { agreementId: ag.agreementId, agreement: ag }
439
- : { agreementId: result?.agreementId || '' };
440
- return { kind, proposal };
441
- }
442
- case 'proposal-resolved': {
443
- const ag: AgreementRef | undefined = result?.agreement ?? (result?.agreementId ? result as unknown as AgreementRef : undefined);
444
- const status = ag?.proposal?.status;
445
- const action_: 'approve' | 'reject' = status === 'rejected' ? 'reject' : 'approve';
446
- const proposal: ProposalRef = ag
447
- ? { agreementId: ag.agreementId, agreement: ag }
448
- : { agreementId: result?.agreementId || '' };
449
- return { kind, action: action_, proposal, proposedByMe: false }; // turn path = our own agreement_respond ran — we are the responder, by definition not the proposer
450
- }
451
- case 'tool-result':
452
- return { kind, tool, result };
453
-
454
- case 'error': {
455
- const cause = primary?.error || primary?.result || 'unknown error';
456
- const source = primary?.type === 'tool_error' || primary?.type === 'tool_result' ? 'tool' : 'unknown';
457
- return { kind, source, cause, retryable: false };
458
- }
459
- case 'extension':
460
- return { kind, name: tool || 'unknown', payload: result };
461
- }
462
- }
463
-
464
- // ── applyOutcomeToCtx: persistent ctx updates from a new outcome ─────────────
465
-
466
- /**
467
- * Mutates ctx to absorb persistent state from a new outcome:
468
- * - active agreement/task ids on assignment, cleared on close
469
- * - pending proposal id on proposal-made, cleared on resolution
470
- * - delegated task ids accumulated on delegation, used to match later subtask events
471
- */
472
- export function applyOutcomeToCtx(ctx: Ctx, outcome: Outcome): void {
473
- ctx.lastOutcome = outcome;
474
-
475
- switch (outcome.kind) {
476
- case 'task-assigned': {
477
- const t = outcome.task || ({} as TaskRef);
478
- const tid = t.taskId || (t as unknown as Record<string, unknown>).id as string | undefined;
479
- const agId = t.agreementId || t.agreement?.agreementId || ctx.pendingProposalAgreementId;
480
- if (tid) ctx.activeTaskId = tid;
481
- if (agId) ctx.activeAgreementId = agId;
482
- ctx.pendingProposalAgreementId = null;
483
- return;
484
- }
485
- case 'task-delegated': {
486
- const t = outcome.task || ({} as TaskRef);
487
- const tid = t.taskId;
488
- const agId = t.agreementId || t.agreement?.agreementId;
489
- if (tid && !(tid in ctx.pendingSubtasks)) {
490
- ctx.pendingSubtasks[tid] = {
491
- agentId: t.assigneeId ?? t.executorId ?? t.agreement?.parties?.provider ?? null,
492
- spawnedAt: Date.now(),
493
- };
494
- }
495
- if (agId && !ctx.delegatedAgreementIds.includes(agId)) ctx.delegatedAgreementIds.push(agId);
496
- return;
497
- }
498
- case 'proposal-made': {
499
- const agId = outcome.proposal?.agreementId;
500
- if (agId) ctx.pendingProposalAgreementId = agId;
501
- return;
502
- }
503
- case 'proposal-resolved': {
504
- // Approval of the agent's PRIMARY proposal (the one binding it to its
505
- // counterparty — e.g. Ziggs ↔ user) promotes the pending id into
506
- // activeAgreementId so transitions gated on activeAgreementId fire.
507
- // We only do this when no agreement is currently active, so that
508
- // approvals of CHILD sub-agreements (e.g. coffee-agent approving the
509
- // Ziggs-issued subcontract) don't overwrite the root the primary agent
510
- // is bound to. Sub-agreement bookkeeping lives in delegatedAgreementIds
511
- // (recorded on task-delegated) — not here.
512
- if (outcome.action === 'approve' && !ctx.activeAgreementId) {
513
- const agId = outcome.proposal?.agreementId || ctx.pendingProposalAgreementId;
514
- if (agId) ctx.activeAgreementId = agId;
515
- }
516
- ctx.pendingProposalAgreementId = null;
517
- return;
518
- }
519
- case 'subtask-finished': {
520
- const t = outcome.task;
521
- const taskId = t?.taskId;
522
- const agId = t?.agreementId || t?.agreement?.agreementId;
523
- if (taskId) {
524
- const pending = ctx.pendingSubtasks[taskId];
525
- delete ctx.pendingSubtasks[taskId];
526
- const payload = t?.result ?? null;
527
- const existing = ctx.collectedResults.find(r => r.taskId === taskId);
528
- if (!existing) {
529
- ctx.collectedResults.push({
530
- taskId,
531
- agentId: pending?.agentId ?? t?.assigneeId ?? t?.executorId ?? t?.agreement?.parties?.provider ?? null,
532
- status: outcome.status,
533
- result: payload,
534
- });
535
- } else if (existing.result == null && payload != null) {
536
- // A bare resource_changed(subtask_completed) skeleton ({taskId, state})
537
- // can arrive BEFORE the full task_result for the same completion.
538
- // Upgrade the placeholder in place instead of dropping the real payload.
539
- // The skeleton often lacks executor identity, so also fill agentId
540
- // from the fuller frame when the placeholder recorded none.
541
- existing.status = outcome.status;
542
- existing.result = payload;
543
- if (existing.agentId == null) {
544
- existing.agentId = t?.assigneeId ?? t?.executorId ?? t?.agreement?.parties?.provider ?? null;
545
- }
546
- }
547
- }
548
- if (agId) ctx.delegatedAgreementIds = ctx.delegatedAgreementIds.filter(id => id !== agId);
549
- return;
550
- }
551
- case 'task-closed': {
552
- ctx.activeAgreementId = null;
553
- ctx.activeTaskId = null;
554
- ctx.pendingProposalAgreementId = null;
555
- ctx.pendingSubtasks = {};
556
- ctx.collectedResults = [];
557
- ctx.delegatedAgreementIds = [];
558
- return;
559
- }
560
- default:
561
- return;
562
- }
563
- }
@@ -1,86 +0,0 @@
1
- import type { Action, Ctx, MechanicalState, Outcome, Produces, Transition, ThinkingState } from '../types.js';
2
-
3
- /**
4
- * Defaults that workflow authors spread into thinking states explicitly.
5
- * No auto-injection — what you read in the file is what runs.
6
- *
7
- * const dflt = thinkingDefaults({ initial: 'idle' });
8
- *
9
- * listening: {
10
- * kind: 'thinking',
11
- * ...dflt,
12
- * prompt: { ... },
13
- * actions: { ...dflt.actions, greetUser: { ... } },
14
- * transitions: [
15
- * { to: 'executing', when: o => o.kind === 'task-assigned' },
16
- * ...dflt.transitions,
17
- * ],
18
- * }
19
- */
20
- export interface ThinkingDefaults {
21
- actions: Record<string, Action>;
22
- transitions: Transition[];
23
- }
24
-
25
- export const DEFAULT_WAIT_PROMPT = Object.freeze({
26
- instruction: 'Do nothing - wait for the next event.',
27
- when: 'No action is needed, you are waiting for external input, or you should pause without repeating yourself.',
28
- format: '{"thought": "...", "action": "wait"}',
29
- });
30
-
31
- export function thinkingDefaults(opts: { initial: string }): ThinkingDefaults {
32
- const { initial } = opts;
33
- return {
34
- actions: {
35
- wait: {
36
- prompt: { ...DEFAULT_WAIT_PROMPT },
37
- produces: 'wait',
38
- },
39
- },
40
- transitions: [
41
- { to: initial, when: o => o.kind === 'wait' },
42
- { to: initial, when: o => o.kind === 'message-sent' },
43
- // Errors (empty/failed turns) fall back to the initial state instead of
44
- // silently re-entering and recursing until the depth guard (ZIG-303).
45
- { to: initial, when: o => o.kind === 'error' },
46
- ],
47
- };
48
- }
49
-
50
- /**
51
- * Convenience builder for a `thinking` state that always carries the defaults.
52
- * Equivalent to spreading manually but the spread points are in one place.
53
- *
54
- * defineThinkingState({ initial: 'idle' }, {
55
- * prompt: { ... },
56
- * actions: { greetUser: { ... } },
57
- * transitions: [ { to: 'executing', when: o => o.kind === 'task-assigned' } ],
58
- * })
59
- */
60
- export function defineThinkingState(
61
- opts: { initial: string },
62
- state: Omit<ThinkingState, 'kind' | 'actions' | 'transitions'> & {
63
- actions: Record<string, Action>;
64
- transitions: Transition[];
65
- }
66
- ): ThinkingState {
67
- const dflt = thinkingDefaults(opts);
68
- return {
69
- kind: 'thinking',
70
- prompt: state.prompt,
71
- allowNoWait: state.allowNoWait,
72
- actions: { ...dflt.actions, ...state.actions },
73
- transitions: [...state.transitions, ...dflt.transitions],
74
- };
75
- }
76
-
77
- /** ZIG-764: mechanical state — one tool call, zero LLM turns. */
78
- export function defineMechanicalState(state: {
79
- tool: string;
80
- args?: Record<string, unknown>;
81
- buildArgs?: (ctx: Ctx, outcome: Outcome) => Record<string, unknown>;
82
- produces: Produces;
83
- transitions: Transition[];
84
- }): MechanicalState {
85
- return { kind: 'mechanical', ...state };
86
- }
@@ -1,35 +0,0 @@
1
- import type { State, ThinkingState, Workflow } from '../types.js';
2
-
3
- /**
4
- * ZIG-826: true when the workflow exposes `agreement_respond` on a thinking
5
- * action — the agent can approve/reject inbound proposals directed at it.
6
- * Kickoff-only states (proposer-side approval → task_spawn) do not count.
7
- */
8
- export function deriveRespondsToProposals(workflow: Workflow): boolean {
9
- if (!workflow?.states) return false;
10
- for (const state of Object.values(workflow.states)) {
11
- if (state.kind !== 'thinking') continue;
12
- const actions = (state as ThinkingState).actions;
13
- if (!actions) continue;
14
- for (const action of Object.values(actions)) {
15
- if (action?.tool === 'agreement_respond') return true;
16
- }
17
- }
18
- return false;
19
- }
20
-
21
- /** Scan custom states (pre-defineAgent) for agreement_respond actions. */
22
- export function statesRespondToProposals(
23
- states: Record<string, State> | undefined,
24
- ): boolean {
25
- if (!states) return false;
26
- for (const state of Object.values(states)) {
27
- if (state.kind !== 'thinking') continue;
28
- const actions = (state as ThinkingState).actions;
29
- if (!actions) continue;
30
- for (const action of Object.values(actions)) {
31
- if (action?.tool === 'agreement_respond') return true;
32
- }
33
- }
34
- return false;
35
- }