@ziggs-ai/agent-sdk 0.1.12 → 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.
- package/CHANGELOG.md +14 -0
- package/README.md +41 -2
- package/dist/AgentHost.d.ts +201 -0
- package/dist/AgentHost.js +652 -0
- package/dist/adapters/AnthropicAdapter.d.ts +39 -0
- package/dist/adapters/AnthropicAdapter.js +200 -0
- package/dist/adapters/McpAdapter.d.ts +199 -0
- package/dist/adapters/McpAdapter.js +468 -0
- package/dist/adapters/OpenAIAdapter.d.ts +26 -0
- package/dist/adapters/OpenAIAdapter.js +158 -0
- package/dist/adapters/index.js +2 -0
- package/dist/agent/Agent.d.ts +78 -0
- package/dist/agent/Agent.js +58 -0
- package/dist/agent/ClaudeSdkAgent.d.ts +38 -0
- package/dist/agent/ClaudeSdkAgent.js +322 -0
- package/dist/agent/claudeCognition.d.ts +67 -0
- package/dist/agent/claudeCognition.js +103 -0
- package/dist/agent/claudeSdkProtocol.d.ts +11 -0
- package/dist/agent/claudeSdkTools.d.ts +19 -0
- package/dist/agent/claudeSdkTools.js +57 -0
- package/dist/agent/hostedAgentConnection.d.ts +15 -0
- package/dist/agent/hostedAgentConnection.js +29 -0
- package/dist/agent/toolManagerToSdkMcp.d.ts +12 -0
- package/dist/agent/toolManagerToSdkMcp.js +123 -0
- package/dist/brain/index.d.ts +50 -0
- package/dist/brain/index.js +45 -0
- package/dist/cognition/validateContext.d.ts +11 -0
- package/dist/cognition/validateContext.js +117 -0
- package/dist/context/applyEffects.d.ts +2 -0
- package/dist/context/applyEffects.js +89 -0
- package/dist/context/batch.d.ts +2 -0
- package/dist/context/batch.js +18 -0
- package/dist/context/classifyEnvelope.d.ts +1 -0
- package/dist/context/classifyEnvelope.js +58 -0
- package/dist/context/routingLabels.d.ts +4 -0
- package/dist/context/routingLabels.js +48 -0
- package/dist/defineAgent.d.ts +14 -0
- package/dist/defineAgent.js +68 -0
- package/dist/formatters/AgreementFormatter.d.ts +18 -0
- package/dist/formatters/AgreementFormatter.js +130 -0
- package/dist/formatters/HistoryFormatter.d.ts +26 -0
- package/dist/formatters/HistoryFormatter.js +173 -0
- package/dist/formatters/index.js +2 -0
- package/{src/index.ts → dist/index.d.ts} +7 -53
- package/dist/index.js +66 -0
- package/dist/ingress/normalizeIncoming.d.ts +65 -0
- package/dist/ingress/normalizeIncoming.js +88 -0
- package/dist/memory/MemoryStore.d.ts +55 -0
- package/dist/memory/MemoryStore.js +78 -0
- package/dist/pricing/fleetDefaults.d.ts +46 -0
- package/dist/pricing/fleetDefaults.js +168 -0
- package/dist/pricing/fleetEvalFree.d.ts +7 -0
- package/dist/pricing/fleetEvalFree.js +24 -0
- package/dist/pricing/fleetFreeTierA.gen.d.ts +6 -0
- package/{src/pricing/fleetFreeTierA.gen.ts → dist/pricing/fleetFreeTierA.gen.js} +5 -6
- package/dist/pricing/fleetTierByAgentId.gen.d.ts +7 -0
- package/dist/pricing/fleetTierByAgentId.gen.js +768 -0
- package/dist/runtime/AgentMachine.d.ts +143 -0
- package/dist/runtime/AgentMachine.js +400 -0
- package/dist/runtime/PromptBuilder.d.ts +96 -0
- package/dist/runtime/PromptBuilder.js +439 -0
- package/{src/runtime/bootstrapCtx.ts → dist/runtime/bootstrapCtx.d.ts} +1 -22
- package/dist/runtime/bootstrapCtx.js +37 -0
- package/dist/runtime/buildOutcome.d.ts +68 -0
- package/dist/runtime/buildOutcome.js +464 -0
- package/dist/runtime/defaults.d.ts +54 -0
- package/dist/runtime/defaults.js +47 -0
- package/dist/runtime/deriveRespondsToProposals.d.ts +9 -0
- package/dist/runtime/deriveRespondsToProposals.js +38 -0
- package/dist/runtime/kickoff.d.ts +15 -0
- package/dist/runtime/kickoff.js +112 -0
- package/dist/runtime/runMechanical.d.ts +25 -0
- package/dist/runtime/runMechanical.js +74 -0
- package/dist/runtime/runTurn.d.ts +63 -0
- package/dist/runtime/runTurn.js +800 -0
- package/dist/runtime/validateWorkflow.d.ts +17 -0
- package/dist/runtime/validateWorkflow.js +209 -0
- package/dist/server/ConnectionPool.d.ts +68 -0
- package/dist/server/ConnectionPool.js +166 -0
- package/dist/server/EventQueue.d.ts +33 -0
- package/dist/server/EventQueue.js +98 -0
- package/dist/server/InboxCatchUp.d.ts +24 -0
- package/dist/server/InboxCatchUp.js +213 -0
- package/dist/server/OutboxBuffer.d.ts +33 -0
- package/dist/server/OutboxBuffer.js +68 -0
- package/dist/server/SeenMessages.d.ts +13 -0
- package/dist/server/SeenMessages.js +31 -0
- package/dist/server/StateTimers.d.ts +34 -0
- package/dist/server/StateTimers.js +70 -0
- package/dist/server/ZiggsEffectHandler.d.ts +79 -0
- package/dist/server/ZiggsEffectHandler.js +319 -0
- package/dist/server/agreements/AgreementService.d.ts +50 -0
- package/dist/server/agreements/AgreementService.js +85 -0
- package/dist/server/createHealthServer.d.ts +7 -0
- package/dist/server/createHealthServer.js +75 -0
- package/dist/server/proactive/ProactiveTrigger.d.ts +33 -0
- package/dist/server/proactive/ProactiveTrigger.js +71 -0
- package/dist/server/runLauncher.d.ts +28 -0
- package/dist/server/runLauncher.js +93 -0
- package/dist/server/tasks/TaskService.d.ts +25 -0
- package/dist/server/tasks/TaskService.js +103 -0
- package/dist/server/tasks/index.js +1 -0
- package/dist/server/telemetryIngest.d.ts +24 -0
- package/dist/server/telemetryIngest.js +62 -0
- package/dist/server/tools/index.d.ts +24 -0
- package/{src/server/tools/index.ts → dist/server/tools/index.js} +4 -24
- package/dist/server/tools/tier1/protocolRunner.d.ts +39 -0
- package/dist/server/tools/tier1/protocolRunner.js +288 -0
- package/dist/server/tools/tier1/protocolTools.d.ts +12 -0
- package/dist/server/tools/tier1/protocolTools.js +37 -0
- package/dist/server/tools/tier2/connectionTools.d.ts +4 -0
- package/dist/server/tools/tier2/connectionTools.js +63 -0
- package/dist/server/tools/tier2/contextTools.d.ts +4 -0
- package/dist/server/tools/tier2/contextTools.js +46 -0
- package/dist/server/tools/tier2/discoveryTools.d.ts +4 -0
- package/dist/server/tools/tier2/discoveryTools.js +25 -0
- package/dist/server/tools/tier2/marketplaceTools.d.ts +3 -0
- package/dist/server/tools/tier2/marketplaceTools.js +22 -0
- package/dist/server/tools/tier2/paymentTools.d.ts +12 -0
- package/dist/server/tools/tier2/paymentTools.js +165 -0
- package/dist/server/ziggsconnect/ZiggsConnectClient.d.ts +35 -0
- package/dist/server/ziggsconnect/ZiggsConnectClient.js +95 -0
- package/dist/server/ziggscontext/ZiggsContextClient.d.ts +48 -0
- package/dist/server/ziggscontext/ZiggsContextClient.js +90 -0
- package/dist/server/ziggspay/ZiggsPayClient.d.ts +82 -0
- package/dist/server/ziggspay/ZiggsPayClient.js +188 -0
- package/dist/shared/ids.d.ts +1 -0
- package/dist/shared/ids.js +3 -0
- package/dist/shared/runtimeLog.d.ts +18 -0
- package/dist/shared/runtimeLog.js +68 -0
- package/dist/shared/types.d.ts +22 -0
- package/dist/shared/types.js +23 -0
- package/dist/tasks/protocolRegistry.d.ts +16 -0
- package/dist/tasks/protocolRegistry.js +20 -0
- package/dist/tools/ToolManager.d.ts +12 -0
- package/dist/tools/ToolManager.js +74 -0
- package/dist/tools/ToolProvider.d.ts +6 -0
- package/dist/tools/ToolProvider.js +21 -0
- package/dist/tools/defineTool.d.ts +27 -0
- package/dist/tools/defineTool.js +62 -0
- package/{src/tools/index.ts → dist/tools/index.d.ts} +0 -1
- package/dist/tools/index.js +6 -0
- package/dist/tools/recordReport.d.ts +41 -0
- package/dist/tools/recordReport.js +30 -0
- package/dist/types.d.ts +466 -0
- package/dist/types.js +7 -0
- package/dist/utils/jsonExtractor.d.ts +2 -0
- package/dist/utils/jsonExtractor.js +111 -0
- package/package.json +13 -5
- package/src/AgentHost.ts +0 -814
- package/src/adapters/AnthropicAdapter.ts +0 -238
- package/src/adapters/McpAdapter.ts +0 -678
- package/src/adapters/OpenAIAdapter.ts +0 -194
- package/src/agent/Agent.ts +0 -112
- package/src/agent/ClaudeSdkAgent.ts +0 -401
- package/src/agent/claudeCognition.ts +0 -139
- package/src/agent/claudeSdkTools.ts +0 -81
- package/src/agent/hostedAgentConnection.ts +0 -41
- package/src/agent/toolManagerToSdkMcp.ts +0 -136
- package/src/cognition/validateContext.ts +0 -95
- package/src/context/applyEffects.ts +0 -80
- package/src/context/batch.ts +0 -19
- package/src/context/classifyEnvelope.ts +0 -38
- package/src/context/routingLabels.ts +0 -46
- package/src/defineAgent.ts +0 -77
- package/src/formatters/AgreementFormatter.ts +0 -111
- package/src/formatters/HistoryFormatter.ts +0 -172
- package/src/ingress/normalizeIncoming.ts +0 -162
- package/src/memory/MemoryStore.ts +0 -104
- package/src/pricing/fleetDefaults.ts +0 -225
- package/src/pricing/fleetEvalFree.ts +0 -24
- package/src/pricing/fleetTierByAgentId.gen.ts +0 -775
- package/src/runtime/AgentMachine.ts +0 -484
- package/src/runtime/PromptBuilder.ts +0 -522
- package/src/runtime/buildOutcome.ts +0 -563
- package/src/runtime/defaults.ts +0 -86
- package/src/runtime/deriveRespondsToProposals.ts +0 -35
- package/src/runtime/kickoff.ts +0 -117
- package/src/runtime/runMechanical.ts +0 -106
- package/src/runtime/runTurn.ts +0 -870
- package/src/runtime/validateWorkflow.ts +0 -221
- package/src/server/ConnectionPool.ts +0 -206
- package/src/server/EventQueue.ts +0 -133
- package/src/server/InboxCatchUp.ts +0 -291
- package/src/server/OutboxBuffer.ts +0 -90
- package/src/server/SeenMessages.ts +0 -27
- package/src/server/StateTimers.ts +0 -85
- package/src/server/ZiggsEffectHandler.ts +0 -427
- package/src/server/agreements/AgreementService.ts +0 -118
- package/src/server/createHealthServer.ts +0 -85
- package/src/server/proactive/ProactiveTrigger.ts +0 -83
- package/src/server/runLauncher.ts +0 -146
- package/src/server/tasks/TaskService.ts +0 -111
- package/src/server/telemetryIngest.ts +0 -91
- package/src/server/tools/tier1/protocolRunner.ts +0 -353
- package/src/server/tools/tier1/protocolTools.ts +0 -114
- package/src/server/tools/tier2/connectionTools.ts +0 -75
- package/src/server/tools/tier2/contextTools.ts +0 -63
- package/src/server/tools/tier2/discoveryTools.ts +0 -34
- package/src/server/tools/tier2/marketplaceTools.ts +0 -27
- package/src/server/tools/tier2/paymentTools.ts +0 -170
- package/src/server/ziggsconnect/ZiggsConnectClient.ts +0 -126
- package/src/server/ziggscontext/ZiggsContextClient.ts +0 -129
- package/src/server/ziggspay/ZiggsPayClient.ts +0 -193
- package/src/shared/ids.ts +0 -3
- package/src/shared/runtimeLog.ts +0 -72
- package/src/shared/types.ts +0 -29
- package/src/tasks/protocolRegistry.ts +0 -25
- package/src/tools/ToolManager.ts +0 -95
- package/src/tools/ToolProvider.ts +0 -19
- package/src/tools/defineTool.ts +0 -90
- package/src/tools/recordReport.ts +0 -82
- package/src/types.ts +0 -483
- package/src/utils/jsonExtractor.ts +0 -100
- /package/{src/adapters/index.ts → dist/adapters/index.d.ts} +0 -0
- /package/{src/agent/claudeSdkProtocol.ts → dist/agent/claudeSdkProtocol.js} +0 -0
- /package/{src/formatters/index.ts → dist/formatters/index.d.ts} +0 -0
- /package/{src/server/tasks/index.ts → dist/server/tasks/index.d.ts} +0 -0
|
@@ -1,194 +0,0 @@
|
|
|
1
|
-
import OpenAI from 'openai';
|
|
2
|
-
import type { ToolDefinition } from '../tools/defineTool.js';
|
|
3
|
-
import { runtimeLog } from '../shared/runtimeLog.js';
|
|
4
|
-
|
|
5
|
-
interface ChatResult {
|
|
6
|
-
content: string | null;
|
|
7
|
-
tool_calls: OpenAI.Chat.ChatCompletionMessageToolCall[] | null;
|
|
8
|
-
message: OpenAI.Chat.ChatCompletionMessage;
|
|
9
|
-
usage: OpenAI.CompletionUsage | undefined;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
interface AdapterOptions {
|
|
13
|
-
key?: string;
|
|
14
|
-
model?: string;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/** OpenAI completion-token cap varies by model family (e.g. gpt-4o-mini max 16384). */
|
|
18
|
-
export function maxCompletionTokensForModel(model: string): number {
|
|
19
|
-
const m = model.toLowerCase();
|
|
20
|
-
if (m.includes('gpt-4o')) return 16384;
|
|
21
|
-
return 25000;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export class OpenAIAdapter {
|
|
25
|
-
private client: OpenAI;
|
|
26
|
-
model: string;
|
|
27
|
-
|
|
28
|
-
constructor({ key, model = 'gpt-5.4' }: AdapterOptions) {
|
|
29
|
-
this.client = new OpenAI({ apiKey: key });
|
|
30
|
-
this.model = model;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
async chat(
|
|
34
|
-
prompt: string,
|
|
35
|
-
tools: ToolDefinition[] = [],
|
|
36
|
-
temperature = 0.2,
|
|
37
|
-
systemHints: OpenAI.Chat.ChatCompletionMessageParam[] = [],
|
|
38
|
-
options: Record<string, unknown> = {},
|
|
39
|
-
): Promise<ChatResult> {
|
|
40
|
-
const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [
|
|
41
|
-
{ role: 'system', content: 'Respond with valid JSON.' },
|
|
42
|
-
...systemHints,
|
|
43
|
-
{ role: 'user', content: prompt },
|
|
44
|
-
];
|
|
45
|
-
return this.chatMessages(messages, tools, { ...options, temperature });
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
async chatMessages(
|
|
49
|
-
messages: OpenAI.Chat.ChatCompletionMessageParam[],
|
|
50
|
-
tools: ToolDefinition[] = [],
|
|
51
|
-
options: Record<string, unknown> = {},
|
|
52
|
-
): Promise<ChatResult> {
|
|
53
|
-
const openAITools: OpenAI.Chat.ChatCompletionTool[] | undefined = tools.length > 0
|
|
54
|
-
? tools.map(t => {
|
|
55
|
-
const fn = (t.schema.function || t.schema) as Record<string, unknown>;
|
|
56
|
-
const tAny = t as unknown as Record<string, unknown>;
|
|
57
|
-
const usageWhen = tAny['usage']
|
|
58
|
-
? ` Use when: ${(tAny['usage'] as Record<string, unknown>)['when']}`
|
|
59
|
-
: '';
|
|
60
|
-
return {
|
|
61
|
-
type: 'function' as const,
|
|
62
|
-
function: {
|
|
63
|
-
name: fn['name'] as string,
|
|
64
|
-
description: ((fn['description'] as string) || '') + usageWhen,
|
|
65
|
-
parameters: fn['parameters'] as Record<string, unknown>,
|
|
66
|
-
},
|
|
67
|
-
};
|
|
68
|
-
})
|
|
69
|
-
: undefined;
|
|
70
|
-
|
|
71
|
-
try {
|
|
72
|
-
const { usage: _u, response_format: _explicitResponseFormat, ...restOptions } = options as Record<string, unknown>;
|
|
73
|
-
const responseFormat = openAITools
|
|
74
|
-
? undefined
|
|
75
|
-
: ((_explicitResponseFormat as OpenAI.ResponseFormatJSONObject) ?? { type: 'json_object' });
|
|
76
|
-
|
|
77
|
-
// OpenAI 400s response_format:{type:'json_object'} unless the word "json"
|
|
78
|
-
// appears somewhere in the messages. Callers are expected to mention it
|
|
79
|
-
// in their system prompt, but that's an implicit cross-file contract —
|
|
80
|
-
// guarantee it here instead of trusting every call site to remember.
|
|
81
|
-
let finalMessages = messages;
|
|
82
|
-
if (
|
|
83
|
-
responseFormat?.type === 'json_object' &&
|
|
84
|
-
!messages.some(m => {
|
|
85
|
-
const c = typeof m.content === 'string' ? m.content : JSON.stringify(m.content ?? '');
|
|
86
|
-
return /json/i.test(c);
|
|
87
|
-
})
|
|
88
|
-
) {
|
|
89
|
-
finalMessages = [...messages, { role: 'system', content: 'Respond with valid JSON.' }];
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// Verbose LLM request/response logging — enabled for debugging.
|
|
93
|
-
// Comment out again to reduce log noise.
|
|
94
|
-
const divider = '─'.repeat(80);
|
|
95
|
-
console.log(`\n${divider}`);
|
|
96
|
-
console.log(`📤 LLM REQUEST → ${this.model} (${finalMessages.length} msg${finalMessages.length === 1 ? '' : 's'})`);
|
|
97
|
-
console.log(divider);
|
|
98
|
-
for (const m of finalMessages) {
|
|
99
|
-
const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content);
|
|
100
|
-
const len = content?.length ?? 0;
|
|
101
|
-
console.log(`\n[${m.role.toUpperCase()}] ${len} chars`);
|
|
102
|
-
console.log(content ?? '');
|
|
103
|
-
}
|
|
104
|
-
console.log(`${divider}\n`);
|
|
105
|
-
const res = await this.client.chat.completions.create({
|
|
106
|
-
model: this.model,
|
|
107
|
-
messages: finalMessages,
|
|
108
|
-
stream: false,
|
|
109
|
-
// Reasoning models (gpt-5.x/o-series) need a high cap for hidden
|
|
110
|
-
// reasoning tokens; gpt-4o family is capped lower by the API.
|
|
111
|
-
max_completion_tokens: maxCompletionTokensForModel(this.model),
|
|
112
|
-
response_format: responseFormat,
|
|
113
|
-
...(openAITools && { tools: openAITools }),
|
|
114
|
-
...restOptions,
|
|
115
|
-
} as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming);
|
|
116
|
-
|
|
117
|
-
const msg = res.choices[0].message;
|
|
118
|
-
const finishReason = res.choices[0].finish_reason;
|
|
119
|
-
const content = msg.content?.trim() ?? null;
|
|
120
|
-
const toolCalls = msg.tool_calls?.length ? msg.tool_calls : null;
|
|
121
|
-
// Verbose LLM response logging — enabled for debugging.
|
|
122
|
-
// Comment out again to reduce log noise.
|
|
123
|
-
console.log(`\n${divider}`);
|
|
124
|
-
console.log(`📥 LLM RESPONSE ← ${this.model} finish=${finishReason}`);
|
|
125
|
-
console.log(divider);
|
|
126
|
-
if (content) {
|
|
127
|
-
console.log(`\n[CONTENT] ${content.length} chars`);
|
|
128
|
-
console.log(content);
|
|
129
|
-
}
|
|
130
|
-
if (toolCalls) {
|
|
131
|
-
console.log(`\n[TOOL CALLS] ${toolCalls.length}`);
|
|
132
|
-
for (const tc of toolCalls) {
|
|
133
|
-
console.log(` → ${tc.function.name}(${tc.function.arguments})`);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
if (!content && !toolCalls) console.log('\n(no content, no tool calls)');
|
|
137
|
-
if (res.usage) {
|
|
138
|
-
const u = res.usage as OpenAI.CompletionUsage & { completion_tokens_details?: { reasoning_tokens?: number } };
|
|
139
|
-
console.log(`\n[USAGE] prompt=${u.prompt_tokens} completion=${u.completion_tokens}${u.completion_tokens_details?.reasoning_tokens != null ? ` (reasoning=${u.completion_tokens_details.reasoning_tokens})` : ''} total=${u.total_tokens}`);
|
|
140
|
-
}
|
|
141
|
-
console.log(`${divider}\n`);
|
|
142
|
-
if (!content && !toolCalls && finishReason === 'length') {
|
|
143
|
-
const u = res.usage as (OpenAI.CompletionUsage & { completion_tokens_details?: { reasoning_tokens?: number } }) | undefined;
|
|
144
|
-
throw new Error(
|
|
145
|
-
`LLM returned no usable output — completion token budget exhausted before any content ` +
|
|
146
|
-
`(finish_reason=length, reasoning_tokens=${u?.completion_tokens_details?.reasoning_tokens ?? 'unknown'})`,
|
|
147
|
-
);
|
|
148
|
-
}
|
|
149
|
-
return {
|
|
150
|
-
content,
|
|
151
|
-
tool_calls: toolCalls,
|
|
152
|
-
message: msg,
|
|
153
|
-
usage: res.usage,
|
|
154
|
-
};
|
|
155
|
-
} catch (error) {
|
|
156
|
-
const err = error as Error & { status?: number; code?: string };
|
|
157
|
-
runtimeLog.error('OpenAIAdapter', `LLM API call failed: ${err.message}`, {
|
|
158
|
-
model: this.model,
|
|
159
|
-
error: err.message,
|
|
160
|
-
status: err.status || 'unknown',
|
|
161
|
-
code: err.code || 'unknown',
|
|
162
|
-
});
|
|
163
|
-
throw error;
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
async chatMessagesStream(
|
|
168
|
-
messages: OpenAI.Chat.ChatCompletionMessageParam[],
|
|
169
|
-
onChunk: (text: string) => void,
|
|
170
|
-
): Promise<{ text: string; usage: OpenAI.CompletionUsage | undefined }> {
|
|
171
|
-
const stream = await this.client.chat.completions.create({
|
|
172
|
-
model: this.model,
|
|
173
|
-
messages,
|
|
174
|
-
stream: true,
|
|
175
|
-
// Without this, a streamed completion never returns a usage block — the
|
|
176
|
-
// streamed reply (often the largest output) would bill tokens that are
|
|
177
|
-
// counted nowhere (ZIG-813). The usage arrives on a final chunk whose
|
|
178
|
-
// `choices` is empty.
|
|
179
|
-
stream_options: { include_usage: true },
|
|
180
|
-
max_completion_tokens: maxCompletionTokensForModel(this.model),
|
|
181
|
-
});
|
|
182
|
-
let text = '';
|
|
183
|
-
let usage: OpenAI.CompletionUsage | undefined;
|
|
184
|
-
for await (const chunk of stream) {
|
|
185
|
-
if (chunk.usage) usage = chunk.usage;
|
|
186
|
-
const delta = chunk.choices[0]?.delta?.content;
|
|
187
|
-
if (delta) {
|
|
188
|
-
text += delta;
|
|
189
|
-
onChunk(delta);
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
return { text, usage };
|
|
193
|
-
}
|
|
194
|
-
}
|
package/src/agent/Agent.ts
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
import type { Ctx, Identity, Workflow, EffectHandler } from '../types.js';
|
|
2
|
-
import { AgentMachine, type TransitionEvent } from '../runtime/AgentMachine.js';
|
|
3
|
-
import { runTurn } from '../runtime/runTurn.js';
|
|
4
|
-
import { PromptBuilder } from '../runtime/PromptBuilder.js';
|
|
5
|
-
import type { MemoryStore } from '../memory/MemoryStore.js';
|
|
6
|
-
import type { ToolManager } from '../tools/ToolManager.js';
|
|
7
|
-
import type { RawEvent } from '../runtime/buildOutcome.js';
|
|
8
|
-
|
|
9
|
-
export interface AgentOptions {
|
|
10
|
-
workflow: Workflow;
|
|
11
|
-
toolManager: ToolManager;
|
|
12
|
-
promptBuilder?: PromptBuilder;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export interface TickInput {
|
|
16
|
-
/** Wire event (already normalized: a `message` or `task_result`-style envelope). */
|
|
17
|
-
event: unknown;
|
|
18
|
-
/** Server-provided per-session state. Omit on the first tick — a fresh ctx is constructed. */
|
|
19
|
-
ctx?: Ctx;
|
|
20
|
-
/** Server-provided workflow state name. Omit on the first tick — defaults to `workflow.initial`. */
|
|
21
|
-
state?: string;
|
|
22
|
-
/** Who am I and what session am I running in. The Agent carries this through Ctx. */
|
|
23
|
-
identity: Identity;
|
|
24
|
-
/** The single side channel for I/O — LLM, context, tools, send, record. */
|
|
25
|
-
eff: EffectHandler;
|
|
26
|
-
/**
|
|
27
|
-
* Agent-private long-term memory. Operator-provided (default
|
|
28
|
-
* `InMemoryStore` when omitted by `AgentHost`). Key shape is the agent's
|
|
29
|
-
* choice — `counterparty:<id>`, `agreement:<id>:notes`, etc.
|
|
30
|
-
*/
|
|
31
|
-
memory?: MemoryStore;
|
|
32
|
-
/** Optional tap for FSM transition events (ZIG-442). */
|
|
33
|
-
transitionTap?: (event: TransitionEvent) => void;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export interface TickOutput {
|
|
37
|
-
/** Updated ctx — Server persists this against the session. */
|
|
38
|
-
ctx: Ctx;
|
|
39
|
-
/** Workflow state name after the tick — Server persists this against the session. */
|
|
40
|
-
state: string;
|
|
41
|
-
/** Whether the machine settled at a parked state. */
|
|
42
|
-
parked: boolean;
|
|
43
|
-
/** True when a state-timeout outcome matched no transition this tick — the host must NOT re-arm. */
|
|
44
|
-
stateTimeoutUnhandled: boolean;
|
|
45
|
-
/**
|
|
46
|
-
* Accumulated LLM call count and token usage for this tick.
|
|
47
|
-
* `cacheRead` / `cacheCreation` are populated by the Claude brain (its usage
|
|
48
|
-
* exposes cache traffic, which is the bulk of real cost — ZIG-759/813); the
|
|
49
|
-
* FSM path leaves them undefined. `total` includes cache tokens when present.
|
|
50
|
-
*/
|
|
51
|
-
metrics: {
|
|
52
|
-
llmCalls: number;
|
|
53
|
-
tokens: { total: number; input: number; output: number; cacheRead?: number; cacheCreation?: number };
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Pure agent: workflow definition + cognition machinery. No I/O, no transport,
|
|
59
|
-
* no services. The Agent's only side channel is the `eff` handler it receives
|
|
60
|
-
* on each `tick`. Server-side state (sessions, lanes, queue, outbox) lives in
|
|
61
|
-
* `AgentHost` — not here.
|
|
62
|
-
*
|
|
63
|
-
* The contract:
|
|
64
|
-
*
|
|
65
|
-
* `tick({ event, ctx, state, identity, eff })` →
|
|
66
|
-
* `{ ctx, state, parked }`
|
|
67
|
-
*
|
|
68
|
-
* Reads top-to-bottom like a synchronous function. Every `await eff(...)`
|
|
69
|
-
* inside the cognition core is a yield to the Server, which performs the
|
|
70
|
-
* impure operation and resumes the Agent with the result.
|
|
71
|
-
*/
|
|
72
|
-
export class Agent {
|
|
73
|
-
workflow: Workflow;
|
|
74
|
-
toolManager: ToolManager;
|
|
75
|
-
promptBuilder: PromptBuilder;
|
|
76
|
-
|
|
77
|
-
constructor({ workflow, toolManager, promptBuilder }: AgentOptions) {
|
|
78
|
-
if (!workflow?.states) throw new Error('Agent: workflow with states is required');
|
|
79
|
-
if (!toolManager) throw new Error('Agent: toolManager is required');
|
|
80
|
-
this.workflow = workflow;
|
|
81
|
-
this.toolManager = toolManager;
|
|
82
|
-
this.promptBuilder = promptBuilder || new PromptBuilder();
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
async tick({ event, ctx, state, identity, eff, memory, transitionTap }: TickInput): Promise<TickOutput> {
|
|
86
|
-
if (!identity?.sessionId) throw new Error('Agent.tick: identity.sessionId is required');
|
|
87
|
-
if (!eff) throw new Error('Agent.tick: eff is required');
|
|
88
|
-
|
|
89
|
-
const machine = new AgentMachine({
|
|
90
|
-
workflow: this.workflow,
|
|
91
|
-
executionCore: runTurn,
|
|
92
|
-
eff,
|
|
93
|
-
toolManager: this.toolManager,
|
|
94
|
-
promptBuilder: this.promptBuilder,
|
|
95
|
-
memory,
|
|
96
|
-
input: { identity, ctx, state },
|
|
97
|
-
transitionTap,
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
// `send` awaits the recursive _step until the machine settles at a
|
|
101
|
-
// parked state (or stops). When it returns, we have the final state.
|
|
102
|
-
await machine.send({ event: event as RawEvent | undefined, identity });
|
|
103
|
-
|
|
104
|
-
return {
|
|
105
|
-
ctx: machine.ctx,
|
|
106
|
-
state: machine.state,
|
|
107
|
-
parked: machine.isParked,
|
|
108
|
-
stateTimeoutUnhandled: machine.stateTimeoutUnhandled,
|
|
109
|
-
metrics: { llmCalls: machine.llmCalls, tokens: machine.tokens },
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
}
|