@parcha/agentrun-serve 0.1.0-beta.40 → 0.1.0-beta.41

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 (126) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +78 -15
  3. package/dist/api-only.d.ts +3 -1
  4. package/dist/api-only.js +4 -2
  5. package/dist/api-token.d.ts +30 -0
  6. package/dist/api-token.js +89 -0
  7. package/dist/cli.js +19 -5
  8. package/dist/composio-made.d.ts +54 -0
  9. package/dist/composio-made.js +83 -0
  10. package/dist/composio-preset.d.ts +16 -8
  11. package/dist/composio-preset.js +106 -43
  12. package/dist/composio-triggers.d.ts +7 -2
  13. package/dist/composio-triggers.js +13 -7
  14. package/dist/computer-attach.d.ts +29 -11
  15. package/dist/computer-attach.js +141 -47
  16. package/dist/computer-keys.d.ts +4 -0
  17. package/dist/computer-keys.js +5 -0
  18. package/dist/computers.d.ts +11 -1
  19. package/dist/computers.js +21 -12
  20. package/dist/console/assets/{index-B8Zn1Iqn.css → index-C3gNPz58.css} +1 -1
  21. package/dist/console/assets/index-COGhx_2Z.js +711 -0
  22. package/dist/console/index.html +2 -2
  23. package/dist/decisions.js +9 -2
  24. package/dist/eval-feed.d.ts +26 -0
  25. package/dist/eval-feed.js +68 -0
  26. package/dist/eval-mailbox.d.ts +4 -1
  27. package/dist/eval-mailbox.js +11 -3
  28. package/dist/exa-keyless.d.ts +1 -1
  29. package/dist/exa-keyless.js +1 -1
  30. package/dist/feed/feed-faux.d.ts +62 -0
  31. package/dist/feed/feed-faux.js +123 -0
  32. package/dist/feed/fetch.d.ts +41 -0
  33. package/dist/feed/fetch.js +128 -0
  34. package/dist/feed/parse.d.ts +41 -0
  35. package/dist/feed/parse.js +300 -0
  36. package/dist/learn/check.d.ts +3 -1
  37. package/dist/learn/check.js +57 -2
  38. package/dist/learn/compile.js +1 -1
  39. package/dist/learned-nodes.d.ts +21 -4
  40. package/dist/learned-nodes.js +21 -8
  41. package/dist/learned-workflow.d.ts +3 -3
  42. package/dist/learned-workflow.js +14 -5
  43. package/dist/mcp-oauth.d.ts +15 -1
  44. package/dist/mcp-oauth.js +39 -5
  45. package/dist/mcp-pin-first.d.ts +4 -2
  46. package/dist/mcp-pin-first.js +4 -3
  47. package/dist/mcp-servers-store.d.ts +58 -5
  48. package/dist/mcp-servers-store.js +136 -17
  49. package/dist/mcp.d.ts +2 -2
  50. package/dist/mcp.js +2 -2
  51. package/dist/observation/http.d.ts +4 -1
  52. package/dist/observation/http.js +5 -4
  53. package/dist/openapi.js +46 -12
  54. package/dist/print.d.ts +6 -3
  55. package/dist/print.js +4 -2
  56. package/dist/run-labels.d.ts +23 -0
  57. package/dist/run-labels.js +79 -0
  58. package/dist/run-secrets.js +12 -4
  59. package/dist/runner/adapter-loop.js +91 -10
  60. package/dist/runner/adapter-run-spec.d.ts +4 -0
  61. package/dist/runner/adapter-run-spec.js +38 -31
  62. package/dist/runner/beside.d.ts +6 -3
  63. package/dist/runner/beside.js +9 -7
  64. package/dist/runner/cli-run-spec.js +32 -26
  65. package/dist/runner/conformance/harness.js +69 -14
  66. package/dist/runner/conformance/subject.d.ts +4 -1
  67. package/dist/runner/main.d.ts +1 -1
  68. package/dist/runner/main.js +2 -2
  69. package/dist/runner/mcp-claim.d.ts +3 -0
  70. package/dist/runner/mcp-claim.js +1 -1
  71. package/dist/runner/mcp-run.d.ts +4 -0
  72. package/dist/runner/mcp-run.js +5 -3
  73. package/dist/runner/model-route.d.ts +4 -2
  74. package/dist/runner/model-route.js +8 -8
  75. package/dist/runner/promotion.d.ts +8 -0
  76. package/dist/runner/promotion.js +43 -1
  77. package/dist/runner/workflow-first.d.ts +6 -5
  78. package/dist/runner/workflow-first.js +9 -7
  79. package/dist/runs-over-store.js +5 -2
  80. package/dist/sdk/runs.d.ts +7 -1
  81. package/dist/sdk/runs.js +19 -6
  82. package/dist/secret-cut.js +3 -1
  83. package/dist/secrets.js +3 -1
  84. package/dist/server.d.ts +27 -2
  85. package/dist/server.js +168 -50
  86. package/dist/store/dialect.d.ts +3 -0
  87. package/dist/store/dialect.js +1 -0
  88. package/dist/store/index.d.ts +1 -1
  89. package/dist/store/postgres/dialect.js +1 -0
  90. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  91. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  92. package/dist/store/schema.d.ts +9 -0
  93. package/dist/store/schema.js +26 -2
  94. package/dist/store/sqlite/connection.js +11 -3
  95. package/dist/store/sqlite/run-patch.d.ts +2 -1
  96. package/dist/store/sqlite/run-patch.js +3 -2
  97. package/dist/store/sqlite/store.js +64 -10
  98. package/dist/store/store.d.ts +38 -1
  99. package/dist/store-reads/journal.js +2 -1
  100. package/dist/store-reads/learning.js +6 -1
  101. package/dist/store-reads/runs.d.ts +4 -3
  102. package/dist/store-reads/runs.js +3 -2
  103. package/dist/store-view.js +4 -2
  104. package/dist/template-eval.d.ts +4 -0
  105. package/dist/template-eval.js +127 -50
  106. package/dist/templates.d.ts +10 -0
  107. package/dist/templates.js +75 -17
  108. package/dist/timeline/origin.d.ts +1 -1
  109. package/dist/timeline/origin.js +2 -2
  110. package/dist/trigger-adapter.d.ts +9 -4
  111. package/dist/trigger-adapters.js +2 -1
  112. package/dist/trigger-feed.d.ts +12 -0
  113. package/dist/trigger-feed.js +371 -0
  114. package/dist/triggers.d.ts +2 -1
  115. package/dist/triggers.js +23 -5
  116. package/dist/webhooks.js +9 -5
  117. package/dist/workspace/computer-deps.d.ts +5 -1
  118. package/dist/workspace/computer-deps.js +2 -2
  119. package/dist/workspace/index.d.ts +1 -0
  120. package/dist/workspace/index.js +2 -0
  121. package/dist/workspace/resolve-computer.d.ts +32 -3
  122. package/dist/workspace/resolve-computer.js +47 -9
  123. package/launcher/agentrun-serve +6 -1
  124. package/package.json +10 -9
  125. package/templates/README.md +27 -2
  126. package/dist/console/assets/index-Jbxjcmdp.js +0 -705
