@ziggs-ai/agent-sdk 0.1.11 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +41 -2
  3. package/dist/AgentHost.d.ts +201 -0
  4. package/dist/AgentHost.js +652 -0
  5. package/dist/adapters/AnthropicAdapter.d.ts +39 -0
  6. package/dist/adapters/AnthropicAdapter.js +200 -0
  7. package/dist/adapters/McpAdapter.d.ts +199 -0
  8. package/dist/adapters/McpAdapter.js +468 -0
  9. package/dist/adapters/OpenAIAdapter.d.ts +26 -0
  10. package/dist/adapters/OpenAIAdapter.js +158 -0
  11. package/dist/adapters/index.js +2 -0
  12. package/dist/agent/Agent.d.ts +78 -0
  13. package/dist/agent/Agent.js +58 -0
  14. package/dist/agent/ClaudeSdkAgent.d.ts +38 -0
  15. package/dist/agent/ClaudeSdkAgent.js +322 -0
  16. package/dist/agent/claudeCognition.d.ts +67 -0
  17. package/dist/agent/claudeCognition.js +103 -0
  18. package/dist/agent/claudeSdkProtocol.d.ts +11 -0
  19. package/dist/agent/claudeSdkProtocol.js +27 -0
  20. package/dist/agent/claudeSdkTools.d.ts +19 -0
  21. package/dist/agent/claudeSdkTools.js +57 -0
  22. package/dist/agent/hostedAgentConnection.d.ts +15 -0
  23. package/dist/agent/hostedAgentConnection.js +29 -0
  24. package/dist/agent/toolManagerToSdkMcp.d.ts +12 -0
  25. package/dist/agent/toolManagerToSdkMcp.js +123 -0
  26. package/dist/brain/index.d.ts +50 -0
  27. package/dist/brain/index.js +45 -0
  28. package/dist/cognition/validateContext.d.ts +11 -0
  29. package/dist/cognition/validateContext.js +117 -0
  30. package/dist/context/applyEffects.d.ts +2 -0
  31. package/dist/context/applyEffects.js +89 -0
  32. package/dist/context/batch.d.ts +2 -0
  33. package/dist/context/batch.js +18 -0
  34. package/dist/context/classifyEnvelope.d.ts +1 -0
  35. package/dist/context/classifyEnvelope.js +58 -0
  36. package/dist/context/routingLabels.d.ts +4 -0
  37. package/dist/context/routingLabels.js +48 -0
  38. package/dist/defineAgent.d.ts +14 -0
  39. package/dist/defineAgent.js +68 -0
  40. package/dist/formatters/AgreementFormatter.d.ts +18 -0
  41. package/dist/formatters/AgreementFormatter.js +130 -0
  42. package/dist/formatters/HistoryFormatter.d.ts +26 -0
  43. package/dist/formatters/HistoryFormatter.js +173 -0
  44. package/dist/formatters/index.js +2 -0
  45. package/{src/index.ts → dist/index.d.ts} +13 -53
  46. package/dist/index.js +66 -0
  47. package/dist/ingress/normalizeIncoming.d.ts +65 -0
  48. package/dist/ingress/normalizeIncoming.js +88 -0
  49. package/dist/memory/MemoryStore.d.ts +55 -0
  50. package/dist/memory/MemoryStore.js +78 -0
  51. package/dist/pricing/fleetDefaults.d.ts +46 -0
  52. package/dist/pricing/fleetDefaults.js +168 -0
  53. package/dist/pricing/fleetEvalFree.d.ts +7 -0
  54. package/dist/pricing/fleetEvalFree.js +24 -0
  55. package/dist/pricing/fleetFreeTierA.gen.d.ts +6 -0
  56. package/{src/pricing/fleetFreeTierA.gen.ts → dist/pricing/fleetFreeTierA.gen.js} +5 -6
  57. package/dist/pricing/fleetTierByAgentId.gen.d.ts +7 -0
  58. package/dist/pricing/fleetTierByAgentId.gen.js +768 -0
  59. package/dist/runtime/AgentMachine.d.ts +143 -0
  60. package/dist/runtime/AgentMachine.js +400 -0
  61. package/dist/runtime/PromptBuilder.d.ts +96 -0
  62. package/dist/runtime/PromptBuilder.js +439 -0
  63. package/dist/runtime/bootstrapCtx.d.ts +18 -0
  64. package/dist/runtime/bootstrapCtx.js +37 -0
  65. package/dist/runtime/buildOutcome.d.ts +68 -0
  66. package/dist/runtime/buildOutcome.js +464 -0
  67. package/dist/runtime/defaults.d.ts +54 -0
  68. package/dist/runtime/defaults.js +47 -0
  69. package/dist/runtime/deriveRespondsToProposals.d.ts +9 -0
  70. package/dist/runtime/deriveRespondsToProposals.js +38 -0
  71. package/dist/runtime/kickoff.d.ts +15 -0
  72. package/dist/runtime/kickoff.js +112 -0
  73. package/dist/runtime/runMechanical.d.ts +25 -0
  74. package/dist/runtime/runMechanical.js +74 -0
  75. package/dist/runtime/runTurn.d.ts +63 -0
  76. package/dist/runtime/runTurn.js +800 -0
  77. package/dist/runtime/validateWorkflow.d.ts +17 -0
  78. package/dist/runtime/validateWorkflow.js +209 -0
  79. package/dist/server/ConnectionPool.d.ts +68 -0
  80. package/dist/server/ConnectionPool.js +166 -0
  81. package/dist/server/EventQueue.d.ts +33 -0
  82. package/dist/server/EventQueue.js +98 -0
  83. package/dist/server/InboxCatchUp.d.ts +24 -0
  84. package/dist/server/InboxCatchUp.js +213 -0
  85. package/dist/server/OutboxBuffer.d.ts +33 -0
  86. package/dist/server/OutboxBuffer.js +68 -0
  87. package/dist/server/SeenMessages.d.ts +13 -0
  88. package/dist/server/SeenMessages.js +31 -0
  89. package/dist/server/StateTimers.d.ts +34 -0
  90. package/dist/server/StateTimers.js +70 -0
  91. package/dist/server/ZiggsEffectHandler.d.ts +79 -0
  92. package/dist/server/ZiggsEffectHandler.js +319 -0
  93. package/dist/server/agreements/AgreementService.d.ts +50 -0
  94. package/dist/server/agreements/AgreementService.js +85 -0
  95. package/dist/server/createHealthServer.d.ts +7 -0
  96. package/dist/server/createHealthServer.js +75 -0
  97. package/dist/server/proactive/ProactiveTrigger.d.ts +33 -0
  98. package/dist/server/proactive/ProactiveTrigger.js +71 -0
  99. package/dist/server/runLauncher.d.ts +28 -0
  100. package/dist/server/runLauncher.js +93 -0
  101. package/dist/server/tasks/TaskService.d.ts +25 -0
  102. package/dist/server/tasks/TaskService.js +103 -0
  103. package/dist/server/tasks/index.js +1 -0
  104. package/dist/server/telemetryIngest.d.ts +24 -0
  105. package/dist/server/telemetryIngest.js +62 -0
  106. package/dist/server/tools/index.d.ts +24 -0
  107. package/{src/server/tools/index.ts → dist/server/tools/index.js} +4 -24
  108. package/dist/server/tools/tier1/protocolRunner.d.ts +39 -0
  109. package/dist/server/tools/tier1/protocolRunner.js +288 -0
  110. package/dist/server/tools/tier1/protocolTools.d.ts +12 -0
  111. package/dist/server/tools/tier1/protocolTools.js +37 -0
  112. package/dist/server/tools/tier2/connectionTools.d.ts +4 -0
  113. package/dist/server/tools/tier2/connectionTools.js +63 -0
  114. package/dist/server/tools/tier2/contextTools.d.ts +4 -0
  115. package/dist/server/tools/tier2/contextTools.js +46 -0
  116. package/dist/server/tools/tier2/discoveryTools.d.ts +4 -0
  117. package/dist/server/tools/tier2/discoveryTools.js +25 -0
  118. package/dist/server/tools/tier2/marketplaceTools.d.ts +3 -0
  119. package/dist/server/tools/tier2/marketplaceTools.js +22 -0
  120. package/dist/server/tools/tier2/paymentTools.d.ts +12 -0
  121. package/dist/server/tools/tier2/paymentTools.js +165 -0
  122. package/dist/server/ziggsconnect/ZiggsConnectClient.d.ts +35 -0
  123. package/dist/server/ziggsconnect/ZiggsConnectClient.js +95 -0
  124. package/dist/server/ziggscontext/ZiggsContextClient.d.ts +48 -0
  125. package/dist/server/ziggscontext/ZiggsContextClient.js +90 -0
  126. package/dist/server/ziggspay/ZiggsPayClient.d.ts +82 -0
  127. package/dist/server/ziggspay/ZiggsPayClient.js +188 -0
  128. package/dist/shared/ids.d.ts +1 -0
  129. package/dist/shared/ids.js +3 -0
  130. package/dist/shared/runtimeLog.d.ts +18 -0
  131. package/dist/shared/runtimeLog.js +68 -0
  132. package/dist/shared/types.d.ts +22 -0
  133. package/dist/shared/types.js +23 -0
  134. package/dist/tasks/protocolRegistry.d.ts +16 -0
  135. package/dist/tasks/protocolRegistry.js +20 -0
  136. package/dist/tools/ToolManager.d.ts +12 -0
  137. package/dist/tools/ToolManager.js +74 -0
  138. package/dist/tools/ToolProvider.d.ts +6 -0
  139. package/dist/tools/ToolProvider.js +21 -0
  140. package/dist/tools/defineTool.d.ts +27 -0
  141. package/dist/tools/defineTool.js +62 -0
  142. package/{src/tools/index.ts → dist/tools/index.d.ts} +0 -1
  143. package/dist/tools/index.js +6 -0
  144. package/dist/tools/recordReport.d.ts +41 -0
  145. package/dist/tools/recordReport.js +30 -0
  146. package/dist/types.d.ts +466 -0
  147. package/dist/types.js +7 -0
  148. package/dist/utils/jsonExtractor.d.ts +2 -0
  149. package/dist/utils/jsonExtractor.js +111 -0
  150. package/package.json +17 -7
  151. package/src/AgentHost.ts +0 -545
  152. package/src/adapters/AnthropicAdapter.ts +0 -206
  153. package/src/adapters/McpAdapter.ts +0 -348
  154. package/src/adapters/OpenAIAdapter.ts +0 -187
  155. package/src/agent/Agent.ts +0 -104
  156. package/src/cognition/validateContext.ts +0 -95
  157. package/src/context/applyEffects.ts +0 -80
  158. package/src/context/batch.ts +0 -19
  159. package/src/context/classifyEnvelope.ts +0 -38
  160. package/src/context/routingLabels.ts +0 -46
  161. package/src/defineAgent.ts +0 -70
  162. package/src/formatters/AgreementFormatter.ts +0 -111
  163. package/src/formatters/HistoryFormatter.ts +0 -172
  164. package/src/ingress/normalizeIncoming.ts +0 -162
  165. package/src/memory/MemoryStore.ts +0 -104
  166. package/src/pricing/fleetDefaults.ts +0 -225
  167. package/src/pricing/fleetEvalFree.ts +0 -24
  168. package/src/pricing/fleetTierByAgentId.gen.ts +0 -775
  169. package/src/runtime/AgentMachine.ts +0 -402
  170. package/src/runtime/PromptBuilder.ts +0 -485
  171. package/src/runtime/buildOutcome.ts +0 -563
  172. package/src/runtime/defaults.ts +0 -75
  173. package/src/runtime/kickoff.ts +0 -117
  174. package/src/runtime/runTurn.ts +0 -813
  175. package/src/runtime/validateWorkflow.ts +0 -202
  176. package/src/server/ConnectionPool.ts +0 -206
  177. package/src/server/EventQueue.ts +0 -133
  178. package/src/server/InboxCatchUp.ts +0 -254
  179. package/src/server/OutboxBuffer.ts +0 -90
  180. package/src/server/SeenMessages.ts +0 -27
  181. package/src/server/StateTimers.ts +0 -85
  182. package/src/server/ZiggsEffectHandler.ts +0 -418
  183. package/src/server/agreements/AgreementService.ts +0 -118
  184. package/src/server/createHealthServer.ts +0 -85
  185. package/src/server/proactive/ProactiveTrigger.ts +0 -83
  186. package/src/server/runLauncher.ts +0 -146
  187. package/src/server/tasks/TaskService.ts +0 -110
  188. package/src/server/telemetryIngest.ts +0 -91
  189. package/src/server/tools/tier1/protocolRunner.ts +0 -144
  190. package/src/server/tools/tier1/protocolTools.ts +0 -99
  191. package/src/server/tools/tier2/connectionTools.ts +0 -75
  192. package/src/server/tools/tier2/contextTools.ts +0 -63
  193. package/src/server/tools/tier2/discoveryTools.ts +0 -34
  194. package/src/server/tools/tier2/marketplaceTools.ts +0 -27
  195. package/src/server/tools/tier2/paymentTools.ts +0 -170
  196. package/src/server/ziggsconnect/ZiggsConnectClient.ts +0 -126
  197. package/src/server/ziggscontext/ZiggsContextClient.ts +0 -129
  198. package/src/server/ziggspay/ZiggsPayClient.ts +0 -193
  199. package/src/shared/ids.ts +0 -3
  200. package/src/shared/runtimeLog.ts +0 -72
  201. package/src/shared/types.ts +0 -29
  202. package/src/tasks/protocolRegistry.ts +0 -25
  203. package/src/tools/ToolManager.ts +0 -95
  204. package/src/tools/ToolProvider.ts +0 -19
  205. package/src/tools/defineTool.ts +0 -90
  206. package/src/tools/recordReport.ts +0 -82
  207. package/src/types.ts +0 -456
  208. package/src/utils/jsonExtractor.ts +0 -100
  209. /package/{src/adapters/index.ts → dist/adapters/index.d.ts} +0 -0
  210. /package/{src/formatters/index.ts → dist/formatters/index.d.ts} +0 -0
  211. /package/{src/server/tasks/index.ts → dist/server/tasks/index.d.ts} +0 -0
