@parcha/agentrun-serve 0.1.0-beta.57 → 0.1.0-beta.58

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 (108) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +64 -33
  3. package/dist/api-only.d.ts +2 -4
  4. package/dist/api-only.js +2 -4
  5. package/dist/box-paths.d.ts +4 -3
  6. package/dist/box-paths.js +7 -4
  7. package/dist/claude-login-token.d.ts +117 -0
  8. package/dist/claude-login-token.js +737 -0
  9. package/dist/claude-login.d.ts +52 -12
  10. package/dist/claude-login.js +164 -39
  11. package/dist/cli.js +7 -41
  12. package/dist/computer-attach.d.ts +35 -17
  13. package/dist/computer-attach.js +301 -49
  14. package/dist/computers.d.ts +10 -10
  15. package/dist/computers.js +5 -5
  16. package/dist/console/assets/{backend-DVhHzJX2.js → backend-CSAWUqtZ.js} +1 -1
  17. package/dist/console/assets/index-DPh29cyz.js +747 -0
  18. package/dist/console/index.html +1 -1
  19. package/dist/dial-relay.d.ts +25 -4
  20. package/dist/dial-relay.js +129 -1
  21. package/dist/env-switch.d.ts +1 -3
  22. package/dist/env-switch.js +1 -3
  23. package/dist/fal-price.d.ts +1 -3
  24. package/dist/fal-price.js +77 -26
  25. package/dist/learn/ledger.d.ts +170 -0
  26. package/dist/learn/ledger.js +218 -0
  27. package/dist/learn/promote.d.ts +3 -3
  28. package/dist/learn/promote.js +1 -1
  29. package/dist/learning-cost.d.ts +22 -20
  30. package/dist/learning-cost.js +15 -21
  31. package/dist/live-reach.d.ts +2 -0
  32. package/dist/live-reach.js +2 -0
  33. package/dist/mcp-api-only-origins.d.ts +8 -3
  34. package/dist/mcp-api-only-origins.js +17 -17
  35. package/dist/micro.d.ts +2 -0
  36. package/dist/micro.js +2 -0
  37. package/dist/model.d.ts +5 -4
  38. package/dist/model.js +7 -6
  39. package/dist/monid.d.ts +14 -1
  40. package/dist/monid.js +103 -26
  41. package/dist/openapi.js +34 -12
  42. package/dist/place-offers.d.ts +4 -0
  43. package/dist/place-offers.js +7 -4
  44. package/dist/provider.d.ts +2 -2
  45. package/dist/provider.js +9 -5
  46. package/dist/run-learning-served.d.ts +2 -2
  47. package/dist/run-view.d.ts +1 -2
  48. package/dist/run-view.js +2 -1
  49. package/dist/runner/adapter-loop.js +3 -16
  50. package/dist/runner/adapter-run-spec.d.ts +20 -13
  51. package/dist/runner/adapter-run-spec.js +57 -48
  52. package/dist/runner/beside.d.ts +9 -2
  53. package/dist/runner/beside.js +24 -7
  54. package/dist/runner/claim-secrets.d.ts +17 -15
  55. package/dist/runner/claim-secrets.js +32 -34
  56. package/dist/runner/cli-run-spec.js +21 -9
  57. package/dist/runner/held.d.ts +16 -4
  58. package/dist/runner/main.d.ts +11 -6
  59. package/dist/runner/main.js +12 -7
  60. package/dist/runner/mcp-claim.js +3 -2
  61. package/dist/runner/mcp-run.d.ts +3 -6
  62. package/dist/runner/mcp-run.js +3 -4
  63. package/dist/runner/presence.d.ts +11 -1
  64. package/dist/runner/presence.js +7 -0
  65. package/dist/runner/reflect-hook.js +1 -1
  66. package/dist/runner/run-child-host.d.ts +19 -8
  67. package/dist/runner/run-child-host.js +80 -34
  68. package/dist/runner/runner.d.ts +3 -0
  69. package/dist/runner/runner.js +1 -1
  70. package/dist/runner/save-slots.js +2 -1
  71. package/dist/runner/subagent.d.ts +11 -0
  72. package/dist/runner/subagent.js +17 -3
  73. package/dist/runner/workflow-first.d.ts +27 -14
  74. package/dist/runner/workflow-first.js +29 -22
  75. package/dist/runner/workflow-spec.js +1 -1
  76. package/dist/server.d.ts +18 -7
  77. package/dist/server.js +150 -64
  78. package/dist/slots.d.ts +9 -0
  79. package/dist/slots.js +45 -0
  80. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  81. package/dist/store/schema.d.ts +17 -0
  82. package/dist/store/schema.js +47 -1
  83. package/dist/store/sqlite/run-patch.d.ts +11 -1
  84. package/dist/store/sqlite/run-patch.js +29 -1
  85. package/dist/store/sqlite/store.js +72 -9
  86. package/dist/store/store.d.ts +14 -0
  87. package/dist/store-reads/learning.d.ts +81 -124
  88. package/dist/store-reads/learning.js +207 -286
  89. package/dist/template-eval.d.ts +19 -0
  90. package/dist/template-eval.js +92 -43
  91. package/dist/template-import.d.ts +0 -10
  92. package/dist/template-import.js +5 -10
  93. package/dist/timeline/web-calls.d.ts +12 -14
  94. package/dist/timeline/web-calls.js +14 -30
  95. package/dist/web-save.d.ts +4 -9
  96. package/dist/web-save.js +4 -43
  97. package/dist/workspace/attached-computers.d.ts +32 -9
  98. package/dist/workspace/attached-computers.js +77 -13
  99. package/dist/workspace/computer-deps.d.ts +6 -1
  100. package/dist/workspace/computer-deps.js +1 -1
  101. package/dist/workspace/computer-for-claim.js +6 -3
  102. package/dist/workspace/paired-route.d.ts +91 -0
  103. package/dist/workspace/paired-route.js +153 -0
  104. package/dist/wrapped.d.ts +8 -2
  105. package/dist/wrapped.js +21 -6
  106. package/package.json +12 -12
  107. package/templates/README.md +3 -3
  108. package/dist/console/assets/index-okP-y8PK.js +0 -747
