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