@ptkl/toolkit 1.3.0 → 1.4.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/README.md +37 -30
- package/dist/bin/toolkit.js +37 -3
- package/dist/commands/__tests__/apiUsers.test.js +16 -0
- package/dist/commands/__tests__/forge-requires.test.js +58 -0
- package/dist/commands/__tests__/profile.test.js +65 -0
- package/dist/commands/apiUsers.js +12 -0
- package/dist/commands/forge.js +82 -6
- package/dist/commands/profile.js +84 -76
- package/dist/lib/kortex/__tests__/fixtures/providers/conformance.test.js +120 -0
- package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +172 -0
- package/dist/lib/kortex/__tests__/legacy-compatibility.test.js +273 -0
- package/dist/lib/kortex/__tests__/phase-1-conversion.test.js +154 -0
- package/dist/lib/kortex/__tests__/phase-2-runtime.test.js +100 -0
- package/dist/lib/kortex/__tests__/phase-3-provider.test.js +48 -0
- package/dist/lib/kortex/config/loader.js +129 -0
- package/dist/lib/kortex/config/schema.js +60 -0
- package/dist/lib/kortex/controller.js +60 -0
- package/dist/lib/kortex/conversation/legacy-conversion.js +141 -0
- package/dist/lib/kortex/conversation/types.js +13 -0
- package/dist/lib/kortex/events/index.js +1 -0
- package/dist/lib/kortex/events/reducer.js +86 -0
- package/dist/lib/kortex/events/types.js +7 -0
- package/dist/lib/kortex/events/writer.js +76 -0
- package/dist/lib/kortex/mcp/index.js +1 -0
- package/dist/lib/kortex/orchestration/index.js +1 -0
- package/dist/lib/kortex/orchestration/manager-worker.js +88 -0
- package/dist/lib/kortex/orchestration/peer-collaboration.js +59 -0
- package/dist/lib/kortex/orchestration/plan.js +133 -0
- package/dist/lib/kortex/orchestration/scheduler.js +124 -0
- package/dist/lib/kortex/persistence/index.js +1 -0
- package/dist/lib/kortex/persistence/run-journal.js +94 -0
- package/dist/lib/kortex/providers/anthropic.js +34 -0
- package/dist/lib/kortex/providers/index.js +1 -0
- package/dist/lib/kortex/providers/openai-compatible.js +190 -0
- package/dist/lib/kortex/providers/protokol.js +204 -0
- package/dist/lib/kortex/providers/registry.js +61 -0
- package/dist/lib/kortex/providers/types.js +13 -0
- package/dist/lib/kortex/runtime/agent-runner.js +241 -0
- package/dist/lib/kortex/runtime/approval-queue.js +95 -0
- package/dist/lib/kortex/runtime/budget-controller.js +105 -0
- package/dist/lib/kortex/runtime/index.js +1 -0
- package/dist/lib/kortex/runtime/tool-runtime.js +66 -0
- package/dist/lib/kortex/runtime/workspace.js +52 -0
- package/dist/lib/kortex/tools/index.js +1 -0
- package/dist/lib/kortex/tools.js +226 -34
- package/dist/lib/kortex/types.js +7 -0
- package/dist/lib/kortex/ui/index.js +1 -0
- package/dist/lib/oauth/CallbackPages.js +82 -0
- package/dist/lib/oauth/CallbackServer.js +84 -0
- package/dist/lib/oauth/OAuthClient.js +81 -0
- package/dist/lib/oauth/OAuthError.js +17 -0
- package/dist/lib/oauth/OAuthLogin.js +60 -0
- package/dist/lib/oauth/OAuthSession.js +100 -0
- package/dist/lib/oauth/Pkce.js +19 -0
- package/dist/lib/oauth/ProfileLogin.js +76 -0
- package/dist/lib/oauth/RefreshLock.js +61 -0
- package/dist/lib/oauth/ScopePreset.js +38 -0
- package/dist/lib/oauth/__tests__/mockServer.js +29 -0
- package/dist/lib/oauth/__tests__/oauth.test.js +347 -0
- package/dist/lib/util.js +9 -2
- package/package.json +6 -4
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Protokol adapter — wraps the platform's /luma/kortex/v1/chat SSE endpoint
|
|
3
|
+
* as a ProviderAdapter.
|
|
4
|
+
*
|
|
5
|
+
* This is the first adapter implemented because it:
|
|
6
|
+
* 1. Uses the existing, tested endpoint.
|
|
7
|
+
* 2. Proves the ProviderAdapter abstraction without adding a dependency on
|
|
8
|
+
* an external provider SDK.
|
|
9
|
+
* 3. Provides the backward compatibility path for existing single-agent users.
|
|
10
|
+
*
|
|
11
|
+
* The endpoint is stateless: the client sends the full message history
|
|
12
|
+
* and receives SSE events back. Tool calls from the model are returned
|
|
13
|
+
* in the message_complete event.
|
|
14
|
+
*/
|
|
15
|
+
import axios from 'axios';
|
|
16
|
+
export class ProtokolAdapter {
|
|
17
|
+
id = 'protokol';
|
|
18
|
+
family = 'protokol';
|
|
19
|
+
client;
|
|
20
|
+
constructor(opts) {
|
|
21
|
+
this.client = axios.create({
|
|
22
|
+
baseURL: opts.host,
|
|
23
|
+
timeout: 180_000,
|
|
24
|
+
headers: {
|
|
25
|
+
Authorization: `Bearer ${opts.token}`,
|
|
26
|
+
'Content-Type': 'application/json',
|
|
27
|
+
'X-Agent-Context': 'cli',
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
async resolveCapabilities(_target) {
|
|
32
|
+
return {
|
|
33
|
+
streaming: true,
|
|
34
|
+
toolUse: true,
|
|
35
|
+
structuredOutput: false,
|
|
36
|
+
parallelToolCalls: true,
|
|
37
|
+
tokenCounting: 'usage-only',
|
|
38
|
+
supportsAbort: true,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
async *stream(request, signal) {
|
|
42
|
+
// Convert canonical Turns to the format expected by the Protokol endpoint
|
|
43
|
+
const messages = this.turnsToProtokolMessages(request.turns);
|
|
44
|
+
const agentUUID = request.target.type === 'provider_agent'
|
|
45
|
+
? request.target.id
|
|
46
|
+
: 'protokol-bot';
|
|
47
|
+
try {
|
|
48
|
+
const response = await this.client.post('/luma/kortex/v1/chat', {
|
|
49
|
+
agent_uuid: agentUUID,
|
|
50
|
+
messages,
|
|
51
|
+
tools: request.tools,
|
|
52
|
+
}, {
|
|
53
|
+
responseType: 'stream',
|
|
54
|
+
signal,
|
|
55
|
+
});
|
|
56
|
+
const stream = response.data;
|
|
57
|
+
yield* this.parseSSEStream(stream);
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
if (axios.isCancel(err) || err.name === 'CanceledError' || signal.aborted) {
|
|
61
|
+
return; // clean cancellation — no error event
|
|
62
|
+
}
|
|
63
|
+
const providerError = {
|
|
64
|
+
kind: err.response?.status === 429 ? 'rate_limit'
|
|
65
|
+
: err.response?.status === 401 ? 'auth'
|
|
66
|
+
: err.response?.status === 403 ? 'auth'
|
|
67
|
+
: err.code === 'ECONNABORTED' ? 'timeout'
|
|
68
|
+
: err.code === 'ERR_NETWORK' ? 'network'
|
|
69
|
+
: 'internal',
|
|
70
|
+
message: err.response?.data?.message || err.message || 'Unknown Protokol error',
|
|
71
|
+
retryable: err.response?.status ? err.response.status >= 500 : true,
|
|
72
|
+
retryAfterMs: err.response?.headers?.['retry-after']
|
|
73
|
+
? parseInt(err.response.headers['retry-after']) * 1000
|
|
74
|
+
: undefined,
|
|
75
|
+
};
|
|
76
|
+
yield { type: 'error', error: providerError };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// ── Internal helpers ──
|
|
80
|
+
turnsToProtokolMessages(turns) {
|
|
81
|
+
const messages = [];
|
|
82
|
+
for (const turn of turns) {
|
|
83
|
+
const textBlocks = turn.blocks.filter((b) => b.type === 'text');
|
|
84
|
+
const text = textBlocks.map(b => b.text).join('\n');
|
|
85
|
+
const toolCallBlocks = turn.blocks.filter((b) => b.type === 'tool_call');
|
|
86
|
+
const toolResultBlocks = turn.blocks.filter((b) => b.type === 'tool_result');
|
|
87
|
+
if (turn.role === 'tool') {
|
|
88
|
+
for (const tr of toolResultBlocks) {
|
|
89
|
+
messages.push({
|
|
90
|
+
role: 'tool',
|
|
91
|
+
content: tr.output.text,
|
|
92
|
+
tool_call_id: tr.callId,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
else if (toolCallBlocks.length > 0) {
|
|
97
|
+
messages.push({
|
|
98
|
+
role: 'assistant',
|
|
99
|
+
content: text,
|
|
100
|
+
tool_calls: toolCallBlocks.map(tc => ({
|
|
101
|
+
id: tc.id,
|
|
102
|
+
type: 'function',
|
|
103
|
+
function: { name: tc.name, arguments: JSON.stringify(tc.arguments) },
|
|
104
|
+
})),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
else if (turn.role === 'system') {
|
|
108
|
+
messages.push({ role: 'context', content: text || turn.id });
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
messages.push({
|
|
112
|
+
role: turn.role === 'assistant' ? 'assistant' : 'user',
|
|
113
|
+
content: text,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return messages;
|
|
118
|
+
}
|
|
119
|
+
async *parseSSEStream(stream) {
|
|
120
|
+
let buffer = '';
|
|
121
|
+
for await (const chunk of stream) {
|
|
122
|
+
buffer += chunk.toString();
|
|
123
|
+
const parts = buffer.split('\n\n');
|
|
124
|
+
buffer = parts.pop() || '';
|
|
125
|
+
for (const part of parts) {
|
|
126
|
+
const lines = part.split('\n');
|
|
127
|
+
let eventType = '';
|
|
128
|
+
let data = '';
|
|
129
|
+
for (const line of lines) {
|
|
130
|
+
if (line.startsWith('event: '))
|
|
131
|
+
eventType = line.slice(7);
|
|
132
|
+
else if (line.startsWith('data: '))
|
|
133
|
+
data = line.slice(6);
|
|
134
|
+
}
|
|
135
|
+
if (!eventType || !data)
|
|
136
|
+
continue;
|
|
137
|
+
try {
|
|
138
|
+
const parsed = JSON.parse(data);
|
|
139
|
+
switch (eventType) {
|
|
140
|
+
case 'content_delta': {
|
|
141
|
+
if (parsed.delta)
|
|
142
|
+
yield { type: 'text', delta: parsed.delta };
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
case 'thinking_delta': {
|
|
146
|
+
if (parsed.delta)
|
|
147
|
+
yield { type: 'reasoning_summary', text: parsed.delta };
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
case 'message_start': {
|
|
151
|
+
// Used for agent attribution — can be captured as metadata
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
case 'message_complete': {
|
|
155
|
+
const toolCalls = parsed.tool_calls?.map((tc) => ({
|
|
156
|
+
id: tc.id,
|
|
157
|
+
name: tc.function?.name ?? 'unknown',
|
|
158
|
+
arguments: tc.function?.arguments ?? '{}',
|
|
159
|
+
}));
|
|
160
|
+
if (toolCalls && toolCalls.length > 0) {
|
|
161
|
+
// Emit tool call events for each call
|
|
162
|
+
for (const tc of toolCalls) {
|
|
163
|
+
yield { type: 'tool_call_start', id: tc.id, name: tc.name };
|
|
164
|
+
yield { type: 'tool_call_delta', id: tc.id, delta: tc.arguments };
|
|
165
|
+
yield { type: 'tool_call_end', id: tc.id, name: tc.name, arguments: tc.arguments };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
yield {
|
|
169
|
+
type: 'completed',
|
|
170
|
+
stopReason: toolCalls?.length ? 'tool_call' : 'end_turn',
|
|
171
|
+
toolCalls,
|
|
172
|
+
};
|
|
173
|
+
if (parsed.token_usage) {
|
|
174
|
+
yield {
|
|
175
|
+
type: 'usage',
|
|
176
|
+
usage: {
|
|
177
|
+
inputTokens: parsed.token_usage.prompt_tokens,
|
|
178
|
+
outputTokens: parsed.token_usage.completion_tokens,
|
|
179
|
+
estimated: false,
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
case 'error': {
|
|
186
|
+
yield {
|
|
187
|
+
type: 'error',
|
|
188
|
+
error: {
|
|
189
|
+
kind: 'internal',
|
|
190
|
+
message: parsed.error || 'Unknown Protokol error',
|
|
191
|
+
retryable: false,
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
// Malformed event — skip
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ProviderRegistry — loads configured providers, instantiates adapters, resolves capabilities.
|
|
3
|
+
*
|
|
4
|
+
* Phase 2: supports Protokol adapter only. Extended in Phase 3+ with direct adapters.
|
|
5
|
+
*/
|
|
6
|
+
export class ProviderRegistry {
|
|
7
|
+
adapters = new Map();
|
|
8
|
+
capabilityCache = new Map();
|
|
9
|
+
/**
|
|
10
|
+
* Register an adapter at runtime (used by tests and factory methods).
|
|
11
|
+
*/
|
|
12
|
+
register(adapter) {
|
|
13
|
+
this.adapters.set(adapter.id, adapter);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Get a registered adapter by its ID.
|
|
17
|
+
*/
|
|
18
|
+
get(id) {
|
|
19
|
+
const adapter = this.adapters.get(id);
|
|
20
|
+
if (!adapter)
|
|
21
|
+
throw new Error(`Unknown provider adapter: "${id}"`);
|
|
22
|
+
return adapter;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Get a provider for a specific target (model or provider_agent).
|
|
26
|
+
* Resolves the provider ID from the target's context if needed.
|
|
27
|
+
*/
|
|
28
|
+
getForTarget(target, agentProvider) {
|
|
29
|
+
const providerId = agentProvider ?? 'protokol';
|
|
30
|
+
return this.get(providerId);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Resolve and cache capabilities for a specific target via its adapter.
|
|
34
|
+
*/
|
|
35
|
+
async resolveCapabilities(target, agentProvider) {
|
|
36
|
+
const providerId = agentProvider ?? 'protokol';
|
|
37
|
+
const key = `${providerId}::${target.type === 'model' ? target.model : target.id}`;
|
|
38
|
+
const cached = this.capabilityCache.get(key);
|
|
39
|
+
if (cached)
|
|
40
|
+
return cached;
|
|
41
|
+
const adapter = this.get(providerId);
|
|
42
|
+
const caps = await adapter.resolveCapabilities(target);
|
|
43
|
+
this.capabilityCache.set(key, caps);
|
|
44
|
+
return caps;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* List all registered adapter IDs.
|
|
48
|
+
*/
|
|
49
|
+
list() {
|
|
50
|
+
return Array.from(this.adapters.keys());
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Default registry with the Protokol adapter pre-registered.
|
|
55
|
+
*/
|
|
56
|
+
export function createDefaultRegistry() {
|
|
57
|
+
const registry = new ProviderRegistry();
|
|
58
|
+
// ProtokolAdapter is registered lazily or imported — for now
|
|
59
|
+
// tests and the CLI inject it manually.
|
|
60
|
+
return registry;
|
|
61
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ProviderAdapter interface — the contract between AgentRunner and any LLM provider.
|
|
3
|
+
*
|
|
4
|
+
* Each adapter wraps one provider family (Anthropic, OpenAI, Google, etc.) or
|
|
5
|
+
* a specific endpoint (Protokol backend, OpenRouter, etc.).
|
|
6
|
+
*
|
|
7
|
+
* Design rules:
|
|
8
|
+
* - Raw SDK types never escape the adapter.
|
|
9
|
+
* - Model specification uses a discriminated union (model name vs. provider-managed agent).
|
|
10
|
+
* - Errors normalize to the ProviderError taxonomy.
|
|
11
|
+
* - Capabilities are resolved per model/target, not per provider family.
|
|
12
|
+
*/
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgentRunner — runs a single agent through a provider-agnostic tool loop.
|
|
3
|
+
*
|
|
4
|
+
* Replaces the existing sendAndProcess + executeToolLoop pattern from session.ts
|
|
5
|
+
* with a clean, provider-agnostic implementation.
|
|
6
|
+
*
|
|
7
|
+
* Flow:
|
|
8
|
+
* 1. Build provider input from task + bounded context
|
|
9
|
+
* 2. Stream one model call
|
|
10
|
+
* 3. Validate and execute tool calls through ToolRuntime
|
|
11
|
+
* 4. Append results using provider-correct semantics
|
|
12
|
+
* 5. Repeat until terminal output or a limit is reached
|
|
13
|
+
* 6. Emit structured worker summary and artifact references
|
|
14
|
+
*/
|
|
15
|
+
import { randomUUID } from 'node:crypto';
|
|
16
|
+
export class AgentRunner {
|
|
17
|
+
toolRuntime;
|
|
18
|
+
approvalQueue;
|
|
19
|
+
budgetController;
|
|
20
|
+
constructor(toolRuntime, approvalQueue, budgetController) {
|
|
21
|
+
this.toolRuntime = toolRuntime;
|
|
22
|
+
this.approvalQueue = approvalQueue;
|
|
23
|
+
this.budgetController = budgetController;
|
|
24
|
+
}
|
|
25
|
+
async run(request, provider) {
|
|
26
|
+
const { runId, task, attempt, agent, context, budgets, signal } = request;
|
|
27
|
+
const turns = this.buildInitialTurns(agent, context, task);
|
|
28
|
+
let round = 0;
|
|
29
|
+
const maxRounds = agent.limits?.maxModelCalls ?? 25;
|
|
30
|
+
const observedChanges = [];
|
|
31
|
+
const toolCallSummaries = [];
|
|
32
|
+
let totalUsage = { estimated: false };
|
|
33
|
+
let finalText = '';
|
|
34
|
+
let finalToolCalls = [];
|
|
35
|
+
while (round < maxRounds) {
|
|
36
|
+
round++;
|
|
37
|
+
if (signal.aborted) {
|
|
38
|
+
return {
|
|
39
|
+
status: 'cancelled',
|
|
40
|
+
summary: 'Run was cancelled by user',
|
|
41
|
+
transcriptRef: runId,
|
|
42
|
+
artifacts: [],
|
|
43
|
+
usage: totalUsage,
|
|
44
|
+
toolCalls: toolCallSummaries,
|
|
45
|
+
observedChanges,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
// Check budgets
|
|
49
|
+
if (this.budgetController.isExceeded()) {
|
|
50
|
+
return {
|
|
51
|
+
status: 'budget_exceeded',
|
|
52
|
+
summary: `Budget exceeded after ${round} rounds`,
|
|
53
|
+
transcriptRef: runId,
|
|
54
|
+
artifacts: [],
|
|
55
|
+
usage: totalUsage,
|
|
56
|
+
toolCalls: toolCallSummaries,
|
|
57
|
+
observedChanges,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
const modelRequest = {
|
|
61
|
+
target: agent.target,
|
|
62
|
+
instructions: agent.instructions,
|
|
63
|
+
turns,
|
|
64
|
+
tools: agent.tools,
|
|
65
|
+
limits: { maxOutputTokens: agent.limits?.maxOutputTokensPerCall ?? 4096 },
|
|
66
|
+
};
|
|
67
|
+
// Stream model response
|
|
68
|
+
const stream = provider.stream(modelRequest, signal);
|
|
69
|
+
const { content, toolCalls, usage } = await this.processStream(stream, signal);
|
|
70
|
+
totalUsage = {
|
|
71
|
+
inputTokens: (totalUsage.inputTokens ?? 0) + (usage.inputTokens ?? 0),
|
|
72
|
+
outputTokens: (totalUsage.outputTokens ?? 0) + (usage.outputTokens ?? 0),
|
|
73
|
+
estimated: totalUsage.estimated || usage.estimated,
|
|
74
|
+
};
|
|
75
|
+
// Track usage
|
|
76
|
+
try {
|
|
77
|
+
this.budgetController.recordUsage(usage);
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
return {
|
|
81
|
+
status: 'budget_exceeded',
|
|
82
|
+
summary: e.message,
|
|
83
|
+
transcriptRef: runId,
|
|
84
|
+
artifacts: [],
|
|
85
|
+
usage: totalUsage,
|
|
86
|
+
toolCalls: toolCallSummaries,
|
|
87
|
+
observedChanges,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
if (content) {
|
|
91
|
+
finalText = content;
|
|
92
|
+
}
|
|
93
|
+
if (!toolCalls || toolCalls.length === 0) {
|
|
94
|
+
break; // No more tool calls — conversation is complete
|
|
95
|
+
}
|
|
96
|
+
// Execute tool calls
|
|
97
|
+
for (const tc of toolCalls) {
|
|
98
|
+
const call = {
|
|
99
|
+
id: tc.id,
|
|
100
|
+
name: tc.name,
|
|
101
|
+
arguments: this.parseArguments(tc.arguments),
|
|
102
|
+
};
|
|
103
|
+
// Approve (Phase 4+: wire through ApprovalQueue)
|
|
104
|
+
// For Phase 2, auto-approve all tool calls
|
|
105
|
+
const approved = true;
|
|
106
|
+
if (!approved) {
|
|
107
|
+
toolCallSummaries.push({
|
|
108
|
+
id: tc.id, name: tc.name, risk: 'execute',
|
|
109
|
+
approved: false, durationMs: 0, truncated: false,
|
|
110
|
+
});
|
|
111
|
+
turns.push(this.buildToolErrorTurn(call, 'User denied permission'));
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const startTime = Date.now();
|
|
115
|
+
const result = await this.toolRuntime.execute({ runId, taskId: task.id, attempt, agent: agent.name, workspace: request.workspace, policy: { allowedTools: ['*'], riskCeiling: 'execute', requiresApproval: false, approvalScope: 'once' }, signal }, call);
|
|
116
|
+
const durationMs = Date.now() - startTime;
|
|
117
|
+
try {
|
|
118
|
+
this.budgetController.recordToolCall();
|
|
119
|
+
}
|
|
120
|
+
catch (e) {
|
|
121
|
+
return {
|
|
122
|
+
status: 'budget_exceeded',
|
|
123
|
+
summary: e.message,
|
|
124
|
+
transcriptRef: runId,
|
|
125
|
+
artifacts: [],
|
|
126
|
+
usage: totalUsage,
|
|
127
|
+
toolCalls: toolCallSummaries,
|
|
128
|
+
observedChanges,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
toolCallSummaries.push({
|
|
132
|
+
id: tc.id, name: tc.name, risk: 'execute',
|
|
133
|
+
approved: true, durationMs, truncated: result.content.length > 100_000,
|
|
134
|
+
});
|
|
135
|
+
turns.push({
|
|
136
|
+
id: randomUUID(),
|
|
137
|
+
role: 'tool',
|
|
138
|
+
createdAt: new Date().toISOString(),
|
|
139
|
+
blocks: [{
|
|
140
|
+
type: 'tool_result',
|
|
141
|
+
callId: call.id,
|
|
142
|
+
name: call.name,
|
|
143
|
+
output: { text: result.content, truncated: result.content.length > 100_000 },
|
|
144
|
+
isError: result.content.startsWith('Error:'),
|
|
145
|
+
}],
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return {
|
|
150
|
+
status: round >= maxRounds ? 'failed' : 'succeeded',
|
|
151
|
+
summary: finalText.slice(0, 500),
|
|
152
|
+
transcriptRef: runId,
|
|
153
|
+
artifacts: [],
|
|
154
|
+
usage: totalUsage,
|
|
155
|
+
toolCalls: toolCallSummaries,
|
|
156
|
+
observedChanges,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
buildInitialTurns(agent, context, task) {
|
|
160
|
+
const turns = [];
|
|
161
|
+
// System instruction through context/summaries
|
|
162
|
+
if (context.dependencySummaries.length > 0) {
|
|
163
|
+
const summaryText = context.dependencySummaries.map(d => `[Dependency: ${d.title}] Status: ${d.status}${d.summary ? `\n${d.summary}` : ''}`).join('\n\n');
|
|
164
|
+
turns.push({
|
|
165
|
+
id: randomUUID(),
|
|
166
|
+
role: 'system',
|
|
167
|
+
createdAt: new Date().toISOString(),
|
|
168
|
+
blocks: [{ type: 'text', text: `Previous work:\n${summaryText}` }],
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
// Task prompt
|
|
172
|
+
turns.push({
|
|
173
|
+
id: randomUUID(),
|
|
174
|
+
role: 'user',
|
|
175
|
+
createdAt: new Date().toISOString(),
|
|
176
|
+
blocks: [{ type: 'text', text: task.prompt }],
|
|
177
|
+
});
|
|
178
|
+
return turns;
|
|
179
|
+
}
|
|
180
|
+
async processStream(stream, signal) {
|
|
181
|
+
let content = '';
|
|
182
|
+
const toolCalls = [];
|
|
183
|
+
let usage = { estimated: false };
|
|
184
|
+
let currentToolCall = null;
|
|
185
|
+
for await (const event of stream) {
|
|
186
|
+
if (signal.aborted)
|
|
187
|
+
break;
|
|
188
|
+
switch (event.type) {
|
|
189
|
+
case 'text':
|
|
190
|
+
content += event.delta;
|
|
191
|
+
break;
|
|
192
|
+
case 'tool_call_start':
|
|
193
|
+
currentToolCall = { id: event.id, name: event.name, arguments: '' };
|
|
194
|
+
break;
|
|
195
|
+
case 'tool_call_delta':
|
|
196
|
+
if (currentToolCall)
|
|
197
|
+
currentToolCall.arguments = (currentToolCall.arguments ?? '') + event.delta;
|
|
198
|
+
break;
|
|
199
|
+
case 'tool_call_end':
|
|
200
|
+
if (currentToolCall) {
|
|
201
|
+
toolCalls.push({
|
|
202
|
+
id: currentToolCall.id ?? event.id,
|
|
203
|
+
name: currentToolCall.name ?? event.name,
|
|
204
|
+
arguments: currentToolCall.arguments ?? event.arguments,
|
|
205
|
+
});
|
|
206
|
+
currentToolCall = null;
|
|
207
|
+
}
|
|
208
|
+
break;
|
|
209
|
+
case 'usage':
|
|
210
|
+
usage = event.usage;
|
|
211
|
+
break;
|
|
212
|
+
case 'error':
|
|
213
|
+
// Error handled upstream; break out
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return { content, toolCalls, usage };
|
|
218
|
+
}
|
|
219
|
+
parseArguments(raw) {
|
|
220
|
+
try {
|
|
221
|
+
return JSON.parse(raw);
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
return { _raw: raw };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
buildToolErrorTurn(call, message) {
|
|
228
|
+
return {
|
|
229
|
+
id: randomUUID(),
|
|
230
|
+
role: 'tool',
|
|
231
|
+
createdAt: new Date().toISOString(),
|
|
232
|
+
blocks: [{
|
|
233
|
+
type: 'tool_result',
|
|
234
|
+
callId: call.id,
|
|
235
|
+
name: call.name,
|
|
236
|
+
output: { text: `Error: ${message}`, truncated: false },
|
|
237
|
+
isError: true,
|
|
238
|
+
}],
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ApprovalQueue — serializes consent requests from concurrent agents.
|
|
3
|
+
*
|
|
4
|
+
* Each request is tagged with run/task/agent/call IDs so the UI can
|
|
5
|
+
* attribute decisions correctly. Decisions are scoped: 'once' (single call),
|
|
6
|
+
* 'task' (all matching calls within this task), or 'run' (all matching
|
|
7
|
+
* calls for the entire run).
|
|
8
|
+
*/
|
|
9
|
+
export class ApprovalQueue {
|
|
10
|
+
queue = [];
|
|
11
|
+
decisions = new Map();
|
|
12
|
+
scopedDecisions = [];
|
|
13
|
+
resolveCurrent = null;
|
|
14
|
+
pendingRequestId = null;
|
|
15
|
+
/**
|
|
16
|
+
* Request consent for a tool call. Resolves when the user or policy decides.
|
|
17
|
+
*/
|
|
18
|
+
async requestConsent(runId, taskId, attempt, agent, call, risk, summary) {
|
|
19
|
+
// Check scoped decisions first
|
|
20
|
+
const scoped = this.findScopedDecision(taskId, call.name);
|
|
21
|
+
if (scoped)
|
|
22
|
+
return scoped;
|
|
23
|
+
const request = {
|
|
24
|
+
id: `${runId}::${taskId}::${call.id}`,
|
|
25
|
+
runId,
|
|
26
|
+
taskId,
|
|
27
|
+
attempt,
|
|
28
|
+
agent,
|
|
29
|
+
callId: call.id,
|
|
30
|
+
toolName: call.name,
|
|
31
|
+
risk,
|
|
32
|
+
summary,
|
|
33
|
+
requestedAt: new Date().toISOString(),
|
|
34
|
+
};
|
|
35
|
+
this.queue.push(request);
|
|
36
|
+
return new Promise((resolve) => {
|
|
37
|
+
this.resolveCurrent = resolve;
|
|
38
|
+
this.pendingRequestId = request.id;
|
|
39
|
+
// Emit for UI to pick up
|
|
40
|
+
// Phase 4+: integrate with UIBridge event system
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Resolve the current pending consent request.
|
|
45
|
+
*/
|
|
46
|
+
resolvePending(decision) {
|
|
47
|
+
if (this.pendingRequestId) {
|
|
48
|
+
this.decisions.set(this.pendingRequestId, decision);
|
|
49
|
+
// Store scoped decision
|
|
50
|
+
if (decision.scope !== 'once') {
|
|
51
|
+
const req = this.queue.find(r => r.id === this.pendingRequestId);
|
|
52
|
+
this.scopedDecisions.push({
|
|
53
|
+
scope: decision.scope,
|
|
54
|
+
taskId: req?.taskId,
|
|
55
|
+
toolName: req?.toolName,
|
|
56
|
+
outcome: decision.outcome,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
const resolve = this.resolveCurrent;
|
|
60
|
+
this.resolveCurrent = null;
|
|
61
|
+
this.pendingRequestId = null;
|
|
62
|
+
resolve?.(decision);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Check for a previously scoped decision that covers this request.
|
|
67
|
+
*/
|
|
68
|
+
findScopedDecision(taskId, toolName) {
|
|
69
|
+
for (const sd of this.scopedDecisions) {
|
|
70
|
+
if (sd.outcome === 'denied')
|
|
71
|
+
continue;
|
|
72
|
+
if (sd.scope === 'run' && sd.toolName === toolName) {
|
|
73
|
+
return { requestId: 'scoped', outcome: 'approved', scope: 'run', decidedAt: new Date().toISOString() };
|
|
74
|
+
}
|
|
75
|
+
if (sd.scope === 'task' && sd.taskId === taskId && sd.toolName === toolName) {
|
|
76
|
+
return { requestId: 'scoped', outcome: 'approved', scope: 'task', decidedAt: new Date().toISOString() };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Get all pending consent requests (for UI rendering).
|
|
83
|
+
*/
|
|
84
|
+
get pending() {
|
|
85
|
+
return [...this.queue];
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Clear all pending requests (e.g., on run cancellation).
|
|
89
|
+
*/
|
|
90
|
+
clear() {
|
|
91
|
+
this.queue = [];
|
|
92
|
+
this.resolveCurrent = null;
|
|
93
|
+
this.pendingRequestId = null;
|
|
94
|
+
}
|
|
95
|
+
}
|