@@ -6,9 +6,12 @@
6
6
  // A Linux box with no display (computerd's hello says linux, with files and exec) is a sandbox: in Mode 2 it holds the
7
7
  // run's folder as a synced folder in its own /workspace, as a hosted computer that dials does.
8
8
  //
9
- // Its socket is held by the AttachHub of the server's process: a runner in that process (the CLI's start, its runner
10
- // beside the server) takes it; a runner of its own process cannot reach it and refuses it in ONE_PROCESS_WORDS.
11
- import { attachedProvider, SETTING_KIND_NAMES, SETTING_KINDS } from "@parcha/agentrun-computer";
9
+ // Its socket is held by the AttachHub of the server's process while no run holds it: a runner in that process (the CLI's
10
+ // start, its runner beside the server) takes it there, its route taken all the same (dial-relay.ts pairedRelayOn over
11
+ // the server's hub, runner/beside.ts), so a runner apart takes it for no other run meanwhile. A runner of its own
12
+ // process with a relay (dial-relay.ts) has the server move the box's socket onto its own hub for the run (PairedRelay,
13
+ // workspace/paired-route.ts); one with no relay cannot reach it and refuses it in ONE_PROCESS_WORDS.
14
+ import { attachedProvider, fail, RUN_LABEL, runLifetimeMs, SETTING_KIND_NAMES, SETTING_KINDS } from "@parcha/agentrun-computer";
12
15
  /** A paired computer's id starts with this; the rest is lowercase letters and digits, so the whole is an id an agent's
13
16
  * computer setting takes as its provider (lowercase letters, digits and dashes). */
14
17
  export const PAIRED_ID_PREFIX = "cmp-";
@@ -16,11 +19,16 @@ export const PAIRED_ID_PREFIX = "cmp-";
16
19
  export const ATTACHED_IMAGE = "attached";
17
20
  /** How to start a server so its runs can use a paired computer, in one line: the same words wherever it is said. */
18
21
  export const ONE_PROCESS_FIX = "start the image with the server options alone, without server-and-runner (outside the image: agentrun-serve without --no-runner)";
