@parcha/agentrun-serve 0.1.0-beta.53 → 0.1.0-beta.55

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 (224) hide show
  1. package/CHANGELOG.md +138 -3
  2. package/README.md +346 -99
  3. package/dist/adapters.d.ts +10 -0
  4. package/dist/adapters.js +46 -0
  5. package/dist/agent-package.d.ts +3 -3
  6. package/dist/agent-package.js +7 -14
  7. package/dist/agent-rows.d.ts +1 -1
  8. package/dist/agents-store.js +7 -6
  9. package/dist/api-only.d.ts +17 -6
  10. package/dist/api-only.js +22 -9
  11. package/dist/cli.js +11 -4
  12. package/dist/composio-made.d.ts +26 -1
  13. package/dist/composio-made.js +39 -2
  14. package/dist/composio-preset.d.ts +6 -4
  15. package/dist/composio-preset.js +50 -17
  16. package/dist/computer-held-routes.js +2 -3
  17. package/dist/computer-needs.d.ts +1 -1
  18. package/dist/computer-needs.js +1 -1
  19. package/dist/computer-setting.d.ts +8 -4
  20. package/dist/computer-setting.js +0 -2
  21. package/dist/computers-running.d.ts +8 -0
  22. package/dist/computers-running.js +27 -0
  23. package/dist/computers.d.ts +0 -2
  24. package/dist/computers.js +1 -1
  25. package/dist/console/assets/backend-D5EmB4N3.js +166 -0
  26. package/dist/console/assets/index-DUYLaqiR.js +746 -0
  27. package/dist/console/assets/index-DYhU4adm.css +1 -0
  28. package/dist/console/index.html +2 -2
  29. package/dist/docker-host-addresses.d.ts +23 -3
  30. package/dist/docker-host-addresses.js +90 -18
  31. package/dist/errors.d.ts +4 -0
  32. package/dist/errors.js +7 -0
  33. package/dist/exa-keyless.d.ts +2 -3
  34. package/dist/exa-keyless.js +43 -127
  35. package/dist/firecrawl-keyless.d.ts +41 -0
  36. package/dist/firecrawl-keyless.js +152 -0
  37. package/dist/github-connection.d.ts +50 -1
  38. package/dist/github-connection.js +96 -3
  39. package/dist/github-faux.d.ts +11 -2
  40. package/dist/github-faux.js +138 -7
  41. package/dist/github-pull-request.d.ts +37 -0
  42. package/dist/github-pull-request.js +110 -0
  43. package/dist/handed-secret.d.ts +3 -1
  44. package/dist/handed-secret.js +4 -2
  45. package/dist/harness-keys.d.ts +98 -0
  46. package/dist/harness-keys.js +247 -0
  47. package/dist/harness-recipe-entry.d.ts +14 -9
  48. package/dist/harness-recipe-entry.js +25 -14
  49. package/dist/harness-table.d.ts +16 -1
  50. package/dist/harness-table.js +19 -7
  51. package/dist/harness.d.ts +4 -0
  52. package/dist/harness.js +12 -1
  53. package/dist/host-check.d.ts +2 -0
  54. package/dist/host-check.js +6 -0
  55. package/dist/import-summary.d.ts +1 -1
  56. package/dist/import-summary.js +1 -1
  57. package/dist/import.d.ts +5 -5
  58. package/dist/import.js +54 -67
  59. package/dist/keyless-mcp.d.ts +36 -0
  60. package/dist/keyless-mcp.js +127 -0
  61. package/dist/learn/audit.d.ts +3 -3
  62. package/dist/learn/audit.js +3 -3
  63. package/dist/learn/commit.d.ts +8 -7
  64. package/dist/learn/commit.js +60 -20
  65. package/dist/learn/compile.d.ts +4 -3
  66. package/dist/learn/compile.js +7 -5
  67. package/dist/learn/folder.d.ts +16 -3
  68. package/dist/learn/folder.js +46 -13
  69. package/dist/learn/promote.d.ts +37 -13
  70. package/dist/learn/promote.js +112 -40
  71. package/dist/learn/secrets.js +10 -2
  72. package/dist/learning-routes.d.ts +22 -17
  73. package/dist/learning-routes.js +40 -39
  74. package/dist/learning.js +2 -2
  75. package/dist/live-reach.d.ts +34 -7
  76. package/dist/live-reach.js +76 -11
  77. package/dist/manifest.d.ts +10 -0
  78. package/dist/manifest.js +30 -0
  79. package/dist/mcp-pin-first.d.ts +4 -2
  80. package/dist/mcp-pin-first.js +5 -2
  81. package/dist/mcp-probe.js +2 -2
  82. package/dist/mcp-secret-writes.d.ts +16 -7
  83. package/dist/mcp-secret-writes.js +35 -27
  84. package/dist/mcp-servers-store.d.ts +30 -6
  85. package/dist/mcp-servers-store.js +112 -28
  86. package/dist/mcp-sources.d.ts +10 -2
  87. package/dist/mcp-sources.js +9 -2
  88. package/dist/mcp-store.d.ts +13 -7
  89. package/dist/mcp-store.js +12 -9
  90. package/dist/model-form.d.ts +3 -2
  91. package/dist/model-form.js +11 -7
  92. package/dist/model.d.ts +20 -4
  93. package/dist/model.js +68 -9
  94. package/dist/native/history.d.ts +1 -1
  95. package/dist/native/history.js +2 -2
  96. package/dist/ollama-provider.d.ts +92 -0
  97. package/dist/ollama-provider.js +495 -0
  98. package/dist/openapi/agentrun-v2.openapi.json +2 -2
  99. package/dist/openapi.js +235 -41
  100. package/dist/page.d.ts +11 -3
  101. package/dist/page.js +22 -7
  102. package/dist/place-offers.d.ts +17 -1
  103. package/dist/place-offers.js +46 -5
  104. package/dist/print.js +1 -1
  105. package/dist/purged-workflow.d.ts +35 -7
  106. package/dist/purged-workflow.js +73 -26
  107. package/dist/run-computer.d.ts +2 -0
  108. package/dist/run-computer.js +2 -0
  109. package/dist/run-files.d.ts +4 -0
  110. package/dist/run-files.js +4 -0
  111. package/dist/run-keys.d.ts +2 -4
  112. package/dist/run-keys.js +6 -7
  113. package/dist/run-launch.d.ts +4 -0
  114. package/dist/run-launch.js +4 -0
  115. package/dist/run-reads-over-store.d.ts +3 -2
  116. package/dist/run-reads-over-store.js +66 -2
  117. package/dist/run-secrets.js +5 -2
  118. package/dist/runner/adapter-loop.d.ts +6 -3
  119. package/dist/runner/adapter-loop.js +34 -15
  120. package/dist/runner/adapter-run-spec.d.ts +3 -0
  121. package/dist/runner/adapter-run-spec.js +6 -4
  122. package/dist/runner/audit.js +8 -4
  123. package/dist/runner/beside.d.ts +2 -1
  124. package/dist/runner/beside.js +6 -2
  125. package/dist/runner/claim-secrets.d.ts +5 -8
  126. package/dist/runner/claim-secrets.js +6 -0
  127. package/dist/runner/cli-run-spec.d.ts +1 -1
  128. package/dist/runner/cli-run-spec.js +39 -7
  129. package/dist/runner/harness-loops.d.ts +22 -9
  130. package/dist/runner/harness-loops.js +21 -11
  131. package/dist/runner/held.d.ts +3 -0
  132. package/dist/runner/learning-end.d.ts +1 -1
  133. package/dist/runner/learning-end.js +8 -3
  134. package/dist/runner/loop-contract.d.ts +5 -4
  135. package/dist/runner/main.js +4 -2
  136. package/dist/runner/mcp-claim.d.ts +3 -0
  137. package/dist/runner/mcp-claim.js +26 -2
  138. package/dist/runner/mcp-run.d.ts +3 -0
  139. package/dist/runner/mcp-run.js +2 -1
  140. package/dist/runner/metrics.d.ts +10 -8
  141. package/dist/runner/metrics.js +20 -27
  142. package/dist/runner/model-route.d.ts +3 -0
  143. package/dist/runner/model-route.js +6 -2
  144. package/dist/runner/pr-checkout.d.ts +21 -4
  145. package/dist/runner/pr-checkout.js +103 -4
  146. package/dist/runner/promotion.d.ts +15 -9
  147. package/dist/runner/promotion.js +25 -15
  148. package/dist/runner/run-child-host.js +24 -11
  149. package/dist/runner/run-child.js +3 -1
  150. package/dist/runner/runner-check.d.ts +3 -0
  151. package/dist/runner/runner-check.js +23 -0
  152. package/dist/runner/sdk-loop.js +2 -0
  153. package/dist/runner/workflow-loop.d.ts +2 -2
  154. package/dist/runner/workflow-loop.js +1 -2
  155. package/dist/runner/workflow-spec.d.ts +1 -1
  156. package/dist/runner/workflow-spec.js +6 -6
  157. package/dist/sdk/check.d.ts +4 -1
  158. package/dist/sdk/check.js +2 -1
  159. package/dist/sdk/runs.d.ts +2 -2
  160. package/dist/sdk/runs.js +8 -6
  161. package/dist/secret-cut.js +2 -1
  162. package/dist/secret-writes.d.ts +3 -2
  163. package/dist/secret-writes.js +1 -1
  164. package/dist/server.d.ts +55 -8
  165. package/dist/server.js +363 -118
  166. package/dist/standard-webhooks.d.ts +11 -0
  167. package/dist/standard-webhooks.js +20 -2
  168. package/dist/store/agent-body.d.ts +2 -2
  169. package/dist/store/agent-body.js +2 -2
  170. package/dist/store/index.d.ts +1 -1
  171. package/dist/store/schema.js +5 -2
  172. package/dist/store/sqlite/store.js +90 -34
  173. package/dist/store/store.d.ts +54 -14
  174. package/dist/store-reads/journal.d.ts +7 -2
  175. package/dist/store-reads/journal.js +9 -6
  176. package/dist/store-reads/learning.d.ts +12 -9
  177. package/dist/store-reads/learning.js +18 -24
  178. package/dist/store-view.d.ts +0 -5
  179. package/dist/store-view.js +9 -8
  180. package/dist/suggestions.d.ts +282 -0
  181. package/dist/suggestions.js +919 -0
  182. package/dist/telemetry.d.ts +8 -1
  183. package/dist/telemetry.js +12 -4
  184. package/dist/template-eval.d.ts +49 -4
  185. package/dist/template-eval.js +168 -45
  186. package/dist/template-import.d.ts +17 -0
  187. package/dist/template-import.js +36 -2
  188. package/dist/templates.d.ts +83 -76
  189. package/dist/templates.js +29 -48
  190. package/dist/timeline/labels.d.ts +2 -2
  191. package/dist/timeline/labels.js +2 -2
  192. package/dist/timeline/timeline.d.ts +2 -2
  193. package/dist/timeline/timeline.js +1 -1
  194. package/dist/tool-plane.d.ts +17 -9
  195. package/dist/tool-plane.js +38 -17
  196. package/dist/tools.js +2 -2
  197. package/dist/trigger-launch-hook.d.ts +19 -9
  198. package/dist/trigger-launch-hook.js +35 -25
  199. package/dist/trigger-targets.d.ts +18 -8
  200. package/dist/trigger-targets.js +42 -19
  201. package/dist/triggers.d.ts +85 -23
  202. package/dist/triggers.js +303 -96
  203. package/dist/validate.d.ts +1 -1
  204. package/dist/validate.js +2 -2
  205. package/dist/web-fake.js +3 -3
  206. package/dist/web-fetch-direct.d.ts +4 -0
  207. package/dist/web-fetch-direct.js +8 -1
  208. package/dist/web-fetch.d.ts +12 -3
  209. package/dist/web-fetch.js +47 -14
  210. package/dist/web-search.d.ts +33 -4
  211. package/dist/web-search.js +100 -41
  212. package/dist/webhooks.js +4 -5
  213. package/dist/workspace/synced-folder.d.ts +1 -1
  214. package/dist/workspace/synced-folder.js +11 -14
  215. package/launcher/agentrun-serve +5 -1
  216. package/package.json +17 -13
  217. package/templates/README.md +5 -4
  218. package/templates/agent-scout/agent.md +46 -0
  219. package/templates/agent-scout/skills/scout/SKILL.md +88 -0
  220. package/templates/agent-scout/skills/scout/suggestions.schema.json +112 -0
  221. package/dist/console/assets/index-BFgyZzF_.js +0 -734
  222. package/dist/console/assets/index-DbilxljH.css +0 -1
  223. package/dist/import-sources.d.ts +0 -116
  224. package/dist/import-sources.js +0 -693
