@tenonai/yew 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +23 -5
  3. package/THIRD-PARTY-NOTICES.md +6 -1
  4. package/dist/cli/serve.js +75 -3
  5. package/dist/server/agent/prompt.js +3 -2
  6. package/dist/server/agent/runner.js +40 -0
  7. package/dist/server/http/api.js +17 -1
  8. package/dist/server/http/app.js +10 -2
  9. package/dist/server/mail/envelope.js +11 -6
  10. package/dist/server/mcp-builtin.js +14 -1
  11. package/dist/server/mcp.js +70 -8
  12. package/dist/server/permissions/engine.js +23 -5
  13. package/dist/server/sandbox.js +447 -0
  14. package/dist/server/settings.js +34 -1
  15. package/dist/server/tools/jobs.js +3 -2
  16. package/dist/server/tools/mail.js +11 -1
  17. package/dist/server/tools/process.js +63 -12
  18. package/dist/server/tools/search.js +5 -2
  19. package/dist/server/tools/shell.js +70 -17
  20. package/dist/shared/policy.js +20 -20
  21. package/dist/shared/version.js +6 -0
  22. package/dist/sim/client.d.ts +17 -0
  23. package/dist/sim/client.js +41 -0
  24. package/dist/sim/index.d.ts +7 -0
  25. package/dist/sim/index.js +6 -0
  26. package/dist/sim/types.d.ts +161 -0
  27. package/dist/sim/types.js +5 -0
  28. package/dist/sim/world.d.ts +6 -0
  29. package/dist/sim/world.js +359 -0
  30. package/package.json +17 -3
  31. package/web/dist/assets/index-BQdFuM-f.css +1 -0
  32. package/web/dist/assets/index-Dh9QdEsc.js +70 -0
  33. package/web/dist/icons/apple-touch-icon.png +0 -0
  34. package/web/dist/index.html +2 -2
  35. package/web/dist/mascot/on-duty.webp +0 -0
  36. package/web/dist/mascot/permission.webp +0 -0
  37. package/web/dist/assets/index-B_NesKxw.js +0 -68
  38. package/web/dist/assets/index-BqTqnE18.css +0 -1
@@ -1,6 +1,6 @@
1
1
  import { dirname } from "node:path";
2
2
  import { permissionModeOf, } from "../../shared/types.js";
3
- import { isInside, isSecretPath, pathMatches, resolvePath, secretLocations } from "./paths.js";
3
+ import { canonical, isInside, isSecretPath, pathMatches, resolvePath, secretLocations, } from "./paths.js";
4
4
  import { isReadOnly, matchesPrefix, mustConfirmReason, parseShell, pathArguments, rememberPrefix, unwrap, } from "./shell.js";
5
5
  const SAFE_REDIRECT_TARGETS = new Set(["/dev/null", "/dev/stdout", "/dev/stderr", "&1", "&2", "-"]);
6
6
  /**
@@ -30,9 +30,19 @@ export class PermissionEngine {
30
30
  #secrets;
31
31
  /** Folders outside the working folder that may be read without asking: memory and skill folders. */
32
32
  readRoots = () => [];
33
+ /** Folders the person keeps from sessions (the settings): refused like credential locations. */
34
+ hidden = () => [];
33
35
  constructor(yewHome) {
34
36
  this.#secrets = secretLocations(yewHome);
35
37
  }
