Skip to content

Commit 2777fe3

Browse files
committed
Load AGENTS.md in the browser terminal from its workspace
The browser build turned off AGENTS.md loading because WebAssembly has no filesystem, and nothing gave createFxTerminal another way to read the files or said they were left out. Workspace adapters can now provide readFile. The terminal reads the global, project, and scoped AGENTS.md files through it with the CLI's selection and size rules. A workspace without readFile reports the omitted instructions to the model and the full transcript.
1 parent 6bdd497 commit 2777fe3

11 files changed

Lines changed: 1005 additions & 66 deletions

File tree

‎sdk/AGENTS.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ The SDK has two WebAssembly surfaces and one shared JavaScript host layer:
1616
| Native and WebAssembly capability policy | `src/core/hosts/runtime_profile.zig` |
1717
| Host-backed terminal session persistence | `src/core/app/app_session_runtime.zig` and `sdk/fx-sdk.js` |
1818
| Browser workspace contract and `shell.run` bridge | `src/core/hosts/js_host_workspace.zig` and `src/tools/shell/browser_shell.zig` |
19+
| Browser workspace AGENTS.md reads | `src/core/hosts/js_host_workspace.zig`, `src/builtins/context.zig`, and `sdk/fx-sdk.js` |
1920
| Browser device login, OAuth session persistence, and URL opening | `src/core/auth/js_host_auth.zig`, `src/core/auth/oauth_session.zig`, and `src/core/hosts/js_host_url_opener.zig` |
2021
| WASI target, optimization mode, threading, and artifact names | `build.zig` |
2122
| Core browser fixture and its automation contract | `sdk/index.html` and `sdk/tests/test-core-browser.mjs` |
@@ -32,6 +33,7 @@ Do not treat the demos or this file as the implementation contract. When prose a
3233
- Treat JavaScript host stores as durable contracts. Session and OAuth snapshots are opaque bytes with optimistic revisions. Preserve `FX_SESSION_REVISION_CONFLICT` and `FX_OAUTH_SESSION_REVISION_CONFLICT`. Persist configuration only after fx accepts it, and do not collapse prompt-history outcomes into generic success.
3334
- Preserve cancellation and lifecycle behavior. Fetch cancellation must reach the host `AbortSignal`; terminal subscriptions must be released exactly once; `abort()` must settle `exited` and must not leave input or resize listeners attached.
3435
- The WebAssembly runtime is not the native runtime. Keep native tools disabled. The optional workspace host may expose only completion-only `shell.run` through its typed boundary and permission policy. Its schema is exactly `{ action: "run", command }`; native profiles, TTYs, and managed running handles are unavailable. Any additional capability requires its own typed host boundary, permission review where applicable, and coverage on the affected surface.
36+
- The optional workspace `readFile` boundary serves only project instruction loading. Keep it limited to absolute `AGENTS.md` paths inside the workspace root or home, with UTF-8 validation, the 1 MiB copy limit, and the shared abort path. It is not a model-callable file tool. A workspace without `readFile` must report the omitted instructions rather than skip them silently.
3537
- Keep workspace version 1 constrained to an ephemeral, non-git workspace whose normalized `cwd` equals `root`. Preserve command and output limits, the 30-second maximum deadline, and Ctrl+C cancellation through the shared host-effect abort path.
3638
- `window.__fxCoreTest` and `document.body.dataset.state` are test interfaces for the core debugger. If either changes intentionally, update the browser test in the same change.
3739
- The live demos may pass a locally stored credential into the WebAssembly environment. Never print, serialize into artifacts, or add test assertions containing that credential.
@@ -46,6 +48,7 @@ Do not treat the demos or this file as the implementation contract. When prose a
4648
| Terminal adapter, input encoding, resize, cleanup, config, or prompt history | Terminal build and the headless terminal suite |
4749
| Terminal session persistence or browser device login | Terminal build plus `sdk/tests/test-term-session-resume.mjs` or `sdk/tests/test-term-login.mjs` |
4850
| Browser workspace metadata, permissions, execution, limits, or cancellation | Terminal build plus `sdk/node/test-term-workspace.mjs` |
51+
| Browser workspace AGENTS.md reads | Terminal build plus `sdk/node/test-term-agents-md.mjs` |
4952
| `encodeXtermKeyEvent()` or `xtermAdapter()` only | `sdk/node/test-xterm-adapter.mjs` |
5053
| Core debugger query behavior or automation state | `sdk/tests/test-core-browser.mjs` |
5154
| Terminal demo asset references, integrity, or cache policy | Package into a fresh temporary directory and inspect the generated HTML, manifest, and headers |

