@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.
Files changed (218) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +41 -2
  3. package/dist/AgentHost.d.ts +201 -0
  4. package/dist/AgentHost.js +652 -0
  5. package/dist/adapters/AnthropicAdapter.d.ts +39 -0
  6. package/dist/adapters/AnthropicAdapter.js +200 -0
  7. package/dist/adapters/McpAdapter.d.ts +199 -0
  8. package/dist/adapters/McpAdapter.js +468 -0
  9. package/dist/adapters/OpenAIAdapter.d.ts +26 -0
  10. package/dist/adapters/OpenAIAdapter.js +158 -0
  11. package/dist/adapters/index.js +2 -0
  12. package/dist/agent/Agent.d.ts +78 -0
  13. package/dist/agent/Agent.js +58 -0
  14. package/dist/agent/ClaudeSdkAgent.d.ts +38 -0
  15. package/dist/agent/ClaudeSdkAgent.js +322 -0
  16. package/dist/agent/claudeCognition.d.ts +67 -0
  17. package/dist/agent/claudeCognition.js +103 -0
  18. package/dist/agent/claudeSdkProtocol.d.ts +11 -0
  19. package/dist/agent/claudeSdkTools.d.ts +19 -0
  20. package/dist/agent/claudeSdkTools.js +57 -0
  21. package/dist/agent/hostedAgentConnection.d.ts +15 -0
  22. package/dist/agent/hostedAgentConnection.js +29 -0
  23. package/dist/agent/toolManagerToSdkMcp.d.ts +12 -0
  24. package/dist/agent/toolManagerToSdkMcp.js +123 -0
  25. package/dist/brain/index.d.ts +50 -0
  26. package/dist/brain/index.js +45 -0
  27. package/dist/cognition/validateContext.d.ts +11 -0
  28. package/dist/cognition/validateContext.js +117 -0
  29. package/dist/context/applyEffects.d.ts +2 -0
  30. package/dist/context/applyEffects.js +89 -0
  31. package/dist/context/batch.d.ts +2 -0
  32. package/dist/context/batch.js +18 -0
  33. package/dist/context/classifyEnvelope.d.ts +1 -0
  34. package/dist/context/classifyEnvelope.js +58 -0
  35. package/dist/context/routingLabels.d.ts +4 -0
  36. package/dist/context/routingLabels.js +48 -0
  37. package/dist/defineAgent.d.ts +14 -0
  38. package/dist/defineAgent.js +68 -0
  39. package/dist/formatters/AgreementFormatter.d.ts +18 -0
  40. package/dist/formatters/AgreementFormatter.js +130 -0
  41. package/dist/formatters/HistoryFormatter.d.ts +26 -0
  42. package/dist/formatters/HistoryFormatter.js +173 -0
  43. package/dist/formatters/index.js +2 -0
  44. package/{src/index.ts → dist/index.d.ts} +7 -53
  45. package/dist/index.js +66 -0
  46. package/dist/ingress/normalizeIncoming.d.ts +65 -0
  47. package/dist/ingress/normalizeIncoming.js +88 -0
  48. package/dist/memory/MemoryStore.d.ts +55 -0
  49. package/dist/memory/MemoryStore.js +78 -0
  50. package/dist/pricing/fleetDefaults.d.ts +46 -0
  51. package/dist/pricing/fleetDefaults.js +168 -0
  52. package/dist/pricing/fleetEvalFree.d.ts +7 -0
  53. package/dist/pricing/fleetEvalFree.js +24 -0
  54. package/dist/pricing/fleetFreeTierA.gen.d.ts +6 -0
  55. package/{src/pricing/fleetFreeTierA.gen.ts → dist/pricing/fleetFreeTierA.gen.js} +5 -6
  56. package/dist/pricing/fleetTierByAgentId.gen.d.ts +7 -0
  57. package/dist/pricing/fleetTierByAgentId.gen.js +768 -0
  58. package/dist/runtime/AgentMachine.d.ts +143 -0
  59. package/dist/runtime/AgentMachine.js +400 -0
  60. package/dist/runtime/PromptBuilder.d.ts +96 -0
  61. package/dist/runtime/PromptBuilder.js +439 -0
  62. package/{src/runtime/bootstrapCtx.ts → dist/runtime/bootstrapCtx.d.ts} +1 -22
  63. package/dist/runtime/bootstrapCtx.js +37 -0
  64. package/dist/runtime/buildOutcome.d.ts +68 -0
  65. package/dist/runtime/buildOutcome.js +464 -0
  66. package/dist/runtime/defaults.d.ts +54 -0
  67. package/dist/runtime/defaults.js +47 -0
  68. package/dist/runtime/deriveRespondsToProposals.d.ts +9 -0
  69. package/dist/runtime/deriveRespondsToProposals.js +38 -0
  70. package/dist/runtime/kickoff.d.ts +15 -0
  71. package/dist/runtime/kickoff.js +112 -0
  72. package/dist/runtime/runMechanical.d.ts +25 -0
  73. package/dist/runtime/runMechanical.js +74 -0
  74. package/dist/runtime/runTurn.d.ts +63 -0
  75. package/dist/runtime/runTurn.js +800 -0
  76. package/dist/runtime/validateWorkflow.d.ts +17 -0
  77. package/dist/runtime/validateWorkflow.js +209 -0
  78. package/dist/server/ConnectionPool.d.ts +68 -0
  79. package/dist/server/ConnectionPool.js +166 -0
  80. package/dist/server/EventQueue.d.ts +33 -0
  81. package/dist/server/EventQueue.js +98 -0
  82. package/dist/server/InboxCatchUp.d.ts +24 -0
  83. package/dist/server/InboxCatchUp.js +214 -0
  84. package/dist/server/OutboxBuffer.d.ts +33 -0
  85. package/dist/server/OutboxBuffer.js +68 -0
  86. package/dist/server/SeenMessages.d.ts +13 -0
  87. package/dist/server/SeenMessages.js +31 -0
  88. package/dist/server/StateTimers.d.ts +34 -0
  89. package/dist/server/StateTimers.js +70 -0
  90. package/dist/server/ZiggsEffectHandler.d.ts +79 -0
  91. package/dist/server/ZiggsEffectHandler.js +319 -0
  92. package/dist/server/agreements/AgreementService.d.ts +50 -0
  93. package/dist/server/agreements/AgreementService.js +85 -0
  94. package/dist/server/createHealthServer.d.ts +7 -0
  95. package/dist/server/createHealthServer.js +75 -0
  96. package/dist/server/proactive/ProactiveTrigger.d.ts +33 -0
  97. package/dist/server/proactive/ProactiveTrigger.js +71 -0
  98. package/dist/server/runLauncher.d.ts +28 -0
  99. package/dist/server/runLauncher.js +93 -0
  100. package/dist/server/tasks/TaskService.d.ts +25 -0
  101. package/dist/server/tasks/TaskService.js +103 -0
  102. package/dist/server/tasks/index.js +1 -0
  103. package/dist/server/telemetryIngest.d.ts +24 -0
  104. package/dist/server/telemetryIngest.js +62 -0
  105. package/dist/server/tools/index.d.ts +24 -0
  106. package/{src/server/tools/index.ts → dist/server/tools/index.js} +4 -24
  107. package/dist/server/tools/tier1/protocolRunner.d.ts +39 -0
  108. package/dist/server/tools/tier1/protocolRunner.js +288 -0
  109. package/dist/server/tools/tier1/protocolTools.d.ts +12 -0
  110. package/dist/server/tools/tier1/protocolTools.js +37 -0
  111. package/dist/server/tools/tier2/connectionTools.d.ts +4 -0
  112. package/dist/server/tools/tier2/connectionTools.js +63 -0
  113. package/dist/server/tools/tier2/contextTools.d.ts +4 -0
  114. package/dist/server/tools/tier2/contextTools.js +46 -0
  115. package/dist/server/tools/tier2/discoveryTools.d.ts +4 -0
  116. package/dist/server/tools/tier2/discoveryTools.js +25 -0
  117. package/dist/server/tools/tier2/marketplaceTools.d.ts +3 -0
  118. package/dist/server/tools/tier2/marketplaceTools.js +22 -0
  119. package/dist/server/tools/tier2/paymentTools.d.ts +12 -0
  120. package/dist/server/tools/tier2/paymentTools.js +165 -0
  121. package/dist/server/ziggsconnect/ZiggsConnectClient.d.ts +35 -0
  122. package/dist/server/ziggsconnect/ZiggsConnectClient.js +95 -0
  123. package/dist/server/ziggscontext/ZiggsContextClient.d.ts +53 -0
  124. package/dist/server/ziggscontext/ZiggsContextClient.js +124 -0
  125. package/dist/server/ziggspay/ZiggsPayClient.d.ts +82 -0
  126. package/dist/server/ziggspay/ZiggsPayClient.js +203 -0
  127. package/dist/shared/ids.d.ts +1 -0
  128. package/dist/shared/ids.js +3 -0
  129. package/dist/shared/runtimeLog.d.ts +18 -0
  130. package/dist/shared/runtimeLog.js +68 -0
  131. package/dist/shared/types.d.ts +22 -0
  132. package/dist/shared/types.js +23 -0
  133. package/dist/tasks/protocolRegistry.d.ts +16 -0
  134. package/dist/tasks/protocolRegistry.js +20 -0
  135. package/dist/tools/ToolManager.d.ts +12 -0
  136. package/dist/tools/ToolManager.js +74 -0
  137. package/dist/tools/ToolProvider.d.ts +6 -0
  138. package/dist/tools/ToolProvider.js +21 -0
  139. package/dist/tools/defineTool.d.ts +27 -0
  140. package/dist/tools/defineTool.js +62 -0
  141. package/{src/tools/index.ts → dist/tools/index.d.ts} +0 -1
  142. package/dist/tools/index.js +6 -0
  143. package/dist/tools/recordReport.d.ts +41 -0
  144. package/dist/tools/recordReport.js +30 -0
  145. package/dist/types.d.ts +466 -0
  146. package/dist/types.js +7 -0
  147. package/dist/utils/jsonExtractor.d.ts +2 -0
  148. package/dist/utils/jsonExtractor.js +111 -0
  149. package/package.json +14 -6
  150. package/src/AgentHost.ts +0 -814
  151. package/src/adapters/AnthropicAdapter.ts +0 -238
  152. package/src/adapters/McpAdapter.ts +0 -678
  153. package/src/adapters/OpenAIAdapter.ts +0 -194
  154. package/src/agent/Agent.ts +0 -112
  155. package/src/agent/ClaudeSdkAgent.ts +0 -401
  156. package/src/agent/claudeCognition.ts +0 -139
  157. package/src/agent/claudeSdkTools.ts +0 -81
  158. package/src/agent/hostedAgentConnection.ts +0 -41
  159. package/src/agent/toolManagerToSdkMcp.ts +0 -136
  160. package/src/cognition/validateContext.ts +0 -95
  161. package/src/context/applyEffects.ts +0 -80
  162. package/src/context/batch.ts +0 -19
  163. package/src/context/classifyEnvelope.ts +0 -38
  164. package/src/context/routingLabels.ts +0 -46
  165. package/src/defineAgent.ts +0 -77
  166. package/src/formatters/AgreementFormatter.ts +0 -111
  167. package/src/formatters/HistoryFormatter.ts +0 -172
  168. package/src/ingress/normalizeIncoming.ts +0 -162
  169. package/src/memory/MemoryStore.ts +0 -104
  170. package/src/pricing/fleetDefaults.ts +0 -225
  171. package/src/pricing/fleetEvalFree.ts +0 -24
  172. package/src/pricing/fleetTierByAgentId.gen.ts +0 -775
  173. package/src/runtime/AgentMachine.ts +0 -484
  174. package/src/runtime/PromptBuilder.ts +0 -522
  175. package/src/runtime/buildOutcome.ts +0 -563
  176. package/src/runtime/defaults.ts +0 -86
  177. package/src/runtime/deriveRespondsToProposals.ts +0 -35
  178. package/src/runtime/kickoff.ts +0 -117
  179. package/src/runtime/runMechanical.ts +0 -106
  180. package/src/runtime/runTurn.ts +0 -870
  181. package/src/runtime/validateWorkflow.ts +0 -221
  182. package/src/server/ConnectionPool.ts +0 -206
  183. package/src/server/EventQueue.ts +0 -133
  184. package/src/server/InboxCatchUp.ts +0 -291
  185. package/src/server/OutboxBuffer.ts +0 -90
  186. package/src/server/SeenMessages.ts +0 -27
  187. package/src/server/StateTimers.ts +0 -85
  188. package/src/server/ZiggsEffectHandler.ts +0 -427
  189. package/src/server/agreements/AgreementService.ts +0 -118
  190. package/src/server/createHealthServer.ts +0 -85
  191. package/src/server/proactive/ProactiveTrigger.ts +0 -83
  192. package/src/server/runLauncher.ts +0 -146
  193. package/src/server/tasks/TaskService.ts +0 -111
  194. package/src/server/telemetryIngest.ts +0 -91
  195. package/src/server/tools/tier1/protocolRunner.ts +0 -353
  196. package/src/server/tools/tier1/protocolTools.ts +0 -114
  197. package/src/server/tools/tier2/connectionTools.ts +0 -75
  198. package/src/server/tools/tier2/contextTools.ts +0 -63
  199. package/src/server/tools/tier2/discoveryTools.ts +0 -34
  200. package/src/server/tools/tier2/marketplaceTools.ts +0 -27
  201. package/src/server/tools/tier2/paymentTools.ts +0 -170
  202. package/src/server/ziggsconnect/ZiggsConnectClient.ts +0 -126
  203. package/src/server/ziggscontext/ZiggsContextClient.ts +0 -129
  204. package/src/server/ziggspay/ZiggsPayClient.ts +0 -193
  205. package/src/shared/ids.ts +0 -3
  206. package/src/shared/runtimeLog.ts +0 -72
  207. package/src/shared/types.ts +0 -29
  208. package/src/tasks/protocolRegistry.ts +0 -25
  209. package/src/tools/ToolManager.ts +0 -95
  210. package/src/tools/ToolProvider.ts +0 -19
  211. package/src/tools/defineTool.ts +0 -90
  212. package/src/tools/recordReport.ts +0 -82
  213. package/src/types.ts +0 -483
  214. package/src/utils/jsonExtractor.ts +0 -100
  215. /package/{src/adapters/index.ts → dist/adapters/index.d.ts} +0 -0
  216. /package/{src/agent/claudeSdkProtocol.ts → dist/agent/claudeSdkProtocol.js} +0 -0
  217. /package/{src/formatters/index.ts → dist/formatters/index.d.ts} +0 -0
  218. /package/{src/server/tasks/index.ts → dist/server/tasks/index.d.ts} +0 -0
