@parcha/agentrun-serve 0.1.0-beta.50 → 0.1.0-beta.51

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 (146) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +142 -17
  3. package/dist/agents-store.js +7 -3
  4. package/dist/api-only.d.ts +2 -1
  5. package/dist/api-only.js +3 -2
  6. package/dist/capacity.d.ts +50 -0
  7. package/dist/capacity.js +49 -0
  8. package/dist/cli-learning/claude-wire.d.ts +41 -0
  9. package/dist/cli-learning/claude-wire.js +258 -0
  10. package/dist/cli-learning/cli.d.ts +11 -0
  11. package/dist/cli-learning/cli.js +241 -0
  12. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  13. package/dist/cli-learning/codex-worktree.js +119 -0
  14. package/dist/cli-learning/connections.d.ts +62 -0
  15. package/dist/cli-learning/connections.js +87 -0
  16. package/dist/cli-learning/entry.d.ts +1 -0
  17. package/dist/cli-learning/entry.js +4 -0
  18. package/dist/cli-learning/evidence.d.ts +78 -0
  19. package/dist/cli-learning/evidence.js +492 -0
  20. package/dist/cli-learning/hook.d.ts +33 -0
  21. package/dist/cli-learning/hook.js +544 -0
  22. package/dist/cli-learning/install.d.ts +33 -0
  23. package/dist/cli-learning/install.js +335 -0
  24. package/dist/cli-learning/observation-proof.d.ts +14 -0
  25. package/dist/cli-learning/observation-proof.js +10 -0
  26. package/dist/cli-learning/policy.d.ts +48 -0
  27. package/dist/cli-learning/policy.js +363 -0
  28. package/dist/cli-learning/schema.d.ts +16 -0
  29. package/dist/cli-learning/schema.js +27 -0
  30. package/dist/cli-learning/state.d.ts +23 -0
  31. package/dist/cli-learning/state.js +61 -0
  32. package/dist/cli.js +24 -2
  33. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  34. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  35. package/dist/console/index.html +2 -2
  36. package/dist/email/email-faux.d.ts +3 -1
  37. package/dist/email/email-faux.js +3 -2
  38. package/dist/email/routes.js +22 -12
  39. package/dist/harness-install.d.ts +6 -2
  40. package/dist/harness-install.js +40 -8
  41. package/dist/harness.d.ts +1 -1
  42. package/dist/harness.js +2 -2
  43. package/dist/learn/secrets.js +14 -3
  44. package/dist/learning-words.d.ts +1 -1
  45. package/dist/learning-words.js +1 -1
  46. package/dist/mcp-pin-first.js +2 -1
  47. package/dist/mcp-private-hosts.d.ts +24 -3
  48. package/dist/mcp-private-hosts.js +53 -3
  49. package/dist/model-gateway.d.ts +2 -0
  50. package/dist/model-gateway.js +3 -1
  51. package/dist/native/runtimes.d.ts +2 -0
  52. package/dist/native/runtimes.js +2 -0
  53. package/dist/observation/learning.d.ts +32 -0
  54. package/dist/observation/learning.js +66 -0
  55. package/dist/observation/observer.d.ts +8 -1
  56. package/dist/observation/observer.js +89 -9
  57. package/dist/observation/schema.js +12 -4
  58. package/dist/observation/usage-identity.d.ts +9 -0
  59. package/dist/observation/usage-identity.js +11 -0
  60. package/dist/openapi.js +89 -13
  61. package/dist/run-launch.d.ts +14 -0
  62. package/dist/run-launch.js +4 -0
  63. package/dist/run-view.d.ts +2 -0
  64. package/dist/run-view.js +12 -7
  65. package/dist/runner/adapter-loop.js +29 -26
  66. package/dist/runner/adapter-run-spec.js +2 -2
  67. package/dist/runner/beside.d.ts +13 -0
  68. package/dist/runner/beside.js +27 -8
  69. package/dist/runner/cli-run-spec.js +2 -2
  70. package/dist/runner/disk-free.d.ts +44 -0
  71. package/dist/runner/disk-free.js +96 -0
  72. package/dist/runner/feedback-round.d.ts +12 -8
  73. package/dist/runner/feedback-round.js +16 -30
  74. package/dist/runner/harness-loops.js +3 -1
  75. package/dist/runner/journal-kinds.d.ts +1 -1
  76. package/dist/runner/learning-end.js +4 -0
  77. package/dist/runner/main.d.ts +17 -6
  78. package/dist/runner/main.js +187 -45
  79. package/dist/runner/presence.d.ts +11 -2
  80. package/dist/runner/presence.js +31 -3
  81. package/dist/runner/run-child-host.d.ts +12 -15
  82. package/dist/runner/run-child-host.js +46 -108
  83. package/dist/runner/run-errors.js +2 -0
  84. package/dist/runner/runner-check.d.ts +51 -0
  85. package/dist/runner/runner-check.js +206 -0
  86. package/dist/runner/runner-metrics.d.ts +19 -0
  87. package/dist/runner/runner-metrics.js +49 -0
  88. package/dist/runner/runner.d.ts +37 -0
  89. package/dist/runner/runner.js +43 -3
  90. package/dist/runner/sdk-loop.js +34 -22
  91. package/dist/runs-over-store.d.ts +8 -1
  92. package/dist/runs-over-store.js +57 -9
  93. package/dist/sdk/runs.d.ts +22 -2
  94. package/dist/sdk/runs.js +103 -34
  95. package/dist/server.d.ts +3 -0
  96. package/dist/server.js +149 -26
  97. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  98. package/dist/start-switches.js +2 -0
  99. package/dist/stats.d.ts +4 -0
  100. package/dist/stats.js +1 -1
  101. package/dist/store/agent-body.d.ts +12 -0
  102. package/dist/store/agent-body.js +16 -2
  103. package/dist/store/dialect.d.ts +2 -0
  104. package/dist/store/dialect.js +1 -0
  105. package/dist/store/index.d.ts +3 -3
  106. package/dist/store/index.js +2 -2
  107. package/dist/store/postgres/connection.d.ts +5 -2
  108. package/dist/store/postgres/connection.js +19 -7
  109. package/dist/store/postgres/dialect.js +1 -0
  110. package/dist/store/postgres/migrate.d.ts +30 -0
  111. package/dist/store/postgres/migrate.js +72 -5
  112. package/dist/store/postgres/migration-lint.d.ts +8 -0
  113. package/dist/store/postgres/migration-lint.js +119 -0
  114. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  115. package/dist/store/postgres/store.d.ts +8 -3
  116. package/dist/store/postgres/store.js +31 -11
  117. package/dist/store/schema.d.ts +18 -1
  118. package/dist/store/schema.js +33 -2
  119. package/dist/store/sqlite/run-launch.d.ts +9 -1
  120. package/dist/store/sqlite/run-launch.js +44 -0
  121. package/dist/store/sqlite/store.d.ts +17 -0
  122. package/dist/store/sqlite/store.js +87 -10
  123. package/dist/store/store-schema.d.ts +34 -0
  124. package/dist/store/store-schema.js +125 -0
  125. package/dist/store/store.d.ts +53 -1
  126. package/dist/store/store.js +13 -0
  127. package/dist/store-reads/analytics.d.ts +3 -2
  128. package/dist/store-reads/analytics.js +20 -8
  129. package/dist/store-view.d.ts +4 -3
  130. package/dist/store-view.js +11 -7
  131. package/dist/templates.d.ts +3 -2
  132. package/dist/tool-gate.d.ts +4 -2
  133. package/dist/unified-usage.d.ts +24 -0
  134. package/dist/unified-usage.js +400 -0
  135. package/dist/uploads-archil.d.ts +100 -0
  136. package/dist/uploads-archil.js +430 -0
  137. package/dist/uploads.d.ts +55 -1
  138. package/dist/uploads.js +185 -98
  139. package/dist/validate.js +1 -1
  140. package/dist/workspace/archil-disk.d.ts +6 -5
  141. package/dist/workspace/archil-disk.js +27 -12
  142. package/dist/workspace/archil.js +3 -2
  143. package/package.json +10 -10
  144. package/skills/agentrun-serve/SKILL.md +52 -7
  145. package/dist/console/assets/index-D0mr9wfZ.css +0 -1
  146. package/dist/console/assets/index-D7G6o-1E.js +0 -720