19
- /** The words a run gets when its agent's computer is a paired computer and its runner is not in the server's process. */
20
- export const ONE_PROCESS_WORDS = `a paired computer's socket is held by the server process it dialed, and this runner runs in a process of its own: ${ONE_PROCESS_FIX}`;
22
+ /** The fix for a runner in a process of its own that relays no computer's socket: it relays once it has the server's
23
+ * public address (dial-relay.ts). */
24
+ const RELAY_FIX = "give the runner AGENTRUN_PUBLIC_URL (this server's public address)";
25
+ /** The words a run gets when its agent's computer is a paired computer and its runner, in a process of its own, keeps
26
+ * no relay. */
27
+ export const ONE_PROCESS_WORDS = `a paired computer's socket is held by the server process it dialed, and this runner runs in a process of its own and relays no computer's socket: ${RELAY_FIX}, or ${ONE_PROCESS_FIX}`;
21
28
  /** What a pairing code, the pair answer and each paired computer say on a server whose runner runs in a process of its
22
- * own (--no-runner; the image's server-and-runner): the computer pairs, and no run here can use it. */
23
- export const RUNNER_APART_WORDS = `no run on this server can use a paired computer: its runner runs in a process of its own, and the computer's socket is held by the server's: ${ONE_PROCESS_FIX}`;
29
+ * own (--no-runner; the image's server-and-runner) while no runner relays: the computer pairs, and no run here can use
30
+ * it. */
31
+ export const RUNNER_APART_WORDS = `no run on this server can use a paired computer: its runner runs in a process of its own and relays no computer's socket: ${RELAY_FIX}, or ${ONE_PROCESS_FIX}`;
24
32
  /** What a provider whose machines dial this server (the computer package's connectOf "dial": Fly Machines, Cloudflare,
25
33
  * and E2B, Daytona or Modal set to dial) says on such a server: its row in GET /v2/computers and its test. Its
26
34
  * machines' sockets are taken by the server's attach hub, and a runner of its own process has none, so its create
@@ -115,12 +123,68 @@ export function withPaired(registry, rows) {
115
123
  return registry;
116
124
  return { ...registry, PROVIDERS: [...registry.PROVIDERS, ...rows.map((row) => pairedEntry(row, registry))] };
117
125
  }
118
- /** The provider of the paired computer `row`: attachedProvider over the hub, or a refusal in ONE_PROCESS_WORDS where this
119
- * process holds no hub. */
120
- export function pairedProvider(row, hub) {
121
- if (hub === undefined)
122
- throw Object.assign(new Error(ONE_PROCESS_WORDS), { code: "computer_unavailable" });
123
- return attachedProvider(pairedOf(row), hub);
126
+ /** The provider of the paired computer `row`: over a relay's hub where the runner has one (`relay`: a runner apart's
127
+ * own, or the server's for the runner beside it), the box brought there before each create and let go after each
128
+ * release (relayedProvider); else attachedProvider over the server's hub (`hub`) with no route; else a refusal in
129
+ * ONE_PROCESS_WORDS. `claim`: the run's claim (ClaimLaunch.claim), which the bring's route takes under. */
130
+ export function pairedProvider(row, hub, relay, claim) {
131
+ if (relay !== undefined)
132
+ return relayedProvider(row, relay, claim);
133
+ if (hub !== undefined)
134
+ return attachedProvider(pairedOf(row), hub);
135
+ throw Object.assign(new Error(ONE_PROCESS_WORDS), { code: "computer_unavailable" });
136
+ }
137
+ /** attachedProvider over a relay's hub: create brings the box to this runner for the run (its labels' run, its
138
+ * lifetime's end) and is refused in the bring's words, never hanging; a create that fails after the bring lets the box
139
+ * go; release ends the hold, then lets the box go (a run's loop releases in its finally, so a cancelled run or a throw
140
+ * in its pass lets the box go as it unwinds). Every other call is attachedProvider's own. */
141
+ function relayedProvider(row, relay, claim) {
142
+ const inner = attachedProvider(pairedOf(row), relay.hub);
143
+ /** The run of each hold this provider made, by its ref's id (`<computer id>.<hold>`). */
144
+ const runs = new Map();
145
+ return {
146
+ id: inner.id,
147
+ get version() {
148
+ return inner.version;
149
+ },
150
+ capabilities: () => inner.capabilities(),
151
+ check: (spec) => inner.check(spec),
152
+ async create(spec, context) {
153
+ const run = spec.labels?.[RUN_LABEL];
154
+ if (run === undefined)
155
+ return inner.create(spec, context);
156
+ try {
157
+ // The claim's cancel (the create's signal) ends the bring's wait at once, the route it took dropped.
158
+ await relay.bring(row, { run, until: Date.now() + runLifetimeMs(spec), ...(claim ? { claim } : {}), ...(context.signal ? { signal: context.signal } : {}) });
159
+ }
160
+ catch (error) {
161
+ // A superseded claim (Fenced), and any failure that is not the bring's in words, is the claim's to answer.
162
+ if (error.code !== "computer_unavailable")
163
+ throw error;
164
+ return fail(context.signal?.aborted ? "aborted" : "refused", error.message);
165
+ }
166
+ const made = await inner.create(spec, context);
167
+ if (!made.ok) {
168
+ await relay.letGo(row.id, undefined, run).catch(() => undefined);
169
+ return made;
170
+ }
171
+ runs.set(made.value.id, run);
172
+ return made;
173
+ },
174
+ attach: (asked, context) => inner.attach(asked, context),
175
+ list: (labels, context) => inner.list(labels, context),
176
+ network: (asked, policy, context) => inner.network(asked, policy, context),
177
+ connect: (asked) => inner.connect(asked),
178
+ async release(asked, how, context) {
179
+ const done = await inner.release(asked, how, context);
180
+ if (done.ok && asked.id !== row.id) {
181
+ const run = runs.get(asked.id);
182
+ runs.delete(asked.id);
183
+ await relay.letGo(row.id, undefined, run);
184
+ }
185
+ return done;
186
+ },
187
+ };
124
188
  }
125
189
  /** Why the paired computer `row` cannot be had now, in words that say what to do, or undefined: it must be attached (its
126
190
  * driver dialed this server). Asked at a run's start, as a vendor's readiness is; another run's hold is the claim's. */
@@ -6,6 +6,7 @@ import type { FauxComputers } from "../faux-computers.js";
6
6
  import { type KeyEnv } from "../key-meta.js";
7
7
  import { BOX_CPUS_ENV, BOX_MEMORY_ENV, BOX_PIDS_ENV } from "../start-switches.js";
8
8
  import type { Store } from "../store/index.js";
9
+ import type { PairedRelay } from "./attached-computers.js";
9
10
  import { type ClaimComputer, type ClaimLaunch, computerForClaim, type ComputerForClaimDeps, type ComputerSaid, type KeptKind, type OpenComputerView, type Replaced } from "./computer-for-claim.js";
10
11
  import { type ProviderLoad } from "./computer-providers.js";
11
12
  import { type KindRegistry } from "./resolve-computer.js";
@@ -53,8 +54,12 @@ export interface ComputerDepsOptions {
53
54
  readonly pairedComputers?: Pick<Store["pairedComputers"], "list">;
54
55
  };
55
56
  /** The server's AttachHub, where this runner shares the server's process (runner/beside.ts): a paired computer's
56
- * socket is there. Absent: a runner of its own process, which refuses a paired computer in words. */
57
+ * socket is there. Absent: a runner of its own process, which reaches a paired computer through its relay
58
+ * (`pairedRelay`), or refuses one in words where it keeps none. */
57
59
  readonly hub?: AttachHub;
60
+ /** The relay of a runner in a process of its own (dial-relay.ts RunnerRelay.paired): the server moves a paired
61
+ * computer's socket onto its hub for the run. Absent: none. */
62
+ readonly pairedRelay?: PairedRelay;
58
63
  /** The server's dial (Serve.dial), where this runner shares the server's process: every remote provider's create
59
64
  * takes it, and one whose host dials the server (facts.connect "dial") mints its machine's token there. Absent: a
60
65
  * runner of its own process, where such a provider's create refuses in words. */
@@ -326,7 +326,7 @@ export function computerDepsFrom(options) {
326
326
  ...(options.hostWhy ? { hostWhy: (provider) => (Object.hasOwn(options.hostWhy, provider) ? options.hostWhy[provider] : undefined) } : {}),
327
327
  ...(options.daemon ? { daemon: options.daemon } : { daemon: dockerDaemonOf(env) }),
328
328
  ...(options.openComputerView ? { openComputerView: options.openComputerView } : {}),
329
- ...(store.pairedComputers ? { attached: { rows: () => store.pairedComputers.list(), ...(options.hub ? { hub: options.hub } : {}) } } : {}),
329
+ ...(store.pairedComputers ? { attached: { rows: () => store.pairedComputers.list(), ...(options.hub ? { hub: options.hub } : {}), ...(options.pairedRelay ? { relay: options.pairedRelay } : {}) } } : {}),
330
330
  };
331
331
  const factories = { ...computerProviderFactories(providers, (id) => storeLedger(store.computerLedger, id)), ...faux?.factories };
332
332
  return { computerForClaim: claimComputer, computerDeps, factories };
@@ -35,8 +35,9 @@
35
35
  // and a test's stand-ins are passed in.
36
36
  //
37
37
  // A paired computer (a person's own, attached-computers.ts) is one more provider of the registry for the claim, by its
38
- // id: claimed through the hub of the server's process (the computer package's attachedProvider), released by ending the
39
- // run's hold, never made or deleted.
38
+ // id: claimed through the hub of the server's process (the computer package's attachedProvider), or through a runner's
39
+ // relay hub once the server moved the box's socket there (dial-relay.ts), released by ending the run's hold, never made
40
+ // or deleted.
40
41
  //
41
42
  // A persistent setting (the agent's own computer, agent-computer.ts) is made once under the agent's owner (this server's
42
43
  // id and the agent's), found again by its owner at each later claim and attached under the new claim, and detached, not
@@ -856,7 +857,9 @@ store, deps) {
856
857
  madeBy = entry;
857
858
  return own;
858
859
  }
859
- const provider = pairedRow ? pairedProvider(pairedRow, deps.attached?.hub) : await vendorProvider(entry, keys, configuration);
860
+ // Under a runner of its own process, through its relay: the box is routed under the run's claim (launch.claim, a
861
+ // store Claim from each claim's launch), so a claim another runner superseded is Fenced at the route.
862
+ const provider = pairedRow ? pairedProvider(pairedRow, deps.attached?.hub, deps.attached?.relay, launch.claim) : await vendorProvider(entry, keys, configuration);
860
863
  const spec = { ...(await specOf(entry, provider, kind, configuration, signal, gpu)), ...(mount ? { mount } : {}) };
861
864
  // A browser makes nothing here: the run's browser tool opens each session through it, so a session lives (and is
862
865
  // booked) only while the tool holds it.
@@ -0,0 +1,91 @@
1
+ import { type Claim, type Runners, type Runs, type Settings } from "../store/index.js";
2
+ /** The settings key prefix of the paired computers' routes, one row per computer. */
3
+ export declare const ROUTE_PREFIX = "paired_route:";
4
+ /** The settings key of computer `id`'s route. */
5
+ export declare const routeKeyOf: (id: string) => string;
6
+ /** How often the server compares each route with where the box's socket is (server.ts, computer-attach.ts tick). */
7
+ export declare const PAIRED_ROUTE_MS = 1000;
8
+ /** How long a run's claim waits for its box to reach its runner: one tick of the server's, the driver's longest wait
9
+ * between dials (it backs off after quick reconnects), the relay's connect and the hub's hello. */
10
+ export declare const PAIRED_BRING_MS: number;
11
+ /** How often the claim reads the route while it waits. */
12
+ export declare const PAIRED_BRING_POLL_MS = 500;
13
+ /** A paired computer's route: the runner whose hub holds the box for `run` (and that runner's incarnation), the hold's
14
+ * end (ms), and the server's note of why a route was refused or dropped. All null: no route, the server's hub. */
15
+ export type Route = {
16
+ readonly runner: string | null;
17
+ readonly incarnation: string | null;
18
+ readonly run: string | null;
19
+ readonly until: number | null;
20
+ readonly refused: string | null;
21
+ };
22
+ /** No route and no note. */
23
+ export declare const EMPTY_ROUTE: Route;
24
+ /** What a run's claim asks: its runner and incarnation, the run, and its hold's end (ms). */
25
+ export type RouteWant = {
26
+ readonly runner: string;
27
+ readonly incarnation: string;
28
+ readonly run: string;
29
+ readonly until: number;
30
+ };
31
+ /** The settings the routes live in. */
32
+ export type RouteSettings = Pick<Settings, "get" | "putIfAbsent" | "replaceIf" | "removeIf" | "remove" | "all">;
33
+ /** What a take reads: the routes, the runners (is the route's runner live), and the runs (is the route's run final). */
34
+ export type RouteDeps = {
35
+ readonly settings: Pick<RouteSettings, "get" | "putIfAbsent" | "replaceIf" | "removeIf">;
36
+ readonly runners: Pick<Runners, "live">;
37
+ readonly runs?: Pick<Runs, "get">;
38
+ };
39
+ /** A row's value as a Route; anything else reads as EMPTY_ROUTE. */
40
+ export declare function routeOf(value: unknown): Route;
41
+ /** Computer `id`'s route as its row reads now: EMPTY_ROUTE when there is none. */
42
+ export declare function readRoute(settings: Pick<RouteSettings, "get">, id: string): Promise<Route>;
43
+ /** Computer `id`'s route and its row's value as read (undefined: no row), for a compare-and-set on it. */
44
+ export declare function seeRoute(settings: Pick<RouteSettings, "get">, id: string): Promise<{
45
+ readonly seen: unknown;
46
+ readonly route: Route;
47
+ }>;
48
+ /** Every route row, as the server's tick reads them: one read of the prefix, a range on the settings' primary key. */
49
+ export declare function allRoutes(settings: Pick<RouteSettings, "all">): Promise<{
50
+ readonly id: string;
51
+ readonly seen: unknown;
52
+ readonly route: Route;
53
+ }[]>;
54
+ /** Writes `next` over computer `id`'s row while it still holds `seen` (as read): one compare-and-set. An empty `next` (no
55
+ * route, no note) removes the row. False when the row changed since. */
56
+ export declare function replaceRoute(settings: Pick<RouteSettings, "putIfAbsent" | "replaceIf" | "removeIf">, id: string, seen: unknown, next: Route, claim?: Claim): Promise<boolean>;
57
+ /** `name` held by another run, on a live runner. */
58
+ export declare const heldWords: (name: string, run: string, runner: string) => string;
59
+ /** How a stale route's words end (the server's 503 and the box's note): where the box goes, and when. */
60
+ export declare const ROUTE_COMES_BACK = "it comes back to this server at its next dial, within 60 s, and the run's next claim takes it again";
61
+ /** What a route says once its runner restarted. The words for a runner gone are the relay's own (computer-attach.ts
62
+ * relayDial), ending in ROUTE_COMES_BACK. */
63
+ export declare const routeRestartedWords: (runner: string) => string;
64
+ /** A box routed to a run's runner, attached nowhere: the claim's wait ends in these words. */
65
+ export declare const notAttachedWords: (name: string) => string;
66
+ /** A box that did not reach its run's runner within PAIRED_BRING_MS. */
67
+ export declare const lateWords: (name: string, runner: string) => string;
68
+ /** What a take came to: the route taken (as written), or why not, with the route as it is. */
69
+ export type Took = {
70
+ readonly taken: true;
71
+ readonly route: Route;
72
+ } | {
73
+ readonly taken: false;
74
+ readonly why: string;
75
+ readonly route: Route;
76
+ };
77
+ /** Routes computer `id` to `want`'s runner for its run, where holdsAgainst lets it: the run's claim, before it waits for
78
+ * the box (dial-relay.ts bring). With `claim`, the write checks the claim's epoch and lease in its transaction, so a
79
+ * claim another runner superseded throws Fenced and writes nothing. `name` is the computer's, for the words. */
80
+ export declare function takeRoute(deps: RouteDeps, id: string, want: RouteWant, { claim, name }?: {
81
+ readonly claim?: Claim;
82
+ readonly name?: string;
83
+ }): Promise<Took>;
84
+ /** Drops computer `id`'s route where it is `mine` (its runner and incarnation, and its run where given): the runner
85
+ * that holds it, once its hold ended. `note` is kept on the row (why the run let it go); none: the row goes. False when
86
+ * the route is not mine (another's, or none). */
87
+ export declare function dropRoute(settings: Pick<RouteSettings, "get" | "putIfAbsent" | "replaceIf" | "removeIf">, id: string, mine: {
88
+ readonly runner: string;
89
+ readonly incarnation: string;
90
+ readonly run?: string;
91
+ }, note?: string): Promise<boolean>;
@@ -0,0 +1,153 @@
1
+ // Where a paired computer's socket goes on a server whose runner runs in a process of its own (the image's
2
+ // server-and-runner, `agentrun-serve runner`): its route. The box's driver dials the server's one public address, and
3
+ // keeps that one socket. While no run holds the box, the server's own hub takes it; while a run holds it, the server
4
+ // relays the same socket to the attach listener of the runner that holds the run (computer-attach.ts, the relay of
5
+ // dial-relay.ts), where that runner's hub takes it and the run's hold lives. A move is the server closing the socket with
6
+ // 1001 and the box's own redial landing where the route now says; nothing changes on the box.
7
+ //
8
+ // One server setting per paired computer holds it (`paired_route:<computer id>`): the runner, its incarnation, the run,
9
+ // the hold's end (shown, never judged), and a note the server keeps of why a route was refused or dropped. It is written
10
+ // by compare-and-set, as computer_kept:<run id> is (computer-kept.ts), the same calls on SQLite and Postgres: the run's
11
+ // claim takes it (takeRoute, with the claim, so a superseded claim's take is Fenced), the runner that holds it drops it
12
+ // once its hold ended (dropRoute), and the server notes and drops a stale one (replaceRoute). A row exists only while it
13
+ // holds a route or a note, so the server's tick reads only rows that matter (one indexed read of the prefix).
14
+ //
15
+ // The runner beside the server, in its process, takes a route the same way for a box its run holds in the server's own
16
+ // hub (runner/beside.ts, under the name and incarnation Serve.beside gives it): the box stays where it is, and a runner
17
+ // apart's take for another run is refused while that hold lasts.
18
+ //
19
+ // A route is stale only when its runner is not live (runner/presence.ts: no word of it for PRESENCE_STALE_MS; a runner
20
+ // beside its server says it is there with no relay) or names another incarnation (that runner restarted since, or the
21
+ // server it ran beside did); or when its run is final, so a runner's release that never dropped its route (its write
22
+ // failed) keeps the box from no other run. A route of another run, on a live runner, refuses the take: one run at a time.
23
+ import { ATTACH_HELLO_MS, ATTACH_REDIAL_MAX_MS } from "@parcha/agentrun-computer";
24
+ import { RELAY_CONNECT_MS } from "../live-reach.js";
25
+ import { PRESENCE_STALE_MS } from "../runner/presence.js";
26
+ import { FINAL_STATES } from "../store/index.js";
27
+ /** The settings key prefix of the paired computers' routes, one row per computer. */
28
+ export const ROUTE_PREFIX = "paired_route:";
29
+ /** The settings key of computer `id`'s route. */
30
+ export const routeKeyOf = (id) => `${ROUTE_PREFIX}${id}`;
31
+ /** How often the server compares each route with where the box's socket is (server.ts, computer-attach.ts tick). */
32
+ export const PAIRED_ROUTE_MS = 1_000;
33
+ /** How long a run's claim waits for its box to reach its runner: one tick of the server's, the driver's longest wait
34
+ * between dials (it backs off after quick reconnects), the relay's connect and the hub's hello. */
35
+ export const PAIRED_BRING_MS = PAIRED_ROUTE_MS + ATTACH_REDIAL_MAX_MS + RELAY_CONNECT_MS + ATTACH_HELLO_MS;
36
+ /** How often the claim reads the route while it waits. */
37
+ export const PAIRED_BRING_POLL_MS = 500;
38
+ /** How many times a take or a drop reads the row again after another writer changed it between its read and its write. */
39
+ const ROUTE_TRIES = 5;
40
+ /** No route and no note. */
41
+ export const EMPTY_ROUTE = { runner: null, incarnation: null, run: null, until: null, refused: null };
42
+ const text = (value) => (typeof value === "string" && value !== "" ? value : null);
43
+ /** A row's value as a Route; anything else reads as EMPTY_ROUTE. */
44
+ export function routeOf(value) {
45
+ if (!value || typeof value !== "object")
46
+ return EMPTY_ROUTE;
47
+ const row = value;
48
+ const runner = text(row.runner);
49
+ const incarnation = text(row.incarnation);
50
+ const refused = text(row.refused);
51
+ // A route names its runner, its incarnation and its run together, or none of them.
52
+ const run = text(row.run);
53
+ if (runner === null || incarnation === null || run === null)
54
+ return { ...EMPTY_ROUTE, refused };
55
+ const until = typeof row.until === "number" && Number.isFinite(row.until) ? row.until : null;
56
+ return { runner, incarnation, run, until, refused };
57
+ }
58
+ /** The row as written: its fields in one order, so a compare-and-set reads the same text. */
59
+ const rowOf = (route) => ({ runner: route.runner, incarnation: route.incarnation, run: route.run, until: route.until, refused: route.refused });
60
+ const isEmpty = (route) => route.runner === null && route.refused === null;
61
+ /** Computer `id`'s route as its row reads now: EMPTY_ROUTE when there is none. */
62
+ export async function readRoute(settings, id) {
63
+ return routeOf(await settings.get(routeKeyOf(id)));
64
+ }
65
+ /** Computer `id`'s route and its row's value as read (undefined: no row), for a compare-and-set on it. */
66
+ export async function seeRoute(settings, id) {
67
+ const seen = await settings.get(routeKeyOf(id));
68
+ return { seen, route: routeOf(seen) };
69
+ }
70
+ /** Every route row, as the server's tick reads them: one read of the prefix, a range on the settings' primary key. */
71
+ export async function allRoutes(settings) {
72
+ return (await settings.all({ prefix: ROUTE_PREFIX })).map((row) => ({ id: row.key.slice(ROUTE_PREFIX.length), seen: row.value, route: routeOf(row.value) }));
73
+ }
74
+ /** Writes `next` over computer `id`'s row while it still holds `seen` (as read): one compare-and-set. An empty `next` (no
75
+ * route, no note) removes the row. False when the row changed since. */
76
+ export async function replaceRoute(settings, id, seen, next, claim) {
77
+ const key = routeKeyOf(id);
78
+ if (seen === undefined) {
79
+ if (isEmpty(next))
80
+ return true;
81
+ const there = await settings.putIfAbsent(key, rowOf(EMPTY_ROUTE));
82
+ // Another writer's row landed between the read and this put (a route, or a note): the row changed since, so the
83
+ // caller reads it again and judges it, never writes over it unread. Only the empty placeholder goes on to the
84
+ // compare-and-set.
85
+ if (!isEmpty(routeOf(there)))
86
+ return false;
87
+ return replaceRoute(settings, id, there, next, claim);
88
+ }
89
+ if (isEmpty(next) && claim === undefined)
90
+ return settings.removeIf(key, seen);
91
+ return settings.replaceIf(key, seen, rowOf(next), claim);
92
+ }
93
+ /** `name` held by another run, on a live runner. */
94
+ export const heldWords = (name, run, runner) => `${name} is held by run ${run} on runner ${runner}: one run at a time`;
95
+ /** How a stale route's words end (the server's 503 and the box's note): where the box goes, and when. */
96
+ export const ROUTE_COMES_BACK = `it comes back to this server at its next dial, within ${ATTACH_REDIAL_MAX_MS / 1000} s, and the run's next claim takes it again`;
97
+ /** What a route says once its runner restarted. The words for a runner gone are the relay's own (computer-attach.ts
98
+ * relayDial), ending in ROUTE_COMES_BACK. */
99
+ export const routeRestartedWords = (runner) => `runner ${runner}, which holds it, restarted since, and the hold was its earlier process's: ${ROUTE_COMES_BACK}`;
100
+ /** A box routed to a run's runner, attached nowhere: the claim's wait ends in these words. */
101
+ export const notAttachedWords = (name) => `${name} is not attached now: open its driver on that computer, which dials this server`;
102
+ /** A box that did not reach its run's runner within PAIRED_BRING_MS. */
103
+ export const lateWords = (name, runner) => `${name} did not reach runner ${runner} within ${PAIRED_BRING_MS / 1000} s: its driver waits up to ${ATTACH_REDIAL_MAX_MS / 1000} s between dials after quick reconnects, so the run's next claim may find it there`;
104
+ /** A take or a drop that lost every compare-and-set to another writer. */
105
+ const changedWords = (name) => `${name}'s route changed while this run took it: its next claim tries again`;
106
+ /** Why `route` keeps computer `name` from `want`'s run, or undefined where the run may take it: no route, the run's own
107
+ * (a resume on another runner), a route whose runner is not live or restarted since, or one whose run is final. A
108
+ * live runner is any runner's row seen within PRESENCE_STALE_MS, with a relay or without one: the runner beside its
109
+ * server keeps none, and its route holds the same. */
110
+ async function holdsAgainst(deps, route, want, name) {
111
+ if (route.runner === null || route.run === want.run)
112
+ return undefined;
113
+ const at = (await deps.runners.live(PRESENCE_STALE_MS)).find((row) => row.runner === route.runner);
114
+ if (at === undefined || at.incarnation !== route.incarnation)
115
+ return undefined;
116
+ // A run that ended, stopped or failed holds nothing: its runner's release dropped the route, or that write failed. It
117
+ // fails closed: a run the store has no row of (purged included), or a read that throws, is not final, so the route
118
+ // stands. One read per refusal, no retry.
119
+ const run = deps.runs === undefined ? undefined : await deps.runs.get(route.run).catch(() => undefined);
120
+ if (run !== undefined && FINAL_STATES.includes(run.state))
121
+ return undefined;
122
+ return heldWords(name, route.run, route.runner);
123
+ }
124
+ /** Routes computer `id` to `want`'s runner for its run, where holdsAgainst lets it: the run's claim, before it waits for
125
+ * the box (dial-relay.ts bring). With `claim`, the write checks the claim's epoch and lease in its transaction, so a
126
+ * claim another runner superseded throws Fenced and writes nothing. `name` is the computer's, for the words. */
127
+ export async function takeRoute(deps, id, want, { claim, name = id } = {}) {
128
+ const mine = rowOf({ runner: want.runner, incarnation: want.incarnation, run: want.run, until: want.until, refused: null });
129
+ let route = EMPTY_ROUTE;
130
+ for (let tried = 0; tried < ROUTE_TRIES; tried++) {
131
+ const read = await seeRoute(deps.settings, id);
132
+ route = read.route;
133
+ const why = await holdsAgainst(deps, route, want, name);
134
+ if (why !== undefined)
135
+ return { taken: false, why, route };
136
+ if (await replaceRoute(deps.settings, id, read.seen, mine, claim))
137
+ return { taken: true, route: mine };
138
+ }
139
+ return { taken: false, why: changedWords(name), route };
140
+ }
141
+ /** Drops computer `id`'s route where it is `mine` (its runner and incarnation, and its run where given): the runner
142
+ * that holds it, once its hold ended. `note` is kept on the row (why the run let it go); none: the row goes. False when
143
+ * the route is not mine (another's, or none). */
144
+ export async function dropRoute(settings, id, mine, note) {
145
+ for (let tried = 0; tried < ROUTE_TRIES; tried++) {
146
+ const { seen, route } = await seeRoute(settings, id);
147
+ if (route.runner !== mine.runner || route.incarnation !== mine.incarnation || (mine.run !== undefined && route.run !== mine.run))
148
+ return false;
149
+ if (await replaceRoute(settings, id, seen, { ...EMPTY_ROUTE, refused: note ?? null }))
150
+ return true;
151
+ }
152
+ return false;
153
+ }
package/dist/wrapped.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Wrapped } from "@parcha/agentrun-import";
1
+ import { type Wrapped } from "@parcha/agentrun-import";
2
2
  /** `wrapped` (the import package's) as GET /v2/wrapped serves it, and the runs imported from each source (`imported`). */
