@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.30

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 (152) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/README.md +564 -97
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +11 -5
  6. package/dist/agents.js +16 -10
  7. package/dist/app.js +80 -20
  8. package/dist/background.d.ts +28 -0
  9. package/dist/background.js +376 -0
  10. package/dist/box-egress.d.ts +98 -0
  11. package/dist/box-egress.js +259 -0
  12. package/dist/box-image.d.ts +1 -1
  13. package/dist/box-image.js +9 -7
  14. package/dist/box-relay-vm.d.ts +80 -0
  15. package/dist/box-relay-vm.js +389 -0
  16. package/dist/box-relay.d.ts +8 -5
  17. package/dist/box-relay.js +14 -9
  18. package/dist/boxes.d.ts +21 -3
  19. package/dist/boxes.js +14 -7
  20. package/dist/browser-cost.d.ts +41 -0
  21. package/dist/browser-cost.js +158 -0
  22. package/dist/cap.d.ts +129 -21
  23. package/dist/cap.js +338 -67
  24. package/dist/coding-tools.d.ts +7 -3
  25. package/dist/coding-tools.js +16 -10
  26. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  27. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  28. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  29. package/dist/console/index.html +2 -2
  30. package/dist/content-filter.d.ts +7 -0
  31. package/dist/content-filter.js +23 -0
  32. package/dist/decision-rows.d.ts +11 -3
  33. package/dist/decision-rows.js +18 -11
  34. package/dist/errors.d.ts +2 -0
  35. package/dist/errors.js +5 -2
  36. package/dist/files.d.ts +6 -1
  37. package/dist/files.js +7 -2
  38. package/dist/grade.d.ts +7 -10
  39. package/dist/grade.js +31 -51
  40. package/dist/graph-served.d.ts +23 -0
  41. package/dist/graph-served.js +75 -0
  42. package/dist/graph-view.d.ts +7 -5
  43. package/dist/graph-view.js +10 -3
  44. package/dist/harness-app.d.ts +4 -2
  45. package/dist/harness-app.js +101 -19
  46. package/dist/harness-opencode/adapter.d.ts +45 -0
  47. package/dist/harness-opencode/adapter.js +272 -0
  48. package/dist/harness-opencode/binary.d.ts +18 -0
  49. package/dist/harness-opencode/binary.js +87 -0
  50. package/dist/harness-opencode/config.d.ts +24 -0
  51. package/dist/harness-opencode/config.js +61 -0
  52. package/dist/harness-opencode/harness.d.ts +77 -0
  53. package/dist/harness-opencode/harness.js +620 -0
  54. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  55. package/dist/harness-opencode/host/mcp.js +208 -0
  56. package/dist/harness-opencode/host/policy.d.ts +71 -0
  57. package/dist/harness-opencode/host/policy.js +419 -0
  58. package/dist/harness-opencode/host/server.d.ts +55 -0
  59. package/dist/harness-opencode/host/server.js +165 -0
  60. package/dist/harness-opencode/index.d.ts +9 -0
  61. package/dist/harness-opencode/index.js +6 -0
  62. package/dist/harness-opencode/verify.d.ts +32 -0
  63. package/dist/harness-opencode/verify.js +75 -0
  64. package/dist/harness-opencode/versions.d.ts +33 -0
  65. package/dist/harness-opencode/versions.js +64 -0
  66. package/dist/harness.d.ts +4 -1
  67. package/dist/harness.js +5 -2
  68. package/dist/host-tools.d.ts +12 -2
  69. package/dist/host-tools.js +26 -12
  70. package/dist/host.js +6 -2
  71. package/dist/hosted-search.js +5 -1
  72. package/dist/import.d.ts +2 -2
  73. package/dist/import.js +4 -3
  74. package/dist/key-check.d.ts +3 -2
  75. package/dist/key-check.js +7 -3
  76. package/dist/key-refusal.js +8 -4
  77. package/dist/learn/check.d.ts +10 -1
  78. package/dist/learn/check.js +19 -1
  79. package/dist/learn/grade.d.ts +3 -2
  80. package/dist/learn/grade.js +25 -13
  81. package/dist/learn/index.d.ts +2 -2
  82. package/dist/learn/index.js +2 -2
  83. package/dist/learn/notes.js +2 -1
  84. package/dist/learn/reflect.d.ts +2 -2
  85. package/dist/learn/reflect.js +51 -5
  86. package/dist/learn/secrets.js +28 -8
  87. package/dist/learn/skills.d.ts +17 -4
  88. package/dist/learn/skills.js +79 -6
  89. package/dist/learned-workflow.d.ts +59 -0
  90. package/dist/learned-workflow.js +191 -0
  91. package/dist/learning-run.d.ts +7 -5
  92. package/dist/learning-run.js +45 -23
  93. package/dist/learning-words.d.ts +6 -3
  94. package/dist/learning-words.js +8 -5
  95. package/dist/learning.d.ts +44 -3
  96. package/dist/learning.js +148 -3
  97. package/dist/mcp-servers.d.ts +7 -4
  98. package/dist/mcp-servers.js +5 -0
  99. package/dist/mcp.js +5 -5
  100. package/dist/model.d.ts +13 -11
  101. package/dist/model.js +11 -10
  102. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  103. package/dist/openapi.js +358 -48
  104. package/dist/paid-calls.d.ts +5 -1
  105. package/dist/paid-calls.js +1 -1
  106. package/dist/pause.d.ts +2 -0
  107. package/dist/place.d.ts +27 -4
  108. package/dist/place.js +42 -10
  109. package/dist/propose.d.ts +2 -0
  110. package/dist/propose.js +38 -8
  111. package/dist/request-start.d.ts +12 -4
  112. package/dist/request-start.js +139 -15
  113. package/dist/run-box.d.ts +56 -4
  114. package/dist/run-box.js +173 -23
  115. package/dist/runnable.d.ts +5 -2
  116. package/dist/runnable.js +12 -4
  117. package/dist/runs.d.ts +258 -36
  118. package/dist/runs.js +830 -89
  119. package/dist/secrets.d.ts +12 -0
  120. package/dist/secrets.js +18 -0
  121. package/dist/server.d.ts +131 -35
  122. package/dist/server.js +467 -105
  123. package/dist/sign-ins.d.ts +99 -0
  124. package/dist/sign-ins.js +288 -0
  125. package/dist/skills.d.ts +16 -4
  126. package/dist/skills.js +35 -7
  127. package/dist/stats.d.ts +7 -2
  128. package/dist/stats.js +28 -7
  129. package/dist/tool-gate.d.ts +266 -0
  130. package/dist/tool-gate.js +554 -0
  131. package/dist/tool-keys.d.ts +46 -10
  132. package/dist/tool-keys.js +44 -2
  133. package/dist/tool-plane.d.ts +112 -27
  134. package/dist/tool-plane.js +205 -47
  135. package/dist/tools.d.ts +69 -14
  136. package/dist/tools.js +143 -24
  137. package/dist/trigger-secrets.d.ts +32 -0
  138. package/dist/trigger-secrets.js +143 -0
  139. package/dist/triggers.d.ts +439 -0
  140. package/dist/triggers.js +863 -0
  141. package/dist/turn-end.d.ts +3 -2
  142. package/dist/turn-end.js +3 -2
  143. package/dist/usage-lines.d.ts +26 -0
  144. package/dist/usage-lines.js +28 -0
  145. package/dist/validate.d.ts +2 -0
  146. package/dist/validate.js +11 -2
  147. package/dist/webhooks.d.ts +11 -4
  148. package/dist/webhooks.js +17 -1
  149. package/launcher/agentrun-serve +1 -1
  150. package/package.json +19 -13
  151. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  152. package/dist/console/assets/index-By-jkqki.css +0 -1
