homeagent-runner 0.4.15 → 0.4.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/README.md +203 -159
- package/README.zh-CN.md +341 -0
- package/dist/runner/lsp.js +999 -0
- package/dist/runner/patch.js +66 -11
- package/dist/runner/permissions.js +24 -11
- package/dist/runner/shells.js +305 -0
- package/dist/runner/tools.js +19 -2
- package/dist/shared/protocol.js +1 -1
- package/dist/shared/tools.js +24 -4
- package/docs/OPEN_SOURCE.md +8 -8
- package/docs/TOOLS.md +17 -4
- package/docs/WEBCODEX_CODE_AUDIT.md +3 -3
- package/package.json +2 -2
- package/README.en.md +0 -383
package/dist/runner/patch.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { AppError } from '../shared/protocol.js';
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
const normalizeLine = (line) => line.replace(/[ \t]+(?=\n|$)/g, '').trimStart();
|
|
3
|
+
/** Unified diff parser with optional bounded fuzzy hunk relocation and whitespace tolerance. */
|
|
4
|
+
export async function parseUnifiedDiff(files, project, diff, expected, options = {}) {
|
|
5
|
+
const fuzz = Math.max(0, Math.min(200, options.fuzz ?? 20));
|
|
6
|
+
const ignoreWhitespace = options.ignoreWhitespace ?? false;
|
|
7
|
+
const relocatedHunks = [];
|
|
4
8
|
const lines = diff.replace(/\r\n/g, '\n').split('\n');
|
|
5
9
|
const changes = [];
|
|
6
10
|
let index = 0;
|
|
@@ -39,13 +43,13 @@ export async function parseUnifiedDiff(files, project, diff, expected) {
|
|
|
39
43
|
throw new AppError('invalid_patch', 'Invalid hunk header');
|
|
40
44
|
const oldCount = Number(header[2] ?? 1), newCount = Number(header[4] ?? 1);
|
|
41
45
|
const oldStart = oldCount === 0 ? Number(header[1]) : Number(header[1]) - 1;
|
|
42
|
-
if (oldStart < consumed || oldStart > original.length)
|
|
43
|
-
throw new AppError('invalid_patch', 'Overlapping or out-of-range hunks');
|
|
44
|
-
output.push(...original.slice(consumed, oldStart));
|
|
45
|
-
consumed = oldStart;
|
|
46
46
|
const newStart = newCount === 0 ? Number(header[3]) : Number(header[3]) - 1;
|
|
47
|
-
if (
|
|
48
|
-
|
|
47
|
+
if (fuzz === 0) {
|
|
48
|
+
if (oldStart < consumed || oldStart > original.length)
|
|
49
|
+
throw new AppError('invalid_patch', 'Overlapping or out-of-range hunks');
|
|
50
|
+
if (newStart !== output.length + (oldStart - consumed))
|
|
51
|
+
throw new AppError('invalid_patch', 'New hunk line position does not match preceding changes');
|
|
52
|
+
}
|
|
49
53
|
const removed = [], added = [];
|
|
50
54
|
let oldLines = 0, newLines = 0, previous;
|
|
51
55
|
while (oldLines < oldCount || newLines < newCount) {
|
|
@@ -74,10 +78,61 @@ export async function parseUnifiedDiff(files, project, diff, expected) {
|
|
|
74
78
|
if (oldLines > oldCount || newLines > newCount)
|
|
75
79
|
throw new AppError('invalid_patch', 'Hunk line counts do not match header');
|
|
76
80
|
}
|
|
77
|
-
|
|
81
|
+
const matchesAt = (pos, loose) => {
|
|
82
|
+
if (pos < consumed || pos + oldCount > original.length)
|
|
83
|
+
return false;
|
|
84
|
+
for (let k = 0; k < oldCount; k++) {
|
|
85
|
+
const left = original[pos + k], right = removed[k];
|
|
86
|
+
if (loose ? normalizeLine(left) !== normalizeLine(right) : left !== right)
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
return true;
|
|
90
|
+
};
|
|
91
|
+
let targetPos;
|
|
92
|
+
if (oldCount === 0) {
|
|
93
|
+
if (oldStart < consumed || oldStart > original.length)
|
|
94
|
+
throw new AppError('invalid_patch', 'Overlapping or out-of-range hunks');
|
|
95
|
+
targetPos = oldStart;
|
|
96
|
+
}
|
|
97
|
+
else if (matchesAt(oldStart, false)) {
|
|
98
|
+
targetPos = oldStart;
|
|
99
|
+
}
|
|
100
|
+
else if (fuzz > 0) {
|
|
101
|
+
const minPos = Math.max(consumed, oldStart - fuzz), maxPos = Math.min(original.length - oldCount, oldStart + fuzz);
|
|
102
|
+
const exactCandidates = [];
|
|
103
|
+
for (let pos = minPos; pos <= maxPos; pos++)
|
|
104
|
+
if (matchesAt(pos, false))
|
|
105
|
+
exactCandidates.push(pos);
|
|
106
|
+
if (exactCandidates.length === 1) {
|
|
107
|
+
targetPos = exactCandidates[0];
|
|
108
|
+
relocatedHunks.push({ path: name, hunkIndex: hunks + 1, expectedLine: oldStart + 1, appliedLine: targetPos + 1, offset: targetPos - oldStart });
|
|
109
|
+
}
|
|
110
|
+
else if (exactCandidates.length > 1) {
|
|
111
|
+
throw new AppError('ambiguous_patch', `Fuzzy hunk context matches multiple locations in ${name}`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (targetPos === undefined && ignoreWhitespace && oldCount > 0) {
|
|
115
|
+
const minPos = Math.max(consumed, oldStart - fuzz), maxPos = Math.min(original.length - oldCount, oldStart + fuzz);
|
|
116
|
+
const looseCandidates = [];
|
|
117
|
+
for (let pos = minPos; pos <= maxPos; pos++)
|
|
118
|
+
if (matchesAt(pos, true))
|
|
119
|
+
looseCandidates.push(pos);
|
|
120
|
+
if (looseCandidates.length === 1) {
|
|
121
|
+
targetPos = looseCandidates[0];
|
|
122
|
+
relocatedHunks.push({ path: name, hunkIndex: hunks + 1, expectedLine: oldStart + 1, appliedLine: targetPos + 1, offset: targetPos - oldStart, whitespaceNormalized: true });
|
|
123
|
+
}
|
|
124
|
+
else if (looseCandidates.length > 1) {
|
|
125
|
+
throw new AppError('ambiguous_patch', `Fuzzy hunk context matches multiple locations in ${name}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (targetPos === undefined) {
|
|
129
|
+
if (oldStart < consumed || oldStart > original.length)
|
|
130
|
+
throw new AppError('invalid_patch', 'Overlapping or out-of-range hunks');
|
|
78
131
|
throw new AppError('patch_context', `Hunk context does not match ${name}`);
|
|
132
|
+
}
|
|
133
|
+
output.push(...original.slice(consumed, targetPos));
|
|
79
134
|
output.push(...added);
|
|
80
|
-
consumed
|
|
135
|
+
consumed = targetPos + oldCount;
|
|
81
136
|
hunks++;
|
|
82
137
|
}
|
|
83
138
|
if (!hunks)
|
|
@@ -98,6 +153,6 @@ export async function parseUnifiedDiff(files, project, diff, expected) {
|
|
|
98
153
|
}
|
|
99
154
|
if (!changes.length || changes.length > 32)
|
|
100
155
|
throw new AppError('invalid_patch', 'Expected 1 to 32 file changes');
|
|
101
|
-
return changes;
|
|
156
|
+
return Object.assign(changes, { relocatedHunks });
|
|
102
157
|
}
|
|
103
158
|
//# sourceMappingURL=patch.js.map
|
|
@@ -31,6 +31,11 @@ export class RunnerPermissions {
|
|
|
31
31
|
this.consent?.validatePermissions(policy);
|
|
32
32
|
if (policy.revision < this.revision)
|
|
33
33
|
throw new AppError('stale_permissions', 'Refusing an older device permission revision');
|
|
34
|
+
// Retire the old expiration before invalidation or task shutdown can yield.
|
|
35
|
+
if (this.timer)
|
|
36
|
+
clearTimeout(this.timer);
|
|
37
|
+
this.timer = undefined;
|
|
38
|
+
this.current = undefined;
|
|
34
39
|
const expired = !!policy.expiresAt && policy.expiresAt <= Date.now();
|
|
35
40
|
const selected = expired ? policy.fallbackProjects : policy.projects;
|
|
36
41
|
// A policy that fails validation must still stop the previous authority.
|
|
@@ -38,7 +43,6 @@ export class RunnerPermissions {
|
|
|
38
43
|
await this.tools.processes.stopAllAndWait();
|
|
39
44
|
this.config.projects = [];
|
|
40
45
|
this.tools.policy.expiresAt = undefined;
|
|
41
|
-
this.current = undefined;
|
|
42
46
|
const projects = [];
|
|
43
47
|
for (const project of selected) {
|
|
44
48
|
if (!path.isAbsolute(project.root))
|
|
@@ -54,8 +58,6 @@ export class RunnerPermissions {
|
|
|
54
58
|
}
|
|
55
59
|
if (new Set(projects.map(project => project.id)).size !== projects.length)
|
|
56
60
|
throw new AppError('duplicate_project', 'Project IDs must be unique');
|
|
57
|
-
if (this.timer)
|
|
58
|
-
clearTimeout(this.timer);
|
|
59
61
|
this.revision = policy.revision;
|
|
60
62
|
this.current = policy;
|
|
61
63
|
this.config.projects = projects;
|
|
@@ -69,14 +71,25 @@ export class RunnerPermissions {
|
|
|
69
71
|
}
|
|
70
72
|
if (!expired && policy.expiresAt)
|
|
71
73
|
this.timer = setTimeout(() => {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
74
|
+
const next = this.queue.catch(() => { }).then(async () => {
|
|
75
|
+
// An update may have superseded this policy while expiration was queued.
|
|
76
|
+
if (this.current !== policy)
|
|
77
|
+
return;
|
|
78
|
+
if (this.consent) {
|
|
79
|
+
this.consent.revoke();
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
// Keep revocation and fallback together so an update cannot land between them.
|
|
83
|
+
try {
|
|
84
|
+
await this.resetNow();
|
|
85
|
+
await this.applyNow({ revision: policy.revision, projects: policy.fallbackProjects, expiresAt: null, fallbackProjects: policy.fallbackProjects });
|
|
86
|
+
this.changed(policy.revision);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
this.changed(policy.revision, error instanceof Error ? error.message : 'Permission expiration failed');
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
this.queue = next;
|
|
80
93
|
}, Math.max(1, policy.expiresAt - Date.now())).unref();
|
|
81
94
|
}
|
|
82
95
|
reset() {
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { AppError } from '../shared/protocol.js';
|
|
4
|
+
function detectShellKind(executable) {
|
|
5
|
+
const base = path.basename(executable).toLowerCase();
|
|
6
|
+
if (/^(?:powershell|pwsh)(?:\.exe)?$/.test(base))
|
|
7
|
+
return 'powershell';
|
|
8
|
+
if (/^cmd(?:\.exe)?$/.test(base))
|
|
9
|
+
return 'cmd';
|
|
10
|
+
return 'posix';
|
|
11
|
+
}
|
|
12
|
+
const powershellLoopEncoded = Buffer.from([
|
|
13
|
+
"$env:PSModulePath = [System.IO.Path]::Combine($PSHOME, 'Modules')",
|
|
14
|
+
"Import-Module -Name ([System.IO.Path]::Combine($PSHOME, 'Modules', 'Microsoft.PowerShell.Management', 'Microsoft.PowerShell.Management.psd1')) -ErrorAction SilentlyContinue",
|
|
15
|
+
"Import-Module -Name ([System.IO.Path]::Combine($PSHOME, 'Modules', 'Microsoft.PowerShell.Utility', 'Microsoft.PowerShell.Utility.psd1')) -ErrorAction SilentlyContinue",
|
|
16
|
+
'[Console]::OutputEncoding = $OutputEncoding = [System.Text.UTF8Encoding]::new($false)',
|
|
17
|
+
'while ($null -ne ($__ha_l = [Console]::In.ReadLine())) { if ($__ha_l.Trim().Length -gt 0) { . ([ScriptBlock]::Create($__ha_l)) } }',
|
|
18
|
+
].join('; '), 'utf16le').toString('base64');
|
|
19
|
+
function defaultShellArgs(kind, executable) {
|
|
20
|
+
if (kind === 'powershell')
|
|
21
|
+
return ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', powershellLoopEncoded];
|
|
22
|
+
if (kind === 'cmd')
|
|
23
|
+
return ['/Q', '/K', 'prompt $S'];
|
|
24
|
+
const base = path.basename(executable).toLowerCase();
|
|
25
|
+
if (base === 'bash' || base === 'bash.exe')
|
|
26
|
+
return ['--noprofile', '--norc'];
|
|
27
|
+
if (base === 'zsh' || base === 'zsh.exe')
|
|
28
|
+
return ['--no-rcs'];
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
function selectDefaultShell(project) {
|
|
32
|
+
if (Object.hasOwn(project.commandAliases, 'shell'))
|
|
33
|
+
return 'shell';
|
|
34
|
+
const candidates = process.platform === 'win32'
|
|
35
|
+
? ['powershell.exe', 'pwsh.exe', 'pwsh', 'powershell', 'cmd.exe', 'bash.exe', 'sh.exe']
|
|
36
|
+
: ['/bin/bash', 'bash', '/bin/sh', 'sh', '/bin/zsh', 'zsh'];
|
|
37
|
+
if (project.commandMode === 'allowlist') {
|
|
38
|
+
for (const allowed of project.commands) {
|
|
39
|
+
const base = path.basename(allowed).toLowerCase();
|
|
40
|
+
if (candidates.some(candidate => path.basename(candidate).toLowerCase() === base))
|
|
41
|
+
return allowed;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return process.platform === 'win32' ? 'powershell.exe' : 'sh';
|
|
45
|
+
}
|
|
46
|
+
function buildFramedScript(kind, token, command) {
|
|
47
|
+
if (kind === 'powershell') {
|
|
48
|
+
const encoded = Buffer.from(command, 'utf8').toString('base64');
|
|
49
|
+
return `[Console]::Out.WriteLine('__HA_B_'+'${token}__'); [Console]::Out.Flush(); $global:LASTEXITCODE=0; $__ha_ec=0; try { . ([ScriptBlock]::Create([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${encoded}')))); if (-not $?) { $__ha_ec = if ($LASTEXITCODE) { [int]$LASTEXITCODE } else { 1 } } elseif ($LASTEXITCODE) { $__ha_ec = [int]$LASTEXITCODE } } catch { [Console]::Error.WriteLine($_); $__ha_ec = 1 }; $__ha_cwd=[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($PWD.Path)); [Console]::Out.WriteLine('__HA_E_'+'${token}:'+$__ha_ec+':'+$__ha_cwd+'__'); [Console]::Out.Flush()\r\n`;
|
|
50
|
+
}
|
|
51
|
+
if (kind === 'cmd') {
|
|
52
|
+
return `@echo __HA_B_${token}__\r\n${command}\r\n@echo __HA_E_${token}:%ERRORLEVEL%:%CD%__\r\n`;
|
|
53
|
+
}
|
|
54
|
+
const singleQuoted = command.replace(/'/g, `'\\''`);
|
|
55
|
+
return `printf '__HA_B_%s__\\n' '${token}'\neval '${singleQuoted}'\n__ha_ec=$?\nprintf '\\n__HA_E_%s:%d:%s__\\n' '${token}' "$__ha_ec" "$(pwd)"\n`;
|
|
56
|
+
}
|
|
57
|
+
function parseFramedOutput(raw, kind, token) {
|
|
58
|
+
const normalized = raw.replace(/\r\n/g, '\n');
|
|
59
|
+
const beginMarker = `__HA_B_${token}__`;
|
|
60
|
+
const beginIndex = normalized.indexOf(beginMarker);
|
|
61
|
+
const contentStart = beginIndex >= 0
|
|
62
|
+
? (normalized[beginIndex + beginMarker.length] === '\n' ? beginIndex + beginMarker.length + 1 : beginIndex + beginMarker.length)
|
|
63
|
+
: 0;
|
|
64
|
+
const endRegex = new RegExp(`__HA_E_${token}:(-?\\d+):([^\\n]*?)__`);
|
|
65
|
+
const slice = normalized.slice(contentStart);
|
|
66
|
+
const match = endRegex.exec(slice);
|
|
67
|
+
if (!match) {
|
|
68
|
+
return { completed: false, output: slice, exitCode: null };
|
|
69
|
+
}
|
|
70
|
+
let output = slice.slice(0, match.index);
|
|
71
|
+
if (kind === 'posix' && output.endsWith('\n')) {
|
|
72
|
+
// Strip the leading newline injected before __HA_E_ when command output did not end with one, or preserve natural trailing newline.
|
|
73
|
+
output = output.slice(0, -1);
|
|
74
|
+
}
|
|
75
|
+
const exitCode = Number(match[1]);
|
|
76
|
+
let cwd = match[2].trim();
|
|
77
|
+
if (kind === 'powershell' && cwd) {
|
|
78
|
+
try {
|
|
79
|
+
cwd = Buffer.from(cwd, 'base64').toString('utf8');
|
|
80
|
+
}
|
|
81
|
+
catch { }
|
|
82
|
+
}
|
|
83
|
+
return { completed: true, output, exitCode, cwd: cwd || undefined };
|
|
84
|
+
}
|
|
85
|
+
export class Shells {
|
|
86
|
+
policy;
|
|
87
|
+
processes;
|
|
88
|
+
sessions = new Map();
|
|
89
|
+
constructor(policy, processes) {
|
|
90
|
+
this.policy = policy;
|
|
91
|
+
this.processes = processes;
|
|
92
|
+
}
|
|
93
|
+
async reconcile(session) {
|
|
94
|
+
const jobs = this.processes.list(session.owner, session.projectId);
|
|
95
|
+
const job = jobs.find(item => item.id === session.sessionId);
|
|
96
|
+
if (!job) {
|
|
97
|
+
this.sessions.delete(session.sessionId);
|
|
98
|
+
throw new AppError('unknown_shell', 'Shell session is not owned by this client and project');
|
|
99
|
+
}
|
|
100
|
+
if (session.pending) {
|
|
101
|
+
try {
|
|
102
|
+
const tail = this.processes.tail(session.owner, session.projectId, { processId: session.sessionId, cursor: session.pending.startCursor, length: 65536 });
|
|
103
|
+
const parsed = parseFramedOutput(tail.output, session.kind, session.pending.token);
|
|
104
|
+
if (parsed.completed) {
|
|
105
|
+
session.lastExitCode = parsed.exitCode;
|
|
106
|
+
if (parsed.cwd)
|
|
107
|
+
session.cwd = parsed.cwd;
|
|
108
|
+
session.pending = undefined;
|
|
109
|
+
}
|
|
110
|
+
else if (job.finished) {
|
|
111
|
+
session.lastExitCode = job.exitCode ?? null;
|
|
112
|
+
session.pending = undefined;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
if (job.finished)
|
|
117
|
+
session.pending = undefined;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return job;
|
|
121
|
+
}
|
|
122
|
+
ownedSession(owner, projectId, sessionId) {
|
|
123
|
+
const session = this.sessions.get(sessionId);
|
|
124
|
+
if (!session || session.owner !== owner || session.projectId !== projectId) {
|
|
125
|
+
throw new AppError('unknown_shell', 'Shell session is not owned by this client and project');
|
|
126
|
+
}
|
|
127
|
+
return session;
|
|
128
|
+
}
|
|
129
|
+
async start(project, owner, args, signal, authorization) {
|
|
130
|
+
const requested = args.shell ?? selectDefaultShell(project);
|
|
131
|
+
const alias = Object.hasOwn(project.commandAliases, requested) ? project.commandAliases[requested] : undefined;
|
|
132
|
+
const resolvedExecutable = alias?.executable ?? requested;
|
|
133
|
+
const kind = detectShellKind(resolvedExecutable);
|
|
134
|
+
const launchArgs = alias?.args?.length ? [] : defaultShellArgs(kind, resolvedExecutable);
|
|
135
|
+
const cwd = await this.policy.resolve(project, args.cwd);
|
|
136
|
+
const started = await this.processes.start(project, owner, { executable: requested, args: launchArgs, cwd: args.cwd, timeoutMs: args.timeoutMs, environment: args.environment }, signal, authorization);
|
|
137
|
+
const session = {
|
|
138
|
+
sessionId: started.id,
|
|
139
|
+
owner,
|
|
140
|
+
projectId: project.id,
|
|
141
|
+
shell: path.basename(resolvedExecutable),
|
|
142
|
+
kind,
|
|
143
|
+
cwd,
|
|
144
|
+
started: started.started,
|
|
145
|
+
lastExitCode: null,
|
|
146
|
+
};
|
|
147
|
+
this.sessions.set(session.sessionId, session);
|
|
148
|
+
return {
|
|
149
|
+
sessionId: session.sessionId,
|
|
150
|
+
processId: session.sessionId,
|
|
151
|
+
shell: session.shell,
|
|
152
|
+
kind: session.kind,
|
|
153
|
+
cwd: session.cwd,
|
|
154
|
+
state: started.state === 'running' || started.state === 'starting' ? 'ready' : started.state,
|
|
155
|
+
started: session.started,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
async run(project, owner, args, signal, authorization) {
|
|
159
|
+
if (args.command.includes('\0'))
|
|
160
|
+
throw new AppError('invalid_command', 'NUL is not permitted in shell commands');
|
|
161
|
+
let session;
|
|
162
|
+
let created = false;
|
|
163
|
+
if (args.sessionId) {
|
|
164
|
+
session = this.ownedSession(owner, project.id, args.sessionId);
|
|
165
|
+
const job = await this.reconcile(session);
|
|
166
|
+
if (job.finished)
|
|
167
|
+
throw new AppError('shell_finished', 'Shell session has already terminated; start a new shell session');
|
|
168
|
+
if (session.pending)
|
|
169
|
+
throw new AppError('shell_busy', 'Shell session is currently executing a command; wait for completion or stop_shell');
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
for (const candidate of this.sessions.values()) {
|
|
173
|
+
if (candidate.owner === owner && candidate.projectId === project.id) {
|
|
174
|
+
const job = await this.reconcile(candidate);
|
|
175
|
+
if (!job.finished && !candidate.pending && (!args.shell || candidate.shell.toLowerCase() === path.basename(args.shell).toLowerCase())) {
|
|
176
|
+
session = candidate;
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (!session) {
|
|
182
|
+
const started = await this.start(project, owner, { shell: args.shell, cwd: args.cwd, timeoutMs: args.timeoutMs, environment: args.environment }, signal, authorization);
|
|
183
|
+
session = this.ownedSession(owner, project.id, started.sessionId);
|
|
184
|
+
created = true;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const initialTail = this.processes.tail(owner, project.id, { processId: session.sessionId, length: 1 });
|
|
188
|
+
const startCursor = initialTail.nextCursor;
|
|
189
|
+
const token = randomUUID().replace(/-/g, '');
|
|
190
|
+
const script = buildFramedScript(session.kind, token, args.command);
|
|
191
|
+
session.pending = { token, startCursor, command: args.command };
|
|
192
|
+
try {
|
|
193
|
+
await this.processes.input(owner, project.id, { processId: session.sessionId, input: script, close: false });
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
session.pending = undefined;
|
|
197
|
+
throw error;
|
|
198
|
+
}
|
|
199
|
+
const deadline = Date.now() + args.waitMs;
|
|
200
|
+
let cursor = startCursor;
|
|
201
|
+
let collected = '';
|
|
202
|
+
while (true) {
|
|
203
|
+
const remaining = Math.max(0, deadline - Date.now());
|
|
204
|
+
const stepWait = Math.min(remaining, 20000);
|
|
205
|
+
const waited = await this.processes.wait(owner, project.id, {
|
|
206
|
+
processId: session.sessionId,
|
|
207
|
+
cursor,
|
|
208
|
+
length: 65536,
|
|
209
|
+
waitMs: stepWait,
|
|
210
|
+
until: 'output',
|
|
211
|
+
}, signal);
|
|
212
|
+
if (waited.output) {
|
|
213
|
+
const delta = waited.cursor > cursor ? waited.output : waited.output.slice(Math.max(0, cursor - waited.cursor));
|
|
214
|
+
collected += delta;
|
|
215
|
+
cursor = waited.nextCursor;
|
|
216
|
+
}
|
|
217
|
+
const parsed = parseFramedOutput(collected, session.kind, token);
|
|
218
|
+
if (parsed.completed) {
|
|
219
|
+
session.pending = undefined;
|
|
220
|
+
session.lastExitCode = parsed.exitCode;
|
|
221
|
+
if (parsed.cwd)
|
|
222
|
+
session.cwd = parsed.cwd;
|
|
223
|
+
return {
|
|
224
|
+
sessionId: session.sessionId,
|
|
225
|
+
processId: session.sessionId,
|
|
226
|
+
shell: session.shell,
|
|
227
|
+
created,
|
|
228
|
+
state: 'ready',
|
|
229
|
+
finished: true,
|
|
230
|
+
exitCode: parsed.exitCode,
|
|
231
|
+
cwd: session.cwd,
|
|
232
|
+
output: parsed.output,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
if (waited.finished) {
|
|
236
|
+
session.pending = undefined;
|
|
237
|
+
session.lastExitCode = waited.exitCode ?? null;
|
|
238
|
+
return {
|
|
239
|
+
sessionId: session.sessionId,
|
|
240
|
+
processId: session.sessionId,
|
|
241
|
+
shell: session.shell,
|
|
242
|
+
created,
|
|
243
|
+
state: waited.state,
|
|
244
|
+
finished: true,
|
|
245
|
+
exitCode: waited.exitCode ?? 0,
|
|
246
|
+
cwd: session.cwd,
|
|
247
|
+
output: parsed.output,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
if (Date.now() >= deadline) {
|
|
251
|
+
return {
|
|
252
|
+
sessionId: session.sessionId,
|
|
253
|
+
processId: session.sessionId,
|
|
254
|
+
shell: session.shell,
|
|
255
|
+
created,
|
|
256
|
+
state: 'running',
|
|
257
|
+
finished: false,
|
|
258
|
+
exitCode: null,
|
|
259
|
+
cwd: session.cwd,
|
|
260
|
+
output: parsed.output,
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
async list(owner, projectId) {
|
|
266
|
+
const items = [];
|
|
267
|
+
for (const session of [...this.sessions.values()]) {
|
|
268
|
+
if (session.owner !== owner || session.projectId !== projectId)
|
|
269
|
+
continue;
|
|
270
|
+
try {
|
|
271
|
+
const job = await this.reconcile(session);
|
|
272
|
+
items.push({
|
|
273
|
+
sessionId: session.sessionId,
|
|
274
|
+
processId: session.sessionId,
|
|
275
|
+
shell: session.shell,
|
|
276
|
+
kind: session.kind,
|
|
277
|
+
cwd: session.cwd,
|
|
278
|
+
state: job.finished ? job.state : (session.pending ? 'running' : 'ready'),
|
|
279
|
+
lastExitCode: session.lastExitCode,
|
|
280
|
+
started: session.started,
|
|
281
|
+
finished: Boolean(job.finished),
|
|
282
|
+
finishedAt: job.finished ?? null,
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
catch { }
|
|
286
|
+
}
|
|
287
|
+
return items.sort((a, b) => b.started - a.started);
|
|
288
|
+
}
|
|
289
|
+
async stop(owner, projectId, sessionId) {
|
|
290
|
+
const session = this.ownedSession(owner, projectId, sessionId);
|
|
291
|
+
session.pending = undefined;
|
|
292
|
+
await this.processes.stop(owner, projectId, sessionId);
|
|
293
|
+
const waited = await this.processes.wait(owner, projectId, { processId: sessionId, waitMs: 2000, until: 'finished', length: 1 }).catch(() => undefined);
|
|
294
|
+
const current = waited ?? this.processes.list(owner, projectId).find(item => item.id === sessionId);
|
|
295
|
+
return {
|
|
296
|
+
sessionId: session.sessionId,
|
|
297
|
+
processId: session.sessionId,
|
|
298
|
+
shell: session.shell,
|
|
299
|
+
cwd: session.cwd,
|
|
300
|
+
state: current?.state ?? 'stopped',
|
|
301
|
+
finished: Boolean(current?.finished ?? true),
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
//# sourceMappingURL=shells.js.map
|
package/dist/runner/tools.js
CHANGED
|
@@ -7,6 +7,8 @@ import { Git } from './git.js';
|
|
|
7
7
|
import { Editor } from './editor.js';
|
|
8
8
|
import { Context } from './context.js';
|
|
9
9
|
import { parseUnifiedDiff } from './patch.js';
|
|
10
|
+
import { Shells } from './shells.js';
|
|
11
|
+
import { Lsp } from './lsp.js';
|
|
10
12
|
/** Serialize each project's mutations so expected hashes and moves are meaningful across concurrent clients. */
|
|
11
13
|
export class Tools {
|
|
12
14
|
deviceId;
|
|
@@ -17,6 +19,8 @@ export class Tools {
|
|
|
17
19
|
git;
|
|
18
20
|
editor;
|
|
19
21
|
context;
|
|
22
|
+
shells;
|
|
23
|
+
lsp;
|
|
20
24
|
locks = new Map();
|
|
21
25
|
constructor(config, deviceId, consent) {
|
|
22
26
|
this.deviceId = deviceId;
|
|
@@ -27,6 +31,8 @@ export class Tools {
|
|
|
27
31
|
this.git = new Git(this.policy);
|
|
28
32
|
this.editor = new Editor(config, this.files);
|
|
29
33
|
this.context = new Context(config, this.files, this.git, this.processes);
|
|
34
|
+
this.shells = new Shells(this.policy, this.processes);
|
|
35
|
+
this.lsp = new Lsp(this.policy, this.files, this.git);
|
|
30
36
|
}
|
|
31
37
|
async invoke(name, input, principal, signal) {
|
|
32
38
|
let executionPolicy;
|
|
@@ -65,7 +71,8 @@ export class Tools {
|
|
|
65
71
|
}
|
|
66
72
|
case 'apply_unified_diff': {
|
|
67
73
|
const input = toolSchemas.apply_unified_diff.parse(args);
|
|
68
|
-
|
|
74
|
+
const parsed = await parseUnifiedDiff(this.files, project, input.diff, input.expectedSha256, { fuzz: input.fuzz, ignoreWhitespace: input.ignoreWhitespace });
|
|
75
|
+
return { ...await this.editor.edit(project, principal.id, parsed, input.dryRun, signal), relocatedHunks: parsed.relocatedHunks };
|
|
69
76
|
}
|
|
70
77
|
case 'get_edit_transactions': return this.editor.list(project, principal.id);
|
|
71
78
|
case 'recover_edit_transaction': return this.editor.recover(project, principal.id, toolSchemas.recover_edit_transaction.parse(args).transactionId);
|
|
@@ -101,11 +108,21 @@ export class Tools {
|
|
|
101
108
|
case 'write_process_input': return this.processes.input(principal.id, project.id, toolSchemas.write_process_input.parse(args));
|
|
102
109
|
case 'list_processes': return this.processes.list(principal.id, project.id);
|
|
103
110
|
case 'stop_process': return this.processes.stop(principal.id, project.id, toolSchemas.stop_process.parse(args).processId);
|
|
111
|
+
case 'start_shell': return this.shells.start(project, principal.id, toolSchemas.start_shell.parse(args), signal, executionAuthorization);
|
|
112
|
+
case 'run_shell': return this.shells.run(project, principal.id, toolSchemas.run_shell.parse(args), signal, executionAuthorization);
|
|
113
|
+
case 'list_shells': return this.shells.list(principal.id, project.id);
|
|
114
|
+
case 'stop_shell': return this.shells.stop(principal.id, project.id, toolSchemas.stop_shell.parse(args).sessionId);
|
|
115
|
+
case 'lsp_document_symbols': return this.lsp.documentSymbols(project, toolSchemas.lsp_document_symbols.parse(args));
|
|
116
|
+
case 'lsp_workspace_symbols': return this.lsp.workspaceSymbols(project, toolSchemas.lsp_workspace_symbols.parse(args), signal);
|
|
117
|
+
case 'lsp_definition': return this.lsp.definition(project, toolSchemas.lsp_definition.parse(args), signal);
|
|
118
|
+
case 'lsp_references': return this.lsp.references(project, toolSchemas.lsp_references.parse(args), signal);
|
|
119
|
+
case 'lsp_hover': return this.lsp.hover(project, toolSchemas.lsp_hover.parse(args), signal);
|
|
120
|
+
case 'lsp_diagnostics': return this.lsp.diagnostics(project, principal, toolSchemas.lsp_diagnostics.parse(args), signal);
|
|
104
121
|
default: return this.git.invoke(project, tool, args, signal);
|
|
105
122
|
}
|
|
106
123
|
};
|
|
107
124
|
const checkedExecute = async () => { const value = await execute(); guard(); return value; };
|
|
108
|
-
if (toolScope(tool) === 'read' || ['start_process', 'run_command', 'stop_process', 'write_process_input'].includes(tool))
|
|
125
|
+
if (toolScope(tool) === 'read' || ['start_process', 'run_command', 'stop_process', 'write_process_input', 'start_shell', 'run_shell', 'stop_shell'].includes(tool))
|
|
109
126
|
return result(await checkedExecute());
|
|
110
127
|
const prior = this.locks.get(project.id) ?? Promise.resolve();
|
|
111
128
|
const current = prior.catch(() => { }).then(checkedExecute);
|
package/dist/shared/protocol.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { remotePermissionsSchema } from './permissions.js';
|
|
3
3
|
import { assistContextSchema, assistDescriptorSchema, assistMultiDescriptorSchema, assistCleanupSchema, ASSIST_FEATURE, ASSIST_MULTI_FEATURE } from './assist.js';
|
|
4
|
-
export const VERSION = '0.4.
|
|
4
|
+
export const VERSION = '0.4.18';
|
|
5
5
|
export const RUNNER_PROTOCOL = 2;
|
|
6
6
|
export const MAX_FRAME = 2 * 1024 * 1024;
|
|
7
7
|
export const SCOPES = ['read', 'write', 'execute', 'git'];
|
package/dist/shared/tools.js
CHANGED
|
@@ -23,7 +23,7 @@ const schemas = {
|
|
|
23
23
|
save_project_note: z.object({ ...target, text: z.string().max(8192) }).strict(),
|
|
24
24
|
read_files: z.object({ ...target, files: z.array(z.object({ path: z.string().min(1).max(4096), startLine: z.number().int().min(1).default(1), endLine: z.number().int().min(1).optional(), expectedSha256: sha.optional() }).strict()).min(1).max(16), maxBytes: z.number().int().min(1024).max(262144).default(131072) }).strict(),
|
|
25
25
|
edit_files: z.object({ ...target, changes: z.array(change).min(1).max(32), dryRun: z.boolean().default(false) }).strict(),
|
|
26
|
-
apply_unified_diff: z.object({ ...target, diff: z.string().min(1).max(262144), expectedSha256: z.record(z.string(), sha.nullable()), dryRun: z.boolean().default(false) }).strict(),
|
|
26
|
+
apply_unified_diff: z.object({ ...target, diff: z.string().min(1).max(262144), expectedSha256: z.record(z.string(), sha.nullable()), dryRun: z.boolean().default(false), fuzz: z.number().int().min(0).max(200).default(20).describe('Maximum line offset for relocating hunks whose @@ line numbers are slightly off; 0 requires exact line numbers'), ignoreWhitespace: z.boolean().default(false).describe('Allow matching hunk context when only leading/trailing horizontal whitespace differs') }).strict(),
|
|
27
27
|
get_edit_transactions: z.object({ ...target }).strict(),
|
|
28
28
|
recover_edit_transaction: z.object({ ...target, transactionId: z.string().uuid() }).strict(),
|
|
29
29
|
list_directory: z.object({ ...target, path, offset: z.number().int().min(0).max(100000).default(0), limit: z.number().int().min(1).max(1000).default(200) }).strict(),
|
|
@@ -42,6 +42,16 @@ const schemas = {
|
|
|
42
42
|
write_process_input: z.object({ ...target, processId: z.string().uuid(), input: z.string().max(65536), close: z.boolean().default(false) }).strict(),
|
|
43
43
|
list_processes: z.object({ ...target }).strict(),
|
|
44
44
|
stop_process: z.object({ ...target, processId: z.string().uuid() }).strict(),
|
|
45
|
+
start_shell: z.object({ ...target, shell: z.string().min(1).max(4096).optional().describe('Shell executable or command alias; defaults to a permitted project shell or platform shell'), cwd: path, timeoutMs: z.number().int().min(100).max(86400000).default(3600000), environment: z.string().min(1).max(64).optional().describe('Administrator-configured environment profile name') }).strict(),
|
|
46
|
+
run_shell: z.object({ ...target, sessionId: z.string().uuid().optional().describe('Existing shell session ID; if omitted, reuses an idle session or starts a new one'), command: z.string().min(1).max(65536), shell: z.string().min(1).max(4096).optional(), cwd: path, timeoutMs: z.number().int().min(100).max(86400000).default(3600000), environment: z.string().min(1).max(64).optional(), waitMs: z.number().int().min(100).max(20000).default(20000) }).strict(),
|
|
47
|
+
list_shells: z.object({ ...target }).strict(),
|
|
48
|
+
stop_shell: z.object({ ...target, sessionId: z.string().uuid() }).strict(),
|
|
49
|
+
lsp_document_symbols: z.object({ ...target, path: z.string().min(1).max(4096) }).strict(),
|
|
50
|
+
lsp_workspace_symbols: z.object({ ...target, path, query: z.string().min(1).max(256).optional(), kind: z.enum(['class', 'interface', 'type', 'enum', 'function', 'method', 'property', 'constant', 'variable', 'struct', 'trait', 'impl', 'module']).optional(), exportedOnly: z.boolean().default(false), limit: z.number().int().min(1).max(500).default(100), respectGitIgnore: z.boolean().default(true) }).strict(),
|
|
51
|
+
lsp_definition: z.object({ ...target, path: z.string().min(1).max(4096), line: z.number().int().min(1).optional(), column: z.number().int().min(1).optional(), symbol: z.string().min(1).max(256).optional(), respectGitIgnore: z.boolean().default(true) }).strict(),
|
|
52
|
+
lsp_references: z.object({ ...target, path: z.string().min(1).max(4096), line: z.number().int().min(1).optional(), column: z.number().int().min(1).optional(), symbol: z.string().min(1).max(256).optional(), includeDeclaration: z.boolean().default(true), contextLines: z.number().int().min(0).max(5).default(0), limit: z.number().int().min(1).max(500).default(100), respectGitIgnore: z.boolean().default(true) }).strict(),
|
|
53
|
+
lsp_hover: z.object({ ...target, path: z.string().min(1).max(4096), line: z.number().int().min(1).optional(), column: z.number().int().min(1).optional(), symbol: z.string().min(1).max(256).optional(), respectGitIgnore: z.boolean().default(true) }).strict(),
|
|
54
|
+
lsp_diagnostics: z.object({ ...target, path: z.string().max(4096).optional(), limit: z.number().int().min(1).max(500).default(100), respectGitIgnore: z.boolean().default(true), serverExecutable: z.string().min(1).max(4096).optional().describe('Optional permitted stdio LSP server executable or alias'), serverArgs: z.array(z.string().max(4096)).max(64).default([]) }).strict(),
|
|
45
55
|
git_status: z.object({ ...gitTarget }).strict(),
|
|
46
56
|
git_diff: z.object({ ...gitTarget, staged: z.boolean().default(false), path: z.string().max(4096).optional() }).strict(),
|
|
47
57
|
git_log: z.object({ ...gitTarget, limit: z.number().int().min(1).max(100).default(20) }).strict(),
|
|
@@ -60,7 +70,7 @@ const descriptions = {
|
|
|
60
70
|
save_project_note: 'Save your bounded project handoff note for the next conversation. Note is tied to this client identity, project and local root; it grants no authority.',
|
|
61
71
|
read_files: 'Read up to 16 UTF-8 files by line range in one bounded call. Returns full-file SHA-256 for revision-fenced edits, per-file errors and nextStartLine.',
|
|
62
72
|
edit_files: 'Preflight a batch of explicit create/replace/exact-edit/delete operations. Existing files require SHA-256. Uses a durable journal and conflict-aware rollback; dryRun previews without writes. Not filesystem snapshot isolation.',
|
|
63
|
-
apply_unified_diff: 'Apply a
|
|
73
|
+
apply_unified_diff: 'Apply a textual unified diff (---/+++/@@) through the journaled editor. Every path requires its expected SHA-256, or null for creation. Supports bounded fuzzy hunk relocation (fuzz) and optional whitespace tolerance while rejecting ambiguous or stale contexts.',
|
|
64
74
|
get_edit_transactions: 'List your recent edit receipts and unresolved recovery transactions for this project; does not expose backup contents.',
|
|
65
75
|
recover_edit_transaction: 'Recover your interrupted edit batch. Restores only paths still matching transaction after-images; refuses to overwrite external changes.',
|
|
66
76
|
list_directory: 'List a project directory in bounded live pages using nextOffset. Concurrent directory changes can shift entries.',
|
|
@@ -79,6 +89,16 @@ const descriptions = {
|
|
|
79
89
|
write_process_input: 'Send text to a tracked process stdin, optionally closing it.',
|
|
80
90
|
list_processes: 'List your tracked processes for this project.',
|
|
81
91
|
stop_process: 'Terminate a tracked process and its process tree.',
|
|
92
|
+
start_shell: 'Start a persistent stateful shell session (preserving working directory and shell variables across commands) supervised by the Runner process manager. Requires a permitted shell executable or alias.',
|
|
93
|
+
run_shell: 'Execute a command inside a persistent shell session (or auto-start/reuse one), wait for command completion and return its isolated output, exitCode and updated cwd while keeping the shell alive.',
|
|
94
|
+
list_shells: 'List your persistent shell sessions for this project, including current working directory and ready/running state.',
|
|
95
|
+
stop_shell: 'Terminate a persistent shell session and its supervised process tree.',
|
|
96
|
+
lsp_document_symbols: 'Extract structured symbols (classes, interfaces, functions, methods, types, constants) and module imports from a project source file.',
|
|
97
|
+
lsp_workspace_symbols: 'Search symbol definitions across the project workspace by name and kind, respecting .gitignore and directory policies.',
|
|
98
|
+
lsp_definition: 'Locate the definition of a symbol at a 1-based line/column or by name, resolving local declarations, relative/module imports and workspace exports.',
|
|
99
|
+
lsp_references: 'Find identifier-boundary references to a symbol across the project workspace, distinguishing declarations and imports.',
|
|
100
|
+
lsp_hover: 'Inspect the declaration signature, documentation comment, symbol kind and definition preview for a symbol at a 1-based line/column or by name.',
|
|
101
|
+
lsp_diagnostics: 'Collect syntax, import-resolution and TypeScript/LSP diagnostics for a file or project. Optionally queries a permitted stdio LSP server.',
|
|
82
102
|
git_status: 'Read Git porcelain status.',
|
|
83
103
|
git_diff: 'Read bounded working tree or staged Git diff.',
|
|
84
104
|
git_log: 'Read recent commits.',
|
|
@@ -94,7 +114,7 @@ const descriptions = {
|
|
|
94
114
|
export function toolScope(name) {
|
|
95
115
|
if (['write_file', 'create_directory', 'move_file', 'edit_block', 'edit_files', 'apply_unified_diff', 'recover_edit_transaction', 'save_project_note'].includes(name))
|
|
96
116
|
return 'write';
|
|
97
|
-
if (['start_process', 'run_command', 'write_process_input', 'stop_process'].includes(name))
|
|
117
|
+
if (['start_process', 'run_command', 'write_process_input', 'stop_process', 'start_shell', 'run_shell', 'stop_shell'].includes(name))
|
|
98
118
|
return 'execute';
|
|
99
119
|
if (['git_add', 'git_commit', 'git_commit_paths', 'git_switch_branch', 'git_fetch', 'git_pull', 'git_push'].includes(name))
|
|
100
120
|
return 'git';
|
|
@@ -103,6 +123,6 @@ export function toolScope(name) {
|
|
|
103
123
|
export const toolDefinitions = Object.entries(schemas).map(([name, schema]) => ({
|
|
104
124
|
name, description: descriptions[name],
|
|
105
125
|
inputSchema: z.toJSONSchema(schema, { target: 'draft-7' }),
|
|
106
|
-
annotations: { readOnlyHint: toolScope(name) === 'read', destructiveHint: toolScope(name) !== 'read', idempotentHint: false, openWorldHint: ['start_process', 'run_command', 'write_process_input', 'git_fetch', 'git_pull', 'git_push'].includes(name) },
|
|
126
|
+
annotations: { readOnlyHint: toolScope(name) === 'read', destructiveHint: toolScope(name) !== 'read', idempotentHint: false, openWorldHint: ['start_process', 'run_command', 'write_process_input', 'start_shell', 'run_shell', 'git_fetch', 'git_pull', 'git_push'].includes(name) },
|
|
107
127
|
}));
|
|
108
128
|
//# sourceMappingURL=tools.js.map
|