‎sdk/README.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -596,6 +596,28 @@ workspace stores remain terminal-only host integrations. Clipboard copy writes
596596
through the host `clipboard.writeText(text)` adapter and defaults to
597597
`navigator.clipboard`.
598598

599+
A terminal with a `workspace` adapter loads AGENTS.md project instructions from
600+
it the way the CLI reads them from disk: `<root>/AGENTS.md`, scoped
601+
`AGENTS.md` files below the root, and `<home>/.fx/AGENTS.md`. Provide them
602+
through an optional `readFile` method:
603+
604+
```js
605+
const workspace = {
606+
info: { version: 1, root: "/workspace", cwd: "/workspace", home: "/home/visitor", gitAvailable: false, ephemeral: true },
607+
permission: "allow-sandboxed",
608+
exec({ command, cwd, signal, timeoutMs, outputLimitBytes }) { /* run one command */ },
609+
async readFile({ path, signal }) {
610+
// Return a string or UTF-8 bytes, or null when the file does not exist.
611+
},
612+
};
613+
```
614+
615+
fx calls `readFile` only for absolute `AGENTS.md` paths inside `root` or
616+
`home`. Each read has a 10-second deadline, the interrupt key aborts it through
617+
`signal`, and the CLI's project instruction size limits apply. Without
618+
`readFile`, fx tells the model that the workspace's project instructions were
619+
omitted and records the omission in the full transcript.
620+
599621
During `/compact` and automatic compaction, the terminal shows a live
600622
`Compacting` activity row with elapsed time. Input and cancellation remain
601623
responsive while the summary request is pending. Compaction progress and

‎sdk/fx-sdk.js‎

Lines changed: 97 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ const strictDecoder = new TextDecoder("utf-8", { fatal: true });
77
const workspaceInfoLimit = 4 * 1024;
88
const workspaceCommandLimit = 64 * 1024;
99
const workspaceOutputLimit = 64 * 1024;
10+
// Matches max_instruction_file_bytes and max_instruction_path_bytes in js_host_workspace.zig.
11+
const workspaceInstructionFileLimit = 1024 * 1024;
12+
const workspaceInstructionPathLimit = 4 * 1024;
13+
const workspaceReadTimeoutMs = 10_000;
1014
const maxInstructionsBytes = 64 * 1024;
1115
const maxApiKeyBytes = 64 * 1024;
1216
const maxModelBytes = 1024;
@@ -253,12 +257,24 @@ function validWorkspacePath(path) {
253257
return path.slice(1).split("/").every((part) => part && part !== "." && part !== "..");
254258
}
255259

