@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,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 {};
|
package/dist/lib/kortex/tools.js
CHANGED
|
@@ -1,6 +1,65 @@
|
|
|
1
|
-
import { readFileSync, writeFileSync, existsSync, statSync, readdirSync, mkdirSync } from 'node:fs';
|
|
2
|
-
import { execSync } from 'node:child_process';
|
|
1
|
+
import { readFileSync, writeFileSync, existsSync, statSync, readdirSync, mkdirSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { execSync, spawnSync, spawn } from 'node:child_process';
|
|
3
3
|
import { resolve, dirname, relative } from 'node:path';
|
|
4
|
+
const toolRiskMap = {
|
|
5
|
+
read_file: 'read',
|
|
6
|
+
write_file: 'write',
|
|
7
|
+
edit_file: 'write',
|
|
8
|
+
list_directory: 'read',
|
|
9
|
+
search_files: 'read',
|
|
10
|
+
bash: 'execute',
|
|
11
|
+
git_status: 'read',
|
|
12
|
+
git_diff: 'read',
|
|
13
|
+
git_log: 'read',
|
|
14
|
+
git_commit: 'destructive',
|
|
15
|
+
git_branch: 'write', // create/switch mutate refs
|
|
16
|
+
};
|
|
17
|
+
export function getToolRisk(name) {
|
|
18
|
+
// MCP tool names follow mcp_<server>_<name> — default to external
|
|
19
|
+
if (name.startsWith('mcp_'))
|
|
20
|
+
return 'external';
|
|
21
|
+
return toolRiskMap[name] ?? 'execute';
|
|
22
|
+
}
|
|
23
|
+
export function validateToolArgs(toolName, args, schema) {
|
|
24
|
+
const errors = [];
|
|
25
|
+
if (!schema.properties)
|
|
26
|
+
return errors; // no schema to validate against
|
|
27
|
+
// Check required fields
|
|
28
|
+
const required = schema.required ?? [];
|
|
29
|
+
for (const field of required) {
|
|
30
|
+
if (args[field] === undefined || args[field] === null) {
|
|
31
|
+
errors.push({ path: field, message: `Required field "${field}" is missing` });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// Type-check known properties
|
|
35
|
+
for (const [field, value] of Object.entries(args)) {
|
|
36
|
+
const propSchema = schema.properties[field];
|
|
37
|
+
if (!propSchema) {
|
|
38
|
+
// If the schema defines specific properties, warn about unknowns
|
|
39
|
+
if (Object.keys(schema.properties).length > 0) {
|
|
40
|
+
errors.push({ path: field, message: `Unknown field "${field}"` });
|
|
41
|
+
}
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const expectedType = propSchema.type;
|
|
45
|
+
if (expectedType === 'string' && typeof value !== 'string') {
|
|
46
|
+
errors.push({ path: field, message: `Expected string, got ${typeof value}` });
|
|
47
|
+
}
|
|
48
|
+
else if (expectedType === 'number' && typeof value !== 'number') {
|
|
49
|
+
errors.push({ path: field, message: `Expected number, got ${typeof value}` });
|
|
50
|
+
}
|
|
51
|
+
else if (expectedType === 'array' && !Array.isArray(value)) {
|
|
52
|
+
errors.push({ path: field, message: `Expected array, got ${typeof value}` });
|
|
53
|
+
}
|
|
54
|
+
else if (expectedType === 'object' && (typeof value !== 'object' || Array.isArray(value) || value === null)) {
|
|
55
|
+
errors.push({ path: field, message: `Expected object, got ${typeof value}` });
|
|
56
|
+
}
|
|
57
|
+
else if (expectedType === 'boolean' && typeof value !== 'boolean') {
|
|
58
|
+
errors.push({ path: field, message: `Expected boolean, got ${typeof value}` });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return errors;
|
|
62
|
+
}
|
|
4
63
|
const MAX_OUTPUT = 100_000;
|
|
5
64
|
function clampOutput(text) {
|
|
6
65
|
if (text.length <= MAX_OUTPUT)
|
|
@@ -10,6 +69,52 @@ function clampOutput(text) {
|
|
|
10
69
|
function resolvePath(cwd, filePath) {
|
|
11
70
|
return resolve(cwd, filePath);
|
|
12
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* Canonicalize a file path and validate it stays inside the workspace root.
|
|
74
|
+
*
|
|
75
|
+
* - Rejects `..` traversal that escapes cwd.
|
|
76
|
+
* - Rejects symlink escape for existing paths.
|
|
77
|
+
* - For a new path, validates its closest existing parent directory.
|
|
78
|
+
*
|
|
79
|
+
* This is a safety boundary, not a sandbox. bash / MCP tools are not
|
|
80
|
+
* constrained by this check — they run with the user's OS permissions.
|
|
81
|
+
*/
|
|
82
|
+
function resolveSafePath(cwd, filePath) {
|
|
83
|
+
const cleaned = filePath.replace(/[<>]/g, '').trim();
|
|
84
|
+
const resolved = resolve(cwd, cleaned);
|
|
85
|
+
// Reject paths that escape cwd
|
|
86
|
+
const cwdCanonical = resolve(cwd);
|
|
87
|
+
if (!resolved.startsWith(cwdCanonical)) {
|
|
88
|
+
throw new Error(`Path "${filePath}" escapes the working directory`);
|
|
89
|
+
}
|
|
90
|
+
// For existing paths, resolve symlinks
|
|
91
|
+
if (existsSync(resolved)) {
|
|
92
|
+
try {
|
|
93
|
+
const real = realpathSync(resolved);
|
|
94
|
+
if (!real.startsWith(realpathSync(cwd))) {
|
|
95
|
+
throw new Error(`Path "${filePath}" escapes the working directory via symlink`);
|
|
96
|
+
}
|
|
97
|
+
return real;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
throw new Error(`Path "${filePath}" cannot be resolved`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// For new paths, validate closest existing parent
|
|
104
|
+
const parent = dirname(resolved);
|
|
105
|
+
if (parent !== resolved && existsSync(parent)) {
|
|
106
|
+
try {
|
|
107
|
+
const realParent = realpathSync(parent);
|
|
108
|
+
if (!realParent.startsWith(realpathSync(cwd))) {
|
|
109
|
+
throw new Error(`Path "${filePath}" escapes the working directory`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
throw new Error(`Path "${filePath}" cannot be resolved`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return resolved;
|
|
117
|
+
}
|
|
13
118
|
export function getToolDefinitions() {
|
|
14
119
|
return [
|
|
15
120
|
// ── File system ──
|
|
@@ -181,7 +286,13 @@ export function getToolDefinitions() {
|
|
|
181
286
|
}
|
|
182
287
|
// ── File system executors ──
|
|
183
288
|
function execReadFile(cwd, args) {
|
|
184
|
-
|
|
289
|
+
let fullPath;
|
|
290
|
+
try {
|
|
291
|
+
fullPath = resolveSafePath(cwd, args.path);
|
|
292
|
+
}
|
|
293
|
+
catch (e) {
|
|
294
|
+
return `Error: ${e.message}`;
|
|
295
|
+
}
|
|
185
296
|
if (!existsSync(fullPath))
|
|
186
297
|
return `Error: file not found: ${args.path}`;
|
|
187
298
|
const stat = statSync(fullPath);
|
|
@@ -196,7 +307,13 @@ function execReadFile(cwd, args) {
|
|
|
196
307
|
return clampOutput(numbered);
|
|
197
308
|
}
|
|
198
309
|
function execWriteFile(cwd, args) {
|
|
199
|
-
|
|
310
|
+
let fullPath;
|
|
311
|
+
try {
|
|
312
|
+
fullPath = resolveSafePath(cwd, args.path);
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
return `Error: ${e.message}`;
|
|
316
|
+
}
|
|
200
317
|
const dir = dirname(fullPath);
|
|
201
318
|
if (!existsSync(dir))
|
|
202
319
|
mkdirSync(dir, { recursive: true });
|
|
@@ -204,7 +321,13 @@ function execWriteFile(cwd, args) {
|
|
|
204
321
|
return `File written: ${args.path}`;
|
|
205
322
|
}
|
|
206
323
|
function execEditFile(cwd, args) {
|
|
207
|
-
|
|
324
|
+
let fullPath;
|
|
325
|
+
try {
|
|
326
|
+
fullPath = resolveSafePath(cwd, args.path);
|
|
327
|
+
}
|
|
328
|
+
catch (e) {
|
|
329
|
+
return `Error: ${e.message}`;
|
|
330
|
+
}
|
|
208
331
|
if (!existsSync(fullPath))
|
|
209
332
|
return `Error: file not found: ${args.path}`;
|
|
210
333
|
const content = readFileSync(fullPath, 'utf-8');
|
|
@@ -219,7 +342,13 @@ function execEditFile(cwd, args) {
|
|
|
219
342
|
}
|
|
220
343
|
function execListDirectory(cwd, args) {
|
|
221
344
|
const rawPath = (args.path || '.').replace(/[<>]/g, '').trim() || '.';
|
|
222
|
-
|
|
345
|
+
let targetPath;
|
|
346
|
+
try {
|
|
347
|
+
targetPath = resolveSafePath(cwd, rawPath);
|
|
348
|
+
}
|
|
349
|
+
catch (e) {
|
|
350
|
+
return `Error: ${e.message}`;
|
|
351
|
+
}
|
|
223
352
|
if (!existsSync(targetPath))
|
|
224
353
|
return `Error: path not found: ${args.path || '.'}`;
|
|
225
354
|
const maxDepth = args.depth ?? 3;
|
|
@@ -261,13 +390,16 @@ function execListDirectory(cwd, args) {
|
|
|
261
390
|
}
|
|
262
391
|
function execSearchFiles(cwd, args) {
|
|
263
392
|
const searchPath = args.path || '.';
|
|
264
|
-
|
|
393
|
+
const grepArgs = ['-r', '-n', args.pattern, searchPath];
|
|
265
394
|
if (args.include)
|
|
266
|
-
|
|
267
|
-
cmd += ' 2>/dev/null | head -100';
|
|
395
|
+
grepArgs.push('--include', args.include);
|
|
268
396
|
try {
|
|
269
|
-
const
|
|
270
|
-
|
|
397
|
+
const result = spawnSync('grep', grepArgs, { cwd, timeout: 15_000, encoding: 'utf-8', maxBuffer: 1024 * 1024 * 5 });
|
|
398
|
+
if (result.status === 0) {
|
|
399
|
+
return clampOutput(result.stdout || 'No matches found.');
|
|
400
|
+
}
|
|
401
|
+
// grep exits 1 when no match — not an error
|
|
402
|
+
return 'No matches found.';
|
|
271
403
|
}
|
|
272
404
|
catch {
|
|
273
405
|
return 'No matches found.';
|
|
@@ -295,62 +427,65 @@ function execBash(cwd, args) {
|
|
|
295
427
|
// ── Git executors ──
|
|
296
428
|
function git(cwd, args) {
|
|
297
429
|
try {
|
|
298
|
-
const
|
|
430
|
+
const result = spawnSync('git', args, {
|
|
299
431
|
cwd,
|
|
300
432
|
timeout: 15_000,
|
|
301
433
|
encoding: 'utf-8',
|
|
302
434
|
maxBuffer: 1024 * 1024 * 5,
|
|
303
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
304
435
|
});
|
|
305
|
-
return clampOutput(
|
|
436
|
+
return clampOutput(result.stdout?.trim() || '(no output)');
|
|
306
437
|
}
|
|
307
438
|
catch (err) {
|
|
308
|
-
const stdout = err.stdout || '';
|
|
309
439
|
const stderr = err.stderr || '';
|
|
310
|
-
return clampOutput(`Error: ${stderr
|
|
440
|
+
return clampOutput(`Error: ${stderr}`.trim());
|
|
311
441
|
}
|
|
312
442
|
}
|
|
313
443
|
function execGitStatus(cwd) {
|
|
314
|
-
return git(cwd, 'status');
|
|
444
|
+
return git(cwd, ['status']);
|
|
315
445
|
}
|
|
316
446
|
function execGitDiff(cwd, args) {
|
|
317
447
|
const target = args.target || 'unstaged';
|
|
318
|
-
const
|
|
319
|
-
if (target === 'staged')
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
448
|
+
const gitArgs = ['diff'];
|
|
449
|
+
if (target === 'staged') {
|
|
450
|
+
gitArgs.push('--cached');
|
|
451
|
+
}
|
|
452
|
+
else if (target !== 'unstaged') {
|
|
453
|
+
gitArgs.push(target);
|
|
454
|
+
}
|
|
455
|
+
if (args.path)
|
|
456
|
+
gitArgs.push('--', args.path);
|
|
457
|
+
return git(cwd, gitArgs);
|
|
324
458
|
}
|
|
325
459
|
function execGitLog(cwd, args) {
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
460
|
+
const gitArgs = ['log', '--oneline', '--decorate', '-n', String(args.count ?? 10)];
|
|
461
|
+
if (args.branch)
|
|
462
|
+
gitArgs.push(args.branch);
|
|
463
|
+
if (args.path)
|
|
464
|
+
gitArgs.push('--', args.path);
|
|
465
|
+
return git(cwd, gitArgs);
|
|
330
466
|
}
|
|
331
467
|
function execGitCommit(cwd, args) {
|
|
332
468
|
if (args.files && args.files.length > 0) {
|
|
333
|
-
|
|
334
|
-
git(cwd, `add ${fileList}`);
|
|
469
|
+
git(cwd, ['add', ...args.files]);
|
|
335
470
|
}
|
|
336
471
|
else {
|
|
337
|
-
git(cwd, 'add -A');
|
|
472
|
+
git(cwd, ['add', '-A']);
|
|
338
473
|
}
|
|
339
|
-
return git(cwd,
|
|
474
|
+
return git(cwd, ['commit', '-m', args.message]);
|
|
340
475
|
}
|
|
341
476
|
function execGitBranch(cwd, args) {
|
|
342
477
|
const action = args.action || 'list';
|
|
343
478
|
switch (action) {
|
|
344
479
|
case 'list':
|
|
345
|
-
return git(cwd, 'branch -a');
|
|
480
|
+
return git(cwd, ['branch', '-a']);
|
|
346
481
|
case 'create':
|
|
347
482
|
if (!args.name)
|
|
348
483
|
return 'Error: branch name is required';
|
|
349
|
-
return git(cwd,
|
|
484
|
+
return git(cwd, ['checkout', '-b', args.name]);
|
|
350
485
|
case 'switch':
|
|
351
486
|
if (!args.name)
|
|
352
487
|
return 'Error: branch name is required';
|
|
353
|
-
return git(cwd,
|
|
488
|
+
return git(cwd, ['checkout', args.name]);
|
|
354
489
|
default:
|
|
355
490
|
return `Error: unknown action "${action}"`;
|
|
356
491
|
}
|
|
@@ -404,3 +539,60 @@ export function executeTool(cwd, call) {
|
|
|
404
539
|
}
|
|
405
540
|
return { tool_call_id: call.id, name: call.function.name, content };
|
|
406
541
|
}
|
|
542
|
+
// ── Async tool execution (Phase 0: bash only; remaining tools migrate alongside Session) ──
|
|
543
|
+
/**
|
|
544
|
+
* async execBash — uses spawn() and supports AbortSignal for cancellation.
|
|
545
|
+
* The shell is still used to interpret pipes, redirects, and compound commands.
|
|
546
|
+
*/
|
|
547
|
+
export async function execBashAsync(cwd, args, signal) {
|
|
548
|
+
const timeoutMs = args.timeout ?? 30_000;
|
|
549
|
+
return new Promise((resolve) => {
|
|
550
|
+
const chunks = [];
|
|
551
|
+
const errChunks = [];
|
|
552
|
+
const child = spawn(args.command, [], {
|
|
553
|
+
cwd,
|
|
554
|
+
shell: true,
|
|
555
|
+
signal,
|
|
556
|
+
timeout: timeoutMs,
|
|
557
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
558
|
+
});
|
|
559
|
+
child.stdout.on('data', (chunk) => chunks.push(chunk.toString()));
|
|
560
|
+
child.stderr.on('data', (chunk) => errChunks.push(chunk.toString()));
|
|
561
|
+
child.on('error', (err) => {
|
|
562
|
+
if (err.code === 'ABORT_ERR' || err.message.includes('aborted')) {
|
|
563
|
+
resolve(clampOutput('(cancelled)'));
|
|
564
|
+
}
|
|
565
|
+
else {
|
|
566
|
+
resolve(clampOutput(`Error: ${err.message}`));
|
|
567
|
+
}
|
|
568
|
+
});
|
|
569
|
+
child.on('exit', (code) => {
|
|
570
|
+
const stdout = chunks.join('');
|
|
571
|
+
const stderr = errChunks.join('');
|
|
572
|
+
if (code === 0) {
|
|
573
|
+
resolve(clampOutput(stdout || '(no output)'));
|
|
574
|
+
}
|
|
575
|
+
else {
|
|
576
|
+
resolve(clampOutput(`Exit code: ${code}\n${stdout}\n${stderr}`.trim()));
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Async tool dispatcher. Bash calls run asynchronously with cancellation support;
|
|
583
|
+
* all other tools fall through to the synchronous executeTool.
|
|
584
|
+
*/
|
|
585
|
+
export async function executeToolAsync(cwd, call, signal) {
|
|
586
|
+
if (call.function.name === 'bash') {
|
|
587
|
+
let args;
|
|
588
|
+
try {
|
|
589
|
+
args = JSON.parse(call.function.arguments);
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
return { tool_call_id: call.id, name: call.function.name, content: 'Error: invalid JSON arguments' };
|
|
593
|
+
}
|
|
594
|
+
const content = await execBashAsync(cwd, args, signal);
|
|
595
|
+
return { tool_call_id: call.id, name: call.function.name, content };
|
|
596
|
+
}
|
|
597
|
+
return executeTool(cwd, call);
|
|
598
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** Headers for every callback page: nothing external may load, nothing is cached or leaked. */
|
|
2
|
+
export const PAGE_HEADERS = {
|
|
3
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
4
|
+
"Cache-Control": "no-store",
|
|
5
|
+
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
|
|
6
|
+
"Referrer-Policy": "no-referrer",
|
|
7
|
+
"X-Content-Type-Options": "nosniff",
|
|
8
|
+
};
|
|
9
|
+
/** Where the browser tab lands after a successful login. */
|
|
10
|
+
export const GUIDE_URL = "https://docs.protokol.io/platform/oauth/";
|
|
11
|
+
const MAX_DESCRIPTION = 200;
|
|
12
|
+
/** Self-contained HTML (inline CSS/SVG only) for the loopback login result. */
|
|
13
|
+
export default class CallbackPages {
|
|
14
|
+
static escape(s) {
|
|
15
|
+
return s.replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
|
16
|
+
}
|
|
17
|
+
static clip(s, max = MAX_DESCRIPTION) {
|
|
18
|
+
return s.length > max ? s.slice(0, max) + "..." : s;
|
|
19
|
+
}
|
|
20
|
+
static retryCommand(c) {
|
|
21
|
+
const name = c.name;
|
|
22
|
+
return c.isNew
|
|
23
|
+
? `ptkl profile new -n ${name} -h ${c.host} -P ${c.project}`
|
|
24
|
+
: `ptkl profile auth ${name}`;
|
|
25
|
+
}
|
|
26
|
+
static retry(c) {
|
|
27
|
+
return `<p class="retry">Try again:</p><pre>${CallbackPages.escape(CallbackPages.retryCommand(c))}</pre>`;
|
|
28
|
+
}
|
|
29
|
+
static denied(c) {
|
|
30
|
+
return CallbackPages.page(400, "You declined access", "No permissions were granted to the CLI.", CallbackPages.retry(c));
|
|
31
|
+
}
|
|
32
|
+
static invalidLink(c) {
|
|
33
|
+
return CallbackPages.page(400, "This login link is no longer valid", "The request does not match a login started from your terminal.", CallbackPages.retry(c));
|
|
34
|
+
}
|
|
35
|
+
static expired(c) {
|
|
36
|
+
return CallbackPages.page(408, "This login timed out", "The CLI stopped waiting for the browser.", CallbackPages.retry(c));
|
|
37
|
+
}
|
|
38
|
+
/** Server-reported OAuth error. Only the (escaped, capped) code and description are shown. */
|
|
39
|
+
static failed(c, code, description) {
|
|
40
|
+
const detail = `<p class="code">${CallbackPages.escape(CallbackPages.clip(code, 64))}</p>` +
|
|
41
|
+
(description ? `<p class="desc">${CallbackPages.escape(CallbackPages.clip(description))}</p>` : "");
|
|
42
|
+
return CallbackPages.page(400, "Login failed", "The authorization server returned an error.", detail + CallbackPages.retry(c));
|
|
43
|
+
}
|
|
44
|
+
static forError(c, code, description) {
|
|
45
|
+
if (code === "access_denied")
|
|
46
|
+
return CallbackPages.denied(c);
|
|
47
|
+
if (code === "state_mismatch" || code === "invalid_response")
|
|
48
|
+
return CallbackPages.invalidLink(c);
|
|
49
|
+
if (code === "timeout")
|
|
50
|
+
return CallbackPages.expired(c);
|
|
51
|
+
return CallbackPages.failed(c, code, description);
|
|
52
|
+
}
|
|
53
|
+
static page(status, title, lead, body) {
|
|
54
|
+
const icon = `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7l10 10M17 7L7 17" fill="none" stroke="#fff" stroke-width="2.6" stroke-linecap="round"/></svg>`;
|
|
55
|
+
const html = `<!doctype html>
|
|
56
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
57
|
+
<title>${CallbackPages.escape(title)} - Protokol</title>
|
|
58
|
+
<style>
|
|
59
|
+
:root{--bg:#f8f9fa;--card:#fff;--text:#1f2328;--muted:#656d76;--line:rgba(0,0,0,.08);--code:#f1f3f4;--err:#d64545;--p1:#6c80ff;--p2:#764ba2}
|
|
60
|
+
@media (prefers-color-scheme:dark){:root{--bg:#1e1f22;--card:#313338;--text:#f2f3f5;--muted:#b5bac1;--line:rgba(255,255,255,.08);--code:#2b2d31}}
|
|
61
|
+
*{box-sizing:border-box}
|
|
62
|
+
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:16px;background:var(--bg);color:var(--text);font:16px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
63
|
+
main{width:100%;max-width:440px;background:var(--card);border:1px solid var(--line);border-radius:16px;padding:40px 32px 28px;text-align:center;box-shadow:0 8px 32px rgba(0,0,0,.08)}
|
|
64
|
+
.brand{font-weight:700;letter-spacing:.04em;background:linear-gradient(90deg,var(--p1),var(--p2));-webkit-background-clip:text;background-clip:text;color:transparent;margin-bottom:28px}
|
|
65
|
+
.icon{width:56px;height:56px;border-radius:50%;margin:0 auto 20px;padding:13px;background:var(--err)}
|
|
66
|
+
h1{font-size:1.35rem;line-height:1.3;margin:0 0 8px}
|
|
67
|
+
.lead{color:var(--muted);margin:0 0 24px}
|
|
68
|
+
pre,code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
|
69
|
+
pre{margin:0 0 8px;padding:12px;background:var(--code);border-radius:10px;font-size:.85rem;text-align:left;white-space:pre-wrap;word-break:break-all}
|
|
70
|
+
.retry{color:var(--muted);margin:0 0 8px;text-align:left;font-size:.9rem}
|
|
71
|
+
.code{font-family:ui-monospace,Menlo,monospace;font-size:.85rem;margin:0 0 4px}.desc{color:var(--muted);font-size:.9rem;margin:0 0 20px;word-break:break-word}
|
|
72
|
+
</style></head>
|
|
73
|
+
<body><main>
|
|
74
|
+
<div class="brand">PROTOKOL</div>
|
|
75
|
+
<div class="icon">${icon}</div>
|
|
76
|
+
<h1>${CallbackPages.escape(title)}</h1>
|
|
77
|
+
<p class="lead">${CallbackPages.escape(lead)}</p>
|
|
78
|
+
${body}
|
|
79
|
+
</main></body></html>`;
|
|
80
|
+
return { status, html };
|
|
81
|
+
}
|
|
82
|
+
}
|