@parcha/agentrun-serve 0.1.0-beta.50 → 0.1.0-beta.52
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.
- package/CHANGELOG.md +185 -0
- package/README.md +236 -30
- package/dist/adapters.js +1 -1
- package/dist/agent-delete.d.ts +13 -2
- package/dist/agent-delete.js +14 -5
- package/dist/agents-store.d.ts +5 -1
- package/dist/agents-store.js +17 -7
- package/dist/api-only.d.ts +6 -3
- package/dist/api-only.js +8 -5
- package/dist/archil-routes.d.ts +1 -0
- package/dist/archil-routes.js +28 -2
- package/dist/capacity.d.ts +50 -0
- package/dist/capacity.js +49 -0
- package/dist/cli-learning/claude-wire.d.ts +41 -0
- package/dist/cli-learning/claude-wire.js +258 -0
- package/dist/cli-learning/cli.d.ts +11 -0
- package/dist/cli-learning/cli.js +241 -0
- package/dist/cli-learning/codex-worktree.d.ts +10 -0
- package/dist/cli-learning/codex-worktree.js +119 -0
- package/dist/cli-learning/connections.d.ts +62 -0
- package/dist/cli-learning/connections.js +87 -0
- package/dist/cli-learning/entry.d.ts +1 -0
- package/dist/cli-learning/entry.js +4 -0
- package/dist/cli-learning/evidence.d.ts +78 -0
- package/dist/cli-learning/evidence.js +492 -0
- package/dist/cli-learning/hook.d.ts +33 -0
- package/dist/cli-learning/hook.js +544 -0
- package/dist/cli-learning/install.d.ts +33 -0
- package/dist/cli-learning/install.js +335 -0
- package/dist/cli-learning/observation-proof.d.ts +14 -0
- package/dist/cli-learning/observation-proof.js +10 -0
- package/dist/cli-learning/policy.d.ts +48 -0
- package/dist/cli-learning/policy.js +363 -0
- package/dist/cli-learning/schema.d.ts +16 -0
- package/dist/cli-learning/schema.js +27 -0
- package/dist/cli-learning/state.d.ts +23 -0
- package/dist/cli-learning/state.js +61 -0
- package/dist/cli.js +24 -2
- package/dist/computer-setting.d.ts +8 -0
- package/dist/computer-setting.js +11 -0
- package/dist/computers.d.ts +6 -2
- package/dist/computers.js +2 -2
- package/dist/console/assets/index-B-D0EM3j.js +733 -0
- package/dist/console/assets/{index-D0mr9wfZ.css → index-DlQepP2J.css} +1 -1
- package/dist/console/index.html +2 -2
- package/dist/email/email-faux.d.ts +3 -1
- package/dist/email/email-faux.js +3 -2
- package/dist/email/routes.js +22 -12
- package/dist/fal-price.d.ts +76 -0
- package/dist/fal-price.js +368 -0
- package/dist/harness-install.d.ts +6 -2
- package/dist/harness-install.js +40 -8
- package/dist/harness.d.ts +1 -1
- package/dist/harness.js +2 -2
- package/dist/learn/commit.d.ts +5 -0
- package/dist/learn/commit.js +4 -1
- package/dist/learn/compile.d.ts +13 -5
- package/dist/learn/compile.js +24 -7
- package/dist/learn/delete.d.ts +12 -6
- package/dist/learn/delete.js +17 -11
- package/dist/learn/folder.d.ts +11 -0
- package/dist/learn/folder.js +20 -3
- package/dist/learn/learning-of.d.ts +8 -0
- package/dist/learn/learning-of.js +8 -0
- package/dist/learn/learning.sh +14 -1
- package/dist/learn/promote.d.ts +51 -7
- package/dist/learn/promote.js +51 -8
- package/dist/learn/secrets.js +14 -3
- package/dist/learning-reset.d.ts +18 -0
- package/dist/learning-reset.js +115 -0
- package/dist/learning-routes.d.ts +1 -1
- package/dist/learning-words.d.ts +6 -1
- package/dist/learning-words.js +6 -1
- package/dist/learning.d.ts +8 -6
- package/dist/learning.js +5 -4
- package/dist/llms.txt +1 -0
- package/dist/mcp-gateway.d.ts +39 -2
- package/dist/mcp-gateway.js +41 -10
- package/dist/mcp-pin-first.js +3 -2
- package/dist/mcp-private-hosts.d.ts +24 -3
- package/dist/mcp-private-hosts.js +53 -3
- package/dist/mcp-servers-store.d.ts +1 -0
- package/dist/mcp-servers-store.js +2 -1
- package/dist/media-duration.d.ts +2 -0
- package/dist/media-duration.js +136 -0
- package/dist/model-gateway.d.ts +2 -0
- package/dist/model-gateway.js +3 -1
- package/dist/native/runtimes.d.ts +2 -0
- package/dist/native/runtimes.js +2 -0
- package/dist/observation/learning.d.ts +32 -0
- package/dist/observation/learning.js +66 -0
- package/dist/observation/observer.d.ts +8 -1
- package/dist/observation/observer.js +89 -9
- package/dist/observation/schema.js +12 -4
- package/dist/observation/usage-identity.d.ts +9 -0
- package/dist/observation/usage-identity.js +11 -0
- package/dist/openapi.js +133 -24
- package/dist/provider.d.ts +8 -0
- package/dist/provider.js +14 -2
- package/dist/refusal-words.d.ts +0 -3
- package/dist/refusal-words.js +0 -3
- package/dist/request-metadata.d.ts +20 -0
- package/dist/request-metadata.js +24 -0
- package/dist/run-launch.d.ts +27 -4
- package/dist/run-launch.js +18 -3
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-usage.d.ts +48 -4
- package/dist/run-usage.js +156 -39
- package/dist/run-view.d.ts +2 -0
- package/dist/run-view.js +8 -7
- package/dist/runner/adapter-loop.d.ts +3 -1
- package/dist/runner/adapter-loop.js +41 -35
- package/dist/runner/adapter-run-spec.d.ts +1 -1
- package/dist/runner/adapter-run-spec.js +15 -15
- package/dist/runner/audit.d.ts +8 -3
- package/dist/runner/audit.js +21 -6
- package/dist/runner/beside.d.ts +13 -0
- package/dist/runner/beside.js +27 -8
- package/dist/runner/claim-secrets.d.ts +2 -1
- package/dist/runner/claim-secrets.js +5 -3
- package/dist/runner/cli-run-spec.d.ts +1 -1
- package/dist/runner/cli-run-spec.js +14 -13
- package/dist/runner/conformance/harness.js +4 -2
- package/dist/runner/disk-free.d.ts +44 -0
- package/dist/runner/disk-free.js +96 -0
- package/dist/runner/dispatch.js +4 -2
- package/dist/runner/feedback-round.d.ts +12 -8
- package/dist/runner/feedback-round.js +16 -30
- package/dist/runner/harness-loops.js +8 -3
- package/dist/runner/journal-kinds.d.ts +4 -1
- package/dist/runner/learning-end.d.ts +2 -1
- package/dist/runner/learning-end.js +51 -22
- package/dist/runner/main.d.ts +17 -6
- package/dist/runner/main.js +187 -45
- package/dist/runner/mcp-claim.js +1 -1
- package/dist/runner/mcp-run.d.ts +9 -0
- package/dist/runner/mcp-run.js +16 -1
- package/dist/runner/model-route.js +7 -4
- package/dist/runner/presence.d.ts +11 -2
- package/dist/runner/presence.js +31 -3
- package/dist/runner/promotion.d.ts +40 -21
- package/dist/runner/promotion.js +130 -59
- package/dist/runner/run-child-host.d.ts +12 -15
- package/dist/runner/run-child-host.js +52 -112
- package/dist/runner/run-errors.js +2 -0
- package/dist/runner/runner-check.d.ts +51 -0
- package/dist/runner/runner-check.js +206 -0
- package/dist/runner/runner-metrics.d.ts +19 -0
- package/dist/runner/runner-metrics.js +49 -0
- package/dist/runner/runner.d.ts +37 -0
- package/dist/runner/runner.js +58 -6
- package/dist/runner/sdk-loop.d.ts +2 -2
- package/dist/runner/sdk-loop.js +37 -25
- package/dist/runner/store-port.d.ts +3 -0
- package/dist/runner/workflow-spec.js +3 -3
- package/dist/runs-over-store.d.ts +13 -3
- package/dist/runs-over-store.js +71 -16
- package/dist/sdk/check.d.ts +6 -5
- package/dist/sdk/check.js +17 -16
- package/dist/sdk/runs.d.ts +22 -2
- package/dist/sdk/runs.js +167 -82
- package/dist/server.d.ts +3 -0
- package/dist/server.js +230 -43
- package/dist/skills/agentrun-serve/SKILL.md +52 -7
- package/dist/start-switches.js +2 -0
- package/dist/stats.d.ts +4 -0
- package/dist/stats.js +1 -1
- package/dist/store/agent-body.d.ts +16 -0
- package/dist/store/agent-body.js +20 -3
- package/dist/store/dialect.d.ts +2 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/index.d.ts +3 -3
- package/dist/store/index.js +2 -2
- package/dist/store/journal/storage.d.ts +2 -0
- package/dist/store/journal/storage.js +2 -1
- package/dist/store/postgres/connection.d.ts +5 -2
- package/dist/store/postgres/connection.js +19 -7
- package/dist/store/postgres/dialect.js +1 -0
- package/dist/store/postgres/migrate.d.ts +30 -0
- package/dist/store/postgres/migrate.js +72 -5
- package/dist/store/postgres/migration-lint.d.ts +8 -0
- package/dist/store/postgres/migration-lint.js +119 -0
- package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
- package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
- package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
- package/dist/store/postgres/store.d.ts +8 -3
- package/dist/store/postgres/store.js +31 -11
- package/dist/store/schema.d.ts +32 -2
- package/dist/store/schema.js +74 -5
- package/dist/store/sqlite/run-launch.d.ts +31 -1
- package/dist/store/sqlite/run-launch.js +111 -2
- package/dist/store/sqlite/run-patch.d.ts +2 -1
- package/dist/store/sqlite/run-patch.js +4 -3
- package/dist/store/sqlite/store.d.ts +17 -0
- package/dist/store/sqlite/store.js +226 -37
- package/dist/store/store-schema.d.ts +34 -0
- package/dist/store/store-schema.js +125 -0
- package/dist/store/store.d.ts +120 -5
- package/dist/store/store.js +13 -0
- package/dist/store-reads/analytics.d.ts +3 -2
- package/dist/store-reads/analytics.js +20 -8
- package/dist/store-reads/learning.d.ts +12 -8
- package/dist/store-reads/learning.js +33 -24
- package/dist/store-reads/loop.d.ts +4 -3
- package/dist/store-reads/loop.js +7 -5
- package/dist/store-view.d.ts +4 -3
- package/dist/store-view.js +11 -7
- package/dist/template-eval.js +4 -4
- package/dist/templates.d.ts +6 -2
- package/dist/templates.js +7 -5
- package/dist/timeline/labels.js +1 -1
- package/dist/tool-gate.d.ts +4 -2
- package/dist/tools.js +1 -1
- package/dist/unified-usage.d.ts +24 -0
- package/dist/unified-usage.js +400 -0
- package/dist/uploads-archil.d.ts +100 -0
- package/dist/uploads-archil.js +431 -0
- package/dist/uploads.d.ts +52 -1
- package/dist/uploads.js +186 -108
- package/dist/validate.js +5 -1
- package/dist/web-save.d.ts +3 -0
- package/dist/web-save.js +17 -2
- package/dist/workspace/archil-disk.d.ts +6 -5
- package/dist/workspace/archil-disk.js +27 -12
- package/dist/workspace/archil-exec.js +1 -1
- package/dist/workspace/archil.js +4 -3
- package/dist/workspace/revision-skills.js +24 -11
- package/dist/workspace/synced-folder.d.ts +3 -3
- package/dist/workspace/synced-folder.js +7 -6
- package/package.json +10 -10
- package/skills/agentrun-serve/SKILL.md +52 -7
- package/dist/console/assets/index-D7G6o-1E.js +0 -720
package/dist/agents-store.js
CHANGED
|
@@ -12,6 +12,7 @@ import { approvalsOf } from "./approvals.js";
|
|
|
12
12
|
import { ApiError, invalid } from "./errors.js";
|
|
13
13
|
import { harnessOfBody } from "./harness.js";
|
|
14
14
|
import { learningSettingIssue } from "./learning-setting.js";
|
|
15
|
+
import { learningSettingForBody } from "./store/agent-body.js";
|
|
15
16
|
import { storedHarness } from "./harness-table.js";
|
|
16
17
|
import { AgentBodyInvalid, RevisionMoved, bodyOf, canonical, isObject, StoreConstraint, } from "./store/index.js";
|
|
17
18
|
import { canonicalToolSettings, settingsIssues } from "./tool-plane.js";
|
|
@@ -20,7 +21,8 @@ import { skillIssues, skillNames } from "./validate.js";
|
|
|
20
21
|
/** The last millisecond a UUIDv7 was minted in, and how many were minted in it. */
|
|
21
22
|
let mintedMs = -1;
|
|
22
23
|
let mintedInMs = 0;
|
|
23
|
-
/** A UUIDv7: time-ordered, so a listing by (created_at, id) is stable, and unique per revision
|
|
24
|
+
/** A UUIDv7: time-ordered, so a listing by (created_at, id) is stable, and unique per revision, per minted agent and per
|
|
25
|
+
* upload (uploads.ts lists files by id, newest first). Two
|
|
24
26
|
* minted in one millisecond keep their order: the 12 bits after the time count them up (RFC 9562's monotonic counter),
|
|
25
27
|
* and a clock that steps back keeps the last millisecond, so each id sorts after the one before it. Without that, two
|
|
26
28
|
* edits in one millisecond tie on created_at and their random ids could number the newer revision first. */
|
|
@@ -50,11 +52,14 @@ function storeError(error) {
|
|
|
50
52
|
throw invalid([{ field: "definition", reason: "invalid", message: error.message }]);
|
|
51
53
|
throw error;
|
|
52
54
|
}
|
|
55
|
+
/** Whether another system owns `agent`: an inline run with `external` made it (its `externalRef` set), so the system that
|
|
56
|
+
* sent it sends its deletes, the agent's whole (DELETE /agents/{id}) and, on an API-only server, a run's purge. */
|
|
57
|
+
export const ownedElsewhere = (agent) => agent.externalRef !== null;
|
|
53
58
|
/** Refuses a write to an externally owned agent: one that mirrors an agent in another system (its `externalRef` set) is
|
|
54
59
|
* read-only here — its source is the truth, which writes a new version by running it. Edits, set-current and archive are
|
|
55
60
|
* refused (403 forbidden); reads work as for any agent. */
|
|
56
61
|
export function refuseExternal(agent) {
|
|
57
|
-
if (agent
|
|
62
|
+
if (ownedElsewhere(agent))
|
|
58
63
|
throw new ApiError("forbidden", `The agent ${agent.id} is managed by its source and is read-only here; change it there and run it again.`);
|
|
59
64
|
}
|
|
60
65
|
/** The store's one key of an external reference, "<source>:<kind>:<id>": source and kind hold no colon (POST /runs checks
|
|
@@ -99,7 +104,7 @@ function revisionInputOf(definition, files) {
|
|
|
99
104
|
// pin's arguments sorted) so two revisions that say the same are one body. The store never reimplements it.
|
|
100
105
|
const set = toolSettingsOf(definition.tool_settings);
|
|
101
106
|
const common = { skills: files, tools: definition.tools ?? [], ...harness, ...place, ...set };
|
|
102
|
-
const capped = typeof definition.max_cost_usd === "number" && definition.max_cost_usd > 0 ? { maxCostUsd: definition.max_cost_usd } : {};
|
|
107
|
+
const capped = { ...(typeof definition.max_cost_usd === "number" && definition.max_cost_usd > 0 ? { maxCostUsd: definition.max_cost_usd } : {}), ...(typeof definition.max_requests === "number" && definition.max_requests > 0 ? { maxRequests: definition.max_requests } : {}) };
|
|
103
108
|
// A workflow keeps its approvals too ("never": it runs unattended), so its call nodes are checked with them (runnable.ts,
|
|
104
109
|
// permissionOf with the revision's approvals): a call node on a tool set to ask runs under never, as on main.
|
|
105
110
|
if (isObject(definition.workflow))
|
|
@@ -109,6 +114,7 @@ function revisionInputOf(definition, files) {
|
|
|
109
114
|
return {
|
|
110
115
|
kind: "agentic",
|
|
111
116
|
instructions: definition.instructions,
|
|
117
|
+
...(definition.cli_learning !== undefined ? { cli_learning: definition.cli_learning } : {}),
|
|
112
118
|
...(definition.sdk !== undefined ? { sdk: definition.sdk } : {}),
|
|
113
119
|
...(isObject(definition.native) ? { native: definition.native } : {}),
|
|
114
120
|
...(typeof definition.model === "string" ? { model: definition.model } : {}),
|
|
@@ -194,7 +200,7 @@ export async function createAgent(store, { definition, skills = {}, note }, opti
|
|
|
194
200
|
if (given !== undefined && (await store.agents.get(given)))
|
|
195
201
|
throw new ApiError("agent_exists", `an agent ${given} exists here`);
|
|
196
202
|
// Stamped on the revision now, never resolved at run time: an agent saved with no place keeps running on the runner.
|
|
197
|
-
const placed = options.fresh && definition.place === undefined && definition.computer === undefined && !isObject(definition.workflow) && !isObject(definition.sdk)
|
|
203
|
+
const placed = options.fresh && definition.place === undefined && definition.computer === undefined && !isObject(definition.workflow) && !isObject(definition.sdk) && !isObject(definition.cli_learning)
|
|
198
204
|
? { place: options.fresh.place, ...(definition.tools === undefined ? { tools: [...options.fresh.tools] } : {}) }
|
|
199
205
|
: {};
|
|
200
206
|
// A template's agent keeps the package it was applied from on its first revision (store `revisions.package`).
|
|
@@ -323,6 +329,7 @@ function editOn(entry, definition, skills, note, fromPackage = false) {
|
|
|
323
329
|
files = (isObject(current?.skills) ? current.skills : {});
|
|
324
330
|
const carried = current
|
|
325
331
|
? {
|
|
332
|
+
...(currentBody.cli_learning && definition.cli_learning === undefined ? { cli_learning: currentBody.cli_learning } : {}),
|
|
326
333
|
...(currentBody.sdk && definition.sdk === undefined ? { sdk: currentBody.sdk } : {}),
|
|
327
334
|
...(currentBody.native && definition.native === undefined ? { native: currentBody.native } : {}),
|
|
328
335
|
...(definition.harness === undefined && currentBody.harness ? { harness: currentBody.harness } : {}),
|
|
@@ -335,10 +342,12 @@ function editOn(entry, definition, skills, note, fromPackage = false) {
|
|
|
335
342
|
// What the host owns (the sdk and native references, the harness, the computer and place) carries as an edit's does.
|
|
336
343
|
const owned = current && !fromPackage
|
|
337
344
|
? {
|
|
338
|
-
...(definition.learning === undefined && current.kind === "agentic" && !isObject(definition.workflow) && currentBody
|
|
345
|
+
...(definition.learning === undefined && current.kind === "agentic" && !isObject(definition.workflow) && learningSettingForBody(currentBody) !== undefined ? { learning: learningSettingForBody(currentBody) } : {}),
|
|
339
346
|
// No approvals here: an edit that leaves them out asks (openapi.ts DefinitionInput.approvals),
|
|
340
347
|
// so no edit makes an agent unattended by saying nothing. The console's edit sends back the approvals it read.
|
|
341
348
|
...(definition.max_cost_usd === undefined && currentBody.maxCostUsd !== undefined ? { max_cost_usd: currentBody.maxCostUsd } : {}),
|
|
349
|
+
// So does its limit on each run's free-model requests (0 clears it): leaving a field out never removes a limit.
|
|
350
|
+
...(definition.max_requests === undefined && currentBody.maxRequests !== undefined ? { max_requests: currentBody.maxRequests } : {}),
|
|
342
351
|
// Its input's and its structured answer's schemas are the agent's contract with its callers: an edit that leaves
|
|
343
352
|
// one out keeps it.
|
|
344
353
|
...(definition.input_schema === undefined && current.kind === "agentic" && !isObject(definition.workflow) && currentBody.inputSchema !== undefined ? { input_schema: currentBody.inputSchema } : {}),
|
|
@@ -383,9 +392,9 @@ export const etagOf = (entry) => `"${entry.revision?.id ?? "none"}"`;
|
|
|
383
392
|
/** A revision as a definition, as POST /agents takes one, numbered. */
|
|
384
393
|
export function definitionOf(agent, revision, version) {
|
|
385
394
|
const body = revision.body;
|
|
386
|
-
const common = body.maxCostUsd !== undefined ? { max_cost_usd: body.maxCostUsd } : {};
|
|
395
|
+
const common = { ...(body.maxCostUsd !== undefined ? { max_cost_usd: body.maxCostUsd } : {}), ...(body.maxRequests !== undefined ? { max_requests: body.maxRequests } : {}) };
|
|
387
396
|
const kindBody = revision.kind === "agentic"
|
|
388
|
-
? { instructions: body.instructions, ...(body.model ? { model: body.model } : {}), ...(body.modelTiers ? { model_tiers: body.modelTiers } : {}), ...(body.thinking ? { thinking: body.thinking } : {}), ...(body
|
|
397
|
+
? { instructions: body.instructions, ...(body.model ? { model: body.model } : {}), ...(body.modelTiers ? { model_tiers: body.modelTiers } : {}), ...(body.thinking ? { thinking: body.thinking } : {}), ...(learningSettingForBody(body) !== undefined ? { learning: learningSettingForBody(body) } : {}), ...(body.inputSchema !== undefined ? { input_schema: body.inputSchema } : {}), ...(body.outputSchema !== undefined ? { output_schema: body.outputSchema } : {}), ...(body.checkout !== undefined ? { checkout: body.checkout } : {}), ...common }
|
|
389
398
|
: { workflow: body.workflow, ...common };
|
|
390
399
|
return {
|
|
391
400
|
id: agent.id,
|
|
@@ -393,6 +402,7 @@ export function definitionOf(agent, revision, version) {
|
|
|
393
402
|
name: agent.name,
|
|
394
403
|
...(agent.description !== null && agent.description !== undefined ? { description: agent.description } : {}),
|
|
395
404
|
...kindBody,
|
|
405
|
+
...(body.cli_learning ? { cli_learning: body.cli_learning } : {}),
|
|
396
406
|
...(body.sdk ? { sdk: body.sdk } : {}),
|
|
397
407
|
...(body.native ? { native: body.native } : {}),
|
|
398
408
|
// Its approvals, of either kind: "ask" where none is set, as the definition read says it (definitionOf).
|
package/dist/api-only.d.ts
CHANGED
|
@@ -4,10 +4,13 @@ export declare const API_ONLY_ENV = "AGENTRUN_API_ONLY";
|
|
|
4
4
|
/** The routes (server.ts ROUTES, by name) an API-only server serves. Past a run's own, why each group is here:
|
|
5
5
|
* - a run's hosted machine fetches computerd with the token its create minted, not the server's;
|
|
6
6
|
* - the computers list and the Archil settings are read before a launch, naming keys, never a value;
|
|
7
|
-
* - an agent its inline runs made has its disk and its
|
|
7
|
+
* - an agent its inline runs made has its disk, its delete and its runs' purges sent by the backend that made it (a run
|
|
8
|
+
* of an agent made here is refused by the purge's route itself, server.ts deleteRun, in this profile's words);
|
|
8
9
|
* - a run's computer, take-over, hand-back and viewer link go to the backend, which has no owner's session here;
|
|
9
|
-
* - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's
|
|
10
|
-
*
|
|
10
|
+
* - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's,
|
|
11
|
+
* and resets it (deleteAgentLearning: the agent and its runs kept) when it erases what an agent learned;
|
|
12
|
+
* - a run's usage lines (what its cost.usd joins, by meter) are a read of that run alone, cut as the run's read is;
|
|
13
|
+
* - an operator or a scaler reads the runners' capacity (getCapacity, capacity.ts) from the server whose runners run apart. */
|
|
11
14
|
export declare const API_ONLY_ROUTES: ReadonlySet<string>;
|
|
12
15
|
/** Whether `env` turns the profile on: `1` or `true` on; unset, empty, `0` or `false` off. Any other value is refused in
|
|
13
16
|
* words (a TypeError), so a typo never leaves the console open on a server meant to be API-only. */
|
package/dist/api-only.js
CHANGED
|
@@ -3,21 +3,24 @@ export const API_ONLY_ENV = "AGENTRUN_API_ONLY";
|
|
|
3
3
|
/** The routes (server.ts ROUTES, by name) an API-only server serves. Past a run's own, why each group is here:
|
|
4
4
|
* - a run's hosted machine fetches computerd with the token its create minted, not the server's;
|
|
5
5
|
* - the computers list and the Archil settings are read before a launch, naming keys, never a value;
|
|
6
|
-
* - an agent its inline runs made has its disk and its
|
|
6
|
+
* - an agent its inline runs made has its disk, its delete and its runs' purges sent by the backend that made it (a run
|
|
7
|
+
* of an agent made here is refused by the purge's route itself, server.ts deleteRun, in this profile's words);
|
|
7
8
|
* - a run's computer, take-over, hand-back and viewer link go to the backend, which has no owner's session here;
|
|
8
|
-
* - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's
|
|
9
|
-
*
|
|
9
|
+
* - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's,
|
|
10
|
+
* and resets it (deleteAgentLearning: the agent and its runs kept) when it erases what an agent learned;
|
|
11
|
+
* - a run's usage lines (what its cost.usd joins, by meter) are a read of that run alone, cut as the run's read is;
|
|
12
|
+
* - an operator or a scaler reads the runners' capacity (getCapacity, capacity.ts) from the server whose runners run apart. */
|
|
10
13
|
export const API_ONLY_ROUTES = new Set([
|
|
11
14
|
"createRun", "createInlineRun", "getComputerDaemon",
|
|
12
15
|
"getRunComputer", "takeOverRunComputer", "handBackRunComputer", "createRunComputerViewer",
|
|
13
16
|
"listComputers", "getWorkspaceArchil",
|
|
14
|
-
"getAgentArchil", "deleteAgentArchil", "deleteAgent",
|
|
17
|
+
"getAgentArchil", "deleteAgentArchil", "deleteAgent", "deleteAgentLearning", "deleteRun",
|
|
15
18
|
"getLearningLoop", "listLearningPromotions", "getLearningCost", "getRunLearning",
|
|
16
19
|
"getRun", "getRunUsage", "listRuns", "listAllRuns", "getTimeline",
|
|
17
20
|
"sendMessage", "stopRun", "cancelRun", "raiseRunCap", "gradeRun",
|
|
18
21
|
"listRunFiles", "readRunFile",
|
|
19
22
|
"createFile", "listFiles", "getFile", "uploadFile", "deleteFile",
|
|
20
|
-
"getCapabilities", "getHealth", "getUsage",
|
|
23
|
+
"getCapabilities", "getHealth", "getUsage", "getCapacity",
|
|
21
24
|
]);
|
|
22
25
|
/** Whether `env` turns the profile on: `1` or `true` on; unset, empty, `0` or `false` off. Any other value is refused in
|
|
23
26
|
* words (a TypeError), so a typo never leaves the console open on a server meant to be API-only. */
|
package/dist/archil-routes.d.ts
CHANGED
|
@@ -71,6 +71,7 @@ export declare function createArchilRoutes(options: ArchilRoutesOptions): {
|
|
|
71
71
|
}>;
|
|
72
72
|
checkLaunchDisk: (diskId: string, signal?: AbortSignal) => Promise<void>;
|
|
73
73
|
removeRunFolder: (agentId: string, runId: string, diskId: string, whose?: "launch" | "agent") => Promise<void>;
|
|
74
|
+
removeLearningFolder: (agentId: string, diskId: string) => Promise<void>;
|
|
74
75
|
};
|
|
75
76
|
export type ArchilRoutes = ReturnType<typeof createArchilRoutes>;
|
|
76
77
|
/** One of the owner's Archil routes at its handler: its answer (sent 200), or an ApiError (sent with its status). An
|
package/dist/archil-routes.js
CHANGED
|
@@ -30,7 +30,7 @@ import { unknownFields } from "./validate.js";
|
|
|
30
30
|
import { ArchilClaimRefused } from "./workspace/archil-claim.js";
|
|
31
31
|
import { archilDisk } from "./workspace/archil-disk.js";
|
|
32
32
|
import { deleteDisk, getDisk, listOneDisk } from "./workspace/archil-disks.js";
|
|
33
|
-
import { archilWorkspace } from "./workspace/archil.js";
|
|
33
|
+
import { archilWorkspace, spillFolderOf } from "./workspace/archil.js";
|
|
34
34
|
import { agentDirName } from "./workspace/paths.js";
|
|
35
35
|
import { WorkspaceError } from "./workspace/workspace.js";
|
|
36
36
|
import { ARCHIL_API_KEY_ENV, archilApiKey } from "./workspace/archil-key.js";
|
|
@@ -285,6 +285,32 @@ export function createArchilRoutes(options) {
|
|
|
285
285
|
throw new ApiError("upstream_failed", `${what} is not deleted there yet: ${describe(error).split(key).join("[the key]")}`);
|
|
286
286
|
}
|
|
287
287
|
}
|
|
288
|
+
/** Agent `agentId`'s learning folder on disk `diskId` deleted over the disk's file API: agents/<agent>/learning and
|
|
289
|
+
* everything under it (paths.ts learningKey), which a Mode 2 run's end writes on the disk its claim mounted, the
|
|
290
|
+
* agent's own or one its launch named (the caller's: never made, renamed or removed here), and the folder a learning
|
|
291
|
+
* exec spills beside it (workspace/archil.ts spillFolderOf: a write's input text, left by a failed cleanup). Nothing
|
|
292
|
+
* else on the disk is touched: the agent's runs' folders stay. Done again, it does nothing: a folder not there is gone, and so is the
|
|
293
|
+
* folder of a disk Archil says is gone. Archil off, or no account key, is 503 unavailable; a delete Archil refuses
|
|
294
|
+
* (a computer that still holds the folder, Archil not reached) is 424 upstream_failed, what was not deleted left for
|
|
295
|
+
* the next call. */
|
|
296
|
+
async function removeLearningFolder(agentId, diskId) {
|
|
297
|
+
const what = `The agent ${agentId}'s learning folder on the Archil disk ${diskId}`;
|
|
298
|
+
const settings = await loadArchilSettings(store, env);
|
|
299
|
+
if (settings === undefined)
|
|
300
|
+
throw new ApiError("unavailable", `${what} is not deleted yet: Archil is off on this server, so it can't be reached. Turn Archil on again (PUT /v2/workspace/archil)`);
|
|
301
|
+
const key = await keyOr("unavailable", `${what} can't be deleted`);
|
|
302
|
+
const disk = (options.control?.makeDisk ?? archilDisk)({ disk: diskId, region: settings.region, s3BaseUrl: settings.s3Url, key: () => key });
|
|
303
|
+
try {
|
|
304
|
+
const agent = archilWorkspace(disk, `agents/${agentDirName(agentId)}`, { queueMs: 5_000 });
|
|
305
|
+
for (const name of ["learning", spillFolderOf("learning")])
|
|
306
|
+
await agent.remove(name, { recursive: true, force: true });
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
if (await diskGone(settings, key, diskId))
|
|
310
|
+
return;
|
|
311
|
+
throw new ApiError("upstream_failed", `${what} is not deleted there yet: ${describe(error).split(key).join("[the key]")}`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
288
314
|
/** Whether Archil's control plane says disk `diskId` is gone: its read answers that the account has no such disk (404,
|
|
289
315
|
* getDisk's undefined) or reads it as deleted. Only Archil's word counts: a read that fails (not reached, a 5xx, the key
|
|
290
316
|
* refused) says nothing, so the disk is taken as still there. */
|
|
@@ -297,7 +323,7 @@ export function createArchilRoutes(options) {
|
|
|
297
323
|
return false;
|
|
298
324
|
}
|
|
299
325
|
}
|
|
300
|
-
return { view, save, off, test, agentView, removeAgentDisk, checkLaunchDisk, removeRunFolder };
|
|
326
|
+
return { view, save, off, test, agentView, removeAgentDisk, checkLaunchDisk, removeRunFolder, removeLearningFolder };
|
|
301
327
|
}
|
|
302
328
|
/** One of the owner's Archil routes at its handler: its answer (sent 200), or an ApiError (sent with its status). An
|
|
303
329
|
* agent's route takes the agent as the dispatch read it. */
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { Runners } from "./store/store.js";
|
|
2
|
+
/** The hand-back window when none is asked, in minutes. */
|
|
3
|
+
export declare const CAPACITY_WINDOW_MINUTES = 15;
|
|
4
|
+
/** The longest window, in minutes: the hand-backs the store keeps (schema.ts HAND_BACKS_KEPT_MS). */
|
|
5
|
+
export declare const CAPACITY_WINDOW_MAX_MINUTES: number;
|
|
6
|
+
/** One live runner, as the capacity read shows it. */
|
|
7
|
+
export interface CapacityRunner {
|
|
8
|
+
/** The runner's name (--name, AGENTRUN_RUNNER_NAME, or its host and process). */
|
|
9
|
+
readonly id: string;
|
|
10
|
+
/** Its build's version; null for a runner of a build before this read. */
|
|
11
|
+
readonly version: string | null;
|
|
12
|
+
/** The most runs it holds at once (its loops); null when it did not say (a build before this read, or a runner that
|
|
13
|
+
* refused to claim). */
|
|
14
|
+
readonly slots: number | null;
|
|
15
|
+
/** The runs its live claims hold now. */
|
|
16
|
+
readonly executing: number;
|
|
17
|
+
/** Its slots less what it holds (never below 0), 0 for a runner that refused to claim, null with no slots said. A
|
|
18
|
+
* runner also claims by its host's memory (memory-claim.ts), so a free slot is the most it may take, not a promise. */
|
|
19
|
+
readonly free_slots: number | null;
|
|
20
|
+
/** It refused to claim any run (its run isolation refused): it takes none. Its words are in capabilities' runner_refused. */
|
|
21
|
+
readonly refused: boolean;
|
|
22
|
+
/** When it last said it was there (the deadlines' clock). */
|
|
23
|
+
readonly seen_at: string;
|
|
24
|
+
}
|
|
25
|
+
/** The capacity read's answer. */
|
|
26
|
+
export interface CapacityView {
|
|
27
|
+
/** When it was read (the deadlines' clock: the database's on Postgres). */
|
|
28
|
+
readonly at: string;
|
|
29
|
+
readonly runs: {
|
|
30
|
+
/** Runs waiting for a runner now: queued, handed back or with their claim run out (past any backoff), or parked with
|
|
31
|
+
* something to wake them; the backlog a scaler reads. */
|
|
32
|
+
readonly queued: number;
|
|
33
|
+
/** Runs a live claim holds now, on any runner. */
|
|
34
|
+
readonly executing: number;
|
|
35
|
+
};
|
|
36
|
+
/** The live runners, by name. */
|
|
37
|
+
readonly runners: readonly CapacityRunner[];
|
|
38
|
+
/** The free slots of every live runner that said its slots. */
|
|
39
|
+
readonly free_slots: number;
|
|
40
|
+
/** Runs given back still running (a drain, a loop that closed itself, a claim given back) within the window. */
|
|
41
|
+
readonly hand_backs: {
|
|
42
|
+
readonly window_minutes: number;
|
|
43
|
+
readonly count: number;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** The `window` query parameter in minutes: CAPACITY_WINDOW_MINUTES when absent; a whole number from 1 to
|
|
47
|
+
* CAPACITY_WINDOW_MAX_MINUTES, else 400 bad_request. */
|
|
48
|
+
export declare function capacityWindowOf(url: URL): number;
|
|
49
|
+
/** The capacity read over `runners` (the store's), with hand-backs over the last `windowMinutes`. */
|
|
50
|
+
export declare function capacityOverStore(runners: Pick<Runners, "live" | "capacity">, windowMinutes: number, staleMs?: number): Promise<CapacityView>;
|
package/dist/capacity.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// GET /v2/capacity: what an operator, or an autoscaler, reads to size the runners. Read from the store alone, so a server
|
|
2
|
+
// with no runner beside it (--no-runner, the API-only profile) answers for every runner on its store: the runs waiting for
|
|
3
|
+
// a runner and the runs a claim holds, each live runner (its row seen within PRESENCE_STALE_MS) with its version, its
|
|
4
|
+
// slots and how many are free, and the hand-backs within a window. Counts, runner names and versions only: no run id,
|
|
5
|
+
// agent, prompt, address or customer's word. Behind the server's token, as every route but capabilities and health.
|
|
6
|
+
import { ApiError } from "./errors.js";
|
|
7
|
+
import { PRESENCE_STALE_MS } from "./runner/presence.js";
|
|
8
|
+
/** The hand-back window when none is asked, in minutes. */
|
|
9
|
+
export const CAPACITY_WINDOW_MINUTES = 15;
|
|
10
|
+
/** The longest window, in minutes: the hand-backs the store keeps (schema.ts HAND_BACKS_KEPT_MS). */
|
|
11
|
+
export const CAPACITY_WINDOW_MAX_MINUTES = 24 * 60;
|
|
12
|
+
/** The `window` query parameter in minutes: CAPACITY_WINDOW_MINUTES when absent; a whole number from 1 to
|
|
13
|
+
* CAPACITY_WINDOW_MAX_MINUTES, else 400 bad_request. */
|
|
14
|
+
export function capacityWindowOf(url) {
|
|
15
|
+
const text = url.searchParams.get("window");
|
|
16
|
+
if (text === null)
|
|
17
|
+
return CAPACITY_WINDOW_MINUTES;
|
|
18
|
+
const minutes = /^\d{1,5}$/.test(text) ? Number(text) : NaN;
|
|
19
|
+
if (!(minutes >= 1 && minutes <= CAPACITY_WINDOW_MAX_MINUTES))
|
|
20
|
+
throw new ApiError("bad_request", `window is a whole number of minutes from 1 to ${CAPACITY_WINDOW_MAX_MINUTES}, not ${JSON.stringify(text)}`);
|
|
21
|
+
return minutes;
|
|
22
|
+
}
|
|
23
|
+
/** The capacity read over `runners` (the store's), with hand-backs over the last `windowMinutes`. */
|
|
24
|
+
export async function capacityOverStore(runners, windowMinutes, staleMs = PRESENCE_STALE_MS) {
|
|
25
|
+
const [counts, live] = await Promise.all([runners.capacity(windowMinutes * 60_000), runners.live(staleMs)]);
|
|
26
|
+
const shown = live.map((row) => {
|
|
27
|
+
const executing = counts.held.get(row.runner) ?? 0;
|
|
28
|
+
const refused = row.refused !== null;
|
|
29
|
+
return {
|
|
30
|
+
id: row.runner,
|
|
31
|
+
version: row.version,
|
|
32
|
+
slots: row.slots,
|
|
33
|
+
executing,
|
|
34
|
+
free_slots: refused ? 0 : row.slots === null ? null : Math.max(0, row.slots - executing),
|
|
35
|
+
refused,
|
|
36
|
+
seen_at: new Date(row.seenAt).toISOString(),
|
|
37
|
+
};
|
|
38
|
+
});
|
|
39
|
+
let executing = 0;
|
|
40
|
+
for (const count of counts.held.values())
|
|
41
|
+
executing += count;
|
|
42
|
+
return {
|
|
43
|
+
at: new Date(counts.at).toISOString(),
|
|
44
|
+
runs: { queued: counts.queued, executing },
|
|
45
|
+
runners: shown,
|
|
46
|
+
free_slots: shown.reduce((sum, runner) => sum + (runner.free_slots ?? 0), 0),
|
|
47
|
+
hand_backs: { window_minutes: windowMinutes, count: counts.handBacks },
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
type Policy = {
|
|
2
|
+
text: string;
|
|
3
|
+
complete: boolean;
|
|
4
|
+
reason?: string;
|
|
5
|
+
};
|
|
6
|
+
type Blob = {
|
|
7
|
+
role: string;
|
|
8
|
+
text?: string;
|
|
9
|
+
complete: boolean;
|
|
10
|
+
reason?: string;
|
|
11
|
+
};
|
|
12
|
+
type Request = {
|
|
13
|
+
shapeHash: string;
|
|
14
|
+
refs: string[];
|
|
15
|
+
complete: boolean;
|
|
16
|
+
reason?: string;
|
|
17
|
+
};
|
|
18
|
+
export type ClaudeWireState = {
|
|
19
|
+
version: 1;
|
|
20
|
+
shapes: Record<string, Policy>;
|
|
21
|
+
blobs: Record<string, Blob>;
|
|
22
|
+
requests: Record<string, Request>;
|
|
23
|
+
current?: {
|
|
24
|
+
prompt: string;
|
|
25
|
+
text: string;
|
|
26
|
+
stableText?: string;
|
|
27
|
+
complete: boolean;
|
|
28
|
+
reason?: string;
|
|
29
|
+
};
|
|
30
|
+
/** Re-read ordinary source rows from this byte offset after restoring the JSON cache. */
|
|
31
|
+
replayFrom?: number;
|
|
32
|
+
reminders?: string[];
|
|
33
|
+
};
|
|
34
|
+
/** Keep native request policy only. User/assistant/tool blobs contribute roles and hashes,
|
|
35
|
+
* never conversation text, tool descriptions, arguments, credentials, or raw request bodies. */
|
|
36
|
+
export declare function updateClaudeWire(state: ClaudeWireState | undefined, row: unknown, options: {
|
|
37
|
+
promptId?: string;
|
|
38
|
+
redact: (text: string) => string;
|
|
39
|
+
recordOffset?: number;
|
|
40
|
+
}): ClaudeWireState;
|
|
41
|
+
export {};
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
const POLICY_BYTES = 256 * 1024, CACHE_BYTES = 4 * 1024 * 1024, MAX_REFS = 4096;
|
|
3
|
+
const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
4
|
+
const hash = (value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
|
|
5
|
+
const requestId = (value) => typeof value === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
|
|
6
|
+
const refused = (reason) => ({ text: '', complete: false, reason });
|
|
7
|
+
// Incremental digests contain no recoverable conversation text and are never serialized.
|
|
8
|
+
// On a cache reload the caller replays typed rows from replayFrom to hydrate this state.
|
|
9
|
+
const sourceRuns = new WeakMap();
|
|
10
|
+
function hashValue(value, write, depth = 0) {
|
|
11
|
+
if (depth > 64)
|
|
12
|
+
throw new Error('Native message nesting exceeds the hashing bound.');
|
|
13
|
+
if (typeof value === 'string') {
|
|
14
|
+
write('"');
|
|
15
|
+
for (let start = 0; start < value.length;) {
|
|
16
|
+
let end = Math.min(start + 65536, value.length);
|
|
17
|
+
if (end < value.length && value.charCodeAt(end - 1) >= 0xd800 && value.charCodeAt(end - 1) <= 0xdbff)
|
|
18
|
+
end--;
|
|
19
|
+
write(JSON.stringify(value.slice(start, end)).slice(1, -1));
|
|
20
|
+
start = end;
|
|
21
|
+
}
|
|
22
|
+
write('"');
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (value === null || typeof value !== 'object') {
|
|
26
|
+
write(JSON.stringify(value) ?? 'null');
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (Array.isArray(value)) {
|
|
30
|
+
write('[');
|
|
31
|
+
value.forEach((item, index) => { if (index)
|
|
32
|
+
write(','); hashValue(item, write, depth + 1); });
|
|
33
|
+
write(']');
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
write('{');
|
|
37
|
+
let first = true;
|
|
38
|
+
for (const key of Object.keys(value).sort()) {
|
|
39
|
+
const item = value[key];
|
|
40
|
+
if (key === 'cache_control' || item === undefined)
|
|
41
|
+
continue;
|
|
42
|
+
if (!first)
|
|
43
|
+
write(',');
|
|
44
|
+
first = false;
|
|
45
|
+
write(JSON.stringify(key));
|
|
46
|
+
write(':');
|
|
47
|
+
hashValue(item, write, depth + 1);
|
|
48
|
+
}
|
|
49
|
+
write('}');
|
|
50
|
+
}
|
|
51
|
+
function sourceMessage(previous, next, row, offset) {
|
|
52
|
+
const message = row.message;
|
|
53
|
+
if (!object(message) || message.role !== row.type || message.content == null) {
|
|
54
|
+
sourceRuns.delete(next);
|
|
55
|
+
delete next.replayFrom;
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const role = message.role, messageId = typeof message.id === 'string' ? message.id : undefined;
|
|
59
|
+
const before = sourceRuns.get(previous);
|
|
60
|
+
if (offset !== undefined && before?.lastOffset !== undefined && offset <= before.lastOffset && offset !== previous.replayFrom)
|
|
61
|
+
return;
|
|
62
|
+
const restarting = offset !== undefined && offset === previous.replayFrom;
|
|
63
|
+
const same = !restarting && before?.role === role && (role === 'user' || (messageId !== undefined && messageId === before?.messageId));
|
|
64
|
+
const unprimed = !before && previous.replayFrom !== undefined && offset !== previous.replayFrom;
|
|
65
|
+
const run = same ? { ...before, value: before.value?.copy() } : {
|
|
66
|
+
role, ...(messageId ? { messageId } : {}), blocks: 0, bytes: 0,
|
|
67
|
+
...(!unprimed ? { value: createHash('sha256').update('{"content":[') } : {}),
|
|
68
|
+
};
|
|
69
|
+
if (!same && !unprimed) {
|
|
70
|
+
if (offset !== undefined)
|
|
71
|
+
next.replayFrom = offset;
|
|
72
|
+
else
|
|
73
|
+
delete next.replayFrom;
|
|
74
|
+
}
|
|
75
|
+
run.lastOffset = offset;
|
|
76
|
+
sourceRuns.set(next, run);
|
|
77
|
+
if (!run.value)
|
|
78
|
+
return;
|
|
79
|
+
const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }]
|
|
80
|
+
: Array.isArray(message.content) ? message.content : [message.content];
|
|
81
|
+
try {
|
|
82
|
+
const write = (part) => {
|
|
83
|
+
run.bytes += Buffer.byteLength(part);
|
|
84
|
+
if (run.bytes > 64 * 1024 * 1024)
|
|
85
|
+
throw new Error('Native message hashing exceeds the byte bound.');
|
|
86
|
+
run.value.update(part);
|
|
87
|
+
};
|
|
88
|
+
for (const block of blocks) {
|
|
89
|
+
if (run.blocks++ > 100_000)
|
|
90
|
+
throw new Error('Native message hashing exceeds the block bound.');
|
|
91
|
+
if (run.blocks > 1)
|
|
92
|
+
write(',');
|
|
93
|
+
hashValue(block, write);
|
|
94
|
+
}
|
|
95
|
+
const digest = run.value.copy().update(`],"role":${JSON.stringify(role)}}`).digest('hex');
|
|
96
|
+
const known = next.blobs[digest];
|
|
97
|
+
put(next.blobs, digest, known && known.role !== role ? { role: 'unknown', complete: false, reason: 'A native transcript hash conflicts with its recorded role.' }
|
|
98
|
+
: { role, complete: true }, 8192);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
delete run.value;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function policy(content, redact) {
|
|
105
|
+
const values = typeof content === 'string' ? [content] : Array.isArray(content)
|
|
106
|
+
&& content.every(block => object(block) && block.type === 'text' && typeof block.text === 'string')
|
|
107
|
+
? content.map(block => block.text) : undefined;
|
|
108
|
+
if (!values)
|
|
109
|
+
return refused('The native request contains unsupported system policy content.');
|
|
110
|
+
if (values.reduce((size, value) => size + Buffer.byteLength(value) + 2, 0) > POLICY_BYTES)
|
|
111
|
+
return refused('The native request policy exceeds the 256 KiB evidence limit.');
|
|
112
|
+
const original = values.join('\n\n');
|
|
113
|
+
let text;
|
|
114
|
+
try {
|
|
115
|
+
text = redact(original);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return refused('The native request policy could not be safely captured.');
|
|
119
|
+
}
|
|
120
|
+
if (typeof text !== 'string' || Buffer.byteLength(text) > POLICY_BYTES)
|
|
121
|
+
return refused('The native request policy exceeds the 256 KiB evidence limit.');
|
|
122
|
+
return { text, complete: text === original, ...(text !== original ? { reason: 'The native request policy contains withheld or redacted text.' } : {}) };
|
|
123
|
+
}
|
|
124
|
+
function put(map, key, value, limit) {
|
|
125
|
+
delete map[key];
|
|
126
|
+
map[key] = value;
|
|
127
|
+
while (Object.keys(map).length > limit)
|
|
128
|
+
delete map[Object.keys(map)[0]];
|
|
129
|
+
}
|
|
130
|
+
function bounded(state) {
|
|
131
|
+
// Eviction only removes reconstruction inputs. A later request referring to an evicted
|
|
132
|
+
// record becomes explicitly incomplete; the independently retained current snapshot stays pinned.
|
|
133
|
+
while (Buffer.byteLength(JSON.stringify(state)) > CACHE_BYTES) {
|
|
134
|
+
const map = Object.keys(state.requests).length ? state.requests : Object.keys(state.blobs).length ? state.blobs : state.shapes;
|
|
135
|
+
const key = Object.keys(map)[0];
|
|
136
|
+
if (!key) {
|
|
137
|
+
state.current = state.current ? { prompt: state.current.prompt, ...refused('The native request cache exceeds its evidence limit.') } : undefined;
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
delete map[key];
|
|
141
|
+
}
|
|
142
|
+
return state;
|
|
143
|
+
}
|
|
144
|
+
/** Keep native request policy only. User/assistant/tool blobs contribute roles and hashes,
|
|
145
|
+
* never conversation text, tool descriptions, arguments, credentials, or raw request bodies. */
|
|
146
|
+
export function updateClaudeWire(state, row, options) {
|
|
147
|
+
const previous = state ?? { version: 1, shapes: {}, blobs: {}, requests: {} };
|
|
148
|
+
if (!object(row) || row.agentId || row.isSidechain || !['user', 'assistant', 'attachment', 'api-request-shape', 'api-request-blob', 'api-request'].includes(row.type))
|
|
149
|
+
return previous;
|
|
150
|
+
const next = { ...previous, shapes: { ...previous.shapes }, blobs: { ...previous.blobs }, requests: { ...previous.requests } };
|
|
151
|
+
const run = sourceRuns.get(previous);
|
|
152
|
+
if (run)
|
|
153
|
+
sourceRuns.set(next, run);
|
|
154
|
+
if (row.type === 'user' || row.type === 'assistant') {
|
|
155
|
+
sourceMessage(previous, next, row, Number.isSafeInteger(options.recordOffset) && options.recordOffset >= 0 ? options.recordOffset : undefined);
|
|
156
|
+
return bounded(next);
|
|
157
|
+
}
|
|
158
|
+
if (row.type === 'attachment') {
|
|
159
|
+
const attachment = row.attachment;
|
|
160
|
+
if (object(attachment) && attachment.type === 'total_tokens_reminder' && row.renderedRole === 'system'
|
|
161
|
+
&& typeof attachment.text === 'string' && /^<total_tokens>(?:\d{1,20}|Infinite) tokens left<\/total_tokens>$/.test(attachment.text)
|
|
162
|
+
&& Array.isArray(row.rendered) && row.rendered.length === 1
|
|
163
|
+
&& row.rendered[0]?.content === `<system-reminder>\n${attachment.text}\n</system-reminder>`) {
|
|
164
|
+
next.reminders = [...(next.reminders ?? []).filter(text => text !== attachment.text), attachment.text].slice(-256);
|
|
165
|
+
}
|
|
166
|
+
return bounded(next);
|
|
167
|
+
}
|
|
168
|
+
if (row.type === 'api-request-shape') {
|
|
169
|
+
if (!hash(row.shapeHash))
|
|
170
|
+
return previous;
|
|
171
|
+
const captured = object(row.shape) ? policy(row.shape.system, options.redact) : refused('The native request shape has no captured system policy.');
|
|
172
|
+
const known = next.shapes[row.shapeHash];
|
|
173
|
+
put(next.shapes, row.shapeHash, known && JSON.stringify(known) !== JSON.stringify(captured)
|
|
174
|
+
? refused('A native shape hash was reused for different policy.') : captured, 128);
|
|
175
|
+
return bounded(next);
|
|
176
|
+
}
|
|
177
|
+
if (row.type === 'api-request-blob') {
|
|
178
|
+
if (!hash(row.hash))
|
|
179
|
+
return previous;
|
|
180
|
+
const message = row.message;
|
|
181
|
+
const role = object(message) && typeof message.role === 'string' ? message.role : 'unknown';
|
|
182
|
+
const captured = ['system', 'developer'].includes(role)
|
|
183
|
+
? { role, ...policy(message.content, options.redact) }
|
|
184
|
+
: ['user', 'assistant', 'tool'].includes(role) ? { role, complete: true }
|
|
185
|
+
: { role: 'unknown', complete: false, reason: 'A referenced native message has an unsupported role.' };
|
|
186
|
+
const known = next.blobs[row.hash];
|
|
187
|
+
put(next.blobs, row.hash, known && JSON.stringify(known) !== JSON.stringify(captured)
|
|
188
|
+
? { role: 'unknown', complete: false, reason: 'A native message hash was reused for different policy.' } : captured, 8192);
|
|
189
|
+
return bounded(next);
|
|
190
|
+
}
|
|
191
|
+
const main = row.querySource === 'sdk' || (typeof row.querySource === 'string' && row.querySource.startsWith('repl_main_thread'));
|
|
192
|
+
const prompt = typeof options.promptId === 'string' && options.promptId.length > 0 && options.promptId.length <= 200 ? options.promptId : undefined;
|
|
193
|
+
const failCurrent = (reason) => { if (main)
|
|
194
|
+
next.current = prompt ? { prompt, ...refused(reason) } : undefined; };
|
|
195
|
+
if (!requestId(row.id) || !hash(row.shapeHash) || !Number.isSafeInteger(row.keep) || row.keep < 0 || row.keep > MAX_REFS
|
|
196
|
+
|| !Array.isArray(row.tail) || row.tail.length > MAX_REFS || !row.tail.every(hash)) {
|
|
197
|
+
failCurrent('The native request has malformed or oversized reconstruction metadata.');
|
|
198
|
+
return bounded(next);
|
|
199
|
+
}
|
|
200
|
+
let reason;
|
|
201
|
+
const fail = (value) => { reason ??= value; };
|
|
202
|
+
let refs = [];
|
|
203
|
+
if (row.keep > 0) {
|
|
204
|
+
const base = requestId(row.base) ? next.requests[row.base] : undefined;
|
|
205
|
+
if (!base || !base.complete || base.refs.length < row.keep)
|
|
206
|
+
fail('The native request base is missing, incomplete, or shorter than its retained prefix.');
|
|
207
|
+
else
|
|
208
|
+
refs = base.refs.slice(0, row.keep);
|
|
209
|
+
}
|
|
210
|
+
if (refs.length + row.tail.length > MAX_REFS)
|
|
211
|
+
fail('The native request has too many referenced messages.');
|
|
212
|
+
else
|
|
213
|
+
refs.push(...row.tail);
|
|
214
|
+
if (Object.hasOwn(row, 'cut') || Object.hasOwn(row, 'withheld'))
|
|
215
|
+
fail('The native request declares cut or withheld evidence.');
|
|
216
|
+
const shape = next.shapes[row.shapeHash];
|
|
217
|
+
if (!shape)
|
|
218
|
+
fail('The native request shape is missing from the bounded policy cache.');
|
|
219
|
+
else if (!shape.complete)
|
|
220
|
+
fail(shape.reason ?? 'The native request shape policy is incomplete.');
|
|
221
|
+
const parts = [], stableParts = [];
|
|
222
|
+
let policyBytes = 0, oversized = false;
|
|
223
|
+
const include = (label, content, reminder = false) => {
|
|
224
|
+
if (!content || oversized)
|
|
225
|
+
return;
|
|
226
|
+
const size = Buffer.byteLength(label) + 1 + Buffer.byteLength(content) + (parts.length ? 2 : 0);
|
|
227
|
+
if (policyBytes + size > POLICY_BYTES) {
|
|
228
|
+
oversized = true;
|
|
229
|
+
fail('The reconstructed native policy exceeds the 256 KiB evidence limit.');
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
parts.push(`${label}\n${content}`);
|
|
233
|
+
if (!reminder)
|
|
234
|
+
stableParts.push(`${label}\n${content}`);
|
|
235
|
+
policyBytes += size;
|
|
236
|
+
};
|
|
237
|
+
if (shape)
|
|
238
|
+
include('Native API system policy:', shape.text);
|
|
239
|
+
for (const ref of refs) {
|
|
240
|
+
const entry = next.blobs[ref];
|
|
241
|
+
if (!entry) {
|
|
242
|
+
fail('A native request message is missing from the bounded policy cache.');
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if (!entry.complete)
|
|
246
|
+
fail(entry.reason ?? 'A referenced native policy message is incomplete.');
|
|
247
|
+
if (entry.role === 'system' || entry.role === 'developer')
|
|
248
|
+
include(`Native API ${entry.role} message:`, entry.text ?? '', entry.role === 'system' && (next.reminders ?? []).includes(entry.text ?? ''));
|
|
249
|
+
}
|
|
250
|
+
const text = oversized ? '' : parts.join('\n\n');
|
|
251
|
+
const known = next.requests[row.id];
|
|
252
|
+
if (known && (known.shapeHash !== row.shapeHash || JSON.stringify(known.refs) !== JSON.stringify(refs)))
|
|
253
|
+
fail('A native request identity was reused for different reconstruction metadata.');
|
|
254
|
+
put(next.requests, row.id, { shapeHash: row.shapeHash, refs, complete: !reason, ...(reason ? { reason } : {}) }, 32);
|
|
255
|
+
if (main)
|
|
256
|
+
next.current = prompt ? { prompt, text, stableText: oversized ? '' : stableParts.join('\n\n'), complete: !reason, ...(reason ? { reason } : {}) } : undefined;
|
|
257
|
+
return bounded(next);
|
|
258
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
type CliIO = {
|
|
2
|
+
stdout?: (text: string) => void;
|
|
3
|
+
stderr?: (text: string) => void;
|
|
4
|
+
stdin?: AsyncIterable<string | Uint8Array>;
|
|
5
|
+
fetch?: typeof fetch;
|
|
6
|
+
/** Test/packaging boundary: executable plus arguments, never evaluated while installing. */
|
|
7
|
+
command?: string[];
|
|
8
|
+
};
|
|
9
|
+
/** Installer/status command plus the bounded stdin worker invoked by ordinary CLI hooks. */
|
|
10
|
+
export declare function learningMain(argv: string[], io?: CliIO): Promise<number>;
|
|
11
|
+
export {};
|