@ziggs-ai/agent-sdk 0.1.11 → 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 (211) 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/claudeSdkProtocol.js +27 -0
  20. package/dist/agent/claudeSdkTools.d.ts +19 -0
  21. package/dist/agent/claudeSdkTools.js +57 -0
  22. package/dist/agent/hostedAgentConnection.d.ts +15 -0
  23. package/dist/agent/hostedAgentConnection.js +29 -0
  24. package/dist/agent/toolManagerToSdkMcp.d.ts +12 -0
  25. package/dist/agent/toolManagerToSdkMcp.js +123 -0
  26. package/dist/brain/index.d.ts +50 -0
  27. package/dist/brain/index.js +45 -0
  28. package/dist/cognition/validateContext.d.ts +11 -0
  29. package/dist/cognition/validateContext.js +117 -0
  30. package/dist/context/applyEffects.d.ts +2 -0
  31. package/dist/context/applyEffects.js +89 -0
  32. package/dist/context/batch.d.ts +2 -0
  33. package/dist/context/batch.js +18 -0
  34. package/dist/context/classifyEnvelope.d.ts +1 -0
  35. package/dist/context/classifyEnvelope.js +58 -0
  36. package/dist/context/routingLabels.d.ts +4 -0
  37. package/dist/context/routingLabels.js +48 -0
  38. package/dist/defineAgent.d.ts +14 -0
  39. package/dist/defineAgent.js +68 -0
  40. package/dist/formatters/AgreementFormatter.d.ts +18 -0
  41. package/dist/formatters/AgreementFormatter.js +130 -0
  42. package/dist/formatters/HistoryFormatter.d.ts +26 -0
  43. package/dist/formatters/HistoryFormatter.js +173 -0
  44. package/dist/formatters/index.js +2 -0
  45. package/{src/index.ts → dist/index.d.ts} +13 -53
  46. package/dist/index.js +66 -0
  47. package/dist/ingress/normalizeIncoming.d.ts +65 -0
  48. package/dist/ingress/normalizeIncoming.js +88 -0
  49. package/dist/memory/MemoryStore.d.ts +55 -0
  50. package/dist/memory/MemoryStore.js +78 -0
  51. package/dist/pricing/fleetDefaults.d.ts +46 -0
  52. package/dist/pricing/fleetDefaults.js +168 -0
  53. package/dist/pricing/fleetEvalFree.d.ts +7 -0
  54. package/dist/pricing/fleetEvalFree.js +24 -0
  55. package/dist/pricing/fleetFreeTierA.gen.d.ts +6 -0
  56. package/{src/pricing/fleetFreeTierA.gen.ts → dist/pricing/fleetFreeTierA.gen.js} +5 -6
  57. package/dist/pricing/fleetTierByAgentId.gen.d.ts +7 -0
  58. package/dist/pricing/fleetTierByAgentId.gen.js +768 -0
  59. package/dist/runtime/AgentMachine.d.ts +143 -0
  60. package/dist/runtime/AgentMachine.js +400 -0
  61. package/dist/runtime/PromptBuilder.d.ts +96 -0
  62. package/dist/runtime/PromptBuilder.js +439 -0
  63. package/dist/runtime/bootstrapCtx.d.ts +18 -0
  64. package/dist/runtime/bootstrapCtx.js +37 -0
  65. package/dist/runtime/buildOutcome.d.ts +68 -0
  66. package/dist/runtime/buildOutcome.js +464 -0
  67. package/dist/runtime/defaults.d.ts +54 -0
  68. package/dist/runtime/defaults.js +47 -0
  69. package/dist/runtime/deriveRespondsToProposals.d.ts +9 -0
  70. package/dist/runtime/deriveRespondsToProposals.js +38 -0
  71. package/dist/runtime/kickoff.d.ts +15 -0
  72. package/dist/runtime/kickoff.js +112 -0
  73. package/dist/runtime/runMechanical.d.ts +25 -0
  74. package/dist/runtime/runMechanical.js +74 -0
  75. package/dist/runtime/runTurn.d.ts +63 -0
  76. package/dist/runtime/runTurn.js +800 -0
  77. package/dist/runtime/validateWorkflow.d.ts +17 -0
  78. package/dist/runtime/validateWorkflow.js +209 -0
  79. package/dist/server/ConnectionPool.d.ts +68 -0
  80. package/dist/server/ConnectionPool.js +166 -0
  81. package/dist/server/EventQueue.d.ts +33 -0
  82. package/dist/server/EventQueue.js +98 -0
  83. package/dist/server/InboxCatchUp.d.ts +24 -0
  84. package/dist/server/InboxCatchUp.js +213 -0
  85. package/dist/server/OutboxBuffer.d.ts +33 -0
  86. package/dist/server/OutboxBuffer.js +68 -0
  87. package/dist/server/SeenMessages.d.ts +13 -0
  88. package/dist/server/SeenMessages.js +31 -0
  89. package/dist/server/StateTimers.d.ts +34 -0
  90. package/dist/server/StateTimers.js +70 -0
  91. package/dist/server/ZiggsEffectHandler.d.ts +79 -0
  92. package/dist/server/ZiggsEffectHandler.js +319 -0
  93. package/dist/server/agreements/AgreementService.d.ts +50 -0
  94. package/dist/server/agreements/AgreementService.js +85 -0
  95. package/dist/server/createHealthServer.d.ts +7 -0
  96. package/dist/server/createHealthServer.js +75 -0
  97. package/dist/server/proactive/ProactiveTrigger.d.ts +33 -0
  98. package/dist/server/proactive/ProactiveTrigger.js +71 -0
  99. package/dist/server/runLauncher.d.ts +28 -0
  100. package/dist/server/runLauncher.js +93 -0
  101. package/dist/server/tasks/TaskService.d.ts +25 -0
  102. package/dist/server/tasks/TaskService.js +103 -0
  103. package/dist/server/tasks/index.js +1 -0
  104. package/dist/server/telemetryIngest.d.ts +24 -0
  105. package/dist/server/telemetryIngest.js +62 -0
  106. package/dist/server/tools/index.d.ts +24 -0
  107. package/{src/server/tools/index.ts → dist/server/tools/index.js} +4 -24
  108. package/dist/server/tools/tier1/protocolRunner.d.ts +39 -0
  109. package/dist/server/tools/tier1/protocolRunner.js +288 -0
  110. package/dist/server/tools/tier1/protocolTools.d.ts +12 -0
  111. package/dist/server/tools/tier1/protocolTools.js +37 -0
  112. package/dist/server/tools/tier2/connectionTools.d.ts +4 -0
  113. package/dist/server/tools/tier2/connectionTools.js +63 -0
  114. package/dist/server/tools/tier2/contextTools.d.ts +4 -0
  115. package/dist/server/tools/tier2/contextTools.js +46 -0
  116. package/dist/server/tools/tier2/discoveryTools.d.ts +4 -0
  117. package/dist/server/tools/tier2/discoveryTools.js +25 -0
  118. package/dist/server/tools/tier2/marketplaceTools.d.ts +3 -0
  119. package/dist/server/tools/tier2/marketplaceTools.js +22 -0
  120. package/dist/server/tools/tier2/paymentTools.d.ts +12 -0
  121. package/dist/server/tools/tier2/paymentTools.js +165 -0
  122. package/dist/server/ziggsconnect/ZiggsConnectClient.d.ts +35 -0
  123. package/dist/server/ziggsconnect/ZiggsConnectClient.js +95 -0
  124. package/dist/server/ziggscontext/ZiggsContextClient.d.ts +48 -0
  125. package/dist/server/ziggscontext/ZiggsContextClient.js +90 -0
  126. package/dist/server/ziggspay/ZiggsPayClient.d.ts +82 -0
  127. package/dist/server/ziggspay/ZiggsPayClient.js +188 -0
  128. package/dist/shared/ids.d.ts +1 -0
  129. package/dist/shared/ids.js +3 -0
  130. package/dist/shared/runtimeLog.d.ts +18 -0
  131. package/dist/shared/runtimeLog.js +68 -0
  132. package/dist/shared/types.d.ts +22 -0
  133. package/dist/shared/types.js +23 -0
  134. package/dist/tasks/protocolRegistry.d.ts +16 -0
  135. package/dist/tasks/protocolRegistry.js +20 -0
  136. package/dist/tools/ToolManager.d.ts +12 -0
  137. package/dist/tools/ToolManager.js +74 -0
  138. package/dist/tools/ToolProvider.d.ts +6 -0
  139. package/dist/tools/ToolProvider.js +21 -0
  140. package/dist/tools/defineTool.d.ts +27 -0
  141. package/dist/tools/defineTool.js +62 -0
  142. package/{src/tools/index.ts → dist/tools/index.d.ts} +0 -1
  143. package/dist/tools/index.js +6 -0
  144. package/dist/tools/recordReport.d.ts +41 -0
  145. package/dist/tools/recordReport.js +30 -0
  146. package/dist/types.d.ts +466 -0
  147. package/dist/types.js +7 -0
  148. package/dist/utils/jsonExtractor.d.ts +2 -0
  149. package/dist/utils/jsonExtractor.js +111 -0
  150. package/package.json +17 -7
  151. package/src/AgentHost.ts +0 -545
  152. package/src/adapters/AnthropicAdapter.ts +0 -206
  153. package/src/adapters/McpAdapter.ts +0 -348
  154. package/src/adapters/OpenAIAdapter.ts +0 -187
  155. package/src/agent/Agent.ts +0 -104
  156. package/src/cognition/validateContext.ts +0 -95
  157. package/src/context/applyEffects.ts +0 -80
  158. package/src/context/batch.ts +0 -19
  159. package/src/context/classifyEnvelope.ts +0 -38
  160. package/src/context/routingLabels.ts +0 -46
  161. package/src/defineAgent.ts +0 -70
  162. package/src/formatters/AgreementFormatter.ts +0 -111
  163. package/src/formatters/HistoryFormatter.ts +0 -172
  164. package/src/ingress/normalizeIncoming.ts +0 -162
  165. package/src/memory/MemoryStore.ts +0 -104
  166. package/src/pricing/fleetDefaults.ts +0 -225
  167. package/src/pricing/fleetEvalFree.ts +0 -24
  168. package/src/pricing/fleetTierByAgentId.gen.ts +0 -775
  169. package/src/runtime/AgentMachine.ts +0 -402
  170. package/src/runtime/PromptBuilder.ts +0 -485
  171. package/src/runtime/buildOutcome.ts +0 -563
  172. package/src/runtime/defaults.ts +0 -75
  173. package/src/runtime/kickoff.ts +0 -117
  174. package/src/runtime/runTurn.ts +0 -813
  175. package/src/runtime/validateWorkflow.ts +0 -202
  176. package/src/server/ConnectionPool.ts +0 -206
  177. package/src/server/EventQueue.ts +0 -133
  178. package/src/server/InboxCatchUp.ts +0 -254
  179. package/src/server/OutboxBuffer.ts +0 -90
  180. package/src/server/SeenMessages.ts +0 -27
  181. package/src/server/StateTimers.ts +0 -85
  182. package/src/server/ZiggsEffectHandler.ts +0 -418
  183. package/src/server/agreements/AgreementService.ts +0 -118
  184. package/src/server/createHealthServer.ts +0 -85
  185. package/src/server/proactive/ProactiveTrigger.ts +0 -83
  186. package/src/server/runLauncher.ts +0 -146
  187. package/src/server/tasks/TaskService.ts +0 -110
  188. package/src/server/telemetryIngest.ts +0 -91
  189. package/src/server/tools/tier1/protocolRunner.ts +0 -144
  190. package/src/server/tools/tier1/protocolTools.ts +0 -99
  191. package/src/server/tools/tier2/connectionTools.ts +0 -75
  192. package/src/server/tools/tier2/contextTools.ts +0 -63
  193. package/src/server/tools/tier2/discoveryTools.ts +0 -34
  194. package/src/server/tools/tier2/marketplaceTools.ts +0 -27
  195. package/src/server/tools/tier2/paymentTools.ts +0 -170
  196. package/src/server/ziggsconnect/ZiggsConnectClient.ts +0 -126
  197. package/src/server/ziggscontext/ZiggsContextClient.ts +0 -129
  198. package/src/server/ziggspay/ZiggsPayClient.ts +0 -193
  199. package/src/shared/ids.ts +0 -3
  200. package/src/shared/runtimeLog.ts +0 -72
  201. package/src/shared/types.ts +0 -29
  202. package/src/tasks/protocolRegistry.ts +0 -25
  203. package/src/tools/ToolManager.ts +0 -95
  204. package/src/tools/ToolProvider.ts +0 -19
  205. package/src/tools/defineTool.ts +0 -90
  206. package/src/tools/recordReport.ts +0 -82
  207. package/src/types.ts +0 -456
  208. package/src/utils/jsonExtractor.ts +0 -100
  209. /package/{src/adapters/index.ts → dist/adapters/index.d.ts} +0 -0
  210. /package/{src/formatters/index.ts → dist/formatters/index.d.ts} +0 -0
  211. /package/{src/server/tasks/index.ts → dist/server/tasks/index.d.ts} +0 -0