3
3
  export declare function wrappedView(wrapped: Wrapped, imported: readonly {
4
4
  source: string;
@@ -25,6 +25,7 @@ export declare function wrappedView(wrapped: Wrapped, imported: readonly {
25
25
  weekdays: number[];
26
26
  active_ms: number;
27
27
  harnesses: {
28
+ sources: string[];
28
29
  harness: string;
29
30
  sessions: number;
30
31
  requests: number;
@@ -35,6 +36,7 @@ export declare function wrappedView(wrapped: Wrapped, imported: readonly {
35
36
  requests: number;
36
37
  tokens: number;
37
38
  cost_usd: number;
39
+ unpriced_requests: number;
38
40
  }[];
39
41
  sources: {
40
42
  source: string;
@@ -59,7 +61,11 @@ export type WrappedRead = {
59
61
  * is shared however long it takes; once it ends, a year already over when its read began is kept until the server stops
60
62
  * (its requests were all in), and any other (this year's, or one that ended while it was read) for a minute. One read at
61
63
  * a time: each is a worker holding a year's sessions, so a year asked while another is read waits for it to end. A read
62
- * that fails is dropped, so the next ask reads again, and frees the turn. One per server. */
64
+ * that fails frees the turn and is kept for a minute too, whatever its year: an ask within it gets the same failure, not
65
+ * another read of a home that fails it (one past the worker's heap would fail each one). One per server. */
63
66
  export declare function keptReads(read: (year: number) => Promise<WrappedRead>): (year: number) => Promise<WrappedRead>;
67
+ /** keptReads over `read`, with each failed read given to `log` once, as it fails: the ask that started it may have had its
68
+ * answer (a 503) long before, and the asks in the minute it is kept get the same failure, not another read or log. */
69
+ export declare function loggedReads(read: (year: number) => Promise<WrappedRead>, log: (year: number, error: Error) => void): (year: number) => Promise<WrappedRead>;
64
70
  /** `read`'s answer if it comes within `ms`, else undefined (the read goes on). */
65
71
  export declare function within<T>(read: Promise<T>, ms: number): Promise<T | undefined>;
package/dist/wrapped.js CHANGED
@@ -1,3 +1,7 @@
1
+ // GET /v2/wrapped: a year of the work under this machine's home (Claude Code, Codex, pi and every other source the import
2
+ // package reads), as numbers. The import package's wrappedHome does the reading; this is its answer in the API's words,
3
+ // with the runs imported here beside it. Numbers and names only: no prompt, title, path or project is in it.
4
+ import { HARNESS_OF } from "@parcha/agentrun-import";
1
5
  const total = ({ input, output, cacheRead, cacheWrite }) => input + output + cacheRead + cacheWrite;
2
6
  /** `wrapped` (the import package's) as GET /v2/wrapped serves it, and the runs imported from each source (`imported`). */
3
7
  export function wrappedView(wrapped, imported, unreadFiles = 0) {
@@ -14,8 +18,10 @@ export function wrappedView(wrapped, imported, unreadFiles = 0) {
14
18
  hours: wrapped.hours,
15
19
  weekdays: wrapped.weekdays,
16
20
  active_ms: wrapped.activeMs,
17
- harnesses: wrapped.harnesses,
18
- models: wrapped.models.map(({ model, requests, tokens, cost }) => ({ model, requests, tokens: total(tokens), cost_usd: cost })),
21
+ // The sources behind each harness (several can share one), so the console links a harness's numbers to their runs
22
+ // without a copy of the table, in the order of `sources`: a source of a reader outside it is its own harness, as wrappedHome counts it.
23
+ harnesses: wrapped.harnesses.map((h) => ({ ...h, sources: wrapped.sources.map((s) => s.source).filter((source) => (HARNESS_OF[source] ?? source) === h.harness) })),
24
+ models: wrapped.models.map(({ model, requests, tokens, cost, unpricedRequests }) => ({ model, requests, tokens: total(tokens), cost_usd: cost, unpriced_requests: unpricedRequests })),
19
25
  sources: wrapped.sources,
20
26
  imported: imported.map(({ source, runs }) => ({ source, runs })),
21
27
  unread_files: unreadFiles,
@@ -29,7 +35,8 @@ export const WRAPPED_WAIT_MS = 15_000;
29
35
  * is shared however long it takes; once it ends, a year already over when its read began is kept until the server stops
30
36
  * (its requests were all in), and any other (this year's, or one that ended while it was read) for a minute. One read at
31
37
  * a time: each is a worker holding a year's sessions, so a year asked while another is read waits for it to end. A read
32
- * that fails is dropped, so the next ask reads again, and frees the turn. One per server. */
38
+ * that fails frees the turn and is kept for a minute too, whatever its year: an ask within it gets the same failure, not
39
+ * another read of a home that fails it (one past the worker's heap would fail each one). One per server. */
33
40
  export function keptReads(read) {
34
41
  const kept = new Map();
35
42
  // The read whose turn it is or the last one given a turn, until it ends: the next starts after it.
@@ -47,7 +54,7 @@ export function keptReads(read) {
47
54
  return (year) => {
48
55
  const held = kept.get(year);
49
56
  const now = Date.now();
50
- if (held && (held.at === undefined || year < held.began || now - held.at < KEEP_MS))
57
+ if (held && (held.at === undefined || (!held.failed && year < held.began) || now - held.at < KEEP_MS))
51
58
  return held.read;
52
59
  const entry = {};
53
60
  entry.read = inTurn(() => {
@@ -58,12 +65,20 @@ export function keptReads(read) {
58
65
  entry.read.then(() => {
59
66
  entry.at = Date.now();
60
67
  }, () => {
61
- if (kept.get(year) === entry)
62
- kept.delete(year);
68
+ entry.at = Date.now();
69
+ entry.failed = true;
63
70
  });
64
71
  return entry.read;
65
72
  };
66
73
  }
74
+ /** keptReads over `read`, with each failed read given to `log` once, as it fails: the ask that started it may have had its
75
+ * answer (a 503) long before, and the asks in the minute it is kept get the same failure, not another read or log. */
76
+ export function loggedReads(read, log) {
77
+ return keptReads((year) => read(year).catch((error) => {
78
+ log(year, error);
79
+ throw error;
80
+ }));
81
+ }
67
82
  /** `read`'s answer if it comes within `ms`, else undefined (the read goes on). */
68
83
  export async function within(read, ms) {
69
84
  let timer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-serve",
3
- "version": "0.1.0-beta.57",
3
+ "version": "0.1.0-beta.58",
4
4
  "description": "The AgentRun server: the /v2 API and console over one store, with runners that run your agents; the deployable process of the AgentRun platform.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -71,17 +71,17 @@
71
71
  "@opentelemetry/resources": "3.1.1",
72
72
  "@opentelemetry/sdk-trace": "3.1.1",
73
73
  "@opentelemetry/semantic-conventions": "1.43.0",
74
- "@parcha/agentrun-computer": "0.1.0-beta.57",
75
- "@parcha/agentrun-decisions": "0.1.0-beta.57",
76
- "@parcha/agentrun-dsl": "0.1.0-beta.57",
77
- "@parcha/agentrun-harness-acp": "0.1.0-beta.57",
78
- "@parcha/agentrun-harness-claude": "0.1.0-beta.57",
79
- "@parcha/agentrun-harness-codex": "0.1.0-beta.57",
80
- "@parcha/agentrun-import": "0.1.0-beta.57",
81
- "@parcha/agentrun-jev": "0.1.0-beta.57",
82
- "@parcha/agentrun-kernel": "0.1.0-beta.57",
83
- "@parcha/agentrun-web": "0.1.0-beta.57",
84
- "@parcha/pi-browser": "0.1.0-beta.57",
74
+ "@parcha/agentrun-computer": "0.1.0-beta.58",
75
+ "@parcha/agentrun-decisions": "0.1.0-beta.58",
76
+ "@parcha/agentrun-dsl": "0.1.0-beta.58",
77
+ "@parcha/agentrun-harness-acp": "0.1.0-beta.58",
78
+ "@parcha/agentrun-harness-claude": "0.1.0-beta.58",
79
+ "@parcha/agentrun-harness-codex": "0.1.0-beta.58",
80
+ "@parcha/agentrun-import": "0.1.0-beta.58",
81
+ "@parcha/agentrun-jev": "0.1.0-beta.58",
82
+ "@parcha/agentrun-kernel": "0.1.0-beta.58",
83
+ "@parcha/agentrun-web": "0.1.0-beta.58",
84
+ "@parcha/pi-browser": "0.1.0-beta.58",
85
85
  "@secretlint/core": "14.1.0",
86
86
  "@secretlint/profiler": "14.1.0",
87
87
  "croner": "11.0.0",
@@ -139,9 +139,9 @@ Each `evals/<case>/` is one test of the package's agent. No eval runs on the ser
139
139
  (rewritten at the session's model proxy, so a claude-agent case on a person's Claude login keeps the real date: run it
140
140
  on the provider route), and each `llm` grader is told it, so a rubric can say "the run's date". A tool that reads the
141
141
  machine's clock (a shell's `date`, a browser's page) and another harness CLI's own date (Codex adds its own to each
142
- turn) still read the real one. A fixture case whose prompt or
143
- pages carry dates sets `now:`, else it drifts a day each day it is run. Only the eval's own server honours it: a case with `now` refuses
144
- `--server`. Without it, the real clock.
142
+ turn) still read the real one. A fixture case whose prompt or pages carry dates sets `now:`, else it drifts a day each
143
+ day it is run. Only the eval's own server honours it: a case with `now` refuses `--server`. Without it, the real
144
+ clock.
145
145
  - `email: fixtures/mailbox.json`, a fixture file in the case: each run gets a fake mail account of its own, seeded from
146
146
  it and saved as the server's email account (plaintext, on this machine's loopback), closed after the run, so no run
147
147
  reads real mail or shares another's mailbox. The fixture: