@ptkl/toolkit 1.3.0 → 1.3.2

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 (41) hide show
  1. package/dist/commands/forge.js +34 -6
  2. package/dist/lib/kortex/__tests__/fixtures/providers/conformance.test.js +120 -0
  3. package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +172 -0
  4. package/dist/lib/kortex/__tests__/legacy-compatibility.test.js +273 -0
  5. package/dist/lib/kortex/__tests__/phase-1-conversion.test.js +154 -0
  6. package/dist/lib/kortex/__tests__/phase-2-runtime.test.js +100 -0
  7. package/dist/lib/kortex/__tests__/phase-3-provider.test.js +48 -0
  8. package/dist/lib/kortex/config/loader.js +129 -0
  9. package/dist/lib/kortex/config/schema.js +60 -0
  10. package/dist/lib/kortex/controller.js +60 -0
  11. package/dist/lib/kortex/conversation/legacy-conversion.js +141 -0
  12. package/dist/lib/kortex/conversation/types.js +13 -0
  13. package/dist/lib/kortex/events/index.js +1 -0
  14. package/dist/lib/kortex/events/reducer.js +86 -0
  15. package/dist/lib/kortex/events/types.js +7 -0
  16. package/dist/lib/kortex/events/writer.js +76 -0
  17. package/dist/lib/kortex/mcp/index.js +1 -0
  18. package/dist/lib/kortex/orchestration/index.js +1 -0
  19. package/dist/lib/kortex/orchestration/manager-worker.js +88 -0
  20. package/dist/lib/kortex/orchestration/peer-collaboration.js +59 -0
  21. package/dist/lib/kortex/orchestration/plan.js +133 -0
  22. package/dist/lib/kortex/orchestration/scheduler.js +124 -0
  23. package/dist/lib/kortex/persistence/index.js +1 -0
  24. package/dist/lib/kortex/persistence/run-journal.js +94 -0
  25. package/dist/lib/kortex/providers/anthropic.js +34 -0
  26. package/dist/lib/kortex/providers/index.js +1 -0
  27. package/dist/lib/kortex/providers/openai-compatible.js +190 -0
  28. package/dist/lib/kortex/providers/protokol.js +204 -0
  29. package/dist/lib/kortex/providers/registry.js +61 -0
  30. package/dist/lib/kortex/providers/types.js +13 -0
  31. package/dist/lib/kortex/runtime/agent-runner.js +241 -0
  32. package/dist/lib/kortex/runtime/approval-queue.js +95 -0
  33. package/dist/lib/kortex/runtime/budget-controller.js +105 -0
  34. package/dist/lib/kortex/runtime/index.js +1 -0
  35. package/dist/lib/kortex/runtime/tool-runtime.js +66 -0
  36. package/dist/lib/kortex/runtime/workspace.js +52 -0
  37. package/dist/lib/kortex/tools/index.js +1 -0
  38. package/dist/lib/kortex/tools.js +226 -34
  39. package/dist/lib/kortex/types.js +7 -0
  40. package/dist/lib/kortex/ui/index.js +1 -0
  41. package/package.json +6 -4
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Scheduler — runs tasks respecting dependencies, concurrency limits,
3
+ * write lease, and failure policies.
4
+ *
5
+ * Uses a ready-set / in-flight / completed model with Promise.race
6
+ * waking the scheduling loop when any task completes.
7
+ */
8
+ export class Scheduler {
9
+ records = new Map();
10
+ inFlight = new Map();
11
+ writeLease = false;
12
+ cancelled = false;
13
+ maxConcurrency;
14
+ onTaskReady;
15
+ constructor(tasks, maxConcurrency, onTaskReady) {
16
+ this.maxConcurrency = maxConcurrency;
17
+ this.onTaskReady = onTaskReady;
18
+ for (const t of tasks) {
19
+ this.records.set(t.id, { task: t, status: 'pending', attempt: 1 });
20
+ }
21
+ }
22
+ /**
23
+ * Run the scheduler to completion. Returns final task records.
24
+ */
25
+ async run() {
26
+ while (!this.cancelled && this.getActiveCount() > 0) {
27
+ const ready = this.getReadyTasks();
28
+ if (ready.length === 0 && this.inFlight.size === 0)
29
+ break;
30
+ // Start ready tasks up to concurrency limit
31
+ for (const task of ready) {
32
+ if (this.inFlight.size >= this.maxConcurrency)
33
+ break;
34
+ if (this.cancelled)
35
+ break;
36
+ // Write lease
37
+ const needsWrite = task.mode === 'write';
38
+ if (needsWrite && this.writeLease)
39
+ continue;
40
+ if (needsWrite)
41
+ this.writeLease = true;
42
+ this.setStatus(task.id, 'running');
43
+ const promise = this.runTask(task).finally(() => {
44
+ this.inFlight.delete(task.id);
45
+ if (needsWrite)
46
+ this.writeLease = false;
47
+ });
48
+ this.inFlight.set(task.id, promise);
49
+ }
50
+ // Wait for at least one to complete before re-evaluating
51
+ if (this.inFlight.size > 0) {
52
+ await Promise.race(this.inFlight.values());
53
+ }
54
+ }
55
+ return this.records;
56
+ }
57
+ /**
58
+ * Cancel the scheduler.
59
+ */
60
+ cancel() {
61
+ this.cancelled = true;
62
+ }
63
+ async runTask(task) {
64
+ try {
65
+ const result = await this.onTaskReady(task);
66
+ this.setStatus(task.id, result);
67
+ }
68
+ catch (e) {
69
+ this.records.get(task.id).error = e.message;
70
+ this.setStatus(task.id, 'failed');
71
+ }
72
+ }
73
+ getReadyTasks() {
74
+ return Array.from(this.records.values())
75
+ .filter(r => r.status === 'pending' || r.status === 'queued')
76
+ .filter(r => this.dependenciesMet(r.task))
77
+ .sort((a, b) => (b.task.priority ?? 0) - (a.task.priority ?? 0))
78
+ .map(r => r.task);
79
+ }
80
+ dependenciesMet(task) {
81
+ return task.dependsOn.every(dep => {
82
+ const depRecord = this.records.get(dep.taskId);
83
+ if (!depRecord)
84
+ return false;
85
+ if (depRecord.status === 'succeeded')
86
+ return true;
87
+ if (dep.onFailure === 'continue' && (depRecord.status === 'failed' || depRecord.status === 'cancelled'))
88
+ return true;
89
+ if (depRecord.status === 'failed' || depRecord.status === 'cancelled') {
90
+ this.setStatus(task.id, 'blocked');
91
+ }
92
+ return false;
93
+ });
94
+ }
95
+ setStatus(taskId, status) {
96
+ const r = this.records.get(taskId);
97
+ if (!r)
98
+ return;
99
+ r.status = status;
100
+ if (status === 'running')
101
+ r.startedAt = Date.now();
102
+ if (['succeeded', 'failed', 'cancelled', 'budget_exceeded'].includes(status)) {
103
+ r.completedAt = Date.now();
104
+ }
105
+ // Propagate blocked status
106
+ if (status === 'failed' || status === 'cancelled') {
107
+ for (const [, other] of this.records) {
108
+ if (other.status === 'pending') {
109
+ const hasFailedDep = other.task.dependsOn.some(d => d.taskId === taskId && d.onFailure !== 'continue');
110
+ if (hasFailedDep)
111
+ this.setStatus(other.task.id, 'blocked');
112
+ }
113
+ }
114
+ }
115
+ }
116
+ getActiveCount() {
117
+ let count = this.inFlight.size;
118
+ for (const [, r] of this.records) {
119
+ if (r.status === 'pending' || r.status === 'queued')
120
+ count++;
121
+ }
122
+ return count;
123
+ }
124
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Run persistence — stores orchestration runs to disk for audit and resume.
3
+ *
4
+ * Runs are stored under: ~/.ptkl/kortex/runs/<run-id>/
5
+ *
6
+ * Structure:
7
+ * run.json — schema version, goal, status, budgets, fingerprints
8
+ * plan.json — approved plan and hash
9
+ * events.jsonl — durable lifecycle events
10
+ * tasks/<id>.json — per-task state
11
+ * artifacts/ — worker outputs
12
+ * summary.md — human-readable summary
13
+ */
14
+ import { mkdirSync, writeFileSync, readFileSync, existsSync, readdirSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { randomUUID } from 'node:crypto';
17
+ const RUNS_DIR = join(process.env.HOME || '~', '.ptkl', 'kortex', 'runs');
18
+ export function createRunDirectory(goal) {
19
+ const runId = randomUUID();
20
+ const dir = join(RUNS_DIR, runId);
21
+ mkdirSync(dir, { recursive: true });
22
+ mkdirSync(join(dir, 'tasks'), { recursive: true });
23
+ mkdirSync(join(dir, 'artifacts'), { recursive: true });
24
+ const record = {
25
+ schemaVersion: 1,
26
+ runId,
27
+ goal,
28
+ status: 'running',
29
+ createdAt: new Date().toISOString(),
30
+ updatedAt: new Date().toISOString(),
31
+ configFingerprint: '',
32
+ toolCatalogFingerprint: '',
33
+ budgetSummary: { modelCalls: 0, toolCalls: 0, inputTokens: 0, outputTokens: 0 },
34
+ };
35
+ writeFileSync(join(dir, 'run.json'), JSON.stringify(record, null, 2));
36
+ return dir;
37
+ }
38
+ export function savePlan(dir, plan, hash) {
39
+ writeFileSync(join(dir, 'plan.json'), JSON.stringify({ plan, hash, approvedAt: new Date().toISOString() }, null, 2));
40
+ }
41
+ export function saveTaskResult(dir, taskId, result) {
42
+ writeFileSync(join(dir, 'tasks', `${taskId}.json`), JSON.stringify(result, null, 2));
43
+ }
44
+ export function saveArtifact(dir, name, content) {
45
+ const path = join(dir, 'artifacts', name);
46
+ writeFileSync(path, content, 'utf-8');
47
+ return path;
48
+ }
49
+ export function writeSummary(dir, text) {
50
+ writeFileSync(join(dir, 'summary.md'), text, 'utf-8');
51
+ }
52
+ export function updateRunStatus(dir, status, budgetSummary) {
53
+ const path = join(dir, 'run.json');
54
+ if (!existsSync(path))
55
+ return;
56
+ try {
57
+ const record = JSON.parse(readFileSync(path, 'utf-8'));
58
+ record.status = status;
59
+ record.updatedAt = new Date().toISOString();
60
+ record.budgetSummary = budgetSummary;
61
+ writeFileSync(path, JSON.stringify(record, null, 2));
62
+ }
63
+ catch { /* ignore */ }
64
+ }
65
+ export function loadRun(dir) {
66
+ try {
67
+ return JSON.parse(readFileSync(join(dir, 'run.json'), 'utf-8'));
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ export function loadPlan(dir) {
74
+ try {
75
+ return JSON.parse(readFileSync(join(dir, 'plan.json'), 'utf-8'));
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
81
+ export function listRuns() {
82
+ try {
83
+ if (!existsSync(RUNS_DIR))
84
+ return [];
85
+ return readdirSync(RUNS_DIR)
86
+ .filter(f => f !== '.gitkeep')
87
+ .map(f => loadRun(join(RUNS_DIR, f)))
88
+ .filter((r) => r !== null)
89
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
90
+ }
91
+ catch {
92
+ return [];
93
+ }
94
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Anthropic provider adapter stub.
3
+ *
4
+ * This adapter is the second provider family (structurally different
5
+ * from OpenAI — ordered content blocks, thinking blocks, opaque
6
+ * tool state). Full implementation requires @anthropic-ai/sdk.
7
+ *
8
+ * Phase 6+.
9
+ */
10
+ export class AnthropicAdapter {
11
+ id = 'anthropic';
12
+ family = 'anthropic';
13
+ async resolveCapabilities(_target) {
14
+ return {
15
+ streaming: true,
16
+ toolUse: true,
17
+ structuredOutput: false,
18
+ parallelToolCalls: true,
19
+ tokenCounting: 'exact',
20
+ contextWindow: 200_000,
21
+ maxOutputTokens: 4096,
22
+ supportsAbort: true,
23
+ };
24
+ }
25
+ async *stream(_request, _signal) {
26
+ // Phase 6: implement with @anthropic-ai/sdk
27
+ // Key differences from OpenAI:
28
+ // - System prompt as top-level param, not a message
29
+ // - Thinking blocks: thinking_delta → reasoning_summary
30
+ // - Tool use as content blocks: tool_use_start/delta/end
31
+ // - Opaque provider state for thinking continuity
32
+ yield { type: 'error', error: { kind: 'unavailable', message: 'Not yet implemented', retryable: false } };
33
+ }
34
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,190 @@
1
+ /**
2
+ * OpenAI-compatible provider adapter.
3
+ *
4
+ * Covers OpenAI, DeepSeek, OpenRouter, Groq, Together, xAI, Fireworks,
5
+ * and any other OpenAI-compatible API with a single implementation.
6
+ *
7
+ * The adapter uses the official `openai` SDK for reliability. For
8
+ * OpenAI-compatible services, only the `baseURL` and `apiKey` differ.
9
+ */
10
+ import { OpenAI } from 'openai';
11
+ export class OpenAICompatibleAdapter {
12
+ id;
13
+ family = 'openai';
14
+ client;
15
+ defaultModel;
16
+ constructor(id, config) {
17
+ this.id = id;
18
+ this.defaultModel = config.defaultModel ?? 'gpt-4o';
19
+ this.client = new OpenAI({
20
+ apiKey: config.apiKey,
21
+ baseURL: config.baseURL,
22
+ timeout: 180_000,
23
+ maxRetries: 0, // We handle retries ourselves
24
+ });
25
+ }
26
+ async resolveCapabilities(target) {
27
+ const model = target.type === 'model' ? target.model : this.defaultModel;
28
+ const isReasoning = model.includes('o1') || model.includes('o3') || model.includes('deepseek-reasoner');
29
+ const isDeepSeek = model.includes('deepseek');
30
+ return {
31
+ streaming: true,
32
+ toolUse: !isReasoning, // o1/o3 models before o3-mini don't support tools
33
+ structuredOutput: model.includes('gpt-4o') || model.includes('gpt-4.1'),
34
+ parallelToolCalls: true,
35
+ tokenCounting: isDeepSeek ? 'estimated' : 'exact',
36
+ contextWindow: model.includes('gpt-4o') ? 128_000
37
+ : model.includes('gpt-4.1') ? 1_000_000
38
+ : model.includes('deepseek') ? 64_000
39
+ : 128_000,
40
+ maxOutputTokens: isReasoning ? 100_000 : 16_384,
41
+ maxToolsPerRequest: 128,
42
+ supportsAbort: true,
43
+ };
44
+ }
45
+ async *stream(request, signal) {
46
+ const model = request.target.type === 'model' ? request.target.model : this.defaultModel;
47
+ // Convert canonical Turns to OpenAI messages
48
+ const messages = this.turnsToOpenAIMessages(request.turns);
49
+ // Convert canonical ToolDefinitions to OpenAI tools
50
+ const tools = request.tools.length > 0
51
+ ? request.tools.map(t => ({
52
+ type: 'function',
53
+ function: {
54
+ name: t.function.name,
55
+ description: t.function.description,
56
+ parameters: t.function.parameters,
57
+ },
58
+ }))
59
+ : undefined;
60
+ try {
61
+ const stream = await this.client.chat.completions.create({
62
+ model,
63
+ messages,
64
+ tools,
65
+ stream: true,
66
+ max_tokens: request.limits.maxOutputTokens,
67
+ }, {
68
+ signal,
69
+ });
70
+ let toolCallBuffer = new Map();
71
+ let usageEmitted = false;
72
+ for await (const chunk of stream) {
73
+ const delta = chunk.choices?.[0]?.delta;
74
+ if (!delta)
75
+ continue;
76
+ // Text content
77
+ if (delta.content) {
78
+ yield { type: 'text', delta: delta.content };
79
+ }
80
+ // Reasoning content (o1/o3 series, DeepSeek-R1)
81
+ if (delta.reasoning_content) {
82
+ yield { type: 'reasoning_summary', text: delta.reasoning_content };
83
+ }
84
+ // Tool calls
85
+ if (delta.tool_calls) {
86
+ for (const tc of delta.tool_calls) {
87
+ if (tc.id) {
88
+ // New tool call started
89
+ toolCallBuffer.set(tc.id, { id: tc.id, name: tc.function?.name ?? '', arguments: '' });
90
+ yield { type: 'tool_call_start', id: tc.id, name: tc.function?.name ?? '' };
91
+ }
92
+ const existing = toolCallBuffer.get(tc.id ?? '');
93
+ if (existing && tc.function?.arguments) {
94
+ existing.arguments += tc.function.arguments;
95
+ yield { type: 'tool_call_delta', id: existing.id, delta: tc.function.arguments };
96
+ }
97
+ }
98
+ }
99
+ // Usage (final chunk only for OpenAI)
100
+ if (chunk.usage && !usageEmitted) {
101
+ usageEmitted = true;
102
+ yield {
103
+ type: 'usage',
104
+ usage: {
105
+ inputTokens: chunk.usage.prompt_tokens ?? undefined,
106
+ outputTokens: chunk.usage.completion_tokens ?? undefined,
107
+ estimated: false,
108
+ },
109
+ };
110
+ }
111
+ }
112
+ // Emit completed tool calls
113
+ const toolCalls = [];
114
+ for (const tc of toolCallBuffer.values()) {
115
+ yield { type: 'tool_call_end', id: tc.id, name: tc.name, arguments: tc.arguments };
116
+ toolCalls.push(tc);
117
+ }
118
+ yield {
119
+ type: 'completed',
120
+ stopReason: toolCalls.length > 0 ? 'tool_call' : 'end_turn',
121
+ toolCalls: toolCalls.map(tc => ({ id: tc.id, name: tc.name, arguments: tc.arguments })),
122
+ };
123
+ }
124
+ catch (err) {
125
+ if (err.name === 'AbortError' || signal.aborted)
126
+ return;
127
+ const status = err.status;
128
+ const providerError = {
129
+ kind: status === 429 ? 'rate_limit'
130
+ : status === 401 ? 'auth'
131
+ : status === 400 ? 'invalid_request'
132
+ : status === 408 ? 'timeout'
133
+ : status >= 500 ? 'unavailable'
134
+ : err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND' ? 'network'
135
+ : 'internal',
136
+ message: err.error?.message || err.message || 'Unknown OpenAI-compatible error',
137
+ retryable: status ? status >= 429 : true,
138
+ retryAfterMs: err.headers?.get?.('retry-after')
139
+ ? parseInt(err.headers.get('retry-after')) * 1000
140
+ : undefined,
141
+ };
142
+ yield { type: 'error', error: providerError };
143
+ }
144
+ }
145
+ // ── Internal helpers ──
146
+ turnsToOpenAIMessages(turns) {
147
+ const messages = [];
148
+ for (const turn of turns) {
149
+ if (turn.role === 'system') {
150
+ const text = turn.blocks.filter(b => b.type === 'text').map(b => b.text).join('\n');
151
+ if (text)
152
+ messages.push({ role: 'system', content: text });
153
+ continue;
154
+ }
155
+ if (turn.role === 'tool') {
156
+ for (const block of turn.blocks) {
157
+ if (block.type === 'tool_result') {
158
+ messages.push({
159
+ role: 'tool',
160
+ tool_call_id: block.callId,
161
+ content: block.output.text,
162
+ });
163
+ }
164
+ }
165
+ continue;
166
+ }
167
+ if (turn.role === 'assistant') {
168
+ const text = turn.blocks.filter(b => b.type === 'text').map(b => b.text).join('\n');
169
+ const toolCalls = turn.blocks
170
+ .filter(b => b.type === 'tool_call')
171
+ .map(b => ({
172
+ id: b.id,
173
+ type: 'function',
174
+ function: { name: b.name, arguments: JSON.stringify(b.arguments) },
175
+ }));
176
+ const msg = { role: 'assistant' };
177
+ if (text)
178
+ msg.content = text;
179
+ if (toolCalls.length > 0)
180
+ msg.tool_calls = toolCalls;
181
+ messages.push(msg);
182
+ continue;
183
+ }
184
+ // User
185
+ const text = turn.blocks.filter(b => b.type === 'text').map(b => b.text).join('\n');
186
+ messages.push({ role: 'user', content: text || '(empty)' });
187
+ }
188
+ return messages;
189
+ }
190
+ }
@@ -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
+ }