@@ -1,402 +0,0 @@
1
- import type { Ctx, Outcome, Workflow, Identity, EffectHandler } from '../types.js';
2
- import { runtimeLog } from '../shared/runtimeLog.js';
3
- import { applyOutcomeToCtx, outcomeFromEvent, type RawEvent } from './buildOutcome.js';
4
- import type { runTurn as RunTurnFn } from './runTurn.js';
5
- import { PromptBuilder } from './PromptBuilder.js';
6
- import type { MemoryStore } from '../memory/MemoryStore.js';
7
- import type { ToolManager } from '../tools/ToolManager.js';
8
-
9
- export interface MachineSnapshot {
10
- value: string;
11
- ctx: Ctx;
12
- status: 'active' | 'stopped';
13
- }
14
-
15
- export type TransitionEvent =
16
- | { kind: 'transition'; fromState: string; toState: string; outcomeKind: string; depth: number }
17
- | { kind: 'no-match'; state: string; outcomeKind: string; depth: number }
18
- | { kind: 'depth-guard'; state: string; depth: number }
19
- | { kind: 'error-escape'; fromState: string; toState: string }
20
- | { kind: 'timeout-unhandled'; state: string; waitedMs: number };
21
-
22
- interface MachineInput {
23
- identity: Identity;
24
- /** Server-provided ctx for an existing session. If omitted, a fresh ctx is built. */
25
- ctx?: Ctx;
26
- /** Server-provided state name for an existing session. Defaults to workflow.initial. */
27
- state?: string;
28
- }
29
-
30
- interface MachineOptions {
31
- workflow: Workflow;
32
- executionCore: typeof RunTurnFn;
33
- /** Side channel for all I/O. Provided by the Server. */
34
- eff: EffectHandler;
35
- /** Pure tool metadata (schemas, flags). Owned by the Agent. */
36
- toolManager: ToolManager;
37
- promptBuilder: PromptBuilder;
38
- /** Agent-private long-term memory. Operator-provided. */
39
- memory?: MemoryStore;
40
- input: MachineInput;
41
- /** Optional tap for FSM transition events — called synchronously on each transition. */
42
- transitionTap?: (event: TransitionEvent) => void;
43
- }
44
-
45
- interface IncomingFrame {
46
- event?: RawEvent;
47
- identity?: Identity;
48
- }
49
-
50
- type Subscriber = (snapshot: MachineSnapshot) => void;
51
-
52
- /**
53
- * Per-lane interpreter. Holds (current state name, Ctx). Re-entry is the
54
- * single primitive: every external event and every turn produces exactly
55
- * one Outcome that re-enters the current state.
56
- *
57
- * Parked states stop on entry. Thinking states run an LLM turn → produce an
58
- * outcome → re-enter. Transitions are evaluated against the new outcome
59
- * (first matching `when` wins; no `when` is fallthrough).
60
- *
61
- * `_running` guards against concurrent turns on the same machine — outer
62
- * runtime is expected to serialize via EventQueue, but we belt-and-suspenders.
63
- */
64
- export class AgentMachine {
65
- workflow: Workflow;
66
- executionCore: typeof RunTurnFn;
67
- eff: EffectHandler;
68
- toolManager: ToolManager;
69
- promptBuilder: PromptBuilder;
70
- memory?: MemoryStore;
71
- state: string;
72
- status: 'active' | 'stopped' = 'active';
73
- ctx: Ctx;
74
- _running = false;
75
- _subscribers = new Set<Subscriber>();
76
- _prevSnapshot: MachineSnapshot | null = null;
77
- _pendingFrames: IncomingFrame[] = [];
78
- _draining = false;
79
- _llmCalls = 0;
80
- _tokens = { total: 0, input: 0, output: 0 };
81
- _lastUserSenderId: string | null = null;
82
- _stateTimeoutUnhandled = false;
83
- _transitionTap: ((event: TransitionEvent) => void) | undefined;
84
-
85
- get llmCalls(): number { return this._llmCalls; }
86
- get tokens(): { total: number; input: number; output: number } { return this._tokens; }
87
- get stateTimeoutUnhandled(): boolean { return this._stateTimeoutUnhandled; }
88
-
89
- constructor({ workflow, executionCore, eff, toolManager, promptBuilder, memory, input, transitionTap }: MachineOptions) {
90
- this.workflow = workflow;
91
- this.executionCore = executionCore;
92
- this.eff = eff;
93
- this.toolManager = toolManager;
94
- this.promptBuilder = promptBuilder;
95
- this.memory = memory;
96
- this._transitionTap = transitionTap;
97
- this.state = input.state || workflow.initial;
98
- this.ctx = input.ctx
99
- ? {
100
- ...input.ctx,
101
- identity: input.identity,
102
- // Sessions persisted before pendingSubtasks/collectedResults existed
103
- // (DynamoDB rows live up to SESSION_TTL_SECONDS = 24h) restore without
104
- // these fields. Default them ONCE here — nowhere else.
105
- pendingSubtasks: input.ctx.pendingSubtasks ?? {},
106
- collectedResults: input.ctx.collectedResults ?? [],
107
- }
108
- : {
109
- identity: input.identity,
110
- activeAgreementId: null,
111
- activeTaskId: null,
112
- pendingProposalAgreementId: null,
113
- delegatedAgreementIds: [],
114
- pendingSubtasks: {},
115
- collectedResults: [],
116
- toolResults: [],
117
- lastOutcome: { kind: 'enter' },
118
- };
119
- }
120
-
121
- getSnapshot(): MachineSnapshot {
122
- return { value: this.state, ctx: this.ctx, status: this.status };
123
- }
124
-
125
- /** Parked = currently in a parked state and not executing a turn. */
126
- get isParked(): boolean {
127
- if (this._running) return false;
128
- const sd = this.workflow.states[this.state];
129
- return sd?.kind === 'parked';
130
- }
131
-
132
- subscribe(fn: Subscriber): { unsubscribe: () => void } {
133
- this._subscribers.add(fn);
134
- return { unsubscribe: () => this._subscribers.delete(fn) };
135
- }
136
-
137
- /**
138
- * Process an incoming wire event: convert to outcome → apply to ctx →
139
- * evaluate current state's transitions → re-enter or stop.
140
- *
141
- * Serialized via a single-slot queue: if a turn is already in flight, the
142
- * frame is held until the running turn settles, then drained. Without this,
143
- * an inbound event mid-turn re-entered _step with a stale state and a hot
144
- * `_running=true`, which spawned overlapping turns and re-created the
145
- * clarifyingDuringApproval feedback loop even after fixing the workflow
146
- * fall-through (ZIG-181).
147
- */
148
- async send(frame: IncomingFrame): Promise<void> {
149
- if (this.status !== 'active') return;
150
- this._pendingFrames.push(frame);
151
- if (this._draining) return;
152
- this._draining = true;
153
- try {
154
- while (this._pendingFrames.length) {
155
- const next = this._pendingFrames.shift()!;
156
- await this._handleFrame(next);
157
- }
158
- } finally {
159
- this._draining = false;
160
- }
161
- }
162
-
163
- async _handleFrame(frame: IncomingFrame): Promise<void> {
164
- if (this.status !== 'active') return;
165
- if (frame.identity) this.ctx.identity = frame.identity;
166
-
167
- const ev = frame.event;
168
- this._lastIncomingEvent = ev ?? null;
169
- if (ev?.senderId && String(ev?.senderType ?? '').toUpperCase() === 'USER') {
170
- this._lastUserSenderId = String(ev.senderId);
171
- }
172
- runtimeLog.debug(
173
- 'FSM',
174
- `_handleFrame ev.type=${ev?.type} ev.senderId=${ev?.senderId} ev.receiverId=${ev?.receiverId} myId=${this.ctx.identity?.agentId}`,
175
- );
176
- const outcome = outcomeFromEvent(ev, this.ctx.identity.agentId);
177
-
178
- // `outcomeFromEvent` never returns null — it falls back to `{ kind: 'enter' }`
179
- // when all events in a batch are no-ops (resource_changed, self-echo, etc.).
180
- // If a real raw event produced `enter`, that means the event carried no
181
- // meaningful signal for the FSM, so skip it entirely. Without this guard
182
- // `idle`'s unconditional `{ to: 'understanding' }` transition fires on every
183
- // resource_changed wake-up, kicking off an LLM turn that sends a duplicate
184
- // message, which triggers another resource_changed, and so on.
185
- if (ev && outcome.kind === 'enter') return;
186
-
187
- // Proposer detection must read pendingProposalAgreementId BEFORE
188
- // applyOutcomeToCtx clears it on resolution (buildOutcome.ts). Wire frames
189
- // carry no trustworthy proposer field — agreement_lifecycle drops `parties`
190
- // in normalizeIncomingEvent, and parties.creator is a principal id, not an
191
- // agentId (backend ZIG-272) — so the SDK's own "I made this proposal"
192
- // memory is the signal. Side effect we rely on: the first resolution clears
193
- // the pending id, so duplicate approval frames compute proposedByMe=false
194
- // and can never double-kickoff.
195
- if (outcome.kind === 'proposal-resolved') {
196
- outcome.proposedByMe =
197
- this.ctx.pendingProposalAgreementId !== null &&
198
- outcome.proposal.agreementId === this.ctx.pendingProposalAgreementId;
199
- }
200
-
201
- applyOutcomeToCtx(this.ctx, outcome);
202
- await this._step(outcome);
203
- }
204
-
205
- async _step(outcome: Outcome, depth = 0): Promise<void> {
206
- const fromState = this.state;
207
- const target = this._evaluateTransitions(outcome);
208
- const o = outcome as Record<string, unknown>;
209
- runtimeLog.debug(
210
- 'FSM',
211
- `_step from=${fromState} outcome.kind=${o?.kind} senderId=${o?.senderId ?? '<none>'} myId=${this.ctx.identity?.agentId ?? '<none>'} → target=${target ?? '(stay)'} depth=${depth}`,
212
- );
213
- if (target && target !== this.state) {
214
- this._transitionTap?.({ kind: 'transition', fromState, toState: target, outcomeKind: (outcome as Record<string, unknown>).kind as string, depth });
215
- this.state = target;
216
- this._notify();
217
- }
218
-
219
- // A state-timeout only enters at depth 0 (host-armed frame via _handleFrame;
220
- // turns cannot produce it — validateWorkflow rejects produces:'state-timeout').
221
- // No matching transition = the author declared timeoutMs but no route: park
222
- // loudly and tell the host not to re-arm (re-arming would error every
223
- // timeoutMs forever). Next real event still recovers the lane. A matched
224
- // transition (target !== null) — including an explicit self-loop — is
225
- // "handled" and re-arms as a heartbeat.
226
- if (outcome.kind === 'state-timeout' && depth === 0 && !target) {
227
- this._stateTimeoutUnhandled = true;
228
- runtimeLog.error(
229
- 'AgentMachine',
230
- `state=${this.state} timed out after ${outcome.waitedMs}ms but no transition matches { kind: 'state-timeout' } — parking without a timer. Add a state-timeout transition to "${this.state}" or remove timeoutMs.`,
231
- );
232
- this._transitionTap?.({ kind: 'timeout-unhandled', state: this.state, waitedMs: outcome.waitedMs });
233
- this._notify();
234
- return;
235
- }
236
-
237
- const sd = this.workflow.states[this.state];
238
- if (!sd) return;
239
- if (sd.kind === 'parked') {
240
- runtimeLog.debug('FSM', `_step parked state=${this.state} — exit`);
241
- // Notify so runtime detects park and resolves the wait promise.
242
- this._notify();
243
- return;
244
- }
245
-
246
- // A thinking turn that yields an outcome no transition handles must not
247
- // silently re-enter the same state and burn another LLM call (ZIG-303).
248
- // Explicit self-loops still match (target is non-null, even if target === state).
249
- if (
250
- sd.kind === 'thinking' &&
251
- depth > 0 &&
252
- fromState === this.state &&
253
- !target
254
- ) {
255
- if (await this._escapeToInitialParked(outcome, fromState)) return;
256
- runtimeLog.warn(
257
- 'AgentMachine',
258
- `state=${fromState} outcome.kind=${(outcome as Record<string, unknown>).kind} matched no transition; parking (depth=${depth})`,
259
- );
260
- this._transitionTap?.({ kind: 'no-match', state: fromState, outcomeKind: (outcome as Record<string, unknown>).kind as string, depth });
261
- await this._sendFallbackIfUserWaiting('Something went wrong. Please try again.');
262
- this._notify();
263
- return;
264
- }
265
-
266
- // Recursion / runaway-turn guard. Without this, a thinking state whose
267
- // transitions don't match the turn outcome (e.g. `delegating` not
268
- // catching `tool-result` from an agent_network search) re-enters the
269
- // same state forever — the LLM keeps re-rolling search/dummy actions
270
- // until something accidentally matches, burning tokens and emitting
271
- // duplicate side effects (ZIG-181: ziggs ran `discoverSpecialist` six
272
- // times before finally invoking `delegate`). 12 is well above any
273
- // legitimate same-state turn chain we exercise in tests; if we trip
274
- // it, treat the state as wedged and park.
275
- if (depth >= 12) {
276
- runtimeLog.warn(
277
- 'AgentMachine',
278
- `state=${this.state} runaway turn loop (depth=${depth}); parking`,
279
- );
280
- this._transitionTap?.({ kind: 'depth-guard', state: this.state, depth });
281
- await this._sendFallbackIfUserWaiting('Something went wrong. Please try again.');
282
- this._notify();
283
- return;
284
- }
285
- runtimeLog.debug('FSM', `_step thinking state=${this.state} — run turn`);
286
-
287
- // Thinking: run a turn, produce an outcome, re-step.
288
- this._running = true;
289
- try {
290
- const { outcome: turnOutcome, toolResults, llmCalls, tokens } = await this.executionCore({
291
- stateId: this.state,
292
- statePrompt: sd.prompt,
293
- actions: sd.actions,
294
- incomingEvent: this._lastIncomingEvent,
295
- ctx: this.ctx,
296
- eff: this.eff,
297
- toolManager: this.toolManager,
298
- promptBuilder: this.promptBuilder,
299
- memory: this.memory,
300
- definition: this.workflow,
301
- });
302
-
303
- this.ctx.toolResults = toolResults;
304
- this._llmCalls += llmCalls;
305
- this._tokens.total += tokens.total;
306
- this._tokens.input += tokens.input;
307
- this._tokens.output += tokens.output;
308
- applyOutcomeToCtx(this.ctx, turnOutcome);
309
- this._running = false;
310
- this._notify();
311
-
312
- await this._step(turnOutcome, depth + 1);
313
- } catch (error: unknown) {
314
- runtimeLog.error('AgentMachine', `state=${this.state} error: ${(error as Error)?.message || error}`);
315
- const errOutcome: Outcome = {
316
- kind: 'error',
317
- source: 'unknown',
318
- cause: (error as Error)?.message || String(error),
319
- retryable: false,
320
- };
321
- applyOutcomeToCtx(this.ctx, errOutcome);
322
- this._running = false;
323
- this._notify();
324
- // Try to fall through using current state's transitions; if none match
325
- // the error outcome the machine just parks (next event will re-enter).
326
- const fallback = this._evaluateTransitions(errOutcome);
327
- if (fallback && fallback !== this.state) {
328
- this.state = fallback;
329
- this._notify();
330
- } else {
331
- await this._sendFallbackIfUserWaiting('Something went wrong. Please try again.');
332
- }
333
- }
334
- }
335
-
336
- /** Error with no author-defined escape: park at workflow.initial if it is parked. */
337
- async _escapeToInitialParked(outcome: Outcome, fromState: string): Promise<boolean> {
338
- if (outcome.kind !== 'error') return false;
339
- const initial = this.workflow.initial;
340
- const initialSd = this.workflow.states[initial];
341
- if (!initialSd || initialSd.kind !== 'parked' || initial === fromState) {
342
- return false;
343
- }
344
- runtimeLog.warn(
345
- 'AgentMachine',
346
- `state=${fromState} error outcome had no transition — escaped to parked initial "${initial}"`,
347
- );
348
- this._transitionTap?.({ kind: 'error-escape', fromState, toState: initial });
349
- this.state = initial;
350
- // The turn failed and no workflow transition handled it — a waiting human
351
- // got nothing, so apologize before parking (same text as the other parks).
352
- await this._sendFallbackIfUserWaiting('Something went wrong. Please try again.');
353
- this._notify();
354
- return true;
355
- }
356
-
357
- /** Sends a short fallback to the last known human user when the machine parks unexpectedly. Best-effort — never throws. */
358
- async _sendFallbackIfUserWaiting(text: string): Promise<void> {
359
- const userId = this._lastUserSenderId;
360
- if (!userId) return;
361
- try {
362
- await this.eff({ kind: 'send-message', sessionId: this.ctx.identity.sessionId, receiverId: userId, text });
363
- } catch { /* best-effort */ }
364
- }
365
-
366
- _evaluateTransitions(outcome: Outcome): string | null {
367
- const sd = this.workflow.states[this.state];
368
- if (!sd?.transitions?.length) {
369
- runtimeLog.debug('FSM', `evaluate state=${this.state}: NO TRANSITIONS DEFINED`);
370
- return null;
371
- }
372
- for (let i = 0; i < sd.transitions.length; i++) {
373
- const rule = sd.transitions[i]!;
374
- let matched: boolean;
375
- let err: unknown = null;
376
- if (!rule.when) {
377
- matched = true;
378
- } else {
379
- try { matched = !!rule.when(outcome, this.ctx); }
380
- catch (e) { matched = false; err = e; }
381
- }
382
- runtimeLog.debug(
383
- 'FSM',
384
- `evaluate state=${this.state} rule[${i}] to=${rule.to} when=${rule.when ? 'fn' : 'always'} → ${matched}${err ? ` ERR=${(err as Error).message}` : ''}`,
385
- );
386
- if (matched) return rule.to;
387
- }
388
- runtimeLog.debug('FSM', `evaluate state=${this.state}: NONE matched`);
389
- return null;
390
- }
391
-
392
- _notify(): void {
393
- const snapshot = this.getSnapshot();
394
- for (const fn of this._subscribers) {
395
- try { fn(snapshot); } catch {}
396
- }
397
- }
398
-
399
- // Held so PromptBuilder/runTurn can render the original wire event in <event>.
400
- // Set by the runtime layer when it calls send(); we don't classify it twice.
401
- _lastIncomingEvent: RawEvent | null = null;
402
- }