@@ -22,6 +22,17 @@ export declare const keyBytes: (value: string) => number;
22
22
  export declare const secretForms: (value: string) => string[];
23
23
  /** The signature header of `body`, sent as message `id` at `timestamp` (Unix seconds), under `secret` (`whsec_...`). */
24
24
  export declare const signatureOf: (secret: string, id: string, timestamp: string, body: string | Buffer) => string;
25
+ /** The headers of a signed POST of JSON `body` as message `id`, stamped `timestamp` (Unix seconds, from the sender's own
26
+ * clock) and signed with `secret`, sent as `agent`: the outbound webhook's and the launch hook's. */
27
+ export declare const signedRequest: (secret: string, id: string, timestamp: string, body: string, agent: string) => Record<string, string>;
28
+ /** What a receiver's answer `res` says, its body never read: undefined for a 2xx, else why it did not land ("answered
29
+ * 503"; a redirect is not followed). */
30
+ export declare function answerOf(res: {
31
+ readonly status: number;
32
+ readonly body: {
33
+ cancel(): Promise<void>;
34
+ } | null;
35
+ }): Promise<string | undefined>;
25
36
  /** Why a request's webhook headers are refused before its body is read, or undefined when they may be checked:
26
37
  * present, a webhook-id of printable ASCII, a bounded signature list, a timestamp within HOOK_TOLERANCE_S. */
27
38
  export declare function headersRefusal(headers: Record<string, string | string[] | undefined>, nowMs: number): string | undefined;
@@ -1,7 +1,8 @@
1
1
  // The Standard Webhooks spec (standardwebhooks.com), once, for every message this server signs and every request it
2
2
  // checks: a secret is `whsec_` and its bytes in base64, and a signature is `v1,<base64 HMAC-SHA256 of
3
- // "{id}.{timestamp}.{body}">` under those bytes. The outbound webhook (webhooks.ts) signs with it; a pushed trigger
4
- // source (the webhook trigger) verifies with it.
3
+ // "{id}.{timestamp}.{body}">` under those bytes. The outbound webhook (webhooks.ts) and the launch hook
4
+ // (trigger-launch-hook.ts) sign with it and read their receiver's answer the same way; a pushed trigger source (the
5
+ // webhook trigger) verifies with it.
5
6
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
6
7
  /** How far a request's `webhook-timestamp` may be from this server's clock, either way. */
7
8
  export const HOOK_TOLERANCE_S = 300;
@@ -41,6 +42,23 @@ export const secretForms = (value) => {
41
42
  };
42
43
  /** The signature header of `body`, sent as message `id` at `timestamp` (Unix seconds), under `secret` (`whsec_...`). */
43
44
  export const signatureOf = (secret, id, timestamp, body) => `v1,${hmacOf(secret, id, timestamp, body).toString("base64")}`;
