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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/CHANGELOG.md +142 -2
  2. package/README.md +310 -98
  3. package/dist/adapters.d.ts +11 -0
  4. package/dist/adapters.js +49 -0
  5. package/dist/agent-package.d.ts +3 -3
  6. package/dist/agent-package.js +6 -13
  7. package/dist/agents-store.js +6 -5
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-only.d.ts +16 -4
  11. package/dist/api-only.js +23 -7
  12. package/dist/calendar/tools.js +3 -2
  13. package/dist/chatgpt-plan.d.ts +16 -1
  14. package/dist/chatgpt-plan.js +116 -12
  15. package/dist/claude-login.d.ts +34 -5
  16. package/dist/claude-login.js +31 -7
  17. package/dist/claude-sign-in.d.ts +35 -0
  18. package/dist/claude-sign-in.js +90 -0
  19. package/dist/cli.js +5 -3
  20. package/dist/composio-made.d.ts +26 -1
  21. package/dist/composio-made.js +39 -2
  22. package/dist/composio-preset.d.ts +3 -2
  23. package/dist/composio-preset.js +46 -14
  24. package/dist/computer-held-routes.js +2 -3
  25. package/dist/computer-setting.d.ts +4 -2
  26. package/dist/computer-setting.js +0 -2
  27. package/dist/computers-running.d.ts +8 -0
  28. package/dist/computers-running.js +27 -0
  29. package/dist/console/assets/backend-Boh7tC4i.js +166 -0
  30. package/dist/console/assets/index-CQ3cJRzI.js +746 -0
  31. package/dist/console/assets/index-DKkaS3a0.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/docker-host-addresses.d.ts +23 -3
  34. package/dist/docker-host-addresses.js +90 -18
  35. package/dist/exa-keyless.d.ts +2 -3
  36. package/dist/exa-keyless.js +43 -127
  37. package/dist/firecrawl-keyless.d.ts +41 -0
  38. package/dist/firecrawl-keyless.js +152 -0
  39. package/dist/handed-secret.d.ts +3 -1
  40. package/dist/handed-secret.js +4 -2
  41. package/dist/harness-keys.d.ts +98 -0
  42. package/dist/harness-keys.js +247 -0
  43. package/dist/harness-recipe-entry.d.ts +14 -9
  44. package/dist/harness-recipe-entry.js +25 -14
  45. package/dist/harness-table.d.ts +16 -1
  46. package/dist/harness-table.js +19 -7
  47. package/dist/harness.d.ts +4 -0
  48. package/dist/harness.js +12 -1
  49. package/dist/host-check.d.ts +6 -0
  50. package/dist/host-check.js +10 -0
  51. package/dist/import-summary.d.ts +1 -1
  52. package/dist/import-summary.js +1 -1
  53. package/dist/import.d.ts +5 -5
  54. package/dist/import.js +54 -67
  55. package/dist/key-refusal.d.ts +21 -5
  56. package/dist/key-refusal.js +231 -37
  57. package/dist/keyless-mcp.d.ts +36 -0
  58. package/dist/keyless-mcp.js +127 -0
  59. package/dist/learn/audit.d.ts +3 -3
  60. package/dist/learn/audit.js +3 -3
  61. package/dist/learn/commit.d.ts +8 -7
  62. package/dist/learn/commit.js +60 -20
  63. package/dist/learn/compile.d.ts +4 -3
  64. package/dist/learn/compile.js +7 -5
  65. package/dist/learn/folder.d.ts +16 -3
  66. package/dist/learn/folder.js +46 -13
  67. package/dist/learn/promote.d.ts +37 -13
  68. package/dist/learn/promote.js +112 -40
  69. package/dist/learn/secrets.d.ts +20 -10
  70. package/dist/learn/secrets.js +44 -176
  71. package/dist/learning-routes.d.ts +22 -17
  72. package/dist/learning-routes.js +40 -39
  73. package/dist/learning.js +2 -2
  74. package/dist/llms.txt +1 -1
  75. package/dist/manifest.d.ts +10 -0
  76. package/dist/manifest.js +30 -0
  77. package/dist/mcp-pin-first.d.ts +4 -2
  78. package/dist/mcp-pin-first.js +5 -2
  79. package/dist/mcp-secret-writes.d.ts +16 -7
  80. package/dist/mcp-secret-writes.js +35 -27
  81. package/dist/mcp-servers-store.d.ts +30 -6
  82. package/dist/mcp-servers-store.js +112 -28
  83. package/dist/mcp-sources.d.ts +10 -2
  84. package/dist/mcp-sources.js +9 -2
  85. package/dist/mcp-store.d.ts +13 -7
  86. package/dist/mcp-store.js +12 -9
  87. package/dist/model-form.d.ts +3 -2
  88. package/dist/model-form.js +11 -7
  89. package/dist/model.d.ts +20 -4
  90. package/dist/model.js +68 -9
  91. package/dist/native/history.d.ts +1 -1
  92. package/dist/native/history.js +2 -2
  93. package/dist/ollama-provider.d.ts +92 -0
  94. package/dist/ollama-provider.js +495 -0
  95. package/dist/openapi/agentrun-v2.openapi.json +2 -2
  96. package/dist/openapi.d.ts +3 -3
  97. package/dist/openapi.js +197 -55
  98. package/dist/page.d.ts +11 -3
  99. package/dist/page.js +22 -7
  100. package/dist/place-offers.d.ts +25 -1
  101. package/dist/place-offers.js +62 -8
  102. package/dist/print.js +1 -1
  103. package/dist/purged-workflow.d.ts +35 -7
  104. package/dist/purged-workflow.js +73 -26
  105. package/dist/redact/match.d.ts +74 -0
  106. package/dist/redact/match.js +771 -0
  107. package/dist/run-computer.d.ts +2 -0
  108. package/dist/run-computer.js +2 -0
  109. package/dist/run-files.d.ts +4 -0
  110. package/dist/run-files.js +4 -0
  111. package/dist/run-keys.d.ts +2 -4
  112. package/dist/run-keys.js +6 -7
  113. package/dist/run-launch.d.ts +4 -0
  114. package/dist/run-launch.js +4 -0
  115. package/dist/run-reads-over-store.d.ts +3 -2
  116. package/dist/run-reads-over-store.js +66 -2
  117. package/dist/run-secrets.js +5 -2
  118. package/dist/run-timeline-served.d.ts +1 -1
  119. package/dist/run-timeline-served.js +4 -4
  120. package/dist/runner/adapter-loop.d.ts +9 -3
  121. package/dist/runner/adapter-loop.js +34 -15
  122. package/dist/runner/adapter-run-spec.d.ts +3 -0
  123. package/dist/runner/adapter-run-spec.js +9 -4
  124. package/dist/runner/audit.js +8 -4
  125. package/dist/runner/beside.d.ts +2 -1
  126. package/dist/runner/beside.js +13 -5
  127. package/dist/runner/claim-secrets.d.ts +5 -8
  128. package/dist/runner/claim-secrets.js +6 -0
  129. package/dist/runner/cli-run-spec.d.ts +1 -1
  130. package/dist/runner/cli-run-spec.js +41 -7
  131. package/dist/runner/harness-loops.d.ts +22 -9
  132. package/dist/runner/harness-loops.js +21 -11
  133. package/dist/runner/held.d.ts +3 -0
  134. package/dist/runner/learning-end.d.ts +1 -1
  135. package/dist/runner/learning-end.js +8 -3
  136. package/dist/runner/loop-contract.d.ts +9 -4
  137. package/dist/runner/main.js +12 -6
  138. package/dist/runner/mcp-claim.d.ts +3 -0
  139. package/dist/runner/mcp-claim.js +26 -2
  140. package/dist/runner/mcp-run.d.ts +3 -0
  141. package/dist/runner/mcp-run.js +2 -1
  142. package/dist/runner/metrics.d.ts +10 -10
  143. package/dist/runner/metrics.js +19 -38
  144. package/dist/runner/model-route.d.ts +3 -0
  145. package/dist/runner/model-route.js +6 -2
  146. package/dist/runner/presence.d.ts +4 -3
  147. package/dist/runner/presence.js +4 -2
  148. package/dist/runner/promotion.d.ts +15 -9
  149. package/dist/runner/promotion.js +25 -15
  150. package/dist/runner/run-child-host.d.ts +2 -0
  151. package/dist/runner/run-child-host.js +19 -9
  152. package/dist/runner/run-child.js +3 -1
  153. package/dist/runner/runner.d.ts +4 -0
  154. package/dist/runner/runner.js +33 -3
  155. package/dist/runner/sdk-loop.js +2 -0
  156. package/dist/runner/workflow-loop.d.ts +2 -2
  157. package/dist/runner/workflow-loop.js +1 -2
  158. package/dist/runner/workflow-spec.d.ts +1 -1
  159. package/dist/runner/workflow-spec.js +6 -6
  160. package/dist/sdk/check.d.ts +4 -1
  161. package/dist/sdk/check.js +2 -1
  162. package/dist/sdk/runs.d.ts +2 -2
  163. package/dist/sdk/runs.js +8 -6
  164. package/dist/secret-cut.js +2 -1
  165. package/dist/secret-writes.d.ts +3 -2
  166. package/dist/secret-writes.js +1 -1
  167. package/dist/server.d.ts +49 -10
  168. package/dist/server.js +324 -118
  169. package/dist/standard-webhooks.d.ts +11 -0
  170. package/dist/standard-webhooks.js +20 -2
  171. package/dist/store/dialect.d.ts +3 -0
  172. package/dist/store/dialect.js +1 -0
  173. package/dist/store/index.d.ts +2 -2
  174. package/dist/store/index.js +1 -1
  175. package/dist/store/postgres/dialect.js +3 -0
  176. package/dist/store/schema.js +5 -2
  177. package/dist/store/sqlite/store.js +133 -47
  178. package/dist/store/store.d.ts +64 -15
  179. package/dist/store/store.js +7 -0
  180. package/dist/store-reads/journal.d.ts +7 -2
  181. package/dist/store-reads/journal.js +9 -6
  182. package/dist/store-reads/learning.d.ts +12 -9
  183. package/dist/store-reads/learning.js +18 -24
  184. package/dist/store-view.d.ts +0 -5
  185. package/dist/store-view.js +10 -9
  186. package/dist/template-eval.d.ts +51 -6
  187. package/dist/template-eval.js +177 -53
  188. package/dist/template-import.js +4 -2
  189. package/dist/templates.d.ts +5 -3
  190. package/dist/templates.js +19 -40
  191. package/dist/timeline/index.d.ts +1 -1
  192. package/dist/timeline/index.js +1 -1
  193. package/dist/timeline/labels.d.ts +2 -2
  194. package/dist/timeline/labels.js +2 -2
  195. package/dist/timeline/timeline.d.ts +14 -9
  196. package/dist/timeline/timeline.js +15 -7
  197. package/dist/tool-gate.js +3 -1
  198. package/dist/tool-plane.d.ts +17 -9
  199. package/dist/tool-plane.js +38 -17
  200. package/dist/tools.js +2 -2
  201. package/dist/trigger-launch-hook.d.ts +16 -8
  202. package/dist/trigger-launch-hook.js +32 -23
  203. package/dist/trigger-targets.d.ts +18 -8
  204. package/dist/trigger-targets.js +42 -19
  205. package/dist/triggers.d.ts +85 -23
  206. package/dist/triggers.js +303 -96
  207. package/dist/validate.js +1 -1
  208. package/dist/web-fake.js +3 -3
  209. package/dist/web-fetch-direct.d.ts +4 -0
  210. package/dist/web-fetch-direct.js +8 -1
  211. package/dist/web-fetch.d.ts +12 -3
  212. package/dist/web-fetch.js +47 -14
  213. package/dist/web-search.d.ts +33 -4
  214. package/dist/web-search.js +100 -41
  215. package/dist/webhooks.js +4 -5
  216. package/dist/workspace/computer-deps.d.ts +2 -1
  217. package/dist/workspace/computer-deps.js +5 -4
  218. package/dist/workspace/computer-for-claim.d.ts +8 -2
  219. package/dist/workspace/computer-for-claim.js +28 -9
  220. package/dist/workspace/computer-janitor.d.ts +15 -7
  221. package/dist/workspace/computer-janitor.js +33 -8
  222. package/dist/workspace/computer-kept.d.ts +52 -4
  223. package/dist/workspace/computer-kept.js +118 -6
  224. package/dist/workspace/run-end-computers.d.ts +5 -1
  225. package/dist/workspace/run-end-computers.js +27 -1
  226. package/dist/wrapped.d.ts +57 -0
  227. package/dist/wrapped.js +51 -0
  228. package/launcher/agentrun-serve +5 -1
  229. package/package.json +17 -13
  230. package/templates/README.md +10 -9
  231. package/dist/console/assets/index-B_85An2t.js +0 -745
  232. package/dist/console/assets/index-n1YsbnYh.css +0 -1
  233. package/dist/import-sources.d.ts +0 -116
  234. package/dist/import-sources.js +0 -693