package/dist/run-box.d.ts CHANGED
@@ -2,9 +2,16 @@ import type { Context } from "@earendil-works/chord";
2
2
  import type { ExecutionEnv } from "@earendil-works/pi-durable/env";
3
3
  import type { BoxProvider, BoxSpec } from "@parcha/pi-transport";
4
4
  import type { PullReceipt } from "@parcha/pi-transport/sync";
5
+ import { type BoxEgress, type DockerNetwork, egressBlockedBy } from "./box-egress.js";
5
6
  import { type Place } from "./place.js";
6
7
  /** The label a run's box carries: the run's id. */
7
8
  export declare const RUN_LABEL = "agentrun.run";
9
+ /** And, on a box made with a network list, this one: the list's hash (netLabelOf). A box with none carries no such label,
10
+ * so its `docker run` is as it was. */
11
+ export declare const NET_LABEL = "agentrun.net";
12
+ /** The network label's value for a list: the same hosts give the same label, in whatever order and case the setting
13
+ * names them, each once. */
14
+ export declare const netLabelOf: (allow: readonly string[]) => string;
8
15
  /** And this one, the same on every run's box, which the start's sweep lists them by. */
9
16
  export declare const KIND_LABEL = "agentrun.box";
10
17
  /** The whole environment of a box's programs: a constant, never this process's. */