45
+ /** The headers of a signed POST of JSON `body` as message `id`, stamped `timestamp` (Unix seconds, from the sender's own
46
+ * clock) and signed with `secret`, sent as `agent`: the outbound webhook's and the launch hook's. */
47
+ export const signedRequest = (secret, id, timestamp, body, agent) => ({
48
+ "content-type": "application/json",
49
+ "user-agent": agent,
50
+ "webhook-id": id,
51
+ "webhook-timestamp": timestamp,
52
+ "webhook-signature": signatureOf(secret, id, timestamp, body),
53
+ });
54
+ /** What a receiver's answer `res` says, its body never read: undefined for a 2xx, else why it did not land ("answered
55
+ * 503"; a redirect is not followed). */
56
+ export async function answerOf(res) {
57
+ await res.body?.cancel().catch(() => undefined);
58
+ if (res.status >= 200 && res.status <= 299)
59
+ return undefined;
60
+ return res.status >= 300 && res.status < 400 ? `answered ${res.status}: a redirect is not followed` : `answered ${res.status}`;
61
+ }
44
62
  /** Why a request's webhook headers are refused before its body is read, or undefined when they may be checked:
45
63
  * present, a webhook-id of printable ASCII, a bounded signature list, a timestamp within HOOK_TOLERANCE_S. */
