@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
@@ -1,4 +1,4 @@
1
- import type { ClaudeAgentLogin, ClaudeLoginStatus } from "@parcha/agentrun-harness-claude";
1
+ import type { ClaudeAgentLogin, ClaudeLoginStatus, ClaudeLoginToken } from "@parcha/agentrun-harness-claude";
2
2
  import type { ClaudeSignIns, SignInView } from "./claude-sign-in.js";
3
3
  import type { Settings } from "./store/index.js";
4
4
  /** The switch: `off` (or 0, false, no) turns the mode off on this server, `on` (or 1, true, yes) leaves it there past
@@ -17,6 +17,12 @@ export declare const LOGIN_HARNESS: string;
17
17
  export declare const CLAUDE_LOGIN_PROVIDER = "claude-login";
18
18
  /** The model a run on the login gets when it names none. */
19
19
  export declare const LOGIN_DEFAULT_MODEL = "anthropic/claude-sonnet-5-5";
20
+ /** Whether a run of the login's harness that names `model` goes on the login: one naming none (it gets
21
+ * LOGIN_DEFAULT_MODEL, Anthropic's) or one of Anthropic's own (`anthropic/<id>`). Any other, Anthropic's through
22
+ * OpenRouter (`openrouter/anthropic/<id>`) included, goes on its provider's key whatever the login says. providerFor
23
+ * puts a run on the login by this rule, and loginOnRunnerOnly offers the move to the runner by it. The console reads no
24
+ * server code: its lib/claudeLogin.ts loginServes copies this, and both tests name the same cases. */
25
+ export declare const loginServes: (model: string | undefined) => boolean;
20
26
  /** Where the login is: AgentRun's own directory in its data (`agentrun`, the default), or this machine's own Claude Code
21
27
  * login (`machine`, which the owner opts into by name). */
22
28
  export declare const LOGIN_PLACES: readonly ["agentrun", "machine"];
@@ -51,6 +57,17 @@ export declare function machineFolder(env?: Readonly<Record<string, string | und
51
57
  source: "CLAUDE_CONFIG_DIR" | "default";
52
58
  credentials?: string;
53
59
  };
60
+ /** The person's home: the home of the user this server runs as (`uid`, its effective uid), whose files the login's CLI
61
+ * writes. The env's `HOME` when it is an absolute path to a folder that user owns, else that user's own home as the
62
+ * system has it (`os.userInfo()`), when it owns that. So a server under a sudo that keeps `HOME` (root, with the
63
+ * person's) keeps its login in root's home, never root-owned files in the person's, and a service account that
64
+ * inherited someone's `HOME` reads its own. Neither: `refused` says why in words, and `home` is only what the view
65
+ * shows (nothing is written there). Where there is no uid (Windows), the env's `HOME` when absolute, else
66
+ * `os.homedir()`. */
67
+ export declare function homeOf(env: Readonly<Record<string, string | undefined>>, uid?: number | undefined): {
68
+ home: string;
69
+ refused?: string;
70
+ };
54
71
  /** The directories of a login at `place`: AgentRun's in `data`, or this machine's (machineFolder, and the Anthropic
55
72
  * profiles where the CLI looks for them: `ANTHROPIC_CONFIG_DIR`, else `$XDG_CONFIG_HOME/anthropic`, else
56
73
  * `~/.config/anthropic`). This machine's on the CLI's default folder carries the person's home too, so the harness
@@ -63,20 +80,35 @@ export declare function machineFolder(env?: Readonly<Record<string, string | und
63
80
  export declare function loginAt(place: LoginPlace, data: string, env?: Readonly<Record<string, string | undefined>>): ClaudeAgentLogin;
64
81
  /** The setting as saved, or undefined when the mode is not on (or the row is not one this reads). */
65
82
  export declare function claudeLoginSetting(settings: Pick<Settings, "get">): Promise<Setting | undefined>;
66
- /** The login a run here goes on: the setting's, when the switch is not off and this is the machine it was turned on for. */
83
+ /** The login a run here goes on: the setting's, when the switch is not off, this is the machine it was turned on for,
84
+ * and the server's user owns a home for it (homeOf). */
67
85
  export declare function loginOf(setting: Setting | undefined, data: string, env: Readonly<Record<string, string | undefined>>): ClaudeAgentLogin | undefined;
86
+ /** A login as a run holds it: its two directories, or, in a run's own process under a user of its own, its runner's
87
+ * reader of its access token (held.ts claudeLogin). */
88
+ export type RunLogin = ClaudeAgentLogin | ClaudeLoginToken;
89
+ /** Whether `login` is a reader of its access token, not its directories. */
90
+ export declare const loginByToken: (login: RunLogin) => login is ClaudeLoginToken;
68
91
  /** `env` carrying `login` (none: carrying none), as an enumerable symbol property: a spread keeps it, a spawn never sees
69
- * it (it is no variable), and it holds only two directory names. */
70
- export declare function withClaudeLogin<T extends object>(env: T, login: ClaudeAgentLogin | undefined): T;
92
+ * it (it is no variable), and it holds two directory names or a token reader, never a token. */
93
+ export declare function withClaudeLogin<T extends object>(env: T, login: RunLogin | undefined): T;
71
94
  /** `env` as a run at `place` reads it: a runner place keeps the login; any other place (a sandbox) gets a copy without it,
72
95
  * so a revision's checks there ask for a key, as its run will. */