@@ -36,6 +43,22 @@ export type BoxLimits = {
36
43
  * that every create would fail on (less than a 1 ms quota, less memory than Docker gives, more processes than the kernel
37
44
  * allows), throws, naming its setting: the start checks them (startServe), so no run meets one. */
38
45
  export declare function boxLimitsOf(env: NodeJS.ProcessEnv): BoxLimits;
46
+ /** The setting that names the hosts a box may reach: a comma list of hosts, each a name or `*.` and a name, which
47
+ * replaces the default list; `none` for no network at all. Unset or empty, the default. */
48
+ export declare const BOX_ALLOW_ENV = "AGENTRUN_BOX_ALLOW";
49
+ /** The hosts a box reaches when the setting names none: the package registries pip and npm (and yarn) install from, and
50
+ * GitHub for a clone or an archive. */
51
+ export declare const DEFAULT_BOX_ALLOW: readonly string[];
52
+ /** The most hosts the list may hold: Daytona's own limit on a sandbox's domain list. */
53
+ export declare const MAX_BOX_ALLOW = 100;
54
+ /** The hosts a box may reach, from `env`'s AGENTRUN_BOX_ALLOW: its list, lower-cased, each host once; the default list when
55
+ * unset or empty; `none` for no network. `*`, an IP address, a CIDR, a port, a URL, or more than 100 hosts throws, saying
56
+ * what the setting takes: the start checks it (startServe), so no run meets one. */
57
+ export declare function boxAllowOf(env: NodeJS.ProcessEnv): readonly string[] | "none";
58
+ /** What a server's Docker boxes reach, resolved once at its start: the setting's list (boxAllowOf) where egressBlockedBy
59
+ * (box-egress.ts) finds the daemon is this Linux machine's own, else none with the reason; `none` from the setting, with
60
+ * it as the reason. */
61
+ export declare function boxNetworkOf(env: NodeJS.ProcessEnv, options?: Parameters<typeof egressBlockedBy>[1]): Promise<DockerNetwork>;
39
62
  /** Under `--faux` only: a module whose default export, given the data root, is the provider runs' boxes come from in
40
63
  * place of Docker (the tests' faux box). */
41
64
  export declare const FAUX_BOX_ENV = "AGENTRUN_SERVE_FAUX_BOX";
@@ -54,9 +77,12 @@ export declare function mountSource(root: string, source: string): Promise<strin
54
77
  /** Every mount a run's box gets, each through mountSource: its work/ only, read-write, at BOX_WORK. A run's home joins
55
78
  * this list (read-only parts included) when it comes; nothing else of the data root does. */
56
79
  export declare function boxMounts(root: string, runDir: string, place: Place): Promise<Mount[]>;
57
- /** The provider runs' boxes come from, and what a create of its box waits on first (`ready`, run-box below). */
80
+ /** The provider runs' boxes come from, what a create of its box waits on first (`ready`, run-box below), and, for a box
81
+ * that reaches the server's host list, where it finds its egress proxy (`egress`, box-egress.ts). */
58
82
  export type RunBoxes = BoxProvider & {
59
83
  ready?: BoxReady;
84
+ egress?: BoxEgress;
85
+ net?: string;
60
86
  };
61
87
  /** The provider runs' boxes come from: under `--faux` with a faux box, its module's; else Docker on this machine, run as
62
88
  * this process's user (serve's: a run's process is its child), so what a box writes in work/ stays serve's, within the
@@ -94,13 +120,39 @@ export declare function runBox(given: BoxSource | (() => Promise<RunBoxes>), run
94
120
  dir: string;
95
121
  place: Place;
96
122
  }): RunBox;
123
+ /** A remote box's limits, where its provider takes them (the VM box: CPUs and memory, from the same settings as a Docker
124
+ * box's, boxLimitsOf). */
125
+ export type RemoteLimits = {
126
+ cpus?: number;
127
+ memoryMb?: number;
128
+ };
129
+ /** A Docker size (boxLimitsOf's memory) in MiB, the fraction dropped. */
130
+ export declare const memoryMbOf: (memory: string) => number;
97
131
  /** The server's side of a remote box: run `run`'s box, found by its label or made, with its work/ seeded once (its mark
98
- * says so); its id, and whether it was made now. A found box whose network is not closed is destroyed and made again;
99
- * a box whose seed fails is destroyed, and the call fails. */
132
+ * says so); its id, and whether it was made now. A box is made with the host list `allow` names, or with no network when
133
+ * it is `none`; a create the provider refuses for its list (NO_LIST) is said to `onNoList` at once, with its refusal's
134
+ * code and words (so a closed box or a seed that then fails leaves it said), and made again with no network, never open.
135
+ * A found box is kept when it has no network, or the list asked (the same hosts, in any order, as its provider reads
136
+ * them); any other (open, unknown, another list or one it does not say, or a list when `none` was asked) is copied back
137
+ * whole, then destroyed and made again, so a narrower list holds after a restart. One whose copy back fails or is not
138
+ * whole is kept, and the call fails. A box whose seed fails is destroyed, and the call fails. */
139
+ /** What ensureRemoteBox takes beyond the run: the wake of a box Daytona stopped, the hosts the box may reach (`none` for
140
+ * none), who hears a refused list, and the copy back a found box gets before it is replaced (pullRemoteBox). */
141
+ export type RemoteBoxOptions = {
142
+ wake?: () => Promise<number>;
143
+ allow?: readonly string[] | "none";
144
+ onNoList?: (code: string, message: string) => void;
145
+ pull?: (boxes: BoxProvider, run: {
146
+ id: string;
147
+ dir: string;
148
+ }, context: Context, wake?: () => Promise<number>) => Promise<unknown>;
149
+ /** The box's limits, where its provider takes them (remoteSpec). */
150
+ limits?: RemoteLimits;
151
+ };
100
152
  export declare function ensureRemoteBox(boxes: BoxProvider, run: {
101
153
  id: string;
102
154
  dir: string;
103
- }, context: Context, wake?: () => Promise<number>): Promise<{
155
+ }, context: Context, options?: RemoteBoxOptions): Promise<{
104
156
  id: string;
105
157
  made: boolean;
106
158
  }>;
package/dist/run-box.js CHANGED
@@ -2,7 +2,8 @@
2
2
  // is the record (a bound box's read, write and edit run on this machine: bound-files.ts). A run's process that starts
3
3
  // again finds it by that label and first kills the commands the process before it left running. Serve destroys it at
4
4
  // every settle (a cancel included) and at archive, and its start sweeps the boxes of runs that have ended. A box gets the
5
- // run's work/ only, at BOX_WORK, a fixed environment (never this process's, so no key or token enters it), no network,
5
+ // run's work/ only, at BOX_WORK, a fixed environment (never this process's, so no key or token enters it), no network
6
+ // (or, on Docker with the server's host list set, those hosts alone, through this process's egress proxy: box-egress.ts),
6
7
  // and limits on its CPUs, memory and processes. pi-transport is an optional peer of this package: it is loaded only for a
7
8
  // run whose place is a box.
8
9
  //
@@ -10,19 +11,29 @@
10
11
  // cannot bind work/, and its key is the server's alone. The server makes it (through the box relay, box-relay.ts), seeds
11
12
  // it with work/, pulls work/ back at each turn's end and once more before the run's end is recorded, and destroys it
12
13
  // after that pull; the run's process reaches it through the relay, which holds the key. What the run's own host tools
13
- // file in work/ meanwhile (writeInWork) is copied into the box too, so its tools read it.
14
+ // file in work/ meanwhile (writeInWork) is copied into the box too, so its tools read it. The VM box is remote the same
15
+ // way: the server makes, seeds, pulls and ends it with its own client, and the run's process runs pi-transport's VM
16
+ // provider over the relay's VM half (box-relay-vm.ts), which holds the client and the token. It has no network.
14
17
  import { createHash } from "node:crypto";