38
+ /** Credential locations, Yew's own data and the folders the person keeps from sessions. */
39
+ #offLimits() {
40
+ return [...this.#secrets, ...this.hidden().map(canonical)];
41
+ }
42
+ /** Whether sessions may never read or change `path` (an absolute path). */
43
+ offLimits(path) {
44
+ return isSecretPath(path, this.#offLimits());
45
+ }
36
46
  /**
37
47
  * `flagged` is the model's own judgment, through the `confirm` argument: in the automatic mode a
38
48
  * flagged call is asked about, others run. Must-confirm operations, explicit "ask" rules and commands
@@ -69,13 +79,19 @@ export class PermissionEngine {
69
79
  #files(subject, session, flagged) {
70
80
  const cwd = session.cwd;
71
81
  for (const path of subject.paths) {
82
+ const verb = subject.kind === "read" ? "read" : "change";
72
83
  if (isSecretPath(path, this.#secrets)) {
73
- const verb = subject.kind === "read" ? "read" : "change";
74
84
  return {
75
85
  effect: "deny",
76
86
  reason: `${path} holds credentials or Yew's own data; sessions cannot ${verb} it.`,
77
87
  };
78
88
  }
89
+ if (this.offLimits(path)) {
90
+ return {
91
+ effect: "deny",
92
+ reason: `${path} is in a folder the person keeps from sessions; sessions cannot ${verb} it.`,
93
+ };
94
+ }
79
95
  }
80
96
  const effects = subject.paths.map((path) => this.#rulesFor(session, subject.tool, (rule) => pathMatches(path, rule.pattern ?? "", cwd)));
81
97
  if (effects.includes("deny")) {
@@ -139,18 +155,20 @@ export class PermissionEngine {
139
155
  // File tools cannot touch these places at all; a command that names one asks every time.
140
156
  const secret = pathArguments(argv).some((arg) => {
141
157
  const path = resolvePath(arg, cwd);
142
- return path !== null && isSecretPath(path, this.#secrets);
158
+ return path !== null && isSecretPath(path, this.#offLimits());
143
159
  });
144
160
  if (secret)
145
161
  reasons.add("credentials");
146
162
  }
147
163
  if (privileged)
148
164
  reasons.add("admin");
165
+ if (subject.outsideSandbox)
166
+ reasons.add("outside-sandbox");
149
167
  for (const target of redirectTargets) {
150
168
  const path = resolvePath(target, cwd);
151
169
  if (!path || !cwd || !isInside(path, cwd))
152
170
  reasons.add("write-outside");
153
- else if (isSecretPath(path, this.#secrets))
171
+ else if (isSecretPath(path, this.#offLimits()))
154
172
  reasons.add("write-credentials");
155
173
  }
156
174
  const ruleFor = (argv) => this.#rulesFor(session, subject.tool, (r) => matchesPrefix(argv, r.pattern ?? ""));
@@ -189,7 +207,7 @@ export class PermissionEngine {
189
207
  return false;
190
208
  return pathArguments(argv).every((arg) => {
191
209
  const path = resolvePath(arg, cwd);
192
- return path !== null && isInside(path, cwd) && !isSecretPath(path, this.#secrets);
210
+ return path !== null && isInside(path, cwd) && !isSecretPath(path, this.#offLimits());
193
211
  });
194
212
  }
195
213
  #url(subject, session, flagged) {
@@ -0,0 +1,447 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { existsSync, mkdirSync, readdirSync, realpathSync } from "node:fs";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import { delimiter, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { secretLocations } from "./permissions/paths.js";
8
+ /** The folder with this Yew Harness's package.json: the repository, or the installed package. */
9
+ export const INSTALL_DIR = fileURLToPath(new URL("../..", import.meta.url));
10
+ /** Package registries and the code hosts packages are fetched from (git dependencies, releases). */
11
+ export const PACKAGE_SITES = [
12
+ "registry.npmjs.org",
13
+ "registry.yarnpkg.com",
14
+ "repo.yarnpkg.com",
15
+ "registry.npmmirror.com",
16
+ "cdn.npmmirror.com",
17
+ "jsr.io",
18
+ "npm.jsr.io",
19
+ "deno.land",
20
+ "pypi.org",
21
+ "files.pythonhosted.org",
22
+ "pypi.tuna.tsinghua.edu.cn",
23
+ "mirrors.aliyun.com",
24
+ "crates.io",
25
+ "index.crates.io",
26
+ "static.crates.io",
27
+ "proxy.golang.org",
28
+ "sum.golang.org",
29
+ "goproxy.cn",
30
+ "rubygems.org",
31
+ "index.rubygems.org",
32
+ "repo.maven.apache.org",
33
+ "repo1.maven.org",
34
+ "plugins.gradle.org",
35
+ "services.gradle.org",
36
+ "cdn.cocoapods.org",
37
+ "github.com",
38
+ "codeload.github.com",
39
+ "objects.githubusercontent.com",
40
+ "raw.githubusercontent.com",
41
+ "gitee.com",
42
+ ];
43
+ /** Private networks: an allowed name that resolves into one of them is not dialed. */
44
+ const PRIVATE_RANGES = [
45
+ "10.0.0.0/8",
46
+ "172.16.0.0/12",
47
+ "192.168.0.0/16",
48
+ "100.64.0.0/10",
49
+ "fc00::/7",
50
+ ];
51
+ /** What tells a program where the SSH agent is. */
52
+ const AGENT_VARIABLES = ["SSH_AUTH_SOCK", "SSH_AGENT_PID"];
53
+ const real = (path) => {
54
+ try {
55
+ return realpathSync(path);
56
+ }
57
+ catch {
58
+ return path;
59
+ }
60
+ };
61
+ /**
62
+ * The sandbox's own folder: in the system's cache folder, because commands cannot write in the data
63
+ * folder. Commands' caches go to `cache` in it.
64
+ */
65
+ export function sandboxRoot(userHome = homedir(), platform = process.platform, env = process.env) {
66
+ if (platform === "darwin")
67
+ return join(userHome, "Library", "Caches", "yew-sandbox");
68
+ return join(env.XDG_CACHE_HOME || join(userHome, ".cache"), "yew-sandbox");
69
+ }
70
+ /**
71
+ * Variables that send the usual tools' caches to the sandbox's own folder, so nothing a command
72
+ * leaves in a cache is picked up by the person's own tools outside. (The library points TMPDIR at
73
+ * its own temporary folder.)
74
+ */
75
+ export function sandboxEnvironment(places) {
76
+ const cache = join(places.root, "cache");
77
+ return {
78
+ XDG_CACHE_HOME: join(cache, "xdg"),
79
+ npm_config_cache: join(cache, "npm"),
80
+ YARN_CACHE_FOLDER: join(cache, "yarn"),
81
+ COREPACK_HOME: join(cache, "corepack"),
82
+ BUN_INSTALL_CACHE_DIR: join(cache, "bun"),
83
+ DENO_DIR: join(cache, "deno"),
84
+ PIP_CACHE_DIR: join(cache, "pip"),
85
+ UV_CACHE_DIR: join(cache, "uv"),
86
+ PYTHONPYCACHEPREFIX: join(cache, "pycache"),
87
+ GOCACHE: join(cache, "go-build"),
88
+ GOMODCACHE: join(cache, "go-mod"),
89
+ GRADLE_USER_HOME: join(cache, "gradle"),
90
+ ELECTRON_CACHE: join(cache, "electron"),
91
+ };
92
+ }
93
+ /**
94
+ * The keychain files: never readable, whatever the setting for credentials says (the security group,
95
+ * 11-18), so the keychain's items cannot be read from the sandbox. git over HTTPS with saved
96
+ * credentials and gh run outside the sandbox.
97
+ */
98
+ function keychains(places) {
99
+ return join(real(places.userHome), "Library", "Keychains");
100
+ }
101
+ /**
102
+ * The usual credential files and folders (the ones file tools refuse), without the data folder and
103
+ * the keychain files, which stay closed either way: what the setting for credentials opens.
104
+ */
105
+ function credentialFiles(places) {
106
+ const closed = new Set([real(places.home), keychains(places)]);
107
+ return secretLocations(places.home).filter((path) => !closed.has(path));
108
+ }
109
+ /**
110
+ * The hooks and settings of the repositories of submodules and worktrees under a writable folder:
111
+ * changed, they would run commands outside the sandbox the next time the person uses git there.
112
+ * macOS takes patterns; bubblewrap takes only paths, so on Linux the ones there now are listed.
113
+ */
114
+ export function gitInternals(folder, platform = process.platform) {
115
+ if (platform === "darwin") {
116
+ return ["", "/**"].flatMap((under) => [
117
+ `${folder}${under}/.git/**/hooks`,
118
+ `${folder}${under}/.git/**/hooks/**`,
119
+ `${folder}${under}/.git/**/config`,
120
+ `${folder}${under}/.git/**/config.worktree`,
121
+ ]);
122
+ }
123
+ const found = [];
124
+ const walk = (dir, depth) => {
125
+ let names;
126
+ try {
127
+ names = readdirSync(dir);
128
+ }
129
+ catch {
130
+ return;
131
+ }
132
+ for (const name of names) {
133
+ const path = join(dir, name);
134
+ if (name === "hooks" || name === "config" || name === "config.worktree")
135
+ found.push(path);
136
+ else if (depth > 0)
137
+ walk(path, depth - 1);
138
+ }
139
+ };
140
+ walk(join(folder, ".git", "modules"), 6);
141
+ walk(join(folder, ".git", "worktrees"), 1);
142
+ return found;
143
+ }
144
+ /**
145
+ * The temporary folders: /tmp, and on macOS the user's own (…/T), which `mktemp` and Apple's tools
146
+ * use whatever TMPDIR says. Not the cache folder next to it (…/C): shared caches stay read-only.
147
+ */
148
+ function temporary(platform) {
149
+ const folders = new Set(["/tmp", real("/tmp")]);
150
+ const own = real(tmpdir());
151
+ if (platform === "darwin" && /^\/private\/var\/folders\/[^/]+\/[^/]+\/T$/.test(own))
152
+ folders.add(own);
153
+ return [...folders];
154
+ }
155
+ /** Where Yew Harness's own port is: commands must not reach its local interface. */
156
+ function ownPort(port) {
157
+ return [`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`];
158
+ }
159
+ /** The file system part of one command's configuration: the base plus what the command is granted. */
160
+ export function commandFilesystem(places, policy, grant = {}, platform = process.platform) {
161
+ const writable = (grant.writable ?? []).map(real);
162
+ const user = real(places.userHome);
163
+ return {
164
+ allowWrite: [...writable, join(places.root, "cache"), ...temporary(platform)],
165
+ denyWrite: [
166
+ real(places.home),
167
+ real(places.install),
168
+ join(user, "Library", "LaunchAgents"),
169
+ join(user, "Applications", "Yew.app"),
170
+ join(user, ".config", "systemd", "user"),
171
+ join(user, ".config", "autostart"),
172
+ ...writable.flatMap((folder) => gitInternals(folder, platform)),
173
+ ...policy.hidden,
174
+ ],
175
+ denyRead: [
176
+ real(places.home),
177
+ keychains(places),
178
+ ...policy.hidden,
179
+ ...(policy.credentials ? [] : credentialFiles(places)),
180
+ ],
181
+ allowRead: (grant.readable ?? []).map(real),
182
+ allowGitConfig: false,
183
+ };
184
+ }
185
+ /** The configuration the sandbox starts with; each command adds its own file system part. */
186
+ export function sandboxConfig(places, policy, options = {}) {
187
+ const platform = options.platform ?? process.platform;
188
+ const agent = policy.credentials ? options.agentSocket : undefined;
189
+ return {
190
+ network: {
191
+ allowedDomains: [...new Set([...PACKAGE_SITES, ...policy.sites])],
192
+ deniedDomains: ownPort(places.port),
193
+ deniedResolvedAddresses: PRIVATE_RANGES,
194
+ allowLocalBinding: false,
195
+ allowAllUnixSockets: false,
196
+ // The SSH agent only when the setting allows it (macOS; Linux cannot single out a socket).
197
+ ...(agent ? { allowUnixSockets: [agent] } : {}),
198
+ },
199
+ filesystem: commandFilesystem(places, policy, {}, platform),
200
+ ...(policy.credentials
201
+ ? {}
202
+ : {
203
+ credentials: {
204
+ files: credentialFiles(places).map((path) => ({ path, mode: "deny" })),
205
+ envVars: AGENT_VARIABLES.map((name) => ({ name, mode: "deny" })),
206
+ },
207
+ }),
208
+ allowAppleEvents: false,
209
+ allowPty: false,
210
+ enableWeakerNestedSandbox: false,
211
+ enableWeakerNetworkIsolation: false,
212
+ allowNestedUserNamespaces: false,
213
+ ...(options.ripgrep ? { ripgrep: { command: options.ripgrep } } : {}),
214
+ };
215
+ }
216
+ /**
217
+ * Whether `yew serve` starts the sandbox: on macOS and Linux unless `YEW_SANDBOX=off` (founder,
218
+ * 11-18: Linux too). `YEW_SANDBOX=on` asks for it elsewhere as well; startSandbox says why not.
219
+ */
220
+ export function sandboxWanted(setting, platform = process.platform) {
221
+ if (setting === "on")
222
+ return true;
223
+ if (setting === "off")
224
+ return false;
225
+ return platform === "darwin" || platform === "linux";
226
+ }
227
+ /** A program's full path, from PATH and the usual places a service started at login may lack. */
228
+ export function findProgram(name, env = process.env) {
229
+ const folders = [
230
+ ...(env.PATH ?? "").split(delimiter),
231
+ "/opt/homebrew/bin",
232
+ "/usr/local/bin",
233
+ "/usr/bin",
234
+ "/bin",
235
+ ];
236
+ for (const folder of folders) {
237
+ if (folder && existsSync(join(folder, name)))
238
+ return join(folder, name);
239
+ }
240
+ return null;
241
+ }
242
+ let active = null;
243
+ const running = new Map();
244
+ /** How a site reads in an allow list: `host:port`, with brackets around an IPv6 address. */
245
+ const siteOf = (host, port) => {
246
+ const name = host.includes(":") ? `[${host}]` : host;
247
+ return port === undefined ? name : `${name}:${port}`;
248
+ };
249
+ /** Turned down, with a reason the command's output and the model can read. */
250
+ const refuse = (reason) => ({ allow: false, reason });
251
+ /**
252
+ * Asked about a site no rule decides. The library does not say which command is connecting, so the
253
+ * question goes to the one command that can ask (a session's command the person is there for); with
254
+ * none or several, the site is turned down and the reason says why. While anything else runs in the
255
+ * sandbox too (a background command, an MCP server), the card says the source is unsure and lists
256
+ * what runs, and a yes lets only this connection through.
257
+ */
258
+ const decideSite = async ({ host, port }) => {
259
+ const site = siteOf(host, port);
260
+ const askers = [...running.entries()].filter(([, command]) => command.ask);
261
+ if (askers.length === 0) {
262
+ return refuse(`${host} is not among the sites commands may reach, and nobody could be asked: run it as a command of a session the person is watching, or outside the sandbox`);
263
+ }
264
+ if (askers.length > 1) {
265
+ return refuse(`${host} is not among the sites commands may reach, and several commands were running, so Yew Harness could not tell whose connection this was: run the command again by itself`);
266
+ }
267
+ const [id, command] = askers[0];
268
+ if (command.allowed.includes(site))
269
+ return true;
270
+ if (command.refused.has(site))
271
+ return refuse(`The person did not allow ${host} for this command`);
272
+ const others = [...running.entries()].filter(([other]) => other !== id);
273
+ const unsure = others.length > 0 ? [command.label, ...others.map(([, other]) => other.label)] : undefined;
274
+ let question = command.asking.get(site);
275
+ if (!question) {
276
+ const ask = command.ask;
277
+ question = ask({
278
+ host,
279
+ ...(port === undefined ? {} : { port }),
280
+ ...(unsure ? { unsure } : {}),
281
+ }).catch(() => false);
282
+ command.asking.set(site, question);
283
+ }
284
+ const allowed = await question;
285
+ command.asking.delete(site);
286
+ if (!allowed) {
287
+ command.refused.add(site);
288
+ return refuse(`The person did not allow ${host} for this command`);
289
+ }
290
+ // Unsure whose connection it was: this one goes through, and the next one is asked about again.
291
+ if (unsure)
292
+ return true;
293
+ if (!command.allowed.includes(site))
294
+ command.allowed.push(site);
295
+ // The rest of this command's connections there go through without asking again.
296
+ if (running.has(id))
297
+ active?.manager.registerCommandNetworkLists(id, { allowedDomains: command.allowed });
298
+ return true;
299
+ };
300
+ /**
301
+ * Starts the sandbox once, when `yew serve` starts. Returns the kind in use, or "none" with the
302
+ * reasons when this computer cannot run it (another system, or a missing program).
303
+ */
304
+ export async function startSandbox(places, policy, env = process.env) {
305
+ if (process.platform !== "darwin" && process.platform !== "linux") {
306
+ return { kind: "none", problems: [`${process.platform} has no sandbox Yew Harness can use`] };
307
+ }
308
+ const { SandboxManager } = await import("@anthropic-ai/sandbox-runtime");
309
+ if (!SandboxManager.isSupportedPlatform()) {
310
+ return { kind: "none", problems: ["this system is not supported by the sandbox"] };
311
+ }
312
+ const ripgrep = findProgram("rg", env);
313
+ const check = SandboxManager.checkDependencies(ripgrep ? { command: ripgrep } : undefined);
314
+ if (check.errors.length > 0)
315
+ return { kind: "none", problems: check.errors };
316
+ mkdirSync(join(places.root, "cache"), { recursive: true, mode: 0o700 });
317
+ const options = { ripgrep, ...(env.SSH_AUTH_SOCK ? { agentSocket: env.SSH_AUTH_SOCK } : {}) };
318
+ const config = sandboxConfig(places, policy(), options);
319
+ await SandboxManager.initialize(config, decideSite, true);
320
+ // A system that cannot run a command in it (bubblewrap without user namespaces, say) gets no
321
+ // sandbox, rather than sessions whose every command fails.
322
+ const failed = await selfCheck(SandboxManager, places, policy());
323
+ if (failed) {
324
+ await SandboxManager.reset();
325
+ return { kind: "none", problems: [failed] };
326
+ }
327
+ const kind = process.platform === "darwin" ? "macos" : "linux";
328
+ active = {
329
+ kind,
330
+ manager: SandboxManager,
331
+ places,
332
+ policy,
333
+ options,
334
+ applied: JSON.stringify(config),
335
+ };
336
+ return { kind, problems: check.warnings };
337
+ }
338
+ /** Runs `true` in the sandbox; null when it ran, otherwise why it did not. */
339
+ async function selfCheck(manager, places, policy) {
340
+ const line = await manager.wrapWithSandbox("true", undefined, {
341
+ filesystem: commandFilesystem(places, policy),
342
+ });
343
+ const outcome = await new Promise((resolve) => {
344
+ const child = spawn(line, { shell: true, stdio: ["ignore", "ignore", "pipe"] });
345
+ let errors = "";
346
+ child.stderr.on("data", (chunk) => {
347
+ errors = (errors + chunk.toString("utf8")).slice(-500);
348
+ });
349
+ const timer = setTimeout(() => {
350
+ child.kill("SIGKILL");
351
+ resolve("a test command in the sandbox did not finish within 10 seconds");
352
+ }, 10_000);
353
+ child.on("error", (error) => {
354
+ clearTimeout(timer);
355
+ resolve(`a test command in the sandbox could not start: ${error.message}`);
356
+ });
357
+ child.on("close", (code) => {
358
+ clearTimeout(timer);
359
+ resolve(code === 0 ? null : `a test command in the sandbox failed (${code}): ${errors.trim()}`);
360
+ });
361
+ });
362
+ manager.cleanupAfterCommand();
363
+ return outcome;
364
+ }
365
+ /** Stops the sandbox's helpers (its proxies) when `yew serve` stops. */
366
+ export async function stopSandbox() {
367
+ const current = active;
368
+ active = null;
369
+ running.clear();
370
+ await current?.manager.reset();
371
+ }
372
+ /** The sandbox commands run in now; "none" when it is off. */
373
+ export function activeSandbox() {
374
+ return active?.kind ?? "none";
375
+ }
376
+ /**
377
+ * Prepares `command` (a shell command line) to run in the sandbox; null when the sandbox is off.
378
+ * `ask` puts a site the command wants to reach to the person and resolves whether they allowed it.
379
+ */
380
+ export async function sandboxed(command, options = {}) {
381
+ const current = active;
382
+ if (!current)
383
+ return null;
384
+ const policy = current.policy();
385
+ // A changed setting or a new key applies from the next command on.
386
+ const config = sandboxConfig(current.places, policy, current.options);
387
+ const applied = JSON.stringify(config);
388
+ if (applied !== current.applied) {
389
+ current.manager.updateConfig(config);
390
+ current.applied = applied;
391
+ }
392
+ // The id ties the command's connections to its allow list: random, never guessable.
393
+ const id = randomBytes(16).toString("base64url");
394
+ const line = await current.manager.wrapWithSandbox(command, undefined, { filesystem: commandFilesystem(current.places, policy, options.grant) }, undefined, { commandId: id, commandText: options.text ?? command });
395
+ const allowed = [...(options.grant?.sites ?? [])];
396
+ running.set(id, {
397
+ label: options.label ?? { kind: "command", text: (options.text ?? command).slice(0, 300) },
398
+ ...(options.ask ? { ask: options.ask } : {}),
399
+ allowed,
400
+ refused: new Set(),
401
+ asking: new Map(),
402
+ });
403
+ if (allowed.length > 0)
404
+ current.manager.registerCommandNetworkLists(id, { allowedDomains: allowed });
405
+ let finished = null;
406
+ return {
407
+ line,
408
+ env: sandboxEnvironment(current.places),
409
+ unset: policy.credentials ? [] : AGENT_VARIABLES,
410
+ finish: () => {
411
+ if (finished)
412
+ return finished;
413
+ running.delete(id);
414
+ if (active !== current) {
415
+ finished = [];
416
+ return finished;
417
+ }
418
+ current.manager.unregisterCommandNetworkLists(id);
419
+ finished = current.manager
420
+ .getSandboxViolationStore()
421
+ .getViolationsForCommand(id)
422
+ .map((violation) => violation.line)
423
+ // Files and connections; programs also look up system values they are not given, which
424
+ // rarely matters and would only bury these.
425
+ .filter((line) => /\b(file-|network)/.test(line));
426
+ // Leftovers of commands (Linux mount points) go once none is running.
427
+ if (running.size === 0)
428
+ current.manager.cleanupAfterCommand();
429
+ return finished;
430
+ },
431
+ };
432
+ }
433
+ /** A word for a shell command line, in single quotes. */
434
+ export function quote(word) {
435
+ return `'${word.replace(/'/g, `'\\''`)}'`;
436
+ }
437
+ /**
438
+ * Settings for a command the person approved to run outside the sandbox: git runs no hooks and no
439
+ * file system monitor there, so one a command planted inside cannot come along with a push.
440
+ */
441
+ export const OUTSIDE_GIT = {
442
+ GIT_CONFIG_COUNT: "2",
443
+ GIT_CONFIG_KEY_0: "core.hooksPath",
444
+ GIT_CONFIG_VALUE_0: "/dev/null",
445
+ GIT_CONFIG_KEY_1: "core.fsmonitor",
446
+ GIT_CONFIG_VALUE_1: "false",
447
+ };
@@ -1,8 +1,9 @@
1
1
  import { existsSync, realpathSync, statSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { basename, dirname, isAbsolute, join } from "node:path";
3
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
4
  import { DEFAULT_RELAY_URL } from "../shared/types.js";
5
5
  import { invalid } from "./errors.js";
6
+ import { canonical } from "./permissions/paths.js";
6
7
  /** Which kinds of events notify the phone (blueprint 6.10, item 34). All on unless turned off. */
7
8
  export const NOTIFY_KINDS = ["waiting", "error", "task", "budget"];
8
9
  export const SETTING_DEFAULTS = {
@@ -33,7 +34,20 @@ export const SETTING_DEFAULTS = {
33
34
  disabledSkills: [],
34
35
  /** The mascot at the foot of the sidebar and the opening animation (blueprint, section 12). */
35
36
  mascot: true,
37
+ /** Whether the opening leaves by itself once started, or waits for a click (blueprint 6.10, item 45). */
38
+ opening: "auto",
39
+ /**
40
+ * Whether commands in the system sandbox may use the SSH agent and the usual credential files;
41
+ * off by default (founder, 11-18, on the security group's advice; blueprint, section 11).
42
+ */
43
+ sandboxCredentials: false,
44
+ /**
45
+ * Folders sessions may not read, besides credentials and Yew Harness's own data: file tools refuse
46
+ * them, searches leave them out, and the system sandbox closes them (the security group, 11-18).
47
+ */
48
+ hiddenFolders: [],
36
49
  };
50
+ export const OPENING_MODES = ["auto", "click"];
37
51
  export function readSettings(store) {
38
52
  const workspaces = store.getSetting("workspaces", SETTING_DEFAULTS.workspaces);
39
53
  const defaultWorkspaceId = store.getSetting("defaultWorkspaceId", SETTING_DEFAULTS.defaultWorkspaceId);
@@ -55,8 +69,27 @@ export function readSettings(store) {
55
69
  notify: { ...SETTING_DEFAULTS.notify, ...store.getSetting("notify", SETTING_DEFAULTS.notify) },
56
70
  disabledSkills: store.getSetting("disabledSkills", SETTING_DEFAULTS.disabledSkills),
57
71
  mascot: store.getSetting("mascot", SETTING_DEFAULTS.mascot),
72
+ opening: store.getSetting("opening", SETTING_DEFAULTS.opening),
73
+ sandboxCredentials: store.getSetting("sandboxCredentials", SETTING_DEFAULTS.sandboxCredentials),
74
+ hiddenFolders: store.getSetting("hiddenFolders", SETTING_DEFAULTS.hiddenFolders),
58
75
  };
59
76
  }
77
+ /**
78
+ * A folder kept from sessions, as saved: absolute, `~` expanded, links resolved where it exists. It
79
+ * may not exist yet. The root and the home folder are refused: they would hide everything.
80
+ */
81
+ export function resolveHiddenFolder(path, userHome = homedir()) {
82
+ const trimmed = path.trim();
83
+ const expanded = trimmed === "~" || trimmed.startsWith("~/") ? join(userHome, trimmed.slice(2)) : trimmed;
84
+ if (!isAbsolute(expanded)) {
85
+ throw invalid("A folder kept from sessions must be an absolute path.", "hiddenFolders");
86
+ }
87
+ const resolved = canonical(resolve(expanded));
88
+ if (resolved === "/" || resolved === canonical(userHome)) {
89
+ throw invalid(`${path} would hide everything; name a folder inside it.`, "hiddenFolders");
90
+ }
91
+ return resolved;
92
+ }
60
93
  /** The decision log must be a Markdown file in an existing folder; `~` is expanded. */
61
94
  export function resolveLogFile(path) {
62
95
  const expanded = path === "~" || path.startsWith("~/") ? join(homedir(), path.slice(2)) : path;
@@ -7,9 +7,10 @@ export class Jobs {
7
7
  constructor(onFinish) {
8
8
  this.#onFinish = onFinish;
9
9
  }
10
- start(options) {
10
+ /** Starts a command in the background; it runs in the sandbox like any other, but never asks the person. */
11
+ async start(options) {
11
12
  const id = `job-${this.#next++}`;
12
- const running = startCommand(options);
13
+ const running = await startCommand({ ...options, background: true });
13
14
  const job = {
14
15
  id,
15
16
  command: options.command,
@@ -443,7 +443,13 @@ export const finishTaskTool = {
443
443
  description: "Record how your task ended: done, given_up or failed. Then end your turn with your report: the result, what changed, how you checked it, and what is left.",
444
444
  parameters: {
445
445
  type: "object",
446
- properties: { result: { type: "string", enum: [...TASK_OUTCOMES] } },
446
+ properties: {
447
+ result: { type: "string", enum: [...TASK_OUTCOMES] },
448
+ next: {
449
+ type: "string",
450
+ description: "What is left, and who does it next. Leave it out when nothing is.",
451
+ },
452
+ },
447
453
  required: ["result"],
448
454
  additionalProperties: false,
449
455
  },
@@ -457,6 +463,10 @@ export const finishTaskTool = {
457
463
  const outcome = choice(args, "result", TASK_OUTCOMES);
458
464
  if (!outcome)
459
465
  throw new ToolInputError("result is required.");
466
+ // What is left is kept with the call itself, where an evaluation reads it (PROTOCOL_VERSION 1).
467
+ if (args.next !== undefined && typeof args.next !== "string") {
468
+ throw new ToolInputError("next is text: what is left, and who does it next.");
469
+ }
460
470
  const session = ctx.mail.finish(outcome);
461
471
  const to = session.parentId
462
472
  ? `It goes to ${nameOf(ctx.mail, session.parentId)}.`