@@ -517,6 +517,7 @@ export function startRunner(options) {
517
517
  // whatever its backoff (a person's stop never waits on a failed resume's), so the run would be claimed again at once.
518
518
  await release(claim, { state: "running", backoffUntil: now() + wait });
519
519
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: "interrupted" });
520
+ emit({ type: "handed-back", runId: claim.runId, epoch: claim.epoch, cause: "end_retry" });
520
521
  };
521
522
  /** Whether the run under `claim` never started: its journal has no conversation yet, so no input of it went out. A
522
523
  * journal that cannot be read says no (the claim's loop applies the stop as it would). */
@@ -611,6 +612,9 @@ export function startRunner(options) {
611
612
  : inARow > 0 ? { backoffUntil: Date.now() + interruptBackoffMs * 2 ** Math.min(inARow - 1, 6) }
612
613
  : {});
613
614
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: end.state });
615
+ // Left running for another claim: a hand-back, by its cause (this runner's close stopped its loop, or it ended so).
616
+ if (end.state === "interrupted")
617
+ emit({ type: "handed-back", runId: claim.runId, epoch: claim.epoch, cause: closed && !closedItself ? "drain" : "interrupted" });
614
618
  if (end.state === "ended" || end.state === "stopped" || end.state === "failed")
615
619
  await announceEnd(claim);
616
620
  }
@@ -775,7 +779,7 @@ export function startRunner(options) {
775
779
  if (runs.get(claim.runId)?.claim.epoch === claim.epoch || endingClaims.has(`${claim.runId}:${claim.epoch}`) || known.some((k) => k.runId === claim.runId && k.epoch === claim.epoch))
776
780
  continue;
777
781
  emit({ type: "error", runId: claim.runId, step: "claim", message: `run ${claim.runId}: a claim answered Unanswered had landed (epoch ${claim.epoch}); given back` });
778
- await release(claim, {}).catch((error) => emit({ type: "error", runId: claim.runId, step: "claim give-back", message: message(error) }));
782
+ await release(claim, {}).then(() => emit({ type: "handed-back", runId: claim.runId, epoch: claim.epoch, cause: "give_back" }), (error) => emit({ type: "error", runId: claim.runId, step: "claim give-back", message: message(error) }));
779
783
  }