15
18
  import { appendFile, lstat, readFile, realpath } from "node:fs/promises";
16
19
  import { isAbsolute, join, posix, relative, sep } from "node:path";
17
20
  import { pathToFileURL } from "node:url";
18
21
  import { BACKGROUND_CONTEXT as BACKGROUND } from "@earendil-works/chord/context";
22
+ import { egressBlockedBy, forwarderStart, hostEgress, PROXY_ENV, relayFailed, runBoxAllowOf } from "./box-egress.js";
19
23
  import { awaitImage, boxImageOf } from "./box-image.js";
20
24
  import { RELAYED_KEY, relayedBox, relayFetch } from "./box-relay.js";
25
+ import { VM_PROVIDER } from "./boxes.js";
21
26
  import { readJson, writeDurable } from "./files.js";
22
27
  import { FAUX_ENV } from "./model.js";
23
28
  import { agentWorkDir, BOX_WORK } from "./place.js";
24
29
  /** The label a run's box carries: the run's id. */
25
30
  export const RUN_LABEL = "agentrun.run";
31
+ /** And, on a box made with a network list, this one: the list's hash (netLabelOf). A box with none carries no such label,
32
+ * so its `docker run` is as it was. */
33
+ export const NET_LABEL = "agentrun.net";
34
+ /** The network label's value for a list: the same hosts give the same label, in whatever order and case the setting
35
+ * names them, each once. */
36
+ export const netLabelOf = (allow) => createHash("sha256").update([...new Set(allow.map((host) => host.toLowerCase()))].sort().join(",")).digest("hex").slice(0, 16);
26
37
  /** And this one, the same on every run's box, which the start's sweep lists them by. */
27
38
  export const KIND_LABEL = "agentrun.box";
28
39
  /** The whole environment of a box's programs: a constant, never this process's. */
@@ -76,6 +87,47 @@ export function boxLimitsOf(env) {
76
87
  const pids = read(BOX_PIDS_ENV, "a whole number from 1 to 4194304, such as 1024", (value) => /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= MAX_BOX_PIDS);
77
88
  return { cpus: cpus === undefined ? DEFAULT_BOX_CPUS : Number(cpus), memory: memory ?? DEFAULT_BOX_MEMORY, pidsLimit: pids === undefined ? DEFAULT_BOX_PIDS : Number(pids) };
78
89
  }
90
+ /** The setting that names the hosts a box may reach: a comma list of hosts, each a name or `*.` and a name, which
91
+ * replaces the default list; `none` for no network at all. Unset or empty, the default. */
92
+ export const BOX_ALLOW_ENV = "AGENTRUN_BOX_ALLOW";
93
+ /** The hosts a box reaches when the setting names none: the package registries pip and npm (and yarn) install from, and
94
+ * GitHub for a clone or an archive. */
95
+ export const DEFAULT_BOX_ALLOW = Object.freeze(["pypi.org", "files.pythonhosted.org", "registry.npmjs.org", "registry.yarnpkg.com", "github.com", "codeload.github.com"]);
96
+ /** The most hosts the list may hold: Daytona's own limit on a sandbox's domain list. */
97
+ export const MAX_BOX_ALLOW = 100;
98
+ /** A host name, or `*.` and one: letters, digits and hyphens in dotted labels, the last one starting with a letter, so no
99
+ * IP address is one. */
100
+ const ALLOW_HOST = /^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
101
+ /** The hosts a box may reach, from `env`'s AGENTRUN_BOX_ALLOW: its list, lower-cased, each host once; the default list when
102
+ * unset or empty; `none` for no network. `*`, an IP address, a CIDR, a port, a URL, or more than 100 hosts throws, saying
103
+ * what the setting takes: the start checks it (startServe), so no run meets one. */
104
+ export function boxAllowOf(env) {
105
+ const value = (env[BOX_ALLOW_ENV] ?? "").trim();
106
+ if (!value)
107
+ return DEFAULT_BOX_ALLOW;
108
+ if (value.toLowerCase() === "none")
109
+ return "none";
110
+ const hosts = [...new Set(value.split(",").map((host) => host.trim().toLowerCase()).filter(Boolean))];
111
+ const takes = "a comma list of host names (such as pypi.org or *.pythonhosted.org), or none for no network";
112
+ const bad = hosts.find((host) => !ALLOW_HOST.test(host));
113
+ if (bad !== undefined)
114
+ throw new Error(`${BOX_ALLOW_ENV} is ${takes}: ${JSON.stringify(bad)} is not a host name${bad === "*" ? " (a box never reaches every host)" : ""}`);
115
+ if (hosts.length === 0)
116
+ throw new Error(`${BOX_ALLOW_ENV} is ${takes}; it is ${JSON.stringify(value)}`);
117
+ if (hosts.length > MAX_BOX_ALLOW)
118
+ throw new Error(`${BOX_ALLOW_ENV} names ${hosts.length} hosts; it takes at most ${MAX_BOX_ALLOW}`);
119
+ return Object.freeze(hosts);
120
+ }
121
+ /** What a server's Docker boxes reach, resolved once at its start: the setting's list (boxAllowOf) where egressBlockedBy
122
+ * (box-egress.ts) finds the daemon is this Linux machine's own, else none with the reason; `none` from the setting, with
123
+ * it as the reason. */
124
+ export async function boxNetworkOf(env, options = {}) {
125
+ const allow = boxAllowOf(env);
126
+ if (allow === "none")
127
+ return { allow: "none", reason: `${BOX_ALLOW_ENV} is none` };
128
+ const blocked = await egressBlockedBy(env, options);
129
+ return blocked ? { allow: "none", reason: blocked } : { allow };
130
+ }
79
131
  /** Under `--faux` only: a module whose default export, given the data root, is the provider runs' boxes come from in
80
132
  * place of Docker (the tests' faux box). */