@@ -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) {
@@ -10,6 +10,9 @@ export interface Dialect {
10
10
  jsonValue(column: string, path: readonly string[]): string;
11
11
  /** True unless the JSON TEXT column's value at `path` is false or 0 (absent or null count as true). */
12
12
  jsonNotFalse(column: string, path: readonly string[]): string;
13
+ /** The JSON TEXT column's value at `path` as a number to compare with one, or SQL NULL when it is absent or not a JSON
14
+ * number (never a cast that fails on a row's text). */
15
+ jsonNumber(column: string, path: readonly string[]): string;
13
16
  /** True when the JSON array in TEXT column `column` holds the string parameter that follows (one `?`). */
14
17
  jsonArrayHas(column: string): string;
15
18
  /** True when the JSON object of strings in TEXT column `column` holds the key and the value of the two string parameters
@@ -15,6 +15,7 @@ export const SQLITE = {
15
15
  jsonText: (column, path) => `json_extract(${column}, ${jsonPath(path)})`,
16
16
  jsonValue: (column, path) => `${column} -> ${jsonPath(path)}`,
17
17
  jsonNotFalse: (column, path) => `json_extract(${column}, ${jsonPath(path)}) IS NOT 0`,
18
+ jsonNumber: (column, path) => `(CASE WHEN json_type(${column}, ${jsonPath(path)}) IN ('integer', 'real') THEN json_extract(${column}, ${jsonPath(path)}) END)`,
18
19
  jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ?)`,
19
20
  jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) AS entry WHERE entry.key = ? AND entry.value = ?)`,
20
21
  jsonArrayLength: (column) => `json_array_length(${column})`,
@@ -1,5 +1,5 @@
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";
1
+ export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, KEPT_PREFIX, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RUNNER_STALE_MS, 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, 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";
@@ -1,5 +1,5 @@
1
1
  // The one store (design 2.1), for the cutover: nothing on main imports it until then.
2
- 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 { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, KEPT_PREFIX, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RUNNER_STALE_MS, 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";
3
3
  export { aadOf, openMcpCredential, openRunLaunch, openRunMcpAuth, sealColumn, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, bodyOf, canonical, isObject, isSkillPath, sha256, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
@@ -12,6 +12,9 @@ export function postgresDialect(schema, { testClock = false } = {}) {
12
12
  jsonValue: (column, keys) => `(${column}::json #> ${path(keys)})::text`,
13
13
  // SQLite's json_extract(...) IS NOT 0: true unless the value is false or the number 0 (absent and null are true).
14
14
  jsonNotFalse: (column, keys) => `COALESCE((${column}::json #> ${path(keys)})::text NOT IN ('false', '0'), TRUE)`,
15
+ // SQLite's json_type(...) IN ('integer', 'real'): a JSON number read as numeric, anything else NULL, never a cast of
16
+ // text that would fail the statement.
17
+ jsonNumber: (column, keys) => `(CASE WHEN json_typeof(${column}::json #> ${path(keys)}) = 'number' THEN (${column}::json #>> ${path(keys)})::numeric END)`,
15
18
  jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_array_elements_text(${column}::json) AS element(value) WHERE element.value = ?)`,
16
19
  jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each_text(${column}::json) AS entry(key, value) WHERE entry.key = ? AND entry.value = ?)`,
17
20
  jsonArrayLength: (column) => `json_array_length(${column}::json)`,
@@ -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),
@@ -13,7 +13,7 @@ import { claimFence, storeNow } from "../fence.js";
13
13
  import { JOURNAL_FIRST_ID, RunStorage } from "../journal/storage.js";
14
14
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
15
15
  import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, diskUpgrade, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUN_ATTEMPTS, RUNNERS, RUNNERS_ADDED, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
16
- import { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, UPLOAD_PREFIX, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, tombstoneMetrics, } from "../store.js";
16
+ import { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, UPLOAD_PREFIX, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, KEPT_PREFIX, RUNNER_ROWS_KEPT_MS, RUNNER_STALE_MS, tombstoneMetrics, } from "../store.js";
17
17
  /** The run a launch body is made from (Runs.madeFrom): the run whose input it replays (`replay.of`) or audits (`audit.of`). */
18
18
  const madeOf = (body) => {
19
19
  for (const link of ["replay", "audit"]) {
@@ -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`;
@@ -125,17 +132,44 @@ const lockCommandsOf = (tx, runId) => tx.dialect.lockKey(tx, `commands:${runId}`
125
132
  * its claim run out, once its backoff (an interrupted run's) has passed; parked, once no claim holds it (a run parks
126
133
  * under its claim and is released a few seconds later), with its wake_at passed, an untaken stop or cancel, or an untaken command
127
134
  * that can answer it once its backoff (a failed resume's) has passed. A row marked `answers: false` (a trigger's
128
- * follow-up message) answers no park: it waits, untaken, and its loop gets it after the person's answer wakes the run. */
129
- const claimableIn = (d, n) => ({
130
- sql: `(state = 'queued'
135
+ * follow-up message) answers no park: it waits, untaken, and its loop gets it after the person's answer wakes the run.
136
+ * With `claimer` (a claim's runner), a parked run whose computer is pinned to another runner (keptElsewhere) is left
137
+ * out while only its wake or an answering command makes it claimable; without it (a count of what waits) it is in.
138
+ * An untaken stop or cancel row is its own branch, outside the pin: a person's stop never waits on a pin, and any
139
+ * runner claims the run at once to end it (runner.ts claimMore ends it without a loop, never taking the kept machine).
140
+ * The SQL tells the branches apart by place: the stop/cancel EXISTS is OR'ed beside a parenthesis holding the wake and
141
+ * the answer, and only that parenthesis carries `AND NOT keptElsewhere`. */
142
+ const claimableIn = (d, n, claimer) => {
143
+ const pin = claimer === undefined ? undefined : keptElsewhere(d, n, claimer);
144
+ return {
145
+ sql: `(state = 'queued'
131
146
  OR (state = 'running' AND (runner IS NULL OR claimed_until < ${n.sql}) AND (backoff_until IS NULL OR backoff_until <= ${n.sql}))
132
147
  OR (state = 'parked' AND (runner IS NULL OR claimed_until < ${n.sql}) AND (
133
- (wake_at IS NOT NULL AND wake_at <= ${n.sql})
134
- OR EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.kind IN ('stop', 'cancel'))
135
- OR ((backoff_until IS NULL OR backoff_until <= ${n.sql}) AND EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL
136
- AND ${d.jsonNotFalse(readableJson(d, "commands.body"), ["answers"])})))))`,
137
- params: [...n.params, ...n.params, ...n.params, ...n.params, ...n.params],
138
- });
148
+ EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.kind IN ('stop', 'cancel'))
149
+ OR (((wake_at IS NOT NULL AND wake_at <= ${n.sql})
150
+ OR ((backoff_until IS NULL OR backoff_until <= ${n.sql}) AND EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL
151
+ AND ${d.jsonNotFalse(readableJson(d, "commands.body"), ["answers"])})))${pin ? `
152
+ AND NOT ${pin.sql}` : ""}))))`,
153
+ params: [...n.params, ...n.params, ...n.params, ...n.params, ...n.params, ...(pin?.params ?? [])],
154
+ };
155
+ };
156
+ /** The run's computer is kept at its park (its KEPT_PREFIX row) pinned to a runner other than `claimer` that is still
157
+ * there under the incarnation the row names, at the deadlines' clock `n`: its runners row seen within RUNNER_STALE_MS,
158
+ * claiming (refused NULL); the keep neither ending nor ended, and its `until` ahead. That runner's Docker engine or
159
+ * attach hub holds the machine, so only it can take it back (workspace/computer-kept.ts pinnedOf); once any of these
160
+ * stops holding, any runner claims the run. Read in the claim's own statement, so no check-then-act gap. A row with no
161
+ * runner (a computer any runner reaches: an exec vendor's, a phone; or one an earlier build kept) pins nothing. */
162
+ const keptElsewhere = (d, n, claimer) => {
163
+ const value = readableJson(d, "kept.value");
164
+ const field = (name) => d.jsonText(value, [name]);
165
+ return {
166
+ sql: `EXISTS (SELECT 1 FROM settings kept JOIN runners pin ON pin.runner = ${field("runner")}
167
+ WHERE kept.key = '${KEPT_PREFIX}' || runs.id AND pin.runner <> ? AND pin.incarnation = ${field("incarnation")} AND pin.refused IS NULL
168
+ AND pin.seen_at >= ${n.sql} - ${d.bigintParam} AND ${field("ending")} IS NULL AND ${field("ended")} IS NULL
169
+ AND ${d.jsonNumber(value, ["until"])} > ${n.sql})`,
170
+ params: [claimer, ...n.params, RUNNER_STALE_MS, ...n.params],
171
+ };
172
+ };
139
173
  /** What a claim sets: the next epoch, the runner and its lease (from `n`, the deadlines' clock, plus a lease in ms), running,
140
174
  * no backoff. Binds the runner, `n`'s parameters, then the lease. */
141
175
  const claimSet = (n) => `epoch = epoch + 1, runner = ?, claimed_until = ${n.sql} + ?, state = 'running', backoff_until = NULL`;
@@ -902,17 +936,17 @@ class SqliteStore {
902
936
  // The uploads it was applied from, each gone unless another agent not purged was applied from it too: nothing
903
937
  // else owns one, and a server that serves no template route (API-only) could never remove it. Each is held by its
904
938
  // 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.
939
+ // reads the earlier's purge (committed) and removes the upload. Only the package it was applied from goes, by its
940
+ // sha too: a newer upload of the same name, which another deploy has yet to apply, stays.
906
941
  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) {
942
+ 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))
943
+ .filter((row) => row.id !== null && row.id.startsWith(UPLOAD_PREFIX) && row.sha !== null)
944
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
945
+ for (const { id, sha } of applied) {
912
946
  await d.lockKey(tx, `imported_templates:${id}`);
913
947
  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
948
  if (!kept)
915
- await tx.run("DELETE FROM imported_templates WHERE id = ?", id);
949
+ await tx.run("DELETE FROM imported_templates WHERE id = ? AND sha = ?", id, sha);
916
950
  }
917
951
  // Each revision's content; its id, kind, parent and time stay, which its runs' tombstones name.
918
952
  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 +1080,12 @@ class SqliteStore {
1046
1080
  const at = now();
1047
1081
  await d.lockRow(tx, "triggers", "id", triggerId);
1048
1082
  const was = await tx.get(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE trigger_id = ? AND key = ?`, triggerId, key);