780
784
  }
781
785
  };
@@ -787,6 +791,8 @@ export function startRunner(options) {
787
791
  const free = loops - runs.size - replaced.size;
788
792
  if (free <= 0)
789
793
  return;
794
+ if (!(await gateOpen(false)))
795
+ return;
790
796
  // By count alone, one store call claims the batch, each run at its own epoch + 1 (store.runs.claimMany): filling 300
791
797
  // loops, or taking a dead runner's runs over, is one transaction, not 300. By memory, each run that fits is claimed
792
798
  // on its own (claimByMemory).
@@ -801,6 +807,13 @@ export function startRunner(options) {
801
807
  await giveBackUnknown([]);
802
808
  throw error;
803
809
  }
810
+ // Asked again, fresh, before any loop starts on what this poll claimed: a run claimed as the gate's answer changed is
811
+ // given back untouched (released at its epoch, as a closing runner gives back a batch), for a runner that can serve it.
812
+ if (claims.length > 0 && !(await gateOpen(true))) {
813
+ for (const claim of claims)
814
+ await release(claim, {}).catch((error) => emit({ type: "error", runId: claim.runId, step: "claim give-back", message: message(error) }));
815
+ return;
816
+ }
804
817
  // A claim whose run must only end, with no loop (endRetried), so no turn, model request or tool runs on it:
805
818
  // - a run stopped or cancelled while it had not started: claimed from queued, or claimed from running when an earlier
806
819
  // claim was lost before the run's journal had anything (its runner gone before it wrote a word). Nothing of it
@@ -830,7 +843,7 @@ export function startRunner(options) {
830
843
  // Closed while the batch was claimed (or a run this runner still holds, which a claim cannot be): given back.
831
844
  if (before && !before.fence.lost)
832
845
  emit({ type: "error", runId: claim.runId, step: "claim", message: "claimed a run this runner still holds" });
833
- await release(claim, {}).catch(() => { });
846
+ await release(claim, {}).then(() => emit({ type: "handed-back", runId: claim.runId, epoch: claim.epoch, cause: "give_back" }), () => { });
834
847
  continue;
835
848
  }
836
849
  try {
@@ -895,6 +908,29 @@ export function startRunner(options) {
895
908
  }
896
909
  return claims;
897
910
  };
911
+ /** The claim gate's last answer (RunnerOptions.claimGate): null while it lets this runner claim. */
912
+ let refusing = null;
913
+ /** Whether this runner may claim now (claimGate), its presence row and its lines told at each change of answer. A gate
914
+ * that throws is said, and claims nothing this poll; its last answer stands. */
915
+ const gateOpen = async (fresh) => {
916
+ if (!options.claimGate)
917
+ return true;
918
+ let words;
919
+ try {
920
+ words = await options.claimGate(fresh);
921
+ }
922
+ catch (error) {
923
+ emit({ type: "error", step: "claim gate", message: message(error) });
924
+ return false;
925
+ }
926
+ const now = words ?? null;
927
+ if (now !== refusing) {
928
+ refusing = now;
929
+ emit({ type: "refusing", reason: now });
930
+ await (options.presence ?? presence)?.refuse(now).catch(() => undefined);
931
+ }
932
+ return now === null;
933
+ };
898
934
  /** The poll's claim in flight, if any: close() waits for it, so a runner whose close resolved claims nothing after it. */
899
935
  let claiming;
900
936
  /** A run was queued while a poll was in flight (claimNow): one more poll follows that poll's end at once. */
@@ -930,7 +966,7 @@ export function startRunner(options) {
930
966
  };
931
967
  // Its word in the store that a runner that claims is here (presence.ts), for as long as it runs: a server reads a
932
968
  // refusal left by an earlier runner as over once this is there. One its caller keeps is its caller's to close.
933
- const presence = options.presence ? undefined : store.runners ? keepPresence(store.runners, name, null, { warn: (line) => emit({ type: "error", step: "presence", message: line }) }) : undefined;
969
+ const presence = options.presence ? undefined : store.runners ? keepPresence(store.runners, name, null, { warn: (line) => emit({ type: "error", step: "presence", message: line }), slots: loops }) : undefined;
934
970
  poll();
935
971
  commandTimer = setTimeout(deliverAll, commandPollMs);
936
972
  // A run queued in this process is claimed now (claimNow). A command written for a run this runner holds is handed on
@@ -1024,12 +1060,16 @@ export function startRunner(options) {
1024
1060
  // them), its claims renewed, for up to drainMs; a turn in flight then finishes, never cut and paid again on the
1025
1061
  // resume. Whatever is still going at the bound is stopped below, for a shutdown, where it can resume.
1026
1062
  const going = [...runs.values()].filter((held) => !held.fence.lost && !held.ending);
1063
+ const drainFrom = Date.now();
1027
1064
  if (draining && going.length > 0) {
1028
1065
  let bound;
1029
1066
  await Promise.race([Promise.all(going.map((held) => held.done)), new Promise((resolve) => (bound = setTimeout(resolve, drainMs)))]);
1030
1067
  clearTimeout(bound);
1031
1068
  }
1032
1069
  draining = false;
1070
+ // How long the drain took, and what it left for the shutdown to hand back (the runner's metrics: runner-metrics.ts).
1071
+ if (going.length > 0)
1072
+ emit({ type: "drained", ms: Date.now() - drainFrom, held: going.length, left: going.filter((held) => !held.ending && !held.fence.lost).length });
1033
1073
  clearTimeout(commandTimer);
1034
1074
  const live = [...runs.values()].filter((held) => !held.fence.lost);
1035
1075
  // One window for the stop after the drain, the one runnerCloseBoundMs counts (the lease less its margin): the read
@@ -7,7 +7,7 @@ import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
7
7
  import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
8
8
  import { learningFolderOf, secretsShown } from "../learning.js";
9
9
  import { said, STOPPED } from "../learning-words.js";
10
- import { closeSdkInbox, sdkInbox } from "../sdk/runs.js";
10
+ import { cliPolicyOf, closeSdkInbox, sdkInbox } from "../sdk/runs.js";
11
11
  import { settleSdkCheck } from "../sdk/check.js";
12
12
  import { runPathOverStore } from "../store-reads/learning.js";
13
13
  import { capSpendOf, learningEndOfRun } from "./learning-end.js";
@@ -20,15 +20,17 @@ import { stopEnd } from "./loop-contract.js";
20
20
  import { END_PATCH_MS, END_PATCH_UNKNOWN } from "./loop.js";
21
21
  import { storeSecrets } from "./store-secrets.js";
22
22
  import { pathMetrics } from "./workflow-first.js";
23
- const ROOT = ROOT_CONVERSATION_ID, MARK = "agentrun.sdk";
23
+ const ROOT = ROOT_CONVERSATION_ID;
24
24
  export function createSdkLoop(launch, host, route) {
25
+ const execution = launch.cli_learning ?? launch.sdk;
26
+ const MARK = launch.cli_learning ? "agentrun.cli" : "agentrun.sdk";
25
27
  return (deps) => {
26
28
  let stopped;
27
29
  const abort = new AbortController(), signal = AbortSignal.any([deps.signal, abort.signal]);
28
30
  let settled;
29
31
  return {
30
32
  command: async () => ({
31
- refused: "This run is owned by your backend SDK. Start a fresh SDK call for another task.",
33
+ refused: launch.cli_learning ? "This run belongs to your coding CLI. Continue in the original session." : "This run is owned by your backend SDK. Start a fresh SDK call for another task.",
32
34
  }),
33
35
  stop: async (reason) => {
34
36
  stopped = reason;
@@ -143,8 +145,8 @@ export function createSdkLoop(launch, host, route) {
143
145
  {
144
146
  kind: `${MARK}.started`,
145
147
  data: {
146
- runtime: launch.sdk.runtime,
147
- model: launch.sdk.model ?? null,
148
+ runtime: execution.runtime,
149
+ model: execution.model ?? null,
148
150
  learning_revision: launch.learning?.seed ?? null,
149
151
  },
150
152
  },
@@ -177,6 +179,8 @@ export function createSdkLoop(launch, host, route) {
177
179
  for (const event of batch.events) {
178
180
  if (event.type === "text")
179
181
  partial = (partial + event.text).slice(-16_000);
182
+ else if (event.type === "message")
183
+ entries.push({ kind: KINDS.message, data: { role: event.role === "user" ? "person" : "model", text: event.text, at: Date.now() } });
180
184
  else if (event.type === "session")
181
185
  entries.push({ kind: `${MARK}.session`, data: { session_id: event.session_id } });
182
186
  else if (event.type === "workflow_check")
@@ -216,14 +220,18 @@ export function createSdkLoop(launch, host, route) {
216
220
  if (inbox.completion)
217
221
  break;
218
222
  if (inbox.closed)
219
- throw new Error(inbox.closed === "expired"
220
- ? "The backend did not complete this SDK run before its deadline; execution outcome is unknown. No SDK request was replayed."
221
- : "This SDK run closed before its completion was recorded; execution outcome is unknown. No SDK request was replayed.");
223
+ throw new Error(launch.cli_learning
224
+ ? inbox.closed === "expired"
225
+ ? "The coding CLI did not report completion within 24 hours; execution outcome is unknown. No source prompt was replayed."
226
+ : "This CLI prompt window closed before completion was recorded; execution outcome is unknown. No source prompt was replayed."
227
+ : inbox.closed === "expired"
228
+ ? "The backend did not complete this SDK run before its deadline; execution outcome is unknown. No SDK request was replayed."
229
+ : "This SDK run closed before its completion was recorded; execution outcome is unknown. No SDK request was replayed.");
222
230
  await delay(100, undefined, { signal });
223
231
  }
224
- const result = inbox.completion;
232
+ const result = launch.cli_learning && inbox.evidence_incomplete ? { ...inbox.completion, evidence_complete: false } : inbox.completion;
225
233
  // Reported usage still counts, but a known partial trace cannot prove which execution path it took.
226
- const completeEvidence = result.evidence_complete !== false;
234
+ const completeEvidence = launch.cli_learning ? result.evidence_complete === true : result.evidence_complete !== false;
227
235
  const usage = result.usage;
228
236
  const tools = {};
229
237
  for (const event of inbox.batches.flatMap((batch) => batch.events)) {
@@ -242,9 +250,8 @@ export function createSdkLoop(launch, host, route) {
242
250
  cacheWrite: usage?.cache_write_tokens ?? null,
243
251
  requests: null,
244
252
  unmetered: null,
245
- model: result.model ?? launch.sdk.model ?? null,
246
- sdk_runtime: launch.sdk.runtime,
247
- sdk_session_id: result.session_id ?? null,
253
+ model: result.model ?? execution.model ?? null,
254
+ ...(launch.cli_learning ? { cli_runtime: execution.runtime, cli_session_id: result.session_id ?? launch.cli_learning.session_id } : { sdk_runtime: execution.runtime, sdk_session_id: result.session_id ?? null }),
248
255
  models: {},
249
256
  tools,
250
257
  };
@@ -254,7 +261,7 @@ export function createSdkLoop(launch, host, route) {
254
261
  { kind: KINDS.message, data: { role: "model", text: redacted(result.answer), at: Date.now() } },
255
262
  {
256
263
  kind: "runner.request",
257
- data: { turn: 1, model: result.model ?? launch.sdk.model ?? launch.sdk.runtime, aggregate: true },
264
+ data: { turn: 1, model: result.model ?? execution.model ?? execution.runtime, aggregate: true },
258
265
  },
259
266
  {
260
267
  kind: "runner.turn",
@@ -282,11 +289,12 @@ export function createSdkLoop(launch, host, route) {
282
289
  });
283
290
  if (end) {
284
291
  const evidence = JSON.stringify({
285
- application_instructions: launch.sdk.instructions,
292
+ application_instructions: cliPolicyOf(launch, result)?.instructions ?? execution.instructions,
286
293
  supplied_workflows: inbox.learning_workflows ?? [],
287
- workflow_tools: launch.sdk.workflow_tools ?? [],
288
- workflow_adapters: launch.sdk.workflow_adapters ?? [],
294
+ workflow_tools: launch.sdk?.workflow_tools ?? [],
295
+ workflow_adapters: launch.sdk?.workflow_adapters ?? [],
289
296
  user_input: launch.input.content,
297
+ ...(launch.cli_learning ? { dialogue: inbox.batches.flatMap(batch => batch.events.filter(event => event.type === "message")), source_session_id: launch.cli_learning.session_id, source_turn_id: launch.cli_learning.turn_id, seed_observed: result.seed_observed === true } : {}),
290
298
  tool_events: inbox.batches.flatMap((batch) => batch.events.filter((event) => event.type === "tool")),
291
299
  final_answer: result.answer,
292
300
  });
@@ -299,11 +307,15 @@ export function createSdkLoop(launch, host, route) {
299
307
  // A compile-only round has no plain look-back request. Its first ask keeps the same task figures.
300
308
  keptOf: round => keptOf(previous, reflectRequestId(claim.runId, false, round), true),
301
309
  ask: async (prompt, opts) => {
302
- if (result.evidence_complete === false)
310
+ // Capture-only CLI connections have no executable workflow bridge. Their source prompts
311
+ // never receive an extra compile request; they only read the owner's pinned corrections.
312
+ if (launch.cli_learning)
313
+ return { failed: { code: "cli_workflows_unavailable", message: "CLI capture does not provide a workflow execution bridge." } };
314
+ if (!completeEvidence)
303
315
  return {
304
316
  failed: {
305
317
  code: "sdk_evidence_incomplete",
306
- message: "The backend reported incomplete run evidence; no learning was inferred from a partial trace.",
318
+ message: launch.cli_learning ? "The coding CLI reported incomplete evidence; no learning was inferred from a partial trace." : "The backend reported incomplete run evidence; no learning was inferred from a partial trace.",
307
319
  },
308
320
  };
309
321
  if (evidence.length > 384_000)
@@ -417,20 +429,20 @@ export function createSdkLoop(launch, host, route) {
417
429
  kind: KINDS.end,
418
430
  data: {
419
431
  state: cancelled ? "stopped" : "failed",
420
- error: result.error ?? "The backend SDK run did not complete.",
432
+ error: result.error ?? (launch.cli_learning ? "The source CLI prompt did not complete." : "The backend SDK run did not complete."),
421
433
  },
422
434
  },
423
435
  ], {
424
436
  state: cancelled ? "stopped" : "failed",
425
437
  outcome: cancelled ? "cancelled" : null,
426
- summary: result.error ?? "The backend SDK run did not complete.",
438
+ summary: result.error ?? (launch.cli_learning ? "The source CLI prompt did not complete." : "The backend SDK run did not complete."),
427
439
  ...patch,
428
440
  }, also);
429
441
  return cancelled
430
442
  ? { state: "stopped" }
431
443
  : {
432
444
  state: "failed",
433
- error: { code: "sdk_failed", message: result.error ?? "Backend SDK run failed." },
445
+ error: { code: launch.cli_learning ? "cli_failed" : "sdk_failed", message: result.error ?? (launch.cli_learning ? "Source CLI prompt failed." : "Backend SDK run failed.") },
434
446
  };
435
447
  }
436
448
  catch (error) {
@@ -140,6 +140,13 @@ export interface StartDeps {
140
140
  readonly files?: {
141
141
  hold(runId: string, ids: readonly string[]): Promise<void>;
142
142
  release(runId: string): Promise<void>;
143
+ /** In Mode 2, the run's files copied into its folder before its row is written (uploads-archil.ts placeRunFiles):
144
+ * its launch, saying so and naming its disk, and how to undo it when the row is not written. Undefined in Mode 1:
145
+ * the files are held (hold) for the claim to copy. */
146
+ place?(runId: string, agentId: string, launch: RunLaunch): Promise<{
147
+ readonly launch: RunLaunch;
148
+ undo(): Promise<void>;
149
+ } | undefined>;
143
150
  };
144
151
  /** Where a revision naming these tools and no place runs here (server.ts fallbackPlace). */
145
152
  fallbackPlace(kind: "agentic" | "workflow", tools: readonly unknown[]): Place;
@@ -239,7 +246,7 @@ export interface InlineAgent {
239
246
  * agent already mapped to the reference is the run's (its id, its learning), so a run of a later version learns from the
240
247
  * earlier ones. A different definition under a version already run is 409 external_body_conflict, nothing written; under
241
248
  * `origin`, a key that already started a run gets that run, as startRun's. */
242
- export declare function startInline(store: Pick<Store, "runs" | "runOfOrigin" | "agents">, deps: StartDeps, inline: InlineAgent, body: Json, { origin, sealed }?: Pick<StartOptions, "origin" | "sealed">): Promise<RunRow>;
249
+ export declare function startInline(store: Pick<Store, "runs" | "runOfOrigin" | "agents">, deps: StartDeps, inline: InlineAgent, body: Json, options?: Pick<StartOptions, "origin" | "sealed">): Promise<RunRow>;
243
250
  /** A run's launch from its create body, with every check the old start made before a run started, in the same order and
244
251
  * words: the body's fields, the revision it pins, the input against its schema, the cap rules, the plane this host
245
252
  * resolves, whether the revision can run here; then its title, plane, model and learning start. Nothing is written: the
@@ -132,6 +132,8 @@ async function controlLaunchBody(store, runId) {
132
132
  /** Only the application can abort its SDK and tools. An HTTP acknowledgement must not pretend that it did. */
133
133
  async function refuseSdkStop(store, runId) {
134
134
  const launch = await controlLaunchBody(store, runId);
135
+ if (isObject(launch) && launch.cli_learning)
136
+ throw new ApiError("not_continuable", "This run belongs to your existing CLI session. Stop it in that session; AgentRun does not control its execution.");
135
137
  if (isObject(launch) && launch.sdk)
136
138
  throw new ApiError("not_continuable", "This agent runs in your backend SDK. Cancel it using the original application's cancellation signal; its wrapper will report that outcome here.");
137
139
  }
@@ -164,6 +166,8 @@ export async function message(store, moment, content, { requestId, answers = tru
164
166
  if (moment.importedSource !== undefined)
165
167
  throw importedRefusal(moment);
166
168
  const launchBody = await controlLaunchBody(store, moment.id);
169
+ if (isObject(launchBody) && launchBody.cli_learning)
170
+ throw new ApiError("not_continuable", "Continue in the original CLI session.");
167
171
  if (isObject(launchBody) && launchBody.sdk)
168
172
  throw new ApiError("not_continuable", "Backend SDK runs are single-task sessions. Start a new SDK call for another task.");
169
173
  if (nativeOf(launchBody))
@@ -439,6 +443,8 @@ export async function learningStartFor(deps, entry, revision, rbody, { use = fal
439
443
  * runner's. Under `origin`, a key that already started a run gets that run (the store's one-run-per-key), so a retry never
440
444
  * starts a second. */
441
445
  export async function startRun(store, deps, entry, body, { trigger, origin, capped = false, from, title, sealed } = {}) {
446
+ if (entry.revision?.body?.cli_learning)
447
+ throw new ApiError("agent_not_runnable", "Start the next prompt in your existing CLI session. AgentRun records its learning; it does not launch this connection.");
442
448
  if (entry.revision?.body?.sdk)
443
449
  throw new ApiError("agent_not_runnable", "This agent runs in your backend SDK. Start it through its SDK learning wrapper; AgentRun does not launch its tools or credentials.");
444
450
  const { launch, revision } = await prepareLaunch(deps, entry, body, { ...(trigger ? { trigger } : {}), capped, ...(from ? { from } : {}), ...(title !== undefined ? { title } : {}) });
@@ -446,7 +452,7 @@ export async function startRun(store, deps, entry, body, { trigger, origin, capp
446
452
  const runId = (deps.newRunId ?? uuidv7)();
447
453
  try {
448
454
  const labels = labelsOf(body.labels);
449
- return await withHeldFiles(deps, runId, launch, () => store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: revision.id, ...(origin ? { origin } : {}), ...(labels ? { labels } : {}) }, { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId, launch, revision.kind) } : {}) }));
455
+ return await withHeldFiles(deps, runId, entry.agent.id, launch, (launch) => store.runs.create({ id: runId, agentId: entry.agent.id, revisionId: revision.id, ...(origin ? { origin } : {}), ...(labels ? { labels } : {}) }, { body: launchBody(launch), ...(sealed ? { sealed: sealed(runId, launch, revision.kind) } : {}) }));
450
456
  }
451
457
  catch (error) {
452
458
  // Only another writer of the store got here first under the same origin key: its run is the one asked for.
@@ -466,15 +472,30 @@ function keyedOrRefused(deps, launch, kind, sealed) {
466
472
  if (!sealed && serverKeyMissing(deps.planeEnv(), { kind, model: launch.model, native: Boolean(launch.native) }))
467
473
  throw modelKeyRequired(false);
468
474
  }
469
- /** Writes run `runId` with `write`, its files (launch.files) held for it first (StartDeps.files): a hold that fails part
470
- * way, a write that fails, or one that answers another run (an origin key's run started before), lets go of the hold. */
471
- async function withHeldFiles(deps, runId, launch, write) {
475
+ /** Writes run `runId` of agent `agentId` with `write`, its files (launch.files) held for it first (StartDeps.files): a
476
+ * hold that fails part way, a write that fails, or one that answers another run (an origin key's run started before),
477
+ * lets go of the hold. In Mode 2 they are placed in the run's folder instead (StartDeps.files.place), and the run is
478
+ * written with the launch that says so; the same failures undo the placing. */
479
+ async function withHeldFiles(deps, runId, agentId, launch, write) {
472
480
  const ids = launch.files ?? [];
473
481
  if (!ids.length || !deps.files)
474
- return await write();
482
+ return await write(launch);
483
+ const placed = await deps.files.place?.(runId, agentId, launch);
484
+ if (placed) {
485
+ try {
486
+ const row = await write(placed.launch);
487
+ if (row.id !== runId)
488
+ await placed.undo();
489
+ return row;
490
+ }
491
+ catch (error) {
492
+ await placed.undo().catch(() => undefined);
493
+ throw error;
494
+ }
495
+ }
475
496
  try {
476
497
  await deps.files.hold(runId, ids);
477
- const row = await write();
498
+ const row = await write(launch);
478
499
  if (row.id !== runId)
479
500
  await deps.files.release(runId);
480
501
  return row;
@@ -492,7 +513,34 @@ const bodyConflict = ({ source, kind, id, version }) => new ApiError("external_b
492
513
  * agent already mapped to the reference is the run's (its id, its learning), so a run of a later version learns from the
493
514
  * earlier ones. A different definition under a version already run is 409 external_body_conflict, nothing written; under
494
515
  * `origin`, a key that already started a run gets that run, as startRun's. */
495
- export async function startInline(store, deps, inline, body, { origin, sealed } = {}) {
516
+ export async function startInline(store, deps, inline, body, options = {}) {
517
+ const ref = externalKey(inline.external);
518
+ // A reference's first starts that overlap in this server share one agent id: each prepares its launch, and in Mode 2
519
+ // places its files (uploads-archil.ts place), under the id the agent is written with, whichever start's transaction
520
+ // writes it (createInline writes the agent once per reference and reads it back). They run at once; none waits on
521
+ // another. (One server writes a store: its owner lock.)
522
+ let tentative = tentativeAgents.get(ref);
523
+ if (!tentative)
524
+ tentativeAgents.set(ref, (tentative = { id: uuidv7(), starts: 0 }));
525
+ tentative.starts += 1;
526
+ let written = false;
527
+ try {
528
+ const row = await startInlineOnce(store, deps, inline, body, options, tentative.id);
529
+ written = true;
530
+ return row;
531
+ }
532
+ finally {
533
+ tentative.starts -= 1;
534
+ // A first start that failed keeps the id for its reference: what it made under it (in Mode 2, the agent's disk, made
535
+ // before the agent is written) is found again by the next start, never made anew. Once a start is written, the
536
+ // reference maps to its agent and the id is let go.
537
+ if (tentative.starts === 0 && written && tentativeAgents.get(ref) === tentative)
538
+ tentativeAgents.delete(ref);
539
+ }
540
+ }
541
+ /** The agent id each reference's first starts in progress share, and a failed first start's kept (startInline). */
542
+ const tentativeAgents = new Map();
543
+ async function startInlineOnce(store, deps, inline, body, { origin, sealed }, newAgentId) {
496
544
  const { external, revision, stored: storedRevision } = inline;
497
545
  const ref = externalKey(external);
498
546
  // A version's body never changes here: a different one is refused before anything else is read or written.
@@ -511,7 +559,7 @@ export async function startInline(store, deps, inline, body, { origin, sealed }
511
559
  const entry = stored
512
560
  ? firstOfVersion ? { ...stored, agent: { ...stored.agent, name: inline.name, description: inline.description } } : stored
513
561
  : {
514
- agent: { id: uuidv7(), name: inline.name, description: inline.description, currentRevision: null, createdAt: Date.now(), archivedAt: null, externalRef: ref, purgedAt: null },
562
+ agent: { id: newAgentId, name: inline.name, description: inline.description, currentRevision: null, createdAt: Date.now(), archivedAt: null, externalRef: ref, purgedAt: null },
515
563
  revision: null, version: 0, revisions: 0, sizes: new Map(),
516
564
  };
517
565
  // A store revision is the revision the run path reads as a pi Revision (its body is the revision body), as pinnedOf hands
@@ -521,7 +569,7 @@ export async function startInline(store, deps, inline, body, { origin, sealed }
521
569
  const runId = (deps.newRunId ?? uuidv7)();
522
570
  const labels = labelsOf(body.labels);
523
571
  try {
524
- return await withHeldFiles(deps, runId, launch, () => store.runs.createInline({
572
+ return await withHeldFiles(deps, runId, entry.agent.id, launch, (launch) => store.runs.createInline({
525
573
  agent: { id: entry.agent.id, name: inline.name, description: inline.description, ref },
526
574
  revision: { id: revision.id, version: external.version, kind: revision.kind, body: revision.body, skills: revision.skills, ...(revision.note !== undefined ? { note: revision.note } : {}), ...(revision.mcpPin !== undefined ? { mcpPin: revision.mcpPin } : {}), ...(revision.monidPin !== undefined ? { monidPin: revision.monidPin } : {}) },
527
575
  run: { id: runId, ...(origin ? { origin } : {}), ...(labels ? { labels } : {}) },
@@ -1,5 +1,6 @@
1
1
  import type { Claim, RunOrigin, Store } from "../store/store.js";
2
2
  import type { AgentEntry } from "../agents-store.js";
3
+ import { type RunLaunch } from "../run-launch.js";
3
4
  import { type StartDeps } from "../runs-over-store.js";
4
5
  import { type LearnedWorkflow } from "../learning.js";
5
6
  import type { SdkWorkflowCheckEvent } from "./check.js";
@@ -19,6 +20,10 @@ export type SdkEvent = SdkWorkflowCheckEvent | {
19
20
  } | {
20
21
  type: "session";
21
22
  session_id: string;
23
+ } | {
24
+ type: "message";
25
+ role: "user" | "assistant";
26
+ text: string;
22
27
  } | {
23
28
  type: "tool";
24
29
  id: string;
@@ -33,10 +38,22 @@ export type SdkCompletion = {
33
38
  answer: string;
34
39
  error?: string;
35
40
  evidence_complete?: boolean;
41
+ seed_observed?: boolean;
42
+ seed_revision?: string;
43
+ /** Claude records the effective same-prompt policy only after UserPromptSubmit. */
44
+ source_policy?: {
45
+ instructions: string;
46
+ complete: boolean;
47
+ };
36
48
  model?: string;
37
49
  session_id?: string;
38
50
  usage?: SdkUsage;
39
51
  };
52
+ /** Claude's begin snapshot is provisional; only its immutable same-window completion can establish policy. */
53
+ export declare function cliPolicyOf(launch: RunLaunch, completion?: SdkCompletion): {
54
+ instructions: string;
55
+ complete: boolean;
56
+ } | undefined;
40
57
  export type SdkInbox = {
41
58
  run_id: string;
42
59
  created_at: number;
@@ -52,6 +69,8 @@ export type SdkInbox = {
52
69
  /** Server cleaning changed evidence: two different secret-bearing answers must never agree by their placeholder. */
53
70
  check_redacted?: true;
54
71
  completion?: SdkCompletion;
72
+ /** CLI source evidence was withheld by the redactor; never infer learning from that partial trace. */
73
+ evidence_incomplete?: true;
55
74
  /** Internal terminal admission fence. No later evidence can be newly acknowledged after this CAS wins. */
56
75
  closed?: "expired" | "failed" | "cancelled";
57
76
  };
@@ -71,16 +90,17 @@ export declare class SdkRuns {
71
90
  private readonly secret;
72
91
  private readonly secrets;
73
92
  private readonly earlier;
93
+ private readonly lane;
74
94
  /** `earlier` are the keys credentials were once signed with (the server's API tokens, before `secret` was its seal
75
95
  * key's): a credential any of them signed is still taken, so a run started before an upgrade keeps its credential. */
76
- constructor(store: Store, data: string, secret: string, secrets?: () => readonly string[], earlier?: readonly string[]);
96
+ constructor(store: Store, data: string, secret: string, secrets?: () => readonly string[], earlier?: readonly string[], lane?: "sdk" | "cli");
77
97
  token(runId: string): string;
78
98
  authenticate(runId: string, token: string): Promise<void>;
79
99
  private clean;
80
100
  start(entry: AgentEntry, body: Record<string, unknown>, deps: StartDeps, origin: RunOrigin | undefined, compile: {
81
101
  readonly model?: string;
82
102
  check(model: string): Promise<void>;
83
- }, consoleOrigin: string): Promise<{
103
+ }, consoleOrigin: string, cli?: NonNullable<RunLaunch["cli_learning"]>): Promise<{
84
104
  run_id: string;
85
105
  agent_id: string;
86
106
  console_url: string;