@@ -0,0 +1,203 @@
1
+ import 'dotenv/config';
2
+ function getDefaultBaseUrl() {
3
+ return process.env.BACKEND_URL || process.env.ZIGGS_BACKEND_URL || 'http://localhost:3000';
4
+ }
5
+ function randomIdempotencyKey(prefix = 'op') {
6
+ return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
7
+ }
8
+ function parseError(text, fallback) {
9
+ if (!text)
10
+ return fallback;
11
+ try {
12
+ const parsed = JSON.parse(text);
13
+ return parsed['error'] || parsed['message'] || text;
14
+ }
15
+ catch {
16
+ return text;
17
+ }
18
+ }
19
+ export class ZiggsPayClient {
20
+ operatorKey;
21
+ actAsAgentId;
22
+ baseUrl;
23
+ constructor({ operatorKey, actAsAgentId, baseUrl }) {
24
+ if (!operatorKey || typeof operatorKey !== 'string')
25
+ throw new Error('ZiggsPayClient requires an operatorKey');
26
+ this.operatorKey = operatorKey;
27
+ this.actAsAgentId = actAsAgentId || null;
28
+ this.baseUrl = baseUrl || getDefaultBaseUrl();
29
+ }
30
+ async balance() {
31
+ const w = await this._get('/payments/wallet');
32
+ const wallet = w['wallet'];
33
+ return { walletId: wallet?.['walletId'] || null, currency: wallet?.['currency'] || 'pez', balance: w['balance'] ?? 0, availableBalance: w['availableBalance'] ?? 0 };
34
+ }
35
+ async resolve({ userId, agentId } = {}) {
36
+ if (!userId && !agentId)
37
+ throw new Error('resolve: provide userId or agentId');
38
+ const params = new URLSearchParams();
39
+ if (userId)
40
+ params.set('userId', userId);
41
+ if (agentId)
42
+ params.set('agentId', agentId);
43
+ const res = await this._get(`/payments/wallets/resolve?${params}`);
44
+ return res['wallet'] || null;
45
+ }
46
+ async transfer({ to, amount, idempotencyKey, description, paymentGrantId }) {
47
+ if (!to)
48
+ throw new Error('transfer: `to` is required');
49
+ if (!(Number.isInteger(amount) && amount > 0))
50
+ throw new Error('transfer: `amount` must be a positive integer (cents)');
51
+ if (this.actAsAgentId && !paymentGrantId)
52
+ throw new Error('transfer: paymentGrantId is required for agent-impersonated transfers. The wallet owner must have issued a payment grant to this agentId.');
53
+ let toWalletId = to;
54
+ if (!to.startsWith('wal_')) {
55
+ const w = await this.resolve(to.startsWith('agent_') ? { agentId: to } : { userId: to });
56
+ if (!w?.['walletId'])
57
+ throw new Error(`transfer: could not resolve wallet for "${to}"`);
58
+ toWalletId = w['walletId'];
59
+ }
60
+ const result = await this._post('/payments/transfer', { toWalletId, amount, idempotencyKey: idempotencyKey || randomIdempotencyKey('xfer'), description, paymentGrantId });
61
+ if (result?.['status'] === 'approval_required') {
62
+ const approval = result['approval'] || {};
63
+ return { status: 'approval_required', approvalId: approval['approvalId'] || null, expiresAt: approval['expiresAt'] || null, reason: approval['reason'] || 'Amount exceeds auto-approve threshold', toWalletId, amount };
64
+ }
65
+ const tx = result?.['transaction'];
66
+ return { status: 'transferred', transactionId: tx?.['transactionId'] || null, toWalletId, amount };
67
+ }
68
+ async hold({ amount, idempotencyKey, description }) {
69
+ if (!(Number.isInteger(amount) && amount > 0))
70
+ throw new Error('hold: `amount` must be a positive integer (cents)');
71
+ return this._post('/payments/hold', { amount, idempotencyKey: idempotencyKey || randomIdempotencyKey('hold'), description });
72
+ }
73
+ async release({ holdId, action = 'complete', toWalletId, idempotencyKey }) {
74
+ return this._post(`/payments/release/${holdId}`, { idempotencyKey: idempotencyKey || randomIdempotencyKey('rel'), action, toWalletId });
75
+ }
76
+ async history(params = {}) {
77
+ const q = new URLSearchParams();
78
+ if (params.limit != null)
79
+ q.set('limit', String(params.limit));
80
+ if (params.offset != null)
81
+ q.set('offset', String(params.offset));
82
+ if (params.type)
83
+ q.set('type', params.type);
84
+ return this._get('/payments/history' + (q.toString() ? `?${q}` : ''));
85
+ }
86
+ async issueGrant({ holderId, caveats }) {
87
+ return this._post('/payments/grants', { holderId, caveats });
88
+ }
89
+ async attenuateGrant({ grantId, holderId, caveats }) {
90
+ return this._post(`/payments/grants/${grantId}/attenuate`, { holderId, caveats });
91
+ }
92
+ async revokeGrant(grantId) {
93
+ return this._request('DELETE', `/payments/grants/${grantId}`, undefined);
94
+ }
95
+ async listGrants() {
96
+ // GET /payments/grants was retired (ZIG-648); wallet grants the acting agent
97
+ // holds are listed via the unified GET /grants. Follow the cursor so a holder
98
+ // with more than one page isn't truncated; live grants only.
99
+ const all = [];
100
+ let cursor;
101
+ for (let page = 0; page < 50; page++) {
102
+ const q = new URLSearchParams({ scopeKind: 'wallet', health: 'active' });
103
+ if (cursor)
104
+ q.set('cursor', cursor);
105
+ const res = (await this._get(`/grants?${q.toString()}`));
106
+ all.push(...(res['items'] || []));
107
+ const next = res['nextCursor'];
108
+ if (!next)
109
+ break;
110
+ cursor = next;
111
+ }
112
+ return all;
113
+ }
114
+ async createTopUpIntent({ amount, description, currency } = {}) {
115
+ return this._post('/payments/onramp/intent', { amount, description, currency });
116
+ }
117
+ async confirmMockIntent(intentId) {
118
+ return this._post(`/payments/onramp/mock-confirm/${intentId}`, {});
119
+ }
120
+ async faucet({ amount, description = 'Faucet', idempotencyKey } = {}) {
121
+ return this._post('/payments/wallet/fund', { amount, idempotencyKey: idempotencyKey || randomIdempotencyKey('faucet'), description });
122
+ }
123
+ async approvals({ status = 'pending' } = {}) {
124
+ const res = await this._get(`/payments/approvals?status=${encodeURIComponent(status)}`);
125
+ return res['approvals'] || [];
126
+ }
127
+ async getApproval(approvalId) {
128
+ if (!approvalId)
129
+ throw new Error('getApproval: approvalId is required');
130
+ try {
131
+ const res = await this._get(`/payments/approvals/${approvalId}`);
132
+ return res?.['approval'] || null;
133
+ }
134
+ catch (err) {
135
+ if (err.status === 404)
136
+ return null;
137
+ throw err;
138
+ }
139
+ }
140
+ async decide(approvalId, decision, note = '') {
141
+ return this._post(`/payments/approvals/${approvalId}/decide`, { decision, note });
142
+ }
143
+ async waitForApproval(approvalId, opts = {}) {
144
+ const pollMs = Math.max(500, opts.pollMs ?? 3_000);
145
+ const timeoutMs = Math.max(pollMs, opts.timeoutMs ?? 120_000);
146
+ const signal = opts.signal;
147
+ const deadline = Date.now() + timeoutMs;
148
+ const sleep = (ms) => new Promise((resolve, reject) => {
149
+ const timer = setTimeout(resolve, ms);
150
+ if (signal) {
151
+ if (signal.aborted) {
152
+ clearTimeout(timer);
153
+ reject(new Error('aborted'));
154
+ return;
155
+ }
156
+ signal.addEventListener('abort', () => { clearTimeout(timer); reject(new Error('aborted')); }, { once: true });
157
+ }
158
+ });
159
+ while (true) {
160
+ if (signal?.aborted)
161
+ throw new Error('aborted');
162
+ const approval = await this.getApproval(approvalId);
163
+ if (!approval)
164
+ return { status: 'gone' };
165
+ const s = approval['status'];
166
+ if (s === 'executed')
167
+ return { status: 'executed', approval, transactionId: approval['executedTransactionId'] || null };
168
+ if (s === 'rejected')
169
+ return { status: 'rejected', approval };
170
+ if (s === 'expired')
171
+ return { status: 'expired', approval };
172
+ const remaining = deadline - Date.now();
173
+ if (remaining <= 0)
174
+ return { status: 'timeout', approval };
175
+ await sleep(Math.min(pollMs, remaining));
176
+ }
177
+ }
178
+ _buildHeaders(extra = {}) {
179
+ const h = { Authorization: `Bearer ${this.operatorKey}`, ...extra };
180
+ if (this.actAsAgentId)
181
+ h['X-Agent-Id'] = this.actAsAgentId;
182
+ return h;
183
+ }
184
+ async _request(method, path, body) {
185
+ const init = { method, headers: this._buildHeaders(body !== undefined ? { 'content-type': 'application/json' } : {}) };
186
+ if (body !== undefined)
187
+ init.body = JSON.stringify(body);
188
+ const response = await fetch(`${this.baseUrl}${path}`, init);
189
+ const text = await response.text();
190
+ if (!response.ok) {
191
+ const err = new Error(parseError(text, `HTTP ${response.status}`));
192
+ err.status = response.status;
193
+ err.body = text;
194
+ throw err;
195
+ }
196
+ return text ? JSON.parse(text) : null;
197
+ }
198
+ _get(path) { return this._request('GET', path, undefined); }
199
+ _post(path, body) { return this._request('POST', path, body ?? {}); }
200
+ }
201
+ export function createZiggsPayClient(opts) {
202
+ return new ZiggsPayClient(opts);
203
+ }
@@ -0,0 +1 @@
1
+ export declare function generateId(): string;
@@ -0,0 +1,3 @@
1
+ export function generateId() {
2
+ return `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
3
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Process-wide log levels for agentplus runtimes. Default is `info` so FSM /
3
+ * socket chatter stays quiet unless operators opt in.
4
+ *
5
+ * Env (first match wins for the debug shortcut):
6
+ * - `DEBUG_AGENTPLUS=1` or `AGENTPLUS_DEBUG=1` → threshold `debug`
7
+ * - `LOG_LEVEL` or `AGENTPLUS_LOG_LEVEL` → `debug` | `info` | `warn` | `error` | `silent`
8
+ * (`silent` keeps only `error` output)
9
+ */
10
+ export type RuntimeLogLevel = 'debug' | 'info' | 'warn' | 'error';
11
+ /** Test hook: re-read env after `process.env` mutations. */
12
+ export declare function resetRuntimeLogLevelCache(): void;
13
+ export declare const runtimeLog: {
14
+ debug(scope: string, msg: string, ...rest: unknown[]): void;
15
+ info(scope: string, msg: string, ...rest: unknown[]): void;
16
+ warn(scope: string, msg: string, ...rest: unknown[]): void;
17
+ error(scope: string, msg: string, ...rest: unknown[]): void;
18
+ };
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Process-wide log levels for agentplus runtimes. Default is `info` so FSM /
3
+ * socket chatter stays quiet unless operators opt in.
4
+ *
5
+ * Env (first match wins for the debug shortcut):
6
+ * - `DEBUG_AGENTPLUS=1` or `AGENTPLUS_DEBUG=1` → threshold `debug`
7
+ * - `LOG_LEVEL` or `AGENTPLUS_LOG_LEVEL` → `debug` | `info` | `warn` | `error` | `silent`
8
+ * (`silent` keeps only `error` output)
9
+ */
10
+ const SEVERITY = {
11
+ debug: 0,
12
+ info: 1,
13
+ warn: 2,
14
+ error: 3,
15
+ };
16
+ function parseThreshold() {
17
+ if (process.env.DEBUG_AGENTPLUS === '1' || process.env.AGENTPLUS_DEBUG === '1') {
18
+ return SEVERITY.debug;
19
+ }
20
+ const raw = (process.env.LOG_LEVEL ||
21
+ process.env.AGENTPLUS_LOG_LEVEL ||
22
+ 'info').toLowerCase();
23
+ if (raw === 'silent' || raw === 'none')
24
+ return SEVERITY.error;
25
+ if (raw === 'debug' || raw === 'trace')
26
+ return SEVERITY.debug;
27
+ if (raw === 'warn')
28
+ return SEVERITY.warn;
29
+ if (raw === 'error')
30
+ return SEVERITY.error;
31
+ return SEVERITY.info;
32
+ }
33
+ let cachedThreshold = null;
34
+ function threshold() {
35
+ if (cachedThreshold === null)
36
+ cachedThreshold = parseThreshold();
37
+ return cachedThreshold;
38
+ }
39
+ /** Test hook: re-read env after `process.env` mutations. */
40
+ export function resetRuntimeLogLevelCache() {
41
+ cachedThreshold = null;
42
+ }
43
+ function shouldEmit(level) {
44
+ return SEVERITY[level] >= threshold();
45
+ }
46
+ function fmt(scope, msg) {
47
+ return `[${scope}] ${msg}`;
48
+ }
49
+ export const runtimeLog = {
50
+ debug(scope, msg, ...rest) {
51
+ if (!shouldEmit('debug'))
52
+ return;
53
+ console.log(fmt(scope, msg), ...rest);
54
+ },
55
+ info(scope, msg, ...rest) {
56
+ if (!shouldEmit('info'))
57
+ return;
58
+ console.log(fmt(scope, msg), ...rest);
59
+ },
60
+ warn(scope, msg, ...rest) {
61
+ if (!shouldEmit('warn'))
62
+ return;
63
+ console.warn(fmt(scope, msg), ...rest);
64
+ },
65
+ error(scope, msg, ...rest) {
66
+ console.error(fmt(scope, msg), ...rest);
67
+ },
68
+ };
@@ -0,0 +1,22 @@
1
+ export declare const EntryTypes: {
2
+ readonly MESSAGE: "message";
3
+ readonly NOTIFICATION: "notification";
4
+ readonly ARTIFACT: "artifact";
5
+ readonly TASK_HISTORY: "task_history";
6
+ };
7
+ export type EntryType = (typeof EntryTypes)[keyof typeof EntryTypes];
8
+ export declare const ContentTypes: {
9
+ readonly TEXT: "text";
10
+ readonly OPERATION: "operation";
11
+ readonly CONTEXT: "context";
12
+ readonly RESULT: "result";
13
+ readonly TASK_UPDATE: "task_update";
14
+ readonly THOUGHT: "thought";
15
+ };
16
+ export type ContentType = (typeof ContentTypes)[keyof typeof ContentTypes];
17
+ export declare const ContextProperties: {
18
+ readonly HISTORY: "history";
19
+ readonly AGREEMENTS: "agreements";
20
+ readonly AGENTS: "agents";
21
+ readonly USERS: "users";
22
+ };
@@ -0,0 +1,23 @@
1
+ // Inlined from `@ziggs-ai/api-client` so the pure SDK doesn't depend on the
2
+ // Ziggs HTTP client. Both client and server agree on these string constants
3
+ // because the protocol is the same — they're just two views of one schema.
4
+ export const EntryTypes = {
5
+ MESSAGE: 'message',
6
+ NOTIFICATION: 'notification',
7
+ ARTIFACT: 'artifact',
8
+ TASK_HISTORY: 'task_history',
9
+ };
10
+ export const ContentTypes = {
11
+ TEXT: 'text',
12
+ OPERATION: 'operation',
13
+ CONTEXT: 'context',
14
+ RESULT: 'result',
15
+ TASK_UPDATE: 'task_update',
16
+ THOUGHT: 'thought',
17
+ };
18
+ export const ContextProperties = {
19
+ HISTORY: 'history',
20
+ AGREEMENTS: 'agreements',
21
+ AGENTS: 'agents',
22
+ USERS: 'users',
23
+ };
@@ -0,0 +1,16 @@
1
+ export declare const PROTOCOL_TOOL_TO_OPERATION: Readonly<{
2
+ readonly agreement_propose: "agreement-propose";
3
+ readonly agreement_subcontract: "agreement-subcontract";
4
+ readonly agreement_respond: "agreement-respond";
5
+ readonly agreement_counter_proposal: "agreement-counter-proposal";
6
+ readonly agreement_check_proposal: "agreement-check-proposal";
7
+ readonly agreement_revoke: "agreement-revoke";
8
+ readonly task_spawn: "task-spawn";
9
+ readonly task_update: "task-update";
10
+ readonly task_update_plan_step: "task-update-plan-step";
11
+ }>;
12
+ export type ProtocolToolName = keyof typeof PROTOCOL_TOOL_TO_OPERATION;
13
+ export type ProtocolOperation = (typeof PROTOCOL_TOOL_TO_OPERATION)[ProtocolToolName];
14
+ export declare const PROTOCOL_TOOL_NAMES: readonly ProtocolToolName[];
15
+ export declare function mapProtocolToolToOperation(toolName: string): ProtocolOperation | null;
16
+ export declare function isProtocolToolName(toolName: string): toolName is ProtocolToolName;
@@ -0,0 +1,20 @@
1
+ export const PROTOCOL_TOOL_TO_OPERATION = Object.freeze({
2
+ agreement_propose: 'agreement-propose',
3
+ agreement_subcontract: 'agreement-subcontract',
4
+ agreement_respond: 'agreement-respond',
5
+ agreement_counter_proposal: 'agreement-counter-proposal',
6
+ agreement_check_proposal: 'agreement-check-proposal',
7
+ agreement_revoke: 'agreement-revoke',
8
+ task_spawn: 'task-spawn',
9
+ task_update: 'task-update',
10
+ task_update_plan_step: 'task-update-plan-step',
11
+ });
12
+ export const PROTOCOL_TOOL_NAMES = Object.freeze(Object.keys(PROTOCOL_TOOL_TO_OPERATION));
13
+ export function mapProtocolToolToOperation(toolName) {
14
+ if (!toolName || typeof toolName !== 'string')
15
+ return null;
16
+ return PROTOCOL_TOOL_TO_OPERATION[toolName] ?? null;
17
+ }
18
+ export function isProtocolToolName(toolName) {
19
+ return mapProtocolToolToOperation(toolName) != null;
20
+ }
@@ -0,0 +1,12 @@
1
+ import { ToolProvider } from './ToolProvider.js';
2
+ import type { ToolDefinition } from './defineTool.js';
3
+ export declare class ToolManager extends ToolProvider {
4
+ private tools;
5
+ constructor();
6
+ register(tool: ToolDefinition): string;
7
+ registerAll(tools?: ToolDefinition[]): void;
8
+ getAvailableTools(): Promise<ToolDefinition[]>;
9
+ getTool(name: string): ToolDefinition | null;
10
+ executeTool(name: string, args?: Record<string, unknown>, context?: Record<string, unknown>): Promise<unknown>;
11
+ private _validateArgs;
12
+ }
@@ -0,0 +1,74 @@
1
+ import AjvModule from 'ajv';
2
+ import { ToolProvider } from './ToolProvider.js';
3
+ const AjvClass = AjvModule.default ?? AjvModule;
4
+ const ajv = new AjvClass({ allErrors: true, strict: false });
5
+ function makeError(message, type, extra) {
6
+ const err = new Error(message);
7
+ err.type = type;
8
+ if (extra)
9
+ Object.assign(err, extra);
10
+ return err;
11
+ }
12
+ function stripNullish(args) {
13
+ if (!args || typeof args !== 'object' || Array.isArray(args))
14
+ return args;
15
+ const out = {};
16
+ for (const [k, v] of Object.entries(args)) {
17
+ if (v !== null && v !== undefined)
18
+ out[k] = v;
19
+ }
20
+ return out;
21
+ }
22
+ export class ToolManager extends ToolProvider {
23
+ tools;
24
+ constructor() {
25
+ super();
26
+ this.tools = new Map();
27
+ }
28
+ register(tool) {
29
+ if (!tool?.schema)
30
+ throw makeError('Tool must have a schema', 'invalid_tool');
31
+ if (typeof tool.handler !== 'function')
32
+ throw makeError('Tool must have a handler function', 'invalid_tool');
33
+ const name = (tool.schema.function?.['name'] || tool.schema['name']);
34
+ if (!name)
35
+ throw makeError('Tool schema must have a name', 'invalid_tool');
36
+ this.tools.set(name, tool);
37
+ return name;
38
+ }
39
+ registerAll(tools = []) {
40
+ for (const tool of tools)
41
+ this.register(tool);
42
+ }
43
+ async getAvailableTools() {
44
+ return Array.from(this.tools.values());
45
+ }
46
+ getTool(name) {
47
+ const normalized = this._normalizeName(name);
48
+ return this.tools.get(normalized) ?? null;
49
+ }
50
+ async executeTool(name, args = {}, context = {}) {
51
+ const normalized = this._normalizeName(name);
52
+ const tool = this.tools.get(normalized);
53
+ if (!tool)
54
+ throw makeError(`Tool not found: ${name}`, 'tool_not_found');
55
+ const cleanedArgs = stripNullish(args);
56
+ this._validateArgs(tool, cleanedArgs);
57
+ try {
58
+ return await tool.handler(cleanedArgs, context);
59
+ }
60
+ catch (error) {
61
+ throw makeError(`Tool "${name}" failed: ${error.message}`, 'tool_error', { cause: error });
62
+ }
63
+ }
64
+ _validateArgs(tool, args) {
65
+ const parameters = tool.schema.function?.['parameters'] || tool.schema['parameters'];
66
+ if (!parameters)
67
+ return;
68
+ const validate = ajv.compile(parameters);
69
+ if (!validate(args)) {
70
+ const name = tool.schema.function?.['name'];
71
+ throw makeError(`Invalid args for "${name}": ${ajv.errorsText(validate.errors)}`, 'validation_error', { data: { errors: validate.errors } });
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,6 @@
1
+ export declare class ToolProvider {
2
+ getAvailableTools(): Promise<unknown[]>;
3
+ executeTool(_name: string, _args?: Record<string, unknown>, _context?: Record<string, unknown>): Promise<unknown>;
4
+ getTool(_name: string): unknown | null;
5
+ _normalizeName(name: unknown): unknown;
6
+ }
@@ -0,0 +1,21 @@
1
+ export class ToolProvider {
2
+ async getAvailableTools() {
3
+ throw new Error('getAvailableTools must be implemented');
4
+ }
5
+ async executeTool(_name, _args, _context) {
6
+ throw new Error('executeTool must be implemented');
7
+ }
8
+ getTool(_name) {
9
+ throw new Error('getTool must be implemented');
10
+ }
11
+ _normalizeName(name) {
12
+ if (!name || typeof name !== 'string')
13
+ return name;
14
+ const prefixes = ['functions.', 'tools.', 'function.', 'tool.'];
15
+ for (const prefix of prefixes) {
16
+ if (name.startsWith(prefix))
17
+ return name.substring(prefix.length);
18
+ }
19
+ return name;
20
+ }
21
+ }
@@ -0,0 +1,27 @@
1
+ export interface ToolDefinition {
2
+ schema: {
3
+ type: 'function';
4
+ function: Record<string, unknown>;
5
+ };
6
+ handler: (args: Record<string, unknown>, context: Record<string, unknown>) => Promise<unknown>;
7
+ echoUserSummaryOnSuccess?: boolean;
8
+ /**
9
+ * When true, the runtime will skip a second invocation of this tool in
10
+ * the same assistant message. Use for "create an agreement"-style tools
11
+ * where the model is prone to fire two near-identical create calls.
12
+ */
13
+ isAgreementCreation?: boolean;
14
+ /**
15
+ * When true, the runtime will execute this tool even when no state
16
+ * action is bound to it. Use for discovery tools (e.g. agent search,
17
+ * task board) that should always be callable.
18
+ */
19
+ isGenericFallback?: boolean;
20
+ }
21
+ export interface DefineToolOptions {
22
+ description?: string;
23
+ echoUserSummaryOnSuccess?: boolean;
24
+ isAgreementCreation?: boolean;
25
+ isGenericFallback?: boolean;
26
+ }
27
+ export declare function defineTool(name: string, params: Record<string, unknown>, handler: (args: Record<string, unknown>, context: Record<string, unknown>) => Promise<unknown>, options?: DefineToolOptions): ToolDefinition;
@@ -0,0 +1,62 @@
1
+ const PRIMITIVES = new Set(['string', 'number', 'boolean', 'integer']);
2
+ function convertField(value) {
3
+ if (typeof value === 'string') {
4
+ if (!PRIMITIVES.has(value))
5
+ throw new Error(`Unknown type shorthand: "${value}"`);
6
+ return { schema: { type: value }, required: false };
7
+ }
8
+ if (Array.isArray(value)) {
9
+ if (value.length !== 1)
10
+ throw new Error('Array shorthand must have exactly one element describing the item type');
11
+ const inner = value[0];
12
+ if (typeof inner === 'string')
13
+ return { schema: { type: 'array', items: { type: inner } }, required: false };
14
+ return { schema: { type: 'array', items: convertObject(inner) }, required: false };
15
+ }
16
+ if (typeof value === 'object' && value !== null) {
17
+ const v = value;
18
+ if (v['type'] && PRIMITIVES.has(v['type'])) {
19
+ const { required: isReq, ...rest } = v;
20
+ return { schema: rest, required: !!isReq };
21
+ }
22
+ if (v['type'] === 'array' || v['type'] === 'object') {
23
+ const { required: isReq, ...rest } = v;
24
+ return { schema: rest, required: !!isReq };
25
+ }
26
+ return { schema: convertObject(v), required: false };
27
+ }
28
+ throw new Error(`Cannot convert field value: ${JSON.stringify(value)}`);
29
+ }
30
+ function convertObject(fields) {
31
+ const properties = {};
32
+ const required = [];
33
+ for (const [key, value] of Object.entries(fields)) {
34
+ if (key === 'required')
35
+ continue;
36
+ const { schema, required: isReq } = convertField(value);
37
+ properties[key] = schema;
38
+ if (isReq)
39
+ required.push(key);
40
+ }
41
+ const result = { type: 'object', properties };
42
+ if (required.length > 0)
43
+ result['required'] = required;
44
+ return result;
45
+ }
46
+ export function defineTool(name, params, handler, options = {}) {
47
+ if (!name || typeof name !== 'string')
48
+ throw new Error('defineTool: name is required');
49
+ if (!handler || typeof handler !== 'function')
50
+ throw new Error('defineTool: handler function is required');
51
+ const parameters = convertObject(params || {});
52
+ const fn = { name, parameters };
53
+ if (options.description)
54
+ fn['description'] = options.description;
55
+ return {
56
+ schema: { type: 'function', function: fn },
57
+ handler,
58
+ ...(options.echoUserSummaryOnSuccess ? { echoUserSummaryOnSuccess: true } : {}),
59
+ ...(options.isAgreementCreation ? { isAgreementCreation: true } : {}),
60
+ ...(options.isGenericFallback ? { isGenericFallback: true } : {}),
61
+ };
62
+ }
@@ -3,5 +3,4 @@ export { ToolProvider } from './ToolProvider.js';
3
3
  export { defineTool } from './defineTool.js';
4
4
  export { recordReport } from './recordReport.js';
5
5
  export type { RecordReportInput, RecordReportResult, TaskReport } from './recordReport.js';
6
- // Pure protocol-tool name registry (no handlers, no services).
7
6
  export { PROTOCOL_TOOL_NAMES, PROTOCOL_TOOL_TO_OPERATION, mapProtocolToolToOperation, isProtocolToolName } from '../tasks/protocolRegistry.js';
@@ -0,0 +1,6 @@
1
+ export { ToolManager } from './ToolManager.js';
2
+ export { ToolProvider } from './ToolProvider.js';
3
+ export { defineTool } from './defineTool.js';
4
+ export { recordReport } from './recordReport.js';
5
+ // Pure protocol-tool name registry (no handlers, no services).
6
+ export { PROTOCOL_TOOL_NAMES, PROTOCOL_TOOL_TO_OPERATION, mapProtocolToolToOperation, isProtocolToolName } from '../tasks/protocolRegistry.js';
@@ -0,0 +1,41 @@
1
+ import { type Creds } from '@ziggs-ai/api-client';
2
+ /**
3
+ * The canonical report shape (B1 convention — ZIG-561).
4
+ * Matches Task.result as set by ziggs_set_task_result.
5
+ */
6
+ export interface TaskReport {
7
+ summary: string;
8
+ status?: string;
9
+ links?: string[];
10
+ }
11
+ export interface RecordReportInput {
12
+ creds: Creds;
13
+ taskId: string;
14
+ report: TaskReport;
15
+ /**
16
+ * Primary artifact scope — required when `deliverable` is provided.
17
+ * Pass exactly one of chatId or agreementId.
18
+ */
19
+ chatId?: string;
20
+ agreementId?: string;
21
+ /**
22
+ * Heavy deliverable text (document, diff, data).
23
+ * When present, writes a `content_type=result` artifact bound to the task
24
+ * alongside setting Task.result.
25
+ */
26
+ deliverable?: string;
27
+ }
28
+ export interface RecordReportResult {
29
+ taskId: string;
30
+ artifactId?: string;
31
+ }
32
+ /**
33
+ * Record a conformant report for a completed task (B2 — ZIG-562).
34
+ *
35
+ * Always sets Task.result via updateTaskState (the canonical done payload).
36
+ * When `deliverable` is provided, also writes a task-bound result artifact
37
+ * via ArtifactsClient so it is retrievable as `via=task:<taskId>`.
38
+ *
39
+ * Implements the B1 convention (Agents/REPORTING.md).
40
+ */
41
+ export declare function recordReport(input: RecordReportInput): Promise<RecordReportResult>;