73
96
  export declare function envAtPlace<T extends object>(env: T, place: {
74
97
  readonly mode: string;
75
98
  } | undefined): T;
76
99
  /** The login `env` carries, unless the switch is off. */
77
- export declare function claudeLoginOf(env: NodeJS.ProcessEnv): ClaudeAgentLogin | undefined;
100
+ export declare function claudeLoginOf(env: NodeJS.ProcessEnv): RunLogin | undefined;
78
101
  /** Whether `harness` runs on the login `env` carries. */
79
102
  export declare const onClaudeLogin: (env: NodeJS.ProcessEnv, harness: string) => boolean;
103
+ /** For a run refused for its model: the words that say why the login `env` carries does not run it, when its harness
104
+ * runs on that login, the login would run its `model` (loginServes: Anthropic's own, or none), and its place is a box
105
+ * (the login is a model only on the runner, loginForRun), naming the box and the move that runs it there; else
106
+ * undefined. A model the login never runs (an OpenRouter one) still needs its key after a move, so none is offered. The
107
+ * login's state is not asked: a signed-out one fails a run on the runner in its own words. */
108
+ export declare function loginOnRunnerOnly(env: NodeJS.ProcessEnv, harness: string | undefined, model: string | undefined, place: {
109
+ readonly mode: string;
110
+ readonly box?: string;
111
+ } | undefined): string | undefined;
80
112
  /** The CLI that answers for a login: the pinned one this server installed for claude-agent (`pinned`), else a `claude` on
81
113
  * PATH, else none. */
82
114
  export declare function loginCli(pinned: string | undefined, env: Readonly<Record<string, string | undefined>>): string | undefined;
@@ -166,6 +198,8 @@ export type ClaudeLoginDeps = {
166
198
  claude: () => Promise<ClaudeLoginCli>;
167
199
  saved: (login: ClaudeAgentLogin | undefined) => void;
168
200
  changed: () => Promise<void>;
201
+ /** The user this server runs as, whose home the login needs (homeOf): its effective uid unless given. */
202
+ uid?: number;
169
203
  };
170
204
  /** A server's API keys as the login needs them (api-keys.ts ApiKeys): how many there are now, and their turn. */
