@nathapp/nax-agent 0.91.6 → 0.91.7-canary.10
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 +40 -0
- package/dist/coding-tools/coding-tool-extras.d.ts +52 -0
- package/dist/coding-tools/coding-tool-extras.js +56 -0
- package/dist/coding-tools/coding-tool-support.d.ts +9 -0
- package/dist/coding-tools/coding-tool-support.js +12 -1
- package/dist/config/catalog-overrides.d.ts +9 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -1
- package/dist/internal/argv-exec.d.ts +6 -0
- package/dist/internal/argv-exec.js +158 -63
- package/dist/mcp/connect.js +26 -3
- package/dist/mcp/types.d.ts +7 -0
- package/dist/native/adapter-deps.d.ts +2 -0
- package/dist/native/adapter-deps.js +2 -0
- package/dist/native/models.js +2 -0
- package/dist/native/session/loop-events/types.d.ts +5 -0
- package/dist/native/session-adapter.js +19 -5
- package/dist/permissions/approval-memory.d.ts +18 -0
- package/dist/permissions/approval-memory.js +88 -0
- package/dist/permissions/index.d.ts +1 -0
- package/dist/permissions/index.js +1 -0
- package/dist/permissions/types.d.ts +6 -0
- package/dist/runtime/node-runtime.js +5 -0
- package/dist/sandbox/claude-settings.d.ts +2 -1
- package/dist/sandbox/claude-settings.js +7 -3
- package/dist/sandbox/defaults.js +1 -0
- package/dist/sandbox/launcher.js +7 -0
- package/dist/sandbox/types.d.ts +6 -0
- package/dist/session/agent-session-command.d.ts +19 -0
- package/dist/session/agent-session-command.js +38 -0
- package/dist/session/agent-session-types.d.ts +26 -0
- package/dist/session/agent-session.js +86 -1
- package/dist/session/native-backend-options.d.ts +37 -2
- package/dist/session/native-backend-options.js +39 -3
- package/dist/session/native-backend.js +55 -5
- package/dist/session/native-posture-rules.d.ts +18 -0
- package/dist/session/native-posture-rules.js +33 -0
- package/dist/session/session-ask-link.d.ts +6 -0
- package/dist/session/session-ask-link.js +5 -0
- package/dist/session/session-ask-port.js +4 -0
- package/dist/session/session-backend.d.ts +23 -1
- package/dist/session/session-interaction.d.ts +2 -0
- package/dist/session/session-interaction.js +8 -1
- package/dist/session/session-tool-support.d.ts +49 -3
- package/dist/session/session-tool-support.js +66 -11
- package/dist/session-store/index.d.ts +3 -0
- package/dist/session-store/index.js +3 -0
- package/dist/session-store/session-lock-guard.d.ts +6 -0
- package/dist/session-store/session-lock-guard.js +85 -0
- package/dist/session-store/session-lock.d.ts +39 -0
- package/dist/session-store/session-lock.js +178 -0
- package/dist/session-store/session-meta.d.ts +27 -0
- package/dist/session-store/session-meta.js +20 -0
- package/dist/session-store/storage.d.ts +39 -0
- package/dist/session-store/storage.js +164 -0
- package/dist/tools/ask-request.d.ts +18 -0
- package/dist/tools/ask-request.js +30 -0
- package/dist/tools/bash-background.d.ts +74 -0
- package/dist/tools/bash-background.js +151 -0
- package/dist/tools/bash.d.ts +11 -0
- package/dist/tools/bash.js +77 -17
- package/dist/tools/git.js +10 -3
- package/dist/tools/policy-match.d.ts +2 -2
- package/dist/tools/policy-match.js +9 -6
- package/dist/tools/policy-paths-branch.js +4 -1
- package/dist/tools/provider-advertise.d.ts +7 -0
- package/dist/tools/provider-advertise.js +13 -1
- package/dist/tools/provider-types.d.ts +6 -0
- package/dist/tools/run-command-exec.js +12 -0
- package/dist/tools/run-command-surface.d.ts +28 -0
- package/dist/tools/run-command-surface.js +109 -0
- package/dist/tools/run-command.d.ts +17 -16
- package/dist/tools/run-command.js +48 -68
- package/dist/tools/runtime-calltool.d.ts +101 -0
- package/dist/tools/runtime-calltool.js +112 -3
- package/dist/tools/runtime.d.ts +12 -0
- package/dist/tools/runtime.js +36 -18
- package/dist/tools/types.d.ts +8 -0
- package/package.json +3 -3
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session files beside the S3 transcript (S5 spec §5.1): `<id>.session.json`
|
|
3
|
+
* metadata, written as a temp file then renamed, and `<id>.lock`, created
|
|
4
|
+
* exclusively. Nonce-owned locks use heartbeats to detect stale live pids;
|
|
5
|
+
* legacy locks remain pid-based. Listing scans the metadata files.
|
|
6
|
+
* Files that cannot be read are never rewritten or deleted here.
|
|
7
|
+
*/
|
|
8
|
+
import { mkdir, mkdtemp, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { errorMessage } from "#src/infra/errors";
|
|
11
|
+
import { NaxError } from "#src/infra/nax-error";
|
|
12
|
+
import { acquireSessionLock, holderState, readSessionLock, } from "./session-lock.js";
|
|
13
|
+
import { MetaSchema } from "./session-meta.js";
|
|
14
|
+
export { LOCK_HEARTBEAT_MS, LOCK_STALE_MS } from "./session-lock.js";
|
|
15
|
+
export const LIST_PAGE_SIZE = 50;
|
|
16
|
+
const META_SUFFIX = ".session.json";
|
|
17
|
+
function codeOf(error) {
|
|
18
|
+
return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
|
|
19
|
+
? error.code
|
|
20
|
+
: undefined;
|
|
21
|
+
}
|
|
22
|
+
/** Signal 0 checks existence only. EPERM means the process exists under another user. */
|
|
23
|
+
export function processAlive(pid) {
|
|
24
|
+
try {
|
|
25
|
+
process.kill(pid, 0);
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
return codeOf(error) === "EPERM";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function unreadable(sessionId, reason) {
|
|
33
|
+
return new NaxError(`session metadata for "${sessionId}" is unreadable: ${reason}`, "SESSION_META_UNREADABLE", {
|
|
34
|
+
stage: "session-store",
|
|
35
|
+
sessionId,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
function encodeCursor(offset) {
|
|
39
|
+
return Buffer.from(String(offset), "utf8").toString("base64");
|
|
40
|
+
}
|
|
41
|
+
function decodeCursor(cursor) {
|
|
42
|
+
if (cursor === undefined || cursor === null || cursor === "")
|
|
43
|
+
return 0;
|
|
44
|
+
const text = Buffer.from(cursor, "base64").toString("utf8");
|
|
45
|
+
const offset = Number(text);
|
|
46
|
+
if (!/^\d+$/.test(text) || !Number.isSafeInteger(offset))
|
|
47
|
+
throw new NaxError("invalid cursor", "SESSION_LIST_CURSOR_INVALID", { stage: "session-store" });
|
|
48
|
+
return offset;
|
|
49
|
+
}
|
|
50
|
+
const sortKey = (meta) => meta.updatedAt ?? meta.createdAt;
|
|
51
|
+
function infoOf(meta) {
|
|
52
|
+
return { sessionId: meta.sessionId, cwd: meta.cwd, title: meta.title, updatedAt: sortKey(meta) };
|
|
53
|
+
}
|
|
54
|
+
export function createSessionStorage(deps) {
|
|
55
|
+
const isAlive = deps.isAlive ?? processAlive;
|
|
56
|
+
const metaPath = (id) => join(deps.dir, `${id}${META_SUFFIX}`);
|
|
57
|
+
const lockPath = (id) => join(deps.dir, `${id}.lock`);
|
|
58
|
+
async function readMeta(sessionId) {
|
|
59
|
+
let text;
|
|
60
|
+
try {
|
|
61
|
+
text = await readFile(metaPath(sessionId), "utf8");
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (codeOf(error) === "ENOENT")
|
|
65
|
+
return null;
|
|
66
|
+
throw unreadable(sessionId, errorMessage(error));
|
|
67
|
+
}
|
|
68
|
+
let json;
|
|
69
|
+
try {
|
|
70
|
+
json = JSON.parse(text);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
throw unreadable(sessionId, "invalid JSON");
|
|
74
|
+
}
|
|
75
|
+
const version = typeof json === "object" && json !== null && "schemaVersion" in json ? json.schemaVersion : undefined;
|
|
76
|
+
if (version !== 1)
|
|
77
|
+
throw unreadable(sessionId, `schemaVersion ${String(version)}; this build reads 1`);
|
|
78
|
+
const parsed = MetaSchema.safeParse(json);
|
|
79
|
+
if (!parsed.success)
|
|
80
|
+
throw unreadable(sessionId, parsed.error.issues[0]?.message ?? "bad shape");
|
|
81
|
+
return parsed.data;
|
|
82
|
+
}
|
|
83
|
+
async function acquireLock(sessionId) {
|
|
84
|
+
await mkdir(deps.dir, { recursive: true });
|
|
85
|
+
return acquireSessionLock(lockPath(sessionId), deps, isAlive);
|
|
86
|
+
}
|
|
87
|
+
async function list(query) {
|
|
88
|
+
const offset = decodeCursor(query.cursor);
|
|
89
|
+
let names;
|
|
90
|
+
try {
|
|
91
|
+
names = await readdir(deps.dir);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (codeOf(error) === "ENOENT")
|
|
95
|
+
return { sessions: [] };
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
const metas = [];
|
|
99
|
+
for (const name of names.filter((n) => n.endsWith(META_SUFFIX))) {
|
|
100
|
+
try {
|
|
101
|
+
const meta = await readMeta(name.slice(0, -META_SUFFIX.length));
|
|
102
|
+
if (meta !== null)
|
|
103
|
+
metas.push(meta);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
deps.logger.warn("session", "skipping unreadable session metadata", { file: name, error: errorMessage(error) });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const matching = metas
|
|
110
|
+
.filter((meta) => query.cwd === undefined || query.cwd === null || meta.cwd === query.cwd)
|
|
111
|
+
.sort((a, b) => sortKey(b).localeCompare(sortKey(a)));
|
|
112
|
+
const end = offset + LIST_PAGE_SIZE;
|
|
113
|
+
return {
|
|
114
|
+
sessions: matching.slice(offset, end).map(infoOf),
|
|
115
|
+
...(end < matching.length ? { nextCursor: encodeCursor(end) } : {}),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
dir: deps.dir,
|
|
120
|
+
readMeta,
|
|
121
|
+
async writeMeta(meta) {
|
|
122
|
+
await mkdir(deps.dir, { recursive: true });
|
|
123
|
+
const path = metaPath(meta.sessionId);
|
|
124
|
+
// An exclusively created directory owns this write's temp file, even when
|
|
125
|
+
// another storage instance in the same process writes the same session.
|
|
126
|
+
const tempDir = await mkdtemp(`${path}.${deps.pid}.`);
|
|
127
|
+
try {
|
|
128
|
+
const temp = join(tempDir, "metadata.tmp");
|
|
129
|
+
await writeFile(temp, `${JSON.stringify(meta, null, 2)}\n`);
|
|
130
|
+
await rename(temp, path);
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
await rm(tempDir, { recursive: true, force: true });
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
async hasMeta(sessionId) {
|
|
137
|
+
try {
|
|
138
|
+
await stat(metaPath(sessionId));
|
|
139
|
+
return true;
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
if (codeOf(error) === "ENOENT")
|
|
143
|
+
return false;
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
async removeMeta(sessionId) {
|
|
148
|
+
await rm(metaPath(sessionId), { force: true });
|
|
149
|
+
},
|
|
150
|
+
acquireLock,
|
|
151
|
+
async readLockHolder(sessionId) {
|
|
152
|
+
const { body } = readSessionLock(lockPath(sessionId));
|
|
153
|
+
if (body === undefined)
|
|
154
|
+
return null;
|
|
155
|
+
return {
|
|
156
|
+
pid: body.pid,
|
|
157
|
+
startedAt: body.startedAt,
|
|
158
|
+
heartbeatAt: body.heartbeatAt ?? null,
|
|
159
|
+
state: holderState(body, deps, isAlive),
|
|
160
|
+
};
|
|
161
|
+
},
|
|
162
|
+
list,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
@@ -25,6 +25,24 @@ export interface AskSummary {
|
|
|
25
25
|
* what approval needs; the payload is what the audit sink already holds.
|
|
26
26
|
*/
|
|
27
27
|
export declare function askSummary(tool: string, scope: ToolScope, input: Record<string, unknown>): AskSummary;
|
|
28
|
+
/**
|
|
29
|
+
* The reason clause an unsandboxed approval carries (US-004).
|
|
30
|
+
*
|
|
31
|
+
* The reason is model-authored and travels to a human, so it is masked through
|
|
32
|
+
* `maskForPrompt` and cut to `MAX_ASK_SUMMARY_CHARS` — in that order, for the
|
|
33
|
+
* same reason `askSummary` masks before it cuts: cutting first can split a
|
|
34
|
+
* secret so that no pattern matches what is left. A reason whose masked form
|
|
35
|
+
* would hide shell syntax is WITHHELD rather than denying the ask (the command
|
|
36
|
+
* itself is already vetted by `askSummary`); the person still learns the call
|
|
37
|
+
* wants to run outside the sandbox, which is the fact the suffix exists for.
|
|
38
|
+
*
|
|
39
|
+
* A blank or whitespace-only reason takes the SAME fallback as an absent one:
|
|
40
|
+
* the model wrote nothing that could explain anything, and the approver must
|
|
41
|
+
* never be shown the dangling clause the prefix alone renders.
|
|
42
|
+
*/
|
|
43
|
+
export declare function unsandboxedReasonSuffix(input: {
|
|
44
|
+
readonly unsandboxedReason?: unknown;
|
|
45
|
+
}): string;
|
|
28
46
|
/**
|
|
29
47
|
* The reason a `denied:ask` ledger row carries, chosen by WHO refused.
|
|
30
48
|
*
|
|
@@ -37,6 +37,36 @@ export function askSummary(tool, scope, input) {
|
|
|
37
37
|
return { summary: `${tool} [arguments withheld: contains a secret]`, unshowable: true };
|
|
38
38
|
return { summary: masked.masked.slice(0, MAX_ASK_SUMMARY_CHARS), unshowable: false };
|
|
39
39
|
}
|
|
40
|
+
/** The clause `unsandboxedReasonSuffix` renders, before the reason itself. */
|
|
41
|
+
const UNSANDBOXED_PREFIX = " -- runs OUTSIDE the sandbox: ";
|
|
42
|
+
/** What the suffix says when the model gave no usable reason. */
|
|
43
|
+
const NO_REASON = "no reason given";
|
|
44
|
+
/** What the suffix says instead of a reason that cannot be shown safely. */
|
|
45
|
+
const REASON_WITHHELD = "reason withheld";
|
|
46
|
+
/**
|
|
47
|
+
* The reason clause an unsandboxed approval carries (US-004).
|
|
48
|
+
*
|
|
49
|
+
* The reason is model-authored and travels to a human, so it is masked through
|
|
50
|
+
* `maskForPrompt` and cut to `MAX_ASK_SUMMARY_CHARS` — in that order, for the
|
|
51
|
+
* same reason `askSummary` masks before it cuts: cutting first can split a
|
|
52
|
+
* secret so that no pattern matches what is left. A reason whose masked form
|
|
53
|
+
* would hide shell syntax is WITHHELD rather than denying the ask (the command
|
|
54
|
+
* itself is already vetted by `askSummary`); the person still learns the call
|
|
55
|
+
* wants to run outside the sandbox, which is the fact the suffix exists for.
|
|
56
|
+
*
|
|
57
|
+
* A blank or whitespace-only reason takes the SAME fallback as an absent one:
|
|
58
|
+
* the model wrote nothing that could explain anything, and the approver must
|
|
59
|
+
* never be shown the dangling clause the prefix alone renders.
|
|
60
|
+
*/
|
|
61
|
+
export function unsandboxedReasonSuffix(input) {
|
|
62
|
+
const raw = input.unsandboxedReason;
|
|
63
|
+
if (typeof raw !== "string" || raw.trim() === "")
|
|
64
|
+
return `${UNSANDBOXED_PREFIX}${NO_REASON}`;
|
|
65
|
+
const masked = maskForPrompt(raw);
|
|
66
|
+
if (!masked.ok)
|
|
67
|
+
return `${UNSANDBOXED_PREFIX}${REASON_WITHHELD}`;
|
|
68
|
+
return `${UNSANDBOXED_PREFIX}${masked.masked.slice(0, MAX_ASK_SUMMARY_CHARS)}`;
|
|
69
|
+
}
|
|
40
70
|
/**
|
|
41
71
|
* The reason a `denied:ask` ledger row carries, chosen by WHO refused.
|
|
42
72
|
*
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { RunArgvOptions } from "#src/internal/argv-exec";
|
|
2
|
+
export type BackgroundStream = "stdout" | "stderr";
|
|
3
|
+
export interface BackgroundCommandEnd {
|
|
4
|
+
readonly exitCode: number;
|
|
5
|
+
readonly timedOut: boolean;
|
|
6
|
+
readonly aborted: boolean;
|
|
7
|
+
/** Present when the launch itself failed. */
|
|
8
|
+
readonly launchError?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface BackgroundCommandHandle {
|
|
11
|
+
readonly command: string;
|
|
12
|
+
readonly description?: string;
|
|
13
|
+
readonly origin: "agent" | "moved";
|
|
14
|
+
/** Always resolves, including on launch failure. */
|
|
15
|
+
readonly ended: Promise<BackgroundCommandEnd>;
|
|
16
|
+
/** Immediately aborts the launch, SIGKILLing its process group. */
|
|
17
|
+
stop(): void;
|
|
18
|
+
}
|
|
19
|
+
export interface BackgroundCommandSink {
|
|
20
|
+
readonly id: string;
|
|
21
|
+
append(stream: BackgroundStream, chunk: Uint8Array): void;
|
|
22
|
+
}
|
|
23
|
+
export interface ForegroundCommand {
|
|
24
|
+
readonly command: string;
|
|
25
|
+
moveToBackground(): void;
|
|
26
|
+
}
|
|
27
|
+
export interface BackgroundCommandPort {
|
|
28
|
+
adopt(handle: BackgroundCommandHandle): BackgroundCommandSink;
|
|
29
|
+
/** Register a foreground call; the returned function unregisters it. */
|
|
30
|
+
foreground(call: ForegroundCommand): () => void;
|
|
31
|
+
}
|
|
32
|
+
export type BackgroundLaunchOptions = Pick<RunArgvOptions, "signal" | "releaseDeadline" | "onOutput">;
|
|
33
|
+
/** The newest raw output retained while a foreground call can still be moved. */
|
|
34
|
+
export declare const FOREGROUND_REPLAY_BYTES: number;
|
|
35
|
+
type BackgroundResult = {
|
|
36
|
+
content: string;
|
|
37
|
+
isError: false;
|
|
38
|
+
};
|
|
39
|
+
interface LaunchResult {
|
|
40
|
+
readonly launched: {
|
|
41
|
+
readonly exitCode: number;
|
|
42
|
+
readonly timedOut: boolean;
|
|
43
|
+
readonly aborted?: boolean;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
interface BashExecutionRequest<T extends LaunchResult> {
|
|
47
|
+
readonly port?: BackgroundCommandPort;
|
|
48
|
+
readonly runInBackground: unknown;
|
|
49
|
+
readonly command: string;
|
|
50
|
+
readonly description: unknown;
|
|
51
|
+
readonly signal?: AbortSignal;
|
|
52
|
+
readonly launch: (options?: BackgroundLaunchOptions, isForeground?: () => boolean) => Promise<T>;
|
|
53
|
+
}
|
|
54
|
+
/** Keep framing in Bash, but keep all ownership and early-return logic here. */
|
|
55
|
+
export declare function runBashWithBackground<T extends LaunchResult>(request: BashExecutionRequest<T>): Promise<T | BackgroundResult>;
|
|
56
|
+
export declare function withBackgroundSentence(description: string, port?: BackgroundCommandPort): string;
|
|
57
|
+
/** Adopt before launching so even the first output chunk has a sink. */
|
|
58
|
+
export declare function startBashBackground(request: {
|
|
59
|
+
readonly port?: BackgroundCommandPort;
|
|
60
|
+
readonly runInBackground: unknown;
|
|
61
|
+
readonly command: string;
|
|
62
|
+
readonly description: unknown;
|
|
63
|
+
readonly launch: (options: BackgroundLaunchOptions) => Promise<{
|
|
64
|
+
readonly launched: {
|
|
65
|
+
readonly exitCode: number;
|
|
66
|
+
readonly timedOut: boolean;
|
|
67
|
+
readonly aborted?: boolean;
|
|
68
|
+
};
|
|
69
|
+
}>;
|
|
70
|
+
}): {
|
|
71
|
+
content: string;
|
|
72
|
+
isError: false;
|
|
73
|
+
} | undefined;
|
|
74
|
+
export {};
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { errorMessage } from "#src/infra/errors";
|
|
2
|
+
/** The newest raw output retained while a foreground call can still be moved. */
|
|
3
|
+
export const FOREGROUND_REPLAY_BYTES = 1024 * 1024;
|
|
4
|
+
/** Keep framing in Bash, but keep all ownership and early-return logic here. */
|
|
5
|
+
export async function runBashWithBackground(request) {
|
|
6
|
+
const background = startBashBackground(request);
|
|
7
|
+
if (background !== undefined)
|
|
8
|
+
return background;
|
|
9
|
+
if (request.port === undefined)
|
|
10
|
+
return request.launch();
|
|
11
|
+
return runMovableForeground({ ...request, port: request.port });
|
|
12
|
+
}
|
|
13
|
+
function outputReplay() {
|
|
14
|
+
let chunks = [];
|
|
15
|
+
let bytes = 0;
|
|
16
|
+
let sink;
|
|
17
|
+
let replaying = false;
|
|
18
|
+
return {
|
|
19
|
+
append(stream, chunk) {
|
|
20
|
+
if (sink !== undefined)
|
|
21
|
+
return sink.append(stream, chunk);
|
|
22
|
+
if (chunk.byteLength === 0)
|
|
23
|
+
return;
|
|
24
|
+
const tail = replaying ? chunk : chunk.subarray(-FOREGROUND_REPLAY_BYTES);
|
|
25
|
+
// Copy even Buffer inputs: Buffer.slice retains the original backing allocation.
|
|
26
|
+
chunks.push({ stream, chunk: Uint8Array.from(tail) });
|
|
27
|
+
bytes += tail.byteLength;
|
|
28
|
+
while (!replaying && bytes > FOREGROUND_REPLAY_BYTES) {
|
|
29
|
+
const first = chunks[0];
|
|
30
|
+
if (first === undefined)
|
|
31
|
+
break;
|
|
32
|
+
const dropped = Math.min(first.chunk.byteLength, bytes - FOREGROUND_REPLAY_BYTES);
|
|
33
|
+
bytes -= dropped;
|
|
34
|
+
if (dropped === first.chunk.byteLength)
|
|
35
|
+
chunks.shift();
|
|
36
|
+
else
|
|
37
|
+
first.chunk = first.chunk.slice(dropped);
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
replay(target) {
|
|
41
|
+
// Drain before switching to live forwarding, including any reentrant appends.
|
|
42
|
+
replaying = true;
|
|
43
|
+
for (const item of chunks)
|
|
44
|
+
target.append(item.stream, item.chunk);
|
|
45
|
+
chunks = [];
|
|
46
|
+
bytes = 0;
|
|
47
|
+
sink = target;
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function commandEnd(result) {
|
|
52
|
+
return {
|
|
53
|
+
exitCode: result.launched.exitCode,
|
|
54
|
+
timedOut: result.launched.timedOut,
|
|
55
|
+
aborted: result.launched.aborted === true,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function failedEnd(error) {
|
|
59
|
+
return { exitCode: -1, timedOut: false, aborted: false, launchError: errorMessage(error) };
|
|
60
|
+
}
|
|
61
|
+
function foregroundControl(request) {
|
|
62
|
+
const controller = new AbortController();
|
|
63
|
+
const releaseDeadline = new AbortController();
|
|
64
|
+
const released = Promise.withResolvers();
|
|
65
|
+
const ended = Promise.withResolvers();
|
|
66
|
+
const output = outputReplay();
|
|
67
|
+
let settled = false;
|
|
68
|
+
let moved = false;
|
|
69
|
+
const cancel = () => controller.abort();
|
|
70
|
+
const detach = () => request.signal?.removeEventListener("abort", cancel);
|
|
71
|
+
request.signal?.addEventListener("abort", cancel, { once: true });
|
|
72
|
+
if (request.signal?.aborted === true)
|
|
73
|
+
cancel();
|
|
74
|
+
const call = {
|
|
75
|
+
command: request.command,
|
|
76
|
+
moveToBackground() {
|
|
77
|
+
if (settled || moved)
|
|
78
|
+
return;
|
|
79
|
+
moved = true;
|
|
80
|
+
releaseDeadline.abort();
|
|
81
|
+
detach();
|
|
82
|
+
const sink = request.port.adopt({
|
|
83
|
+
command: request.command,
|
|
84
|
+
...(typeof request.description === "string" ? { description: request.description } : {}),
|
|
85
|
+
origin: "moved",
|
|
86
|
+
ended: ended.promise,
|
|
87
|
+
stop: cancel,
|
|
88
|
+
});
|
|
89
|
+
output.replay(sink);
|
|
90
|
+
released.resolve({ content: `moved to the background as ${sink.id}`, isError: false });
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
return {
|
|
94
|
+
call,
|
|
95
|
+
released: released.promise,
|
|
96
|
+
options: { signal: controller.signal, releaseDeadline: releaseDeadline.signal, onOutput: output.append },
|
|
97
|
+
isForeground: () => !moved,
|
|
98
|
+
finish(end) {
|
|
99
|
+
settled = true;
|
|
100
|
+
ended.resolve(end);
|
|
101
|
+
},
|
|
102
|
+
detach,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
async function runMovableForeground(request) {
|
|
106
|
+
const control = foregroundControl(request);
|
|
107
|
+
const unregister = request.port.foreground(control.call);
|
|
108
|
+
const launch = Promise.resolve().then(() => request.launch(control.options, control.isForeground));
|
|
109
|
+
// Observe both outcomes even after the race releases the foreground tool result.
|
|
110
|
+
void launch.then((result) => control.finish(commandEnd(result)), (error) => control.finish(failedEnd(error)));
|
|
111
|
+
try {
|
|
112
|
+
return await Promise.race([launch, control.released]);
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
control.detach();
|
|
116
|
+
unregister();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
export function withBackgroundSentence(description, port) {
|
|
120
|
+
if (port === undefined)
|
|
121
|
+
return description;
|
|
122
|
+
const separator = description.endsWith(" ") ? "" : " ";
|
|
123
|
+
return `${description}${separator}Set "runInBackground": true to return at once with a task id; a notice arrives when the command ends.`;
|
|
124
|
+
}
|
|
125
|
+
/** Adopt before launching so even the first output chunk has a sink. */
|
|
126
|
+
export function startBashBackground(request) {
|
|
127
|
+
if (request.port === undefined || request.runInBackground !== true)
|
|
128
|
+
return undefined;
|
|
129
|
+
const controller = new AbortController();
|
|
130
|
+
const completion = Promise.withResolvers();
|
|
131
|
+
const sink = request.port.adopt({
|
|
132
|
+
command: request.command,
|
|
133
|
+
...(typeof request.description === "string" ? { description: request.description } : {}),
|
|
134
|
+
origin: "agent",
|
|
135
|
+
ended: completion.promise,
|
|
136
|
+
stop: () => controller.abort(),
|
|
137
|
+
});
|
|
138
|
+
// The promise boundary also settles synchronous launch failures without rejection.
|
|
139
|
+
void Promise.resolve()
|
|
140
|
+
.then(() => request.launch({
|
|
141
|
+
signal: controller.signal,
|
|
142
|
+
releaseDeadline: AbortSignal.abort(),
|
|
143
|
+
onOutput: (stream, chunk) => sink.append(stream, chunk),
|
|
144
|
+
}))
|
|
145
|
+
.then(({ launched }) => completion.resolve({
|
|
146
|
+
exitCode: launched.exitCode,
|
|
147
|
+
timedOut: launched.timedOut,
|
|
148
|
+
aborted: launched.aborted === true,
|
|
149
|
+
}), (error) => completion.resolve({ exitCode: -1, timedOut: false, aborted: false, launchError: errorMessage(error) }));
|
|
150
|
+
return { content: `started in the background as ${sink.id}`, isError: false };
|
|
151
|
+
}
|
package/dist/tools/bash.d.ts
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
import { runArgv } from "#src/internal/argv-exec";
|
|
23
23
|
import type { BashApprovalMode } from "../config/bash-approval.ts";
|
|
24
24
|
import { type CommandLauncher } from "../sandbox/index.ts";
|
|
25
|
+
import { type BackgroundCommandPort } from "./bash-background.ts";
|
|
25
26
|
import type { CodingTool } from "./registry.ts";
|
|
26
27
|
/**
|
|
27
28
|
* Deadline for a Bash spawn — the same ceiling the Exec branch uses
|
|
@@ -32,6 +33,7 @@ import type { CodingTool } from "./registry.ts";
|
|
|
32
33
|
export declare const BASH_TIMEOUT_MS = 300000;
|
|
33
34
|
export declare const DEFAULT_BASH_SHELL = "/bin/sh";
|
|
34
35
|
export interface BashToolOptions {
|
|
36
|
+
readonly background?: BackgroundCommandPort;
|
|
35
37
|
/** `quality.shell`. */
|
|
36
38
|
readonly shell?: string;
|
|
37
39
|
/** `quality.stripEnvVars` — secrets removed before the spawn. */
|
|
@@ -61,6 +63,15 @@ export interface BashToolOptions {
|
|
|
61
63
|
* description, so the agent always knows whether it is sandboxed.
|
|
62
64
|
*/
|
|
63
65
|
readonly launcher?: CommandLauncher;
|
|
66
|
+
/**
|
|
67
|
+
* US-003: whether this session offers the per-call `unsandboxed` argument
|
|
68
|
+
* (`NativeBackendOptions.allowUnsandboxedCommands`, threaded down through
|
|
69
|
+
* `buildSessionToolSupport`). It shapes the ADVERTISEMENT only -- the schema
|
|
70
|
+
* and one description sentence. `run` never reads it: the tool only honours
|
|
71
|
+
* the flag on the call, so a session that did not advertise the argument
|
|
72
|
+
* cannot be steered into running unwrapped by a stray input field.
|
|
73
|
+
*/
|
|
74
|
+
readonly unsandboxedCommands?: boolean;
|
|
64
75
|
}
|
|
65
76
|
/**
|
|
66
77
|
* Injectable spawn seam, mirroring `_argvExecDeps`, plus the platform seam
|
package/dist/tools/bash.js
CHANGED
|
@@ -24,6 +24,7 @@ import { agentOutputOverlay } from "#src/internal/agent-output-env";
|
|
|
24
24
|
import { runArgv } from "#src/internal/argv-exec";
|
|
25
25
|
import { formatExecBody } from "#src/internal/exec-framing";
|
|
26
26
|
import { rawBashRefusalReason, sandboxSentence, unsandboxedSentence } from "../sandbox/index.js";
|
|
27
|
+
import { runBashWithBackground, withBackgroundSentence, } from "./bash-background.js";
|
|
27
28
|
import { cutToByteCap, READ_CEILING } from "./truncate.js";
|
|
28
29
|
import { BASH_TOOL_NAME } from "./types.js";
|
|
29
30
|
/**
|
|
@@ -179,7 +180,7 @@ function bashToolDescription(shell, opts) {
|
|
|
179
180
|
* therefore never the string the policy judged, which is exactly why
|
|
180
181
|
* `interceptShell` re-validates the provider's answer rather than trusting it.
|
|
181
182
|
*/
|
|
182
|
-
async function launchIntercepted({ command, shell, opts, ctx, timeoutMs, }) {
|
|
183
|
+
async function launchIntercepted({ command, shell, opts, ctx, timeoutMs, unwrapped, backgroundLaunch, isForeground, }) {
|
|
183
184
|
// The run's interceptor arrives on the context (S1 spec port 7), immutable
|
|
184
185
|
// for this call, so the launch below and `postProcess` see the same object.
|
|
185
186
|
const interceptor = ctx.interceptor;
|
|
@@ -199,16 +200,21 @@ async function launchIntercepted({ command, shell, opts, ctx, timeoutMs, }) {
|
|
|
199
200
|
stripEnvVars: [...(opts.stripEnvVars ?? [])],
|
|
200
201
|
...(agentOverlay !== undefined ? { env: agentOverlay } : {}),
|
|
201
202
|
...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),
|
|
203
|
+
...backgroundLaunch,
|
|
202
204
|
};
|
|
203
205
|
const launched = opts.launcher !== undefined
|
|
204
206
|
? await opts.launcher.run({
|
|
205
207
|
spec: { kind: "shell", shell, command: intercepted.command },
|
|
206
208
|
root: ctx.root,
|
|
207
209
|
...common,
|
|
210
|
+
// US-003: the key is present only for an exact `true` on the call, so
|
|
211
|
+
// every other request stays byte-identical to what US-002 shipped.
|
|
212
|
+
...(unwrapped ? { unwrapped: true } : {}),
|
|
208
213
|
})
|
|
209
214
|
: { ...(await _bashToolDeps.runArgv({ argv: executed, ...common })), executed, sandbox: undefined };
|
|
210
|
-
if (!intercepted.rewritten)
|
|
215
|
+
if (!intercepted.rewritten || (backgroundLaunch !== undefined && isForeground?.() !== true)) {
|
|
211
216
|
return { launched, stdout: launched.stdout };
|
|
217
|
+
}
|
|
212
218
|
// The request describes the command the MODEL wrote — the same shape
|
|
213
219
|
// `interceptShell` sent — so post-processing stays keyed to the original,
|
|
214
220
|
// mirroring the Git site, which passes the original argv.
|
|
@@ -223,6 +229,52 @@ async function launchIntercepted({ command, shell, opts, ctx, timeoutMs, }) {
|
|
|
223
229
|
return { launched, stdout: launched.stdout };
|
|
224
230
|
}
|
|
225
231
|
}
|
|
232
|
+
/**
|
|
233
|
+
* US-003: the one sentence an opted-in session appends to its description, so
|
|
234
|
+
* the model knows the argument exists and what it is for. Absent from every
|
|
235
|
+
* description when the option is off, which keeps those byte-identical.
|
|
236
|
+
*/
|
|
237
|
+
const UNSANDBOXED_ARGUMENT_SENTENCE = 'Set "unsandboxed": true with an "unsandboxedReason" only when the command needs the network, a local socket or a device the sandbox blocks.';
|
|
238
|
+
/**
|
|
239
|
+
* US-003: the description with the opt-in sentence appended.
|
|
240
|
+
*
|
|
241
|
+
* A separate function rather than a final ternary inside `bashToolDescription`
|
|
242
|
+
* so every existing variant keeps its own wording verbatim, and the separator
|
|
243
|
+
* is chosen here: most variants already end on a space, the sandbox-sentence
|
|
244
|
+
* ones do not, and a description must never end on two spaces or none.
|
|
245
|
+
*/
|
|
246
|
+
function withUnsandboxedSentence(description, opts) {
|
|
247
|
+
if (opts.unsandboxedCommands !== true)
|
|
248
|
+
return description;
|
|
249
|
+
const separator = description.endsWith(" ") ? "" : " ";
|
|
250
|
+
return `${description}${separator}${UNSANDBOXED_ARGUMENT_SENTENCE}`;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* US-003: the input schema, plus the two argument fields when the session opted
|
|
254
|
+
* in. Built here rather than inline in `createBashTool` so the schema's shape
|
|
255
|
+
* has one owner, and the off-form is exactly the three properties it always was.
|
|
256
|
+
*
|
|
257
|
+
* Neither added field is `required`: the escape is per call, and a call without
|
|
258
|
+
* it runs exactly as it does today.
|
|
259
|
+
*/
|
|
260
|
+
function bashToolInputSchema(opts) {
|
|
261
|
+
return {
|
|
262
|
+
type: "object",
|
|
263
|
+
properties: {
|
|
264
|
+
command: { type: "string", description: 'The shell command to run, e.g. "bun test src/a.test.ts"' },
|
|
265
|
+
timeoutMs: {
|
|
266
|
+
type: "number",
|
|
267
|
+
description: `Deadline in milliseconds (default and maximum ${BASH_TIMEOUT_MS}).`,
|
|
268
|
+
},
|
|
269
|
+
description: { type: "string", description: "One short line on what this command is for." },
|
|
270
|
+
...(opts.background !== undefined ? { runInBackground: { type: "boolean" } } : {}),
|
|
271
|
+
...(opts.unsandboxedCommands === true
|
|
272
|
+
? { unsandboxed: { type: "boolean" }, unsandboxedReason: { type: "string" } }
|
|
273
|
+
: {}),
|
|
274
|
+
},
|
|
275
|
+
required: ["command"],
|
|
276
|
+
};
|
|
277
|
+
}
|
|
226
278
|
export function createBashTool(opts = {}) {
|
|
227
279
|
const shell = opts.shell ?? DEFAULT_BASH_SHELL;
|
|
228
280
|
return {
|
|
@@ -231,23 +283,16 @@ export function createBashTool(opts = {}) {
|
|
|
231
283
|
// not a fault worth an operator's attention — the same reason RunCommand
|
|
232
284
|
// sets this.
|
|
233
285
|
routineErrors: true,
|
|
234
|
-
description: bashToolDescription(shell, opts),
|
|
235
|
-
inputSchema:
|
|
236
|
-
type: "object",
|
|
237
|
-
properties: {
|
|
238
|
-
command: { type: "string", description: 'The shell command to run, e.g. "bun test src/a.test.ts"' },
|
|
239
|
-
timeoutMs: {
|
|
240
|
-
type: "number",
|
|
241
|
-
description: `Deadline in milliseconds (default and maximum ${BASH_TIMEOUT_MS}).`,
|
|
242
|
-
},
|
|
243
|
-
description: { type: "string", description: "One short line on what this command is for." },
|
|
244
|
-
},
|
|
245
|
-
required: ["command"],
|
|
246
|
-
},
|
|
286
|
+
description: withBackgroundSentence(withUnsandboxedSentence(bashToolDescription(shell, opts), opts), opts.background),
|
|
287
|
+
inputSchema: bashToolInputSchema(opts),
|
|
247
288
|
// `commandField` is what routes this call to the Bash branch of the policy
|
|
248
289
|
// (src/tools/policy-bash.ts). No pathFields: the paths are inside the
|
|
249
290
|
// command string, where only that branch can see them.
|
|
250
|
-
|
|
291
|
+
//
|
|
292
|
+
// US-003: `unsandboxedField` is declared unconditionally, so the runtime can
|
|
293
|
+
// see the field whether or not this session advertises it -- the option
|
|
294
|
+
// shapes the schema, never the scope.
|
|
295
|
+
scope: { pathFields: [], commandField: "command", unsandboxedField: "unsandboxed" },
|
|
251
296
|
async run(input, ctx) {
|
|
252
297
|
const command = input.command;
|
|
253
298
|
if (typeof command !== "string" || command.trim() === "") {
|
|
@@ -256,7 +301,22 @@ export function createBashTool(opts = {}) {
|
|
|
256
301
|
const requested = typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) ? input.timeoutMs : BASH_TIMEOUT_MS;
|
|
257
302
|
const timeoutMs = Math.min(Math.max(Math.trunc(requested), MIN_BASH_TIMEOUT_MS), BASH_TIMEOUT_MS);
|
|
258
303
|
try {
|
|
259
|
-
|
|
304
|
+
// US-003: exact `true` only. The tool never consults `opts.unsandboxedCommands`
|
|
305
|
+
// here: whether the argument is ADVERTISED is the option's business, and what a
|
|
306
|
+
// given call asked for is the call's.
|
|
307
|
+
const unwrapped = input.unsandboxed === true;
|
|
308
|
+
const request = { command, shell, opts, ctx, timeoutMs, unwrapped };
|
|
309
|
+
const result = await runBashWithBackground({
|
|
310
|
+
port: opts.background,
|
|
311
|
+
runInBackground: input.runInBackground,
|
|
312
|
+
command,
|
|
313
|
+
description: input.description,
|
|
314
|
+
signal: ctx.signal,
|
|
315
|
+
launch: (backgroundLaunch, isForeground) => launchIntercepted({ ...request, backgroundLaunch, isForeground }),
|
|
316
|
+
});
|
|
317
|
+
if ("content" in result)
|
|
318
|
+
return result;
|
|
319
|
+
const { launched, stdout } = result;
|
|
260
320
|
// Same framing ladder as RunCommand (Exec) via the shared
|
|
261
321
|
// `formatExecBody`: an aborted call opens with the cancellation line
|
|
262
322
|
// and surfaces whatever partial output the readers captured before the
|
package/dist/tools/git.js
CHANGED
|
@@ -171,8 +171,15 @@ function buildGitRootArgv(input) {
|
|
|
171
171
|
}
|
|
172
172
|
return ["rev-parse", "--show-toplevel"];
|
|
173
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* `blame` rejects exclude pathspecs (exit 128). On `log` and `show` an exclude
|
|
176
|
+
* filters COMMITS, not just files: a commit that only touches `.nax/` is
|
|
177
|
+
* dropped, so `log HEAD -1` reported an older commit as HEAD and `show HEAD`
|
|
178
|
+
* printed nothing (#2693). Only `diff` and `status` list files.
|
|
179
|
+
*/
|
|
180
|
+
const GIT_EXCLUDE_EXEMPT_VERBS = ["blame", "log", "show"];
|
|
174
181
|
function defaultGitExcludes(subcommand, excludes) {
|
|
175
|
-
return subcommand
|
|
182
|
+
return GIT_EXCLUDE_EXEMPT_VERBS.includes(subcommand) ? [] : excludes;
|
|
176
183
|
}
|
|
177
184
|
/**
|
|
178
185
|
* `defaultExcludes`: pathspecs appended to an unscoped call (the host's own
|
|
@@ -292,8 +299,8 @@ export function buildGitArgv(input, defaultExcludes = []) {
|
|
|
292
299
|
// on this DEFAULT branch: a caller that names a path under .nax/ gets it --
|
|
293
300
|
// the tool is read-only, and silently returning nothing for an explicitly
|
|
294
301
|
// requested path would be a worse failure than the one being fixed.
|
|
295
|
-
// `blame`
|
|
296
|
-
//
|
|
302
|
+
// `blame`, `log` and `show` are exempt (GIT_EXCLUDE_EXEMPT_VERBS); do not
|
|
303
|
+
// "unify" them back in.
|
|
297
304
|
argv.push(...defaultGitExcludes(subcommand, defaultExcludes));
|
|
298
305
|
return argv;
|
|
299
306
|
}
|