@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
@@ -15,7 +15,7 @@
15
15
  // the tier, as its provider bills it), and its cost is that catalog entry, tiers included, for the cap's judgement.
16
16
  import { randomUUID } from "node:crypto";
17
17
  import { calculateCost } from "@earendil-works/pi-ai";
18
- import { ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
18
+ import { onOpenRouter, openRouterAttribution, ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
19
19
  import { chooseModel, MODEL_PROVIDER, runModels } from "../model.js";
20
20
  import { providerFor } from "../provider.js";
21
21
  import { keepText, runnerSecrets, secretRedactor } from "./redact.js";
@@ -76,11 +76,8 @@ export async function routeOf(model, env = process.env, tier = "default", wires
76
76
  // proxy reads it on ROUTE_ORIGIN (statesUsageCost). A model that reasons is given to pi's session as one that asks its
77
77
  // thinking level by name (LEVELS_BY_NAME), which the translation hands to pi-ai (levelOf): the run's effort reaches the
78
78
  // model, mapped and clamped by its own catalog entry.
79
- return { ...route, ...(target.reasoning ? { like: { ...sees, ...LEVELS_BY_NAME } } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream) };
79
+ return { ...route, ...(target.reasoning ? { like: { ...sees, ...LEVELS_BY_NAME } } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream, env) };
80
80
  }
81
- /** OpenRouter's origin: every answer it gives states its cost in its usage (https://openrouter.ai/docs/use-cases/usage-accounting). */
82
- const OPENROUTER_HOST = "openrouter.ai";
83
- const onOpenRouter = (origin) => URL.canParse(origin) && new URL(origin).hostname === OPENROUTER_HOST;
84
81
  /** Whether pi-ai sends `target`'s requests to OpenRouter (pi-ai's own test, utils/openrouter-cost.js isOpenRouterModel). */
85
82
  const piOnOpenRouter = (target) => target.provider === "openrouter" || onOpenRouter(target.baseUrl ?? "");
86
83
  /** How much of an answer's text the error tap keeps: its end, where a stream's error event is. */
@@ -109,8 +106,11 @@ function tapped(upstream) {
109
106
  }
110
107
  /** A fetch that answers Anthropic Messages requests on `target`, through pi-ai's `models`. A provider's error text, which
111
108
  * pi records, goes through `redact` (the runner's one redactor): a provider that echoes its key leaves none there.
112
- * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). */
113
- export function messagesFetch(models, target, redact = keepText, upstream) {
109
+ * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). A request pi-ai
110
+ * sends to OpenRouter carries AgentRun's app attribution unless `env` turns it off (kernel openrouter-attribution.ts),
111
+ * as one the model proxy sends there does; a request to any other provider carries none. */
112
+ export function messagesFetch(models, target, redact = keepText, upstream, env = process.env) {
113
+ const attribution = piOnOpenRouter(target) ? openRouterAttribution(env) : {};
114
114
  // A tool call's id as Messages carries it (letters, digits, _ and -), and back to the provider's own on its result.
115
115
  const providerIds = new Map();
116
116
  const messagesId = (id) => {
@@ -129,7 +129,7 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
129
129
  const tap = piOnOpenRouter(target) ? tapped(upstream) : undefined;
130
130
  const sendWith = tap?.fetch ?? upstream;
131
131
  const level = levelOf(body);
132
- const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}) };
132
+ const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}), ...(Object.keys(attribution).length ? { headers: attribution } : {}) };
133
133
  const events = models.streamSimple(target, context, streamOptions);
134
134
  const encoder = new TextEncoder();