260+
function workspacePathInside(root, path) {
261+
return root === "/" ? path.startsWith("/") : path === root || path.startsWith(`${root}/`);
262+
}
263+
264+
// fx only reads AGENTS.md files below the workspace root or the host home.
265+
function workspaceInstructionPathAllowed(info, path) {
266+
return validWorkspacePath(path) && path.endsWith("/AGENTS.md") &&
267+
(workspacePathInside(info.root, path) || workspacePathInside(info.home, path));
268+
}
269+
256270
function prepareWorkspaceAdapter(workspace) {
257271
if (workspace == null) return { present: false, valid: false };
258272
try {
259273
const info = workspace.info;
260274
const permission = workspace.permission;
275+
const readFile = workspace.readFile;
261276
if (!info || typeof workspace.exec !== "function" || info.version !== 1 ||
277+
(readFile !== undefined && typeof readFile !== "function") ||
262278
!validWorkspacePath(info.root) || !validWorkspacePath(info.cwd) ||
263279
!validWorkspacePath(info.home) || info.cwd !== info.root ||
264280
info.gitAvailable !== false || info.ephemeral !== true ||
@@ -273,6 +289,7 @@ function prepareWorkspaceAdapter(workspace) {
273289
git: false,
274290
ephemeral: true,
275291
permission,
292+
instruction_files: typeof readFile === "function",
276293
};
277294
const encoded = encoder.encode(JSON.stringify(value));
278295
if (encoded.length > workspaceInfoLimit) return { present: true, valid: false };
@@ -493,7 +510,7 @@ function createRuntime(options) {
493510
const inboundAttachments = new Map();
494511
const outboundAttachments = new Map();
495512
let nextOutboundAttachment = 1;
496-
const workspaceExecs = new Set();
513+
const workspaceOperations = new Set();
497514
const workspace = prepareWorkspaceAdapter(options.workspace);
498515
const args = ["fx", ...(options.args || [])];
499516
const env = Object.entries(options.env || {}).map(([key, value]) => `${key}=${value}`);
@@ -1047,32 +1064,13 @@ function createRuntime(options) {
10471064
}
10481065
if (command.includes("\0")) return Promise.resolve(-4);
10491066

1050-
const controller = new AbortController();
1051-
let resolveAbort;
1052-
const aborted = new Promise((resolve) => { resolveAbort = resolve; });
1053-
const state = {
1054-
controller,
1055-
status: null,
1056-
abort(status) {
1057-
if (this.status !== null) return;
1058-
this.status = status;
1059-
resolveAbort(status);
1060-
controller.abort(new DOMException(
1061-
status === -5 ? "workspace command timed out" : "workspace command aborted",
1062-
status === -5 ? "TimeoutError" : "AbortError",
1063-
));
1064-
},
1065-
};
1066-
workspaceExecs.add(state);
1067-
const timer = setTimeout(() => state.abort(-5), timeoutMs);
1068-
const execution = Promise.resolve().then(() => workspace.adapter.exec({
1067+
return runWorkspaceOperation(timeoutMs, "workspace command", (signal) => workspace.adapter.exec({
10691068
command,
10701069
cwd: workspace.info.cwd,
1071-
signal: controller.signal,
1070+
signal,
10721071
timeoutMs,
10731072
outputLimitBytes: workspaceOutputLimit,
1074-
})).then((value) => {
1075-
if (state.status !== null) return state.status;
1073+
}), (value) => {
10761074
if (!value || !Number.isInteger(value.exitCode) || value.exitCode < -0x80000000 ||
10771075
value.exitCode > 0x7fffffff || typeof value.stdout !== "string" ||
10781076
typeof value.stderr !== "string") return -1;
@@ -1106,6 +1104,79 @@ function createRuntime(options) {
11061104
view.setUint32(24, stderr.length, true);
11071105
view.setUint32(28, copied < stdout.length + stderr.length ? 1 : 0, true);
11081106
return 0;
1107+
});
1108+
}
1109+
1110+
function workspaceReadFile(pathPtr, pathLen, outPtr, outCap, resultPtr) {
1111+
if (!workspace.present || (workspace.valid && typeof workspace.adapter.readFile !== "function")) {
1112+
return Promise.resolve(-2);
1113+
}
1114+
if (!workspace.valid) return Promise.resolve(-4);
1115+
const pathBytes = checkedBytes(pathPtr, pathLen);
1116+
if (!pathBytes || !checkedBytes(outPtr, outCap) || !checkedBytes(resultPtr, 8) ||
1117+
pathLen > workspaceInstructionPathLimit || outCap > workspaceInstructionFileLimit) {
1118+
return Promise.resolve(-4);
1119+
}
1120+
let path;
1121+
try {
1122+
path = strictDecoder.decode(pathBytes);
1123+
} catch {
1124+
return Promise.resolve(-4);
1125+
}
1126+
if (!workspaceInstructionPathAllowed(workspace.info, path)) return Promise.resolve(-4);
1127+
1128+
return runWorkspaceOperation(workspaceReadTimeoutMs, "workspace read", (signal) => workspace.adapter.readFile({
1129+
path,
1130+
signal,
1131+
}), (value) => {
1132+
if (value == null) return -6;
1133+
let content;
1134+
if (typeof value === "string") {
1135+
content = encoder.encode(value);
1136+
} else if (ArrayBuffer.isView(value)) {
1137+
content = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
1138+
try {
1139+
strictDecoder.decode(content);
1140+
} catch {
1141+
return -7;
1142+
}
1143+
} else {
1144+
return -1;
1145+
}
1146+
if (content.length > 0xffffffff) return -1;
1147+
const copied = Math.min(content.length, outCap);
1148+
// Reacquire views: memory may have grown while the host read was pending.
1149+
bytes(outPtr, copied).set(content.subarray(0, copied));
1150+
const view = new DataView(memory().buffer, resultPtr, 8);
1151+
view.setUint32(0, content.length, true);
1152+
view.setUint32(4, copied, true);
1153+
return 0;
1154+
});
1155+
}
1156+
1157+
// Runs one host workspace effect under a deadline and the shared Ctrl+C
1158+
// abort path. `finish` maps the host value to an ABI status.
1159+
function runWorkspaceOperation(timeoutMs, label, start, finish) {
1160+
const controller = new AbortController();
1161+
let resolveAbort;
1162+
const aborted = new Promise((resolve) => { resolveAbort = resolve; });
1163+
const state = {
1164+
status: null,
1165+
abort(status) {
1166+
if (this.status !== null) return;
1167+
this.status = status;
1168+
resolveAbort(status);
1169+
controller.abort(new DOMException(
1170+
status === -5 ? `${label} timed out` : `${label} aborted`,
1171+
status === -5 ? "TimeoutError" : "AbortError",
1172+
));
1173+
},
1174+
};
1175+
workspaceOperations.add(state);
1176+
const timer = setTimeout(() => state.abort(-5), timeoutMs);
1177+
const execution = Promise.resolve().then(() => start(controller.signal)).then((value) => {
1178+
if (state.status !== null) return state.status;
1179+
return finish(value);
11091180
}).catch((error) => {
11101181
if (state.status !== null) return state.status;
11111182
if (error?.name === "TimeoutError") return -5;
@@ -1114,15 +1185,15 @@ function createRuntime(options) {
11141185
});
11151186
return Promise.race([execution, aborted]).finally(() => {
11161187
clearTimeout(timer);
1117-
workspaceExecs.delete(state);
1188+
workspaceOperations.delete(state);
11181189
});
11191190
}
11201191

11211192
function abortHostEffects() {
11221193
pendingHostToolResult = null;
11231194
streams.forEach((state) => state.controller.abort(abortReason));
11241195
httpRequests.forEach((controller) => controller.abort(abortReason));
1125-
workspaceExecs.forEach((state) => state.abort(-3));
1196+
workspaceOperations.forEach((state) => state.abort(-3));
11261197
}
11271198

11281199
const unavailable = () => 52;
@@ -1177,6 +1248,7 @@ function createRuntime(options) {
11771248
fx_workspace_available() { return workspace.present ? 1 : 0; },
11781249
fx_workspace_info: workspaceInfo,
11791250
fx_workspace_exec: new WebAssembly.Suspending(workspaceExec),
1251+
fx_workspace_read_file: new WebAssembly.Suspending(workspaceReadFile),
11801252
fx_http_stream_open: streamOpen,
11811253
fx_http_stream_status: new WebAssembly.Suspending(streamStatus),
11821254
fx_http_stream_next: new WebAssembly.Suspending(streamNext),

‎sdk/node/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"private": true,
44
"type": "module",
55
"scripts": {
6-
"test:term": "node test-xterm-adapter.mjs && node --experimental-wasm-jspi test-term-config-restore.mjs && node --experimental-wasm-jspi test-term-headless.mjs && node --experimental-wasm-jspi test-term-table-stream.mjs && node --experimental-wasm-jspi test-term-lifecycle.mjs && node --experimental-wasm-jspi test-term-compaction.mjs && node --experimental-wasm-jspi test-term-features.mjs && node --experimental-wasm-jspi test-term-history.mjs && node --experimental-wasm-jspi test-term-workspace.mjs"
6+
"test:term": "node test-xterm-adapter.mjs && node --experimental-wasm-jspi test-term-config-restore.mjs && node --experimental-wasm-jspi test-term-headless.mjs && node --experimental-wasm-jspi test-term-table-stream.mjs && node --experimental-wasm-jspi test-term-lifecycle.mjs && node --experimental-wasm-jspi test-term-compaction.mjs && node --experimental-wasm-jspi test-term-features.mjs && node --experimental-wasm-jspi test-term-history.mjs && node --experimental-wasm-jspi test-term-workspace.mjs && node --experimental-wasm-jspi test-term-agents-md.mjs"
77
},
88
"devDependencies": {
99
"@xterm/headless": "6.0.0"

0 commit comments

Comments
 (0)