@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,136 +0,0 @@
1
- import { z } from 'zod';
2
- import { createSdkMcpServer } from '@anthropic-ai/claude-agent-sdk';
3
- import type { SdkMcpToolDefinition } from '@anthropic-ai/claude-agent-sdk';
4
- import type { ToolDefinition } from '../tools/defineTool.js';
5
- import type { ClaudeSdkToolContext } from './claudeSdkTools.js';
6
-
7
- type JsonSchema = Record<string, unknown>;
8
-
9
- type CallToolResult = {
10
- content: Array<{ type: 'text'; text: string }>;
11
- isError?: boolean;
12
- };
13
-
14
- function jsonTypeToZod(field: JsonSchema): z.ZodTypeAny {
15
- const t = field['type'];
16
- if (t === 'string') {
17
- let s: z.ZodTypeAny = z.string();
18
- if (Array.isArray(field['enum'])) {
19
- const vals = field['enum'] as string[];
20
- if (vals.length > 0) s = z.enum(vals as [string, ...string[]]);
21
- }
22
- if (typeof field['description'] === 'string') s = s.describe(field['description']);
23
- return s;
24
- }
25
- if (t === 'number' || t === 'integer') {
26
- let n: z.ZodTypeAny = z.number();
27
- if (typeof field['description'] === 'string') n = n.describe(field['description']);
28
- return n;
29
- }
30
- if (t === 'boolean') return z.boolean();
31
- if (t === 'array') {
32
- const items = (field['items'] as JsonSchema | undefined) ?? { type: 'string' };
33
- return z.array(jsonTypeToZod(items));
34
- }
35
- if (t === 'object') {
36
- const props = (field['properties'] as Record<string, JsonSchema> | undefined) ?? {};
37
- const required = new Set((field['required'] as string[] | undefined) ?? []);
38
- const shape: Record<string, z.ZodTypeAny> = {};
39
- for (const [key, val] of Object.entries(props)) {
40
- let node = jsonTypeToZod(val);
41
- if (!required.has(key)) node = node.optional();
42
- shape[key] = node;
43
- }
44
- return z.object(shape).passthrough();
45
- }
46
- return z.unknown();
47
- }
48
-
49
- function parametersToZodShape(parameters: JsonSchema | undefined): z.ZodRawShape {
50
- if (!parameters || parameters['type'] !== 'object') return {};
51
- const props = (parameters['properties'] as Record<string, JsonSchema> | undefined) ?? {};
52
- const required = new Set((parameters['required'] as string[] | undefined) ?? []);
53
- const shape: Record<string, z.ZodTypeAny> = {};
54
- for (const [key, val] of Object.entries(props)) {
55
- let node = jsonTypeToZod(val);
56
- if (!required.has(key)) node = node.optional();
57
- shape[key] = node;
58
- }
59
- return shape;
60
- }
61
-
62
- function toCallToolResult(value: unknown): CallToolResult {
63
- const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
64
- return { content: [{ type: 'text', text }] };
65
- }
66
-
67
- function toCallToolError(err: unknown): CallToolResult {
68
- const message = err instanceof Error ? err.message : String(err);
69
- return { content: [{ type: 'text', text: message }], isError: true };
70
- }
71
-
72
- /**
73
- * Map Ziggs `ToolDefinition`s to Claude Agent SDK MCP tools. Each handler routes
74
- * execution through `eff({ kind: 'tool-call' })` — the shared executor (ZIG-775).
75
- */
76
- export function buildSdkToolDefs(
77
- toolDefs: ToolDefinition[],
78
- getContext: () => ClaudeSdkToolContext,
79
- ): Array<SdkMcpToolDefinition> {
80
- return toolDefs.map((def) => {
81
- const fn = def.schema.function;
82
- const name = String(fn['name'] ?? '');
83
- const description = String(fn['description'] ?? name);
84
- const shape = parametersToZodShape(fn['parameters'] as JsonSchema | undefined);
85
- const inputSchema = Object.keys(shape).length > 0
86
- ? shape
87
- : { _: z.record(z.string(), z.unknown()).optional() };
88
-
89
- return {
90
- name,
91
- description,
92
- inputSchema,
93
- _meta: { 'anthropic/alwaysLoad': true },
94
- handler: async (args: Record<string, unknown>) => {
95
- try {
96
- const ctx = getContext();
97
- const payload = args._ != null && Object.keys(args).length === 1
98
- ? (args._ as Record<string, unknown>)
99
- : args;
100
- const eff = ctx.eff;
101
- if (!eff) return toCallToolError(`tool "${name}": missing eff in tool context`);
102
- const sessionId = ctx.chatId ?? ctx.sessionId;
103
- if (!sessionId) return toCallToolError(`tool "${name}": missing sessionId in tool context`);
104
- const r = await eff({
105
- kind: 'tool-call',
106
- sessionId,
107
- name,
108
- args: payload ?? {},
109
- senderId: ctx.senderId,
110
- senderType: ctx.senderType,
111
- onBehalfOfAgreementId: ctx.onBehalfOfAgreementId as string | undefined,
112
- runId: ctx.runId,
113
- });
114
- if (r.ok) return toCallToolResult(r.result);
115
- return toCallToolError(r.error ?? `tool "${name}" failed`);
116
- } catch (err) {
117
- return toCallToolError(err);
118
- }
119
- },
120
- };
121
- });
122
- }
123
-
124
- export function buildZiggsSdkMcpServer(
125
- toolDefs: ToolDefinition[],
126
- getContext: () => ClaudeSdkToolContext,
127
- options: { name?: string; instructions?: string } = {},
128
- ) {
129
- return createSdkMcpServer({
130
- name: options.name ?? 'ziggs',
131
- version: '1.0.0',
132
- instructions: options.instructions,
133
- tools: buildSdkToolDefs(toolDefs, getContext),
134
- alwaysLoad: true,
135
- });
136
- }
@@ -1,95 +0,0 @@
1
- export class ContextWarning {
2
- constructor(public path: string, public message: string) {}
3
- toString(): string { return `[context] ${this.path}: ${this.message}`; }
4
- }
5
-
6
- type WarnFn = (path: string, msg: string) => void;
7
-
8
- export function validateContext(
9
- ctx: unknown,
10
- { logger }: { logger?: { warn: (msg: string) => void } } = {},
11
- ): ContextWarning[] {
12
- const warnings: ContextWarning[] = [];
13
- const warn: WarnFn = (path, msg) => warnings.push(new ContextWarning(path, msg));
14
-
15
- if (!ctx || typeof ctx !== 'object') {
16
- warn('context', 'missing or not an object');
17
- return warnings;
18
- }
19
-
20
- const c = ctx as Record<string, unknown>;
21
- validateAgreements(c['agreements'], warn);
22
- validateAgents(c['agents'], warn);
23
- validateHistory(c['history'], warn);
24
- validateUsers(c['users'], warn);
25
-
26
- if (logger && warnings.length > 0) {
27
- for (const w of warnings) logger.warn(w.toString());
28
- }
29
- return warnings;
30
- }
31
-
32
- function validateAgreements(agreements: unknown, warn: WarnFn): void {
33
- if (!Array.isArray(agreements)) return;
34
- for (let i = 0; i < agreements.length; i++) {
35
- const ag = agreements[i] as Record<string, unknown>;
36
- const path = `agreements[${i}]`;
37
- if (!ag || typeof ag !== 'object') { warn(path, 'not an object'); continue; }
38
- for (const key of ['agreementId', 'parties']) {
39
- if (ag[key] == null) warn(`${path}.${key}`, 'missing');
40
- }
41
- if (ag['parties'] && typeof ag['parties'] === 'object') {
42
- const parties = ag['parties'] as Record<string, unknown>;
43
- for (const key of ['creator', 'provider']) {
44
- if (!parties[key]) warn(`${path}.parties.${key}`, 'missing');
45
- }
46
- }
47
- if (ag['proposal'] && typeof ag['proposal'] === 'object') {
48
- if (!(ag['proposal'] as Record<string, unknown>)['status']) warn(`${path}.proposal.status`, 'missing');
49
- }
50
- if (ag['task'] && typeof ag['task'] === 'object') {
51
- const t = ag['task'] as Record<string, unknown>;
52
- if (!t['taskId']) warn(`${path}.task.taskId`, 'missing');
53
- if (!t['state']) warn(`${path}.task.state`, 'missing');
54
- }
55
- }
56
- }
57
-
58
- function validateAgents(agents: unknown, warn: WarnFn): void {
59
- if (!Array.isArray(agents)) return;
60
- let youCount = 0;
61
- for (let i = 0; i < agents.length; i++) {
62
- const agent = agents[i] as Record<string, unknown>;
63
- const path = `agents[${i}]`;
64
- if (!agent || typeof agent !== 'object') { warn(path, 'not an object'); continue; }
65
- if (!agent['agentId']) warn(`${path}.agentId`, 'missing');
66
- if (agent['isYou']) youCount++;
67
- }
68
- if (agents.length > 0 && youCount === 0) warn('agents', 'no agent has isYou=true — agent identity will be unknown');
69
- if (youCount > 1) warn('agents', `${youCount} agents have isYou=true — should be exactly 1`);
70
- }
71
-
72
- function validateHistory(history: unknown, warn: WarnFn): void {
73
- if (!Array.isArray(history)) return;
74
- for (let i = 0; i < history.length; i++) {
75
- const entry = history[i] as Record<string, unknown>;
76
- const path = `history[${i}]`;
77
- if (!entry || typeof entry !== 'object') { warn(path, 'not an object'); continue; }
78
- if (!entry['entryType'] && entry['entryType'] !== 0) warn(`${path}.entryType`, 'missing');
79
- if (entry['entryType'] === 'message' && !entry['sender']) warn(`${path}.sender`, 'missing for message entry');
80
- if (entry['entryType'] === 'task_history') {
81
- const svc = entry['service'] as Record<string, unknown> | undefined;
82
- if (!svc?.['task']) warn(`${path}.service.task`, 'missing for task_history entry');
83
- }
84
- }
85
- }
86
-
87
- function validateUsers(users: unknown, warn: WarnFn): void {
88
- if (!Array.isArray(users)) return;
89
- for (let i = 0; i < users.length; i++) {
90
- const user = users[i] as Record<string, unknown>;
91
- const path = `users[${i}]`;
92
- if (!user || typeof user !== 'object') { warn(path, 'not an object'); continue; }
93
- if (!user['userId']) warn(`${path}.userId`, 'missing');
94
- }
95
- }
@@ -1,80 +0,0 @@
1
- import { isProtocolToolName, mapProtocolToolToOperation } from '../tasks/protocolRegistry.js';
2
-
3
- function applyTaskOperationResultToContext(updates: Record<string, unknown>, operation: string | null, result: Record<string, unknown>): void {
4
- const r = result || {};
5
- const agreement = (r['agreement'] as Record<string, unknown>) ||
6
- (r['agreementId'] ? r : null);
7
- const task = (r['task'] as Record<string, unknown>) || (r['taskId'] ? r : null);
8
-
9
- if (operation === 'agreement-propose' || operation === 'agreement-subcontract') {
10
- // Agreement creation no longer spawns a task. The caller has made a
11
- // proposal that the proposedTo party still needs to approve.
12
- if (agreement) updates['proposal'] = r;
13
- }
14
- if (operation === 'task-spawn') {
15
- if (task) {
16
- updates['delegatedTask'] = r;
17
- if (task['taskId']) {
18
- if (!updates['_delegatedTaskIds']) updates['_delegatedTaskIds'] = [];
19
- (updates['_delegatedTaskIds'] as string[]).push(task['taskId'] as string);
20
- }
21
- }
22
- }
23
- if (operation === 'task-update') {
24
- const status = (task?.['state'] || r['state'] || r['status']) as string | undefined;
25
- if (status === 'completed') updates['taskCompleted'] = true;
26
- if (status === 'failed') updates['taskFailed'] = true;
27
- }
28
- if (operation === 'agreement-respond') updates['respondedProposal'] = r;
29
- }
30
-
31
- export const CONTEXT_RESET: Record<string, unknown> = Object.freeze({
32
- messageSent: false, activeWait: false, proposal: null, taskCompleted: false,
33
- taskFailed: false, subtaskResult: null, subtaskFailed: false, toolResults: null,
34
- lastError: null, lastAction: null, lastActionResult: null, approval: false,
35
- rejection: false, taskAssignment: null, incomingMessage: false,
36
- respondedProposal: null, searchCompleted: false, boardResults: null, taskPublished: false,
37
- });
38
-
39
- export function buildContextUpdates(actionName: string, emittedEvents: unknown[]): Record<string, unknown> {
40
- const updates: Record<string, unknown> = { ...CONTEXT_RESET, lastAction: actionName };
41
- if (!Array.isArray(emittedEvents)) return updates;
42
- const toolResults: unknown[] = [];
43
-
44
- for (const ev of emittedEvents) {
45
- if (!ev || typeof ev !== 'object') continue;
46
- const events = Array.isArray(ev) ? ev : [ev];
47
- for (const e of events) {
48
- const event = e as Record<string, unknown>;
49
- switch (event['type']) {
50
- case 'tool_result':
51
- toolResults.push({ tool: event['tool'], result: event['result'] });
52
- updates['lastActionResult'] = event;
53
- if (isProtocolToolName(event['tool'] as string)) {
54
- applyTaskOperationResultToContext(updates, mapProtocolToolToOperation(event['tool'] as string), (event['result'] as Record<string, unknown>) || {});
55
- }
56
- break;
57
- case 'tool_error':
58
- toolResults.push({ tool: event['tool'], error: event['error'] });
59
- updates['lastActionResult'] = event;
60
- updates['lastError'] = event['error'];
61
- break;
62
- case 'message_sent':
63
- updates['messageSent'] = true; updates['lastActionResult'] = event; break;
64
- case 'message_duplicate_skipped':
65
- updates['messageSent'] = true; break;
66
- case 'waited':
67
- updates['activeWait'] = true; break;
68
- case 'task_result': {
69
- updates['lastActionResult'] = event;
70
- applyTaskOperationResultToContext(updates, (event['operation'] as string) || null, (event['result'] as Record<string, unknown>) || {});
71
- break;
72
- }
73
- case 'task_error':
74
- updates['lastError'] = event['error']; updates['lastActionResult'] = event; break;
75
- }
76
- }
77
- }
78
- if (toolResults.length > 0) updates['toolResults'] = toolResults;
79
- return updates;
80
- }
@@ -1,19 +0,0 @@
1
- import { isBroadcastTarget } from '@ziggs-ai/api-client';
2
-
3
- export function getBatchEvents(rawEvent: unknown): unknown[] {
4
- if (!rawEvent) return [];
5
- const e = rawEvent as Record<string, unknown>;
6
- if (e['type'] === 'batch' && Array.isArray(e['events'])) return e['events'] as unknown[];
7
- return [rawEvent];
8
- }
9
-
10
- export function isTaskResultRelevantToAgent(result: Record<string, unknown>, ownAgentId: string | null): boolean {
11
- if (!ownAgentId) return true;
12
- const parties = (result['agreement'] as Record<string, unknown> | undefined)?.['parties'] as Record<string, unknown> | undefined ?? {};
13
- return !!(
14
- result['creatorIsYou'] || result['providerIsYou'] || result['payerIsYou'] || result['proposedToIsYou'] ||
15
- parties['creator'] === ownAgentId || parties['provider'] === ownAgentId ||
16
- parties['payer'] === ownAgentId || parties['proposedTo'] === ownAgentId ||
17
- isBroadcastTarget(parties['proposedTo'] as string | undefined)
18
- );
19
- }
@@ -1,38 +0,0 @@
1
- import { CONTEXT_RESET } from './applyEffects.js';
2
- import { getBatchEvents, isTaskResultRelevantToAgent } from './batch.js';
3
-
4
- function isTaskAssignment(result: Record<string, unknown>, ownAgentId: string | null): boolean {
5
- const parties = (result['agreement'] as Record<string, unknown> | undefined)?.['parties'] as Record<string, unknown> | undefined ?? {};
6
- const isProvider = result['providerIsYou'] || parties['provider'] === ownAgentId;
7
- return !!(isProvider && (result['state'] === 'active' || result['state'] === 'in-progress'));
8
- }
9
-
10
- export function classifyIncomingEvent(rawEvent: unknown, ownAgentId: string | null): Record<string, unknown> {
11
- const flags: Record<string, unknown> = { ...CONTEXT_RESET };
12
- if (!rawEvent) return flags;
13
-
14
- for (const ev of getBatchEvents(rawEvent)) {
15
- if (!ev) continue;
16
- const e = ev as Record<string, unknown>;
17
- if (e['type'] !== 'task_result') { flags['incomingMessage'] = true; continue; }
18
-
19
- const result = (e['result'] as Record<string, unknown>) || {};
20
- if (ownAgentId && !isTaskResultRelevantToAgent(result, ownAgentId) && e['receiverId'] !== ownAgentId) continue;
21
-
22
- const state = result['state'] as string | undefined;
23
- const ag = result['agreement'] as Record<string, unknown> | undefined;
24
- const parties = (ag?.['parties'] as Record<string, unknown>) || {};
25
- const proposalStatus = (ag?.['proposal'] as Record<string, unknown> | undefined)?.['status'];
26
-
27
- if (state === 'active' && proposalStatus === 'approved' && ownAgentId && parties['creator'] === ownAgentId) {
28
- flags['approval'] = true; flags['taskAssignment'] = result; continue;
29
- }
30
- if (isTaskAssignment(result, ownAgentId)) { flags['taskAssignment'] = result; flags['approval'] = true; continue; }
31
- if (proposalStatus === 'approved' || (state === 'active' && proposalStatus === 'pending')) { flags['approval'] = true; flags['taskAssignment'] = result; continue; }
32
- if (proposalStatus === 'rejected' || state === 'cancelled') { flags['rejection'] = true; continue; }
33
- if (state === 'completed') { flags['subtaskResult'] = result; continue; }
34
- if (state === 'failed') { flags['subtaskResult'] = result; flags['subtaskFailed'] = true; continue; }
35
- flags['subtaskResult'] = result;
36
- }
37
- return flags;
38
- }
@@ -1,46 +0,0 @@
1
- import { isProtocolToolName } from '../tasks/protocolRegistry.js';
2
- import { getBatchEvents, isTaskResultRelevantToAgent } from './batch.js';
3
-
4
- export function unwrapBatchEvent(event: unknown): unknown {
5
- const e = event as Record<string, unknown> | null | undefined;
6
- if (e?.['type'] === 'batch' && Array.isArray(e['events']) && e['events'][0]) return e['events'][0];
7
- return event;
8
- }
9
-
10
- export function classifyWorkflowEvent(event: unknown, ownAgentId: string | null = null): string {
11
- const events = getBatchEvents(event);
12
- if (events.length === 0) return 'message';
13
-
14
- let sawTaskResult = false, sawOwnTaskResult = false;
15
-
16
- for (const ev of events) {
17
- const e = ev as Record<string, unknown> | null | undefined;
18
- if (e?.['type'] !== 'task_result') continue;
19
- sawTaskResult = true;
20
- const result = (e['result'] as Record<string, unknown>) || {};
21
- if (!isTaskResultRelevantToAgent(result, ownAgentId)) continue;
22
- sawOwnTaskResult = true;
23
- const state = result['state'] as string | undefined;
24
- const ag = result['agreement'] as Record<string, unknown> | undefined;
25
- const parties = (ag?.['parties'] as Record<string, unknown>) || {};
26
- const proposalStatus = ag?.['proposal'] ? (ag['proposal'] as Record<string, unknown>)['status'] : undefined;
27
- const isProvider = result['providerIsYou'] || parties['provider'] === ownAgentId;
28
- if (isProvider && (state === 'active' || state === 'in-progress')) return 'task_assignment';
29
- if (proposalStatus === 'approved' || (state === 'active' && proposalStatus === 'pending')) return 'task_approved';
30
- if (proposalStatus === 'rejected' || state === 'cancelled') return 'task_rejected';
31
- }
32
- if (sawOwnTaskResult || sawTaskResult) return 'task_update';
33
- return 'message';
34
- }
35
-
36
- export function findTaskResult(output: Record<string, unknown> | null | undefined): unknown {
37
- const events = (output?.['emittedEvents'] as unknown[]) ?? [];
38
- return events.find(e => {
39
- const ev = e as Record<string, unknown>;
40
- return ev['type'] === 'task_result' || (ev['type'] === 'tool_result' && isProtocolToolName(ev['tool'] as string));
41
- }) ?? null;
42
- }
43
-
44
- export function findIncomingTaskResult(incomingEvent: unknown): unknown {
45
- return getBatchEvents(incomingEvent).find(e => (e as Record<string, unknown>)?.['type'] === 'task_result') ?? null;
46
- }
@@ -1,77 +0,0 @@
1
- import type { AgentConfig, DefineAgentInput, Workflow } from './types.js';
2
- import { validateWorkflow } from './runtime/validateWorkflow.js';
3
- import { injectKickoffDefault } from './runtime/kickoff.js';
4
- import { deriveRespondsToProposals } from './runtime/deriveRespondsToProposals.js';
5
- import { runtimeLog } from './shared/runtimeLog.js';
6
- import { DEFAULT_MODEL } from './AgentHost.js';
7
-
8
- /**
9
- * Validates the workflow synchronously, resolves merged tools and model, and
10
- * returns a frozen AgentConfig. Never mutates the input. `wait` defaults remain
11
- * the author's visible spread of `thinkingDefaults`. ONE default is injected (as
12
- * new objects): the agreement-kickoff state `kickingOff` plus a last-position
13
- * transition into it, appended to every state that does not already handle a
14
- * proposer-side proposal-resolved/approve outcome (runtime/kickoff.ts). The
15
- * state name 'kickingOff' is reserved; defining it throws.
16
- *
17
- * Validation throws WorkflowValidationError on hard problems and logs warnings
18
- * on soft ones (e.g. missing wait fallthrough).
19
- */
20
- export function defineAgent(input: DefineAgentInput): AgentConfig {
21
- if (!input?.agentId) throw new Error('[defineAgent] agentId is required');
22
- if (!input?.description) throw new Error('[defineAgent] description is required');
23
- if (!input?.states) throw new Error('[defineAgent] states is required');
24
- if (!input?.initial) throw new Error('[defineAgent] initial state is required');
25
-
26
- // Agreement-kickoff default (see runtime/kickoff.ts): injected BEFORE
27
- // validation so the injected state/transitions are validated too.
28
- const workflow: Workflow = injectKickoffDefault({
29
- id: input.agentId,
30
- description: input.description,
31
- initial: input.initial,
32
- states: input.states,
33
- });
34
-
35
- const { warnings } = validateWorkflow(workflow);
36
- for (const w of warnings) runtimeLog.warn('defineAgent', w);
37
-
38
- const tools = [
39
- ...(Array.isArray(input.tools) ? input.tools : []),
40
- ...(Array.isArray(input.services?.tools) ? input.services!.tools! : []),
41
- ];
42
-
43
- // Model resolution, most-specific-first: a per-agent pin, then the
44
- // fleet-wide `LLM_MODEL` lever, then the single `DEFAULT_MODEL` fallback (the
45
- // ONE place the default lives — see AgentHost). The id also picks the provider
46
- // (claude-* → Anthropic). No agent hardcodes its own fallback.
47
- const model =
48
- input.services?.llm?.model ||
49
- process.env.LLM_MODEL ||
50
- DEFAULT_MODEL;
51
-
52
- // Strip the structural fields we already consumed; pass through everything
53
- // else (operatorKey, taskTools, custom keys consumed by AgentHost).
54
- const {
55
- agentId, description, specialization, services: _services, initial: _initial,
56
- states: _states, tools: _tools, operatorKey, taskTools, ...rest
57
- } = input;
58
-
59
- const config: AgentConfig = {
60
- openaiKey: process.env.OPENAI_API_KEY,
61
- anthropicKey: process.env.ANTHROPIC_API_KEY,
62
- ...(operatorKey ? { operatorKey } : {}),
63
- agentId,
64
- description,
65
- ...(specialization ? { specialization } : {}),
66
- tools,
67
- model,
68
- workflow,
69
- respondsToProposals:
70
- input.respondsToProposals ?? deriveRespondsToProposals(workflow),
71
- ...(input.services ? { services: input.services } : {}),
72
- ...(taskTools !== undefined ? { taskTools } : {}),
73
- ...rest,
74
- };
75
-
76
- return Object.freeze(config) as AgentConfig;
77
- }
@@ -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();