@parcha/agentrun-serve 0.1.0-beta.54 → 0.1.0-beta.56

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 (234) hide show
  1. package/CHANGELOG.md +142 -2
  2. package/README.md +310 -98
  3. package/dist/adapters.d.ts +11 -0
  4. package/dist/adapters.js +49 -0
  5. package/dist/agent-package.d.ts +3 -3
  6. package/dist/agent-package.js +6 -13
  7. package/dist/agents-store.js +6 -5
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-only.d.ts +16 -4
  11. package/dist/api-only.js +23 -7
  12. package/dist/calendar/tools.js +3 -2
  13. package/dist/chatgpt-plan.d.ts +16 -1
  14. package/dist/chatgpt-plan.js +116 -12
  15. package/dist/claude-login.d.ts +34 -5
  16. package/dist/claude-login.js +31 -7
  17. package/dist/claude-sign-in.d.ts +35 -0
  18. package/dist/claude-sign-in.js +90 -0
  19. package/dist/cli.js +5 -3
  20. package/dist/composio-made.d.ts +26 -1
  21. package/dist/composio-made.js +39 -2
  22. package/dist/composio-preset.d.ts +3 -2
  23. package/dist/composio-preset.js +46 -14
  24. package/dist/computer-held-routes.js +2 -3
  25. package/dist/computer-setting.d.ts +4 -2
  26. package/dist/computer-setting.js +0 -2
  27. package/dist/computers-running.d.ts +8 -0
  28. package/dist/computers-running.js +27 -0
  29. package/dist/console/assets/backend-Boh7tC4i.js +166 -0
  30. package/dist/console/assets/index-CQ3cJRzI.js +746 -0
  31. package/dist/console/assets/index-DKkaS3a0.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/docker-host-addresses.d.ts +23 -3
  34. package/dist/docker-host-addresses.js +90 -18
  35. package/dist/exa-keyless.d.ts +2 -3
  36. package/dist/exa-keyless.js +43 -127
  37. package/dist/firecrawl-keyless.d.ts +41 -0
  38. package/dist/firecrawl-keyless.js +152 -0
  39. package/dist/handed-secret.d.ts +3 -1
  40. package/dist/handed-secret.js +4 -2
  41. package/dist/harness-keys.d.ts +98 -0
  42. package/dist/harness-keys.js +247 -0
  43. package/dist/harness-recipe-entry.d.ts +14 -9
  44. package/dist/harness-recipe-entry.js +25 -14
  45. package/dist/harness-table.d.ts +16 -1
  46. package/dist/harness-table.js +19 -7
  47. package/dist/harness.d.ts +4 -0
  48. package/dist/harness.js +12 -1
  49. package/dist/host-check.d.ts +6 -0
  50. package/dist/host-check.js +10 -0
  51. package/dist/import-summary.d.ts +1 -1
  52. package/dist/import-summary.js +1 -1
  53. package/dist/import.d.ts +5 -5
  54. package/dist/import.js +54 -67
  55. package/dist/key-refusal.d.ts +21 -5
  56. package/dist/key-refusal.js +231 -37
  57. package/dist/keyless-mcp.d.ts +36 -0
  58. package/dist/keyless-mcp.js +127 -0
  59. package/dist/learn/audit.d.ts +3 -3
  60. package/dist/learn/audit.js +3 -3
  61. package/dist/learn/commit.d.ts +8 -7
  62. package/dist/learn/commit.js +60 -20
  63. package/dist/learn/compile.d.ts +4 -3
  64. package/dist/learn/compile.js +7 -5
  65. package/dist/learn/folder.d.ts +16 -3
  66. package/dist/learn/folder.js +46 -13
  67. package/dist/learn/promote.d.ts +37 -13
  68. package/dist/learn/promote.js +112 -40
  69. package/dist/learn/secrets.d.ts +20 -10
  70. package/dist/learn/secrets.js +44 -176
  71. package/dist/learning-routes.d.ts +22 -17
  72. package/dist/learning-routes.js +40 -39
  73. package/dist/learning.js +2 -2
  74. package/dist/llms.txt +1 -1
  75. package/dist/manifest.d.ts +10 -0
  76. package/dist/manifest.js +30 -0
  77. package/dist/mcp-pin-first.d.ts +4 -2
  78. package/dist/mcp-pin-first.js +5 -2
  79. package/dist/mcp-secret-writes.d.ts +16 -7
  80. package/dist/mcp-secret-writes.js +35 -27
  81. package/dist/mcp-servers-store.d.ts +30 -6
  82. package/dist/mcp-servers-store.js +112 -28
  83. package/dist/mcp-sources.d.ts +10 -2
  84. package/dist/mcp-sources.js +9 -2
  85. package/dist/mcp-store.d.ts +13 -7
  86. package/dist/mcp-store.js +12 -9
  87. package/dist/model-form.d.ts +3 -2
  88. package/dist/model-form.js +11 -7
  89. package/dist/model.d.ts +20 -4
  90. package/dist/model.js +68 -9
  91. package/dist/native/history.d.ts +1 -1
  92. package/dist/native/history.js +2 -2
  93. package/dist/ollama-provider.d.ts +92 -0
  94. package/dist/ollama-provider.js +495 -0
  95. package/dist/openapi/agentrun-v2.openapi.json +2 -2
  96. package/dist/openapi.d.ts +3 -3
  97. package/dist/openapi.js +197 -55
  98. package/dist/page.d.ts +11 -3
  99. package/dist/page.js +22 -7
  100. package/dist/place-offers.d.ts +25 -1
  101. package/dist/place-offers.js +62 -8
  102. package/dist/print.js +1 -1
  103. package/dist/purged-workflow.d.ts +35 -7
  104. package/dist/purged-workflow.js +73 -26
  105. package/dist/redact/match.d.ts +74 -0
  106. package/dist/redact/match.js +771 -0
  107. package/dist/run-computer.d.ts +2 -0
  108. package/dist/run-computer.js +2 -0
  109. package/dist/run-files.d.ts +4 -0
  110. package/dist/run-files.js +4 -0
  111. package/dist/run-keys.d.ts +2 -4
  112. package/dist/run-keys.js +6 -7
  113. package/dist/run-launch.d.ts +4 -0
  114. package/dist/run-launch.js +4 -0
  115. package/dist/run-reads-over-store.d.ts +3 -2
  116. package/dist/run-reads-over-store.js +66 -2
  117. package/dist/run-secrets.js +5 -2
  118. package/dist/run-timeline-served.d.ts +1 -1
  119. package/dist/run-timeline-served.js +4 -4
  120. package/dist/runner/adapter-loop.d.ts +9 -3
  121. package/dist/runner/adapter-loop.js +34 -15
  122. package/dist/runner/adapter-run-spec.d.ts +3 -0
  123. package/dist/runner/adapter-run-spec.js +9 -4
  124. package/dist/runner/audit.js +8 -4
  125. package/dist/runner/beside.d.ts +2 -1
  126. package/dist/runner/beside.js +13 -5
  127. package/dist/runner/claim-secrets.d.ts +5 -8
  128. package/dist/runner/claim-secrets.js +6 -0
  129. package/dist/runner/cli-run-spec.d.ts +1 -1
  130. package/dist/runner/cli-run-spec.js +41 -7
  131. package/dist/runner/harness-loops.d.ts +22 -9
  132. package/dist/runner/harness-loops.js +21 -11
  133. package/dist/runner/held.d.ts +3 -0
  134. package/dist/runner/learning-end.d.ts +1 -1
  135. package/dist/runner/learning-end.js +8 -3
  136. package/dist/runner/loop-contract.d.ts +9 -4
  137. package/dist/runner/main.js +12 -6
  138. package/dist/runner/mcp-claim.d.ts +3 -0
  139. package/dist/runner/mcp-claim.js +26 -2
  140. package/dist/runner/mcp-run.d.ts +3 -0
  141. package/dist/runner/mcp-run.js +2 -1
  142. package/dist/runner/metrics.d.ts +10 -10
  143. package/dist/runner/metrics.js +19 -38
  144. package/dist/runner/model-route.d.ts +3 -0
  145. package/dist/runner/model-route.js +6 -2
  146. package/dist/runner/presence.d.ts +4 -3
  147. package/dist/runner/presence.js +4 -2
  148. package/dist/runner/promotion.d.ts +15 -9
  149. package/dist/runner/promotion.js +25 -15
  150. package/dist/runner/run-child-host.d.ts +2 -0
  151. package/dist/runner/run-child-host.js +19 -9
  152. package/dist/runner/run-child.js +3 -1
  153. package/dist/runner/runner.d.ts +4 -0
  154. package/dist/runner/runner.js +33 -3
  155. package/dist/runner/sdk-loop.js +2 -0
  156. package/dist/runner/workflow-loop.d.ts +2 -2
  157. package/dist/runner/workflow-loop.js +1 -2
  158. package/dist/runner/workflow-spec.d.ts +1 -1
  159. package/dist/runner/workflow-spec.js +6 -6
  160. package/dist/sdk/check.d.ts +4 -1
  161. package/dist/sdk/check.js +2 -1
  162. package/dist/sdk/runs.d.ts +2 -2
  163. package/dist/sdk/runs.js +8 -6
  164. package/dist/secret-cut.js +2 -1
  165. package/dist/secret-writes.d.ts +3 -2
  166. package/dist/secret-writes.js +1 -1
  167. package/dist/server.d.ts +49 -10
  168. package/dist/server.js +324 -118
  169. package/dist/standard-webhooks.d.ts +11 -0
  170. package/dist/standard-webhooks.js +20 -2
  171. package/dist/store/dialect.d.ts +3 -0
  172. package/dist/store/dialect.js +1 -0
  173. package/dist/store/index.d.ts +2 -2
  174. package/dist/store/index.js +1 -1
  175. package/dist/store/postgres/dialect.js +3 -0
  176. package/dist/store/schema.js +5 -2
  177. package/dist/store/sqlite/store.js +133 -47
  178. package/dist/store/store.d.ts +64 -15
  179. package/dist/store/store.js +7 -0
  180. package/dist/store-reads/journal.d.ts +7 -2
  181. package/dist/store-reads/journal.js +9 -6
  182. package/dist/store-reads/learning.d.ts +12 -9
  183. package/dist/store-reads/learning.js +18 -24
  184. package/dist/store-view.d.ts +0 -5
  185. package/dist/store-view.js +10 -9
  186. package/dist/template-eval.d.ts +51 -6
  187. package/dist/template-eval.js +177 -53
  188. package/dist/template-import.js +4 -2
  189. package/dist/templates.d.ts +5 -3
  190. package/dist/templates.js +19 -40
  191. package/dist/timeline/index.d.ts +1 -1
  192. package/dist/timeline/index.js +1 -1
  193. package/dist/timeline/labels.d.ts +2 -2
  194. package/dist/timeline/labels.js +2 -2
  195. package/dist/timeline/timeline.d.ts +14 -9
  196. package/dist/timeline/timeline.js +15 -7
  197. package/dist/tool-gate.js +3 -1
  198. package/dist/tool-plane.d.ts +17 -9
  199. package/dist/tool-plane.js +38 -17
  200. package/dist/tools.js +2 -2
  201. package/dist/trigger-launch-hook.d.ts +16 -8
  202. package/dist/trigger-launch-hook.js +32 -23
  203. package/dist/trigger-targets.d.ts +18 -8
  204. package/dist/trigger-targets.js +42 -19
  205. package/dist/triggers.d.ts +85 -23
  206. package/dist/triggers.js +303 -96
  207. package/dist/validate.js +1 -1
  208. package/dist/web-fake.js +3 -3
  209. package/dist/web-fetch-direct.d.ts +4 -0
  210. package/dist/web-fetch-direct.js +8 -1
  211. package/dist/web-fetch.d.ts +12 -3
  212. package/dist/web-fetch.js +47 -14
  213. package/dist/web-search.d.ts +33 -4
  214. package/dist/web-search.js +100 -41
  215. package/dist/webhooks.js +4 -5
  216. package/dist/workspace/computer-deps.d.ts +2 -1
  217. package/dist/workspace/computer-deps.js +5 -4
  218. package/dist/workspace/computer-for-claim.d.ts +8 -2
  219. package/dist/workspace/computer-for-claim.js +28 -9
  220. package/dist/workspace/computer-janitor.d.ts +15 -7
  221. package/dist/workspace/computer-janitor.js +33 -8
  222. package/dist/workspace/computer-kept.d.ts +52 -4
  223. package/dist/workspace/computer-kept.js +118 -6
  224. package/dist/workspace/run-end-computers.d.ts +5 -1
  225. package/dist/workspace/run-end-computers.js +27 -1
  226. package/dist/wrapped.d.ts +57 -0
  227. package/dist/wrapped.js +51 -0
  228. package/launcher/agentrun-serve +5 -1
  229. package/package.json +17 -13
  230. package/templates/README.md +10 -9
  231. package/dist/console/assets/index-B_85An2t.js +0 -745
  232. package/dist/console/assets/index-n1YsbnYh.css +0 -1
  233. package/dist/import-sources.d.ts +0 -116
  234. package/dist/import-sources.js +0 -693