@@ -1,111 +0,0 @@
1
- interface AgreementFormatterOptions {
2
- shortIds?: boolean;
3
- indentSize?: number;
4
- }
5
-
6
- type AnyObj = Record<string, unknown>;
7
-
8
- export class AgreementFormatter {
9
- private shortIds: boolean;
10
- private indentSize: number;
11
-
12
- constructor(options: AgreementFormatterOptions = {}) {
13
- this.shortIds = options.shortIds ?? false;
14
- this.indentSize = options.indentSize ?? 2;
15
- }
16
-
17
- format(agreements: AnyObj[] | null | undefined): string {
18
- if (!agreements?.length) return 'No active agreements.';
19
- const pending = agreements.filter(a => (a['proposal'] as AnyObj | undefined)?.['status'] === 'pending' && a['proposedToIsYou']);
20
- const standing = agreements.filter(a => !a['task']);
21
- const active = agreements.filter(a => a['task'] && !((a['proposal'] as AnyObj | undefined)?.['status'] === 'pending' && a['proposedToIsYou']));
22
- const sections: string[] = [];
23
- if (pending.length > 0) { sections.push('Pending Proposals (awaiting your response):'); for (const ag of pending) sections.push(this.formatAgreement(ag, this._indent(1))); }
24
- if (active.length > 0) { if (sections.length > 0) sections.push(''); sections.push('Active Agreements:'); for (const ag of active) sections.push(this.formatAgreement(ag, this._indent(1))); }
25
- if (standing.length > 0) { if (sections.length > 0) sections.push(''); sections.push('Standing Agreements (no execution running):'); for (const ag of standing) sections.push(this.formatAgreement(ag, this._indent(1))); }
26
- return sections.join('\n');
27
- }
28
-
29
- formatAgreement(ag: AnyObj, indent = ''): string {
30
- const status = ((ag['status'] as string) || 'unknown').toUpperCase();
31
- const agId = this.shortId(ag['agreementId'] as string);
32
- const parties = (ag['parties'] as AnyObj) || {};
33
- const lines = [
34
- `${indent}[${status}] Agreement ${agId}`,
35
- `${indent} Creator: ${this._labelParty(parties['creator'] as string, ag['creatorIsYou'] as boolean)}`,
36
- `${indent} Provider: ${this._labelParty(parties['provider'] as string, ag['providerIsYou'] as boolean)}`,
37
- `${indent} Payer: ${this._labelParty(parties['payer'] as string, ag['payerIsYou'] as boolean)}`,
38
- ];
39
- if (parties['proposedTo']) lines.push(`${indent} Proposed to: ${this._labelParty(parties['proposedTo'] as string, ag['proposedToIsYou'] as boolean)}`);
40
- const proposal = ag['proposal'] as AnyObj | undefined;
41
- if (proposal?.['status']) lines.push(`${indent} Proposal: ${proposal['status']}${proposal['respondedBy'] ? ` (by ${proposal['respondedBy']})` : ''}`);
42
- const money = ag['money'] as AnyObj | undefined;
43
- if (typeof money?.['price'] === 'number' && (money['price'] as number) > 0) {
44
- const parts = [`${money['price']} cents`];
45
- if (money['paymentStatus'] && money['paymentStatus'] !== 'none') parts.push(money['paymentStatus'] as string);
46
- lines.push(`${indent} Money: ${parts.join(', ')}`);
47
- }
48
- const terms = ag['terms'] as AnyObj | undefined;
49
- if (terms) {
50
- const tparts: string[] = [];
51
- if (terms['lifecycle'] && terms['lifecycle'] !== 'open') tparts.push(`lifecycle: ${terms['lifecycle']}`);
52
- if (terms['maxExecutions'] != null) tparts.push(`maxExecutions: ${terms['maxExecutions']}`);
53
- if (terms['expiresAt']) tparts.push(`expiresAt: ${terms['expiresAt']}`);
54
- if (terms['description']) tparts.push(`"${terms['description']}"`);
55
- if (tparts.length > 0) lines.push(`${indent} Terms: ${tparts.join(', ')}`);
56
- }
57
- if (ag['task']) { lines.push(''); lines.push(`${indent} Execution:`); lines.push(this._renderTaskExecution(ag['task'] as AnyObj, indent + ' ')); }
58
- else lines.push(`${indent} Execution: (none yet)`);
59
- return lines.join('\n');
60
- }
61
-
62
- _renderTaskExecution(task: AnyObj, indent = ''): string {
63
- const state = ((task['state'] as string) || 'unknown').toUpperCase();
64
- const id = this.shortId(task['taskId'] as string);
65
- const lines = [`${indent}[${state}] ${task['description'] || 'No description'}`, `${indent} Task ID: ${id}`];
66
- if (task['parentTaskId']) lines.push(`${indent} Parent task: ${task['parentTaskId']}`);
67
- if (task['result'] && (task['state'] === 'completed' || task['state'] === 'failed')) {
68
- const r = String(task['result']);
69
- lines.push(`${indent} Result: ${r.length > 100 ? r.slice(0, 100) + '...' : r}`);
70
- }
71
- const plan = task['plan'] as AnyObj | undefined;
72
- const steps = plan?.['steps'] as AnyObj[] | undefined;
73
- if (steps?.length) {
74
- const sorted = [...steps].sort((a, b) => (a['order'] as number) - (b['order'] as number));
75
- const done = sorted.filter(s => s['status'] === 'completed').length;
76
- lines.push(`${indent} Plan (${done}/${sorted.length} done):`);
77
- for (const step of sorted) {
78
- const icon = ({ pending: '○', in_progress: '●', completed: '✓', skipped: '–' } as Record<string, string>)[step['status'] as string] || '?';
79
- const note = step['status'] === 'completed' && step['result'] ? ` → ${String(step['result']).slice(0, 60)}${String(step['result']).length > 60 ? '...' : ''}` : '';
80
- lines.push(`${indent} ${step['order']}. [${icon}] ${step['description'] || step['stepId']}${note}`);
81
- }
82
- }
83
- const subtasks = task['subtasks'] as AnyObj[] | undefined;
84
- if (subtasks?.length) {
85
- lines.push(`${indent} Subtasks (${subtasks.length}):`);
86
- for (const st of subtasks) {
87
- const sstate = ((st['state'] as string) || 'unknown').toUpperCase();
88
- const sid = this.shortId(st['taskId'] as string);
89
- lines.push(`${indent} [${sstate}] ${st['description'] || sid} (${sid}, provider: ${st['providerIsYou'] ? 'You' : (st['provider'] ?? 'unassigned')})`);
90
- }
91
- }
92
- return lines.join('\n');
93
- }
94
-
95
- _labelParty(id: string | null | undefined, isYou: boolean | undefined): string {
96
- if (!id) return 'N/A';
97
- return isYou ? `You (${id})` : id;
98
- }
99
-
100
- shortId(id: string | null | undefined): string {
101
- if (!id) return '?';
102
- if (!this.shortIds) return id;
103
- return id.length > 20 ? id.slice(0, 20) + '...' : id;
104
- }
105
-
106
- private _indent(level: number): string {
107
- return ' '.repeat(level * this.indentSize);
108
- }
109
- }
110
-
111
- export const agreementFormatter = new AgreementFormatter();
@@ -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
- }