46
64
  export function headersRefusal(headers, nowMs) {
@@ -95,7 +95,7 @@ export type AgenticBody = {
95
95
  approvals?: "ask" | "never";
96
96
  inputSchema?: Record<string, unknown>;
97
97
  outputSchema?: Record<string, unknown>;
98
- checkout?: "pull_request";
98
+ checkout?: "pull_request" | "repository";
99
99
  };
100
100
  export type WorkflowBody = {
101
101
  workflow: Record<string, unknown>;
@@ -134,7 +134,7 @@ export type RevisionBodyInput = {
134
134
  approvals?: "ask" | "never";
135
135
  inputSchema?: Record<string, unknown>;
136
136
  outputSchema?: Record<string, unknown>;
137
- checkout?: "pull_request";
137
+ checkout?: "pull_request" | "repository";
138
138
  } | {
139
139
  kind: "workflow";
140
140
  workflow: unknown;
@@ -144,8 +144,8 @@ export function bodyOf(input) {
144
144
  invalid("the inputSchema is not a JSON object");
145
145
  if (input.outputSchema !== undefined && !isObject(input.outputSchema))
146
146
  invalid("the outputSchema is not a JSON object");
147
- if (input.checkout !== undefined && input.checkout !== "pull_request")
148
- invalid("the checkout is not pull_request");
147
+ if (input.checkout !== undefined && input.checkout !== "pull_request" && input.checkout !== "repository")
148
+ invalid("the checkout is not pull_request or repository");
149
149
  if (input.modelTiers !== undefined && !(isObject(input.modelTiers) && Object.keys(input.modelTiers).length && Object.entries(input.modelTiers).every(([tier, ref]) => (tier === "fast" || tier === "strong") && typeof ref === "string" && ref !== "")))
150
150
  invalid("the modelTiers are not fast and strong to a non-empty model");
151
151
  if (input.sdk !== undefined && (!isObject(input.sdk) || Object.keys(input.sdk).some(key => key !== "runtime" && key !== "platform") || !sdkBindingOf(input.sdk)))
@@ -1,5 +1,5 @@
1
1
  export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
2
- export type { ConstraintRule, SettingsGuard, McpGuard, AgentRow, Agents, AlsoRow, AttemptCause, ChannelPost, Claim, Command, ComputerIntervalRow, ComputerIntervals, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunAttemptRow, RunAttempts, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, StoreSchemaState, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, PurgeKept, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
2
+ export type { ConstraintRule, SettingsGuard, McpGuard, AgentRow, Agents, AlsoRow, AttemptCause, ChannelPost, Claim, Command, ComputerIntervalRow, ComputerIntervals, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpTokensMark, McpOwnersMark, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunAttemptRow, RunAttempts, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, StoreSchemaState, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, PurgeKept, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
3
3
  export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunLaunch, openRunMcpAuth, type RunLaunchSecrets, type ComposioBinding, type RunMcpAuth, type RunMcpEntry, type RunModelKey, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, type AgenticBody, bodyOf, canonical, isObject, isSkillPath, type PromptVariant, type ModelTiers, type MonidPinBody, type RevisionBodyInput, type RevisionComputer, type RevisionPlace, sha256, type ToolSettings, type WorkflowBody, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
@@ -487,8 +487,11 @@ export const STORE_DDL = [
487
487
  // Triggers (module E's), their scopes (rows only while enabled), firings, conversations and adapter settings. A trigger's
488
488
  // firings are one table: its history (shown 1, the newest HISTORY_KEPT), the due queue, and the keys kept only for their
489
489
  // day (shown 0: a run now's or a delivery's, an ignored delivery's included). A due firing keeps its next try in
490
- // retry_at under the engine's one backoff table, or waits for its trigger's room (waits_on: the run it waits behind).
491
- // max_active_runs: the most of the trigger's started runs not yet ended (a JOIN on runs), none past it.
490
+ // retry_at under the engine's one backoff table, or waits for its trigger's room (waits_on: what it waits behind, a run's
491
+ // id, or a firing's key while the trigger has no run yet and a firing its launch hook's host took, or one mid-hand,
492
+ // holds the room). retry_at also keeps a sent firing's start_by: the time until which that host may start its run.
493
+ // max_active_runs: the most of the trigger's runs in progress (started and not yet ended, a JOIN on runs, or a sent
494
+ // firing with no run inside its start_by), none past it.
492
495
  `CREATE TABLE IF NOT EXISTS triggers (
493
496
  id TEXT PRIMARY KEY,
494
497
  agent_id TEXT NOT NULL REFERENCES agents (id),
@@ -113,6 +113,13 @@ const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, pac
113
113
  const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
114
114
  const TRIGGER_COLUMNS = "id, agent_id, name, enabled, source, target, next_at, last_run_id, catchup_window_s, failures_in_a_row, disabled, max_active_runs, created_at, updated_at, template_id";
115
115
  const FINAL = FINAL_STATES.map((state) => `'${state}'`).join(", ");
116
+ /** Firing `f` (the alias) is one its launch hook's host took with no run yet, inside its start window: its startBy, kept in
117
+ * retry_at, not passed at the `?` it binds (the triggers' clock). It holds its trigger's room as a run in progress
118
+ * (activeKeys, waiting's free, held) and stays in the history (prune). */
119
+ const holdsRoom = (f) => `(${f}.status = 'sent' AND ${f}.run_id IS NULL AND ${f}.retry_at IS NOT NULL AND ${f}.retry_at >= ?)`;
120
+ /** Firing `f` is one of its trigger's runs in progress: started with run `r` (the alias of its LEFT JOINed run) not ended,
121
+ * or holding the room (holdsRoom, its one `?`). */
122
+ const inProgress = (f, r) => `((${f}.status = 'started' AND ${r}.state NOT IN (${FINAL})) OR ${holdsRoom(f)})`;
116
123
  /** An ended run, not imported, whose stored cost is unknown: null with no bound beside it (cost_upper_bound 0, never NULL).
117
124
  * What Runs.healCost writes over and Runs.costUnknown lists. */
118
125
  const COST_UNKNOWN = `cost_usd IS NULL AND cost_upper_bound = 0 AND state IN (${FINAL}) AND imported_from IS NULL AND ended_at IS NOT NULL`;
@@ -902,17 +909,17 @@ class SqliteStore {
902
909
  // The uploads it was applied from, each gone unless another agent not purged was applied from it too: nothing
903
910
  // else owns one, and a server that serves no template route (API-only) could never remove it. Each is held by its
904
911
  // id, in order, before it is read: two purges of agents applied from one upload read it in turn, so the later
905
- // reads the earlier's purge (committed) and removes the upload.
912
+ // reads the earlier's purge (committed) and removes the upload. Only the package it was applied from goes, by its
913
+ // sha too: a newer upload of the same name, which another deploy has yet to apply, stays.
906
914
  const packageId = (alias) => d.jsonText(`${alias}.package`, ["id"]);
907
- const applied = (await tx.all(`SELECT DISTINCT ${packageId("r")} AS id FROM revisions r WHERE r.agent_id = ? AND r.package IS NOT NULL`, agentId))
908
- .map((row) => row.id)
909
- .filter((id) => id !== null && id.startsWith(UPLOAD_PREFIX))
910
- .sort();
911
- for (const id of applied) {
915
+ const applied = (await tx.all(`SELECT DISTINCT ${packageId("r")} AS id, ${d.jsonText("r.package", ["sha"])} AS sha FROM revisions r WHERE r.agent_id = ? AND r.package IS NOT NULL`, agentId))
916
+ .filter((row) => row.id !== null && row.id.startsWith(UPLOAD_PREFIX) && row.sha !== null)
917
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
918
+ for (const { id, sha } of applied) {
912
919
  await d.lockKey(tx, `imported_templates:${id}`);
913
920
  const kept = await tx.get(`SELECT r.id FROM revisions r JOIN agents a ON a.id = r.agent_id WHERE r.agent_id <> ? AND a.purged_at IS NULL AND ${packageId("r")} = ? LIMIT 1`, agentId, id);
914
921
  if (!kept)
915
- await tx.run("DELETE FROM imported_templates WHERE id = ?", id);
922
+ await tx.run("DELETE FROM imported_templates WHERE id = ? AND sha = ?", id, sha);
916
923
  }
917
924
  // Each revision's content; its id, kind, parent and time stay, which its runs' tombstones name.
918
925
  await tx.run("UPDATE revisions SET body = '{}', skills = NULL, package = NULL, note = NULL, mcp_pin = NULL, monid_pin = NULL WHERE agent_id = ?", agentId);
@@ -1046,7 +1053,12 @@ class SqliteStore {
1046
1053
  const at = now();
1047
1054
  await d.lockRow(tx, "triggers", "id", triggerId);
1048
1055
  const was = await tx.get(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE trigger_id = ? AND key = ?`, triggerId, key);
1049
- if (!was)
1056
+ if (!was || (change.from !== undefined && was.status !== change.from))
1057
+ return undefined;
1058
+ // holdsAt: holdsRoom's own predicate, at that time.
1059
+ if (change.holdsAt !== undefined && !(was.status === "sent" && was.run_id === null && was.retry_at !== null && was.retry_at >= change.holdsAt))
1060
+ return undefined;
1061
+ if (change.startByWas !== undefined && !(was.status === "sent" && was.run_id === null && was.retry_at === change.startByWas))
1050
1062
  return undefined;
1051
1063
  const settled = change.status !== undefined && change.status !== "due";
1052
1064
  // Out of due, a firing keeps no retry, wait, payload or attrs (unless keepAttrs), nor the reason its last try gave
@@ -1132,23 +1144,24 @@ class SqliteStore {
1132
1144
  wakeCommands(this.where, { runId, what: "written" });
1133
1145
  return sent;
1134
1146
  },
1135
- waiting: async () => (await db.all(`SELECT ${FIRING_COLUMNS.split(", ").map((c) => `f.${c}`).join(", ")},
1136
- (SELECT COUNT(*) FROM trigger_firings s JOIN runs r ON r.id = s.run_id
1137
- WHERE s.trigger_id = f.trigger_id AND s.status = 'started' AND r.state NOT IN (${FINAL})) < COALESCE(t.max_active_runs, 1) AS free
1147
+ waiting: async (clockNow) => (await db.all(`SELECT ${FIRING_COLUMNS.split(", ").map((c) => `f.${c}`).join(", ")},
1148
+ (t.max_active_runs IS NULL OR (SELECT COUNT(*) FROM trigger_firings s LEFT JOIN runs r ON r.id = s.run_id
1149
+ WHERE s.trigger_id = f.trigger_id AND ${inProgress("s", "r")}) < t.max_active_runs) AS free
1138
1150
  FROM trigger_firings f JOIN triggers t ON t.id = f.trigger_id
1139
- WHERE f.status = 'due' AND f.waits_on IS NOT NULL ORDER BY f.at, f.${d.firingOrder}`)).map((r) => ({ ...firingOf(r), free: r.free === 1 || r.free === true })),
1151
+ WHERE f.status = 'due' AND f.waits_on IS NOT NULL ORDER BY f.at, f.${d.firingOrder}`, clockNow)).map((r) => ({ ...firingOf(r), free: r.free === 1 || r.free === true })),
1140
1152
  soonest: async () => (await db.get("SELECT MIN(next_at) AS at FROM triggers WHERE enabled = 1 AND next_at IS NOT NULL"))?.at ?? null,
1141
- activeRuns: async (triggerId) => (await db.get(`SELECT COUNT(*) AS n FROM trigger_firings f JOIN runs r ON r.id = f.run_id WHERE f.trigger_id = ? AND f.status = 'started' AND r.state NOT IN (${FINAL})`, triggerId)).n,
1153
+ activeKeys: async (triggerId, clockNow) => (await db.all(`SELECT f.key FROM trigger_firings f LEFT JOIN runs r ON r.id = f.run_id WHERE f.trigger_id = ? AND ${inProgress("f", "r")}`, triggerId, clockNow)).map((r) => r.key),
1154
+ held: async (triggerId, clockNow) => (await db.get(`SELECT f.key FROM trigger_firings f WHERE f.trigger_id = ? AND ${holdsRoom("f")} ORDER BY f.at DESC, f.${d.firingOrder} DESC LIMIT 1`, triggerId, clockNow))?.key,
1142
1155
  prune: async (triggerId, { history, dayMs, keepByKey, kept, now: clockNow }) => db.transaction(async (tx) => {
1143
1156
  const at = now();
1144
1157
  await d.lockRow(tx, "triggers", "id", triggerId);
1145
1158
  // Past the newest `history` shown firings: never a due one, a failure not yet told, a started one whose run has
1146
- // not ended, or a sent one its host may still start (its startBy, in retry_at, not passed on the triggers'
1147
- // clock). The rest leave the history: kept for their key's day when a sender's key names them, else gone.
1159
+ // not ended, or a sent one its host may still start (holdsRoom). The rest leave the history: kept for their
1160
+ // key's day when a sender's key names them, else gone.
1148
1161
  const old = await tx.all(`SELECT f.key, f.by FROM trigger_firings f LEFT JOIN runs r ON r.id = f.run_id
1149
1162
  WHERE f.trigger_id = ? AND f.shown = 1 AND f.status != 'due' AND NOT (f.status = 'failed' AND (f.notified IS NULL OR f.notified = 0))
1150
1163
  AND NOT (f.status = 'started' AND r.id IS NOT NULL AND r.state NOT IN (${FINAL}))
1151
- AND NOT (f.status = 'sent' AND f.retry_at IS NOT NULL AND f.retry_at >= ?)
1164
+ AND NOT ${holdsRoom("f")}
1152
1165
  AND f.key NOT IN (SELECT key FROM trigger_firings WHERE trigger_id = ? AND shown = 1 ORDER BY at DESC, ${d.firingOrder} DESC LIMIT ?)`, triggerId, clockNow, triggerId, history);
1153
1166
  for (const { key, by } of old) {
1154
1167
  if (keepByKey(by ?? "manual"))
@@ -1598,9 +1611,39 @@ class SqliteStore {
1598
1611
  return updated;
1599
1612
  },
1600
1613
  };
1614
+ /** The WHERE term of the API token's write over a saved row (McpTokensMark), its one `?` the source record's key: that
1615
+ * setting still says the token saved this very row (`by` token, `of` the row's created_at). In the statement that
1616
+ * writes or removes the row, so an owner's save, which drops the mark in the transaction that writes its row
1617
+ * (dropTokensMark), never lands in between. */
1618
+ const recordJson = readableJson(d, "settings.value");
1619
+ const tokensMarked = `EXISTS (SELECT 1 FROM settings WHERE settings.key = ? AND ${d.jsonText(recordJson, ["by"])} = 'token' AND ${d.jsonValue(recordJson, ["of"])} = CAST(mcp_servers.created_at AS TEXT))`;
1620
+ /** A write of the saved server `name` that the token's mark decides (McpTokensMark, McpOwnersMark): one transaction that
1621
+ * first holds the server's lock. SQLite's one writer holds it already; on Postgres it makes the token's statement wait
1622
+ * for the owner's transaction to end, so the statement reads the record as that transaction left it (READ COMMITTED
1623
+ * takes each statement's snapshot when it starts, after the lock). */
1624
+ const underMcpLock = (name, work) => db.transaction(async (tx) => {
1625
+ await d.lockKey(tx, `mcp_servers:${name}`);
1626
+ return work(tx);
1627
+ });
1628
+ /** In the owner's write's transaction, once its row is written (McpOwnersMark): the record at `record` loses the token's
1629
+ * mark (`by`) when it still says the token saved that very row (`of` its created_at); the rest of it is kept, as
1630
+ * mcp-sources.ts ownersRecord writes it. Any other record is left as it is. */
1631
+ const dropTokensMark = async (tx, { record }, createdAt) => {
1632
+ const found = await tx.get("SELECT value FROM settings WHERE key = ?", record);
1633
+ const value = found === undefined ? undefined : JSON.parse(found.value);
1634
+ if (typeof value !== "object" || value === null || Array.isArray(value))
1635
+ return;
1636
+ const { by, ...owners } = value;
1637
+ if (by !== "token" || owners.of !== createdAt)
1638
+ return;
1639
+ const encoded = json(owners);
1640
+ await tx.run("UPDATE settings SET value = ?, connector_id = ?, updated_at = ? WHERE key = ?", encoded, nativeCommandOwner(record, encoded), now(), record);
1641
+ };
1601
1642
  /** A server's write (Mcp.put), or with `expected` (Mcp.putIfCredential) only while the row's credential is still that:
1602
- * the statement's own WHERE compares it, so the comparison and the write are one statement. */
1603
- const putServer = async ({ name, url, auth, protocol = null, tools, prices = null, serverInfo = null, instructions = null, sealed = null, listedAt, updatedAt, credentialChangedAt, tokenLeftMs = null }, expected) => {
1643
+ * the statement's own WHERE compares it, so the comparison and the write are one statement. `tokens`: over a saved
1644
+ * row, only while it still carries the token's mark, compared there too (a new row has none to carry). `owns`: the
1645
+ * owner's write, dropping the token's mark in its transaction once the row is written. */
1646
+ const putServer = async ({ name, url, auth, protocol = null, tools, prices = null, serverInfo = null, instructions = null, sealed = null, listedAt, updatedAt, credentialChangedAt, tokenLeftMs = null }, expected, tokens, owns) => {
1604
1647
  const at = now();
1605
1648
  // The access token's end on the deadlines' clock (the database's on Postgres): the writer's measure of its life (a
1606
1649
  // duration, clock-free) laid on that clock's now (token_until), in the statement that writes it.
@@ -1620,9 +1663,9 @@ class SqliteStore {
1620
1663
  ? {
1621
1664
  sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, sealed = ?, refresh_holder = NULL, refresh_until = NULL,
1622
1665
  updated_at = ?, listed_at = ?, credential_changed_at = ?, token_until = ${stamp.sql} + ${d.bigintParam}
1623
- WHERE name = ? AND auth = ? AND sealed IS ${expected.sealed ? "NOT NULL" : "NULL"} AND ${expected.changedAt === null ? "credential_changed_at IS NULL" : "credential_changed_at = ?"}
1666
+ WHERE name = ? AND auth = ? AND sealed IS ${expected.sealed ? "NOT NULL" : "NULL"} AND ${expected.changedAt === null ? "credential_changed_at IS NULL" : "credential_changed_at = ?"}${tokens ? ` AND ${tokensMarked}` : ""}
1624
1667
  RETURNING ${mcpServerColumnsAt(stamp)}`,
1625
- params: [...values, updated, listed, credentialAt, ...stamp.params, left, name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt]), ...stamp.params],
1668
+ params: [...values, updated, listed, credentialAt, ...stamp.params, left, name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt]), ...(tokens ? [tokens.record] : []), ...stamp.params],
1626
1669
  }
1627
1670
  : {
1628
1671
  sql: `INSERT INTO mcp_servers (name, url, auth, protocol, tools, prices, server_info, instructions, sealed, created_at, updated_at, listed_at, credential_changed_at, token_until) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ${stamp.sql} + ${d.bigintParam})
@@ -1632,10 +1675,22 @@ class SqliteStore {
1632
1675
  RETURNING ${mcpServerColumnsAt(stamp)}`,
1633
1676
  params: [name, ...values, at, updated, listed, credentialAt, ...stamp.params, left, ...stamp.params],
1634
1677
  };
1635
- const [result] = await db.write([statement]);
1636
- const written = result.rows[0];
1678
+ const written = await writeMcpRow(name, statement, tokens, owns);
1637
1679
  return written && mcpServerOf(written);
1638
1680
  };
1681
+ /** `statement`, the write of server `name`'s row, answering the row it wrote (RETURNING): alone, or, when the token's mark
1682
+ * decides it (`tokens`, `owns`), in one transaction under the server's lock (underMcpLock), the owner's dropping the
1683
+ * mark once its row is written and only then. */
1684
+ const writeMcpRow = async (name, statement, tokens, owns) => {
1685
+ if (!tokens && !owns)
1686
+ return (await db.write([statement]))[0].rows[0];
1687
+ return underMcpLock(name, async (tx) => {
1688
+ const row = (await tx.step(statement)).rows[0];
1689
+ if (row && owns)
1690
+ await dropTokensMark(tx, owns, mcpServerOf(row).createdAt);
1691
+ return row;
1692
+ });
1693
+ };
1639
1694
  const server = async (executor, name) => {
1640
1695
  const at = clock();
1641
1696
  const row = await executor.get(`SELECT ${mcpServerColumnsAt(at)} FROM mcp_servers WHERE name = ?`, ...at.params, name);
@@ -1643,30 +1698,31 @@ class SqliteStore {
1643
1698
  };
1644
1699
  this.mcp = {
1645
1700
  put: async (row) => (await putServer(row, undefined)),
1646
- putIfCredential: (row, expected) => putServer(row, expected),
1701
+ putIfCredential: (row, expected, tokens, owns) => putServer(row, expected, tokens, owns),
1647
1702
  // One statement compares the credential and writes, as keepRefreshed: no read between, so a refresh's keep never lands
1648
1703
  // in a gap and is then written over. The credential's columns and the refresh lease are not in its SET.
1649
- rewrite: async ({ name, url, auth, protocol = null, tools, prices = null, serverInfo = null, instructions = null, listedAt, updatedAt }, seen) => {
1704
+ rewrite: async ({ name, url, auth, protocol = null, tools, prices = null, serverInfo = null, instructions = null, listedAt, updatedAt }, seen, owns) => {
1650
1705
  const at = now();
1651
1706
  const stamp = clock();
1652
- const [result] = await db.write([{
1653
- sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, updated_at = ?, listed_at = ?
1707
+ const row = await writeMcpRow(name, {
1708
+ sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, updated_at = ?, listed_at = ?
1654
1709
  WHERE name = ? AND ${d.nullSafeEquals("sealed")}
1655
1710
  RETURNING ${mcpServerColumnsAt(stamp)}`,
1656
- params: [url, auth, protocol, json(tools), json(prices), serverInfo === null ? null : json(serverInfo), instructions, updatedAt ?? at, listedAt ?? at, name, seen, ...stamp.params],
1657
- }]);
1658
- const row = result.rows[0];
1711
+ params: [url, auth, protocol, json(tools), json(prices), serverInfo === null ? null : json(serverInfo), instructions, updatedAt ?? at, listedAt ?? at, name, seen, ...stamp.params],
1712
+ }, undefined, owns);
1659
1713
  return row && mcpServerOf(row);
1660
1714
  },
1661
1715
  remove: async (name) => {
1662
1716
  const [result] = await db.write([{ sql: "DELETE FROM mcp_servers WHERE name = ? RETURNING url, sealed", params: [name] }]);
1663
1717
  return removedOf(result.rows[0]);
1664
1718
  },
1665
- removeIfCredential: async (name, expected) => {
1666
- const [result] = await db.write([{
1667
- sql: `DELETE FROM mcp_servers WHERE name = ? AND auth = ? AND sealed IS ${expected.sealed ? "NOT NULL" : "NULL"} AND ${expected.changedAt === null ? "credential_changed_at IS NULL" : "credential_changed_at = ?"} RETURNING url, sealed`,
1668
- params: [name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt])],
1669
- }]);
1719
+ removeIfCredential: async (name, expected, tokens) => {
1720
+ const statement = {
1721
+ sql: `DELETE FROM mcp_servers WHERE name = ? AND auth = ? AND sealed IS ${expected.sealed ? "NOT NULL" : "NULL"} AND ${expected.changedAt === null ? "credential_changed_at IS NULL" : "credential_changed_at = ?"}${tokens ? ` AND ${tokensMarked}` : ""} RETURNING url, sealed`,
1722
+ params: [name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt]), ...(tokens ? [tokens.record] : [])],
1723
+ };
1724
+ // The token's removal under the server's lock (underMcpLock): after an owner's write and its record, never between.
1725
+ const [result] = tokens ? [await underMcpLock(name, (tx) => tx.step(statement))] : await db.write([statement]);
1670
1726
  return removedOf(result.rows[0]);
1671
1727
  },
1672
1728
  servers: async () => {
@@ -110,7 +110,7 @@ export interface TemplatePackage {
110
110
  /** The names of the keys the package declared (its `secrets`, and those of the model choice the apply took), sorted,
111
111
  * never their values: what an export of the agent names, whatever version of the package the server holds later, and
112
112
  * the tool keys a run of the revision may carry (run-keys.ts; under the run-keys setting one that does not is refused).
113
- * Absent on a revision applied before it was kept. */
113
+ * Every apply writes it. */
114
114
  readonly secrets?: readonly string[];
115
115
  }
116
116
  export interface NewRevision {
@@ -643,7 +643,8 @@ export interface Firing {
643
643
  }
644
644
  export type FiringStatus = "due" | "started" | "sent" | "skipped" | "failed" | "missed" | "ignored";
645
645
  /** A trigger's firing as its row keeps it. `shown`: in the trigger's history (the newest HISTORY_KEPT); false, kept only
646
- * for its key's day. `retryAt`: a due firing's next try; `waitsOn`: the run whose turn end wakes a due firing.
646
+ * for its key's day. `retryAt`: a due firing's next try; `waitsOn`: what a due firing waits behind for its trigger's
647
+ * room, a run's id, or a firing's key while the trigger has no run yet (triggers.ts busy).
647
648
  * `startBy`: a firing its launch hook's host took with no run (sent), the time until which the host may still start
648
649
  * its run (triggers.ts handedStart); null on any other. */
649
650
  export interface FiringRow {
@@ -733,6 +734,17 @@ export interface FiringChange {
733
734
  * in the firing's retry_at column, which only a due firing holds otherwise, and is never read back as a retry. Any
734
735
  * other status keeps none. */
735
736
  readonly startBy?: number;
737
+ /** Written only while the firing's status is this one, read in the settle's own transaction: a firing whose host's run
738
+ * started it meanwhile (triggers.ts handedRan) is left as it is, and nothing is written. */
739
+ readonly from?: FiringStatus;
740
+ /** Written only while the firing holds its trigger's room at this time (the triggers' clock): sent with no run, its
741
+ * startBy not passed. Read in the settle's own transaction: a host start that pushes a startBy out (triggers.ts
742
+ * handedStart) leaves a firing whose window closed, or whose run started, meanwhile as it is. */
743
+ readonly holdsAt?: number;
744
+ /** Written only while the firing is sent with no run and its startBy is still this one, read in the settle's own
745
+ * transaction: a host start that pushed a startBy out and wrote no run puts it back (triggers.ts handedStart), unless
746
+ * its run started, or another start moved it, meanwhile. */
747
+ readonly startByWas?: number;
736
748
  }
737
749
  /** What a settle does to the firing's trigger besides: `reset` its failure streak (a run started, a message sent), or
738
750
  * count a `failure` toward it, turning it off at `pauseAt` in a row (auto-pause, the firing marked paused). */
@@ -944,7 +956,8 @@ export interface Triggers {
944
956
  /** The trigger's history, newest first: its shown firings. */
945
957
  firings(triggerId: string): Promise<FiringRow[]>;
946
958
  /** The firing changed (with its trigger's last_run_id moved to a newer run it names, and `streak`), in one transaction:
947
- * undefined when the firing is gone (its trigger deleted). `paused`: this failure turned the trigger off. */
959
+ * undefined when the firing is gone (its trigger deleted), or is no longer the change's `from`. `paused`: this failure
960
+ * turned the trigger off. */
948
961
  settle(triggerId: string, key: string, change: FiringChange, streak?: FiringStreak): Promise<{
949
962
  firing: FiringRow;
950
963
  paused: boolean;
@@ -971,15 +984,21 @@ export interface Triggers {
971
984
  } | {
972
985
  skipped: string;
973
986
  } | undefined>;
974
- /** Every due firing waiting for its trigger's room (waits_on), oldest first, each with whether the room is there now
975
- * (fewer of its trigger's started runs not ended than its max_active_runs): one read for all of them. */
976
- waiting(): Promise<(FiringRow & {
987
+ /** Every due firing waiting for its trigger's room (waits_on), oldest first, each with whether the room is there at
988
+ * `now` (the triggers' clock): fewer of its trigger's runs in progress (activeKeys) than its max_active_runs, or no
989
+ * max_active_runs (cleared while the firing waited: the engine's own check decides). One read for all of them. */
990
+ waiting(now: number): Promise<(FiringRow & {
977
991
  readonly free: boolean;
978
992
  })[]>;
979
993
  /** The soonest next time of an enabled trigger, or null. */
980
994
  soonest(): Promise<number | null>;
981
- /** How many of the trigger's started runs have not ended (a run reopened later does not count). */
982
- activeRuns(triggerId: string): Promise<number>;
995
+ /** The keys of the trigger's firings in progress at `now` (the triggers' clock), in no order: started with a run not
996
+ * ended (a run reopened later does not count), or held, a firing its launch hook's host took with no run yet up to its
997
+ * startBy. max_active_runs counts them. */
998
+ activeKeys(triggerId: string, now: number): Promise<string[]>;
999
+ /** The newest of the trigger's firings that hold its room at `now` (taken by its launch hook's host with no run yet, its
1000
+ * startBy not passed): its key, or undefined. */
1001
+ held(triggerId: string, now: number): Promise<string | undefined>;
983
1002
  /** The history kept to `history` shown firings: older ones a sender's key names (manual, pushed) are kept for their day
984
1003
  * (shown 0), others removed; shown-0 rows past `dayMs` removed, then the oldest past `kept` of them. Never a due
985
1004
  * firing, a failure not yet told, a started firing whose run has not ended, nor a sent one whose startBy is not before
@@ -1389,6 +1408,22 @@ export type McpServerWrite = {
1389
1408
  credentialChangedAt?: number | null;
1390
1409
  tokenLeftMs?: number | null;
1391
1410
  };
1411
+ /** The API token's mark a write over a saved server's row needs, compared in the statement that writes or removes the row:
1412
+ * the setting at `record` (the server's source record, mcp-sources.ts) still says `by: "token"` for that very row (its
1413
+ * `of` is the row's created_at). An owner's save drops the mark in the transaction that writes its row (McpOwnersMark),
1414
+ * so a write that needs the mark never lands over the owner's save, whenever that save lands. The write that needs it
1415
+ * takes the server's lock first, so on Postgres its statement reads the record as the owner's committed transaction left
1416
+ * it. */
1417
+ export type McpTokensMark = {
1418
+ readonly record: string;
1419
+ };
1420
+ /** The owner's write over a saved server's row: in the transaction that writes the row, and only once the row is written,
1421
+ * the setting at `record` (the server's source record) loses the API token's mark (`by`) when it still says the token
1422
+ * saved that very row. A write refused (no row) leaves the record as it was, so a refused owner's save never takes the
1423
+ * server from the token; one that lands makes it the owner's with no moment between its row and its record. */
1424
+ export type McpOwnersMark = {
1425
+ readonly record: string;
1426
+ };
1392
1427
  export interface Mcp {
1393
1428
  /** The server's write: the server's row, inserted or replaced by name (its first save's time kept). An owner's save
1394
1429
  * clears any refresh lease and changes the credential, so a refresh in flight is dropped (keepRefreshed's `kept: false`)
@@ -1397,14 +1432,17 @@ export interface Mcp {
1397
1432
  put(server: McpServerWrite): Promise<McpServerRow>;
1398
1433
  /** put(), only while the server's credential is still `expected` (its mark as the writer read it; null: no server by
1399
1434
  * that name), compared and written in one statement: no other write lands between. Undefined, writing nothing, when
1400
- * it is not. */
1401
- putIfCredential(server: McpServerWrite, expected: McpCredentialMark): Promise<McpServerRow | undefined>;
1435
+ * it is not. `tokens`: the API token's write over a saved row, which lands only while the row still carries the
1436
+ * token's mark (McpTokensMark), in the same statement. `owns`: the owner's write, which drops the token's mark in the
1437
+ * same transaction once the row is written (McpOwnersMark). */
1438
+ putIfCredential(server: McpServerWrite, expected: McpCredentialMark, tokens?: McpTokensMark, owns?: McpOwnersMark): Promise<McpServerRow | undefined>;
1402
1439
  /** An owner's rewrite of a row it read, its credential kept as it is (a tools refresh, a save that sends no new
1403
1440
  * credential): the listing, prices, url and times written by a compare-and-set on the CREDENTIAL, iff the row is still
1404
1441
  * saved and its sealed value is still `seen` (the one the owner read). The credential's columns (sealed, token_until,
1405
1442
  * credential_changed_at) and any refresh lease are left as they are, so a runner's refresh in flight still keeps its
1406
1443
  * set. undefined, writing nothing, when the credential changed meanwhile (a refresh kept a rotated set) or the row went:
1407
- * the caller reads it again and re-applies its change onto the fresh row, a bounded few times. */
1444
+ * the caller reads it again and re-applies its change onto the fresh row, a bounded few times. `owns`: as
1445
+ * putIfCredential's, the token's mark dropped in the same transaction once the row is written. */
1408
1446
  rewrite(server: {
1409
1447
  name: string;
1410
1448
  url: string;
@@ -1416,12 +1454,14 @@ export interface Mcp {
1416
1454
  instructions?: string | null;
1417
1455
  listedAt?: number;
1418
1456
  updatedAt?: number;
1419
- }, seen: Uint8Array | null): Promise<McpServerRow | undefined>;
1457
+ }, seen: Uint8Array | null, owns?: McpOwnersMark): Promise<McpServerRow | undefined>;
1420
1458
  /** Deletes the row, answering what it held as it went (McpRemoved); undefined when there was none. */
1421
1459
  remove(name: string): Promise<McpRemoved | undefined>;
1422
1460
  /** remove(), only while the server's credential is still `expected` (its mark as the remover read it), compared and
1423
- * deleted in one statement. Undefined, deleting nothing, when it is not (or the server is gone). */
1424
- removeIfCredential(name: string, expected: NonNullable<McpCredentialMark>): Promise<McpRemoved | undefined>;
1461
+ * deleted in one statement. Undefined, deleting nothing, when it is not (or the server is gone). `tokens`: the API
1462
+ * token's removal, which lands only while the row still carries the token's mark (McpTokensMark), in the same
1463
+ * statement. */
1464
+ removeIfCredential(name: string, expected: NonNullable<McpCredentialMark>, tokens?: McpTokensMark): Promise<McpRemoved | undefined>;
1425
1465
  /** The registry's rows, by name. */
1426
1466
  servers(): Promise<McpServerRow[]>;
1427
1467
  server(name: string): Promise<McpServerRow | undefined>;
@@ -2,6 +2,7 @@ import type { Context } from "@earendil-works/chord/context";
2
2
  import type { EntryLike, TimelineEvent, TimelineOptions } from "../timeline/index.js";
3
3
  import { Hearing } from "../heard.js";
4
4
  import { type Reflect } from "../reflect-range.js";
5
+ import { journalRecords } from "../runner/journal-reader.js";
5
6
  import type { Store } from "../store/store.js";
6
7
  /** A run's entries from the one store, in log order (by id across every conversation), as the old "SELECT record FROM
7
8
  * entries ORDER BY id" read them for a settled run. A run with no journal reads as none. */
@@ -10,6 +11,7 @@ export declare function runEntries(store: Store, runId: string, context: Context
10
11
  * `after`, the entry before its input, and `until`, the run's end entry once written; `earlier`, each earlier round's (a
11
12
  * follow-up opened the run again after it). Undefined for a run that asked none. */
12
13
  export declare function runReflect(store: Store, runId: string, context: Context): Promise<Pick<Reflect, "after" | "until" | "earlier"> | undefined>;
14
+ type Records = Awaited<ReturnType<typeof journalRecords>>;
13
15
  /** The CLI record (a harness whose own records are resume log only, record "loop": adapter-loop.ts openCliRecord) as the
14
16
  * pi-shaped entries the timeline renderer reads: a model message is an assistant turn, a person message a user turn, and a
15
17
  * tool call its assistant tool-call and its result. So a claude-agent / codex / opencode run reads the same rows, words
@@ -51,8 +53,10 @@ export declare function withoutFeedbackRounds<Row extends {
51
53
  * costIsBooked) has the usage row the renderer folds from its model turns put in its booking's words (bookedUsage): its
52
54
  * model requests at what the run's model proxy booked them at, and its paid tool calls at what they charged, as a pi
53
55
  * run's usage row counts them; its decisions' rows and cost come from their receipts (decision-rows.ts withDecisions),
54
- * once. The end-of-run turn's rows are labelled as the server labels them (reflect-range.ts labelled). */
55
- export declare function runTimeline(store: Store, runId: string, context: Context, options?: TimelineOptions): Promise<TimelineEvent[]>;
56
+ * once. The end-of-run turn's rows are labelled as the server labels them (reflect-range.ts labelled). Its journal is
57
+ * read once: `given`, the run's records as its caller read them (a view that says more of the same entries, its cost's
58
+ * `plan` among them, so both are of one read), else here. */
59
+ export declare function runTimeline(store: Store, runId: string, context: Context, options?: TimelineOptions, given?: Records): Promise<TimelineEvent[]>;
56
60
  /** The run's MCP tools called by a hashed wire name, by that name (hashedMcp over its pin): what its end's metrics count
57
61
  * each one's calls under its catalog name by (runner/metrics.ts runMetrics's `catalog`), as its timeline names them. */
58
62
  export declare const hashedMcpOf: (store: Store, runId: string) => Promise<ReadonlyMap<string, string>>;
@@ -83,3 +87,4 @@ export declare function wholeAnswers(store: Store, runId: string, context: Conte
83
87
  /** What was said to a run (its hearing), from the one store's entries, as runs.ts noteTurns fed it from the stream: each
84
88
  * user entry noted in log order, its origin read by the same matcher. */
85
89
  export declare function runHearing(store: Store, runId: string, context: Context): Promise<Hearing>;
90
+ export {};
@@ -22,9 +22,10 @@ import { Turns } from "../turns.js";
22
22
  /** A run's entries from the one store, in log order (by id across every conversation), as the old "SELECT record FROM
23
23
  * entries ORDER BY id" read them for a settled run. A run with no journal reads as none. */
24
24
  export async function runEntries(store, runId, context) {
25
- const entries = (await journalEntries(store.readJournal(runId), context));
26
- return entries.slice().sort((a, b) => Number(a.id ?? 0) - Number(b.id ?? 0));
25
+ return inLogOrder(await journalEntries(store.readJournal(runId), context));
27
26
  }
27
+ /** `entries` (a journal read's, conversation by conversation) in log order: by id across every conversation. */
28
+ const inLogOrder = (entries) => entries.slice().sort((a, b) => Number(a.id ?? 0) - Number(b.id ?? 0));
28
29
  /** Where a run's end-of-run turn is in its journal, as the server's Reflect names it for labelled(): its newest round's
29
30
  * `after`, the entry before its input, and `until`, the run's end entry once written; `earlier`, each earlier round's (a
30
31
  * follow-up opened the run again after it). Undefined for a run that asked none. */
@@ -208,11 +209,13 @@ export function withoutFeedbackRounds(rows) {
208
209
  * costIsBooked) has the usage row the renderer folds from its model turns put in its booking's words (bookedUsage): its
209
210
  * model requests at what the run's model proxy booked them at, and its paid tool calls at what they charged, as a pi
210
211
  * run's usage row counts them; its decisions' rows and cost come from their receipts (decision-rows.ts withDecisions),
211
- * once. The end-of-run turn's rows are labelled as the server labels them (reflect-range.ts labelled). */
212
- export async function runTimeline(store, runId, context, options = {}) {
213
- const entries = await runEntries(store, runId, context);
212
+ * once. The end-of-run turn's rows are labelled as the server labels them (reflect-range.ts labelled). Its journal is
213
+ * read once: `given`, the run's records as its caller read them (a view that says more of the same entries, its cost's
214
+ * `plan` among them, so both are of one read), else here. */
215
+ export async function runTimeline(store, runId, context, options = {}, given) {
216
+ const records = given ?? (await journalRecords(store.readJournal(runId), context));
217
+ const entries = inLogOrder(records.entries);
214
218
  const cli = isCliRecord(entries);
215
- const records = await journalRecords(store.readJournal(runId), context);
216
219
  const reflect = reflectOf(records);
217
220
  // A CLI names a file by its absolute path under its working directory (CallStartData.cwd): the rows name it by its
218
221
  // name in the workspace, never a path on the runner's machine. Its arguments, as the harness sent them, stay.
@@ -6,7 +6,7 @@ import { type PastRun, workflowCostsOf } from "../runner/workflow-first.js";
6
6
  import { type Reflect } from "../reflect-range.js";
7
7
  import type { EntryLike, TimelineEvent } from "../timeline/index.js";
8
8
  import type { AnalyticsFilter } from "./analytics.js";
9
- import { type PromotionRecord, type ResetRevision } from "../learn/promote.js";
9
+ import { type PromotionRecord, type Refused, type ResetRevision } from "../learn/promote.js";
10
10
  import type { LearningProposal, Store } from "../store/store.js";
11
11
  /** A run's learning end: the Learning fields its end sets. */
12
12
  export type RunLearningEnd = Learning;
@@ -91,8 +91,10 @@ export declare function agentLearningOverStore(store: Store, agentId: string): P
91
91
  * out. A run that learns whose record names no path (its end's patch was late or failed, or no runner wrote its end) is
92
92
  * left out too and counted (`unknown_path_runs`): its path and cost are not known, never `agent` at $0. `limit`: the
93
93
  * latest runs shown, each keeping its number; the summary is over every run; `bill` is the owner's bill over all of
94
- * them (billOf, with the revision ledger: agentLedgerOf). */
95
- export declare function agentCostOverStore(store: Store, agentId: string, limit?: number): Promise<{
94
+ * them (billOf, with the revision ledger: agentLedgerOf). Its champion skips what `refused` names of the agent's
95
+ * promotion records (purged-workflow.ts refusedOf, the purge gate's), as a run's claim does; absent, none. */
96
+ export type RefusedFor = (agentId: string, records: readonly PromotionRecord[]) => Promise<Refused>;
97
+ export declare function agentCostOverStore(store: Store, agentId: string, limit?: number, refused?: RefusedFor): Promise<{
96
98
  runs: CostRun[];
97
99
  summary: CostSummary;
98
100
  total_runs: number;
@@ -122,8 +124,9 @@ export type CompileSpend = {
122
124
  * (the bill's unattributed does). It is spread over its first K served runs (`workflow` or `handed_back` of its workflow
123
125
  * at its digest), K its check's compile_after; `state` from its newest record. A revision an earlier reset of the agent's
124
126
  * learning deleted (`reset`, learn/promote.ts keepResetLedger) is one too, first, stopped, at the K it was kept with,
125
- * unless the records name it again. */
126
- export declare function revisionLedgerOf(records: readonly PromotionRecord[], rows: readonly LedgerRow[], compiles?: readonly CompileSpend[], reset?: readonly ResetRevision[]): ReturnType<typeof amortize>;
127
+ * unless the records name it again. Serving is the champion's (championOf), skipping what `refused` names (the purge
128
+ * gate's), so a purged run's revision is never said to serve. */
129
+ export declare function revisionLedgerOf(records: readonly PromotionRecord[], rows: readonly LedgerRow[], compiles?: readonly CompileSpend[], reset?: readonly ResetRevision[], refused?: Refused): ReturnType<typeof amortize>;
127
130
  /** Run `runId`'s path and its costs as GET /runs/{id} shows them (A8): `path` its record's (metrics.path, RUN_PATHS:
128
131
  * `agent` for a run that does not learn; null while it has not ended, for a workflow revision's run, and for a run that
129
132
  * learns whose end named none); `usd` its own spend, the job's (runCostOf's `cost_usd`: its row's cost, `rowUsd` when
@@ -133,8 +136,8 @@ export declare function revisionLedgerOf(records: readonly PromotionRecord[], ro
133
136
  * spend is on the runs it serves, so its `learning_usd` and `all_in_usd` are 0, and the sum of every run's `all_in_usd`
134
137
  * and the bill's `unattributed_usd` is the booked total. While the run is at work `usd` is `rowUsd` and the rest null;
135
138
  * null while unknown (its shadow still at work, a compile's or a check's cost unknown), never $0. Undefined for an
136
- * unknown run. */
137
- export declare function runAllInOverStore(store: Store, runId: string, rowUsd?: number | null): Promise<{
139
+ * unknown run. Its revision's champion skips what `refused` names of the agent's promotion records (agentCostOverStore). */
140
+ export declare function runAllInOverStore(store: Store, runId: string, rowUsd?: number | null, refused?: RefusedFor): Promise<{
138
141
  path: RunPath | null;
139
142
  usd: number | null;
140
143
  learning_usd: number | null;
@@ -144,8 +147,8 @@ export declare function runAllInOverStore(store: Store, runId: string, rowUsd?:
144
147
  * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's check numbers
145
148
  * (the share of the inputs it ran on that said what the agent said, against the agent's own 100%). `cleared`: it passed
146
149
  * (a champion is promoted), with the agreement check it passed (`agreed` of `alone`, its bar `agree_min`). Null when no run was served, nothing serves now (held, or never promoted), or it was promoted
147
- * on no input (a dry run). */
148
- export declare function servingReplayOf(records: readonly PromotionRecord[], runs: readonly CostRun[]): CostReplay | null;
150
+ * on no input (a dry run). The champion skips what `refused` names (the purge gate's). */
151
+ export declare function servingReplayOf(records: readonly PromotionRecord[], runs: readonly CostRun[], refused?: Refused): CostReplay | null;
149
152
  /** What run `runId`'s learning spent, as its cost per run counts it, over every round a follow-up opened (roundsOf): what
150
153
  * it kept as it answered (answeredOf). A run a follow-up opened again (roundsSpendOf's figures): its job is what it had
151
154
  * cost when its first round answered, and everything after (each later round's follow-up turn and every round's