@@ -101,6 +101,56 @@ function whoOf(token) {
101
101
  /** Whether a renewal's refusal is for good: the refresh token spent, expired or revoked (a 400 or 401 from the token
102
102
  * endpoint, as pi-ai words it), not a network fault or a 5xx. */
103
103
  const refusedForGood = (error) => /\((400|401)\)|invalid_grant|refresh_token_(reused|expired|invalidated)/.test(String(error?.message ?? ""));
104
+ /** A sign-in OpenAI finished whose credential this server could not keep (keep threw). */
105
+ class NotKept extends Error {
106
+ }
107
+ /** `value` as a log field or a code in words: letters, digits and `_` alone, 40 at most. */
108
+ const tag = (value) => String(value ?? "").replace(/[^A-Za-z0-9_]/g, "").slice(0, 40);
109
+ /** OpenAI's error code for a workspace whose admin has turned off open-source apps' use of its ChatGPT plans. */
110
+ const WORKSPACE_DENIED = "3p_delegated_access_policy_denied";
111
+ const ADMIN_OFF = "Your ChatGPT workspace's admin has turned off open-source apps (External access → OSS → Use ChatGPT plan): ask them to turn it on, or sign in with another account.";
112
+ /** A grant without DIRECT_SCOPE: OpenAI signed the account in but gave no use of its plan by apps. */
113
+ const PLAN_NOT_USABLE = "This ChatGPT plan can't be used here: OpenAI's sign-in gave AgentRun no use of it. Free plans usually can't; sign in with a paid one.";
114
+ /** What a refusal whose reason OpenAI doesn't name ends with: a Free plan's sign-in has ended in one, and nothing tells it
115
+ * apart. It never says Free can't be used: OpenAI changes which plans can. */
116
+ const FREE_OR_AGAIN = "a Free ChatGPT plan may be the reason; with a paid plan, start it again.";
117
+ const TIMED_OUT = "The sign-in timed out before OpenAI sent the code back: start it again.";
118
+ /** The words for OpenAI's refusal `code` at its sign-in page: fixed words, never the code. Anything on this machine can
119
+ * send the loopback callback an `error` while a sign-in waits, so the code goes to the log alone. */
120
+ const deniedWords = (code) => (tag(code) === WORKSPACE_DENIED ? ADMIN_OFF : `ChatGPT did not sign you in: ${FREE_OR_AGAIN}`);
121
+ /** Why a sign-in past its browser step ended without signing in, from what pi-ai's flow or keep threw: `reason` for the
122
+ * log (OpenAI's status and error code, a missing field's name, a network error's code; never a token or a code) and
123
+ * `words` a person reads. pi-ai's page says the sign-in completed before it exchanges the code, so these are the only
124
+ * word of a failure after it. */
125
+ export function signInFailure(error) {
126
+ const notKept = error instanceof NotKept;
127
+ const cause = notKept ? error.cause : error;
128
+ const message = String(cause?.message ?? "");
129
+ // OpenAI's refusal at its sign-in page, sent back to the loopback in place of a code (pi-ai's words for it), or of the
130
+ // code's exchange. Its code goes to the log; the words are fixed.
131
+ const denied = notKept ? null : /ChatGPT authorization failed: (\S+)/.exec(message);
132
+ const refused = notKept ? null : /token request failed \((\d{3})\)/.exec(message);
133
+ const code = denied ? tag(denied[1]) : refused ? tag(/"error"\s*:\s*"([^"]*)"/.exec(message)?.[1]) : "";
134
+ const reason = denied ? `authorize_${code || "error"}` : refused ? `token_${refused[1]}${code ? `_${code}` : ""}` : "";
135
+ // The workspace's refusal first: OpenAI's description of it may name the plan's scope.
136
+ if (code === WORKSPACE_DENIED)
137
+ return { reason, words: ADMIN_OFF };
138
+ if (message.includes(DIRECT_SCOPE))
139
+ return { reason: "no_direct_scope", words: PLAN_NOT_USABLE };
140
+ if (notKept)
141
+ return { reason: `not_saved${tag(cause?.code) ? `_${tag(cause.code)}` : ""}`, words: "OpenAI signed you in, but this server could not save the sign-in: start it again. The server's log says why." };
142
+ if (denied)
143
+ return { reason, words: deniedWords(code) };
144
+ if (refused)
145
+ return { reason, words: `OpenAI refused the sign-in: ${FREE_OR_AGAIN}` };
146
+ const unread = /token response (?:has invalid (\w+)|did not contain an (ID token)|must be an object)/.exec(message);
147
+ if (unread)
148
+ return { reason: `token_answer_${tag((unread[1] ?? unread[2] ?? "shape").replace(" ", "_"))}`, words: "OpenAI's answer to the sign-in was not one AgentRun can read: start it again. The server's log says what was missing." };
149
+ const network = tag(cause?.cause?.code);
150
+ if (/fetch failed/.test(message) || network)
151
+ return { reason: `network${network ? `_${network}` : ""}`, words: "This server could not reach OpenAI to finish the sign-in: check its connection, then start again." };
152
+ return { reason: `other_${tag(cause?.name) || "error"}`, words: "The sign-in did not finish: start it again. The server's log says why." };
153
+ }
104
154
  /** Whether a renewal that failed surely left its refresh token unspent: OpenAI answered with a fault (a 5xx, a 429), or
105
155
  * the request never reached it (no address, no connection). A timeout, or a fault once it was sent, may have spent it. */