171
205
  export type KeysForLogin = {
@@ -200,24 +234,30 @@ export declare function turnOffClaudeLogin(deps: ClaudeLoginDeps): Promise<Claud
200
234
  * is when the sign-in starts, its `sign_in` waiting. The setting is read, and the CLI started on it, in one turn. */
201
235
  export declare function startLoginHere(deps: ClaudeLoginDeps): Promise<ClaudeLoginView>;
202
236
  /** At the server's start: a setting saved where the mode is now off or refused (`why`: the switch, a listen address past
203
- * loopback, a second token, the API-only profile) goes, so no runner, in this process or another, runs on it; the reason
237
+ * loopback, a second token, the API-only profile, no home the server's user owns) goes, so no runner, in this process or another, runs on it; the reason
204
238
  * is logged. A turn on `signIns`' queue, as every change of the setting is. */
205
239
  export declare function dropRefusedLogin(signIns: Pick<ClaudeSignIns, "serial">, settings: Pick<Settings, "get" | "remove">, why: string | undefined, log: (line: string) => void): Promise<void>;
206
240
  /** What the routes and a run's check use of the harness (its login.ts), loaded only when asked. */
207
241
  export type ClaudeLoginCli = Pick<typeof import("@parcha/agentrun-harness-claude"), "claudeLoginStatus" | "startClaudeLogin" | "claudeLoginCommand">;
208
242
  /** How long a signed-in answer stands in for a check that gives none (loginBeforeRun). */
209
243
  export declare const LOGIN_ANSWER_STANDS_MS: number;
244
+ /** The folder in the data folder that holds, per login, when it last answered signed in (noteAnswer). The server and its
245
+ * runner may be two processes on one data folder (`--no-runner` beside `agentrun-serve runner`): the Settings view's
246
+ * answer is the server's, a run's check the runner's, so the answer is kept where both read it. */
247
+ export declare const LOGIN_ANSWERS_DIR = "claude-login-answers";
210
248
  /** Before a run on the login: its CLI says it is signed in, or the run is refused in words (never a silent switch to a
211
249
  * key). `cli`: the CLI that answers (loginCli); none, nothing to ask yet. `status`: the CLI's status check (the harness's
212
250
  * claudeLoginStatus, which asks once and, when the CLI gives no answer, throws with `code` "timed_out" or "no_status").
213
251
  * A check that gives no answer (it timed out, or the CLI said nothing that reads as a status) is asked once more, since
214
252
  * a loaded host can take past the limit with the login fine. Still none: the run goes on when this login answered
215
- * signed in within LOGIN_ANSWER_STANDS_MS in this server process (a run's check here, or the Settings view's), as its
216
- * own CLI still fails in words if the login is gone; else it is refused with LOGIN_UNKNOWN and why. Any other failure (a
217
- * CLI that is not at its path, say) is refused with LOGIN_UNKNOWN and its own words at once, asked once and never
218
- * waved through by an earlier answer. A signed-out answer is the answer: never asked again nor overridden, refused at
219
- * once, and the earlier signed-in time goes. `now`: the clock (Date.now). */
220
- export declare function loginBeforeRun(login: ClaudeAgentLogin | undefined, cli: string | undefined, status: (cli: string, login: ClaudeAgentLogin) => Promise<ClaudeLoginStatus>, options?: {
253
+ * signed in on this machine within LOGIN_ANSWER_STANDS_MS (a run's check, or the Settings view's, in this process or
254
+ * another on the same data folder, `data`), as its own CLI still fails in words if the login is gone; else it is
255
+ * refused with LOGIN_UNKNOWN and why. Any other failure (a CLI that is not at its path, say) is refused with
256
+ * LOGIN_UNKNOWN and its own words at once, asked once and never waved through by an earlier answer. A signed-out answer
257
+ * is the answer: never asked again nor overridden, refused at once, and the earlier signed-in time goes. `now`: the
258
+ * clock (Date.now). */
259
+ export declare function loginBeforeRun(login: ClaudeAgentLogin | undefined, cli: string | undefined, status: (cli: string, login: ClaudeAgentLogin) => Promise<ClaudeLoginStatus>, options: {
260
+ data: string;
221
261
  now?: () => number;
222
262
  }): Promise<void>;
223
263
  export {};
@@ -1,8 +1,10 @@
1
1
  // Claude Code's login on this machine as claude-agent's model source: a person's own Claude plan, used by the pinned
2
- // Claude Code CLI as that CLI always uses it. AgentRun never reads, copies, stores, proxies or relays the login or a
3
- // browser code: the CLI keeps it in its own files and calls Anthropic with it itself (the harness's login.ts). This
4
- // server only tells the CLI where its login is, asks it for its status (`claude auth status`), and keeps one setting: that
5
- // the owner turned the mode on, where the login is, and on which machine.
2
+ // Claude Code CLI as that CLI always uses it. AgentRun never copies, stores, proxies or relays the login or a browser
3
+ // code: the CLI keeps it in its own files and calls Anthropic with it itself (the harness's login.ts). This server tells
4
+ // the CLI where its login is, asks it for its status (`claude auth status`), and keeps one setting: that the owner turned
5
+ // the mode on, where the login is, and on which machine. Where each run is a user of its own, the runner reads AgentRun's
6
+ // own login folder, renews it there in the CLI's place, with the CLI's own request and lock, and a run gets only its
7
+ // access token (claude-login-token.ts).
6
8
  //
7
9
  // One switch (AGENTRUN_CLAUDE_CODE_LOGIN): unset, the mode is there only on a server that listens on loopback, so a
8
10
  // server bound past it (0.0.0.0 in a container, a hosted service) has it off with nothing to set; `off` or `on` says so
@@ -10,9 +12,9 @@
10
12
  // harness selection reads no setting, so claude-agent runs on the model keys as it does without the mode. The mode is
11
13
  // for a server one person runs: it is refused where more than one person can start runs, `on` included, and the owner
12
14
  // confirms they alone run agents here. It runs only in a runner place, on the machine the owner turned it on for.
13
- import { randomBytes } from "node:crypto";
14
- import { accessSync, chmodSync, constants, existsSync, linkSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
15
- import { homedir } from "node:os";
15
+ import { createHash, randomBytes } from "node:crypto";
16
+ import { accessSync, chmodSync, closeSync, constants, existsSync, fstatSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
17
+ import { homedir, userInfo } from "node:os";
16
18
  import { delimiter, isAbsolute, join } from "node:path";
17
19
  import { facts as claudeFacts } from "@parcha/agentrun-harness-claude/facts";
18
20
  import { registerSecretWrite } from "./secret-writes.js";
@@ -44,6 +46,12 @@ const LOGIN_HARNESSES = Object.freeze([LOGIN_HARNESS]);
44
46
  export const CLAUDE_LOGIN_PROVIDER = "claude-login";
45
47
  /** The model a run on the login gets when it names none. */
46
48
  export const LOGIN_DEFAULT_MODEL = "anthropic/claude-sonnet-5-5";
49
+ /** Whether a run of the login's harness that names `model` goes on the login: one naming none (it gets
50
+ * LOGIN_DEFAULT_MODEL, Anthropic's) or one of Anthropic's own (`anthropic/<id>`). Any other, Anthropic's through
51
+ * OpenRouter (`openrouter/anthropic/<id>`) included, goes on its provider's key whatever the login says. providerFor
52
+ * puts a run on the login by this rule, and loginOnRunnerOnly offers the move to the runner by it. The console reads no
53
+ * server code: its lib/claudeLogin.ts loginServes copies this, and both tests name the same cases. */
54
+ export const loginServes = (model) => !model || model.startsWith("anthropic/");
47
55
  /** Where the login is: AgentRun's own directory in its data (`agentrun`, the default), or this machine's own Claude Code
48
56
  * login (`machine`, which the owner opts into by name). */
49
57
  export const LOGIN_PLACES = ["agentrun", "machine"];
@@ -107,12 +115,46 @@ export function machineFolder(env = process.env) {
107
115
  const credentials = secure === "" || (secure && isAbsolute(secure)) ? { credentials: secure } : {};
108
116
  if (env.CLAUDE_CONFIG_DIR && isAbsolute(env.CLAUDE_CONFIG_DIR))
109
117
  return { folder: env.CLAUDE_CONFIG_DIR, source: "CLAUDE_CONFIG_DIR", ...credentials };
110
- return { folder: join(homeOf(env), ".claude"), source: "default", ...credentials };
118
+ return { folder: join(homeOf(env).home, ".claude"), source: "default", ...credentials };
119
+ }
120
+ /** The person's home: the home of the user this server runs as (`uid`, its effective uid), whose files the login's CLI
121
+ * writes. The env's `HOME` when it is an absolute path to a folder that user owns, else that user's own home as the
122
+ * system has it (`os.userInfo()`), when it owns that. So a server under a sudo that keeps `HOME` (root, with the
123
+ * person's) keeps its login in root's home, never root-owned files in the person's, and a service account that
124
+ * inherited someone's `HOME` reads its own. Neither: `refused` says why in words, and `home` is only what the view
125
+ * shows (nothing is written there). Where there is no uid (Windows), the env's `HOME` when absolute, else
126
+ * `os.homedir()`. */
127
+ export function homeOf(env, uid = process.geteuid?.()) {
128
+ const given = env.HOME && isAbsolute(env.HOME) ? env.HOME : undefined;
129
+ if (uid === undefined)
130
+ return { home: given ?? homedir() };
131
+ const owned = (dir) => {
132
+ if (!dir)
133
+ return false;
134
+ try {
135
+ const stat = statSync(dir);
136
+ return stat.isDirectory() && stat.uid === uid;
137
+ }
138
+ catch {
139
+ return false;
140
+ }
141
+ };
142
+ if (owned(given))
143
+ return { home: given };
144
+ let own;
145
+ try {
146
+ own = userInfo().homedir || undefined;
147
+ }
148
+ catch {
149
+ // No entry for this user on this system.
150
+ }
151
+ if (owned(own))
152
+ return { home: own };
153
+ return {
154
+ home: own ?? given ?? homedir(),
155
+ refused: `Claude Code's login on this machine needs a home this server's user owns: it runs as uid ${uid}, and neither its HOME (${env.HOME || "unset"}) nor that user's own home (${own ?? "none on this system"}) is a folder it owns. Start the server as the person whose Claude plan it is.`,
156
+ };
111
157
  }
112
- /** The person's home as the server's env says it: its `HOME` when absolute, else `os.homedir()`. The person's own CLI
113
- * reads its home as Node does (`os.homedir()`, which is `HOME` when set), so the two agree for the server's own env;
114
- * reading the env handed in first keeps it the one source a test or an embedding host can set. */
115
- const homeOf = (env) => (env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir());
116
158
  /** The directories of a login at `place`: AgentRun's in `data`, or this machine's (machineFolder, and the Anthropic
117
159
  * profiles where the CLI looks for them: `ANTHROPIC_CONFIG_DIR`, else `$XDG_CONFIG_HOME/anthropic`, else
118
160
  * `~/.config/anthropic`). This machine's on the CLI's default folder carries the person's home too, so the harness
@@ -123,7 +165,7 @@ const homeOf = (env) => (env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir()
123
165
  * person's home as `userHome`, read here once (homeOf), so the status check, the sign-in and a run on macOS all run in
124
166
  * that one home whatever reads it later (the harness's personHome). */
125
167
  export function loginAt(place, data, env = process.env) {
126
- const home = homeOf(env);
168
+ const { home } = homeOf(env);
127
169
  if (place === "agentrun")
128
170
  return { dir: join(data, "claude-login"), profiles: join(data, "claude-login", "anthropic"), userHome: home };
129
171
  const config = env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join(home, ".config");
@@ -140,15 +182,18 @@ export async function claudeLoginSetting(settings) {
140
182
  }
141
183
  /** Whether `setting` was turned on for this machine: the one whose data folder (`data`) holds its id (machineId). */
142
184
  const thisMachine = (setting, data) => setting.machine === machineId(data);
143
- /** The login a run here goes on: the setting's, when the switch is not off and this is the machine it was turned on for. */
185
+ /** The login a run here goes on: the setting's, when the switch is not off, this is the machine it was turned on for,
186
+ * and the server's user owns a home for it (homeOf). */
144
187
  export function loginOf(setting, data, env) {
145
- if (!setting || claudeLoginOff(env) || !thisMachine(setting, data))
188
+ if (!setting || claudeLoginOff(env) || !thisMachine(setting, data) || homeOf(env).refused)
146
189
  return undefined;
147
190
  return loginAt(setting.place, data, env);
148
191
  }
149
192
  const LOGIN = Symbol.for("agentrun.claude-login");
193
+ /** Whether `login` is a reader of its access token, not its directories. */
194
+ export const loginByToken = (login) => typeof login.token === "function";
150
195
  /** `env` carrying `login` (none: carrying none), as an enumerable symbol property: a spread keeps it, a spawn never sees
151
- * it (it is no variable), and it holds only two directory names. */
196
+ * it (it is no variable), and it holds two directory names or a token reader, never a token. */
152
197
  export function withClaudeLogin(env, login) {
153
198
  if (login)
154
199
  Object.defineProperty(env, LOGIN, { value: Object.freeze({ ...login }), enumerable: true, configurable: true, writable: false });
@@ -171,6 +216,16 @@ export function claudeLoginOf(env) {
171
216
  }
172
217
  /** Whether `harness` runs on the login `env` carries. */
173
218
  export const onClaudeLogin = (env, harness) => LOGIN_HARNESSES.includes(harness) && claudeLoginOf(env) !== undefined;
219
+ /** For a run refused for its model: the words that say why the login `env` carries does not run it, when its harness
220
+ * runs on that login, the login would run its `model` (loginServes: Anthropic's own, or none), and its place is a box
221
+ * (the login is a model only on the runner, loginForRun), naming the box and the move that runs it there; else
222
+ * undefined. A model the login never runs (an OpenRouter one) still needs its key after a move, so none is offered. The
223
+ * login's state is not asked: a signed-out one fails a run on the runner in its own words. */
224
+ export function loginOnRunnerOnly(env, harness, model, place) {
225
+ if (harness === undefined || !onClaudeLogin(env, harness) || !loginServes(model) || place === undefined || place.mode === "runner")
226
+ return undefined;
227
+ return `Claude Code's login on this machine runs agents on the runner only, and this agent runs in the ${place.box ?? place.mode} box: move it to the runner to run it on the login, or add a key.`;
228
+ }
174
229
  /** The CLI that answers for a login: the pinned one this server installed for claude-agent (`pinned`), else a `claude` on
175
230
  * PATH, else none. */
176
231
  export function loginCli(pinned, env) {
@@ -241,6 +296,8 @@ export async function loginForRun(settings, data, env, harness, place) {
241
296
  /** The routes here (server.ts): every one answers 404, by its name, while the mode is off (`why`). */
242
297
  export const CLAUDE_LOGIN_ROUTES = new Set(["getClaudeLogin", "turnOnClaudeLogin", "turnOffClaudeLogin", "startClaudeLogin"]);
243
298
  export const claudeLoginRouteOff = (name, why) => `${name}: Claude Code's login on this machine is off on this server: ${why}.`;
299
+ /** Why the routes may not turn the mode on or sign in now: the server's own refusal, else no home its user owns. */
300
+ const refusedHere = (deps) => deps.refused() ?? homeOf(deps.env, deps.uid).refused;
244
301
  /** What the one-owner rule gives the login's routes over a server's keys: `refused`, which counts the keys each time
245
302
  * it is asked, and `turn`, the keys' own. The server's routes take both from here, and so does the test that runs the
246
303
  * turn-on against a held revocation: neither is a value read once, or a turn of its own. */
@@ -263,19 +320,23 @@ export async function claudeLoginView(deps) {
263
320
  const login = loginAt(place, deps.data, deps.env);
264
321
  const cli = loginCli(await deps.pinned(), deps.env);
265
322
  const signIn = deps.signIns.view();
266
- const refused = deps.refused();
323
+ const homeless = homeOf(deps.env, deps.uid).refused;
324
+ const refused = deps.refused() ?? homeless;
267
325
  const base = { place, command: (await deps.claude()).claudeLoginCommand(login, cli ?? "claude"), can_start: deps.sameMachine && cli !== undefined && refused === undefined, ...(refused ? { refused } : {}), folder: login.dir, machine: machineFolder(deps.env), ...(signIn ? { sign_in: signIn } : {}) };
268
326
  if (!setting)
269
327
  return { state: "off", ...base };
270
328
  if (!thisMachine(setting, deps.data))
271
329
  return { state: "other_machine", ...base, can_start: false };
330
+ // No home the server's user owns: no login here (loginOf), and the CLI is not asked, since its check runs in that home.
331
+ if (homeless)
332
+ return { state: "off", ...base };
272
333
  if (!cli)
273
334
  return { state: "no_cli", ...base };
274
335
  try {
275
336
  // Asked once: a person waits on this read. Its answer is a run's too (loginBeforeRun), so one who just saw the
276
337
  // login signed in here has a run on a slow host go on.
277
338
  const said = await (await deps.claude()).claudeLoginStatus(cli, login, pathOf(deps.env));
278
- noteAnswer(login, said, Date.now());
339
+ noteAnswer(login, said, Date.now(), deps.data);
279
340
  return said.signedIn ? { state: "signed_in", ...base, account: accountOf(said) } : { state: "signed_out", ...base };
280
341
  }
281
342
  catch {
@@ -294,7 +355,7 @@ export async function turnOnClaudeLogin(deps, body) {
294
355
  // what follows the write (the reading again, the CLI's status) are outside the keys' turn, so a key's revocation never
295
356
  // waits on the CLI.
296
357
  const refusal = () => {
297
- const refused = deps.refused();
358
+ const refused = refusedHere(deps);
298
359
  if (refused)
299
360
  throw new ClaudeLoginRefused("forbidden", refused);
300
361
  };
@@ -334,7 +395,7 @@ export async function turnOffClaudeLogin(deps) {
334
395
  * still waits is ended first (deps.signIns). The browser code goes to the CLI, never here; the answer is the view as it
335
396
  * is when the sign-in starts, its `sign_in` waiting. The setting is read, and the CLI started on it, in one turn. */
336
397
  export async function startLoginHere(deps) {
337
- const refused = deps.refused();
398
+ const refused = refusedHere(deps);
338
399
  if (refused)
339
400
  throw new ClaudeLoginRefused("forbidden", refused);
340
401
  await deps.signIns.serial(async (signIn) => {
@@ -356,7 +417,7 @@ export async function startLoginHere(deps) {
356
417
  return claudeLoginView(deps);
357
418
  }
358
419
  /** At the server's start: a setting saved where the mode is now off or refused (`why`: the switch, a listen address past
359
- * loopback, a second token, the API-only profile) goes, so no runner, in this process or another, runs on it; the reason
420
+ * loopback, a second token, the API-only profile, no home the server's user owns) goes, so no runner, in this process or another, runs on it; the reason
360
421
  * is logged. A turn on `signIns`' queue, as every change of the setting is. */
361
422
  export async function dropRefusedLogin(signIns, settings, why, log) {
362
423
  if (!why)
@@ -371,17 +432,77 @@ export async function dropRefusedLogin(signIns, settings, why, log) {
371
432
  const pathOf = (env) => (env.PATH ? { path: env.PATH } : {});
372
433
  /** How long a signed-in answer stands in for a check that gives none (loginBeforeRun). */
373
434
  export const LOGIN_ANSWER_STANDS_MS = 10 * 60_000;
374
- /** When each login last answered signed in, in this server process: in memory only, never on disk, and nothing but the
375
- * time. A signed-out answer removes its entry. */
376
- const signedInAt = new Map();
435
+ /** The folder in the data folder that holds, per login, when it last answered signed in (noteAnswer). The server and its
436
+ * runner may be two processes on one data folder (`--no-runner` beside `agentrun-serve runner`): the Settings view's
437
+ * answer is the server's, a run's check the runner's, so the answer is kept where both read it. */
438
+ export const LOGIN_ANSWERS_DIR = "claude-login-answers";
377
439
  /** What tells one login from another here: its folder and its credentials dir. */
378
440
  const loginKey = (login) => JSON.stringify([login.dir, login.secure ?? null, login.unsuffixed === true]);
379
- /** Notes what the CLI said of `login` at `now`: signed in, the time; signed out, nothing (the earlier time goes). */
380
- function noteAnswer(login, said, now) {
381
- if (said.signedIn)
382
- signedInAt.set(loginKey(login), now);
383
- else
384
- signedInAt.delete(loginKey(login));
441
+ /** The file of `login`'s answer in `data`: named by a hash of this machine's id (machineId) and the login, so nothing of
442
+ * the login's paths is in its name, and an answer is only ever this machine's and this login's. */
443
+ const answerFile = (data, login) => join(data, LOGIN_ANSWERS_DIR, createHash("sha256").update(JSON.stringify([machineId(data), loginKey(login)])).digest("hex").slice(0, 32));
444
+ /** The most an answer file holds: a time in milliseconds and a newline. A longer file is no note of ours. */
445
+ const ANSWER_MAX_BYTES = 32;
446
+ /** The answers folder in `data`, made 0700, or tightened to 0700 when it was there wider; false when what is at its name
447
+ * is not a folder (a link, say), which a note is never written through. */
448
+ function answersFolder(data) {
449
+ const dir = join(data, LOGIN_ANSWERS_DIR);
450
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
451
+ const at = lstatSync(dir);
452
+ if (!at.isDirectory())
453
+ return false;
454
+ if ((at.mode & 0o777) !== 0o700)
455
+ chmodSync(dir, 0o700);
456
+ return true;
457
+ }
458
+ /** Notes what the CLI said of `login` at `now` in `data`: signed in, the time, alone, in a file of its own (0600, in a
459
+ * folder of 0700, answersFolder), written aside and renamed in place so a reader never sees half of it, the aside file
460
+ * removed when the rename fails; signed out, the file goes (the earlier time with it). The answer only spares a later
461
+ * run a refusal, so a note that can't be written is left out. */
462
+ function noteAnswer(login, said, now, data) {
463
+ try {
464
+ const file = answerFile(data, login);
465
+ if (!said.signedIn)
466
+ return void rmSync(file, { force: true });
467
+ if (!answersFolder(data))
468
+ return;
469
+ const aside = `${file}.${process.pid}.${randomBytes(4).toString("hex")}`;
470
+ try {
471
+ writeFileSync(aside, `${now}\n`, { mode: 0o600, flag: "wx" });
472
+ renameSync(aside, file);
473
+ }
474
+ finally {
475
+ rmSync(aside, { force: true });
476
+ }
477
+ }
478
+ catch {
479
+ // Not noted: a run whose checks give no answer is refused, as with no earlier answer.
480
+ }
481
+ }
482
+ /** When `login` last answered signed in on this machine (noteAnswer), or undefined. Only a regular file at the answer's
483
+ * name, of at most ANSWER_MAX_BYTES, is read: a link there is not followed, and a FIFO opens without waiting (it would
484
+ * hold this read, on a run's start, for ever) and is no file, so neither is an answer. */
485
+ function signedInAt(data, login) {
486
+ let fd;
487
+ try {
488
+ fd = openSync(answerFile(data, login), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
489
+ const at = fstatSync(fd);
490
+ if (!at.isFile() || at.size > ANSWER_MAX_BYTES)
491
+ return undefined;
492
+ const bytes = Buffer.alloc(ANSWER_MAX_BYTES + 1);
493
+ const read = readSync(fd, bytes, 0, bytes.length, 0);
494
+ if (read > ANSWER_MAX_BYTES)
495
+ return undefined;
496
+ const time = Number(bytes.subarray(0, read).toString("utf8").trim());
497
+ return Number.isSafeInteger(time) ? time : undefined;
498
+ }
499
+ catch {
500
+ return undefined;
501
+ }
502
+ finally {
503
+ if (fd !== undefined)
504
+ closeSync(fd);
505
+ }
385
506
  }
386
507
  /** The harness's codes for a status check that gave no answer (claudeLoginStatus's ClaudeLoginTimedOut and
387
508
  * ClaudeLoginNoStatus), read by code as the harness loads only when asked. */
@@ -394,14 +515,16 @@ const unknownLogin = (error) => new Error(`${LOGIN_UNKNOWN}: ${String(error?.mes
394
515
  * claudeLoginStatus, which asks once and, when the CLI gives no answer, throws with `code` "timed_out" or "no_status").
395
516
  * A check that gives no answer (it timed out, or the CLI said nothing that reads as a status) is asked once more, since
396
517
  * a loaded host can take past the limit with the login fine. Still none: the run goes on when this login answered
397
- * signed in within LOGIN_ANSWER_STANDS_MS in this server process (a run's check here, or the Settings view's), as its
398
- * own CLI still fails in words if the login is gone; else it is refused with LOGIN_UNKNOWN and why. Any other failure (a
399
- * CLI that is not at its path, say) is refused with LOGIN_UNKNOWN and its own words at once, asked once and never
400
- * waved through by an earlier answer. A signed-out answer is the answer: never asked again nor overridden, refused at
401
- * once, and the earlier signed-in time goes. `now`: the clock (Date.now). */
402
- export async function loginBeforeRun(login, cli, status, options = {}) {
518
+ * signed in on this machine within LOGIN_ANSWER_STANDS_MS (a run's check, or the Settings view's, in this process or
519
+ * another on the same data folder, `data`), as its own CLI still fails in words if the login is gone; else it is
520
+ * refused with LOGIN_UNKNOWN and why. Any other failure (a CLI that is not at its path, say) is refused with
521
+ * LOGIN_UNKNOWN and its own words at once, asked once and never waved through by an earlier answer. A signed-out answer
522
+ * is the answer: never asked again nor overridden, refused at once, and the earlier signed-in time goes. `now`: the
523
+ * clock (Date.now). */
524
+ export async function loginBeforeRun(login, cli, status, options) {
403
525
  if (!login || !cli)
404
526
  return;
527
+ const { data } = options;
405
528
  const now = options.now ?? Date.now;
406
529
  let said;
407
530
  let lastError;
@@ -416,12 +539,14 @@ export async function loginBeforeRun(login, cli, status, options = {}) {
416
539
  }
417
540
  }
418
541
  if (said === undefined) {
419
- const at = signedInAt.get(loginKey(login));
420
- if (at !== undefined && now() - at <= LOGIN_ANSWER_STANDS_MS)
542
+ // An answer from after now (the clock set back since) stands for nothing.
543
+ const at = signedInAt(data, login);
544
+ const age = at === undefined ? undefined : now() - at;
545
+ if (age !== undefined && age >= 0 && age <= LOGIN_ANSWER_STANDS_MS)
421
546
  return;
422
547
  throw unknownLogin(lastError);
423
548
  }
424
- noteAnswer(login, said, now());
549
+ noteAnswer(login, said, now(), data);
425
550
  if (!said.signedIn)
426
551
  throw new Error(LOGIN_SIGNED_OUT);
427
552
  }
package/dist/cli.js CHANGED
@@ -32,7 +32,6 @@ installEnvProxy();
32
32
  const USAGE = `usage: agentrun-serve [--data DIR] [--listen ADDR] [--port N] [--open] [--faux MODULE] [--faux-browser MODULE] [--faux-github] [--allow-host NAME ...] [--max-runs N] [--drain-timeout D] [--documents DIR] [--allow-code-nodes] [--learning on|off] [--no-runner] [--harness-module MODULE ...] [--harness-recipe FILE ...] [--harness-sign-in]
33
33
  agentrun-serve reset-password [--data DIR]
34
34
  agentrun-serve validate-template DIR
35
- agentrun-serve check-upload < BODY.json
36
35
  agentrun-serve install-harness goose|cursor [--data DIR]
37
36
  agentrun-serve install-harness --recipe FILE [--data DIR]
38
37
  agentrun-serve sign-in-harness --recipe FILE [--data DIR]
@@ -120,9 +119,8 @@ is read only when a page asks for it, kept 5 minutes); an https address reads th
120
119
  is off unless set to an address.
121
120
 
122
121
  AGENTRUN_API_ONLY=1 serves the run API alone, for a server behind its caller's backend (the routes in api-only.ts; every
123
- other address is a 404, and there are no accounts). With it, AGENTRUN_API_ONLY_MCP_ORIGINS (comma-separated origins, such
124
- as https://mcp.example.com) lets the token save a per_run MCP server at one of those origins (PUT
125
- /v2/settings/mcp-servers/NAME); unset, that save is a 404. A loopback origin also needs AGENTRUN_MCP_ALLOW_LOOPBACK=1.
122
+ other address is a 404, and there are no accounts). AGENTRUN_API_ONLY_MCP_ORIGINS: the MCP origins the token may save a
123
+ per_run MCP server at (README, API only).
126
124
 
127
125
  AGENTRUN_LAUNCH_HOOK_URL with AGENTRUN_LAUNCH_HOOK_SECRET (a whsec_ secret): each trigger firing that would start a run
128
126
  is POSTed to that URL, signed as Standard Webhooks, and the host starts the run through the API; this server starts
@@ -346,39 +344,6 @@ if (process.argv[2] === "check-harness") {
346
344
  console.log(`report: ${file}`);
347
345
  process.exit(report.ok ? 0 : 1);
348
346
  }
349
- // An upload's body ({files}, as `agentrun deploy` sends POST /v2/templates/import) read from stdin and checked by the
350
- // import's own check (template-import.ts checkUpload), storing nothing: the package's name and sha as one JSON line and
351
- // 0, or each reason the import would refuse it, a line each, and 1; 2 when stdin is not JSON. Nothing in it runs. Stdin
352
- // is decoded once, whole: a character split between two of its chunks reads back as itself.
353
- if (process.argv[2] === "check-upload") {
354
- const { checkUpload } = await import("./template-import.js");
355
- const { ApiError } = await import("./errors.js");
356
- parseArgs({ args: process.argv.slice(3), options: { data: { type: "string" } } });
357
- const chunks = [];
358
- for await (const chunk of process.stdin)
359
- chunks.push(chunk);
360
- let body;
361
- try {
362
- body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
363
- }
364
- catch {
365
- console.error("agentrun-serve check-upload reads an upload's body, {files}, as JSON on stdin.");
366
- process.exit(2);
367
- }
368
- try {
369
- const { pkg } = checkUpload(typeof body === "object" && body !== null ? body.files : undefined);
370
- console.log(JSON.stringify({ valid: true, name: pkg.name, sha: pkg.origin.sha }));
371
- process.exit(0);
372
- }
373
- catch (error) {
374
- if (!(error instanceof ApiError))
375
- throw error;
376
- const reasons = error.extra.fields?.map((field) => field.message) ?? [];
377
- for (const reason of reasons.length ? reasons : [error.message])
378
- console.error(reason);
379
- process.exit(1);
380
- }
381
- }
382
347
  // A template package folder checked by the one validator the server runs on the packages it ships (templates.ts): what
383
348
  // it holds as one JSON line and 0, or each problem and 1. Nothing in the package runs.
384
349
  if (process.argv[2] === "validate-template") {
@@ -693,11 +658,12 @@ if (!values["no-runner"] && askedAt === undefined) {
693
658
  // its shell is taken out first, as the server's own environment drops it (runner/main.ts besideRunEnv).
694
659
  const { besideRunEnv } = await import("./runner/main.js");
695
660
  // With the computer janitor: what a crashed runner of this server left is ended (never under --faux). With the
696
- // server's AttachHub: a paired computer's socket is in this process, so only this runner takes one (--no-runner's
697
- // separate runners refuse it in words). Its runs reach an MCP server on loopback only when this server is a local
698
- // install (Serve.localInstall).
661
+ // server's AttachHub and the name and incarnation the server gave it (Serve.beside): a paired computer's socket is in
662
+ // this process, and this runner's run holds it under a route that names it, so a runner apart (its own process,
663
+ // relaying through this server) takes it for no other run meanwhile. Its runs reach an MCP server on loopback only
664
+ // when this server is a local install (Serve.localInstall).
699
665
  // Each run a process of its own, as a user of its own where the image's helper can switch (run-child-host.ts).
700
- runnerProc = await runnerBeside(data, { loops, loopsTold, drainMs, env: besideRunEnv(process.env, fauxEnvOf(serveOptions)), janitor: true, ownProcesses: true, hub: serve.attachHub, dial: serve.dial, mcpLoopback: serve.localInstall, mcpOwn: serve.own, ollamaHost: serve.ollamaHost, onRunEnded: telemetry.runEnded });
666
+ runnerProc = await runnerBeside(data, { loops, loopsTold, drainMs, env: besideRunEnv(process.env, fauxEnvOf(serveOptions)), janitor: true, ownProcesses: true, hub: serve.attachHub, beside: serve.beside, dial: serve.dial, mcpLoopback: serve.localInstall, mcpOwn: serve.own, ollamaHost: serve.ollamaHost, onRunEnded: telemetry.runEnded });
701
667
  }
702
668
  catch (error) {
703
669
  // A run isolation the runner cannot give (run-child-host.ts runIsolationOf) is said, and the server serves on with no