81
133
  export const FAUX_BOX_ENV = "AGENTRUN_SERVE_FAUX_BOX";
@@ -123,7 +175,14 @@ export async function runBoxProvider(place, env, root) {
123
175
  // With no capability and no way to gain one (no program in a run's box changes user): as root (serve run as uid 0) a
124
176
  // box could otherwise make a device node in work/.
125
177
  const image = boxImageOf(env);
126
- return { ...dockerBoxes({ image, ...(user ? { user } : {}), ...boxLimitsOf(env), dropCapabilities: true }), ready: (context, note) => awaitImage(root, image, context, note) };
178
+ // The list the server resolved for this run's box (box-egress.ts boxNetworkOf), or none.
179
+ const allow = runBoxAllowOf(env);
180
+ return {
181
+ ...dockerBoxes({ image, ...(user ? { user } : {}), ...boxLimitsOf(env), dropCapabilities: true }),
182
+ ready: (context, note) => awaitImage(root, image, context, note),
183
+ // Where the proxy runs: the one line that picks it (box-egress.ts BoxEgress).
184
+ ...(allow === "none" ? {} : { egress: hostEgress(allow, env, egressLog), net: netLabelOf(allow) }),
185
+ };
127
186
  }
128
187
  /** The tests' faux box provider, from its module. */
129
188
  export const fauxBoxes = async (module, root) => (await import(pathToFileURL(module).href)).default(root);