1049
- if (!was)
1083
+ if (!was || (change.from !== undefined && was.status !== change.from))
1084
+ return undefined;
1085
+ // holdsAt: holdsRoom's own predicate, at that time.
1086
+ if (change.holdsAt !== undefined && !(was.status === "sent" && was.run_id === null && was.retry_at !== null && was.retry_at >= change.holdsAt))
1087
+ return undefined;
1088
+ if (change.startByWas !== undefined && !(was.status === "sent" && was.run_id === null && was.retry_at === change.startByWas))
1050
1089
  return undefined;
1051
1090
  const settled = change.status !== undefined && change.status !== "due";
1052
1091
  // Out of due, a firing keeps no retry, wait, payload or attrs (unless keepAttrs), nor the reason its last try gave
@@ -1132,23 +1171,24 @@ class SqliteStore {
1132
1171
  wakeCommands(this.where, { runId, what: "written" });
1133
1172
  return sent;
1134
1173
  },
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
1174
+ waiting: async (clockNow) => (await db.all(`SELECT ${FIRING_COLUMNS.split(", ").map((c) => `f.${c}`).join(", ")},
1175
+ (t.max_active_runs IS NULL OR (SELECT COUNT(*) FROM trigger_firings s LEFT JOIN runs r ON r.id = s.run_id
1176
+ WHERE s.trigger_id = f.trigger_id AND ${inProgress("s", "r")}) < t.max_active_runs) AS free
1138
1177
  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 })),
1178
+ 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
1179
  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,
1180
+ 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),
1181
+ 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
1182
  prune: async (triggerId, { history, dayMs, keepByKey, kept, now: clockNow }) => db.transaction(async (tx) => {
1143
1183
  const at = now();
1144
1184
  await d.lockRow(tx, "triggers", "id", triggerId);
1145
1185
  // 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.
1186
+ // not ended, or a sent one its host may still start (holdsRoom). The rest leave the history: kept for their
1187
+ // key's day when a sender's key names them, else gone.
1148
1188
  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
1189
  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
1190
  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 >= ?)
1191
+ AND NOT ${holdsRoom("f")}
1152
1192
  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
1193
  for (const { key, by } of old) {
1154
1194
  if (keepByKey(by ?? "manual"))
@@ -1519,8 +1559,9 @@ class SqliteStore {
1519
1559
  const [result] = await db.write([{ sql: `UPDATE runs SET wake_at = ${n.sql} WHERE id = ? AND state = 'parked' RETURNING id`, params: [...n.params, runId] }]);
1520
1560
  return (result?.rows.length ?? 0) > 0;
1521
1561
  },
1522
- claimable: async ({ limit } = {}) => {
1523
- const claimable = claimableIn(d, clock());
1562
+ claimable: async ({ limit, runner } = {}) => {
1563
+ // The claimer's name, where it is a claimer's read (a runner's memory path): a run pinned to another runner is not its.
1564
+ const claimable = claimableIn(d, clock(), runner);
1524
1565
  const bounded = typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0;
1525
1566
  const rows = await db.all(`SELECT id FROM runs WHERE ${claimable.sql} ORDER BY started_at, id${bounded ? " LIMIT ?" : ""}`, ...claimable.params, ...(bounded ? [limit] : []));
1526
1567
  return rows.map((row) => row.id);
@@ -1598,9 +1639,39 @@ class SqliteStore {
1598
1639
  return updated;
1599
1640
  },
1600
1641
  };
1642
+ /** The WHERE term of the API token's write over a saved row (McpTokensMark), its one `?` the source record's key: that
1643
+ * setting still says the token saved this very row (`by` token, `of` the row's created_at). In the statement that
1644
+ * writes or removes the row, so an owner's save, which drops the mark in the transaction that writes its row
1645
+ * (dropTokensMark), never lands in between. */
1646
+ const recordJson = readableJson(d, "settings.value");
1647
+ 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))`;
1648
+ /** A write of the saved server `name` that the token's mark decides (McpTokensMark, McpOwnersMark): one transaction that
1649
+ * first holds the server's lock. SQLite's one writer holds it already; on Postgres it makes the token's statement wait
1650
+ * for the owner's transaction to end, so the statement reads the record as that transaction left it (READ COMMITTED
1651
+ * takes each statement's snapshot when it starts, after the lock). */
1652
+ const underMcpLock = (name, work) => db.transaction(async (tx) => {
1653
+ await d.lockKey(tx, `mcp_servers:${name}`);
1654
+ return work(tx);
1655
+ });
1656
+ /** In the owner's write's transaction, once its row is written (McpOwnersMark): the record at `record` loses the token's
1657
+ * mark (`by`) when it still says the token saved that very row (`of` its created_at); the rest of it is kept, as
1658
+ * mcp-sources.ts ownersRecord writes it. Any other record is left as it is. */
1659
+ const dropTokensMark = async (tx, { record }, createdAt) => {
1660
+ const found = await tx.get("SELECT value FROM settings WHERE key = ?", record);
1661
+ const value = found === undefined ? undefined : JSON.parse(found.value);
1662
+ if (typeof value !== "object" || value === null || Array.isArray(value))
1663
+ return;
1664
+ const { by, ...owners } = value;
1665
+ if (by !== "token" || owners.of !== createdAt)
1666
+ return;
1667
+ const encoded = json(owners);
1668
+ await tx.run("UPDATE settings SET value = ?, connector_id = ?, updated_at = ? WHERE key = ?", encoded, nativeCommandOwner(record, encoded), now(), record);
1669
+ };
1601
1670
  /** 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) => {
1671
+ * the statement's own WHERE compares it, so the comparison and the write are one statement. `tokens`: over a saved
1672
+ * row, only while it still carries the token's mark, compared there too (a new row has none to carry). `owns`: the
1673
+ * owner's write, dropping the token's mark in its transaction once the row is written. */
1674
+ 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
1675
  const at = now();
1605
1676
  // The access token's end on the deadlines' clock (the database's on Postgres): the writer's measure of its life (a
1606
1677
  // duration, clock-free) laid on that clock's now (token_until), in the statement that writes it.
@@ -1620,9 +1691,9 @@ class SqliteStore {
1620
1691
  ? {
1621
1692
  sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, sealed = ?, refresh_holder = NULL, refresh_until = NULL,
1622
1693
  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 = ?"}
1694
+ 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
1695
  RETURNING ${mcpServerColumnsAt(stamp)}`,
1625
- params: [...values, updated, listed, credentialAt, ...stamp.params, left, name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt]), ...stamp.params],
1696
+ params: [...values, updated, listed, credentialAt, ...stamp.params, left, name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt]), ...(tokens ? [tokens.record] : []), ...stamp.params],
1626
1697
  }
1627
1698
  : {
1628
1699
  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 +1703,22 @@ class SqliteStore {
1632
1703
  RETURNING ${mcpServerColumnsAt(stamp)}`,
1633
1704
  params: [name, ...values, at, updated, listed, credentialAt, ...stamp.params, left, ...stamp.params],
1634
1705
  };
1635
- const [result] = await db.write([statement]);
1636
- const written = result.rows[0];
1706
+ const written = await writeMcpRow(name, statement, tokens, owns);
1637
1707
  return written && mcpServerOf(written);
1638
1708
  };
1709
+ /** `statement`, the write of server `name`'s row, answering the row it wrote (RETURNING): alone, or, when the token's mark
1710
+ * decides it (`tokens`, `owns`), in one transaction under the server's lock (underMcpLock), the owner's dropping the
1711
+ * mark once its row is written and only then. */
1712
+ const writeMcpRow = async (name, statement, tokens, owns) => {
1713
+ if (!tokens && !owns)
1714
+ return (await db.write([statement]))[0].rows[0];
1715
+ return underMcpLock(name, async (tx) => {
1716
+ const row = (await tx.step(statement)).rows[0];
1717
+ if (row && owns)
1718
+ await dropTokensMark(tx, owns, mcpServerOf(row).createdAt);
1719
+ return row;
1720
+ });
1721
+ };
1639
1722
  const server = async (executor, name) => {
1640
1723
  const at = clock();
1641
1724
  const row = await executor.get(`SELECT ${mcpServerColumnsAt(at)} FROM mcp_servers WHERE name = ?`, ...at.params, name);
@@ -1643,30 +1726,31 @@ class SqliteStore {
1643
1726
  };
1644
1727
  this.mcp = {
1645
1728
  put: async (row) => (await putServer(row, undefined)),
1646
- putIfCredential: (row, expected) => putServer(row, expected),
1729
+ putIfCredential: (row, expected, tokens, owns) => putServer(row, expected, tokens, owns),
1647
1730
  // One statement compares the credential and writes, as keepRefreshed: no read between, so a refresh's keep never lands
1648
1731
  // 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) => {
1732
+ rewrite: async ({ name, url, auth, protocol = null, tools, prices = null, serverInfo = null, instructions = null, listedAt, updatedAt }, seen, owns) => {
1650
1733
  const at = now();
1651
1734
  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 = ?
1735
+ const row = await writeMcpRow(name, {
1736
+ sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, updated_at = ?, listed_at = ?
1654
1737
  WHERE name = ? AND ${d.nullSafeEquals("sealed")}
1655
1738
  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];
1739
+ params: [url, auth, protocol, json(tools), json(prices), serverInfo === null ? null : json(serverInfo), instructions, updatedAt ?? at, listedAt ?? at, name, seen, ...stamp.params],
1740
+ }, undefined, owns);
1659
1741
  return row && mcpServerOf(row);
1660
1742
  },
1661
1743
  remove: async (name) => {
1662
1744
  const [result] = await db.write([{ sql: "DELETE FROM mcp_servers WHERE name = ? RETURNING url, sealed", params: [name] }]);
1663
1745
  return removedOf(result.rows[0]);
1664
1746
  },
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
- }]);
1747
+ removeIfCredential: async (name, expected, tokens) => {
1748
+ const statement = {
1749
+ 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`,
1750
+ params: [name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt]), ...(tokens ? [tokens.record] : [])],
1751
+ };
1752
+ // The token's removal under the server's lock (underMcpLock): after an owner's write and its record, never between.
1753
+ const [result] = tokens ? [await underMcpLock(name, (tx) => tx.step(statement))] : await db.write([statement]);
1670
1754
  return removedOf(result.rows[0]);
1671
1755
  },
1672
1756
  servers: async () => {
@@ -2417,7 +2501,9 @@ class SqliteStore {
2417
2501
  // The clock is read once the transaction holds the writer lock: a claim that waited for another writer runs its
2418
2502
  // lease from now, never comes back already run out. The deadlines' clock (the database's on Postgres) both judges what
2419
2503
  // is claimable and stamps the lease, which comes back from the row.
2420
- const claimable = claimableIn(this.#db.dialect, this.#clock());
2504
+ // A run whose computer is kept for another runner still there is never picked: no claim, no epoch moved, nothing
2505
+ // given back (keptElsewhere).
2506
+ const claimable = claimableIn(this.#db.dialect, this.#clock(), runner);
2421
2507
  // With many claimers (Postgres), the rows picked are locked as they are read. A poll over many (claimMany) skips a
2422
2508
  // row another claimer holds (Dialect.claimLock): two claims never pick one run, and neither waits for the other. A
2423
2509
  // claim of one named run waits for a write in flight on its row (Dialect.claimOneLock), then reads it as it is: a
@@ -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
@@ -1228,9 +1247,11 @@ export interface Runs {
1228
1247
  failUnclaimed(summary: string): Promise<string[]>;
1229
1248
  /** The runs a runner may claim, oldest first: queued; parked with an untaken command or its wake_at passed; running with
1230
1249
  * no runner (released at a runner's shutdown: it stays running, a run that started keeps that fact) or its claim run
1231
- * out. */
1250
+ * out. A parked run whose computer is kept for another runner that is still there (its pin, KEPT_PREFIX) is that
1251
+ * runner's alone: with `runner`, the claimer, such a run is left out; without it every run is counted. */
1232
1252
  claimable(options?: {
1233
1253
  limit?: number;
1254
+ runner?: string;
1234
1255
  }): Promise<string[]>;
1235
1256
  /** The epoch a runner's claim holds run `runId` at now, judged by the store's own clock (the one claims are stamped
1236
1257
  * and fenced by), never a reader's; undefined when no claim holds it (none, released, or run out) or there is no
@@ -1389,6 +1410,22 @@ export type McpServerWrite = {
1389
1410
  credentialChangedAt?: number | null;
1390
1411
  tokenLeftMs?: number | null;
1391
1412
  };
1413
+ /** The API token's mark a write over a saved server's row needs, compared in the statement that writes or removes the row:
1414
+ * the setting at `record` (the server's source record, mcp-sources.ts) still says `by: "token"` for that very row (its
1415
+ * `of` is the row's created_at). An owner's save drops the mark in the transaction that writes its row (McpOwnersMark),
1416
+ * so a write that needs the mark never lands over the owner's save, whenever that save lands. The write that needs it
1417
+ * takes the server's lock first, so on Postgres its statement reads the record as the owner's committed transaction left
1418
+ * it. */
1419
+ export type McpTokensMark = {
1420
+ readonly record: string;
1421
+ };
1422
+ /** The owner's write over a saved server's row: in the transaction that writes the row, and only once the row is written,
1423
+ * the setting at `record` (the server's source record) loses the API token's mark (`by`) when it still says the token
1424
+ * saved that very row. A write refused (no row) leaves the record as it was, so a refused owner's save never takes the
1425
+ * server from the token; one that lands makes it the owner's with no moment between its row and its record. */
1426
+ export type McpOwnersMark = {
1427
+ readonly record: string;
1428
+ };
1392
1429
  export interface Mcp {
1393
1430
  /** The server's write: the server's row, inserted or replaced by name (its first save's time kept). An owner's save
1394
1431
  * clears any refresh lease and changes the credential, so a refresh in flight is dropped (keepRefreshed's `kept: false`)
@@ -1397,14 +1434,17 @@ export interface Mcp {
1397
1434
  put(server: McpServerWrite): Promise<McpServerRow>;
1398
1435
  /** put(), only while the server's credential is still `expected` (its mark as the writer read it; null: no server by
1399
1436
  * 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>;
1437
+ * it is not. `tokens`: the API token's write over a saved row, which lands only while the row still carries the
1438
+ * token's mark (McpTokensMark), in the same statement. `owns`: the owner's write, which drops the token's mark in the
1439
+ * same transaction once the row is written (McpOwnersMark). */
1440
+ putIfCredential(server: McpServerWrite, expected: McpCredentialMark, tokens?: McpTokensMark, owns?: McpOwnersMark): Promise<McpServerRow | undefined>;
1402
1441
  /** 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
1442
  * credential): the listing, prices, url and times written by a compare-and-set on the CREDENTIAL, iff the row is still
1404
1443
  * saved and its sealed value is still `seen` (the one the owner read). The credential's columns (sealed, token_until,
1405
1444
  * credential_changed_at) and any refresh lease are left as they are, so a runner's refresh in flight still keeps its
1406
1445
  * 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. */
1446
+ * the caller reads it again and re-applies its change onto the fresh row, a bounded few times. `owns`: as
1447
+ * putIfCredential's, the token's mark dropped in the same transaction once the row is written. */
1408
1448
  rewrite(server: {
1409
1449
  name: string;
1410
1450
  url: string;
@@ -1416,12 +1456,14 @@ export interface Mcp {
1416
1456
  instructions?: string | null;
1417
1457
  listedAt?: number;
1418
1458
  updatedAt?: number;
1419
- }, seen: Uint8Array | null): Promise<McpServerRow | undefined>;
1459
+ }, seen: Uint8Array | null, owns?: McpOwnersMark): Promise<McpServerRow | undefined>;
1420
1460
  /** Deletes the row, answering what it held as it went (McpRemoved); undefined when there was none. */
1421
1461
  remove(name: string): Promise<McpRemoved | undefined>;
1422
1462
  /** 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>;
1463
+ * deleted in one statement. Undefined, deleting nothing, when it is not (or the server is gone). `tokens`: the API
1464
+ * token's removal, which lands only while the row still carries the token's mark (McpTokensMark), in the same
1465
+ * statement. */
1466
+ removeIfCredential(name: string, expected: NonNullable<McpCredentialMark>, tokens?: McpTokensMark): Promise<McpRemoved | undefined>;
1425
1467
  /** The registry's rows, by name. */
1426
1468
  servers(): Promise<McpServerRow[]>;
1427
1469
  server(name: string): Promise<McpServerRow | undefined>;
@@ -1742,6 +1784,13 @@ export interface RunCapacity {
1742
1784
  /** How long a runner's row is kept once it stopped saying it is there (a runner that died without its close): its next
1743
1785
  * put removes every row older than this. */
1744
1786
  export declare const RUNNER_ROWS_KEPT_MS: number;
1787
+ /** How old a runner's row can be and still count as there, on the store's clock (runner/presence.ts PRESENCE_STALE_MS:
1788
+ * three renewals missed). The claim rule reads it for a kept computer's pin. */
1789
+ export declare const RUNNER_STALE_MS = 30000;
1790
+ /** The settings key prefix of the computers kept at a run's park, one row per run (workspace/computer-kept.ts). A row
1791
+ * whose computer is pinned to the runner that kept it (its `runner` and `incarnation`) holds the run for that runner in
1792
+ * the claim rule, while that runner is there under that incarnation and the keep lasts. */
1793
+ export declare const KEPT_PREFIX = "computer_kept:";
1745
1794
  /** Every runner's word that it is there (runner/presence.ts). */
1746
1795
  export interface Runners {
1747
1796
  /** Keeps `row` for its runner, replacing any earlier incarnation's, seen now; rows no runner renewed for