@parcha/agentrun-serve 0.1.0-beta.38 → 0.1.0-beta.39
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 +418 -0
- package/README.md +325 -124
- package/dist/adapters.d.ts +4 -1
- package/dist/adapters.js +4 -2
- package/dist/agent-rows.d.ts +0 -2
- package/dist/agents-store.d.ts +5 -5
- package/dist/agents-store.js +14 -14
- package/dist/bash-read-only.js +2 -1
- package/dist/cap-short.d.ts +12 -0
- package/dist/cap-short.js +60 -0
- package/dist/cap.d.ts +3 -10
- package/dist/cap.js +2 -5
- package/dist/catalog.d.ts +0 -5
- package/dist/catalog.js +1 -5
- package/dist/chatgpt-plan.d.ts +163 -0
- package/dist/chatgpt-plan.js +549 -0
- package/dist/cli.js +26 -6
- package/dist/composio-preset.d.ts +8 -0
- package/dist/composio-preset.js +8 -7
- package/dist/composio-triggers.d.ts +113 -0
- package/dist/composio-triggers.js +411 -0
- package/dist/computer-calls.js +2 -2
- package/dist/computer-commands.d.ts +2 -0
- package/dist/computer-commands.js +7 -3
- package/dist/computer-live.d.ts +7 -2
- package/dist/computer-live.js +9 -5
- package/dist/computer-routes.d.ts +2 -2
- package/dist/computer-routes.js +2 -2
- package/dist/computer-setting.d.ts +3 -3
- package/dist/computer-setting.js +5 -5
- package/dist/computer-view.d.ts +15 -0
- package/dist/computer-view.js +16 -2
- package/dist/computer-viewer.js +14 -1
- package/dist/computers.d.ts +5 -2
- package/dist/computers.js +9 -5
- package/dist/console/assets/index-BNhZs-jp.css +1 -0
- package/dist/console/assets/index-BQv5aOGB.js +700 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.js +3 -3
- package/dist/decision-cap.d.ts +2 -5
- package/dist/decision-cap.js +3 -6
- package/dist/decision-rows.js +11 -11
- package/dist/email/account.d.ts +84 -0
- package/dist/email/account.js +159 -0
- package/dist/email/answer.d.ts +10 -0
- package/dist/email/answer.js +182 -0
- package/dist/email/email-faux.d.ts +95 -0
- package/dist/email/email-faux.js +849 -0
- package/dist/email/labels.d.ts +1 -0
- package/dist/email/labels.js +84 -0
- package/dist/email/mail.d.ts +186 -0
- package/dist/email/mail.js +380 -0
- package/dist/email/names.d.ts +20 -0
- package/dist/email/names.js +40 -0
- package/dist/email/routes.d.ts +9 -0
- package/dist/email/routes.js +50 -0
- package/dist/email/tools.d.ts +20 -0
- package/dist/email/tools.js +517 -0
- package/dist/environment.d.ts +17 -2
- package/dist/environment.js +36 -8
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +12 -0
- package/dist/eval-mailbox.d.ts +103 -0
- package/dist/eval-mailbox.js +236 -0
- package/dist/graph-view.d.ts +9 -2
- package/dist/graph-view.js +6 -2
- package/dist/harness-install.d.ts +28 -2
- package/dist/harness-install.js +147 -59
- package/dist/harness-opencode/adapter.js +2 -26
- package/dist/harness-opencode/facts.js +5 -2
- package/dist/harness-opencode/host/policy.d.ts +2 -0
- package/dist/harness-opencode/host/policy.js +10 -5
- package/dist/harness-opencode/index.d.ts +1 -1
- package/dist/harness-opencode/index.js +1 -1
- package/dist/harness-opencode/versions.d.ts +6 -0
- package/dist/harness-opencode/versions.js +6 -0
- package/dist/harness-table.js +8 -5
- package/dist/harness.d.ts +12 -0
- package/dist/harness.js +15 -3
- package/dist/hosted-search.d.ts +3 -1
- package/dist/hosted-search.js +51 -11
- package/dist/import-sources.d.ts +1 -1
- package/dist/import-sources.js +3 -3
- package/dist/import.d.ts +21 -0
- package/dist/import.js +186 -1
- package/dist/key-check.d.ts +0 -2
- package/dist/key-check.js +3 -4
- package/dist/key-refusal.d.ts +8 -2
- package/dist/key-refusal.js +16 -13
- package/dist/learn/check.d.ts +18 -3
- package/dist/learn/check.js +328 -3
- package/dist/learn/compile.d.ts +9 -2
- package/dist/learn/compile.js +52 -16
- package/dist/learn/grade.d.ts +4 -0
- package/dist/learn/grade.js +4 -1
- package/dist/learn/promote.d.ts +106 -51
- package/dist/learn/promote.js +82 -189
- package/dist/learn/refit.d.ts +21 -12
- package/dist/learn/refit.js +51 -23
- package/dist/learn/replay-calls.js +1 -1
- package/dist/learn/skills.d.ts +2 -7
- package/dist/learn/skills.js +28 -14
- package/dist/learned-nodes.d.ts +15 -7
- package/dist/learned-nodes.js +29 -5
- package/dist/learned-workflow.d.ts +41 -31
- package/dist/learned-workflow.js +122 -63
- package/dist/learning-batch.js +3 -3
- package/dist/learning-cost.d.ts +26 -8
- package/dist/learning-cost.js +17 -7
- package/dist/learning-routes.d.ts +2 -4
- package/dist/learning-routes.js +20 -3
- package/dist/learning-words.d.ts +1 -1
- package/dist/learning-words.js +4 -1
- package/dist/learning.d.ts +5 -5
- package/dist/link-check.d.ts +27 -0
- package/dist/link-check.js +164 -0
- package/dist/local-models.d.ts +33 -2
- package/dist/local-models.js +43 -5
- package/dist/mcp-pin-first.js +6 -0
- package/dist/mcp-secret-writes.js +3 -0
- package/dist/mcp-servers-store.d.ts +25 -16
- package/dist/mcp-servers-store.js +23 -3
- package/dist/model-form.d.ts +11 -0
- package/dist/model-form.js +17 -1
- package/dist/model.d.ts +26 -6
- package/dist/model.js +126 -18
- package/dist/monid.d.ts +26 -31
- package/dist/monid.js +84 -79
- package/dist/native/binding.d.ts +13 -0
- package/dist/native/binding.js +57 -0
- package/dist/native/cli.d.ts +2 -0
- package/dist/native/cli.js +48 -0
- package/dist/native/connection.d.ts +8 -0
- package/dist/native/connection.js +94 -0
- package/dist/native/context.d.ts +6 -0
- package/dist/native/context.js +22 -0
- package/dist/native/discovery.d.ts +27 -0
- package/dist/native/discovery.js +404 -0
- package/dist/native/environment.d.ts +4 -0
- package/dist/native/environment.js +18 -0
- package/dist/native/history.d.ts +20 -0
- package/dist/native/history.js +147 -0
- package/dist/native/instructions.d.ts +21 -0
- package/dist/native/instructions.js +173 -0
- package/dist/native/remote-worker-bridge.d.ts +3 -0
- package/dist/native/remote-worker-bridge.js +278 -0
- package/dist/native/remote.d.ts +187 -0
- package/dist/native/remote.js +492 -0
- package/dist/native/runtime.d.ts +17 -0
- package/dist/native/runtime.js +316 -0
- package/dist/native/runtimes.d.ts +66 -0
- package/dist/native/runtimes.js +41 -0
- package/dist/native/schema.d.ts +46 -0
- package/dist/native/schema.js +41 -0
- package/dist/native/types.d.ts +87 -0
- package/dist/native/types.js +1 -0
- package/dist/observation/http.d.ts +4 -0
- package/dist/observation/http.js +140 -0
- package/dist/observation/observer.d.ts +301 -0
- package/dist/observation/observer.js +919 -0
- package/dist/observation/schema.d.ts +52 -0
- package/dist/observation/schema.js +154 -0
- package/dist/openapi.d.ts +1 -0
- package/dist/openapi.js +394 -85
- package/dist/paid-calls.d.ts +8 -3
- package/dist/paid-calls.js +6 -2
- package/dist/place-offers.d.ts +4 -8
- package/dist/place-offers.js +4 -9
- package/dist/port-models.d.ts +7 -2
- package/dist/port-models.js +5 -2
- package/dist/print.d.ts +4 -2
- package/dist/print.js +4 -3
- package/dist/propose.d.ts +1 -2
- package/dist/propose.js +10 -1
- package/dist/provider.d.ts +5 -1
- package/dist/provider.js +8 -0
- package/dist/push-handler.d.ts +3 -2
- package/dist/push-handler.js +20 -6
- package/dist/refusal-words.d.ts +11 -0
- package/dist/refusal-words.js +13 -2
- package/dist/run-launch.d.ts +10 -1
- package/dist/run-launch.js +11 -4
- package/dist/run-learning-served.d.ts +75 -2
- package/dist/run-manifest.d.ts +3 -0
- package/dist/run-manifest.js +13 -1
- package/dist/run-reads-over-store.d.ts +3 -3
- package/dist/run-reads-over-store.js +13 -10
- package/dist/run-timeline-served.d.ts +3 -2
- package/dist/run-timeline-served.js +8 -9
- package/dist/run-view.d.ts +42 -35
- package/dist/run-view.js +79 -44
- package/dist/runnable.d.ts +13 -5
- package/dist/runnable.js +69 -60
- package/dist/runner/adapter-loop.d.ts +42 -11
- package/dist/runner/adapter-loop.js +651 -247
- package/dist/runner/adapter-run-spec.d.ts +37 -12
- package/dist/runner/adapter-run-spec.js +139 -106
- package/dist/runner/adapters/pi.d.ts +24 -0
- package/dist/runner/adapters/pi.js +59 -9
- package/dist/runner/beside.d.ts +3 -1
- package/dist/runner/beside.js +24 -8
- package/dist/runner/claim-secrets.d.ts +3 -1
- package/dist/runner/claim-secrets.js +28 -4
- package/dist/runner/cli-run-spec.d.ts +30 -0
- package/dist/runner/cli-run-spec.js +94 -50
- package/dist/runner/computer-channel.d.ts +5 -2
- package/dist/runner/computer-channel.js +3 -2
- package/dist/runner/computer-journal.d.ts +6 -0
- package/dist/runner/computer-journal.js +8 -10
- package/dist/runner/conformance/harness.js +6 -3
- package/dist/runner/end-of-run.d.ts +2 -0
- package/dist/runner/end-of-run.js +3 -1
- package/dist/runner/feedback-round.d.ts +40 -13
- package/dist/runner/feedback-round.js +64 -16
- package/dist/runner/harness-loops.js +17 -0
- package/dist/runner/journal-kinds.d.ts +37 -13
- package/dist/runner/journal-kinds.js +9 -5
- package/dist/runner/learning-dispatch.d.ts +3 -2
- package/dist/runner/learning-dispatch.js +6 -6
- package/dist/runner/learning-end.d.ts +4 -0
- package/dist/runner/learning-end.js +64 -36
- package/dist/runner/learning-factory.d.ts +3 -0
- package/dist/runner/learning-factory.js +8 -2
- package/dist/runner/learning-loop.d.ts +2 -0
- package/dist/runner/learning-loop.js +19 -4
- package/dist/runner/loop.d.ts +18 -0
- package/dist/runner/loop.js +34 -0
- package/dist/runner/main.d.ts +6 -1
- package/dist/runner/main.js +26 -4
- package/dist/runner/mcp-run.d.ts +4 -1
- package/dist/runner/mcp-run.js +11 -5
- package/dist/runner/meta-tools.d.ts +10 -3
- package/dist/runner/meta-tools.js +112 -36
- package/dist/runner/metrics.d.ts +80 -21
- package/dist/runner/metrics.js +114 -39
- package/dist/runner/model-route.d.ts +12 -3
- package/dist/runner/model-route.js +139 -18
- package/dist/runner/monid-run.d.ts +8 -6
- package/dist/runner/monid-run.js +117 -43
- package/dist/runner/native-loop.d.ts +11 -0
- package/dist/runner/native-loop.js +438 -0
- package/dist/runner/promotion.d.ts +74 -8
- package/dist/runner/promotion.js +365 -124
- package/dist/runner/redact.js +3 -0
- package/dist/runner/reflect-hook.js +9 -0
- package/dist/runner/runner.d.ts +7 -1
- package/dist/runner/runner.js +8 -4
- package/dist/runner/sdk-loop.d.ts +7 -0
- package/dist/runner/sdk-loop.js +470 -0
- package/dist/runner/spec-holds.d.ts +16 -2
- package/dist/runner/spec-holds.js +42 -14
- package/dist/runner/store-secrets.js +17 -2
- package/dist/runner/workflow-first.d.ts +30 -20
- package/dist/runner/workflow-first.js +22 -32
- package/dist/runner/workflow-loop.d.ts +1 -1
- package/dist/runner/workflow-loop.js +18 -12
- package/dist/runner/workflow-spec.d.ts +4 -1
- package/dist/runner/workflow-spec.js +56 -45
- package/dist/runs-over-store.d.ts +30 -2
- package/dist/runs-over-store.js +46 -14
- package/dist/sdk/runs.d.ts +115 -0
- package/dist/sdk/runs.js +422 -0
- package/dist/sdk/schema.d.ts +175 -0
- package/dist/sdk/schema.js +138 -0
- package/dist/sdk/workflows.d.ts +22 -0
- package/dist/sdk/workflows.js +39 -0
- package/dist/secrets.d.ts +2 -0
- package/dist/secrets.js +19 -1
- package/dist/server.d.ts +48 -32
- package/dist/server.js +554 -130
- package/dist/skill-route.d.ts +3 -0
- package/dist/skill-route.js +16 -0
- package/dist/skills/agentrun-serve/SKILL.md +368 -0
- package/dist/stats.d.ts +10 -10
- package/dist/store/agent-body.d.ts +12 -8
- package/dist/store/agent-body.js +9 -4
- package/dist/store/index.d.ts +1 -1
- package/dist/store/native-command-owner.d.ts +10 -0
- package/dist/store/native-command-owner.js +47 -0
- package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
- package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
- package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
- package/dist/store/postgres/store.js +3 -0
- package/dist/store/schema.d.ts +7 -0
- package/dist/store/schema.js +20 -1
- package/dist/store/sqlite/run-patch.d.ts +8 -1
- package/dist/store/sqlite/run-patch.js +14 -3
- package/dist/store/sqlite/store.js +133 -18
- package/dist/store/store.d.ts +52 -7
- package/dist/store-reads/analytics.d.ts +7 -7
- package/dist/store-reads/analytics.js +23 -5
- package/dist/store-reads/cap.js +8 -6
- package/dist/store-reads/journal.d.ts +5 -0
- package/dist/store-reads/journal.js +85 -41
- package/dist/store-reads/learning.d.ts +85 -5
- package/dist/store-reads/learning.js +45 -17
- package/dist/store-reads/runs.d.ts +5 -0
- package/dist/store-reads/runs.js +3 -2
- package/dist/store-view.js +75 -21
- package/dist/template-eval.d.ts +73 -11
- package/dist/template-eval.js +535 -75
- package/dist/templates.d.ts +70 -20
- package/dist/templates.js +191 -34
- package/dist/text-urls.d.ts +38 -0
- package/dist/text-urls.js +170 -0
- package/dist/timeline/index.d.ts +3 -2
- package/dist/timeline/index.js +3 -2
- package/dist/timeline/labels.d.ts +5 -2
- package/dist/timeline/labels.js +29 -6
- package/dist/timeline/origin.d.ts +1 -1
- package/dist/timeline/origin.js +2 -2
- package/dist/timeline/render-text.js +1 -1
- package/dist/timeline/timeline.d.ts +66 -4
- package/dist/timeline/timeline.js +160 -30
- package/dist/timeline/util.d.ts +5 -0
- package/dist/timeline/util.js +44 -8
- package/dist/timeline/web-calls.d.ts +17 -0
- package/dist/timeline/web-calls.js +106 -0
- package/dist/tool-gate.d.ts +42 -42
- package/dist/tool-gate.js +97 -91
- package/dist/tool-list.d.ts +4 -1
- package/dist/tool-list.js +8 -1
- package/dist/tool-names.d.ts +18 -13
- package/dist/tool-names.js +19 -17
- package/dist/tool-plane.d.ts +17 -13
- package/dist/tool-plane.js +12 -5
- package/dist/tools.d.ts +44 -16
- package/dist/tools.js +28 -28
- package/dist/trigger-adapter.d.ts +85 -5
- package/dist/trigger-adapter.js +6 -0
- package/dist/trigger-adapters.js +3 -1
- package/dist/trigger-composio.d.ts +10 -0
- package/dist/trigger-composio.js +122 -0
- package/dist/trigger-email.d.ts +4 -0
- package/dist/trigger-email.js +228 -0
- package/dist/trigger-signatures.d.ts +6 -10
- package/dist/trigger-signatures.js +16 -16
- package/dist/trigger-targets.d.ts +1 -1
- package/dist/trigger-targets.js +4 -3
- package/dist/trigger-webhook.js +6 -4
- package/dist/triggers.d.ts +94 -9
- package/dist/triggers.js +263 -62
- package/dist/uploads.d.ts +9 -0
- package/dist/uploads.js +27 -0
- package/dist/validate.js +1 -7
- package/dist/web-fake.d.ts +56 -0
- package/dist/web-fake.js +102 -0
- package/dist/web-fetch-direct.d.ts +3 -0
- package/dist/web-fetch-direct.js +4 -1
- package/dist/web-fetch.d.ts +5 -1
- package/dist/web-fetch.js +8 -31
- package/dist/web-search.d.ts +51 -2
- package/dist/web-search.js +116 -18
- package/dist/webhooks.d.ts +2 -1
- package/dist/webhooks.js +5 -1
- package/dist/workflow/node-runner.js +10 -2
- package/dist/workspace/archil-claim.d.ts +3 -0
- package/dist/workspace/archil-claim.js +9 -2
- package/dist/workspace/computer-deps.d.ts +22 -9
- package/dist/workspace/computer-deps.js +78 -37
- package/dist/workspace/computer-for-claim.d.ts +54 -4
- package/dist/workspace/computer-for-claim.js +179 -39
- package/dist/workspace/computer-janitor.d.ts +10 -3
- package/dist/workspace/computer-janitor.js +96 -29
- package/dist/workspace/computer-kept.d.ts +82 -0
- package/dist/workspace/computer-kept.js +147 -0
- package/dist/workspace/computer-mcp.js +4 -3
- package/dist/workspace/computer-ports.d.ts +23 -3
- package/dist/workspace/computer-ports.js +115 -5
- package/dist/workspace/index.d.ts +1 -2
- package/dist/workspace/index.js +1 -2
- package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
- package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
- package/dist/workspace/resolve-computer.d.ts +15 -3
- package/dist/workspace/resolve-computer.js +10 -7
- package/dist/workspace/revision-skills.d.ts +6 -2
- package/dist/workspace/revision-skills.js +12 -5
- package/dist/workspace/run-end-computers.d.ts +30 -0
- package/dist/workspace/run-end-computers.js +137 -0
- package/dist/workspace/run-tools.d.ts +28 -29
- package/dist/workspace/run-tools.js +29 -30
- package/dist/wrap-up.d.ts +19 -5
- package/dist/wrap-up.js +31 -4
- package/package.json +13 -9
- package/skills/agentrun-serve/SKILL.md +248 -10
- package/templates/README.md +117 -23
- package/templates/TOOLS.md +168 -0
- package/templates/code-review/agent.md +18 -4
- package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
- package/templates/code-review/evals/other-repo/case.yaml +1 -1
- package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
- package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
- package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
- package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
- package/templates/code-review/skills/review/DEEP.md +2 -2
- package/templates/code-review/skills/review/REVIEWER.md +2 -2
- package/templates/code-review/skills/review/SKILL.md +7 -3
- package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
- package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
- package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
- package/templates/release-notes/evals/other-repo/case.yaml +1 -1
- package/dist/console/assets/index-CjqQirbo.css +0 -1
- package/dist/console/assets/index-b6-XY5A9.js +0 -576
- package/dist/host-calls.d.ts +0 -20
- package/dist/host-calls.js +0 -12
- package/dist/runner/adapters/pi-computer.d.ts +0 -9
- package/dist/runner/adapters/pi-computer.js +0 -51
- package/dist/workspace/computer-script.d.ts +0 -53
- package/dist/workspace/computer-script.js +0 -172
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/** Historical sessions are data, never runnable commands or trusted learning input. */
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { ApiError } from '../errors.js';
|
|
4
|
+
import { transcriptOf, LIVE_MS } from '../import.js';
|
|
5
|
+
import { launchBody } from '../run-launch.js';
|
|
6
|
+
import { runMetricsOf } from '../timeline/index.js';
|
|
7
|
+
import { secretCut, secretsIn } from '../secret-cut.js';
|
|
8
|
+
import { SECRET_NAMES } from '../secrets.js';
|
|
9
|
+
export const REMOTE_HISTORY_SESSION_BYTES = 1_000_000;
|
|
10
|
+
export const REMOTE_HISTORY_BODY_BYTES = 2_000_000;
|
|
11
|
+
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
12
|
+
const fail = () => { throw new ApiError('input_invalid', 'History must contain bounded, completed sessions from the selected runtime, with no execution fields.'); };
|
|
13
|
+
const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : fail();
|
|
14
|
+
const keys = (value, allowed) => { if (Object.keys(value).some(key => !allowed.includes(key)))
|
|
15
|
+
fail(); };
|
|
16
|
+
const text = (value, max = 256_000) => typeof value === 'string' && !value.includes('\0') && Buffer.byteLength(value) <= max ? value : fail();
|
|
17
|
+
const number = (value, max = Number.MAX_SAFE_INTEGER) => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= max ? value : fail();
|
|
18
|
+
const count = (value) => Number.isSafeInteger(value) ? number(value) : fail();
|
|
19
|
+
const optionalText = (value, max) => value === undefined ? undefined : text(value, max);
|
|
20
|
+
const canonical = (value) => Array.isArray(value) ? value.map(canonical) : value !== null && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;
|
|
21
|
+
function argumentsOf(value, depth = 0) {
|
|
22
|
+
if (depth > 16)
|
|
23
|
+
fail();
|
|
24
|
+
if (typeof value === 'string')
|
|
25
|
+
return text(value);
|
|
26
|
+
if (value === null || typeof value === 'boolean')
|
|
27
|
+
return value;
|
|
28
|
+
if (typeof value === 'number')
|
|
29
|
+
return Number.isFinite(value) ? value : fail();
|
|
30
|
+
if (Array.isArray(value)) {
|
|
31
|
+
if (value.length > 2000)
|
|
32
|
+
fail();
|
|
33
|
+
return value.map(item => argumentsOf(item, depth + 1));
|
|
34
|
+
}
|
|
35
|
+
const object = record(value);
|
|
36
|
+
if (Object.keys(object).length > 1000)
|
|
37
|
+
fail();
|
|
38
|
+
return Object.fromEntries(Object.entries(object).map(([key, item]) => [text(key, 1024), argumentsOf(item, depth + 1)]));
|
|
39
|
+
}
|
|
40
|
+
function turnOf(value, now) {
|
|
41
|
+
const t = record(value);
|
|
42
|
+
const role = t.role;
|
|
43
|
+
const at = count(t.at);
|
|
44
|
+
if (at > now)
|
|
45
|
+
fail();
|
|
46
|
+
const common = ['role', 'text', 'at', 'uuids'];
|
|
47
|
+
const base = { role, text: text(t.text), at, ...(t.uuids === undefined ? {} : { uuids: (() => { if (!Array.isArray(t.uuids) || t.uuids.length > 1000)
|
|
48
|
+
fail(); return t.uuids.map((id) => text(id, 1024)); })() }) };
|
|
49
|
+
if (role === 'user') {
|
|
50
|
+
keys(t, common);
|
|
51
|
+
return { ...base, role };
|
|
52
|
+
}
|
|
53
|
+
if (role === 'note') {
|
|
54
|
+
keys(t, [...common, 'author']);
|
|
55
|
+
return { ...base, role, author: text(t.author, 1024) };
|
|
56
|
+
}
|
|
57
|
+
if (role === 'toolResult') {
|
|
58
|
+
keys(t, [...common, 'callId', 'name', 'isError']);
|
|
59
|
+
if (typeof t.isError !== 'boolean')
|
|
60
|
+
fail();
|
|
61
|
+
return { ...base, role, callId: text(t.callId, 1024), name: text(t.name, 1024), isError: t.isError };
|
|
62
|
+
}
|
|
63
|
+
if (role !== 'assistant')
|
|
64
|
+
fail();
|
|
65
|
+
keys(t, [...common, 'calls', 'costUsd', 'key', 'model', 'effort', 'usage', 'error']);
|
|
66
|
+
if (!Array.isArray(t.calls) || t.calls.length > 100)
|
|
67
|
+
fail();
|
|
68
|
+
const calls = t.calls.map((value) => { const c = record(value); keys(c, ['type', 'id', 'name', 'arguments']); if (c.type !== 'toolCall')
|
|
69
|
+
fail(); record(c.arguments); return { type: 'toolCall', id: text(c.id, 1024), name: text(c.name, 1024), arguments: argumentsOf(c.arguments) }; });
|
|
70
|
+
let usage;
|
|
71
|
+
if (t.usage !== undefined) {
|
|
72
|
+
const u = record(t.usage);
|
|
73
|
+
keys(u, ['input', 'output', 'cacheRead', 'cacheWrite', 'cacheWrite1h']);
|
|
74
|
+
usage = { input: count(u.input), output: count(u.output), cacheRead: count(u.cacheRead), cacheWrite: count(u.cacheWrite), ...(u.cacheWrite1h === undefined ? {} : { cacheWrite1h: count(u.cacheWrite1h) }) };
|
|
75
|
+
}
|
|
76
|
+
const rest = Object.fromEntries(['key', 'model', 'effort', 'error'].flatMap(key => t[key] === undefined ? [] : [[key, text(t[key], key === 'error' ? 4096 : 1024)]]));
|
|
77
|
+
return { ...base, role, calls, ...rest, ...(usage ? { usage } : {}), ...(t.costUsd === undefined ? {} : { costUsd: number(t.costUsd, 1e9) }) };
|
|
78
|
+
}
|
|
79
|
+
export function remoteHistorySessions(input, runtime, now = Date.now()) {
|
|
80
|
+
const body = record(input);
|
|
81
|
+
keys(body, ['sessions']);
|
|
82
|
+
if (Buffer.byteLength(JSON.stringify(body)) > REMOTE_HISTORY_BODY_BYTES)
|
|
83
|
+
throw new ApiError('payload_too_large', 'Import at most 2 MB of history per request.');
|
|
84
|
+
if (!Array.isArray(body.sessions) || body.sessions.length < 1 || body.sessions.length > 20)
|
|
85
|
+
fail();
|
|
86
|
+
return body.sessions.map((value) => {
|
|
87
|
+
const s = record(value);
|
|
88
|
+
keys(s, ['source', 'id', 'startedAt', 'endedAt', 'state', 'model', 'costUsd', 'firstPrompt', 'activeMs', 'turns']);
|
|
89
|
+
if (Buffer.byteLength(JSON.stringify(s)) > REMOTE_HISTORY_SESSION_BYTES || s.source !== runtime || !['completed', 'failed', 'stopped'].includes(String(s.state)))
|
|
90
|
+
fail();
|
|
91
|
+
const id = text(s.id, 1024);
|
|
92
|
+
if (!id.trim())
|
|
93
|
+
fail();
|
|
94
|
+
const startedAt = text(s.startedAt, 64), endedAt = text(s.endedAt, 64), start = Date.parse(startedAt), end = Date.parse(endedAt);
|
|
95
|
+
if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end < start || end > now - LIVE_MS)
|
|
96
|
+
throw new ApiError('input_invalid', 'Only sessions ended at least ten minutes ago can be imported. Live sessions stay on their source machine.');
|
|
97
|
+
if (!Array.isArray(s.turns) || s.turns.length > 2000)
|
|
98
|
+
fail();
|
|
99
|
+
return { source: runtime, id, startedAt, endedAt, state: s.state, activeMs: count(s.activeMs), turns: s.turns.map((turn) => turnOf(turn, now - LIVE_MS)), ...(s.model === undefined ? {} : { model: optionalText(s.model, 1024) }), ...(s.firstPrompt === undefined ? {} : { firstPrompt: optionalText(s.firstPrompt, 256_000) }), ...(s.costUsd === undefined ? {} : { costUsd: number(s.costUsd, 1e9) }) };
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
/** Defense in depth for clients other than the shipped source exporter. The destination's credentials and recognized
|
|
103
|
+
* keys are never retained in imported journal text, even when a source submitted an unsanitized session. */
|
|
104
|
+
export async function redactRemoteHistory(sessions, own = []) {
|
|
105
|
+
const cut = secretCut(process.env, SECRET_NAMES), serialized = JSON.stringify(sessions);
|
|
106
|
+
cut.add(own);
|
|
107
|
+
cut.add(await secretsIn(serialized));
|
|
108
|
+
cut.add(serialized.match(/ar_(?:connector|enroll|local)_[A-Za-z0-9_-]{20,}/g) ?? []);
|
|
109
|
+
return sessions.map(packet => { const redacted = cut.json(packet); if (redacted.id !== packet.id)
|
|
110
|
+
redacted.id = `redacted-${hash(packet.id).slice(0, 16)}`; return redacted; });
|
|
111
|
+
}
|
|
112
|
+
export async function importRemoteHistory(store, connectorId, targetId, agentId, revisionId, sessions, beforeWrite) {
|
|
113
|
+
const runs = [];
|
|
114
|
+
for (const packet of sessions) {
|
|
115
|
+
const settingsGuards = await beforeWrite?.();
|
|
116
|
+
const fingerprint = hash(JSON.stringify(canonical(packet)));
|
|
117
|
+
const identity = `${connectorId}:${targetId}:${packet.source}:${packet.id}`;
|
|
118
|
+
const runId = `history-${hash(identity)}`;
|
|
119
|
+
const sourceSession = `remote-${hash(`${connectorId}:${targetId}`).slice(0, 24)}:${packet.id}`;
|
|
120
|
+
const check = (row) => {
|
|
121
|
+
if (!row)
|
|
122
|
+
return false;
|
|
123
|
+
if (row.agentId !== agentId || row.importedFrom?.source !== packet.source || row.importedFrom.session !== sourceSession || !/^[a-f0-9]{64}$/.test(String(row.metrics?.remote_history_sha256)))
|
|
124
|
+
throw new ApiError('idempotency_mismatch', 'This source session identity belongs to different history. Existing history was kept.');
|
|
125
|
+
// Native conversations can resume under the same source ID. Preserve their first historical snapshot, as the
|
|
126
|
+
// local importer does; later growth must not overwrite it or prevent the next session from importing.
|
|
127
|
+
runs.push({ session_id: packet.id, run_id: runId, already: true });
|
|
128
|
+
return true;
|
|
129
|
+
};
|
|
130
|
+
if (check(await store.runs.get(runId)))
|
|
131
|
+
continue;
|
|
132
|
+
const session = { ...packet, file: '', child: false, users: packet.turns.filter(turn => turn.role === 'user').length, copies: 0 };
|
|
133
|
+
const { batches, entries } = transcriptOf(session, value => value);
|
|
134
|
+
const answer = session.turns.findLast(turn => turn.role === 'assistant' && turn.text)?.text;
|
|
135
|
+
try {
|
|
136
|
+
await store.importRun({ id: runId, agentId, revisionId, importedFrom: { source: packet.source, session: sourceSession }, launch: { body: launchBody({ input: { content: session.firstPrompt ?? '' }, title: (session.firstPrompt ?? `${packet.source} session`).slice(0, 120), place: { mode: 'runner' } }) }, state: session.state === 'completed' ? 'ended' : session.state, ...(session.costUsd === undefined ? {} : { costUsd: session.costUsd }), summary: answer ?? session.firstPrompt ?? '', metrics: { ...runMetricsOf(entries), activeMs: session.activeMs, remote_history_sha256: fingerprint }, startedAt: Date.parse(session.startedAt), endedAt: Date.parse(session.endedAt), transcript: batches, settingsGuards, requireActiveAgent: true });
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
await beforeWrite?.();
|
|
140
|
+
if (check(await store.runs.get(runId)))
|
|
141
|
+
continue;
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
runs.push({ session_id: packet.id, run_id: runId, already: false });
|
|
145
|
+
}
|
|
146
|
+
return { agent_id: agentId, runs, imported: runs.filter(run => !run.already).length, already: runs.filter(run => run.already).length };
|
|
147
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { NativeBinding, NativeTarget } from "./types.js";
|
|
2
|
+
export type NativeInstructionSnapshot = {
|
|
3
|
+
text: string;
|
|
4
|
+
files: {
|
|
5
|
+
path: string;
|
|
6
|
+
sha256: string;
|
|
7
|
+
}[];
|
|
8
|
+
truncated: boolean;
|
|
9
|
+
/** A policy source could not be captured; distinct from exceeding the byte limit. */
|
|
10
|
+
incomplete?: string;
|
|
11
|
+
/** This snapshot inspected the discovered Codex policy configuration layers. */
|
|
12
|
+
codexConfigurationChecked?: true;
|
|
13
|
+
/** This snapshot used Claude settings and agent precedence recorded by fresh discovery. */
|
|
14
|
+
claudeConfigurationChecked?: true;
|
|
15
|
+
/** Captured Claude text was checked for imports and discovery inspected direct policy sources. */
|
|
16
|
+
claudePolicySourcesChecked?: true;
|
|
17
|
+
};
|
|
18
|
+
/** Read-only, bounded policy evidence for grading. This text is never installed as grader runtime instructions. */
|
|
19
|
+
export declare function snapshotNativeInstructions(target: NativeTarget | NativeBinding, redact?: (text: string) => string): Promise<NativeInstructionSnapshot>;
|
|
20
|
+
/** Record the pinned AgentRun policy beside native source policy, as bounded redacted grading evidence. */
|
|
21
|
+
export declare function withSavedNativeInstructions(snapshot: NativeInstructionSnapshot, instructions: string, redact: (text: string) => string): NativeInstructionSnapshot;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { basename, dirname, sep } from "node:path";
|
|
4
|
+
import { parse as parseToml } from "smol-toml";
|
|
5
|
+
import { NATIVE_GRADE_INSTRUCTION_BYTES } from "../learn/grade.js";
|
|
6
|
+
import { NATIVE_RUNTIME_FACTS, NATIVE_CLAUDE_POLICY_UNRESOLVED, NATIVE_CLAUDE_ADDITIONAL_POLICY_UNRESOLVED } from './runtimes.js';
|
|
7
|
+
const depth = (path) => path.split(sep).length;
|
|
8
|
+
const scopeOf = (path) => basename(dirname(path)) === ".claude" ? dirname(dirname(path)) : dirname(path);
|
|
9
|
+
/** Read-only, bounded policy evidence for grading. This text is never installed as grader runtime instructions. */
|
|
10
|
+
export async function snapshotNativeInstructions(target, redact = text => text) {
|
|
11
|
+
const captured = new Map();
|
|
12
|
+
const read = async (path) => { const prior = captured.get(path); if (prior)
|
|
13
|
+
return prior; try {
|
|
14
|
+
const bytes = await readFile(path);
|
|
15
|
+
captured.set(path, bytes);
|
|
16
|
+
return bytes;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
throw new Error(`Native instructions cannot be read: ${path}. Discover this project again before launching.`);
|
|
20
|
+
} };
|
|
21
|
+
const verified = async (file) => { const bytes = await read(file.path); if (createHash("sha256").update(bytes).digest("hex") !== file.sha256)
|
|
22
|
+
throw new Error(`Native instructions changed after discovery: ${file.path}. Discover this project again before launching.`); return bytes.toString("utf8"); };
|
|
23
|
+
const names = new Set(target.runtime === "claude-code" ? ["CLAUDE.md", "CLAUDE.local.md"] : ["AGENTS.md", "AGENTS.override.md"]);
|
|
24
|
+
const files = target.configuration.filter(file => names.has(basename(file.path))).sort((a, b) => depth(scopeOf(a.path)) - depth(scopeOf(b.path)) || a.path.localeCompare(b.path));
|
|
25
|
+
let incomplete = [NATIVE_CLAUDE_POLICY_UNRESOLVED, NATIVE_CLAUDE_ADDITIONAL_POLICY_UNRESOLVED].find(issue => target.issues.includes(issue));
|
|
26
|
+
const configEvidence = [];
|
|
27
|
+
const codex = NATIVE_RUNTIME_FACTS[target.runtime].protocol === 'codex-json';
|
|
28
|
+
if (codex) {
|
|
29
|
+
// Codex owns precedence and trust. Inspect every potentially active layer, without merging TOML
|
|
30
|
+
// or reading policy paths from an untrusted config. Named profiles use --profile <name> and
|
|
31
|
+
// $CODEX_HOME/<name>.config.toml; an unselected profile cannot change this task's policy.
|
|
32
|
+
const configs = target.configuration.filter(file => basename(file.path) === "config.toml" || (target.selector.kind === "profile" && basename(file.path) === `${target.selector.name}.config.toml`));
|
|
33
|
+
for (const file of configs) {
|
|
34
|
+
let config;
|
|
35
|
+
try {
|
|
36
|
+
config = parseToml(await verified(file));
|
|
37
|
+
configEvidence.push(file);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
incomplete = "Codex configuration could not be verified and parsed for complete policy evidence.";
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
// Older supported binaries may interpret legacy profile selectors/tables. Do not infer
|
|
44
|
+
// their effective policy from the current CLI's profile-file contract.
|
|
45
|
+
if (["model_instructions_file", "experimental_instructions_file", "developer_instructions", "profile", "profiles"].some(key => Object.hasOwn(config, key))) {
|
|
46
|
+
incomplete = "Codex configuration can supply custom policy outside the captured standing instruction files.";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
let mainAgent = target.selector.kind === "agent" ? target.selector.name : undefined;
|
|
51
|
+
if (target.runtime === "claude-code" && target.selector.kind === "project") {
|
|
52
|
+
// Discovery records scope precedence independently of CLAUDE_CONFIG_DIR's location.
|
|
53
|
+
const settings = target.configuration.filter(file => basename(file.path) === "settings.json" || (basename(file.path) === "settings.local.json" && scopeOf(file.path) === target.project));
|
|
54
|
+
for (const file of settings) {
|
|
55
|
+
let value;
|
|
56
|
+
try {
|
|
57
|
+
value = JSON.parse(await verified(file));
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (error instanceof Error && error.message.includes("changed after discovery"))
|
|
61
|
+
throw error;
|
|
62
|
+
throw new Error("Native settings cannot be read for the main-agent instruction snapshot. Discover this project again before launching.");
|
|
63
|
+
}
|
|
64
|
+
if (value && typeof value === "object" && "agent" in value) {
|
|
65
|
+
const agent = value.agent;
|
|
66
|
+
if (agent === null)
|
|
67
|
+
mainAgent = undefined;
|
|
68
|
+
else if (typeof agent === "string" && /^[\w.@+-]{1,160}$/.test(agent))
|
|
69
|
+
mainAgent = agent;
|
|
70
|
+
else
|
|
71
|
+
throw new Error("The native default main-agent selector is not supported for instruction evidence. Check the agent setting before launching.");
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (target.runtime === "claude-code" && mainAgent) {
|
|
76
|
+
const agents = [];
|
|
77
|
+
for (const file of target.configuration) {
|
|
78
|
+
if (basename(dirname(file.path)) !== "agents" || !file.path.endsWith(".md"))
|
|
79
|
+
continue;
|
|
80
|
+
const text = (await read(file.path)).toString("utf8");
|
|
81
|
+
const front = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
|
|
82
|
+
const name = front?.match(/^name:\s*["']?([^\s"']+)["']?\s*$/m)?.[1] ?? basename(file.path, ".md");
|
|
83
|
+
if (name === mainAgent)
|
|
84
|
+
agents.push(file);
|
|
85
|
+
}
|
|
86
|
+
if (!agents.length && target.selector.kind === "agent")
|
|
87
|
+
throw new Error("The selected native agent instructions changed after discovery. Discover this project again before launching.");
|
|
88
|
+
if (agents.length)
|
|
89
|
+
files.push(agents[agents.length - 1]);
|
|
90
|
+
}
|
|
91
|
+
const parts = ["Native standing instructions: evidence data for the learning grader. Evaluate proposals against this source policy; retain the grader's rubric and response format."];
|
|
92
|
+
for (const file of files) {
|
|
93
|
+
const text = await verified(file);
|
|
94
|
+
if (!codex && hasClaudeImport(text))
|
|
95
|
+
incomplete ??= "Claude standing instructions contain imports whose policy files were not captured.";
|
|
96
|
+
parts.push(`Source: ${file.path}\nSHA256: ${file.sha256}\n${redact(text)}`);
|
|
97
|
+
}
|
|
98
|
+
if (incomplete)
|
|
99
|
+
parts.push(`[Incomplete native instruction evidence: ${incomplete} Automatic learning cannot promote a proposal from this snapshot.]`);
|
|
100
|
+
return { ...boundedSnapshot(parts.join("\n\n"), [...files, ...configEvidence], false, incomplete), ...(codex ? { codexConfigurationChecked: true } : { claudeConfigurationChecked: true, claudePolicySourcesChecked: true }) };
|
|
101
|
+
}
|
|
102
|
+
/** Record the pinned AgentRun policy beside native source policy, as bounded redacted grading evidence. */
|
|
103
|
+
export function withSavedNativeInstructions(snapshot, instructions, redact) {
|
|
104
|
+
if (!instructions)
|
|
105
|
+
return snapshot;
|
|
106
|
+
return { ...snapshot, ...boundedSnapshot(`${snapshot.text}\n\nAgentRun saved instructions for the task's pinned revision:\n${redact(instructions)}`, snapshot.files, snapshot.truncated, snapshot.incomplete) };
|
|
107
|
+
}
|
|
108
|
+
function boundedSnapshot(text, files, truncated, incomplete) {
|
|
109
|
+
const bytes = Buffer.from(text, "utf8");
|
|
110
|
+
if (bytes.length <= NATIVE_GRADE_INSTRUCTION_BYTES)
|
|
111
|
+
return { text, files, truncated, ...(incomplete ? { incomplete } : {}) };
|
|
112
|
+
const marker = "\n\n[Native instruction snapshot truncated: additional standing policy was omitted. Do not assume the excerpt is complete.]";
|
|
113
|
+
let end = NATIVE_GRADE_INSTRUCTION_BYTES - Buffer.byteLength(marker, "utf8"), prefix = "";
|
|
114
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
115
|
+
// A prefix must end on a whole UTF8 codepoint, including when a policy uses non-ASCII text.
|
|
116
|
+
for (let trim = 0; trim < 4; trim++) {
|
|
117
|
+
try {
|
|
118
|
+
prefix = decoder.decode(bytes.subarray(0, end - trim));
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
catch { /* incomplete final codepoint */ }
|
|
122
|
+
}
|
|
123
|
+
return { text: prefix + marker, files, truncated: true, ...(incomplete ? { incomplete } : {}) };
|
|
124
|
+
}
|
|
125
|
+
/** Detect potential imports without resolving paths or reading outside discovered policy sources.
|
|
126
|
+
* Markdown code and quoted paths are examples, not imports. This is deliberately a conservative
|
|
127
|
+
* coverage check, not a replacement for Claude's import parser or first-use approval. */
|
|
128
|
+
function hasClaudeImport(text) {
|
|
129
|
+
let fence;
|
|
130
|
+
const prose = [];
|
|
131
|
+
for (const line of text.split(/\r?\n/)) {
|
|
132
|
+
const run = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
|
|
133
|
+
if (fence) {
|
|
134
|
+
if (run && run[1][0] === fence.char && run[1].length >= fence.length && !run[2].trim())
|
|
135
|
+
fence = undefined;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (run && (run[1][0] === '~' || !run[2].includes('`'))) {
|
|
139
|
+
fence = { char: run[1][0], length: run[1].length };
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
prose.push(line);
|
|
143
|
+
}
|
|
144
|
+
// Mask only single-line code spans. Pairing ticks across lines could cross Markdown blocks;
|
|
145
|
+
// ambiguous multiline examples conservatively retain potential imports for the coverage check.
|
|
146
|
+
return prose.some(body => {
|
|
147
|
+
let outside = '', offset = 0;
|
|
148
|
+
const ticks = [...body.matchAll(/`+/g)];
|
|
149
|
+
const next = new Map(), closes = new Map();
|
|
150
|
+
for (let i = ticks.length - 1; i >= 0; i--) {
|
|
151
|
+
const close = next.get(ticks[i][0].length);
|
|
152
|
+
if (close !== undefined)
|
|
153
|
+
closes.set(i, close);
|
|
154
|
+
next.set(ticks[i][0].length, i);
|
|
155
|
+
}
|
|
156
|
+
for (let i = 0; i < ticks.length; i++) {
|
|
157
|
+
const open = ticks[i], close = closes.get(i);
|
|
158
|
+
let slashes = 0;
|
|
159
|
+
for (let at = open.index - 1; at >= 0 && body[at] === '\\'; at--)
|
|
160
|
+
slashes++;
|
|
161
|
+
if (slashes % 2 || close === undefined)
|
|
162
|
+
continue; // Escaped or unmatched ticks must not hide later policy.
|
|
163
|
+
outside += body.slice(offset, open.index) + ' ';
|
|
164
|
+
offset = ticks[close].index + ticks[close][0].length;
|
|
165
|
+
i = close;
|
|
166
|
+
}
|
|
167
|
+
outside += body.slice(offset);
|
|
168
|
+
// An email is inert, but @owner@example.com is an explicit potential import. The left
|
|
169
|
+
// boundary also prevents the engine from restarting inside that filename's local part.
|
|
170
|
+
outside = outside.replace(/(?<![@\p{L}\p{N}._%+-])[\p{L}\p{N}._%+-]+@[\p{L}\p{N}.-]+\.[\p{L}]{2,}(?=$|[\s.,;:!?)>])/gu, ' ');
|
|
171
|
+
return /@[^\s'"`]/.test(outside);
|
|
172
|
+
});
|
|
173
|
+
}
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/** Source-side JSONL bridge for the explicit remote connector. All native paths and selectors come from the
|
|
2
|
+
* connector's local allowlist. The network peer cannot choose a binary, environment, or arbitrary directory. */
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
|
6
|
+
import { tmpdir } from 'node:os';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { execFile } from 'node:child_process';
|
|
9
|
+
import { promisify, types } from 'node:util';
|
|
10
|
+
import { discoverNative, nativeIdentity, verifyNative } from './discovery.js';
|
|
11
|
+
import { nativeEnvironment } from './environment.js';
|
|
12
|
+
import { openNativeSession } from './runtime.js';
|
|
13
|
+
import { snapshotNativeInstructions } from './instructions.js';
|
|
14
|
+
import { nativeSkillContext } from './context.js';
|
|
15
|
+
import { exportRemoteHistory } from '../import.js';
|
|
16
|
+
import { runnerSecrets, secretRedactor } from '../runner/redact.js';
|
|
17
|
+
import { redactedOutput } from '../key-refusal.js';
|
|
18
|
+
const object = (value) => {
|
|
19
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
20
|
+
throw new Error('Expected an object.');
|
|
21
|
+
return value;
|
|
22
|
+
};
|
|
23
|
+
const text = (value, max = 1_000_000) => {
|
|
24
|
+
if (typeof value !== 'string' || value.length > max)
|
|
25
|
+
throw new Error('Invalid text value.');
|
|
26
|
+
return value;
|
|
27
|
+
};
|
|
28
|
+
const key = (value) => { const result = text(value, 160); if (!/^[\w-]+$/.test(result))
|
|
29
|
+
throw new Error('Invalid session identity.'); return result; };
|
|
30
|
+
const runtime = (value) => { if (value !== 'claude-code' && value !== 'codex')
|
|
31
|
+
throw new Error('Unsupported native runtime.'); return value; };
|
|
32
|
+
const targetOf = (value) => {
|
|
33
|
+
const target = object(value), selector = object(target.selector);
|
|
34
|
+
if (!['project', 'agent', 'profile'].includes(String(selector.kind)))
|
|
35
|
+
throw new Error('Invalid native selector.');
|
|
36
|
+
if (selector.kind !== 'project' && (typeof selector.name !== 'string' || !/^[\w.@+-]{1,160}$/.test(selector.name)))
|
|
37
|
+
throw new Error('Invalid native selector.');
|
|
38
|
+
return { project: text(target.project, 4096), runtime: runtime(target.runtime), machine_id: text(target.machine_id, 128), selector: selector };
|
|
39
|
+
};
|
|
40
|
+
export async function runRemoteWorkerBridge(options = {}) {
|
|
41
|
+
const idleTimeoutMs = Math.min(Math.max(options.idleTimeoutMs ?? 600_000, 1), 600_000);
|
|
42
|
+
const env = nativeEnvironment(), secrets = runnerSecrets(env, runnerSecrets(process.env)), redact = secretRedactor(secrets);
|
|
43
|
+
const sessions = new Map();
|
|
44
|
+
const operations = new Map();
|
|
45
|
+
// Payloads come from native JSON, but their unknown fields must not run getters/toJSON
|
|
46
|
+
// or recurse forever. Redact scalar values and names before serializing the protocol.
|
|
47
|
+
const payload = (value, parents = new Set(), depth = 0) => {
|
|
48
|
+
if (typeof value === 'string')
|
|
49
|
+
return redact(value);
|
|
50
|
+
if (typeof value === 'number')
|
|
51
|
+
return secrets.length ? redactedOutput(value, secrets) : value;
|
|
52
|
+
if (value === null || value === undefined || typeof value === 'boolean')
|
|
53
|
+
return value;
|
|
54
|
+
if (typeof value !== 'object' || depth > 64 || parents.has(value) || types.isProxy(value))
|
|
55
|
+
return '[redacted]';
|
|
56
|
+
const array = Array.isArray(value), prototype = Object.getPrototypeOf(value);
|
|
57
|
+
if (!array && prototype !== Object.prototype && prototype !== null)
|
|
58
|
+
return '[redacted]';
|
|
59
|
+
parents.add(value);
|
|
60
|
+
try {
|
|
61
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
62
|
+
const read = (entry) => !entry ? undefined : 'value' in entry ? payload(entry.value, parents, depth + 1) : '[redacted]';
|
|
63
|
+
if (array)
|
|
64
|
+
return Array.from({ length: value.length }, (_, index) => read(descriptors[String(index)]));
|
|
65
|
+
const entries = Object.entries(descriptors).filter(([, entry]) => entry.enumerable).map(([name, entry]) => [redact(name), read(entry)]);
|
|
66
|
+
return new Set(entries.map(([name]) => name)).size === entries.length ? Object.fromEntries(entries) : '[redacted]';
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
parents.delete(value);
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const output = (value) => {
|
|
73
|
+
// These identities are generated by the connector, not native payload text. Redacting
|
|
74
|
+
// a serialized JSON line can erase them (or its braces) when a payload has a long atom.
|
|
75
|
+
const safe = 'result' in value ? { id: value.id, result: payload(value.result) }
|
|
76
|
+
: 'event' in value ? { session_key: value.session_key, event: payload(value.event) }
|
|
77
|
+
: { ...(value.id === undefined ? {} : { id: value.id }), error: redact(value.error) };
|
|
78
|
+
return process.stdout.write(JSON.stringify(safe) + '\n');
|
|
79
|
+
};
|
|
80
|
+
const close = async (sessionKey) => {
|
|
81
|
+
const held = sessions.get(sessionKey);
|
|
82
|
+
if (!held)
|
|
83
|
+
return;
|
|
84
|
+
sessions.delete(sessionKey);
|
|
85
|
+
clearTimeout(held.idle);
|
|
86
|
+
try {
|
|
87
|
+
await held.session.close();
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
await rm(held.root, { recursive: true, force: true });
|
|
91
|
+
await rm(held.lock, { recursive: true, force: true });
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const expireIdle = (sessionKey) => {
|
|
95
|
+
const held = sessions.get(sessionKey);
|
|
96
|
+
if (!held)
|
|
97
|
+
return;
|
|
98
|
+
clearTimeout(held.idle);
|
|
99
|
+
held.idle = setTimeout(() => { void close(sessionKey); }, idleTimeoutMs);
|
|
100
|
+
};
|
|
101
|
+
const shutdown = async () => { for (const abort of operations.values())
|
|
102
|
+
abort.abort(); await Promise.allSettled([...sessions.keys()].map(close)); };
|
|
103
|
+
const signals = () => { void shutdown().finally(() => process.exit(0)); };
|
|
104
|
+
process.once('SIGTERM', signals);
|
|
105
|
+
process.once('SIGINT', signals);
|
|
106
|
+
const current = async (value) => {
|
|
107
|
+
const chosen = targetOf(value), report = await discoverNative({ project: chosen.project, runtime: chosen.runtime, env });
|
|
108
|
+
const found = report.targets.find(item => nativeIdentity(item) === nativeIdentity(chosen));
|
|
109
|
+
if (!found)
|
|
110
|
+
throw new Error('The selected native target no longer exists on this source machine.');
|
|
111
|
+
const verified = await verifyNative(found, { env });
|
|
112
|
+
if (!verified.connected || verified.state !== 'ready')
|
|
113
|
+
throw new Error('The selected native runtime is not ready. Check its source-machine sign-in and configuration.');
|
|
114
|
+
return verified;
|
|
115
|
+
};
|
|
116
|
+
const dispatch = async (message, signal) => {
|
|
117
|
+
const payload = message.payload === undefined ? {} : object(message.payload), type = message.type;
|
|
118
|
+
if (type === 'discover')
|
|
119
|
+
return discoverNative({ project: text(payload.project, 4096), ...(payload.runtime ? { runtime: runtime(payload.runtime) } : {}), env });
|
|
120
|
+
// Local connector action only: the Python network worker never dispatches these operations.
|
|
121
|
+
if (type === 'history-preview' || type === 'history-export') {
|
|
122
|
+
const target = targetOf(message.target);
|
|
123
|
+
if (target.selector.kind !== 'project')
|
|
124
|
+
throw new Error('History belongs to a project and runtime; select project history instead of a named agent or profile.');
|
|
125
|
+
if (payload.cursor !== undefined && (!Number.isSafeInteger(payload.cursor) || Number(payload.cursor) < 0))
|
|
126
|
+
throw new Error('Invalid local history cursor.');
|
|
127
|
+
if (payload.inventory !== undefined && (typeof payload.inventory !== 'string' || !/^[a-f0-9]{64}$/.test(payload.inventory)))
|
|
128
|
+
throw new Error('Invalid local history inventory.');
|
|
129
|
+
if (payload.redact_values !== undefined && (!Array.isArray(payload.redact_values) || payload.redact_values.length > 16))
|
|
130
|
+
throw new Error('Invalid local history redaction values.');
|
|
131
|
+
const own = Array.isArray(payload.redact_values) ? payload.redact_values.map(value => text(value, 8192)) : [];
|
|
132
|
+
return exportRemoteHistory(target, { env, own, preview: type === 'history-preview', ...(payload.inventory === undefined ? {} : { inventory: String(payload.inventory) }), ...(payload.cursor === undefined ? {} : { cursor: Number(payload.cursor) }) });
|
|
133
|
+
}
|
|
134
|
+
if (type === 'prepare') {
|
|
135
|
+
const target = await current(message.target), instructions = await snapshotNativeInstructions(target, redact);
|
|
136
|
+
return { target, instructions };
|
|
137
|
+
}
|
|
138
|
+
if (type === 'close') {
|
|
139
|
+
const sessionKey = key(message.session_key), held = sessions.get(sessionKey);
|
|
140
|
+
if (held && nativeIdentity(targetOf(message.target)) !== held.identity)
|
|
141
|
+
throw new Error('The session belongs to a different source target.');
|
|
142
|
+
await close(sessionKey);
|
|
143
|
+
return {};
|
|
144
|
+
}
|
|
145
|
+
if (type === 'send') {
|
|
146
|
+
const sessionKey = key(message.session_key), held = sessions.get(sessionKey);
|
|
147
|
+
if (!held)
|
|
148
|
+
throw new Error('The native session is unavailable; an uncertain turn is never resumed automatically.');
|
|
149
|
+
if (nativeIdentity(targetOf(message.target)) !== held.identity)
|
|
150
|
+
throw new Error('The session belongs to a different source target.');
|
|
151
|
+
clearTimeout(held.idle);
|
|
152
|
+
try {
|
|
153
|
+
return await held.session.send(text(payload.prompt), { signal, reflection: payload.reflection === true, timeoutMs: timeout(payload.timeout_ms) });
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
expireIdle(sessionKey);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (type !== 'open' && type !== 'grade')
|
|
160
|
+
throw new Error('Unsupported remote operation.');
|
|
161
|
+
const approved = await current(message.target), identity = nativeIdentity(approved);
|
|
162
|
+
const sessionKey = type === 'grade' ? `grade-${key(message.id)}` : key(message.session_key);
|
|
163
|
+
if (sessions.has(sessionKey) || sessions.size >= 8)
|
|
164
|
+
throw new Error('The native session already exists or the source session limit was reached.');
|
|
165
|
+
signal.throwIfAborted();
|
|
166
|
+
if (type === 'open' && (typeof payload.expected_fingerprint !== 'string' || payload.expected_fingerprint !== approved.fingerprint))
|
|
167
|
+
throw new Error('The source configuration changed after preparation. Start a new run after reviewing it.');
|
|
168
|
+
const root = await mkdtemp(join(tmpdir(), 'agentrun-remote-'));
|
|
169
|
+
const locks = join(tmpdir(), `agentrun-native-locks-${process.getuid?.() ?? 'user'}`);
|
|
170
|
+
await mkdir(locks, { mode: 0o700, recursive: true });
|
|
171
|
+
const lock = join(locks, createHash('sha256').update(type === 'grade' ? root : approved.project).digest('hex'));
|
|
172
|
+
try {
|
|
173
|
+
await mkdir(lock, { mode: 0o700 });
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
await rm(root, { recursive: true, force: true });
|
|
177
|
+
throw new Error('Another remote job holds this source project. Inspect any interrupted job before removing a stale source lock.');
|
|
178
|
+
}
|
|
179
|
+
let opened;
|
|
180
|
+
try {
|
|
181
|
+
let target = approved, context = payload.context === undefined ? '' : text(payload.context);
|
|
182
|
+
if (type === 'grade') {
|
|
183
|
+
await promisify(execFile)('git', ['init', '--quiet', root], { timeout: 10_000 });
|
|
184
|
+
const report = await discoverNative({ project: root, runtime: approved.runtime, env });
|
|
185
|
+
target = { ...report.targets.find(item => item.selector.kind === 'project'), connected: true };
|
|
186
|
+
if (!target.runtime)
|
|
187
|
+
throw new Error('The native grading runtime is unavailable.');
|
|
188
|
+
context = '';
|
|
189
|
+
}
|
|
190
|
+
else if (payload.skills !== undefined) {
|
|
191
|
+
if (!Array.isArray(payload.skills) || payload.skills.length > 64)
|
|
192
|
+
throw new Error('Invalid learned skills.');
|
|
193
|
+
const skills = payload.skills.map(value => {
|
|
194
|
+
const skill = object(value), files = object(skill.files);
|
|
195
|
+
if (Object.keys(files).length > 128)
|
|
196
|
+
throw new Error('Too many learned skill resources.');
|
|
197
|
+
const read = {};
|
|
198
|
+
for (const [path, value] of Object.entries(files))
|
|
199
|
+
read[path] = text(value);
|
|
200
|
+
return { name: text(skill.name, 128), files: read };
|
|
201
|
+
});
|
|
202
|
+
if (Buffer.byteLength(JSON.stringify(skills)) > 2_000_000)
|
|
203
|
+
throw new Error('Learned skills exceed the source limit.');
|
|
204
|
+
context = [context, await nativeSkillContext(join(root, 'skills'), skills)].filter(Boolean).join('\n\n');
|
|
205
|
+
}
|
|
206
|
+
signal.throwIfAborted();
|
|
207
|
+
const session = opened = await openNativeSession({ target, context, env, signal, onEvent: event => { output({ event, session_key: sessionKey }); } });
|
|
208
|
+
signal.throwIfAborted();
|
|
209
|
+
sessions.set(sessionKey, { session, root, lock, identity });
|
|
210
|
+
if (type === 'open') {
|
|
211
|
+
expireIdle(sessionKey);
|
|
212
|
+
return {};
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
return await session.send(text(payload.prompt), { signal, reflection: true, timeoutMs: timeout(payload.timeout_ms) });
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
await close(sessionKey);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
try {
|
|
223
|
+
await opened?.close();
|
|
224
|
+
}
|
|
225
|
+
finally {
|
|
226
|
+
await rm(root, { recursive: true, force: true });
|
|
227
|
+
await rm(lock, { recursive: true, force: true });
|
|
228
|
+
}
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
233
|
+
const pending = new Set();
|
|
234
|
+
for await (const line of lines) {
|
|
235
|
+
if (Buffer.byteLength(line) > 4_000_000) {
|
|
236
|
+
await shutdown();
|
|
237
|
+
throw new Error('Remote bridge request exceeds its limit.');
|
|
238
|
+
}
|
|
239
|
+
let message;
|
|
240
|
+
try {
|
|
241
|
+
message = object(JSON.parse(line));
|
|
242
|
+
key(message.id);
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
output({ error: 'Invalid remote bridge request.' });
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
const id = key(message.id);
|
|
249
|
+
if (message.type === 'cancel') {
|
|
250
|
+
operations.get(text(message.command_id, 160))?.abort();
|
|
251
|
+
output({ id, result: {} });
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (operations.has(id)) {
|
|
255
|
+
output({ id, error: 'Duplicate in-flight bridge request.' });
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
const abort = new AbortController();
|
|
259
|
+
operations.set(id, abort);
|
|
260
|
+
const task = dispatch(message, abort.signal).then(result => { output({ id, result }); }, error => { output({ id, error: error instanceof Error ? error.message : 'Native operation failed.' }); }).finally(() => { operations.delete(id); pending.delete(task); });
|
|
261
|
+
pending.add(task);
|
|
262
|
+
}
|
|
263
|
+
await shutdown();
|
|
264
|
+
await Promise.allSettled(pending);
|
|
265
|
+
process.removeListener('SIGTERM', signals);
|
|
266
|
+
process.removeListener('SIGINT', signals);
|
|
267
|
+
}
|
|
268
|
+
function timeout(value) {
|
|
269
|
+
if (value === undefined)
|
|
270
|
+
return 180_000;
|
|
271
|
+
if (!Number.isInteger(value) || value < 1 || value > 600_000)
|
|
272
|
+
throw new Error('Invalid native deadline.');
|
|
273
|
+
return value;
|
|
274
|
+
}
|
|
275
|
+
// The installed package requires Node >=24.22.3: this stays symlink-safe without repository scripts.
|
|
276
|
+
if (import.meta.main) {
|
|
277
|
+
await runRemoteWorkerBridge();
|
|
278
|
+
}
|