@@ -135,7 +194,7 @@ export function runBox(given, run) {
135
194
  const filed = new Map();
136
195
  const open = async (context, note) => {
137
196
  const { boxEnv, endLeftCommands } = await import("@parcha/pi-transport/hands");
138
- const { box, made } = "relay" in source ? await relayedRunBox(source.relay, run.dir, run.id, context) : await localRunBox(await source.provider(), run, context, note);
197
+ const { box, made } = "relay" in source ? await relayedRunBox(source.relay, run, context) : await localRunBox(await source.provider(), run, context, note);
139
198
  if (!made) {
140
199
  // A process before this one left it: what it still runs is killed first, since its calls were answered interrupted.
141
200
  const ended = await endLeftCommands(box, context);
@@ -252,12 +311,33 @@ async function withMirrored(runDir, mark) {
252
311
  function mirrorFailed(paths, error) {
253
312
  process.stderr.write(`${JSON.stringify({ at: new Date().toISOString(), event: "box_mirror_failed", message: `${paths} filed in work/ but not copied into the run's box: ${error.message}` })}\n`);
254
313
  }
314
+ /** Said in the run's process log: one of its egress proxy's decisions (the host, port, address and class). */
315
+ const egressLog = (line) => void process.stderr.write(`${JSON.stringify({ at: new Date().toISOString(), event: "box_egress", line })}\n`);
255
316
  /** A box of this process's provider: the run's, by its label, or one made now with work/ bound, once its image is in
256
- * (the provider's `ready`, `note` writing the one timeline row while it is built or pulled). */
317
+ * (the provider's `ready`, `note` writing the one timeline row while it is built or pulled). A box that reaches the
318
+ * server's host list has the run's egress proxy started first, its directory bound read-only and the proxy variables
319
+ * in its environment, and, made or found, its relay started (startRelay). */
257
320
  async function localRunBox(boxes, run, context, note) {
321
+ let egress;
322
+ try {
323
+ egress = boxes.egress ? await boxes.egress(run.id) : undefined;
324
+ }
325
+ catch (error) {
326
+ throw new Error(`the run's box could not have its network: ${error.message}`);
327
+ }
328
+ // A box a process before this one made with another network (none, or another list: the server's setting changed
329
+ // since) is made again: its mounts and environment are fixed at its create. Its work/ is this machine's, bound.
330
+ await destroyListed(boxes, { [RUN_LABEL]: run.id }, (labels) => labels[NET_LABEL] !== boxes.net, context);
331
+ // And so is one bound to a proxy directory this process had to make again (the start's sweep took the old one once its
332
+ // proxy was gone): the box's bind holds the old directory, which no proxy listens in.
333
+ if (egress?.fresh)
334
+ await destroyListed(boxes, { [RUN_LABEL]: run.id }, () => true, context);
258
335
  const found = await attachRunBox(boxes, run.id, context);
259
- if (found)
336
+ if (found) {
337
+ if (egress)
338
+ await startRelay(found, egress.socket, context, note);
260
339
  return { box: found, made: false };
340
+ }
261
341
  // A box made while the server builds or pulls its image waits for the image, not for a `docker run` that pulls it.
262
342
  if (boxes.ready) {
263
343
  try {
@@ -269,9 +349,11 @@ async function localRunBox(boxes, run, context, note) {
269
349
  throw new Error(`the run's box could not be made: ${error.message}`);
270
350
  }
271
351
  }
352
+ // Docker's network stays none either way: the box's only way out is the proxy's socket, which checks everything.
272
353
  const spec = {
273
- env: BOX_ENV, workspace: agentWorkDir(run.dir, run.place), mounts: await boxMounts(run.root, run.dir, run.place),
274
- labels: { [RUN_LABEL]: run.id, [KIND_LABEL]: "run" }, network: "none", maxLifetimeMs: BOX_LIFETIME_MS,
354
+ env: egress ? { ...BOX_ENV, ...PROXY_ENV } : BOX_ENV, workspace: agentWorkDir(run.dir, run.place),
355
+ mounts: [...(await boxMounts(run.root, run.dir, run.place)), ...(egress ? [egress.mount] : [])],
356
+ labels: { [RUN_LABEL]: run.id, [KIND_LABEL]: "run", ...(boxes.net ? { [NET_LABEL]: boxes.net } : {}) }, network: "none", maxLifetimeMs: BOX_LIFETIME_MS,
275
357
  };
276
358
  const made = await boxes.create(spec, context);
277
359
  if (!made.ok) {
@@ -279,14 +361,36 @@ async function localRunBox(boxes, run, context, note) {
279
361
  await destroyRunBoxes(boxes, run.id, context).catch(() => undefined);
280
362
  throw new Error(`the run's box could not be made: ${made.error.message}`);
281
363
  }
364
+ if (egress)
365
+ await startRelay(made.value, egress.socket, context, note);
282
366
  return { box: made.value, made: true };
283
367
  }
368
+ /** The box's relay to its proxy's `socket` (box-egress.ts forwarder), started in the background and answered once it
369
+ * listens. One that cannot start (an image with no socat or setsid, or a relay not listening in time) leaves the box with
370
+ * no network, nothing listening on its proxy port, and the run's timeline says why (`note`). */
371
+ async function startRelay(box, socket, context, note) {
372
+ const started = await box.exec(forwarderStart(socket), undefined, context);
373
+ if (!started.ok)
374
+ throw new Error(`the run's box could not start its network relay: ${started.error.message}`);
375
+ let said = "";
376
+ const drain = async (stream, keep) => {
377
+ for await (const chunk of stream)
378
+ if (keep && said.length < 1000)
379
+ said += new TextDecoder().decode(chunk);
380
+ };
381
+ const [ended] = await Promise.all([started.value.wait(), drain(started.value.stdout, false), drain(started.value.stderr, true)]);
382
+ if (!ended.ok)
383
+ throw new Error(`the run's box could not start its network relay: ${ended.error.message}`);
384
+ if (ended.value !== 0)
385
+ await Promise.resolve(note(relayFailed(ended.value, said))).catch(() => undefined);
386
+ }
284
387
  /** A remote box, which the server finds or makes and seeds (ensureRemoteBox), reached through its relay: this process's
285
- * Daytona provider holds no key, and every call it makes goes to the relay, which sends it on with the server's. */
286
- async function relayedRunBox(root, runDir, runId, context) {
388
+ * provider holds no key, and every call it makes goes to the relay, which sends it on with the server's (Daytona's key;
389
+ * the VM box's client, box-relay-vm.ts). */
390
+ async function relayedRunBox(root, run, context) {
391
+ const { id: runId, dir: runDir } = run;
287
392
  const given = await relayedBox(root, runDir, runId, context.abortSignal);
288
- const { daytonaBoxes } = await import("@parcha/pi-transport/box/daytona");
289
- const boxes = daytonaBoxes({ apiKey: RELAYED_KEY, apiUrl: given.apiUrl, fetch: relayFetch(root, runDir, runId) });
393
+ const boxes = run.place.mode === "sandbox" && run.place.box === VM_PROVIDER.id ? await relayedVmBoxes(root, runDir, runId) : await relayedDaytona(root, runDir, runId, given.apiUrl);
290
394
  const attached = await boxes.attach(given.id, context);
291
395
  if (!attached.ok)
292
396
  throw new Error(`the run's box could not be reached: ${attached.error.message}`);
@@ -294,36 +398,82 @@ async function relayedRunBox(root, runDir, runId, context) {
294
398
  throw new Error(`the run's box ${given.id} is not running`);
295
399
  return { box: attached.value, made: given.made };
296
400
  }
297
- /** The spec of a run's remote box: its work/ comes with its seed, never a mount. */
298
- const remoteSpec = (runId) => ({
299
- env: BOX_ENV, workspace: BOX_WORK, labels: { [RUN_LABEL]: runId, [KIND_LABEL]: "run" }, network: "none", maxLifetimeMs: BOX_LIFETIME_MS,
401
+ /** The run's process's Daytona provider: its calls go to the relay, which adds the key. */
402
+ async function relayedDaytona(root, runDir, runId, apiUrl) {
403
+ if (!apiUrl)
404
+ throw new Error("the server gave the run's Daytona box no API address");
405
+ const { daytonaBoxes } = await import("@parcha/pi-transport/box/daytona");
406
+ return daytonaBoxes({ apiKey: RELAYED_KEY, apiUrl, fetch: relayFetch(root, runDir, runId) });
407
+ }
408
+ /** The run's process's VM provider: pi-transport's, over the relay's client (box-relay-vm.ts). It only attaches. */
409
+ async function relayedVmBoxes(root, runDir, runId) {
410
+ const [{ relayedVmSdk }, transport] = await Promise.all([import("./box-relay-vm.js"), import(`@parcha/pi-transport/box/${VM_PROVIDER.id}`)]);
411
+ return transport.modalBoxes(relayedVmSdk(root, runDir, runId), { appName: "relayed" });
412
+ }
413
+ /** A Docker size (boxLimitsOf's memory) in MiB, the fraction dropped. */
414
+ export const memoryMbOf = (memory) => {
415
+ const size = /^(\d+(?:\.\d+)?)([bkmg])$/i.exec(memory);
416
+ return size ? Math.floor((Number(size[1]) * SIZE_UNITS[size[2].toLowerCase()]) / MIB) : 0;
417
+ };
418
+ /** The spec of a run's remote box: its work/ comes with its seed, never a mount; its network the hosts `allow` names, or
419
+ * none; its limits, where its provider takes them. */
420
+ const remoteSpec = (runId, allow, limits = {}) => ({
421
+ env: BOX_ENV, workspace: BOX_WORK, labels: { [RUN_LABEL]: runId, [KIND_LABEL]: "run" }, network: allow === "none" ? "none" : { allow }, maxLifetimeMs: BOX_LIFETIME_MS,
422
+ ...(limits.cpus === undefined ? {} : { cpus: limits.cpus }), ...(limits.memoryMb ? { memoryMb: limits.memoryMb } : {}),
300
423
  });
424
+ /** Whether a box's hosts, as its provider reads them (undefined: it does not say), are the hosts asked, as a set. */
425
+ const sameHosts = (hosts, asked) => {
426
+ if (!hosts)
427
+ return false;
428
+ const have = new Set(hosts.map((host) => host.toLowerCase()));
429
+ const want = new Set(asked.map((host) => host.toLowerCase()));
430
+ return have.size === want.size && [...want].every((host) => have.has(host));
431
+ };
432
+ /** The refusals of a create with a host list that say the provider cannot keep one here, so a box with no network is made
433
+ * in its place: Daytona did not keep the list (`unsupported`), or refused it (`invalid`, `unauthorized`: a tier that takes
434
+ * none). Never a refusal a closed box would meet too, such as a timeout. */
435
+ const NO_LIST = new Set(["unsupported", "invalid", "unauthorized"]);
301
436
  const markOf = async (runDir) => {
302
437
  const kept = (await readJson(join(runDir, BOX_SYNC_FILE)));
303
438
  return typeof kept?.box === "string" && kept.mark && Array.isArray(kept.mark.entries) ? kept : undefined;
304
439
  };
305
440
  const keepMark = (runDir, mark) => writeDurable(join(runDir, BOX_SYNC_FILE), `${JSON.stringify(mark)}\n`);
306
- /** The server's side of a remote box: run `run`'s box, found by its label or made, with its work/ seeded once (its mark
307
- * says so); its id, and whether it was made now. A found box whose network is not closed is destroyed and made again;
308
- * a box whose seed fails is destroyed, and the call fails. */
309
- export async function ensureRemoteBox(boxes, run, context, wake) {
441
+ export async function ensureRemoteBox(boxes, run, context, options = {}) {
442
+ const { wake, allow = "none", onNoList, pull = pullRemoteBox, limits } = options;
443
+ let asked = allow === "none" ? "none" : "allowlist";
310
444
  let box = await runningRunBox(boxes, run.id, context, wake);
311
445
  let made = false;
312
- if (box && box.facts().network !== "none") {
446
+ const facts = box?.facts();
447
+ const keep = facts?.network === "none" || (facts?.network === "allowlist" && allow !== "none" && sameHosts(facts.allow, allow));
448
+ if (box && !keep) {
449
+ // Its files first, whole: a box replaced here holds nothing only it had. One whose copy back fails, or is not whole,
450
+ // is kept for a later copy, and the call refused, so no tool runs in it.
451
+ try {
452
+ await pull(boxes, run, context, wake);
453
+ }
454
+ catch (error) {
455
+ throw new Error(`the run's box has another host list than this server's now (or a network it does not ask for), and its files could not all be copied back, so it is kept and not used: ${error.message}`);
456
+ }
313
457
  await destroyRunBoxes(boxes, run.id, context);
314
458
  box = undefined;
315
459
  }
316
460
  if (!box) {
317
- const created = await boxes.create(remoteSpec(run.id), context);
461
+ let created = await boxes.create(remoteSpec(run.id, allow, limits), context);
462
+ if (!created.ok && asked === "allowlist" && NO_LIST.has(created.error.code)) {
463
+ asked = "none";
464
+ onNoList?.(created.error.code, created.error.message);
465
+ await destroyRunBoxes(boxes, run.id, context).catch(() => undefined);
466
+ created = await boxes.create(remoteSpec(run.id, "none", limits), context);
467
+ }
318
468
  if (!created.ok) {
319
469
  await destroyRunBoxes(boxes, run.id, context).catch(() => undefined);
320
470
  throw new Error(`the run's box could not be made: ${created.error.message}`);
321
471
  }
322
472
  box = created.value;
323
473
  made = true;
324
- if (box.facts().network !== "none") {
474
+ if (box.facts().network !== asked) {
325
475
  await box.destroy(context);
326
- throw new Error("the run's box was made with its network open, so it is not used");
476
+ throw new Error(`the run's box was made with its network ${box.facts().network ?? "unknown"}, not ${asked === "none" ? "closed" : "its host list"}, so it is not used`);
327
477
  }
328
478
  }
329
479
  // A box found without its seed's mark was made by a server that went down before it seeded it: seeded now.
@@ -28,8 +28,9 @@ export type RevisionShape = {
28
28
  };
29
29
  /** One thing that keeps a revision from running here. `host`: a setting of this host could fix it. `tool` (one it does
30
30
  * not bind), `missing` (a bound tool's unset variables), `adapter`, `decision` (a decision provider's unset key), `codeNodes`
31
- * (code nodes this server does not run), `shell` (a shell or executor call), `tier`, `harness` and `box` (the place's,
32
- * which this server does not have) name it for a run's 409 details. */
31
+ * (code nodes this server does not run), `shell` (a shell or executor call), `tier`, `harness`, `box` (the place's,
32
+ * which this server does not have) and `denied` (a tool a workflow's call node calls that is set to deny) name it for a
33
+ * run's 409 details. */
33
34
  export type Blocker = InputIssue & {
34
35
  host: boolean;
35
36
  tool?: string;
@@ -47,6 +48,8 @@ export type Blocker = InputIssue & {
47
48
  tier?: string;
48
49
  harness?: string;
49
50
  box?: string;
51
+ denied?: string;
52
+ asks?: string;
50
53
  };
51
54
  /**
52
55
  * The model `harness` runs an agentic revision on here: `ref`, its own `provider/model-id`, or with none this host's
package/dist/runnable.js CHANGED
@@ -10,7 +10,8 @@ import { DEFAULT_HARNESS, FAUX_HARNESS_ENV, harnessOffers } from "./harness.js";
10
10
  import { chooseModel, llmTiers, nodeTiers, workflowNodes } from "./model.js";
11
11
  import { boxAvailability, placeFix, RUN_BOXES } from "./place.js";
12
12
  import { allows, BOUND_TOOLS, CALL_TOOLS, grantedTools, missingEnv, NODE_TOOLS, toolOf, workflowTools } from "./tools.js";
13
- import { capabilityOf, isUnavailable, NO_PARALLEL_KEY, planeFor, whyUnavailable } from "./tool-plane.js";
13
+ import { capabilityOf, DENIED, isUnavailable, NO_PARALLEL_KEY, planeFor, whyUnavailable } from "./tool-plane.js";
14
+ import { permissionOf } from "./tool-gate.js";
14
15
  import { PARALLEL_KEY_ENV } from "./decisions.js";
15
16
  /**
16
17
  * The model `harness` runs an agentic revision on here: `ref`, its own `provider/model-id`, or with none this host's
@@ -26,7 +27,7 @@ export async function harnessModel(env, harness, ref, available) {
26
27
  if (own && !available)
27
28
  return undefined;
28
29
  // codex's is the run's usual model, but an OpenAI model it reaches through OpenRouter alone is OpenRouter's (codexRef).
29
- const chosen = own ? (await import("./adapters.js")).claudeModel(env, ref) : harness === "codex" ? await (await import("./adapters.js")).codexModel(env, ref) : await chooseModel(env, ref, "default", harness);
30
+ const chosen = own ? (await import("./adapters.js")).claudeModel(env, ref) : harness === "codex" || harness === "opencode" ? await (await import("./adapters.js")).codexModel(env, ref, harness) : await chooseModel(env, ref, "default", harness);
30
31
  if ("why" in chosen)
31
32
  return chosen;
32
33
  // The harness runs here; whether it runs this model (the revision's, or the default) is checked on it.
@@ -49,10 +50,10 @@ export const CODE_NODES_ENV = "AGENTRUN_SERVE_CODE_NODES";
49
50
  export async function blockersOf(env, revision, settings = {}, { capped = false, boxes = [], offers } = {}) {
50
51
  const out = [];
51
52
  /** A web tool its run would resolve unavailable (tool-plane.ts): a warning at save, a 409 at a run, never another
52
- * provider in its place. */
53
+ * provider in its place. One set to deny is not: its run starts, and the gate refuses each call. */
53
54
  const unavailable = (field, tools, tool) => {
54
55
  const resolved = planeFor(env, { tools, harness, ...(revision.kind === "workflow" ? { workflow: true } : {}), ...(revision.kind === "agentic" && revision.model ? { model: revision.model } : {}), ...(revision.toolSettings ? { overrides: revision.toolSettings } : {}) }, settings, { capped })[capabilityOf(tool)];
55
- if (isUnavailable(resolved))
56
+ if (isUnavailable(resolved) && resolved !== DENIED)
56
57
  out.push({ field, reason: NOT_SET_UP, message: `The tool ${tool} does not run here on ${harness}: ${whyUnavailable(resolved)}.`, host: true, ...(resolved === NO_PARALLEL_KEY ? { missing: { tool, vars: [PARALLEL_KEY_ENV] } } : {}) });
57
58
  };
58
59
  /** A bound tool whose variables this host does not set: a warning at save, a 409 at a run. */
@@ -145,6 +146,13 @@ export async function blockersOf(env, revision, settings = {}, { capped = false,
145
146
  for (const tool of named.calls) {
146
147
  if (!allows(CALL_TOOLS, tool))
147
148
  out.push({ field: "definition.workflow", reason: "not_an_option", message: `A workflow's call nodes run the tools ${CALL_TOOLS.join(", ")} here; this workflow also calls ${tool}.`, host: false, tool });
149
+ // A call node is the author's own step, and it cannot wait for an approval: one that calls a tool set to deny, or to
150
+ // ask (which it could never get), would be refused mid-run (app.ts runEffect), so the run never starts.
151
+ // Held to its settings key: a legacy name (fetch_page) takes its capability's permission (web_fetch's), as the gate does.
152
+ else if (permissionOf(capabilityOf(tool), settings, (revision.toolSettings ?? {})) === "ask")
153
+ out.push({ field: "definition.workflow", reason: NOT_SET_UP, message: `This workflow's call node calls ${capabilityOf(tool) === tool ? tool : `${tool} (${capabilityOf(tool)})`}, which is set to ask, and a workflow's call node can't wait for an approval: set it to allow for this agent.`, host: true, asks: capabilityOf(tool) });
154
+ else if (permissionOf(capabilityOf(tool), settings, (revision.toolSettings ?? {})) === "deny")
155
+ out.push({ field: "definition.workflow", reason: NOT_SET_UP, message: `This workflow's call node calls ${capabilityOf(tool) === tool ? tool : `${tool} (${capabilityOf(tool)})`}, which is set to deny on this server.`, host: true, denied: capabilityOf(tool) });
148
156
  }
149
157
  const granted = await grantedTools(revision);
150
158
  for (const tool of new Set([...named.nodes.filter((name) => allows(NODE_TOOLS, name)), ...named.calls.filter((name) => allows(CALL_TOOLS, name))])) {