@ptkl/toolkit 1.2.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 (42) hide show
  1. package/dist/commands/forge.js +39 -7
  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/dist/lib/kortexDevPlugin.js +392 -21
  42. package/package.json +6 -4
@@ -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
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * BudgetController — enforces run-level and task-level budgets.
3
+ *
4
+ * Budgets are acquired atomically before scheduling work. Usage is tracked
5
+ * and reconciled against provider-reported values when available.
6
+ */
7
+ export class BudgetController {
8
+ budgets;
9
+ state;
10
+ constructor(budgets) {
11
+ this.budgets = budgets;
12
+ this.state = {
13
+ modelCallsUsed: 0,
14
+ toolCallsUsed: 0,
15
+ inputTokens: 0,
16
+ outputTokens: 0,
17
+ estimatedCost: 0,
18
+ startTime: Date.now(),
19
+ };
20
+ }
21
+ /**
22
+ * Try to acquire a budget lease for a new agent run.
23
+ * Returns a lease if budget is available, or throws if exceeded.
24
+ */
25
+ acquire(requested) {
26
+ const modelCalls = requested.modelCalls ?? 1;
27
+ if (this.state.modelCallsUsed + modelCalls > this.budgets.maxModelCalls) {
28
+ throw new Error(`Budget exceeded: model calls (${this.state.modelCallsUsed} + ${modelCalls} > ${this.budgets.maxModelCalls})`);
29
+ }
30
+ const remainingTime = this.budgets.deadlineMs - (Date.now() - this.state.startTime);
31
+ if (remainingTime <= 0) {
32
+ throw new Error('Budget exceeded: run deadline reached');
33
+ }
34
+ return {
35
+ modelCalls,
36
+ toolCalls: requested.toolCalls ?? 0,
37
+ deadlineMs: remainingTime,
38
+ };
39
+ }
40
+ /**
41
+ * Record usage after a model call completes.
42
+ */
43
+ recordUsage(usage) {
44
+ this.state.inputTokens += usage.inputTokens ?? 0;
45
+ this.state.outputTokens += usage.outputTokens ?? 0;
46
+ this.state.modelCallsUsed++;
47
+ // Check token budgets
48
+ if (this.budgets.maxInputTokens && this.state.inputTokens > this.budgets.maxInputTokens) {
49
+ throw new Error(`Budget exceeded: input tokens (${this.state.inputTokens} > ${this.budgets.maxInputTokens})`);
50
+ }
51
+ if (this.budgets.maxOutputTokens && this.state.outputTokens > this.budgets.maxOutputTokens) {
52
+ throw new Error(`Budget exceeded: output tokens (${this.state.outputTokens} > ${this.budgets.maxOutputTokens})`);
53
+ }
54
+ }
55
+ /**
56
+ * Record a tool call.
57
+ */
58
+ recordToolCall() {
59
+ this.state.toolCallsUsed++;
60
+ if (this.state.toolCallsUsed > this.budgets.maxToolCalls) {
61
+ throw new Error(`Budget exceeded: tool calls (${this.state.toolCallsUsed} > ${this.budgets.maxToolCalls})`);
62
+ }
63
+ }
64
+ /**
65
+ * Get current budget state (for UI display and resume).
66
+ */
67
+ getState() {
68
+ return { ...this.state };
69
+ }
70
+ /**
71
+ * Get remaining budget as a percentage (for UI).
72
+ */
73
+ get remainingPercent() {
74
+ return Math.max(0, Math.round((1 - this.state.modelCallsUsed / this.budgets.maxModelCalls) * 100));
75
+ }
76
+ /**
77
+ * Check if any budget is exceeded without throwing.
78
+ */
79
+ isExceeded() {
80
+ try {
81
+ const remainingTime = this.budgets.deadlineMs - (Date.now() - this.state.startTime);
82
+ return (this.state.modelCallsUsed > this.budgets.maxModelCalls ||
83
+ this.state.toolCallsUsed > this.budgets.maxToolCalls ||
84
+ remainingTime <= 0 ||
85
+ (this.budgets.maxInputTokens !== undefined && this.state.inputTokens > this.budgets.maxInputTokens) ||
86
+ (this.budgets.maxOutputTokens !== undefined && this.state.outputTokens > this.budgets.maxOutputTokens));
87
+ }
88
+ catch {
89
+ return true;
90
+ }
91
+ }
92
+ }
93
+ // ── Default budgets ──
94
+ export const DEFAULT_RUN_BUDGETS = {
95
+ maxTasks: 10,
96
+ maxConcurrency: 3,
97
+ maxWriteConcurrency: 1,
98
+ maxModelCalls: 50,
99
+ maxToolCalls: 200,
100
+ maxInputTokens: 500_000,
101
+ maxOutputTokens: 100_000,
102
+ deadlineMs: 600_000, // 10 minutes
103
+ maxReplans: 3,
104
+ maxTaskAttempts: 3,
105
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,66 @@
1
+ /**
2
+ * ToolRuntime — owns tool policy, validation, execution, and observation.
3
+ *
4
+ * Wraps the existing tools.ts executors with:
5
+ * - Path containment (via resolveSafePath from tools.ts)
6
+ * - Tool argument validation (via validateToolArgs)
7
+ * - Risk classification (via getToolRisk)
8
+ * - Output capping and truncation metadata
9
+ * - Cancellation support via AbortSignal
10
+ * - Execution lifecycle (requested → approved → started → completed/failed)
11
+ */
12
+ import { validateToolArgs, executeTool as syncExecute, executeToolAsync, getToolDefinitions } from '../tools.js';
13
+ export class ToolRuntime {
14
+ /**
15
+ * Execute a tool call within a given context.
16
+ * Returns a ToolResult with the execution output or error.
17
+ */
18
+ async execute(ctx, call) {
19
+ // 1. Policy check
20
+ if (!ctx.policy.allowedTools.includes(call.name)) {
21
+ return {
22
+ tool_call_id: call.id,
23
+ name: call.name,
24
+ content: `Error: tool "${call.name}" is not allowed by the current policy`,
25
+ };
26
+ }
27
+ // 2. Argument validation
28
+ const toolDef = getToolDefinitions().find(t => t.function.name === call.name);
29
+ if (toolDef) {
30
+ const errs = validateToolArgs(call.name, call.arguments, toolDef.function.parameters);
31
+ if (errs.length > 0) {
32
+ return {
33
+ tool_call_id: call.id,
34
+ name: call.name,
35
+ content: `Error: invalid arguments: ${errs.map(e => `${e.path}: ${e.message}`).join('; ')}`,
36
+ };
37
+ }
38
+ }
39
+ // 3. Execute (async for bash, sync for everything else)
40
+ const callRequest = {
41
+ id: call.id,
42
+ type: 'function',
43
+ function: {
44
+ name: call.name,
45
+ arguments: JSON.stringify(call.arguments),
46
+ },
47
+ };
48
+ let result;
49
+ try {
50
+ if (call.name === 'bash') {
51
+ result = await executeToolAsync(ctx.workspace?.root ?? process.cwd(), callRequest, ctx.signal);
52
+ }
53
+ else {
54
+ result = syncExecute(ctx.workspace?.root ?? process.cwd(), callRequest);
55
+ }
56
+ }
57
+ catch (err) {
58
+ result = {
59
+ tool_call_id: call.id,
60
+ name: call.name,
61
+ content: `Error: ${err.message}`,
62
+ };
63
+ }
64
+ return result;
65
+ }
66
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * ExecutionWorkspace — manages workspace isolation for agent tasks.
3
+ *
4
+ * Phase 7: shared workspace with single-writer lease.
5
+ * Later: git worktree isolation for parallel mutating agents.
6
+ */
7
+ import { resolve } from 'node:path';
8
+ import { execSync } from 'node:child_process';
9
+ /**
10
+ * Create an ExecutionWorkspace for a task.
11
+ */
12
+ export function createWorkspace(taskId, mode) {
13
+ return {
14
+ id: taskId,
15
+ kind: 'shared',
16
+ root: resolve(process.cwd()),
17
+ writable: mode === 'write',
18
+ };
19
+ }
20
+ /**
21
+ * Validate that a path stays inside the workspace root.
22
+ */
23
+ export function isPathInsideWorkspace(path, workspace) {
24
+ try {
25
+ const resolved = resolve(workspace.root, path);
26
+ const canonical = resolve(workspace.root);
27
+ return resolved.startsWith(canonical);
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ /**
34
+ * Create a Git worktree for a task (Phase 7+).
35
+ */
36
+ export function createWorktree(workspace, taskId) {
37
+ if (workspace.kind !== 'git-worktree')
38
+ return null;
39
+ const worktreePath = resolve(workspace.root, '..', `.kortex-wt-${taskId}`);
40
+ try {
41
+ execSync(`git worktree add --detach "${worktreePath}"`, {
42
+ cwd: workspace.root,
43
+ timeout: 30_000,
44
+ encoding: 'utf-8',
45
+ });
46
+ }
47
+ catch {
48
+ // Not a git repo or worktree creation failed
49
+ return null;
50
+ }
51
+ return worktreePath;
52
+ }
@@ -0,0 +1 @@
1
+ export {};