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