106
156
  function unspent(error) {
@@ -125,6 +175,11 @@ export class ChatGPTPlan {
125
175
  /** Set when a sign-in dropped by a sign-out (keep) could not have its revocation confirmed by OpenAI: that sign-out
126
176
  * answers revoked false. Cleared at each sign-out's start. */
127
177
  #droppedUnconfirmed = false;
178
+ /** Why the last sign-in ended without signing in (signInFailure's words past its browser step, or its timeout), until a
179
+ * sign-in starts, finishes or a sign-out. A cancelled one leaves none. */
180
+ #problem;
181
+ /** Set when the server's change callback failed after a sign-in was saved; cleared once it takes (changeAgain). */
182
+ #changeOwed = false;
128
183
  #watchers = new Set();
129
184
  #deps;
130
185
  constructor(deps) {
@@ -203,14 +258,15 @@ export class ChatGPTPlan {
203
258
  }
204
259
  view() {
205
260
  if (this.#pending && this.#pending.expiresAt <= this.now())
206
- this.cancel();
261
+ this.expire();
207
262
  const row = this.#snapshot;
208
263
  const who = row ? { ...(row.email ? { email: row.email } : {}), ...(row.plan ? { plan: row.plan } : {}) } : {};
209
264
  if (this.#pending)
210
265
  return { state: "pending", authorize_url: this.#pending.authorizeUrl, expires_at: new Date(this.#pending.expiresAt).toISOString(), ...who };
266
+ const problem = this.#problem ? { problem: this.#problem } : {};
211
267
  if (!row)
212
- return { state: "signed_out" };
213
- return { state: row.state, ...who, ...(row.state === "signed_in" ? { models: [...row.models] } : {}) };
268
+ return { state: "signed_out", ...problem };
269
+ return { state: row.state, ...who, ...(row.state === "signed_in" ? { models: [...row.models] } : {}), ...problem };
214
270
  }
215
271
  /** This server's id at OpenAI (its agent host id): a UUID made once and kept in the store's settings. Not a credential. */
216
272
  async hostId() {
@@ -229,12 +285,22 @@ export class ChatGPTPlan {
229
285
  clearTimeout(pending.timer);
230
286
  pending.abort.abort();
231
287
  }
288
+ /** Ends the sign-in waiting past its 10 minutes: a cancel, which says nothing by itself, that says it timed out. One
289
+ * whose code OpenAI answered is past waiting (it is being kept) and never times out. */
290
+ expire() {
291
+ if (!this.#pending || this.#pending.answered)
292
+ return;
293
+ this.cancel();
294
+ this.#problem = TIMED_OUT;
295
+ this.#deps.log?.({ chatgpt: "sign_in_failed", reason: "timed_out" });
296
+ }
232
297
  /** Starts a sign-in (one at a time: a new start cancels the one waiting) and gives the address to open. It lasts 10
233
298
  * minutes: the loopback callback finishes it where the browser runs on this machine; elsewhere finishSignIn does. */
234
299
  async startSignIn() {
235
300
  // A sign-in still finishing drops its credential (keep): this one is the person's latest.
236
301
  const epoch = ++this.#epoch;
237
302
  const before = this.#pending;
303
+ this.#problem = undefined;
238
304
  this.cancel();
239
305
  // pi-ai's callback listener on :1455 closes as its login ends: the one cancelled ends before this one listens.
240
306
  if (before)
@@ -259,17 +325,33 @@ export class ChatGPTPlan {
259
325
  this.#pending = undefined;
260
326
  };
261
327
  // Pending until the credential is kept or dropped, so a sign-out meanwhile cancels it (keep's epoch).
262
- const result = login.then((credential) => this.keep(credential, epoch)).finally(settle);
263
- result.catch(() => undefined);
328
+ const result = login.then((credential) => {
329
+ if (this.#pending?.abort === abort)
330
+ this.#pending.answered = true;
331
+ return this.keep(credential, epoch).catch((error) => {
332
+ throw new NotKept("not kept", { cause: error });
333
+ });
334
+ }).finally(settle);
335
+ // Past the browser step, the tab already says it completed: an end that is not a cancel (a newer start, a sign-out,
336
+ // the wait's end, the server's close) says why in the view and the log, whichever way the address came back.
337
+ let waiting = false;
338
+ result.catch((error) => {
339
+ if (!waiting || abort.signal.aborted || epoch !== this.#epoch)
340
+ return;
341
+ const { reason, words } = signInFailure(error);
342
+ this.#problem = words;
343
+ this.#deps.log?.({ chatgpt: "sign_in_failed", reason });
344
+ });
264
345
  const authorizeUrl = await Promise.race([link, result.then(() => undefined, (error) => {
265
346
  throw new PlanSignInRefused(/in use/.test(String(error?.message)) ? "Another sign-in holds this machine's port 1455: finish or cancel it, then start again." : "The sign-in could not start: try again.");
266
347
  })]);
267
348
  if (!authorizeUrl)
268
349
  throw new PlanSignInRefused("The sign-in could not start: try again.");
269
350
  const expiresAt = this.now() + PENDING_MS;
270
- const timer = setTimeout(() => (this.#pending?.abort === abort ? this.cancel() : undefined), PENDING_MS);
351
+ const timer = setTimeout(() => (this.#pending?.abort === abort ? this.expire() : undefined), PENDING_MS);
271
352
  timer.unref();
272
353
  this.#pending = { abort, state: new URL(authorizeUrl).searchParams.get("state") ?? "", authorizeUrl, expiresAt, paste, result, timer };
354
+ waiting = true;
273
355
  return { authorize_url: authorizeUrl, expires_at: new Date(expiresAt).toISOString() };
274
356
  }
275
357
  /** Finishes the sign-in waiting with the address its browser tab ended on, pasted. A URL that is not that sign-in's end
@@ -290,7 +372,7 @@ export class ChatGPTPlan {
290
372
  throw new PlanSignInRefused(shape);
291
373
  const error = url.searchParams.get("error");
292
374
  if (error)
293
- throw new PlanSignInRefused(`ChatGPT did not sign you in (${error.replace(/[^a-z_]/gi, "").slice(0, 40)}): start the sign-in again.`);
375
+ throw new PlanSignInRefused(deniedWords(error));
294
376
  if (url.searchParams.get("state") !== pending.state)
295
377
  throw new PlanSignInRefused("That address is from another sign-in: paste the one from the sign-in you started last, or start again.");
296
378
  if (!url.searchParams.get("code") || !url.searchParams.get("client_id"))
@@ -300,10 +382,7 @@ export class ChatGPTPlan {
300
382
  await pending.result;
301
383
  }
302
384
  catch (error) {
303
- const words = String(error?.message ?? "");
304
- if (words.includes(DIRECT_SCOPE))
305
- throw new PlanSignInRefused("This ChatGPT account did not allow its plan to be used by apps: sign in with an account whose plan allows it.");
306
- throw new PlanSignInRefused("OpenAI refused the sign-in: start it again.");
385
+ throw new PlanSignInRefused(signInFailure(error).words);
307
386
  }
308
387
  return this.view();
309
388
  }
@@ -340,8 +419,32 @@ export class ChatGPTPlan {
340
419
  break;
341
420
  }
342
421
  this.#snapshot = row;
422
+ this.#problem = undefined;
343
423
  this.#deps.log?.({ chatgpt: "signed_in", ...(previousRevoked === undefined ? {} : { previous_revoked: String(previousRevoked) }) });
344
- await this.#deps.changed?.();
424
+ // Saved: what the server does with the change after it is not the sign-in's to fail. One it failed to take is owed,
425
+ // and taken again at its next read (changeAgain).
426
+ try {
427
+ await this.#deps.changed?.();
428
+ this.#changeOwed = false;
429
+ }
430
+ catch (error) {
431
+ this.#changeOwed = true;
432
+ const code = error?.code;
433
+ this.#deps.log?.({ chatgpt: "changed_failed", reason: String(typeof code === "string" ? code : error?.name ?? "error").replace(/[^A-Za-z0-9_]/g, "").slice(0, 40) || "error" });
434
+ }
435
+ }
436
+ /** Takes again a sign-in's change the server failed to take (changed_failed), at the server's read of the sign-in, so
437
+ * what it offers does not wait for a restart. Nothing when none is owed; a failure again stays owed, said once. */
438
+ async changeAgain() {
439
+ if (!this.#changeOwed)
440
+ return;
441
+ try {
442
+ await this.#deps.changed?.();
443
+ this.#changeOwed = false;
444
+ }
445
+ catch {
446
+ // Owed still: the next read takes it again.
447
+ }
345
448
  }
346
449
  /** The plan's models from OpenAI's list (GET /v1/models with the token), those of the current families; the fallback
347
450
  * list when it can't be read. */
@@ -487,6 +590,7 @@ export class ChatGPTPlan {
487
590
  * is not this answer's to give). */
488
591
  async signOut() {
489
592
  this.#droppedUnconfirmed = false;
593
+ this.#problem = undefined;
490
594
  this.#epoch += 1;
491
595
  const finishing = this.#pending;
492
596
  this.cancel();
@@ -1,4 +1,5 @@
1
1
  import type { ClaudeAgentLogin, ClaudeLoginStatus } from "@parcha/agentrun-harness-claude";
2
+ import type { ClaudeSignIns, SignInView } from "./claude-sign-in.js";
2
3
  import type { Settings } from "./store/index.js";
3
4
  /** The switch: `off` (or 0, false, no) turns the mode off on this server, `on` (or 1, true, yes) leaves it there past
4
5
  * loopback; unset, the listen address decides (claudeLoginSwitchedOff). */
@@ -26,7 +27,21 @@ type Setting = {
26
27
  host: string;
27
28
  only_me: true;
28
29
  };
29
- /** The directories of a login at `place`: AgentRun's in `data`, or this machine's (the CLI's own defaults for its user). */
30
+ /** This machine's own Claude Code login folder as the CLI finds it for the server's user, by the CLI's own rule: its
31
+ * config dir is `CLAUDE_CONFIG_DIR` when set, else `~/.claude`, and its credentials are kept there too unless
32
+ * `CLAUDE_SECURESTORAGE_CONFIG_DIR` says otherwise. Read from the server's env, so a Claude Code started with another
33
+ * `CLAUDE_CONFIG_DIR` is found only when AgentRun was started with it as well. A relative one is not taken: the CLI would
34
+ * read it against a working directory this server does not share. `source` says which rule gave the folder. */
35
+ export declare function machineFolder(env?: Readonly<Record<string, string | undefined>>): {
36
+ folder: string;
37
+ source: "CLAUDE_CONFIG_DIR" | "default";
38
+ };
39
+ /** The directories of a login at `place`: AgentRun's in `data`, or this machine's (machineFolder, and the Anthropic
40
+ * profiles where the CLI looks for them: `ANTHROPIC_CONFIG_DIR`, else `$XDG_CONFIG_HOME/anthropic`, else
41
+ * `~/.config/anthropic`). This machine's on the CLI's default folder carries the person's home too, so the harness
42
+ * points the CLI at it as their own CLI runs, with no folder variable (the harness's signInEnv and loginEnv). This
43
+ * machine's is `shared` with the person's own CLI, so a status check runs on a copy of its account file
44
+ * (the harness's claudeLoginStatus). */
30
45
  export declare function loginAt(place: LoginPlace, data: string, env?: Readonly<Record<string, string | undefined>>): ClaudeAgentLogin;
31
46
  /** The setting as saved, or undefined when the mode is not on (or the row is not one this reads). */
32
47
  export declare function claudeLoginSetting(settings: Pick<Settings, "get">): Promise<Setting | undefined>;
@@ -74,6 +89,15 @@ export type ClaudeLoginView = {
74
89
  organization?: string;
75
90
  plan?: string;
76
91
  };
92
+ /** The folder whose login the CLI is asked about: the login's directory at `place`. */
93
+ folder: string;
94
+ /** This machine's own Claude Code login as this server finds it (machineFolder). */
95
+ machine: {
96
+ folder: string;
97
+ source: "CLAUDE_CONFIG_DIR" | "default";
98
+ };
99
+ /** The CLI's sign-in this server started, while this server runs (claude-sign-in.ts). */
100
+ sign_in?: SignInView;
77
101
  };
78
102
  /** The account's words, as the view shows them. */
79
103
  export declare const accountOf: (status: ClaudeLoginStatus) => NonNullable<ClaudeLoginView["account"]>;
@@ -98,8 +122,10 @@ export declare const claudeLoginRouteOff: (name: string, why: string) => string;
98
122
  /** What the routes need of the server. `pinned`: the pinned CLI's path when installed. `refused`: whyNotOneOwner of this
99
123
  * server. `sameMachine`: the request comes from a browser on this machine to a server bound to loopback with no public
100
124
  * address, so a sign-in the CLI opens in a browser here reaches the person. `status`/`start`: the harness's
101
- * claudeLoginStatus and startClaudeLogin. `changed`: env read again after a turn on or off. */
125
+ * claudeLoginStatus and startClaudeLogin. `changed`: env read again after a turn on or off. `signIns`: the sign-in this
126
+ * server started, one per server process (claude-sign-in.ts). */
102
127
  export type ClaudeLoginDeps = {
128
+ signIns: ClaudeSignIns;
103
129
  settings: Pick<Settings, "get" | "put" | "remove">;
104
130
  data: string;
105
131
  env: Readonly<Record<string, string | undefined>>;
@@ -118,10 +144,13 @@ export declare class ClaudeLoginRefused extends Error {
118
144
  export declare function claudeLoginView(deps: ClaudeLoginDeps): Promise<ClaudeLoginView>;
119
145
  /** PUT /settings/claude-login: turned on, refused in one line where more than one person can start runs. */
120
146
  export declare function turnOnClaudeLogin(deps: ClaudeLoginDeps, body: unknown): Promise<ClaudeLoginView>;
121
- /** DELETE /settings/claude-login: turned off. The login itself stays as the CLI keeps it; nothing here signs it out. */
147
+ /** DELETE /settings/claude-login: turned off, and a sign-in this server started that still waits is ended. The login
148
+ * itself stays as the CLI keeps it; nothing here signs it out. */
122
149
  export declare function turnOffClaudeLogin(deps: ClaudeLoginDeps): Promise<ClaudeLoginView>;
123
- /** POST /settings/claude-login/login: the CLI's own sign-in, started on this machine, where it opens a browser. The
124
- * browser code goes to the CLI, never here; the answer is the view as it is when the sign-in starts. */
150
+ /** POST /settings/claude-login/login: the CLI's own sign-in, started on this machine, where it opens a browser, with the
151
+ * shown line's own variables (the harness's signInEnv), so it signs in where the status reads. A sign-in that
152
+ * still waits is ended first (deps.signIns). The browser code goes to the CLI, never here; the answer is the view as it
153
+ * is when the sign-in starts, its `sign_in` waiting. */
125
154
  export declare function startLoginHere(deps: ClaudeLoginDeps): Promise<ClaudeLoginView>;
126
155
  /** At the server's start: a setting saved where the mode is now off or refused (`why`: the switch, a listen address past
127
156
  * loopback, a second token, the API-only profile) goes, so no runner, in this process or another, runs on it; the reason
@@ -46,13 +46,30 @@ export const LOGIN_DEFAULT_MODEL = "anthropic/claude-sonnet-5-5";
46
46
  /** Where the login is: AgentRun's own directory in its data (`agentrun`, the default), or this machine's own Claude Code
47
47
  * login (`machine`, which the owner opts into by name). */
48
48
  export const LOGIN_PLACES = ["agentrun", "machine"];
49
- /** The directories of a login at `place`: AgentRun's in `data`, or this machine's (the CLI's own defaults for its user). */
49
+ /** This machine's own Claude Code login folder as the CLI finds it for the server's user, by the CLI's own rule: its
50
+ * config dir is `CLAUDE_CONFIG_DIR` when set, else `~/.claude`, and its credentials are kept there too unless
51
+ * `CLAUDE_SECURESTORAGE_CONFIG_DIR` says otherwise. Read from the server's env, so a Claude Code started with another
52
+ * `CLAUDE_CONFIG_DIR` is found only when AgentRun was started with it as well. A relative one is not taken: the CLI would
53
+ * read it against a working directory this server does not share. `source` says which rule gave the folder. */
54
+ export function machineFolder(env = process.env) {
55
+ if (env.CLAUDE_CONFIG_DIR && isAbsolute(env.CLAUDE_CONFIG_DIR))
56
+ return { folder: env.CLAUDE_CONFIG_DIR, source: "CLAUDE_CONFIG_DIR" };
57
+ const home = env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir();
58
+ return { folder: join(home, ".claude"), source: "default" };
59
+ }
60
+ /** The directories of a login at `place`: AgentRun's in `data`, or this machine's (machineFolder, and the Anthropic
61
+ * profiles where the CLI looks for them: `ANTHROPIC_CONFIG_DIR`, else `$XDG_CONFIG_HOME/anthropic`, else
62
+ * `~/.config/anthropic`). This machine's on the CLI's default folder carries the person's home too, so the harness
63
+ * points the CLI at it as their own CLI runs, with no folder variable (the harness's signInEnv and loginEnv). This
64
+ * machine's is `shared` with the person's own CLI, so a status check runs on a copy of its account file
65
+ * (the harness's claudeLoginStatus). */
50
66
  export function loginAt(place, data, env = process.env) {
51
67
  if (place === "agentrun")
52
68
  return { dir: join(data, "claude-login"), profiles: join(data, "claude-login", "anthropic") };
53
69
  const home = env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir();
54
70
  const config = env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join(home, ".config");
55
- return { dir: join(home, ".claude"), profiles: env.ANTHROPIC_CONFIG_DIR && isAbsolute(env.ANTHROPIC_CONFIG_DIR) ? env.ANTHROPIC_CONFIG_DIR : join(config, "anthropic") };
71
+ const { folder, source } = machineFolder(env);
72
+ return { dir: folder, profiles: env.ANTHROPIC_CONFIG_DIR && isAbsolute(env.ANTHROPIC_CONFIG_DIR) ? env.ANTHROPIC_CONFIG_DIR : join(config, "anthropic"), ...(source === "default" ? { home } : {}), shared: true };
56
73
  }
57
74
  /** The setting as saved, or undefined when the mode is not on (or the row is not one this reads). */
58
75
  export async function claudeLoginSetting(settings) {
@@ -165,7 +182,8 @@ export async function claudeLoginView(deps) {
165
182
  const place = setting?.place ?? "agentrun";
166
183
  const login = loginAt(place, deps.data, deps.env);
167
184
  const cli = loginCli(await deps.pinned(), deps.env);
168
- const base = { place, command: (await deps.claude()).claudeLoginCommand(login, cli ?? "claude"), can_start: deps.sameMachine && cli !== undefined && deps.refused === undefined, ...(deps.refused ? { refused: deps.refused } : {}) };
185
+ const signIn = deps.signIns.view();
186
+ const base = { place, command: (await deps.claude()).claudeLoginCommand(login, cli ?? "claude"), can_start: deps.sameMachine && cli !== undefined && deps.refused === undefined, ...(deps.refused ? { refused: deps.refused } : {}), folder: login.dir, machine: machineFolder(deps.env), ...(signIn ? { sign_in: signIn } : {}) };
169
187
  if (!setting)
170
188
  return { state: "off", ...base };
171
189
  if (setting.host !== hostname())
@@ -191,14 +209,18 @@ export async function turnOnClaudeLogin(deps, body) {
191
209
  await deps.changed();
192
210
  return claudeLoginView(deps);
193
211
  }
194
- /** DELETE /settings/claude-login: turned off. The login itself stays as the CLI keeps it; nothing here signs it out. */
212
+ /** DELETE /settings/claude-login: turned off, and a sign-in this server started that still waits is ended. The login
213
+ * itself stays as the CLI keeps it; nothing here signs it out. */
195
214
  export async function turnOffClaudeLogin(deps) {
215
+ await deps.signIns.stop();
196
216
  await deps.settings.remove(CLAUDE_LOGIN_SETTING);
197
217
  await deps.changed();
198
218
  return claudeLoginView(deps);
199
219
  }
200
- /** POST /settings/claude-login/login: the CLI's own sign-in, started on this machine, where it opens a browser. The
201
- * browser code goes to the CLI, never here; the answer is the view as it is when the sign-in starts. */
220
+ /** POST /settings/claude-login/login: the CLI's own sign-in, started on this machine, where it opens a browser, with the
221
+ * shown line's own variables (the harness's signInEnv), so it signs in where the status reads. A sign-in that
222
+ * still waits is ended first (deps.signIns). The browser code goes to the CLI, never here; the answer is the view as it
223
+ * is when the sign-in starts, its `sign_in` waiting. */
202
224
  export async function startLoginHere(deps) {
203
225
  if (deps.refused)
204
226
  throw new ClaudeLoginRefused("forbidden", deps.refused);
@@ -213,7 +235,9 @@ export async function startLoginHere(deps) {
213
235
  if (!cli)
214
236
  throw new ClaudeLoginRefused("agent_not_runnable", "No Claude Code CLI here yet: claude-agent's first run installs it, or run the command shown.");
215
237
  // The person's home and desktop, so the CLI can open their browser.
216
- (await deps.claude()).startClaudeLogin(cli, loginAt(setting.place, deps.data, deps.env), { ...pathOf(deps.env), ...(deps.env.HOME ? { home: deps.env.HOME } : {}), display: deps.env });
238
+ const claude = await deps.claude();
239
+ const login = loginAt(setting.place, deps.data, deps.env);
240
+ await deps.signIns.start((timeoutMs) => claude.startClaudeLogin(cli, login, { ...pathOf(deps.env), ...(deps.env.HOME ? { home: deps.env.HOME } : {}), display: deps.env, timeoutMs }));
217
241
  return claudeLoginView(deps);
218
242
  }
219
243
  /** At the server's start: a setting saved where the mode is now off or refused (`why`: the switch, a listen address past
@@ -0,0 +1,35 @@
1
+ import type { ClaudeSignIn } from "@parcha/agentrun-harness-claude";
2
+ /** How long a sign-in waits for its browser by default: the harness's own limit. */
3
+ export declare const SIGN_IN_LIMIT_MS: number;
4
+ /** A sign-in as GET /settings/claude-login says it. `state`: `waiting` (for the browser, since `started_at`),
5
+ * `signed_in` (the CLI exited 0), `timed_out` (ended after `limit_ms` with no answer from the browser), `failed` (the
6
+ * CLI ended without signing in: `exit_code`, or the `signal` that ended it), `not_started` (the CLI could not be
7
+ * started: `error`). */
8
+ export type SignInView = {
9
+ state: "waiting" | "signed_in" | "timed_out" | "failed" | "not_started";
10
+ started_at: string;
11
+ ended_at?: string;
12
+ limit_ms: number;
13
+ exit_code?: number;
14
+ signal?: string;
15
+ error?: string;
16
+ };
17
+ /** The one sign-in this server started, and its start and stop. `limitMs`: how long a sign-in waits for its browser
18
+ * (SIGN_IN_LIMIT_MS by default; a test's is short). `now`: the clock its times are read from. */
19
+ export declare class ClaudeSignIns {
20
+ #private;
21
+ readonly limitMs: number;
22
+ constructor(options?: {
23
+ limitMs?: number;
24
+ now?: () => number;
25
+ });
26
+ /** The sign-in as it stands, or undefined when none was started here (or it was stopped). */
27
+ view(): SignInView | undefined;
28
+ /** Start a sign-in with `begin` (the harness's startClaudeLogin, given the limit), after ending one that waits. */
29
+ start(begin: (limitMs: number) => ClaudeSignIn): Promise<SignInView>;
30
+ /** End a sign-in that waits, and forget the one there is (a turn-off). */
31
+ stop(): Promise<void>;
32
+ /** The server's stop: as stop(), resolving once a CLI that waited is gone, and a start asked after it (a request still
33
+ * in flight) spawns nothing. A CLI left waiting would keep the browser's callback port from the next server's sign-in. */
34
+ close(): Promise<void>;
35
+ }
@@ -0,0 +1,90 @@
1
+ /** How long a sign-in waits for its browser by default: the harness's own limit. */
2
+ export const SIGN_IN_LIMIT_MS = 10 * 60_000;
3
+ const words = (error) => String(error?.message ?? error).slice(0, 200);
4
+ /** The view of a sign-in that ended as `end`. */
5
+ function endedView(started, end, at) {
6
+ const ended = { ...started, ended_at: at };
7
+ switch (end.end) {
8
+ case "exited":
9
+ if (end.code === 0)
10
+ return { ...ended, state: "signed_in" };
11
+ return { ...ended, state: "failed", ...(end.code !== null ? { exit_code: end.code } : {}), ...(end.signal ? { signal: end.signal } : {}) };
12
+ case "timed_out":
13
+ return { ...ended, state: "timed_out" };
14
+ case "failed":
15
+ return { ...ended, state: "not_started", error: end.message };
16
+ case "stopped":
17
+ // Only this server stops one, and it forgets it as it does (stop), so this view is never kept.
18
+ return { ...ended, state: "failed" };
19
+ }
20
+ }
21
+ /** The one sign-in this server started, and its start and stop. `limitMs`: how long a sign-in waits for its browser
22
+ * (SIGN_IN_LIMIT_MS by default; a test's is short). `now`: the clock its times are read from. */
23
+ export class ClaudeSignIns {
24
+ limitMs;
25
+ #now;
26
+ #current;
27
+ // Each start or stop is a turn of its own: an end that arrives after a later turn began is not kept.
28
+ #turn = 0;
29
+ // Starts and stops, one after another, so two presses at once never leave two CLIs waiting on one port.
30
+ #queue = Promise.resolve();
31
+ // Set at the server's stop (close): no start after it spawns a CLI.
32
+ #closed = false;
33
+ constructor(options = {}) {
34
+ this.limitMs = options.limitMs ?? SIGN_IN_LIMIT_MS;
35
+ this.#now = options.now ?? Date.now;
36
+ }
37
+ /** The sign-in as it stands, or undefined when none was started here (or it was stopped). */
38
+ view() {
39
+ return this.#current ? { ...this.#current.view } : undefined;
40
+ }
41
+ /** Start a sign-in with `begin` (the harness's startClaudeLogin, given the limit), after ending one that waits. */
42
+ start(begin) {
43
+ const next = this.#queue.then(async () => {
44
+ await this.#end();
45
+ const turn = ++this.#turn;
46
+ const started = { started_at: new Date(this.#now()).toISOString(), limit_ms: this.limitMs };
47
+ if (this.#closed) {
48
+ this.#current = { view: { ...started, state: "not_started", ended_at: started.started_at, error: "this server is stopping" } };
49
+ return this.view();
50
+ }
51
+ let handle;
52
+ try {
53
+ handle = begin(this.limitMs);
54
+ }
55
+ catch (error) {
56
+ this.#current = { view: { ...started, state: "not_started", ended_at: started.started_at, error: words(error) } };
57
+ return this.view();
58
+ }
59
+ this.#current = { view: { ...started, state: "waiting" }, handle };
60
+ void handle.ended.then((end) => {
61
+ if (turn === this.#turn)
62
+ this.#current = { view: endedView(started, end, new Date(this.#now()).toISOString()) };
63
+ });
64
+ return this.view();
65
+ });
66
+ this.#queue = next.catch(() => { });
67
+ return next;
68
+ }
69
+ /** End a sign-in that waits, and forget the one there is (a turn-off). */
70
+ stop() {
71
+ const next = this.#queue.then(() => this.#end());
72
+ this.#queue = next.catch(() => { });
73
+ return next;
74
+ }
75
+ /** The server's stop: as stop(), resolving once a CLI that waited is gone, and a start asked after it (a request still
76
+ * in flight) spawns nothing. A CLI left waiting would keep the browser's callback port from the next server's sign-in. */
77
+ close() {
78
+ this.#closed = true;
79
+ return this.stop();
80
+ }
81
+ async #end() {
82
+ const current = this.#current;
83
+ this.#turn++;
84
+ this.#current = undefined;
85
+ if (current?.view.state !== "waiting" || !current.handle)
86
+ return;
87
+ current.handle.stop();
88
+ await current.handle.ended;
89
+ }
90
+ }
package/dist/cli.js CHANGED
@@ -573,7 +573,7 @@ catch (error) {
573
573
  }
574
574
  if (early)
575
575
  console.log(`Starting ${publicUrl ?? urlOf(early, values.listen ?? DEFAULT_HOST)}/ (warming: health says so and the API answers 503 until the server is ready)`);
576
- const [{ fauxEnvOf, startServe }, { besideRunnerOptions, besideStopping, runnerBeside }, { startedWith }, { canOpen }] = await Promise.all([import("./server.js"), import("./runner/beside.js"), import("./adapters.js"), import("./host.js")]);
576
+ const [{ fauxEnvOf, startServe }, { besideRunnerOptions, besideStopping, runnerBeside }, { earlierDataRefusal, startedWith }, { canOpen }] = await Promise.all([import("./server.js"), import("./runner/beside.js"), import("./adapters.js"), import("./host.js")]);
577
577
  // How it was started, for the hints that start it again (adapters.ts npxLine): itself and its runs read it.
578
578
  Object.assign(process.env, startedWith({ ...(values.port !== undefined ? { port: values.port } : {}), open: values.open === true }));
579
579
  let serve;
@@ -611,7 +611,9 @@ try {
611
611
  });
612
612
  }
613
613
  catch (error) {
614
- console.error(`agentrun-serve: ${error.message}`);
614
+ // A data directory an earlier version wrote, refused on a start `npx @parcha/agentrun` made: the ways on as that command
615
+ // (adapters.ts earlierDataRefusal). Any other start keeps the refusal's own words.
616
+ console.error(`agentrun-serve: ${earlierDataRefusal(error, data, process.env) ?? error.message}`);
615
617
  process.exit(1);
616
618
  }
617
619
  // The start launches one runner beside the server on the same data dir (design: "server and runner"): it claims and runs
@@ -638,7 +640,7 @@ if (!values["no-runner"] && askedAt === undefined) {
638
640
  // separate runners refuse it in words). Its runs reach an MCP server on loopback only when this server is a local
639
641
  // install (Serve.localInstall).
640
642
  // Each run a process of its own, as a user of its own where the image's helper can switch (run-child-host.ts).
641
- 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, onRunEnded: telemetry.runEnded });
643
+ 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 });
642
644
  }
643
645
  catch (error) {
644
646
  // A run isolation the runner cannot give (run-child-host.ts runIsolationOf) is said, and the server serves on with no
@@ -8,7 +8,8 @@ export type Made = {
8
8
  * under it. `per_run`: saved with `user_id: "per_run"` (COMPOSIO_PER_RUN), its address names no user and no account,
9
9
  * and each run names its own (mcp_auth, composioPerRun); `user` is then that word and `accounts` empty. Only a save made
10
10
  * since the mode exists writes it, so a server saved before for a Composio user literally named "per_run" keeps that
11
- * user until it is saved again. */
11
+ * user until it is saved again. `key_env`: saved with `api_key_env`, its key is the value of this variable the server and
12
+ * each runner were started with, read at each use, and its row seals no credential (composioKeyFromEnv). */
12
13
  export type ComposioMade = {
13
14
  user: string;
14
15
  auth_config: (Made & {
@@ -16,7 +17,14 @@ export type ComposioMade = {
16
17
  }) | null;
17
18
  accounts: Made[];
18
19
  per_run?: true;
20
+ key_env?: typeof COMPOSIO_KEY_ENV;
19
21
  };
22
+ /** The one variable a Composio save may name for its key (`api_key_env`). Composio's host is fixed in code, so no other
23
+ * secret of the server's environment is ever sent there. */
24
+ export declare const COMPOSIO_KEY_ENV = "COMPOSIO_API_KEY";
25
+ /** Composio's origin: its API's base (composio-preset.ts) and where its MCP servers are (a preset save's address). The one
26
+ * place a key read from the environment is ever sent. */
27
+ export declare const COMPOSIO_ORIGIN = "https://backend.composio.dev";
20
28
  /** What a delete does at Composio beyond the MCP server: what it removes, in order (the accounts before the auth config
21
29
  * they are under), and what it keeps, each with whose it stays (`by`: the saved server that uses it too; none: this
22
30
  * server didn't make it). */
@@ -52,6 +60,23 @@ export declare const composioPerRun: (row: {
52
60
  * saved before over this row (`was`) or of another saved server (`others`) says was made here stays made here; and the
53
61
  * accounts the server saved before had made, under the same auth config and user, stay its own. */
54
62
  export declare function madeToWrite(found: ComposioMade, was: ComposioMade | undefined, others: readonly ComposioMade[]): ComposioMade;
63
+ /** The value of `name`, a server's key variable (ComposioMade.key_env), as this process (the server, or a runner) was
64
+ * handed it at its start: over the launcher's pipe, so its environment never holds it (secrets.ts secret; the launcher
65
+ * names it among its secrets). Trimmed; none when unset, blank or longer than any key. Read at each use, never kept. */
66
+ export declare function composioKeyFromEnv(name?: typeof COMPOSIO_KEY_ENV): string | undefined;
67
+ /** Why the server `server`, which reads its key from `name`, can't be used now: the variable is unset. */
68
+ export declare const composioKeyUnset: (server: string, name?: string) => string;
69
+ /** The key the server `server` (its address `url`) reads from `name`, its record's key_env, for a request to that address:
70
+ * the variable's value as this process was started with it (composioKeyFromEnv), only while the address is on Composio's origin (`origin`, COMPOSIO_ORIGIN; a test's fake
71
+ * through the server's and runner's seam). Otherwise why not, in words, and the caller sends nothing: `not_allowed`, an
72
+ * address no preset save writes (a row written by hand); `missing`, the variable unset. Every read of such a key for a
73
+ * request to the server's address goes through here: a save's and a refresh's listing, a run's start, a claim. */
74
+ export declare function composioEnvKey(server: string, url: string, name: typeof COMPOSIO_KEY_ENV, origin?: string): {
75
+ key: string;
76
+ } | {
77
+ refused: string;
78
+ reason: "not_allowed" | "missing";
79
+ };
55
80
  /** The records of the other saved servers (`others`, by name) that say they made the auth config `id`, each as it is to
56
81
  * be written once the owner named that config in a save: made by none of them, so none of their deletes removes it. */
57
82
  export declare function releasedOf(id: string, others: readonly (readonly [string, ComposioMade, ...unknown[]])[]): [string, ComposioMade][];
@@ -9,7 +9,14 @@
9
9
  // same with what the record it replaces made that the new one no longer stands on (droppedOf). An auth config the owner
10
10
  // names in a save (auth_config_id) is the owner's from that save on, whoever made it: the record written says it was not
11
11
  // made here, and every other record's claim to have made it is let go (releasedOf), so no delete or save removes it.
12
+ import { secret } from "./secrets.js";
12
13
  import { isObject } from "./validate.js";
14
+ /** The one variable a Composio save may name for its key (`api_key_env`). Composio's host is fixed in code, so no other
15
+ * secret of the server's environment is ever sent there. */
16
+ export const COMPOSIO_KEY_ENV = "COMPOSIO_API_KEY";
17
+ /** Composio's origin: its API's base (composio-preset.ts) and where its MCP servers are (a preset save's address). The one
18
+ * place a key read from the environment is ever sent. */
19
+ export const COMPOSIO_ORIGIN = "https://backend.composio.dev";
13
20
  /** The store.settings key a server's record lives under. */
14
21
  export const composioMadeKey = (name) => `mcp.composio/${name}`;
15
22
  /** The settings value a record is stored as, bound to the server row it was written for. */
@@ -25,7 +32,7 @@ export function recordedMade(value, createdAt) {
25
32
  const accounts = value.accounts.map(thingOf);
26
33
  if (config === undefined || accounts.some((account) => !account))
27
34
  return undefined;
28
- return { user: value.user, auth_config: config, accounts: accounts, ...(value.per_run === true ? { per_run: true } : {}) };
35
+ return { user: value.user, auth_config: config, accounts: accounts, ...(value.per_run === true ? { per_run: true } : {}), ...(value.key_env === COMPOSIO_KEY_ENV ? { key_env: COMPOSIO_KEY_ENV } : {}) };
29
36
  }
30
37
  /** Whether the saved server `row` is a per-run Composio server: auth headers (the install's sealed key) and its own
31
38
  * record (`recorded`, read at composioMadeKey) saying per_run. Its runs call it as the Composio user and account each
@@ -44,7 +51,37 @@ export function madeToWrite(found, was, others) {
44
51
  const config = found.auth_config && { id: found.auth_config.id, made: !found.auth_config.named && (found.auth_config.made || madeHere(found.auth_config.id)) };
45
52
  const accounts = found.accounts.map((a) => ({ id: a.id, made: a.made || madeHere(a.id) }));
46
53
  const kept = was && sharesAccounts(found, was) ? was.accounts.filter((a) => a.made && !accounts.some((b) => b.id === a.id)) : [];
47
- return { user: found.user, auth_config: config, accounts: [...accounts, ...kept], ...(found.per_run ? { per_run: true } : {}) };
54
+ return { user: found.user, auth_config: config, accounts: [...accounts, ...kept], ...(found.per_run ? { per_run: true } : {}), ...(found.key_env ? { key_env: found.key_env } : {}) };
55
+ }
56
+ /** The value of `name`, a server's key variable (ComposioMade.key_env), as this process (the server, or a runner) was
57
+ * handed it at its start: over the launcher's pipe, so its environment never holds it (secrets.ts secret; the launcher
58
+ * names it among its secrets). Trimmed; none when unset, blank or longer than any key. Read at each use, never kept. */
59
+ export function composioKeyFromEnv(name = COMPOSIO_KEY_ENV) {
60
+ const value = secret(name)?.trim();
61
+ return value && value.length <= 8192 ? value : undefined;
62
+ }
63
+ /** Why the server `server`, which reads its key from `name`, can't be used now: the variable is unset. */
64
+ export const composioKeyUnset = (server, name = COMPOSIO_KEY_ENV) => `The MCP server ${server} reads its Composio key from the environment variable ${name}, which is not set: set it where AgentRun runs, then try again.`;
65
+ /** Why the server `server`, which reads its key from `name`, is never sent it: its address is not on Composio's origin. */
66
+ const composioKeyOffOrigin = (server, url, name, origin) => `The MCP server ${server} reads its Composio key from the environment variable ${name}, and its address (${originOf(url)}) is not Composio's (${origin}): that key is only ever sent to Composio. Save it again with the Composio preset.`;
67
+ const originOf = (url) => {
68
+ try {
69
+ return new URL(url).origin;
70
+ }
71
+ catch {
72
+ return "not a URL";
73
+ }
74
+ };
75
+ /** The key the server `server` (its address `url`) reads from `name`, its record's key_env, for a request to that address:
76
+ * the variable's value as this process was started with it (composioKeyFromEnv), only while the address is on Composio's origin (`origin`, COMPOSIO_ORIGIN; a test's fake
77
+ * through the server's and runner's seam). Otherwise why not, in words, and the caller sends nothing: `not_allowed`, an
78
+ * address no preset save writes (a row written by hand); `missing`, the variable unset. Every read of such a key for a
79
+ * request to the server's address goes through here: a save's and a refresh's listing, a run's start, a claim. */
80
+ export function composioEnvKey(server, url, name, origin = COMPOSIO_ORIGIN) {
81
+ if (originOf(url) !== new URL(origin).origin)
82
+ return { refused: composioKeyOffOrigin(server, url, name, origin), reason: "not_allowed" };
83
+ const key = composioKeyFromEnv(name);
84
+ return key ? { key } : { refused: composioKeyUnset(server, name), reason: "missing" };
48
85
  }
49
86
  /** The records of the other saved servers (`others`, by name) that say they made the auth config `id`, each as it is to
50
87
  * be written once the owner named that config in a save: made by none of them, so none of their deletes removes it. */