package/dist/openapi.js CHANGED
@@ -51,13 +51,29 @@ import { APPROVAL_ROW, ARGS_PREVIEW_BYTES, MAX_PIN_ARGS, MAX_PIN_CHOICES, PERMIS
51
51
  import { BROWSER_VENDOR_IDS, DECISION_PROVIDER_KEYS, KIND_KEYS, MAX_PIN_TEXT, permissionsOf, PICKABLE, PROVIDERS } from "./tool-plane.js";
52
52
  import { tableTools } from "./tool-list.js";
53
53
  import { SECRET_META_SCHEMA } from "./secret-writes.js";
54
+ import { LABEL_KEY, MAX_LABEL_VALUE, MAX_LABELS } from "./run-labels.js";
54
55
  import { BASH_POLICIES } from "./bash-read-only.js";
55
56
  // The modules that own the computer and Archil key writes: loading the document loads their secret-write predicates
56
57
  // (secret-writes.ts registerSecretWrite), so every operation the document marks has its predicate wherever it is read.
57
58
  import "./computers.js";
58
59
  import { ARCHIL_KEY_NAMES } from "./archil-routes.js";
59
60
  import { ATTACH_HEARTBEAT_MS, ATTACH_IDLE_MS, ATTACH_SUBPROTOCOL, MAX_LINE_BYTES, PAIRING_CODE_PATTERN, PAIRING_CODE_TTL_MS, PROTOCOL_VERSION } from "@parcha/agentrun-computer";
60
- import { PAIR_TRIES_PER_MINUTE, PAIRED_NAME_MAX } from "./computer-attach.js";
61
+ import { DAEMON_FETCHES_PER_MINUTE, PAIR_TRIES_PER_MINUTE, PAIRED_NAME_MAX } from "./computer-attach.js";
62
+ /** runlabels/1: a run's labels, given at its start and served on every read of it (run-labels.ts). */
63
+ const RUN_LABELS = {
64
+ type: "object",
65
+ maxProperties: MAX_LABELS,
66
+ propertyNames: { pattern: LABEL_KEY.source },
67
+ additionalProperties: { type: "string", minLength: 1, maxLength: MAX_LABEL_VALUE },
68
+ "x-agentrun-serve": "runlabels/1",
69
+ };
70
+ /** runlabels/1: GET /runs' and GET /agents/{agent_id}/runs' filter on a run's labels. */
71
+ const LABEL_PARAMETER = {
72
+ name: "label", in: "query", required: false,
73
+ description: "Only runs holding this label: `<key>:<value>`, split at the first `:` (a key holds none). Once per request; a second `label`, or one that does not read as a label, is 400.",
74
+ schema: { type: "string" },
75
+ "x-agentrun-serve": "runlabels/1",
76
+ };
61
77
  /** Why each capability this server turns off answers 501, by the route's capability. */
62
78
  export const UNSUPPORTED = {
63
79
  quotes: "This server has no billing, so it gives no quotes.",
@@ -972,7 +988,7 @@ const TRIGGER_FIELDS = closed({
972
988
  catchup_window_s: { type: "integer", minimum: 0, maximum: MAX_EVERY_S, description: `How late a missed time may still fire, once: of the times that came while the server was down (or its timer was late), the latest fires if it is this recent, under its own key, and the rest are one \`missed\` firing. 0: a missed time never fires. Default ${CATCHUP_WINDOW_S}.` },
973
989
  max_active_runs: { type: ["integer", "null"], minimum: 1, maximum: MAX_ACTIVE_RUNS, description: `For a \`start_run\` trigger of a pushed source (a webhook, with or without \`accept\`): each event starts its own run, never skipped behind the last, and this is the most of its runs active at once. A firing past it waits due and is tried again; past 20 due an event is 429 \`rate_limited\`. Null: a trigger with \`accept\` takes every run this server has room for, and one without keeps the overlap skip. A schedule or a \`message_run\` target is 422 with it set.` },
974
990
  failures_in_a_row: { type: "integer", minimum: 0, description: `Failed firings since the last that started a run; at ${FAILURES_TO_PAUSE} the trigger turns itself off (\`disabled\`). Turned on again, it counts from 0.` },
975
- disabled: { oneOf: [closed({ at: DATE_TIME, reason: { const: "auto_paused" } }), closed({ at: DATE_TIME, reason: { const: "source_unreadable" }, detail: { type: "string", description: "Why the source no longer reads." } }), closed({ at: DATE_TIME, reason: { const: "agent_archived" }, detail: { type: "string", description: "The agent it runs as, archived." } }), closed({ at: DATE_TIME, reason: { const: "connection_lost" }, detail: { type: "string", description: "Which connection went (GitHub disconnected here, or the App's installation deleted or suspended on GitHub)." } }), closed({ at: DATE_TIME, reason: { const: "sign_in_refused" }, detail: { type: "string", description: "What to fix: the account in Settings → Email." } }), { type: "null" }], description: `Why it is off, when the server turned it off: \`agent_archived\`, the agent it runs as was archived (turning it on is 409 agent_archived until the agent is unarchived); \`auto_paused\`, ${FAILURES_TO_PAUSE} failed firings in a row; \`connection_lost\`, the connection it needs went (GitHub disconnected here, or the App's installation deleted or suspended on GitHub); \`sign_in_refused\`, an email trigger's mail server refused the sign-in 3 times in a row (fix the account in Settings → Email, then turn it on); \`source_unreadable\`, its cron line or zone no longer reads here (a newer cron library or time zone data refuses it) or its every_s is out of range (a hand edit of its row), found at a start or when it came due, and only this trigger is turned off. Null once it is on again, which for \`source_unreadable\` takes a new source.` },
991
+ disabled: { oneOf: [closed({ at: DATE_TIME, reason: { const: "auto_paused" } }), closed({ at: DATE_TIME, reason: { const: "source_unreadable" }, detail: { type: "string", description: "Why the source no longer reads." } }), closed({ at: DATE_TIME, reason: { const: "agent_archived" }, detail: { type: "string", description: "The agent it runs as, archived." } }), closed({ at: DATE_TIME, reason: { const: "connection_lost" }, detail: { type: "string", description: "Which connection went (GitHub disconnected here, or the App's installation deleted or suspended on GitHub)." } }), closed({ at: DATE_TIME, reason: { const: "sign_in_refused" }, detail: { type: "string", description: "What to fix: the account in Settings → Email." } }), { type: "null" }], description: `Why it is off, when the server turned it off: \`agent_archived\`, the agent it runs as was archived (turning it on is 409 agent_archived until the agent is unarchived); \`auto_paused\`, ${FAILURES_TO_PAUSE} failed firings in a row; \`connection_lost\`, the connection it needs went (GitHub disconnected here, or the App's installation deleted or suspended on GitHub); \`sign_in_refused\`, an email trigger's mail server refused the sign-in 3 times in a row (fix the account in Settings → Email, then turn it on); \`source_unreadable\`, its cron line or zone no longer reads here (a newer cron library or time zone data refuses it) or its every_s is out of range (a hand edit of its row), found at a start or when it came due, and only this trigger is turned off, or every feed a feed trigger reads has stopped (a 410, or a 404 three checks running, each), which turning it on again reads from the start (edit its urls first). Null once it is on again, which for \`source_unreadable\` takes a new source.` },
976
992
  next_at: { type: ["string", "null"], format: "date-time", description: "When it fires next; null while it is off." },
977
993
  last_run_id: { type: ["string", "null"], description: "The run its last firing that started one started; while that run is active (working, or waiting on a person), each firing is skipped, unless its firings each start their own run (a webhook with `accept`, or a pushed trigger with `max_active_runs`). Null until one starts." },
978
994
  created_at: DATE_TIME,
@@ -980,7 +996,7 @@ const TRIGGER_FIELDS = closed({
980
996
  last_firing: { oneOf: [TRIGGER_FIRING, { type: "null" }] },
981
997
  }, "A trigger. A firing while its last run is active (working, or waiting on a person) is skipped, and recorded as a skipped firing with why: never queued, since a firing queued behind a run parked on a person would wait as long as the person does. A webhook trigger with `accept` is the exception: each event it takes starts its own run.");
982
998
  /** A trigger's view: its fields, all there, and `hook_url`, a pushed source's alone. */
983
- const TRIGGER = { ...TRIGGER_FIELDS, properties: { ...TRIGGER_FIELDS.properties, last_check: { oneOf: [closed({ at: DATE_TIME, ok: { type: "boolean" }, message: { type: "string" } }), { type: "null" }], description: "A polled source's (an email's) last check of its mailbox: when, whether it read, and in words (\"Read INBOX: 2 messages new.\", or why not: a server that couldn't be reached is said here and tried at the next time). Null before its first; absent for any other source.", "x-agentrun-serve": "email/1" }, hook_url: { type: "string", description: "Where its sender posts, for a pushed source alone (absent for a schedule): a webhook's own hook, `/v2/hooks/{id}`, at this server's public URL (AGENTRUN_PUBLIC_URL) when it has one, else the path." } } };
999
+ const TRIGGER = { ...TRIGGER_FIELDS, properties: { ...TRIGGER_FIELDS.properties, last_check: { oneOf: [closed({ at: DATE_TIME, ok: { type: "boolean" }, message: { type: "string" } }), { type: "null" }], description: "A polled source's (an email's or a feed's) last check of its mailbox or its feeds: when, whether it read, and in words (\"Read INBOX: 2 messages new.\", \"Read 2 feeds: 1 new.\", or why not: a server that couldn't be reached is said here and tried at the next time). Null before its first; absent for any other source.", "x-agentrun-serve": "email/1" }, hook_url: { type: "string", description: "Where its sender posts, for a pushed source alone (absent for a schedule): a webhook's own hook, `/v2/hooks/{id}`, at this server's public URL (AGENTRUN_PUBLIC_URL) when it has one, else the path." } } };
984
1000
  const TRIGGER_WRITE = {
985
1001
  name: { type: "string", minLength: 1, maxLength: 200, description: "Default the trigger's id." },
986
1002
  enabled: { type: "boolean", default: true, description: "Off, it fires nothing; on again, it goes on from now: the time it was off is skipped, never caught up." },
@@ -1713,6 +1729,7 @@ const EXTENSIONS = {
1713
1729
  { name: "revision", in: "query", required: false, description: "Only runs of this revision.", schema: { type: "string" } },
1714
1730
  { name: "status", in: "query", required: false, description: "Only runs with this status.", schema: ref("schemas/RunStatus") },
1715
1731
  { name: "archived", in: "query", required: false, description: "true lists only archived runs; false, the default, the others.", schema: { type: "boolean" } },
1732
+ LABEL_PARAMETER,
1716
1733
  ],
1717
1734
  responses: { "200": json(ref("schemas/RunList"), "One page of runs, newest first."), ...errors(400, 401, 429, 500) },
1718
1735
  },
@@ -1980,11 +1997,21 @@ const EXTENSIONS = {
1980
1997
  "/computers/attach": {
1981
1998
  get: {
1982
1999
  operationId: "attachComputer", tags: ["local"], summary: "The attach socket: a paired computer's driver dials it (a WebSocket)",
1983
- description: `A WebSocket (spec/computer/attach.md). The driver dials it with \`Authorization: Bearer <its token>\` (POST /computers/pair) and the subprotocol \`${ATTACH_SUBPROTOCOL}\`. A token no paired computer has (unknown, or its computer removed) is 401 before the upgrade; another subprotocol is 426. Frames are text, one JSON-RPC message each, at most ${MAX_LINE_BYTES} bytes (a bigger one closes the socket with 1009, a binary frame with 1003). The server is the caller: it sends hello, and the computer is attached while its hello is what it paired as (else closed with 4400, or 4426 for another protocol version); then the server sends a run's calls. Each side pings every ${ATTACH_HEARTBEAT_MS / 1000} s, and one that hears nothing for ${ATTACH_IDLE_MS / 1000} s closes with 4408. The same computer dialing again replaces its older socket (4409); removing it closes the socket with 4401. A request with no upgrade is 400. One server process holds the socket, so a run uses a paired computer only on a runner in that process (the start's runner beside the server).`,
2000
+ description: `A WebSocket (spec/computer/attach.md). The driver dials it with \`Authorization: Bearer <its token>\` (POST /computers/pair) and the subprotocol \`${ATTACH_SUBPROTOCOL}\`. A hosted machine of a dial provider dials it the same way with the token its create minted (GET /computers/daemon), and its socket stands for that create's machine, whose hello must say the kind, os and arch it was made as (else 4400). A token no paired computer or hosted machine has good (unknown, its computer removed, its machine deleted or past its backstop) is 401 before the upgrade; another subprotocol is 426. Frames are text, one JSON-RPC message each, at most ${MAX_LINE_BYTES} bytes (a bigger one closes the socket with 1009, a binary frame with 1003). The server is the caller: it sends hello, and the computer is attached while its hello is what it paired as (else closed with 4400, or 4426 for another protocol version); then the server sends a run's calls. Each side pings every ${ATTACH_HEARTBEAT_MS / 1000} s, and one that hears nothing for ${ATTACH_IDLE_MS / 1000} s closes with 4408. The same computer dialing again replaces its older socket (4409); removing it closes the socket with 4401. A request with no upgrade is 400. One server process holds the socket, so a run uses a paired computer only on a runner in that process (the start's runner beside the server).`,
1984
2001
  responses: { "101": { description: "Switching to the attach WebSocket." }, ...errors(400, 401, 500) },
1985
2002
  ...ATTACH_MARK,
1986
2003
  },
1987
2004
  },
2005
+ "/computers/daemon": {
2006
+ get: {
2007
+ operationId: "getComputerDaemon", tags: ["local"], summary: "This server's computerd build, for a hosted machine that dials it (its minted token)",
2008
+ description: `A hosted machine of a provider whose host has no exec (a dial provider's) fetches its daemon here as it boots, with \`Authorization: Bearer <its token>\`: the token the machine's create minted, which its env holds (AGENTRUN_ATTACH_TOKEN). The answer is this server's own computerd build for \`arch\`, the same bytes a hosted provider uploads, whose SHA-256 the create put in the machine's env (AGENTRUN_DAEMON_SHA256) for the machine to check before it runs it. A token no machine has good (unknown, revoked at the machine's delete, or past its backstop) is 401; each machine's token gets ${DAEMON_FETCHES_PER_MINUTE} fetches a minute (429 past them, with Retry-After); an arch other than amd64 or arm64 is 422. The owner's token and session are not a machine's token: 401.`,
2009
+ security: [],
2010
+ parameters: [{ name: "arch", in: "query", required: true, description: "The machine's architecture.", schema: { type: "string", enum: ["amd64", "arm64"] } }],
2011
+ responses: { "200": { description: "The daemon's bytes.", content: { "application/octet-stream": { schema: { type: "string", contentMediaType: "application/octet-stream" } } } }, ...errors(401, 422, 429, 500, 503) },
2012
+ ...ATTACH_MARK,
2013
+ },
2014
+ },
1988
2015
  "/computers/{computer_id}": {
1989
2016
  delete: {
1990
2017
  operationId: "deleteComputer", tags: ["local"], summary: "Remove a paired computer: its token ends and its socket closes",
@@ -2206,19 +2233,19 @@ const EXTENSIONS = {
2206
2233
  },
2207
2234
  put: {
2208
2235
  operationId: "saveMcpServer", tags: ["local"], summary: "Preview a remote MCP server, then save it with the tools listed and its credential sealed",
2209
- description: `The credential is sealed under the server's seal key, bound to the server's name and its URL's origin, and kept in the data directory as ciphertext alone. 403 forbidden to the API token for a save that sends a credential's value, or that would drop or change the credential the server holds (another \`auth.type\`, or none): the owner's signed-in session alone. 412 precondition_failed when a save that sends a new credential, or none, finds the server's credential changed while it listed its tools (another save, a sign-in or a removal landed): nothing is written over it. A body with no credential keeps the sealed one while the type and the URL's origin stay the same; else it is 422. A body with no \`prices\` keeps the saved ones for the tools still listed at the same URL, so a save from any client never leaves a paid tool unmetered; \`prices: {}\` clears them. 422 too for a bad name, URL or auth, or a price that is not a finite number 0 or more or names a tool the server does not list. ${MCP_CONNECTS} Nothing is saved unless the listing succeeds.`,
2236
+ description: `The credential is sealed under the server's seal key, bound to the server's name and its URL's origin, and kept in the data directory as ciphertext alone. 403 forbidden to the API token for a save that sends a credential's value, or that would drop or change the credential the server holds (another \`auth.type\`, or none): the owner's signed-in session alone. 412 precondition_failed when a save that sends a new credential, or none, finds the server's credential changed while it listed its tools (another save, a sign-in or a removal landed), or a save that keeps it finds the server at another address or holding another kind of credential by then (a Composio save over it moved it): nothing is written over it. A body with no credential keeps the sealed one while the type and the URL's origin stay the same; else it is 422. A body with no \`prices\` keeps the saved ones for the tools still listed at the same URL, so a save from any client never leaves a paid tool unmetered; \`prices: {}\` clears them. 422 too for a bad name, URL or auth, or a price that is not a finite number 0 or more or names a tool the server does not list. ${MCP_CONNECTS} Nothing is saved unless the listing succeeds. A save that moves a server the Composio preset made to another address makes it another service's server, and removes in the owner's Composio account what the preset made for it, as its delete does (the MCP server, then the connected account its connect link started and the auth config it made, unless another saved server uses them), with the key it was saved with, and answers \`composio\` saying so; 409 composio_in_use, naming them in \`details.triggers\`, while Composio triggers use it: delete them first. A save of a server the preset made lists its tools at once, then writes and cleans up one at a time with the preset's saves and the MCP servers' deletes, in its Composio project's turn.`,
2210
2237
  parameters: [MCP_NAME],
2211
2238
  requestBody: { required: true, content: { "application/json": { schema: { type: "object", additionalProperties: false, required: ["url"], properties: { url: MCP_URL, auth: MCP_AUTH, prices: MCP_PRICES, ...MCP_TOOLKIT_BODY } } } } },
2212
- responses: { "200": json(MCP_SERVER_VIEW, "The server, as saved."), ...errors(400, 401, 403, 409, 412, 415, 422, 429, 500), ...MCP_FAILED },
2239
+ responses: { "200": json({ ...MCP_SERVER_VIEW, properties: { ...MCP_SERVER_VIEW.properties, composio: closed({ removed: { type: "boolean", description: "Nothing the save was to remove at Composio is left there." }, note: { type: "string", description: "What it removed at Composio, what it kept and why, and what is left, with the dashboard's address to remove that by hand." } }, "Present when the save moved a server the Composio preset made off Composio: what became of what the preset made there.") } }, "The server, as saved."), ...errors(400, 401, 403, 409, 412, 415, 422, 429, 500), ...MCP_FAILED },
2213
2240
  "x-agentrun-serve": "mcpservers/1",
2214
2241
  },
2215
2242
  delete: {
2216
2243
  operationId: "deleteMcpServer", tags: ["local"], summary: "Forget a saved MCP server and its credential",
2217
- description: "409 composio_in_use, naming them in `details.triggers`, for a Composio server that Composio triggers still use: delete them first. A server the Composio preset made also has its MCP server deleted in the owner's Composio account, with the saved key, after the row is removed: the row is already gone while that delete waits on Composio. Composio's 404 means it is already gone; when Composio refuses or does not answer, or the saved key does not open, the answer is 200 with `composio.removed: false` and a note to remove it there. 403 forbidden to the API token when the server holds a credential: removing it drops a secret, the owner's signed-in session's alone. A server saved with none is the token's to remove. 412 precondition_failed when the server's credential changed between that check and the removal (a save or a sign-in landed): nothing is removed, and nothing is sent to Composio.",
2244
+ description: "409 composio_in_use, naming them in `details.triggers`, for a Composio server that Composio triggers still use: delete them first. A server the Composio preset made also has its MCP server deleted in the owner's Composio account, with the saved key, after the row is removed: the row is already gone while that delete waits on Composio. So does what its save made for it there that no other saved server uses: the connected account its connect link started (the link with it), and the auth config it made. What another saved server uses is kept, and goes with the last of them; what the save found there already (an auth config or an account the owner had) is never deleted. A preset's delete answers 200 with `composio`: `removed` true when nothing it was to remove is left, and `note`, what it removed, kept (and why) and left, in words. Composio's 404 means that one is already gone; when Composio refuses or does not answer, or the saved key does not open, `removed` is false and the note names what is left, to remove there. 403 forbidden to the API token when the server holds a credential: removing it drops a secret, the owner's signed-in session's alone. A server saved with none is the token's to remove. 412 precondition_failed when the server's credential changed between that check and the removal (a save or a sign-in landed): nothing is removed, and nothing is sent to Composio.",
2218
2245
  parameters: [MCP_NAME],
2219
2246
  responses: {
2220
- "204": { description: "Forgotten (and, for a Composio preset server, its Composio MCP server deleted, or already gone there)." },
2221
- "200": json(closed({ deleted: { type: "boolean", enum: [true] }, composio: closed({ removed: { type: "boolean", enum: [false] }, note: { type: "string", description: "What to do by hand: remove the server in Composio yourself, with the dashboard's address." } }) }), "Forgotten here, but the Composio MCP server a preset made could not be deleted (Composio refused or did not answer): it stays in the owner's Composio account until removed there. The row is gone either way."),
2247
+ "204": { description: "Forgotten: a server the Composio preset did not make." },
2248
+ "200": json(closed({ deleted: { type: "boolean", enum: [true] }, composio: closed({ removed: { type: "boolean", description: "Nothing the delete was to remove at Composio is left there." }, note: { type: "string", description: "What it removed at Composio, what it kept and why, and what is left, with the dashboard's address to remove that by hand." } }) }), "Forgotten here, a Composio preset server: what its delete did in the owner's Composio account. The row is gone either way."),
2222
2249
  ...errors(401, 403, 404, 409, 412, 429, 500),
2223
2250
  },
2224
2251
  "x-agentrun-serve": "mcpservers/1",
@@ -2245,10 +2272,10 @@ const EXTENSIONS = {
2245
2272
  "/settings/mcp-servers/{name}/composio": {
2246
2273
  put: {
2247
2274
  operationId: "saveComposioServer", tags: ["local"], summary: "Have Composio make a managed MCP server for a toolkit's chosen actions, and save it as an MCP server",
2248
- description: COMPOSIO_NOTE + " Makes (or reuses) a Composio-managed auth config for a toolkit that needs the person's account, makes a Composio MCP server allowing only `tools`, asks for its address (the helper actions that connect an account left off; its path ends in `/mcp`), and saves that address as the MCP server `name` through the one MCP save: the key is sealed as an `x-api-key` header, the tools listed, none priced (\"not metered\"). When the toolkit needs an account and `user_id` has no active one, `connect_url` is Composio's page to connect it; nothing here signs in. `user_id` defaults to `agentrun`. 422 for a bad name, key, toolkit or tools, a key or request Composio refuses (each says the step); 424 `upstream_failed` when Composio fails or the saved address does not list its tools. Nothing is saved unless every step succeeds. The owner's signed-in session alone: 403 forbidden to the API token.",
2275
+ description: COMPOSIO_NOTE + " Makes (or reuses) a Composio-managed auth config for a toolkit that needs the person's account, makes a Composio MCP server allowing only `tools`, asks for its address (the helper actions that connect an account left off; its path ends in `/mcp`), and saves that address as the MCP server `name` through the one MCP save: the key is sealed as an `x-api-key` header, the tools listed, none priced (\"not metered\"). When the toolkit needs an account and `user_id` has no active one, `connect_url` is Composio's page to connect it; nothing here signs in. `user_id` defaults to `agentrun`. 422 for a bad name, key, toolkit or tools, a key or request Composio refuses (each says the step); 424 `upstream_failed` when Composio fails or the saved address does not list its tools. Nothing is saved unless every step succeeds, and a save that fails removes in Composio what it made there (the MCP server, the connected account its connect link started, the auth config it made), never what it found; when Composio refuses that too, its error's message names what is left, with the dashboard's address (and a 422 on a field says it in \`details.composio\` as well). A save over a server the preset made removes, once it is saved, the MCP server that server's earlier save made, and what that save made and this one no longer stands on (the account of another `user_id`, the auth config of another toolkit), with the key it was made with, unless another saved server uses it (then it is that one's), and answers `composio` saying so, as a delete does. A save over a server as another `user_id` or auth config is 409 composio_in_use, naming them in `details.triggers`, while Composio triggers use it: delete them first; a save that leaves what they stand on alone goes through. Preset saves, the saves of the servers they made, and deletes of MCP servers run one at a time. The owner's signed-in session alone: 403 forbidden to the API token.",
2249
2276
  parameters: [MCP_NAME],
2250
2277
  requestBody: { required: true, content: { "application/json": { schema: closedWith({ api_key: COMPOSIO_KEY, toolkit: COMPOSIO_TOOLKIT, tools: { type: "array", minItems: 1, maxItems: 500, items: { type: "string", minLength: 1 }, description: "The slugs of the actions to grant, from the listing." } }, { user_id: { type: "string", pattern: "^[A-Za-z0-9._@-]{1,128}$", description: "The Composio user the actions run as; default `agentrun`." } }) } } },
2251
- responses: { "200": json(closedWith({ server: MCP_SERVER_VIEW }, { connect_url: { type: "string", format: "uri", description: "Present when the toolkit needs an account and the user has no active one: Composio's page to connect it." }, not_served: { type: "array", items: { type: "string" }, description: "Present when Composio's server leaves out some of `tools` (it can, for an action it was allowed): the slugs it doesn't list, which a run can't call." } }), "The server as saved, and where to connect the account when it must be."), ...errors(400, 401, 403, 409, 415, 422, 429, 500), ...MCP_FAILED },
2278
+ responses: { "200": json(closedWith({ server: MCP_SERVER_VIEW }, { connect_url: { type: "string", format: "uri", description: "Present when the toolkit needs an account and the user has no active one: Composio's page to connect it." }, not_served: { type: "array", items: { type: "string" }, description: "Present when Composio's server leaves out some of `tools` (it can, for an action it was allowed): the slugs it doesn't list, which a run can't call." }, composio: closed({ removed: { type: "boolean", description: "Nothing the save was to remove at Composio is left there." }, note: { type: "string", description: "What it removed at Composio, what it kept and why, and what is left, with the dashboard's address to remove that by hand." } }, "Present when the save was over a server whose earlier save made something at Composio that this one no longer stands on: what became of it.") }), "The server as saved, and where to connect the account when it must be."), ...errors(400, 401, 403, 409, 415, 422, 429, 500), ...MCP_FAILED },
2252
2279
  "x-agentrun-serve": "mcpservers/1",
2253
2280
  },
2254
2281
  },
@@ -2683,6 +2710,7 @@ const RUN_FIELDS = {
2683
2710
  revision: { type: "string", description: "The id of the agent revision the run runs.", "x-agentrun-serve": "serve/1" },
2684
2711
  kind: { enum: ["agentic", "workflow"], description: "The revision's kind: an agentic run, or a workflow run.", "x-agentrun-serve": "serve/1" },
2685
2712
  archived_at: { type: ["string", "null"], description: "When the run, or its agent, was archived, while it is; else null.", "x-agentrun-serve": "serve/1" },
2713
+ labels: { ...RUN_LABELS, description: "The labels the run was started with (RunCreate.labels), as given; `{}` when none. Always sent by a server that keeps labels (`runlabels/1`); absent from an earlier one's answer." },
2686
2714
  };
2687
2715
  /** What a run waits on, one field for every kind, told apart by `kind`: a question it asked a person, or a tool call
2688
2716
  * that waits for approval. */
@@ -2823,6 +2851,7 @@ const FIELD_EXTENSIONS = {
2823
2851
  },
2824
2852
  RunCreate: {
2825
2853
  mcp_auth: { ...MCP_RUN_AUTH, description: `${MCP_RUN_AUTH.description} Each names a saved MCP server whose \`auth.type\` is per_run (422 at \`mcp_auth.<server>\` otherwise, no run made). Sealed into the run's launch for its life, read at each claim, and erased by the write that ends it; never in its saved body, its timeline, its view or an Idempotency-Key's fingerprint (a retry with a new credential answers the first request's run).` },
2854
+ labels: { ...RUN_LABELS, description: `The caller's own labels for the run: at most ${MAX_LABELS} keys, each 1 to 63 letters, digits, \`.\`, \`_\`, \`-\` or \`/\` starting with a letter or a digit; each value text of 1 to ${MAX_LABEL_VALUE} characters with no control character. Kept on the run as given, served on every read of it (\`labels\` on Run and RunSummary) and matched by GET /runs' \`label\`; set once, at the start. The server reads nothing else from them: put no secret in one. Another shape is 422 under \`labels\` or \`labels.<key>\`. Absent: none.` },
2826
2855
  workflow_first: {
2827
2856
  type: "boolean",
2828
2857
  description: "Whether a run of an agent that learns may start on one of its learned workflows. On (absent or true), a run whose input fits exactly one active learned workflow (its input schema has a required field, and the run's input passes it) runs that workflow first, with no turn of the agent's model: its answer is the run's answer, and if it hands the job back (it escalates, a step fails), the same run goes on with the agent, given what the workflow found. The run keeps which path it took: `workflow`, `handed_back` or `agent`. false: the agent takes the run from its first turn.",
@@ -3548,6 +3577,11 @@ export function openapiDocument(capabilityOf, adapters = TRIGGER_ADAPTERS) {
3548
3577
  listAgents.parameters = [...listAgents.parameters, { name: "archived", in: "query", required: false, description: "true lists only archived agents; false, the default, the others.", schema: { type: "boolean" } }];
3549
3578
  listAgents["x-agentrun-serve-changed"] = { archived: "archivedparam/1" };
3550
3579
  changed.push("GET /agents");
3580
+ // GET /agents/{agent_id}/runs takes GET /runs' `label` filter too (server.ts runsPage, shared by both routes).
3581
+ const listAgentRuns = doc.paths["/agents/{agent_id}/runs"].get;
3582
+ listAgentRuns.parameters = [...listAgentRuns.parameters, LABEL_PARAMETER];
3583
+ listAgentRuns["x-agentrun-serve-changed"] = { ...listAgentRuns["x-agentrun-serve-changed"], label: "runlabels/1" };
3584
+ changed.push("GET /agents/{agent_id}/runs");
3551
3585
  // GET /agents/{agent_id} always sends the agent's `tools` (server.ts getAgent; [] before it has a revision), which the
3552
3586
  // agent in a list, a create or a save does not: its 200 is the contract's Agent with `tools` required.
3553
3587
  const getAgent = doc.paths["/agents/{agent_id}"].get;
@@ -3716,7 +3750,7 @@ export function openapiDocument(capabilityOf, adapters = TRIGGER_ADAPTERS) {
3716
3750
  }, {
3717
3751
  oauth: { ...MCP_SIGN_IN_CLIENT, description: "With `auth: oauth`, when the sign-in's discovery could be made." },
3718
3752
  }),
3719
- input_invalid: { type: "object", additionalProperties: false, properties: { oauth: { ...MCP_SIGN_IN_CLIENT, description: "With field `client_id`, reason `registration_unavailable` (POST .../oauth/start): as a preview's `details.oauth`, `registration` false." } } },
3753
+ input_invalid: { type: "object", additionalProperties: false, properties: { oauth: { ...MCP_SIGN_IN_CLIENT, description: "With field `client_id`, reason `registration_unavailable` (POST .../oauth/start): as a preview's `details.oauth`, `registration` false." }, composio: { type: "string", description: "A Composio preset save refused on a field (PUT .../composio) whose removal of what it made there Composio refused too: what is left there and where to remove it, in words, as its message ends." } } },
3720
3754
  upstream_failed: { type: "object", additionalProperties: false, properties: { status: { type: "integer", description: "The MCP server's HTTP status, when it answered one." } } },
3721
3755
  sign_in_held: { type: "object", additionalProperties: false, minProperties: 1, maxProperties: 1, properties: { held_by: { type: "string", description: "The run that holds the sign-in's save lease." }, handed_to: { type: "string", description: "A run still going that was handed the sign-in (signins/1)." } } },
3722
3756
  wrong_origin: closed({ open: { type: "string", format: "uri", description: "Where to open the console to sign in: the address the authorization server sends the browser back to." } }),
package/dist/print.d.ts CHANGED
@@ -1,9 +1,11 @@
1
- /** Where the token came from: made at this start (printed this once), kept in DIR/.token, or the environment's. */
2
- export type TokenSource = "made" | "file" | "env";
1
+ /** Where the token came from: made at this start (printed this once), kept in DIR/.token, the environment's
2
+ * (AGENTRUN_TOKEN), or the token list's alone (AGENTRUN_TOKENS). */
3
+ export type TokenSource = "made" | "file" | "env" | "list";
3
4
  /** The banner's lines. The token is printed only when this start made it; else where it is. `publicUrl` is the address
4
5
  * people open (AGENTRUN_PUBLIC_URL), which the base URL and the link use. With `accounts` the page is the owner's
5
6
  * password, so its link holds nothing; with none, the link holds this start's launch code (`launchCode`), never the
6
- * token. `apiOnly`: no console to open, so the line says what is served instead. `boxes`: which boxes are ready, in
7
+ * token. `tokenIds`: the ids of the tokens the server takes (api-token.ts), named when there is more than one or a list
8
+ * gave them, never a secret. `apiOnly`: no console to open, so the line says what is served instead. `boxes`: which boxes are ready, in
7
9
  * words (Serve's boxesLine), last. */
8
10
  export declare function banner(o: {
9
11
  url: string;
@@ -11,6 +13,7 @@ export declare function banner(o: {
11
13
  data: string;
12
14
  token: string;
13
15
  source: TokenSource;
16
+ tokenIds?: readonly string[];
14
17
  listen?: string;
15
18
  publicUrl?: string;
16
19
  accounts?: boolean;
package/dist/print.js CHANGED
@@ -4,15 +4,17 @@ import { join } from "node:path";
4
4
  /** The banner's lines. The token is printed only when this start made it; else where it is. `publicUrl` is the address
5
5
  * people open (AGENTRUN_PUBLIC_URL), which the base URL and the link use. With `accounts` the page is the owner's
6
6
  * password, so its link holds nothing; with none, the link holds this start's launch code (`launchCode`), never the
7
- * token. `apiOnly`: no console to open, so the line says what is served instead. `boxes`: which boxes are ready, in
7
+ * token. `tokenIds`: the ids of the tokens the server takes (api-token.ts), named when there is more than one or a list
8
+ * gave them, never a secret. `apiOnly`: no console to open, so the line says what is served instead. `boxes`: which boxes are ready, in
8
9
  * words (Serve's boxesLine), last. */
9
10
  export function banner(o) {
10
- const where = o.source === "env" ? "$AGENTRUN_TOKEN" : `<in ${join(o.data, ".token")}>`;
11
+ const where = o.source === "env" ? "$AGENTRUN_TOKEN" : o.source === "list" ? "<a secret in $AGENTRUN_TOKENS>" : `<in ${join(o.data, ".token")}>`;
11
12
  const key = o.source === "made" ? o.token : where;
12
13
  return [
13
14
  `agentrun-serve on ${o.baseUrl} (agent store in ${o.data}${o.listen ? `, listening on ${o.listen}` : ""})`,
14
15
  `AGENTRUN_BASE_URL=${o.publicUrl ? `${o.publicUrl}/v2` : o.baseUrl}`,
15
16
  `AGENTRUN_API_KEY=${key}`,
17
+ ...(o.tokenIds && (o.tokenIds.length > 1 || o.source === "list") ? [`API tokens taken (ids): ${o.tokenIds.join(", ")}`] : []),
16
18
  o.apiOnly
17
19
  ? "API only (AGENTRUN_API_ONLY=1): the run routes are served; the console, sign-in, setup, settings, MCP, triggers and hooks are refused."
18
20
  : o.accounts || o.launchCode === undefined ? `Open ${o.publicUrl ?? o.url}/` : `Open ${o.publicUrl ?? o.url}/?launch=${o.launchCode}`,
@@ -0,0 +1,23 @@
1
+ import { type InputIssue } from "./errors.js";
2
+ import type { RunLabels } from "./store/store.js";
3
+ /** At most this many labels on a run. */
4
+ export declare const MAX_LABELS = 16;
5
+ /** A label's key: 1 to 63 characters, letters, digits and `.`, `_`, `-`, `/`, starting with a letter or a digit. No `:`, so
6
+ * a filter's `<key>:<value>` splits at its first one. */
7
+ export declare const LABEL_KEY: RegExp;
8
+ /** A label's value: text of 1 to this many characters, counted as Unicode code points (as JSON Schema's maxLength counts
9
+ * them), never UTF-16 units: an emoji is one character. */
10
+ export declare const MAX_LABEL_VALUE = 256;
11
+ /** A UTF-16 surrogate standing alone, half of no character (in `u` mode a whole pair is one code point, so only a lone half
12
+ * matches). JSON.stringify keeps one as a `\ud800` escape that Postgres' json check takes but json_each_text cannot
13
+ * decode: kept on a run, it would fail every later label search that scans that run. */
14
+ export declare const LONE_SURROGATE: RegExp;
15
+ /** A create body's `labels`, field by field: an object of at most MAX_LABELS keys, each matching LABEL_KEY, each value text
16
+ * of 1 to MAX_LABEL_VALUE characters with no control character. Absent is none. */
17
+ export declare function labelsIssues(labels: unknown): InputIssue[];
18
+ /** A create body's labels, once labelsIssues found none: the map as given, or undefined when absent or empty. */
19
+ export declare function labelsOf(labels: unknown): RunLabels | undefined;
20
+ /** GET /runs' `label` parameter, `<key>:<value>` (split at the first `:`, which a key never holds): the label a run must
21
+ * hold. One per request: the document declares a single string, and a client generated from it sends one, so a second
22
+ * is 400 bad_request rather than read here and dropped by a client. 400 too for one that does not read as a label. */
23
+ export declare function labelFilter(given: readonly string[]): RunLabels | undefined;
@@ -0,0 +1,79 @@
1
+ // A run's labels: a small map of the caller's own strings, given at its start (POST /agents/{agent_id}/runs, POST /runs),
2
+ // kept on the run, served on every read of it, and filtered on by GET /runs (`label=<key>:<value>`, one per request: the
3
+ // OpenAPI document declares it a single string, which every generated client sends once). The server never reads
4
+ // them otherwise: they are the caller's way to find its runs again (its own ids for a run, a job, a tenant). They are no
5
+ // place for a secret: every read of the run serves them as given.
6
+ import { ApiError } from "./errors.js";
7
+ /** At most this many labels on a run. */
8
+ export const MAX_LABELS = 16;
9
+ /** A label's key: 1 to 63 characters, letters, digits and `.`, `_`, `-`, `/`, starting with a letter or a digit. No `:`, so
10
+ * a filter's `<key>:<value>` splits at its first one. */
11
+ export const LABEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,62}$/;
12
+ /** A label's value: text of 1 to this many characters, counted as Unicode code points (as JSON Schema's maxLength counts
13
+ * them), never UTF-16 units: an emoji is one character. */
14
+ export const MAX_LABEL_VALUE = 256;
15
+ /** No control character in a value: a label is shown as one line. */
16
+ const CONTROL = /[\u0000-\u001f\u007f]/;
17
+ /** A UTF-16 surrogate standing alone, half of no character (in `u` mode a whole pair is one code point, so only a lone half
18
+ * matches). JSON.stringify keeps one as a `\ud800` escape that Postgres' json check takes but json_each_text cannot
19
+ * decode: kept on a run, it would fail every later label search that scans that run. */
20
+ export const LONE_SURROGATE = /[\ud800-\udfff]/u;
21
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
22
+ /** Why a value is not a label's, or undefined when it is one. */
23
+ function valueProblem(value) {
24
+ if (typeof value !== "string")
25
+ return "is text";
26
+ const characters = [...value].length;
27
+ if (characters < 1 || characters > MAX_LABEL_VALUE)
28
+ return `is text of 1 to ${MAX_LABEL_VALUE} characters`;
29
+ if (CONTROL.test(value))
30
+ return "holds no control character (a newline, a tab, NUL)";
31
+ if (LONE_SURROGATE.test(value))
32
+ return "is whole Unicode characters (no lone UTF-16 surrogate)";
33
+ return undefined;
34
+ }
35
+ /** A create body's `labels`, field by field: an object of at most MAX_LABELS keys, each matching LABEL_KEY, each value text
36
+ * of 1 to MAX_LABEL_VALUE characters with no control character. Absent is none. */
37
+ export function labelsIssues(labels) {
38
+ if (labels === undefined)
39
+ return [];
40
+ if (!isObject(labels))
41
+ return [{ field: "labels", reason: "wrong_type", message: "labels is an object of text values: {\"<key>\": \"<value>\"}" }];
42
+ const issues = [];
43
+ const keys = Object.keys(labels);
44
+ if (keys.length > MAX_LABELS)
45
+ issues.push({ field: "labels", reason: "too_many", message: `labels holds at most ${MAX_LABELS} keys; it holds ${keys.length}.` });
46
+ for (const key of keys) {
47
+ if (!LABEL_KEY.test(key)) {
48
+ issues.push({ field: `labels.${key}`, reason: "bad_format", message: `A label's key is 1 to 63 letters, digits, '.', '_', '-' or '/', starting with a letter or a digit: ${JSON.stringify(key)} is not one.` });
49
+ continue;
50
+ }
51
+ const problem = valueProblem(labels[key]);
52
+ if (problem)
53
+ issues.push({ field: `labels.${key}`, reason: typeof labels[key] === "string" ? "bad_format" : "wrong_type", message: `labels.${key} ${problem}.` });
54
+ }
55
+ return issues;
56
+ }
57
+ /** A create body's labels, once labelsIssues found none: the map as given, or undefined when absent or empty. */
58
+ export function labelsOf(labels) {
59
+ if (!isObject(labels) || Object.keys(labels).length === 0)
60
+ return undefined;
61
+ return Object.fromEntries(Object.entries(labels).map(([key, value]) => [key, String(value)]));
62
+ }
63
+ /** GET /runs' `label` parameter, `<key>:<value>` (split at the first `:`, which a key never holds): the label a run must
64
+ * hold. One per request: the document declares a single string, and a client generated from it sends one, so a second
65
+ * is 400 bad_request rather than read here and dropped by a client. 400 too for one that does not read as a label. */
66
+ export function labelFilter(given) {
67
+ if (given.length === 0)
68
+ return undefined;
69
+ if (given.length > 1)
70
+ throw new ApiError("bad_request", "label is given once: one <key>:<value> per request");
71
+ const one = given[0];
72
+ const at = one.indexOf(":");
73
+ const key = at < 0 ? one : one.slice(0, at);
74
+ const value = at < 0 ? undefined : one.slice(at + 1);
75
+ if (!LABEL_KEY.test(key) || value === undefined || valueProblem(value) !== undefined) {
76
+ throw new ApiError("bad_request", `label is <key>:<value>, a label's key and its value (${JSON.stringify(one)} is not one)`);
77
+ }
78
+ return { [key]: value };
79
+ }
@@ -1,16 +1,24 @@
1
1
  import { harnessModelKeys } from "./adapters.js";
2
+ import { COMPUTER_KEY_NAMES } from "./computer-keys.js";
2
3
  import { BOX_KEYS } from "./place-offers.js";
3
4
  import { providersNamed } from "./decisions.js";
4
5
  import { harnessOfBody } from "./harness.js";
5
6
  import { harnessOf } from "./harness-table.js";
6
7
  import { GATEWAY_KEY_ENV, llmTiers, modelKeys, nodeTiers, PROVIDER_KEYS, workflowNodes } from "./model.js";
7
8
  import { DECISION_KEYS, SECRET_NAMES } from "./secrets.js";
8
- import { TOOL_KEYS, unlocksTool } from "./tool-keys.js";
9
+ import { TOOL_FIELDS, TOOL_KEYS, unlocksTool } from "./tool-keys.js";
9
10
  import { workflowTools } from "./tools.js";
11
+ import { ARCHIL_API_KEY_ENV } from "./workspace/archil-key.js";
12
+ /** The computer providers' account keys a run never gets: every computer key (computer-keys.ts COMPUTER_KEY_NAMES) but
13
+ * a tool key's field (Browserbase's and Kernel's, which a run's `browser` tool takes when its revision binds it). Only
14
+ * the server's and the runner's computer providers read one, at a claim or a Settings test. */
15
+ const COMPUTER_ACCOUNT_KEYS = COMPUTER_KEY_NAMES.filter((name) => !TOOL_FIELDS.includes(name));
10
16
  /** The server's own secrets, which a run never gets: the API token, by name or by value, the seal key the tool keys are
11
- * kept under (tool-keys.ts), the store's URL (it may hold the database's password), and the remote boxes' keys
12
- * (place-offers.ts BOX_KEYS), which only the server's computer providers use. */
13
- const SERVER_ONLY = new Set(["AGENTRUN_TOKEN", "AGENTRUN_API_KEY", "AGENTRUN_SEAL_KEY", "AGENTRUN_STORE_URL", ...BOX_KEYS]);
17
+ * kept under (tool-keys.ts), the store's URL (it may hold the database's password), the remote boxes' keys
18
+ * (place-offers.ts BOX_KEYS) and every other computer provider's account key, which only the server's and the runner's
19
+ * computer providers use, and the Archil account key (archil-key.ts), from which the claim mints each run's own mount
20
+ * credential. */
21
+ const SERVER_ONLY = new Set(["AGENTRUN_TOKEN", "AGENTRUN_TOKENS", "AGENTRUN_API_KEY", "AGENTRUN_SEAL_KEY", "AGENTRUN_STORE_URL", ...BOX_KEYS, ...COMPUTER_ACCOUNT_KEYS, ARCHIL_API_KEY_ENV]);
14
22
  /** The secrets a run may be handed: every one but the server's own and the decision keys, which go apart. */
15
23
  export const RUN_SECRETS = SECRET_NAMES.filter((name) => !SERVER_ONLY.has(name) && !DECISION_KEYS.includes(name));
16
24
  /** The fields a run gets only when its revision names what they unlock: a `tool` key's. Any other kind's (a model key's)
@@ -392,6 +392,20 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
392
392
  followUps.add(requestId);
393
393
  personWritten = true;
394
394
  }),
395
+ steered: (input, requestId, origin) => inTurn(async () => {
396
+ if (followUps.has(requestId))
397
+ return;
398
+ const entry = origin
399
+ ? { entry: { kind: KINDS.input, data: { origin, requestId, at: now() }, model: [{ role: "user", content: input, timestamp: now() }] } }
400
+ : { kind: KINDS.message, data: { role: "steer", text: input, requestId } };
401
+ if (turnsOpen === 0)
402
+ await startsTurn(entry);
403
+ else if ("entry" in entry)
404
+ await harness.commit((tx) => tx.appendEntry(root.id, entry.entry), context);
405
+ else
406
+ await append(entry.kind, entry.data);
407
+ followUps.add(requestId);
408
+ }),
395
409
  message: (input, origin) => inTurn(async () => {
396
410
  if (origin)
397
411
  await startsTurn({ entry: { kind: KINDS.input, data: { origin }, model: [{ role: "user", content: input, timestamp: now() }] } });
@@ -665,6 +679,22 @@ function adapterLoop(specOf, options, deps) {
665
679
  * end waits on each one's submission (turnOfRequest) before the run may end, so the run never reads completed with a
666
680
  * message it took still unanswered, and its session is never closed under that answer. */
667
681
  const steeredIn = [];
682
+ /** A CLI's steers (a harness whose record the loop keeps, and whose session steers: claude-agent), by request id: the
683
+ * model took it (its adapter's message_taken, `takenIds`), then its record entry, the commit its row is taken in
684
+ * (`recorded`). The record says where the model read it, after the tool calls in flight, never where it was queued. */
685
+ const cliSteers = new Map();
686
+ /** The submissions a CLI's adapter said its model took (message_taken), and who waits on one of them. */
687
+ const takenIds = new Set();
688
+ const takenWaiters = new Map();
689
+ const modelTook = (id) => takenIds.has(id) ? Promise.resolve() : new Promise((resolve) => takenWaiters.set(id, [...(takenWaiters.get(id) ?? []), resolve]));
690
+ const tookNow = (ids) => {
691
+ for (const id of ids) {
692
+ takenIds.add(id);
693
+ for (const resolve of takenWaiters.get(id) ?? [])
694
+ resolve();
695
+ takenWaiters.delete(id);
696
+ }
697
+ };
668
698
  /** Set once the claim's last turn has ended and nothing more is sent: a message after it waits for the run's end, as one
669
699
  * during the end-of-run turn does. */
670
700
  let turnsOver = false;
@@ -1125,15 +1155,19 @@ function adapterLoop(specOf, options, deps) {
1125
1155
  }
1126
1156
  // Who wrote it, when the person did not (a trigger's message): carried on its input, as the Timeline shows it.
1127
1157
  const origin = originOf(command.body?.origin);
1128
- if (!session.steer) {
1129
- // A harness that takes no message mid-turn: the API answered it `follow_up` (it waits for the turn's end), so it is
1130
- // the run's next turn, after any taken before it (afterTurn). Taken now as the dispatch takes a row it buffers: the
1131
- // store's take is the commit of its submission, once sent.
1158
+ // A harness that takes no message mid-turn, or a CLI's message that is no steer of the turn in flight (a trigger's that
1159
+ // answers nothing, or the person's answer to the question its last turn ended on, whose session is idle): the API
1160
+ // answered it `follow_up` (it waits for the turn's end), so it is the run's next turn, after any taken before it
1161
+ // (afterTurn). Taken now as the dispatch takes a row it buffers: the store's take is the commit of its submission, once
1162
+ // sent.
1163
+ if (!session.steer || (cliRecord && (followUp || askedLast))) {
1132
1164
  if (turnsOver)
1133
1165
  return { later: "the run has answered and is ending: the message waits for the run's end" };
1134
1166
  afterTurn.push({ commandId: command.id, text, requestId, ...(origin ? { origin } : {}) });
1135
1167
  return { taken: true };
1136
1168
  }
1169
+ if (cliRecord)
1170
+ return steerCli(session, cliRecord, gate, command.id, text, requestId, origin);
1137
1171
  // The claim's last turn has ended and nothing more is sent (turnsOver): a steer placed now would start a turn the run's
1138
1172
  // end then cuts, so it waits for the run's end, as a CLI's message does.
1139
1173
  if (turnsOver && !askedLast)
@@ -1166,6 +1200,50 @@ function adapterLoop(specOf, options, deps) {
1166
1200
  await taken.catch(() => { });
1167
1201
  return { taken: true };
1168
1202
  };
1203
+ /** A person's message steered into a CLI's turn in flight (claude-agent): its session places it (its harness sends it to the
1204
+ * CLI at once, which hands it to the model at its next step); once the model took it, the record's steer entry is written
1205
+ * and the row is taken in that commit (cliSteers). A runner lost before that leaves the row untaken, and the session holds
1206
+ * the steer under the row's request id: the next claim's steer() of the same row places nothing again, its resumed turn
1207
+ * carries the steer if the CLI never had it, and the record is written once. Neither lost nor sent twice. */
1208
+ const steerCli = async (theSession, theRecord, theGate, commandId, text, requestId, origin) => {
1209
+ if (turnsOver)
1210
+ return { later: "the run has answered and is ending: the message waits for the run's end" };
1211
+ const taken = theGate.expect(writesEntry(origin ? KINDS.input : KINDS.message, (data) => data.requestId === requestId), { take: [commandId] });
1212
+ taken.catch(() => undefined);
1213
+ // Waited on before it is placed: the model may take it before steer() resolves.
1214
+ const took = modelTook(requestId);
1215
+ try {
1216
+ await theSession.steer(text, requestId, "steer", origin ? { origin } : undefined);
1217
+ }
1218
+ catch (error) {
1219
+ if (theGate.sealed)
1220
+ return { later: "the run is parking: the steer waits for its resume" };
1221
+ return { refused: `the steer was not placed: ${error.message}` };
1222
+ }
1223
+ await specNow?.hooks?.afterSteerPlaced?.();
1224
+ const recorded = took.then(() => theRecord.steered(text, requestId, origin));
1225
+ recorded.catch(() => undefined);
1226
+ cliSteers.set(requestId, { text, ...(origin ? { origin } : {}), recorded });
1227
+ // Placed in the turn in flight: the turn's end waits for it to be answered (steeredIn), never ending the run first.
1228
+ steeredIn.push(requestId);
1229
+ return { taken: true };
1230
+ };
1231
+ /** The end of the turn that answers a CLI's steer (steerCli): the turn in flight, or the next one its session started for
1232
+ * it. One the turn that ended never took (it ended as the steer was placed) is placed again, which writes nothing twice
1233
+ * and starts the session's next turn. A turn that ends without the model taking it is that end: its row stays untaken. */
1234
+ const cliSteerAnswered = async (theSession, requestId) => {
1235
+ const steer = cliSteers.get(requestId);
1236
+ if (!steer)
1237
+ return theSession.turnEnd();
1238
+ if (!takenIds.has(requestId))
1239
+ await theSession.steer(steer.text, requestId, "steer", steer.origin ? { origin: steer.origin } : undefined);
1240
+ const end = await Promise.race([steer.recorded.then(() => undefined), theSession.turnEnd()]);
1241
+ if (end !== undefined && !takenIds.has(requestId))
1242
+ return end;
1243
+ await steer.recorded;
1244
+ cliSteers.delete(requestId);
1245
+ return theSession.turnEnd();
1246
+ };
1169
1247
  /** A message the turn in flight could not take (afterTurn), sent as a turn of its own. Its row is taken only once the
1170
1248
  * session holds the prompt (send resolves once it is placed): in the commit that writes it on the run's record, right
1171
1249
  * after the send (a CLI's session writes no submission to the run's journal), or, for an adapter keeping its own record,
@@ -2162,6 +2240,9 @@ function adapterLoop(specOf, options, deps) {
2162
2240
  // After a CLI's question to the person (TurnCut armed): what its model says is not on the record, as pi's turn says
2163
2241
  // nothing after the question; a call of another tool lets the turn go on.
2164
2242
  const onEvent = (theRecord) => (event) => {
2243
+ // The model took a steer: its record entry, and its row, follow (steerCli).
2244
+ if (event.type === "message_taken")
2245
+ return tookNow(event.ids);
2165
2246
  if (askCut.armed && event.type === "text")
2166
2247
  return;
2167
2248
  if (askCut.armed && event.type === "tool_start")
@@ -2292,11 +2373,11 @@ function adapterLoop(specOf, options, deps) {
2292
2373
  firstInputPlaced = new Promise((resolve) => (mine.placed = resolve));
2293
2374
  reopen = mine;
2294
2375
  }
2295
- // A CLI run parked on its question (its turn cut there, TurnCut): its session takes no steer, so the person's
2296
- // answer is this claim's turn, sent as a reopened run's follow-up is (steer, through `reopen`), the row's waiting
2297
- // summary going in its take. A turn the session still reads open is the one the cut stopped: settled first,
2298
- // never recovered (recovered, the CLI would go on past its question).
2299
- if (!endsRoot && !inFlight && spec.record === "loop" && !session.steer && turnEndedOnAsk(foundEntries) !== undefined) {
2376
+ // A CLI run parked on its question (its turn cut there, TurnCut): no turn is in flight for a steer to reach (a CLI
2377
+ // steers only the turn in flight), so the person's answer is this claim's turn, sent as a reopened run's follow-up
2378
+ // is (steer, through `reopen`), the row's waiting summary going in its take. A turn the session still reads open is
2379
+ // the one the cut stopped: settled first, never recovered (recovered, the CLI would go on past its question).
2380
+ if (!endsRoot && !inFlight && spec.record === "loop" && turnEndedOnAsk(foundEntries) !== undefined) {
2300
2381
  if (session.state === "open_turn")
2301
2382
  await session.settleOpenTurn();
2302
2383
  if (session.state === "idle")
@@ -2793,7 +2874,7 @@ function adapterLoop(specOf, options, deps) {
2793
2874
  // the run's end. One already answered settles at once.
2794
2875
  const steered = cut ? undefined : steeredIn.shift();
2795
2876
  if (steered !== undefined) {
2796
- turn = turnOfRequest(harness, root, steered);
2877
+ turn = record ? cliSteerAnswered(session, steered) : turnOfRequest(harness, root, steered);
2797
2878
  continue;
2798
2879
  }
2799
2880
  // The output contract: an answer whose last json block misses the agent's output schema is asked again, once,
@@ -134,6 +134,10 @@ export interface AdapterSpecDeps {
134
134
  * server (runner/beside.ts, Serve.localInstall) is told so, by that server in its own process. Absent, never: a hosted
135
135
  * or standalone runner's loopback is its host's other services. */
136
136
  readonly mcpLoopback?: boolean;
137
+ /** That server's own addresses (Serve.own: where it listens, and its public address on loopback), told with
138
+ * mcpLoopback: a run's loopback request (an MCP server's, its authorization server's, a pin's listing) never goes to
139
+ * their ports, as the server's own requests never do. */
140
+ readonly mcpOwn?: readonly string[];
137
141
  /** A template eval's fakes, by the agent a run is of (template-eval.ts, from its case: EvalFakes). Only the eval's own
138
142
  * runner, in the eval's process, is given it (runner/beside.ts); no environment variable, flag, setting or API field
139
143
  * maps onto it. Absent, or undefined for a run: none. */