135
135
  const stream = new ReadableStream({
@@ -70,6 +70,14 @@ export declare function replayClaimed(store: Pick<Store, "settings">, agentId: s
70
70
  * the laid one is not the digest it replays (the replay then fails, never scoring another revision). Any other run's,
71
71
  * as laid. */
72
72
  export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWorkflow[]): LearnedWorkflow[];
73
+ /** The learned workflows a run's learned_workflow tool runs, once its first choice is made: what serves, never a
74
+ * revision its promotion has not promoted. The one its first choice served or the money rule stopped (laidFor: its
75
+ * champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
76
+ * text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
77
+ * promoted yet, or the champion held): a revision replaying, queued, held or never decided is never handed to the
78
+ * agent to run in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A
79
+ * replay run's as laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
80
+ export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentId" | "champion" | "log">, launch: RunLaunch, laid: readonly LearnedWorkflow[], choice: FirstChoice): Promise<LearnedWorkflow[]>;
73
81
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
74
82
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
75
83
  * revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its promotion moved on (decide:
@@ -11,7 +11,7 @@ import { sendCommand } from "./commands.js";
11
11
  import { ClaimRefused } from "./loop-contract.js";
12
12
  import { readSnapshot } from "../learn/folder.js";
13
13
  import { refitGuards, refitRowsOf, scoreRows } from "../learn/refit.js";
14
- import { fits, servedOf, workflowDigest } from "./workflow-first.js";
14
+ import { fits, laidFor, servedOf, workflowDigest } from "./workflow-first.js";
15
15
  import { learningCommit } from "../learn/commit.js";
16
16
  import { recordOnly } from "../learn/promote.js";
17
17
  import { workflowsAt } from "./learning-seed.js";
@@ -85,6 +85,48 @@ export function replayLaid(launch, laid) {
85
85
  const { workflow, digest } = launch.replay;
86
86
  return laid.flatMap((one) => (one.name !== workflow ? [one] : workflowDigest(one) === digest ? [{ ...one, workflow: recordOnly(one.workflow) }] : []));
87
87
  }
88
+ /** The learned workflows a run's learned_workflow tool runs, once its first choice is made: what serves, never a
89
+ * revision its promotion has not promoted. The one its first choice served or the money rule stopped (laidFor: its
90
+ * champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
91
+ * text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
92
+ * promoted yet, or the champion held): a revision replaying, queued, held or never decided is never handed to the
93
+ * agent to run in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A
94
+ * replay run's as laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
95
+ export async function toolFlowsFor(deps, launch, laid, choice) {
96
+ const chosen = laidFor(laid, choice);
97
+ if (launch.replay || !chosen.length)
98
+ return chosen;
99
+ const name = choice.serve?.name ?? choice.revise?.workflow;
100
+ let records;
101
+ try {
102
+ records = await promotionsOf(deps.store.settings, deps.agentId);
103
+ }
104
+ catch (error) {
105
+ deps.log(`workflow-first: the promotions could not be read (${error?.message ?? error}); the learned_workflow tool runs only the workflow chosen first`);
106
+ return chosen.filter((one) => one.name === name);
107
+ }
108
+ const out = [];
109
+ for (const one of chosen) {
110
+ if (one.name === name || !records.some((record) => record.workflow === one.name)) {
111
+ out.push(one);
112
+ continue;
113
+ }
114
+ const digest = workflowDigest(one);
115
+ const champion = championOf(records, one.name);
116
+ if (champion?.digest === digest) {
117
+ out.push(one);
118
+ continue;
119
+ }
120
+ const text = champion?.commit && deps.champion ? await deps.champion(one.name, champion.commit).catch(() => undefined) : undefined;
121
+ if (text && workflowDigest(text) === champion.digest) {
122
+ deps.log(`workflow-first: the learned_workflow tool runs ${one.name}'s champion at ${champion.digest}, not ${digest}, which is not promoted`);
123
+ out.push(text);
124
+ }
125
+ else
126
+ deps.log(`workflow-first: the learned_workflow tool leaves out ${one.name}: ${digest} is not promoted, and ${champion ? `its champion at ${champion.digest} could not be read from its learning commit` : "no revision of it serves"}`);
127
+ }
128
+ return out;
129
+ }
88
130
  const iso = (ms) => new Date(ms).toISOString();
89
131
  /** The claim's seed as a record's `commit`: the learning commit the laid workflow's text was read from. */
90
132
  const seedOf = (deps) => (deps.launch.learning?.seed ? { commit: deps.launch.learning.seed } : {});
@@ -2,7 +2,7 @@ import { type LearnedWorkflow } from "../learning.js";
2
2
  import type { RunLaunch } from "../run-launch.js";
3
3
  import { COST_WINDOW, type RunPath } from "../learning-cost.js";
4
4
  export { COST_WINDOW };
5
- import { type GuardRow } from "../learned-nodes.js";
5
+ import { type GuardRow, type LoopRow } from "../learned-nodes.js";
6
6
  import type { Skipped } from "../learn/replay-calls.js";
7
7
  /** The root entry a run served workflow-first keeps, once the workflow's call ended: which workflow, at which learned
8
8
  * revision, under which call, and how it ended. A later claim that finds it never runs the workflow again. */
@@ -101,8 +101,8 @@ export interface FirstChoice {
101
101
  * is not promoted yet or was held (runner/promotion.ts): the text the run's learned_workflow tool runs (laidFor). */
102
102
  readonly champion?: LearnedWorkflow;
103
103
  }
104
- /** The learned workflows a run's tool runs once its first choice is made: the laid ones, a champion (FirstChoice) in
105
- * place of its laid revision. */
104
+ /** The laid learned workflows with a first choice's champion (FirstChoice) in place of its laid revision: what
105
+ * runner/promotion.ts toolFlowsFor reads the rest of from the promotion records, so the run's tool runs only what serves. */
106
106
  export declare const laidFor: (laid: readonly LearnedWorkflow[], choice: FirstChoice) => LearnedWorkflow[];
107
107
  /** What serves a run in place of its laid workflow: the workflow (the laid one itself, or its champion's text), and the
108
108
  * promotion it serves under (WorkflowFirst.promotion). */
@@ -169,8 +169,8 @@ export declare function reviseOf(entries: readonly {
169
169
  * (runPathOverStore): the path it took, the learned revision it ran on, the learned workflow it ran (served first, or
170
170
  * called by its agent) and, for one served first, its digest and the promotion it served under (`workflow_promotion`,
171
171
  * which its grade keeps); and from its root `entries`, each step guard's check of its learned workflows' calls
172
- * (`guards`, learned-nodes.ts guardsOf), when one ran. learning-cost reads path and workflow from here. None for a run
173
- * that does not learn. */
172
+ * (`guards`, learned-nodes.ts guardsOf) and each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second
173
+ * pass), when one ran. learning-cost reads path and workflow from here. None for a run that does not learn. */
174
174
  export declare function pathMetrics(launch: RunLaunch, classified: {
175
175
  path: RunPath;
176
176
  workflow: string | null;
@@ -186,6 +186,7 @@ export declare function pathMetrics(launch: RunLaunch, classified: {
186
186
  workflow_digest?: string;
187
187
  workflow_promotion?: number;
188
188
  guards?: GuardRow[];
189
+ loops?: LoopRow[];
189
190
  replay?: ReplayMetrics;
190
191
  };
191
192
  /** A replay run's record (metrics.replay): the graded run it replayed and how its workflow ended there. */
@@ -28,7 +28,7 @@ import { COST_WINDOW } from "../learning-cost.js";
28
28
  export { COST_WINDOW };
29
29
  import { KINDS } from "./journal-kinds.js";
30
30
  import { inputIssues, isObject } from "../validate.js";
31
- import { endedIn, guardsOf, replaySkippedIn } from "../learned-nodes.js";
31
+ import { endedIn, guardsOf, loopsOf, replaySkippedIn } from "../learned-nodes.js";
32
32
  import { sameAnswer } from "../learn/promote.js";
33
33
  /** The root entry a run served workflow-first keeps, once the workflow's call ended: which workflow, at which learned
34
34
  * revision, under which call, and how it ended. A later claim that finds it never runs the workflow again. */
@@ -85,8 +85,8 @@ export function workflowCostsOf(past) {
85
85
  return { workflow, digest, state: overLine(line) ? "needs_revision" : "serving", served: line.served.runs ? line.served : null, by_hand: line.by_hand, unknown_cost_runs: line.unknown_runs };
86
86
  });
87
87
  }
88
- /** The learned workflows a run's tool runs once its first choice is made: the laid ones, a champion (FirstChoice) in
89
- * place of its laid revision. */
88
+ /** The laid learned workflows with a first choice's champion (FirstChoice) in place of its laid revision: what
89
+ * runner/promotion.ts toolFlowsFor reads the rest of from the promotion records, so the run's tool runs only what serves. */
90
90
  export const laidFor = (laid, choice) => choice.champion ? laid.map((one) => (one.name === choice.champion.name ? choice.champion : one)) : [...laid];
91
91
  /** A workflow's input schema, resolved as the DSL resolves a schema reference, or undefined when it names none. */
92
92
  function inputSchemaOf(text, resolve) {
@@ -229,13 +229,15 @@ export function reviseOf(entries) {
229
229
  * (runPathOverStore): the path it took, the learned revision it ran on, the learned workflow it ran (served first, or
230
230
  * called by its agent) and, for one served first, its digest and the promotion it served under (`workflow_promotion`,
231
231
  * which its grade keeps); and from its root `entries`, each step guard's check of its learned workflows' calls
232
- * (`guards`, learned-nodes.ts guardsOf), when one ran. learning-cost reads path and workflow from here. None for a run
233
- * that does not learn. */
232
+ * (`guards`, learned-nodes.ts guardsOf) and each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second
233
+ * pass), when one ran. learning-cost reads path and workflow from here. None for a run that does not learn. */
234
234
  export function pathMetrics(launch, classified, entries = []) {
235
235
  if (!launch.learning)
236
236
  return {};
237
237
  const { path, workflow, digest, promotion } = classified ?? { path: "agent", workflow: null };
238
238
  const guards = guardsOf(entries);
239
+ const loops = loopsOf(entries);
240
+ const rows = { ...(guards.length ? { guards } : {}), ...(loops.length ? { loops } : {}) };
239
241
  if (launch.replay) {
240
242
  // A replay run (runner/promotion.ts): path `replay`, whatever its workflow did, so the money rule and the agent's
241
243
  // by-hand cost never read it; how its workflow ended, for the replay's score (learn/promote.ts ReplayRow).
@@ -246,9 +248,9 @@ export function pathMetrics(launch, classified, entries = []) {
246
248
  // evidence. Skipped when a write it needed is not in the graded run's recording (learn/replay-calls.ts): never run.
247
249
  const skipped = replaySkippedIn(entries);
248
250
  const outcome = skipped ? "skipped_write" : path === "workflow" && workflow === name ? "answered" : path === "handed_back" && workflow === name && endedIn(entries, name) === "escalated" ? "handed_back" : "failed";
249
- return { path: "replay", ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), workflow: name, workflow_digest: at, ...(guards.length ? { guards } : {}), replay: { of, outcome, ...(skipped ? { skipped } : {}) } };
251
+ return { path: "replay", ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), workflow: name, workflow_digest: at, ...rows, replay: { of, outcome, ...(skipped ? { skipped } : {}) } };
250
252
  }
251
- return { path, ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), ...(workflow ? { workflow } : {}), ...(digest ? { workflow_digest: digest } : {}), ...(promotion !== undefined ? { workflow_promotion: promotion } : {}), ...(guards.length ? { guards } : {}) };
253
+ return { path, ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), ...(workflow ? { workflow } : {}), ...(digest ? { workflow_digest: digest } : {}), ...(promotion !== undefined ? { workflow_promotion: promotion } : {}), ...rows };
252
254
  }
253
255
  /** What run `entries` (its root's) say its learned workflow answered alone: the workflow and its answer (the model's
254
256
  * message written just before the WORKFLOW_FIRST entry, in its commit); undefined for a run it did not answer. A follow-up that opens such a
@@ -17,6 +17,7 @@ import { CAP_TOLERANCE, money } from "./cap.js";
17
17
  import { holdOf } from "./computer-held.js";
18
18
  import { computerOfPlace, settingOfDefinition } from "./computer-setting.js";
19
19
  import { ApiError, invalid, unsupported } from "./errors.js";
20
+ import { labelsOf } from "./run-labels.js";
20
21
  import { harnessOfBody } from "./harness.js";
21
22
  import { redacted, redactedOutput } from "./key-refusal.js";
22
23
  import { chooseWorkflows, LEARNING_BUDGET, learnedParts, learnsOf, RUN_LEARNING_USE } from "./learning.js";
@@ -447,7 +448,8 @@ export async function startRun(store, deps, entry, body, { trigger, origin, capp
447
448
  const { launch, revision } = await prepareLaunch(deps, entry, body, { ...(trigger ? { trigger } : {}), capped, ...(from ? { from } : {}), ...(title !== undefined ? { title } : {}) });
448
449
  const runId = (deps.newRunId ?? uuidv7)();
449
450
  try {
450
- return await withHeldFiles(deps, runId, launch, () => store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: revision.id, ...(origin ? { origin } : {}) }, { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId) } : {}) }));
451
+ const labels = labelsOf(body.labels);
452
+ return await withHeldFiles(deps, runId, launch, () => store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: revision.id, ...(origin ? { origin } : {}), ...(labels ? { labels } : {}) }, { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId) } : {}) }));
451
453
  }
452
454
  catch (error) {
453
455
  // Only another writer of the store got here first under the same origin key: its run is the one asked for.
@@ -508,11 +510,12 @@ export async function startInline(store, deps, inline, body, { origin, sealed }
508
510
  // one across.
509
511
  const { launch } = await prepareLaunch(deps, entry, body, { revision: (storedRevision ?? revision) });
510
512
  const runId = (deps.newRunId ?? uuidv7)();
513
+ const labels = labelsOf(body.labels);
511
514
  try {
512
515
  return await withHeldFiles(deps, runId, launch, () => store.runs.createInline({
513
516
  agent: { id: entry.agent.id, name: inline.name, description: inline.description, ref },
514
517
  revision: { id: revision.id, version: external.version, kind: revision.kind, body: revision.body, skills: revision.skills, ...(revision.note !== undefined ? { note: revision.note } : {}), ...(revision.mcpPin !== undefined ? { mcpPin: revision.mcpPin } : {}), ...(revision.monidPin !== undefined ? { monidPin: revision.monidPin } : {}) },
515
- run: { id: runId, ...(origin ? { origin } : {}) },
518
+ run: { id: runId, ...(origin ? { origin } : {}), ...(labels ? { labels } : {}) },
516
519
  launch: { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId) } : {}) },
517
520
  }));
518
521
  }
@@ -61,12 +61,18 @@ export declare function sdkInbox(store: Pick<Store, "settings">, runId: string):
61
61
  /** Completion and closure compete on the same inbox. A stale runner cannot close it, and a completion that won
62
62
  * remains available to the next claim even if this one cannot read or journal it. No external SDK call is replayed. */
63
63
  export declare function closeSdkInbox(store: Pick<Store, "settings">, claim: Claim, reason: NonNullable<SdkInbox["closed"]>): Promise<SdkInbox>;
64
+ /** The key a server signs its SDK runs' credentials with: derived from its seal key (seal-key.ts), which stays the
65
+ * store's for its life, so adding, reordering or removing an API token (api-token.ts) never changes a run's credential. */
66
+ export declare const sdkRunSecret: (sealKey: Buffer) => string;
64
67
  export declare class SdkRuns {
65
68
  private readonly store;
66
69
  private readonly data;
67
70
  private readonly secret;
68
71
  private readonly secrets;
69
- constructor(store: Store, data: string, secret: string, secrets?: () => readonly string[]);
72
+ private readonly earlier;
73
+ /** `earlier` are the keys credentials were once signed with (the server's API tokens, before `secret` was its seal
74
+ * key's): a credential any of them signed is still taken, so a run started before an upgrade keeps its credential. */
75
+ constructor(store: Store, data: string, secret: string, secrets?: () => readonly string[], earlier?: readonly string[]);
70
76
  token(runId: string): string;
71
77
  authenticate(runId: string, token: string): Promise<void>;
72
78
  private clean;
package/dist/sdk/runs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Backend SDK calls remain in their application. This inbox only records their evidence and immutable completion;
2
2
  // the ordinary fenced runner owns journals, reflection, checking and learning commits.
3
- import { createHmac, timingSafeEqual } from "node:crypto";
3
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
4
4
  import { inspectWorkflow } from "@parcha/agentrun-dsl";
5
5
  import { ApiError } from "../errors.js";
6
6
  import { canonical, isObject } from "../store/agent-body.js";
@@ -117,28 +117,41 @@ function checkToolParents(row, events) {
117
117
  }
118
118
  }
119
119
  }
120
+ /** The key a server signs its SDK runs' credentials with: derived from its seal key (seal-key.ts), which stays the
121
+ * store's for its life, so adding, reordering or removing an API token (api-token.ts) never changes a run's credential. */
122
+ export const sdkRunSecret = (sealKey) => createHmac("sha256", sealKey).update("agentrun sdk-run credentials").digest("base64url");
123
+ const sign = (secret, runId) => `ar_sdk_${createHmac("sha256", secret).update(`sdk-run\0${runId}`).digest("base64url")}`;
124
+ const digest = (text) => createHash("sha256").update(text).digest();
120
125
  export class SdkRuns {
121
126
  store;
122
127
  data;
123
128
  secret;
124
129
  secrets;
125
- constructor(store, data, secret, secrets = () => []) {
130
+ earlier;
131
+ /** `earlier` are the keys credentials were once signed with (the server's API tokens, before `secret` was its seal
132
+ * key's): a credential any of them signed is still taken, so a run started before an upgrade keeps its credential. */
133
+ constructor(store, data, secret, secrets = () => [], earlier = []) {
126
134
  this.store = store;
127
135
  this.data = data;
128
136
  this.secret = secret;
129
137
  this.secrets = secrets;
138
+ this.earlier = earlier;
130
139
  }
131
140
  token(runId) {
132
- return `ar_sdk_${createHmac("sha256", this.secret).update(`sdk-run\0${runId}`).digest("base64url")}`;
141
+ return sign(this.secret, runId);
133
142
  }
134
143
  async authenticate(runId, token) {
135
- const expected = Buffer.from(this.token(runId)), actual = Buffer.from(token);
136
- if (expected.length !== actual.length || !timingSafeEqual(expected, actual))
144
+ // Every key compared, on equal-length digests, with no early return.
145
+ const given = digest(token);
146
+ let ok = false;
147
+ for (const key of [this.secret, ...this.earlier])
148
+ ok = timingSafeEqual(given, digest(sign(key, runId))) || ok;
149
+ if (!ok)
137
150
  throw new ApiError("unauthenticated", "This credential is scoped to a different SDK run.");
138
151
  await sdkInbox(this.store, runId);
139
152
  }
140
153
  clean(body, runId) {
141
- const redact = secretRedactor([...this.secrets(), ...(runId ? [this.token(runId)] : [])]);
154
+ const redact = secretRedactor([...this.secrets(), ...(runId ? [this.secret, ...this.earlier].map((key) => sign(key, runId)) : [])]);
142
155
  // Redact values structurally: a long string or encoded credential can be withheld whole,
143
156
  // so treating serialized JSON as prose could remove its delimiters and corrupt the envelope.
144
157
  return redactedOutput(body, redact.heldValues?.() ?? []);
@@ -7,6 +7,7 @@ import { rules as recommended } from "@secretlint/secretlint-rule-preset-recomme
7
7
  // No performance marks: the profiler would leave about 14 a call in the process's global buffer.
8
8
  secretLintProfiler.setEnabled(false);
9
9
  import { keyShaped } from "./secret-name.js";
10
+ import { secretValues } from "./api-token.js";
10
11
  /** Whether a name is a secret's, whatever list names it or none does: one of its `_`-separated segments, in any case, is
11
12
  * KEY, TOKEN, SECRET, PASSWORD, PASSWD, PASS, PAT, CREDENTIAL, CREDENTIALS or DSN, or its last is PWD after another.
12
13
  * The one rule: this cut, the harness log's and a run's environment (secrets.ts' withoutSecrets)
@@ -22,7 +23,8 @@ export function secretCut(envs, names = []) {
22
23
  const secrets = (Array.isArray(envs) ? envs : [envs])
23
24
  .flatMap((env) => Object.getOwnPropertyNames(env).map((name) => [name, env[name]]))
24
25
  .filter(([name, value]) => (keyShaped(name) || names.includes(name)) && typeof value === "string" && value.length >= 8)
25
- .map(([, value]) => value)
26
+ // AGENTRUN_TOKENS's each secret too, not only the list whole (api-token.ts secretValues).
27
+ .flatMap(([name, value]) => secretValues(name, value).filter((part) => part.length >= 8))
26
28
  // The longest first: a key that holds a shorter one is cut whole.
27
29
  .sort((a, b) => b.length - a.length);
28
30
  // `text.removed` counts the values it cut, each once however often it was met; `text.probe` cuts the same and counts
package/dist/secrets.js CHANGED
@@ -11,6 +11,7 @@ import { closeSync, existsSync, readFileSync, readSync } from "node:fs";
11
11
  import { homedir } from "node:os";
12
12
  import { keyShaped } from "./secret-cut.js";
13
13
  import { MIN_SECRET } from "./learn/secrets.js";
14
+ import { secretValues } from "./api-token.js";
14
15
  /** The pipe and how many bytes of it are the secrets: the launcher's, or serve's to a run's process. */
15
16
  export const SECRETS_FD_ENV = "AGENTRUN_SECRETS_FD";
16
17
  export const SECRETS_LEN_ENV = "AGENTRUN_SECRETS_LEN";
@@ -94,7 +95,8 @@ const SECRET_NAME = /(?:^|_)(?:KEY|TOKEN|SECRET|PASSWORD)$/i;
94
95
  * every other key, token, secret or password `env` names. One shorter than the checker's MIN_SECRET,
95
96
  * whitespace aside, matches too much text by chance to be refused, and is left out. */
96
97
  export const hostSecrets = (env, stored) => {
97
- const held = [...SECRET_NAMES.flatMap((name) => [secret(name) ?? "", stored?.(name) ?? ""]), ...mcpSecretValues(mcpCredentials()), ...sealKeys.keys(), ...heldTokens];
98
+ // AGENTRUN_TOKENS's each secret too, not only the list whole (api-token.ts secretValues).
99
+ const held = [...SECRET_NAMES.flatMap((name) => [...secretValues(name, secret(name) ?? ""), stored?.(name) ?? ""]), ...mcpSecretValues(mcpCredentials()), ...sealKeys.keys(), ...heldTokens];
98
100
  const named = Object.entries(env).filter(([name]) => SECRET_NAME.test(name) && !SECRET_NAMES.includes(name)).map(([, value]) => value ?? "");
99
101
  return [...new Set([...held, ...named])].filter((value) => value.replace(/\s+/g, "").length >= MIN_SECRET);
100
102
  };
package/dist/server.d.ts CHANGED
@@ -3,6 +3,7 @@ import { type HarnessCapability } from "./harness.js";
3
3
  import { type HarnessInstaller } from "./harness-install.js";
4
4
  import { type LearningMode } from "./learning.js";
5
5
  import { type Place } from "./place.js";
6
+ import { type ApiToken } from "./api-token.js";
6
7
  import { type Store } from "./store/index.js";
7
8
  import { type BoxOffer } from "./place-offers.js";
8
9
  import { type StoredKeys } from "./secrets.js";
@@ -10,7 +11,7 @@ import { type ComposioControl } from "./composio-preset.js";
10
11
  import type { TriggerAdapter } from "./trigger-adapter.js";
11
12
  import { type TriggerClock } from "./triggers.js";
12
13
  import { type ToolSettingsMap } from "./tool-plane.js";
13
- import { AttachHub } from "@parcha/agentrun-computer";
14
+ import { AttachHub, type HostedDial } from "@parcha/agentrun-computer";
14
15
  export declare const CONTRACT = "agentrun.v2/0";
15
16
  export declare const DEFAULT_PORT = 7340;
16
17
  export type ServeOptions = {
@@ -54,8 +55,13 @@ export type ServeOptions = {
54
55
  /** The address to listen on (default 127.0.0.1). On any other address every `Host` name is served and the token is
55
56
  * the only lock: put TLS in front of it. */
56
57
  host?: string;
57
- /** The token to require in place of the one `DIR/.token` keeps: 32 characters or more, no whitespace. */
58
+ /** The token to require in place of the one `DIR/.token` keeps: 32 characters or more, no whitespace. Its id is
59
+ * `default` (api-token.ts). */
58
60
  token?: string;
61
+ /** More API tokens (AGENTRUN_TOKENS, api-token.ts parseTokens), each with an id: every one opens every route the
62
+ * token opens. Given these and no `token`, `DIR/.token` is neither read nor made, and the first is the server's
63
+ * token. Each id names its token in the request log; no line holds a secret. */
64
+ tokens?: readonly ApiToken[];
59
65
  /** Default 7340; 0 is any free port. */
60
66
  port?: number;
61
67
  /** When the port is taken at the listen, the next one that is not, of the 100 from it: the port is found by listening,
@@ -165,6 +171,10 @@ export type ServeOptions = {
165
171
  learningBudget?: number;
166
172
  /** A test's seam: the triggers' clock and timer (triggers.ts), in place of Date.now and setTimeout. */
167
173
  triggerClock?: TriggerClock;
174
+ /** A test's and a template eval's seam: the URL a feed trigger's read of `url` goes to in its place (a fake feed on
175
+ * loopback, feed/feed-faux.ts); null when it serves no feed at `url` (read as unreachable, nothing sent); undefined
176
+ * to read it as it is. The trigger, its payload and its words keep `url`. */
177
+ feedsAt?: (url: string) => string | null | undefined;
168
178
  /** The server's store (store/index.ts), where the triggers and their firings live, with the agents they run as. Without
169
179
  * it the trigger routes answer unavailable and nothing fires. */
170
180
  store?: Pick<Store, "triggers" | "runs" | "agents"> & Partial<Pick<Store, "liveViewers">>;
@@ -191,6 +201,10 @@ export type ServeOptions = {
191
201
  /** Whether the outbound webhook may send to a private network or this machine: off by default, so no caller of the API
192
202
  * can make the server POST inside its own network. The operator's AGENTRUN_WEBHOOK_PRIVATE_TARGETS=1 turns it on. */
193
203
  webhookPrivateTargets?: boolean;
204
+ /** A test's seam: the addresses the outbound webhook's receiver's name resolves to, at a save's check and at each try
205
+ * (webhooks.ts), in place of the system resolver's. A test's server answers its example hosts here, so no CI
206
+ * runner's resolver decides what a test sees. */
207
+ webhookLookup?: (host: string) => Promise<string[]>;
194
208
  };
195
209
  /** The test switches a run's process gets, each module path resolved: empty outside tests. A test's in-process runner
196
210
  * takes the same (test/support.mjs startInProcessRunner). */
@@ -201,11 +215,14 @@ export declare function fauxEnvOf(options: ServeOptions): NodeJS.ProcessEnv;
201
215
  /** `boxesLine`: what the start's banner says of the boxes, in words (place.ts boxesLine). */
202
216
  /** `launchCode`: with no accounts, the code of the console's link this start prints (`/?launch=<code>`), which gives the
203
217
  * browser that opens it a console session (page.ts ConsoleSessions). */
218
+ /** `token` is the first of `tokenIds` (the console's session stands for it); `tokenIds` are the ids of every token the
219
+ * server takes, in order (api-token.ts), never their secrets. */
204
220
  export type Serve = {
205
221
  url: string;
206
222
  baseUrl: string;
207
223
  port: number;
208
224
  token: string;
225
+ tokenIds: readonly string[];
209
226
  tokenFile: string | null;
210
227
  tokenMade: boolean;
211
228
  setupUrl?: string;
@@ -216,10 +233,18 @@ export type Serve = {
216
233
  /** The live sockets of the computers paired with this server (computer-attach.ts): a runner beside the server in this
217
234
  * process takes it (runner/beside.ts), so its runs can use them. */
218
235
  attachHub: AttachHub;
236
+ /** What a dial provider's create takes of this server (HostedProvider's dial): the address its machines dial
237
+ * (AGENTRUN_PUBLIC_URL, absent without one), the tokens it mints for them (computer-attach.ts machineTokens) and the
238
+ * hub their sockets land in. The runner beside the server hands it to its remote providers (runner/beside.ts). */
239
+ dial: HostedDial;
219
240
  /** Whether this server is a local install (listening on loopback, reached at no address off it): the one kind whose own
220
241
  * runner beside it may reach an MCP server's URL on loopback (runner/beside.ts mcpLoopback). Only that runner is told:
221
242
  * it is this process's finding, never a store's, so another host's runner on a shared store never inherits it. */
222
243
  localInstall: boolean;
244
+ /** This server's own addresses (McpServersOverStore.own): where it listens, and its public address when that is on
245
+ * loopback. The runner beside it is told them with localInstall (runner/beside.ts mcpOwn), so its runs' loopback reads
246
+ * never reach this server, as its own reads never do. */
247
+ own: readonly string[];
223
248
  /** What a stop waits on: the runs whose processes still finish their turn, and the longest it waits on them. */
224
249
  stopping(): {
225
250
  runs: number;