@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
@@ -1,172 +0,0 @@
1
- type AnyObj = Record<string, unknown>;
2
-
3
- interface HistoryFormatterOptions {
4
- showTimestamps?: boolean;
5
- shortIds?: boolean;
6
- }
7
-
8
- export class HistoryFormatter {
9
- private showTimestamps: boolean;
10
- private shortIds: boolean;
11
-
12
- constructor(options: HistoryFormatterOptions = {}) {
13
- this.showTimestamps = options.showTimestamps ?? true;
14
- this.shortIds = options.shortIds ?? false;
15
- }
16
-
17
- format(history: AnyObj[] | null | undefined, agentId: string, options: { mode?: string } = {}): string {
18
- if (!history?.length) return 'No previous activity.';
19
- const labelTypes = options.mode === 'mission';
20
- const sorted = [...history].sort((a, b) => {
21
- const tA = a['timestamp'] ? new Date(a['timestamp'] as string).getTime() : 0;
22
- const tB = b['timestamp'] ? new Date(b['timestamp'] as string).getTime() : 0;
23
- return tA - tB;
24
- });
25
- return sorted.map(entry => this.formatEntry(entry, agentId, labelTypes)).join('\n');
26
- }
27
-
28
- formatEntry(entry: AnyObj, agentId: string, labelTypes = false): string {
29
- const timestamp = this.showTimestamps ? this.formatTime(entry['timestamp'] as string | undefined) : '';
30
- const timePrefix = timestamp ? `[${timestamp}] ` : '';
31
- const entryType = entry['entryType'] as string | undefined;
32
-
33
- if (entryType === 'message' || !entryType) {
34
- const label = labelTypes ? '[CHAT] ' : '';
35
- return `${label}${this.formatMessage(entry, agentId, timePrefix)}`;
36
- }
37
- if (entryType === 'task_history') {
38
- const label = labelTypes ? '[TASK] ' : '';
39
- return `${label}${this.formatTaskHistory(entry, agentId, timePrefix)}`;
40
- }
41
- if (entryType === 'artifact') {
42
- const line = this.formatArtifact(entry, agentId, timePrefix);
43
- if (labelTypes) {
44
- if (entry['content_type'] === 'thought') return `[THOUGHT] ${line}`;
45
- const text = (entry['text'] as string) || '';
46
- const json = text.replace(/^operation_(?:started|completed|error):/, '');
47
- const data = json ? this.safeParseJSON(json) : null;
48
- const label = (data?.['type'] === 'tool' || text.includes('operation_error')) ? '[TOOL] ' : '[TASK] ';
49
- return `${label}${line}`;
50
- }
51
- return line;
52
- }
53
- return `${timePrefix}${entry['text'] || 'Unknown entry'}`;
54
- }
55
-
56
- formatMessage(entry: AnyObj, agentId: string, timePrefix: string): string {
57
- const from = this.formatParticipant(entry['sender'] as AnyObj | undefined, agentId);
58
- const to = entry['receiver'] ? ` → ${this.formatParticipant(entry['receiver'] as AnyObj, agentId)}` : '';
59
- return `${timePrefix}${from}${to}: ${entry['text'] || ''}`;
60
- }
61
-
62
- formatTaskHistory(entry: AnyObj, agentId: string, timePrefix: string): string {
63
- const service = entry['service'] as AnyObj | undefined;
64
- const task = service?.['task'] as AnyObj | undefined;
65
- if (!task) return `${timePrefix}Update`;
66
- const changeType = service?.['changeType'] as string | undefined;
67
- const taskId = this.shortId(task['taskId'] as string);
68
- const agreementId = task['agreementId'] ? this.shortId(task['agreementId'] as string) : null;
69
- const desc = (task['description'] as string) || 'No description';
70
- const ids = agreementId ? `agreement=${agreementId} task=${taskId}` : `task=${taskId}`;
71
- switch (changeType) {
72
- case 'created': {
73
- const ag = task['agreement'] as AnyObj | undefined;
74
- const parties = (ag?.['parties'] as AnyObj) || {};
75
- return `${timePrefix}Task created under agreement: "${desc}" (${ids})\n Owner: ${this.formatOwner(task, agentId)}\n Executor: ${this.formatExecutor(task, agentId)}\n Proposed to: ${parties['proposedTo'] || 'N/A'}`;
76
- }
77
- case 'state_changed': {
78
- const prev = (service?.['previousState'] as AnyObj | undefined)?.['state'] || '?';
79
- const next = (service?.['newState'] as AnyObj | undefined)?.['state'] || '?';
80
- return `${timePrefix}Task "${desc}" (${ids}): ${prev} → ${next}`;
81
- }
82
- case 'proposal_responded': {
83
- const action = (service?.['metadata'] as AnyObj | undefined)?.['action'] as string | undefined;
84
- return `${timePrefix}Proposal ${action ?? 'responded'} for "${desc}" (${ids})`;
85
- }
86
- case 'processing_changed': {
87
- const processing = (service?.['newState'] as AnyObj | undefined)?.['processing'];
88
- return `${timePrefix}Task "${desc}" (${ids}): processing ${processing ? 'started' : 'stopped'}`;
89
- }
90
- default:
91
- return `${timePrefix}${changeType}: "${desc}" (${ids})`;
92
- }
93
- }
94
-
95
- formatArtifact(entry: AnyObj, _agentId: string, timePrefix: string): string {
96
- const text = (entry['text'] as string) || '';
97
- if (entry['content_type'] === 'thought') return `${timePrefix}Thought: ${text}`;
98
- if (text.startsWith('operation_started:')) {
99
- const data = this.safeParseJSON(text.replace('operation_started:', ''));
100
- if (data?.['type'] === 'tool') return `${timePrefix}Tool starting: ${data['tool']}(${this.formatArgs(data['args'] as AnyObj)})`;
101
- if (data?.['type'] === 'task') return `${timePrefix}Task operation: ${data['operation']}`;
102
- return `${timePrefix}Operation started: ${data?.['type'] || 'unknown'}`;
103
- }
104
- if (text.startsWith('operation_completed:')) {
105
- const data = this.safeParseJSON(text.replace('operation_completed:', ''));
106
- if (data?.['type'] === 'tool') return `${timePrefix}Tool completed: ${data['tool']}`;
107
- if (data?.['type'] === 'task') return `${timePrefix}Task operation completed: ${data['operation']}`;
108
- return `${timePrefix}Operation completed: ${data?.['type'] || 'unknown'}`;
109
- }
110
- if (text.startsWith('operation_error:')) {
111
- const data = this.safeParseJSON(text.replace('operation_error:', ''));
112
- return `${timePrefix}ERROR: ${data?.['error'] || 'Unknown error'}`;
113
- }
114
- return `${timePrefix}${text}`;
115
- }
116
-
117
- formatParticipant(participant: AnyObj | null | undefined, agentId: string): string {
118
- if (!participant) return 'unknown';
119
- // Message.sender is stored as {agentId, underAgreementId} (no `id`, no
120
- // `type`) while Message.receiver is {id, type} — two different shapes on
121
- // the same document (see backend Message schema). Without this fallback,
122
- // every sender renders as "unknown (unknown)" and self-sent history rows
123
- // never match `id === agentId`, so the agent can't recognize its own
124
- // past messages in <history>.
125
- const id = (participant['id'] as string) || (participant['agentId'] as string) || 'unknown';
126
- if (participant['type'] === 'system') return 'System';
127
- if (id === agentId) return 'You';
128
- return `${id} (${participant['type'] || 'unknown'})`;
129
- }
130
-
131
- formatOwner(task: AnyObj, agentId: string): string {
132
- const ag = task['agreement'] as AnyObj | undefined;
133
- const creatorId = (ag?.['parties'] as AnyObj | undefined)?.['creator'] ?? task['agentId'];
134
- return creatorId === agentId ? 'You' : String(creatorId ?? 'N/A');
135
- }
136
-
137
- formatExecutor(task: AnyObj, agentId: string): string {
138
- const ag = task['agreement'] as AnyObj | undefined;
139
- const providerId = (ag?.['parties'] as AnyObj | undefined)?.['provider'] ?? task['executorId'];
140
- return providerId === agentId ? 'You' : String(providerId ?? 'N/A');
141
- }
142
-
143
- shortId(id: string | null | undefined): string {
144
- if (!id) return '?';
145
- if (!this.shortIds) return id;
146
- const parts = id.split('_');
147
- if (parts.length >= 3) return `task_...${parts[parts.length - 1]}`;
148
- return id.length > 20 ? id.slice(0, 20) + '...' : id;
149
- }
150
-
151
- formatTime(timestamp: string | null | undefined): string {
152
- if (!timestamp) return '??:??';
153
- const date = new Date(timestamp);
154
- if (isNaN(date.getTime())) return '??:??';
155
- return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, timeZone: 'UTC' });
156
- }
157
-
158
- formatArgs(args: AnyObj | null | undefined): string {
159
- if (!args || typeof args !== 'object') return '';
160
- const entries = Object.entries(args);
161
- if (entries.length === 0) return '';
162
- if (entries.length <= 3) return entries.map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(', ');
163
- return JSON.stringify(args);
164
- }
165
-
166
- private safeParseJSON(str: string): AnyObj | null {
167
- try { return JSON.parse(str) as AnyObj; }
168
- catch { return null; }
169
- }
170
- }
171
-
172
- export const historyFormatter = new HistoryFormatter();
@@ -1,162 +0,0 @@
1
- import { OPEN_AGREEMENT_TARGET } from '@ziggs-ai/api-client';
2
-
3
- /** Backend wire operations that map to FSM `proposal-resolved`. */
4
- const PROPOSAL_RESOLVED_OPERATIONS = new Set([
5
- 'proposal_approved',
6
- 'proposal_rejected',
7
- 'proposal_approved_execute',
8
- ]);
9
-
10
- export interface NormalizedEvent {
11
- chatId: string | null;
12
- event: {
13
- senderId?: string;
14
- senderType?: string;
15
- receiverId?: string;
16
- timestamp: number;
17
- type: 'task_result' | 'message' | 'agreement_lifecycle';
18
- operation?: string;
19
- agreementId?: string;
20
- result?: unknown;
21
- text?: string;
22
- };
23
- shouldProcess: boolean;
24
- reason: string | null;
25
- }
26
-
27
- interface WireParties {
28
- creator?: string;
29
- provider?: string;
30
- payer?: string;
31
- proposedTo?: string;
32
- }
33
-
34
- interface WireTask {
35
- taskId?: string;
36
- agentId?: string;
37
- executorId?: string;
38
- payerId?: string;
39
- proposedTo?: string;
40
- createdBy?: string;
41
- parentTaskId?: string;
42
- state?: string;
43
- proposal?: unknown;
44
- agreement?: { parties?: WireParties };
45
- }
46
-
47
- interface WireMetadata {
48
- chatId?: string;
49
- chat_id?: string;
50
- entryType?: string;
51
- content_type?: string;
52
- contentType?: string;
53
- receiverId?: string;
54
- operation?: string;
55
- agreementId?: string;
56
- sender?: { id?: string; type?: string };
57
- receiver?: { id?: string };
58
- to?: { id?: string };
59
- task?: WireTask;
60
- [key: string]: unknown;
61
- }
62
-
63
- interface NormalizeArgs {
64
- text: string;
65
- metadata?: WireMetadata;
66
- ownAgentId?: string | null;
67
- }
68
-
69
- function normalizeChatId(metadata: WireMetadata): string | null {
70
- return metadata.chatId || metadata.chat_id || null;
71
- }
72
-
73
- function normalizeReceiverId(metadata: WireMetadata, taskData: WireTask | null): string | null {
74
- return metadata.receiver?.id || metadata.receiverId || metadata.to?.id || taskData?.executorId || taskData?.proposedTo || null;
75
- }
76
-
77
- function isTaskRelated(metadata: WireMetadata, taskData: WireTask | null): boolean {
78
- if (!taskData?.taskId) return false;
79
- const entryType = metadata.entryType || 'message';
80
- const contentType = metadata.content_type || metadata.contentType || 'text';
81
- return (
82
- entryType === 'notification' || entryType === 'task_history'
83
- || contentType === 'task' || contentType === 'task_update'
84
- || Boolean(taskData.state || taskData.proposal || taskData.parentTaskId || taskData.executorId || taskData.agentId || taskData.payerId || taskData.createdBy)
85
- );
86
- }
87
-
88
- function isRelevantForAgent(ids: (string | null | undefined)[], ownAgentId: string | null): boolean {
89
- if (!ownAgentId) return true;
90
- return ids.includes(ownAgentId) || ids.includes(OPEN_AGREEMENT_TARGET);
91
- }
92
-
93
- function isAgreementLifecycleNotification(metadata: WireMetadata): boolean {
94
- const entryType = metadata.entryType || 'message';
95
- const operation = metadata.operation;
96
- return (
97
- entryType === 'notification' &&
98
- typeof operation === 'string' &&
99
- PROPOSAL_RESOLVED_OPERATIONS.has(operation)
100
- );
101
- }
102
-
103
- export function normalizeIncomingEvent({ text, metadata = {}, ownAgentId = null }: NormalizeArgs): NormalizedEvent {
104
- const taskData = metadata.task || null;
105
- const chatId = normalizeChatId(metadata);
106
- const receiverId = normalizeReceiverId(metadata, taskData);
107
- const senderType = metadata.sender?.type ? String(metadata.sender.type).toUpperCase() : undefined;
108
-
109
- const base = {
110
- senderId: metadata.sender?.id,
111
- senderType,
112
- receiverId: receiverId || undefined,
113
- timestamp: Date.now(),
114
- };
115
-
116
- if (isAgreementLifecycleNotification(metadata)) {
117
- const relevant =
118
- !ownAgentId ||
119
- !receiverId ||
120
- receiverId === ownAgentId ||
121
- receiverId === OPEN_AGREEMENT_TARGET;
122
- const agreementId =
123
- typeof metadata.agreementId === 'string' ? metadata.agreementId : '';
124
- return {
125
- chatId,
126
- event: {
127
- ...base,
128
- type: 'agreement_lifecycle',
129
- operation: metadata.operation,
130
- agreementId,
131
- text,
132
- },
133
- shouldProcess: relevant,
134
- reason: relevant ? null : 'message_not_targeted_to_agent',
135
- };
136
- }
137
-
138
- if (isTaskRelated(metadata, taskData)) {
139
- const receiverFromMeta = metadata.receiver?.id || metadata.receiverId || null;
140
- const parties = taskData!.agreement?.parties ?? {};
141
- const candidateIds = [
142
- parties.creator, parties.provider, parties.payer, parties.proposedTo,
143
- taskData!.agentId, taskData!.executorId, taskData!.payerId, taskData!.proposedTo, taskData!.createdBy,
144
- receiverFromMeta,
145
- ].filter(Boolean);
146
- const relevant = isRelevantForAgent(candidateIds, ownAgentId);
147
- return {
148
- chatId,
149
- event: { ...base, type: 'task_result', result: taskData, text },
150
- shouldProcess: relevant,
151
- reason: relevant ? null : 'task_not_targeted_to_agent',
152
- };
153
- }
154
-
155
- const relevant = !ownAgentId || !receiverId || receiverId === ownAgentId || receiverId === OPEN_AGREEMENT_TARGET;
156
- return {
157
- chatId,
158
- event: { ...base, type: 'message', text },
159
- shouldProcess: relevant,
160
- reason: relevant ? null : 'message_not_targeted_to_agent',
161
- };
162
- }
@@ -1,104 +0,0 @@
1
- /**
2
- * Agent-private long-term memory.
3
- *
4
- * This is the SDK's contract; the *storage* is operator-provided. The agent
5
- * picks the key shape (often `counterparty:<id>`, sometimes `agreement:<id>:notes`,
6
- * etc.) — the SDK does not enforce one.
7
- *
8
- * Reference implementations: `InMemoryStore` (default; non-durable) and
9
- * `FileMemoryStore` (single JSON file; useful for local dev). Anything
10
- * production-grade (sqlite, redis, postgres, …) is operator-owned.
11
- *
12
- * Aligns with the project's "agents are third-party" framing: an agent's
13
- * private notes are its own concern, not the backend's.
14
- */
15
- export interface MemoryStore {
16
- get(key: string): Promise<unknown | undefined>;
17
- put(key: string, value: unknown): Promise<void>;
18
- list(prefix: string): Promise<{ key: string; value: unknown }[]>;
19
- delete?(key: string): Promise<void>;
20
- }
21
-
22
- /** Non-durable reference impl. Per-process; lost on restart. */
23
- export class InMemoryStore implements MemoryStore {
24
- private readonly store = new Map<string, unknown>();
25
-
26
- async get(key: string): Promise<unknown | undefined> {
27
- return this.store.get(key);
28
- }
29
-
30
- async put(key: string, value: unknown): Promise<void> {
31
- this.store.set(key, value);
32
- }
33
-
34
- async list(prefix: string): Promise<{ key: string; value: unknown }[]> {
35
- const out: { key: string; value: unknown }[] = [];
36
- for (const [k, v] of this.store) {
37
- if (k.startsWith(prefix)) out.push({ key: k, value: v });
38
- }
39
- return out;
40
- }
41
-
42
- async delete(key: string): Promise<void> {
43
- this.store.delete(key);
44
- }
45
- }
46
-
47
- /**
48
- * Single-file JSON store. Reads on startup, writes on every put — fine for
49
- * local dev and example agents; not for production (no concurrency control,
50
- * no atomicity). Operators with serious durability needs ship their own
51
- * `MemoryStore` (sqlite, redis, …) and pass it via `defineAgent({ memory })`.
52
- */
53
- export class FileMemoryStore implements MemoryStore {
54
- private cache: Record<string, unknown> | null = null;
55
- private loading: Promise<void> | null = null;
56
-
57
- constructor(private readonly path: string) {}
58
-
59
- private async _ensureLoaded(): Promise<void> {
60
- if (this.cache) return;
61
- if (!this.loading) {
62
- this.loading = (async () => {
63
- try {
64
- const fs = await import('fs/promises');
65
- const txt = await fs.readFile(this.path, 'utf-8');
66
- this.cache = JSON.parse(txt) as Record<string, unknown>;
67
- } catch {
68
- this.cache = {};
69
- }
70
- })();
71
- }
72
- await this.loading;
73
- }
74
-
75
- private async _flush(): Promise<void> {
76
- if (!this.cache) return;
77
- const fs = await import('fs/promises');
78
- await fs.writeFile(this.path, JSON.stringify(this.cache, null, 2), 'utf-8');
79
- }
80
-
81
- async get(key: string): Promise<unknown | undefined> {
82
- await this._ensureLoaded();
83
- return this.cache![key];
84
- }
85
-
86
- async put(key: string, value: unknown): Promise<void> {
87
- await this._ensureLoaded();
88
- this.cache![key] = value;
89
- await this._flush();
90
- }
91
-
92
- async list(prefix: string): Promise<{ key: string; value: unknown }[]> {
93
- await this._ensureLoaded();
94
- return Object.entries(this.cache!)
95
- .filter(([k]) => k.startsWith(prefix))
96
- .map(([key, value]) => ({ key, value }));
97
- }
98
-
99
- async delete(key: string): Promise<void> {
100
- await this._ensureLoaded();
101
- delete this.cache![key];
102
- await this._flush();
103
- }
104
- }
@@ -1,225 +0,0 @@
1
- /**
2
- * ZIG-368 — default paid pricing for Ziggs-operated (first-party) agents.
3
- * Prices are in wallet cents (1 ZIG = 100 cents).
4
- */
5
- import { FLEET_TIER_BY_AGENT_ID, type FleetPricingTier } from './fleetTierByAgentId.gen.js';
6
- import { FREE_TIER_A_AGENT_IDS } from './fleetFreeTierA.gen.js';
7
- import { isEvalFreeExecutor } from './fleetEvalFree.js';
8
-
9
- export const ZIGGS_OPERATOR_CUT_BPS = 1000; // 10%
10
-
11
- export const TIER_PRICE_CENTS: Record<FleetPricingTier, number> = {
12
- A: 200, // 2 ZIG / call
13
- B: 500, // 5 ZIG / call
14
- C: 1500, // 15 ZIG / job (orchestrator, charged once at top)
15
- D: 100, // 1 ZIG / call (hand-written demo agents)
16
- };
17
-
18
- const ZIGGS_ORCHESTRATOR_IDS = new Set(['ziggs-agent']);
19
-
20
- const PING_DESCRIPTION_PATTERN =
21
- /\b(ping|health\s*check|healthcheck|liveness|readiness|heartbeat)\b/i;
22
-
23
- const TRIVIAL_LOOKUP_DESCRIPTION_PATTERN =
24
- /\b(what\s+time|current\s+time|local\s+time|world\s+clock|timezone|time\s+zone|weather|forecast|temperature|uv\s+index)\b/i;
25
-
26
- export function resolveFleetTier(agentId: string): FleetPricingTier | null {
27
- if (!agentId || typeof agentId !== 'string') return null;
28
- return FLEET_TIER_BY_AGENT_ID[agentId] ?? null;
29
- }
30
-
31
- export function isFirstPartyFleetAgent(agentId: string): boolean {
32
- return resolveFleetTier(agentId) != null;
33
- }
34
-
35
- export function tierPriceCents(tier: FleetPricingTier): number {
36
- return TIER_PRICE_CENTS[tier];
37
- }
38
-
39
- export function isZiggsOrchestrator(agentId: string): boolean {
40
- return ZIGGS_ORCHESTRATOR_IDS.has(agentId);
41
- }
42
-
43
- export function isFreeAllowlistedExecutor(
44
- executorId: string,
45
- description?: string | null,
46
- ): boolean {
47
- if (!executorId) return false;
48
- if (isEvalFreeExecutor(executorId)) return true;
49
- if (FREE_TIER_A_AGENT_IDS.has(executorId)) return true;
50
- if (description && PING_DESCRIPTION_PATTERN.test(description)) return true;
51
- if (
52
- description &&
53
- TRIVIAL_LOOKUP_DESCRIPTION_PATTERN.test(description) &&
54
- FREE_TIER_A_AGENT_IDS.has(executorId)
55
- ) {
56
- return true;
57
- }
58
- return false;
59
- }
60
-
61
- export function resolveDefaultPriceCentsForExecutor(
62
- executorId: string,
63
- description?: string | null,
64
- ): number | null {
65
- if (isFreeAllowlistedExecutor(executorId, description)) return 0;
66
- const tier = resolveFleetTier(executorId);
67
- if (!tier) return null;
68
- return tierPriceCents(tier);
69
- }
70
-
71
- export interface ProtocolPricingPayload {
72
- price?: number | null;
73
- description?: string;
74
- agreementDescription?: string;
75
- proposedTo?: string;
76
- providerId?: string;
77
- executorId?: string;
78
- parentAgreementId?: string;
79
- parentTaskId?: string;
80
- [key: string]: unknown;
81
- }
82
-
83
- /**
84
- * Apply ZIG-368 defaults when `price` is omitted (null/undefined).
85
- * Explicit `price: 0` is kept (free-on-purpose).
86
- */
87
- export function applyFleetAgreementPricing(
88
- operation: 'agreement-propose' | 'agreement-subcontract',
89
- payload: ProtocolPricingPayload,
90
- actingAgentId: string,
91
- ): ProtocolPricingPayload {
92
- if (payload.price != null && payload.price !== undefined) {
93
- return payload;
94
- }
95
-
96
- const next = { ...payload };
97
- const scopeDescription = next.description ?? next.agreementDescription;
98
-
99
- if (operation === 'agreement-subcontract') {
100
- const executorId = String(next.executorId ?? '');
101
- if (next.parentAgreementId) {
102
- // Paid parent scope: no second user hold — allocate from parent budget (recordAllocation).
103
- const cents = resolveDefaultPriceCentsForExecutor(executorId, scopeDescription);
104
- next.price = cents ?? 0;
105
- return next;
106
- }
107
- const cents = resolveDefaultPriceCentsForExecutor(executorId, scopeDescription);
108
- if (cents != null) next.price = cents;
109
- return next;
110
- }
111
-
112
- // agreement-propose
113
- if (next.parentAgreementId) {
114
- return next;
115
- }
116
-
117
- const proposedTo = next.proposedTo != null ? String(next.proposedTo) : '';
118
- const providerId = next.providerId != null ? String(next.providerId) : '';
119
-
120
- // Ziggs scope proposal to human user — 15 ZIG once at top.
121
- if (
122
- isZiggsOrchestrator(actingAgentId) &&
123
- proposedTo &&
124
- !isFirstPartyFleetAgent(proposedTo)
125
- ) {
126
- next.price = TIER_PRICE_CENTS.C;
127
- return next;
128
- }
129
-
130
- // Tier C orchestrator proposing scope to a user (non-ziggs fleet orchestrators).
131
- const actingTier = resolveFleetTier(actingAgentId);
132
- if (actingTier === 'C' && proposedTo && !isFirstPartyFleetAgent(proposedTo)) {
133
- next.price = TIER_PRICE_CENTS.C;
134
- return next;
135
- }
136
-
137
- // Matchmaking: propose directly to a fleet specialist with tier list price.
138
- const specialistId = providerId || (isFirstPartyFleetAgent(proposedTo) ? proposedTo : '');
139
- if (specialistId) {
140
- const cents = resolveDefaultPriceCentsForExecutor(specialistId, scopeDescription);
141
- if (cents != null) next.price = cents;
142
- }
143
-
144
- return next;
145
- }
146
-
147
- /**
148
- * Default tier price when a fleet agent counters without an explicit `price`.
149
- *
150
- * Generic over the payload shape so the precise field types of the caller's
151
- * payload survive the round-trip — this helper only ever sets `price`, so a
152
- * richer input type (e.g. protocolRunner's `ProtocolPayload`) must come back
153
- * out unwidened by `ProtocolPricingPayload`'s `[key: string]: unknown` index.
154
- */
155
- export function applyFleetCounterPricing<T extends ProtocolPricingPayload>(
156
- payload: T,
157
- actingAgentId: string,
158
- ): T {
159
- if (payload.price != null && payload.price !== undefined) {
160
- return payload;
161
- }
162
- const cents = resolveDefaultPriceCentsForExecutor(
163
- actingAgentId,
164
- payload.description ?? payload.agreementDescription,
165
- );
166
- if (cents == null) return payload;
167
- return { ...payload, price: cents } as T;
168
- }
169
-
170
- /** User or agent direct-create / marketplace: default from provider specialist. */
171
- export function resolveDefaultPriceForProvider(
172
- providerId: string,
173
- description?: string | null,
174
- explicitPrice?: number | null,
175
- ): number | null {
176
- if (typeof explicitPrice === 'number') return explicitPrice;
177
- return resolveDefaultPriceCentsForExecutor(providerId, description);
178
- }
179
-
180
- /**
181
- * Infer fleet actor when tool context omits agentId (ZIG-368 safety net).
182
- */
183
- export function inferFleetPricingActorId(payload: ProtocolPricingPayload): string | null {
184
- const executor = payload.executorId != null ? String(payload.executorId) : '';
185
- if (executor && isFirstPartyFleetAgent(executor)) return executor;
186
- const provider = payload.providerId != null ? String(payload.providerId) : '';
187
- if (provider && isFirstPartyFleetAgent(provider)) return provider;
188
- const proposed = payload.proposedTo != null ? String(payload.proposedTo) : '';
189
- if (proposed && isFirstPartyFleetAgent(proposed)) return proposed;
190
- return null;
191
- }
192
-
193
- /** Apply fleet defaults with optional acting agent (falls back to payload inference). */
194
- export function applyFleetPricingForProtocol(
195
- operation: 'agreement-propose' | 'agreement-subcontract',
196
- payload: ProtocolPricingPayload,
197
- actingAgentId: string | null,
198
- ): ProtocolPricingPayload {
199
- const actor = actingAgentId?.trim() || inferFleetPricingActorId(payload);
200
- if (!actor) {
201
- if (operation === 'agreement-propose') {
202
- const specialist =
203
- (payload.providerId != null ? String(payload.providerId) : '') ||
204
- (payload.proposedTo != null && isFirstPartyFleetAgent(String(payload.proposedTo))
205
- ? String(payload.proposedTo)
206
- : '');
207
- if (specialist) {
208
- const cents = resolveDefaultPriceCentsForExecutor(
209
- specialist,
210
- payload.description ?? (payload.agreementDescription as string | undefined),
211
- );
212
- if (cents != null) return { ...payload, price: cents };
213
- }
214
- }
215
- if (operation === 'agreement-subcontract' && payload.executorId) {
216
- const cents = resolveDefaultPriceCentsForExecutor(
217
- String(payload.executorId),
218
- payload.description,
219
- );
220
- if (cents != null) return { ...payload, price: cents };
221
- }
222
- return payload;
223
- }
224
- return applyFleetAgreementPricing(operation, payload, actor);
225
- }
@@ -1,24 +0,0 @@
1
- /**
2
- * ZIG-395 — eval/harness free pricing via env flag (no SANDBOX id-shape regex).
3
- */
4
-
5
- /** Capability-probe + test harness agents (agents/test/). */
6
- export const EVAL_HARNESS_AGENT_IDS = new Set([
7
- 'minimal-context-agent',
8
- 'forwarding-agent',
9
- 'failing-agent',
10
- 'messaging-only-agent',
11
- 'principal-agent',
12
- 'capability-probe-agent',
13
- ]);
14
-
15
- export function isEvalFreePricingEnabled(): boolean {
16
- return process.env.FLEET_EVAL_FREE_PRICING === 'true';
17
- }
18
-
19
- export function isEvalFreeExecutor(agentId: string): boolean {
20
- if (!isEvalFreePricingEnabled() || !agentId) return false;
21
- if (agentId === 'eval-user') return true;
22
- if (agentId.endsWith('--eval')) return true;
23
- return EVAL_HARNESS_AGENT_IDS.has(agentId);
24
- }