@parcha/agentrun-serve 0.1.0-beta.38 → 0.1.0-beta.40
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 +455 -0
- package/README.md +376 -125
- 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-B8Zn1Iqn.css +1 -0
- package/dist/console/assets/index-Jbxjcmdp.js +705 -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 +83 -0
- package/dist/email/account.js +159 -0
- package/dist/email/answer.d.ts +15 -0
- package/dist/email/answer.js +217 -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 +373 -0
- package/dist/email/names.d.ts +50 -0
- package/dist/email/names.js +74 -0
- package/dist/email/routes.d.ts +10 -0
- package/dist/email/routes.js +50 -0
- package/dist/email/tools.d.ts +27 -0
- package/dist/email/tools.js +562 -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 +12 -4
- package/dist/learn/compile.js +57 -20
- package/dist/learn/grade.d.ts +4 -0
- package/dist/learn/grade.js +4 -1
- package/dist/learn/promote.d.ts +130 -64
- package/dist/learn/promote.js +113 -202
- 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 +35 -8
- package/dist/learning-cost.js +27 -9
- 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 +39 -2
- package/dist/local-models.js +49 -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 +2 -1
- package/dist/openapi.js +404 -93
- 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 +10 -2
- package/dist/port-models.js +6 -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 +14 -0
- package/dist/refusal-words.js +16 -2
- package/dist/run-launch.d.ts +12 -1
- package/dist/run-launch.js +13 -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 +44 -38
- package/dist/run-view.js +93 -56
- package/dist/runnable.d.ts +13 -5
- package/dist/runnable.js +69 -60
- package/dist/runner/adapter-loop.d.ts +48 -13
- package/dist/runner/adapter-loop.js +691 -254
- package/dist/runner/adapter-run-spec.d.ts +38 -12
- package/dist/runner/adapter-run-spec.js +175 -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 +95 -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 +59 -13
- package/dist/runner/journal-kinds.js +48 -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 +14 -3
- package/dist/runner/model-route.js +155 -19
- 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 +76 -10
- package/dist/runner/promotion.js +476 -154
- 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 +568 -137
- 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/dialect.d.ts +3 -0
- package/dist/store/dialect.js +1 -0
- 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/connection.d.ts +11 -5
- package/dist/store/postgres/connection.js +44 -17
- package/dist/store/postgres/dialect.js +5 -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.d.ts +7 -3
- package/dist/store/postgres/store.js +4 -0
- package/dist/store/schema.d.ts +7 -0
- package/dist/store/schema.js +20 -1
- package/dist/store/sqlite/connection.js +72 -8
- package/dist/store/sqlite/run-launch.d.ts +11 -0
- package/dist/store/sqlite/run-launch.js +8 -0
- 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 +170 -34
- package/dist/store/sqlite/worker.d.ts +2 -0
- package/dist/store/sqlite/worker.js +13 -10
- package/dist/store/store.d.ts +67 -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 +115 -18
- package/dist/store-reads/learning.js +170 -68
- 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 +84 -21
- package/dist/templates.js +254 -47
- 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 +46 -44
- package/dist/tool-gate.js +101 -92
- 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 +57 -16
- package/dist/tools.js +33 -28
- package/dist/trigger-adapter.d.ts +56 -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 +181 -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 +105 -8
- package/dist/triggers.js +286 -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/decision-recovery.js +5 -2
- package/dist/workflow/decisions.d.ts +7 -0
- 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,492 @@
|
|
|
1
|
+
/** Outbound connector transport. Credentials are scoped to one source; commands use source-approved opaque targets.
|
|
2
|
+
* The ordinary runner owns runs, journals and learning. A leased command is NEVER dispatched again after uncertainty.
|
|
3
|
+
* CAS settings rows keep this contract across API/runner processes and restarts without a second run registry. */
|
|
4
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import { ApiError } from '../errors.js';
|
|
7
|
+
import { createAgent, getAgent } from '../agents-store.js';
|
|
8
|
+
import { nativeBindingOf, nativeOf } from './binding.js';
|
|
9
|
+
import { updateNative } from './connection.js';
|
|
10
|
+
import { NATIVE_RUNTIME_FACTS } from './runtimes.js';
|
|
11
|
+
import { importRemoteHistory, remoteHistorySessions, redactRemoteHistory } from './history.js';
|
|
12
|
+
const PREFIX = 'native.remote.';
|
|
13
|
+
const LEASE_MS = 30_000;
|
|
14
|
+
const ONLINE_MS = 45_000;
|
|
15
|
+
const MAX_COMMAND_BYTES = 2_000_000;
|
|
16
|
+
// Match the source worker's full UTF-8 HTTP envelope, including its lease token.
|
|
17
|
+
export const REMOTE_COMPLETION_BODY_BYTES = 4_000_000;
|
|
18
|
+
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
19
|
+
const keyOf = (kind, id) => `${PREFIX}${kind}.${id}`;
|
|
20
|
+
const opaque = (prefix) => `${prefix}_${randomBytes(16).toString('hex')}`;
|
|
21
|
+
const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
22
|
+
const text = (v, max = 160) => typeof v === 'string' && v.length > 0 && v.length <= max && !/[\x00-\x1f]/.test(v);
|
|
23
|
+
const validId = (v) => text(v) && /^[\w.-]+$/.test(v);
|
|
24
|
+
const bounded = (v, max = MAX_COMMAND_BYTES) => { if (Buffer.byteLength(JSON.stringify(v) ?? '') > max)
|
|
25
|
+
throw new ApiError('payload_too_large', 'The connector payload is too large.'); };
|
|
26
|
+
export class RemoteConnectors {
|
|
27
|
+
store;
|
|
28
|
+
now;
|
|
29
|
+
constructor(store, now = Date.now) {
|
|
30
|
+
this.store = store;
|
|
31
|
+
this.now = now;
|
|
32
|
+
}
|
|
33
|
+
async connector(id) {
|
|
34
|
+
const row = await this.store.settings.get(keyOf('connector', id));
|
|
35
|
+
if (!row)
|
|
36
|
+
throw new ApiError('not_found', 'This connector does not exist.');
|
|
37
|
+
return row;
|
|
38
|
+
}
|
|
39
|
+
async targets(id) {
|
|
40
|
+
return (await this.store.settings.all({ prefix: keyOf('target', `${id}.`) })).map(row => row.value);
|
|
41
|
+
}
|
|
42
|
+
async view(row) {
|
|
43
|
+
const targets = await this.targets(row.id);
|
|
44
|
+
return { id: row.id, connector_id: row.id, label: row.label, created_at: row.created_at, last_seen_at: row.last_seen ? new Date(row.last_seen).toISOString() : null,
|
|
45
|
+
status: row.revoked || row.expires <= this.now() ? 'revoked' : row.last_seen + ONLINE_MS >= this.now() ? 'online' : 'offline',
|
|
46
|
+
capabilities: { observe: true, native_execution: row.native_execution, history_import: row.history_import === true },
|
|
47
|
+
targets: targets.map(t => {
|
|
48
|
+
const disconnected = t.owner_disconnected || t.target.connected === false;
|
|
49
|
+
const issue = t.owner_disconnected ? 'Disconnected by the owner. Reconnect this target before starting a run.' : t.target.connected === false && !t.history_only ? 'This source target is disconnected. Reconnect it before starting a run.' : null;
|
|
50
|
+
return { target_id: t.target_id, agent_id: t.agent_id, name: t.name, history_only: t.history_only === true, runtime: t.target.runtime, machine_id: t.target.machine_id, state: disconnected ? 'needs_attention' : t.target.state, issues: issue ? [...t.target.issues, issue] : t.target.issues, capabilities: disconnected ? { ...t.target.capabilities, launch: false } : t.target.capabilities };
|
|
51
|
+
}) };
|
|
52
|
+
}
|
|
53
|
+
async list() {
|
|
54
|
+
const rows = await this.store.settings.all({ prefix: keyOf('connector', '') });
|
|
55
|
+
return { connectors: await Promise.all(rows.map(row => this.view(row.value))) };
|
|
56
|
+
}
|
|
57
|
+
async enroll(input) {
|
|
58
|
+
for (const row of await this.store.settings.all({ prefix: keyOf('enrollment', '') }))
|
|
59
|
+
if (row.value.expires <= this.now())
|
|
60
|
+
await this.store.settings.removeIf(row.key, row.value);
|
|
61
|
+
const b = object(input);
|
|
62
|
+
if (b.label !== undefined && !text(b.label))
|
|
63
|
+
throw new ApiError('input_invalid', 'Choose a short name for this source machine.');
|
|
64
|
+
const requested = object(b.capabilities);
|
|
65
|
+
if (b.capabilities !== undefined && (Object.keys(requested).some(key => !['native_execution', 'history_import'].includes(key)) || Object.values(requested).some(value => typeof value !== 'boolean')))
|
|
66
|
+
throw new ApiError('input_invalid', 'Choose live execution, history import, or both.');
|
|
67
|
+
const capabilities = { native_execution: requested.native_execution ?? true, history_import: requested.history_import ?? false };
|
|
68
|
+
if (!capabilities.native_execution && !capabilities.history_import)
|
|
69
|
+
throw new ApiError('input_invalid', 'Choose live execution, history import, or both.');
|
|
70
|
+
const token = `ar_enroll_${randomBytes(32).toString('base64url')}`;
|
|
71
|
+
const expires = this.now() + 10 * 60_000;
|
|
72
|
+
await this.store.settings.put(keyOf('enrollment', hash(token)), { expires, label: b.label ?? 'Remote machine', capabilities });
|
|
73
|
+
return { enrollment_token: token, expires_at: new Date(expires).toISOString(), workspace_id: 'local' };
|
|
74
|
+
}
|
|
75
|
+
async register(token, input) {
|
|
76
|
+
const key = keyOf('enrollment', hash(token));
|
|
77
|
+
const enrollment = await this.store.settings.get(key);
|
|
78
|
+
if (!token.startsWith('ar_enroll_') || !enrollment || enrollment.expires <= this.now())
|
|
79
|
+
throw new ApiError('unauthenticated', 'The connection code expired or is invalid. Create another in the console.');
|
|
80
|
+
const b = object(input);
|
|
81
|
+
bounded(b, 4096);
|
|
82
|
+
if (!validId(b.installation_id) || !validId(b.operation_id) || (b.label !== undefined && !text(b.label)) || typeof object(b.capabilities).native_execution !== 'boolean' || (object(b.capabilities).history_import !== undefined && typeof object(b.capabilities).history_import !== 'boolean'))
|
|
83
|
+
throw new ApiError('input_invalid', 'Remote native execution requires an explicit installation, operation and capability selection.');
|
|
84
|
+
const requested = { native_execution: object(b.capabilities).native_execution === true, history_import: object(b.capabilities).history_import === true };
|
|
85
|
+
if (!requested.native_execution && !requested.history_import || requested.native_execution && enrollment.capabilities?.native_execution === false || requested.history_import && enrollment.capabilities?.history_import !== true)
|
|
86
|
+
throw new ApiError('forbidden', 'The source requested capabilities not approved by the owner connection code.');
|
|
87
|
+
const requestHash = hash(JSON.stringify(b));
|
|
88
|
+
let id = enrollment.connector_id;
|
|
89
|
+
if (id && enrollment.request_hash !== requestHash)
|
|
90
|
+
throw new ApiError('idempotency_mismatch', 'This connection code has already been used for another request.');
|
|
91
|
+
if (!id) {
|
|
92
|
+
id = opaque('rc');
|
|
93
|
+
if (!await this.store.settings.replaceIf(key, enrollment, { ...enrollment, connector_id: id, request_hash: requestHash }))
|
|
94
|
+
throw new ApiError('idempotency_in_progress', 'Connection registration is in progress. Retry the same request.');
|
|
95
|
+
}
|
|
96
|
+
// Deterministically recover only this registration's reply after a lost HTTP response; no plaintext credential is stored.
|
|
97
|
+
const credential = `ar_connector_${createHmac('sha256', token).update(id).digest('base64url')}`;
|
|
98
|
+
const expires = this.now() + 30 * 24 * 60 * 60_000;
|
|
99
|
+
const row = await this.store.settings.putIfAbsent(keyOf('connector', id), { id, installation_id: b.installation_id, label: b.label ?? enrollment.label, created_at: new Date(this.now()).toISOString(), last_seen: 0, credential_hash: hash(credential), expires, revoked: false, ...requested });
|
|
100
|
+
if (row.revoked || row.expires <= this.now())
|
|
101
|
+
throw new ApiError('forbidden', 'This connector is revoked. Create a new connection code.');
|
|
102
|
+
return { connector: await this.view(row), credential, credential_expires_at: new Date(row.expires).toISOString() };
|
|
103
|
+
}
|
|
104
|
+
async authenticate(id, token) {
|
|
105
|
+
// Scoped callers learn nothing about absent connectors; operational store failures still propagate.
|
|
106
|
+
const row = await this.store.settings.get(keyOf('connector', id));
|
|
107
|
+
if (!row || !token.startsWith('ar_connector_') || !timingSafeEqual(Buffer.from(hash(token)), Buffer.from(row.credential_hash)) || row.revoked || row.expires <= this.now())
|
|
108
|
+
throw new ApiError('unauthenticated', 'The connector credential is invalid, expired or revoked.');
|
|
109
|
+
}
|
|
110
|
+
async revoke(id) {
|
|
111
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
112
|
+
const row = await this.connector(id);
|
|
113
|
+
if (row.revoked || await this.store.settings.replaceIf(keyOf('connector', id), row, { ...row, revoked: true }))
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
const row = await this.connector(id);
|
|
117
|
+
if (!row.revoked)
|
|
118
|
+
throw new ApiError('home_busy', 'The connector changed while it was being revoked; retry.');
|
|
119
|
+
for (const setting of await this.store.settings.all({ prefix: keyOf('command', ''), connectorId: id })) {
|
|
120
|
+
const command = setting.value;
|
|
121
|
+
if (setting.key.startsWith(keyOf('command', '')) && command.connector_id === id && ['queued', 'leased'].includes(command.state))
|
|
122
|
+
await this.store.settings.replaceIf(setting.key, command, { ...command, state: 'cancelled', error: 'Connector revoked.' });
|
|
123
|
+
}
|
|
124
|
+
return { connector: await this.view(row) };
|
|
125
|
+
}
|
|
126
|
+
async assertReady(binding) {
|
|
127
|
+
if (!binding.connected || !binding.remote)
|
|
128
|
+
throw new ApiError('agent_not_runnable', 'The remote connection is disconnected.');
|
|
129
|
+
const row = await this.connector(binding.remote.connector_id);
|
|
130
|
+
if (!row.native_execution)
|
|
131
|
+
throw new ApiError('agent_not_runnable', 'This source is history only. Create a new connection code to authorize live execution.');
|
|
132
|
+
if (row.revoked || row.expires <= this.now())
|
|
133
|
+
throw new ApiError('agent_not_runnable', 'The remote connector was revoked. Reconnect on the source machine.');
|
|
134
|
+
if (row.last_seen + ONLINE_MS < this.now())
|
|
135
|
+
throw new ApiError('agent_not_runnable', 'The source machine is offline. Start its AgentRun CLI worker.');
|
|
136
|
+
const saved = await this.store.settings.get(keyOf('target', `${row.id}.${binding.remote.target_id}`));
|
|
137
|
+
if (!saved || saved.target.machine_id !== binding.machine_id || saved.target.project !== binding.project || saved.target.runtime !== binding.runtime || JSON.stringify(saved.target.selector) !== JSON.stringify(binding.selector))
|
|
138
|
+
throw new ApiError('agent_not_runnable', 'The source target no longer matches this agent. Reconnect the selected agent.');
|
|
139
|
+
}
|
|
140
|
+
async status(binding) {
|
|
141
|
+
try {
|
|
142
|
+
await this.assertReady(binding);
|
|
143
|
+
return binding;
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
return { ...binding, state: 'needs_attention', capabilities: { ...binding.capabilities, launch: false }, issues: [...binding.issues, error instanceof Error ? error.message : 'The remote source is unavailable.'] };
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async importTarget(id, input) {
|
|
150
|
+
const b = object(input);
|
|
151
|
+
bounded(b, 256_000);
|
|
152
|
+
if (b.history_only !== undefined && typeof b.history_only !== 'boolean')
|
|
153
|
+
throw new ApiError('input_invalid', 'history_only must be a boolean.');
|
|
154
|
+
if (!validId(b.target_id) || (b.name !== undefined && !text(b.name)))
|
|
155
|
+
throw new ApiError('input_invalid', 'Choose a source-approved target and name.');
|
|
156
|
+
const raw = object(b.target);
|
|
157
|
+
if (raw.remote !== undefined)
|
|
158
|
+
throw new ApiError('input_invalid', 'The connector cannot choose another connector binding.');
|
|
159
|
+
let native;
|
|
160
|
+
try {
|
|
161
|
+
native = nativeBindingOf({ ...raw, connected: true });
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
throw new ApiError('input_invalid', 'Invalid native target metadata.');
|
|
165
|
+
}
|
|
166
|
+
if (native.configuration.length > 2048 || native.skills.length > 2048 || native.mcp_servers.length > 256 || native.issues.length > 64 || !['ready', 'needs_attention', 'needs_verification'].includes(native.state) || !native.configuration.every(file => text(file.path, 4096) && /^[a-f0-9]{64}$/.test(file.sha256)) || !native.skills.every(s => text(s, 256)) || !native.mcp_servers.every(s => text(s, 256)) || !native.issues.every(s => text(s, 4096)))
|
|
167
|
+
throw new ApiError('input_invalid', 'Invalid or excessive native metadata.');
|
|
168
|
+
const connector = await this.connector(id);
|
|
169
|
+
if (connector.revoked)
|
|
170
|
+
throw new ApiError('forbidden', 'Connector revoked.');
|
|
171
|
+
const historyOnly = b.history_only === true;
|
|
172
|
+
if (historyOnly ? !connector.history_import || connector.native_execution : !connector.native_execution)
|
|
173
|
+
throw new ApiError('forbidden', 'This connection code does not authorize the requested import mode.');
|
|
174
|
+
if (historyOnly)
|
|
175
|
+
native = { ...native, connected: false, capabilities: { ...native.capabilities, launch: false }, issues: [...native.issues, 'History only: past sessions are imported; this source has not authorized live execution.'] };
|
|
176
|
+
native = { ...native, remote: { connector_id: id, target_id: b.target_id } };
|
|
177
|
+
const agentId = `remote-${hash(`${id}:${b.target_id}`).slice(0, 40)}`;
|
|
178
|
+
const targetKey = keyOf('target', `${id}.${b.target_id}`);
|
|
179
|
+
const prior = await this.store.settings.get(targetKey);
|
|
180
|
+
if (prior && (prior.target.project !== native.project || prior.target.runtime !== native.runtime || prior.target.machine_id !== native.machine_id || JSON.stringify(prior.target.selector) !== JSON.stringify(native.selector)))
|
|
181
|
+
throw new ApiError('idempotency_mismatch', 'A target id cannot be reused for another source agent.');
|
|
182
|
+
const name = b.name ?? `${native.runtime} · ${native.selector.name ?? native.project.split('/').filter(Boolean).at(-1) ?? 'project'}`;
|
|
183
|
+
let entry = await getAgent(this.store, agentId);
|
|
184
|
+
if (entry) {
|
|
185
|
+
// A source credential cannot undo an owner disconnect. Re-enrollment is a new explicit owner grant.
|
|
186
|
+
if (nativeOf(entry.revision?.body)?.connected === false)
|
|
187
|
+
native = { ...native, connected: false };
|
|
188
|
+
entry = await updateNative(this.store, entry, native);
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
try {
|
|
192
|
+
entry = await createAgent(this.store, { definition: { id: agentId, name, instructions: '', harness: native.runtime === 'claude-code' ? 'claude-agent' : 'codex', place: { mode: 'runner' }, tools: [], learning: false, native }, skills: {} });
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
if (!(error instanceof ApiError && error.code === 'agent_exists'))
|
|
196
|
+
throw error;
|
|
197
|
+
entry = await getAgent(this.store, agentId);
|
|
198
|
+
if (!entry)
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const savedTarget = { target_id: b.target_id, agent_id: agentId, name, target: native, history_only: historyOnly, owner_disconnected: prior?.owner_disconnected ?? false };
|
|
203
|
+
if (prior) {
|
|
204
|
+
if (!await this.store.settings.replaceIf(targetKey, prior, savedTarget))
|
|
205
|
+
throw new ApiError('home_busy', 'The owner changed this target while it was being imported. Retry after reviewing its connection.');
|
|
206
|
+
}
|
|
207
|
+
else
|
|
208
|
+
await this.store.settings.putIfAbsent(targetKey, savedTarget);
|
|
209
|
+
return { agent_id: agentId, native };
|
|
210
|
+
}
|
|
211
|
+
async disconnectTarget(binding) {
|
|
212
|
+
if (!binding.remote)
|
|
213
|
+
return;
|
|
214
|
+
const key = keyOf('target', `${binding.remote.connector_id}.${binding.remote.target_id}`);
|
|
215
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
216
|
+
const target = await this.store.settings.get(key);
|
|
217
|
+
if (!target || target.owner_disconnected)
|
|
218
|
+
return;
|
|
219
|
+
if (await this.store.settings.replaceIf(key, target, { ...target, owner_disconnected: true }))
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
throw new ApiError('home_busy', 'The source target changed while disconnecting. Retry the disconnect.');
|
|
223
|
+
}
|
|
224
|
+
async importHistory(id, targetId, input, own = []) {
|
|
225
|
+
const connectorKey = keyOf('connector', id), targetKey = keyOf('target', `${id}.${targetId}`);
|
|
226
|
+
const authorize = async () => {
|
|
227
|
+
const connector = await this.connector(id);
|
|
228
|
+
if (connector.revoked || connector.expires <= this.now() || !connector.history_import)
|
|
229
|
+
throw new ApiError('forbidden', 'This source has no owner-approved history import grant.');
|
|
230
|
+
const target = await this.store.settings.get(targetKey);
|
|
231
|
+
if (!target)
|
|
232
|
+
throw new ApiError('not_found', 'Choose an imported target on this connector.');
|
|
233
|
+
const entry = await getAgent(this.store, target.agent_id), native = nativeOf(entry?.revision?.body);
|
|
234
|
+
if (!entry?.revision || !native?.remote || native.remote.connector_id !== id || native.remote.target_id !== targetId || entry.agent.archivedAt !== null)
|
|
235
|
+
throw new ApiError('forbidden', 'This source no longer owns the selected target.');
|
|
236
|
+
if (target.owner_disconnected || !native.connected && !target.history_only)
|
|
237
|
+
throw new ApiError('forbidden', 'The owner disconnected this agent. Its source cannot import more history.');
|
|
238
|
+
if (native.selector.kind !== 'project')
|
|
239
|
+
throw new ApiError('input_invalid', 'Native logs do not reliably attribute named agents or profiles. Select project history explicitly.');
|
|
240
|
+
return { entry, native, guards: [{ key: connectorKey, fields: { revoked: false, history_import: true, expires: connector.expires } }, { key: targetKey, fields: { agent_id: entry.agent.id, owner_disconnected: target.owner_disconnected, history_only: target.history_only } }] };
|
|
241
|
+
};
|
|
242
|
+
const before = await authorize();
|
|
243
|
+
const sessions = await redactRemoteHistory(remoteHistorySessions(input, before.native.runtime, this.now()), own);
|
|
244
|
+
await authorize(); // A revoke/disconnect may have completed while secret scanning was in progress.
|
|
245
|
+
return importRemoteHistory(this.store, id, targetId, before.entry.agent.id, before.entry.revision.id, sessions, async () => (await authorize()).guards);
|
|
246
|
+
}
|
|
247
|
+
async touch(id) {
|
|
248
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
249
|
+
const row = await this.connector(id);
|
|
250
|
+
if (row.revoked || row.expires <= this.now())
|
|
251
|
+
throw new ApiError('unauthenticated', 'Connector revoked or expired.');
|
|
252
|
+
if (await this.store.settings.replaceIf(keyOf('connector', id), row, { ...row, last_seen: this.now() }))
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
throw new ApiError('home_busy', 'Connector heartbeat is busy.');
|
|
256
|
+
}
|
|
257
|
+
async poll(id, input) {
|
|
258
|
+
const b = object(input);
|
|
259
|
+
bounded(b, 32_000);
|
|
260
|
+
if (!validId(b.worker_id) || (b.active !== undefined && (!Array.isArray(b.active) || b.active.length > 32)))
|
|
261
|
+
throw new ApiError('input_invalid', 'A worker identity and bounded active leases are required.');
|
|
262
|
+
if (!(await this.connector(id)).native_execution)
|
|
263
|
+
throw new ApiError('forbidden', 'A history-only source cannot claim execution commands.');
|
|
264
|
+
await this.touch(id);
|
|
265
|
+
const cancelled = [];
|
|
266
|
+
for (const active of b.active ?? []) {
|
|
267
|
+
const key = keyOf('command', String(active.command_id));
|
|
268
|
+
let renewed = false;
|
|
269
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
270
|
+
const c = await this.store.settings.get(key);
|
|
271
|
+
if (!c || c.connector_id !== id || c.worker_id !== b.worker_id || c.lease_token !== active.lease_token)
|
|
272
|
+
break;
|
|
273
|
+
// The result may be committed while its HTTP acknowledgement was lost. Keep the source's identical
|
|
274
|
+
// completion retry valid; calling it cancelled would overwrite its durable result with a different error.
|
|
275
|
+
if (c.state === 'complete') {
|
|
276
|
+
renewed = true;
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
if (c.state !== 'leased' || (c.lease_expires_at ?? 0) < this.now() || c.deadline_at < this.now())
|
|
280
|
+
break;
|
|
281
|
+
if (await this.store.settings.replaceIf(key, c, { ...c, lease_expires_at: Math.min(this.now() + LEASE_MS, c.deadline_at) })) {
|
|
282
|
+
renewed = true;
|
|
283
|
+
break;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (!renewed)
|
|
287
|
+
cancelled.push(String(active.command_id));
|
|
288
|
+
}
|
|
289
|
+
const commands = [];
|
|
290
|
+
for (const setting of await this.store.settings.all({ prefix: keyOf('command', ''), connectorId: id })) {
|
|
291
|
+
if (!setting.key.startsWith(keyOf('command', '')))
|
|
292
|
+
continue;
|
|
293
|
+
const c = setting.value;
|
|
294
|
+
if (c.connector_id !== id)
|
|
295
|
+
continue;
|
|
296
|
+
if (['complete', 'cancelled', 'unknown'].includes(c.state) && c.created_at + 24 * 60 * 60_000 < this.now()) {
|
|
297
|
+
await this.store.settings.removeIf(setting.key, c);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (c.state === 'leased' && ((c.lease_expires_at ?? 0) < this.now() || c.deadline_at < this.now())) {
|
|
301
|
+
await this.store.settings.replaceIf(setting.key, c, { ...c, state: 'unknown', error: 'The remote command lease expired; its outcome is unknown. It was not dispatched again.' });
|
|
302
|
+
cancelled.push(c.command_id);
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (c.state !== 'queued' || commands.length)
|
|
306
|
+
continue;
|
|
307
|
+
if (c.deadline_at < this.now()) {
|
|
308
|
+
await this.store.settings.replaceIf(setting.key, c, { ...c, state: 'cancelled', error: 'Command expired before dispatch.' });
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
const claimed = { ...c, state: 'leased', worker_id: b.worker_id, lease_token: opaque('lease'), lease_expires_at: Math.min(this.now() + LEASE_MS, c.deadline_at) };
|
|
312
|
+
if (await this.store.settings.replaceIf(setting.key, c, claimed))
|
|
313
|
+
commands.push(claimed);
|
|
314
|
+
}
|
|
315
|
+
return { commands: commands.map(({ connector_id: _c, batches: _b, state: _s, created_at: _a, worker_id: _w, ...c }) => c), cancelled, server_time: this.now(), lease_ttl_ms: LEASE_MS };
|
|
316
|
+
}
|
|
317
|
+
async leased(id, commandId, lease, allowComplete = false) {
|
|
318
|
+
const c = await this.store.settings.get(keyOf('command', commandId));
|
|
319
|
+
if (!c || c.connector_id !== id)
|
|
320
|
+
throw new ApiError('not_found', 'This command does not belong to the connector.');
|
|
321
|
+
if (c.lease_token !== lease || (!allowComplete || c.state !== 'complete') && (c.state !== 'leased' || (c.lease_expires_at ?? 0) < this.now() || c.deadline_at < this.now()))
|
|
322
|
+
throw new ApiError('precondition_failed', 'This remote command lease is no longer valid. Stop the source operation.');
|
|
323
|
+
return c;
|
|
324
|
+
}
|
|
325
|
+
async events(id, commandId, input) {
|
|
326
|
+
const b = object(input);
|
|
327
|
+
bounded(b, 256_000);
|
|
328
|
+
if (!Number.isSafeInteger(b.sequence) || b.sequence < 0 || !Array.isArray(b.events) || b.events.length > 256)
|
|
329
|
+
throw new ApiError('input_invalid', 'Events require a monotonic batch sequence.');
|
|
330
|
+
for (const event of b.events)
|
|
331
|
+
if (!validEvent(event))
|
|
332
|
+
throw new ApiError('input_invalid', 'Invalid native event.');
|
|
333
|
+
const digest = hash(JSON.stringify(b.events));
|
|
334
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
335
|
+
const c = await this.leased(id, commandId, b.lease_token);
|
|
336
|
+
const prior = c.batches.find(batch => batch.sequence === b.sequence);
|
|
337
|
+
if (prior) {
|
|
338
|
+
if (prior.hash !== digest)
|
|
339
|
+
throw new ApiError('idempotency_mismatch', 'The event batch changed.');
|
|
340
|
+
return { accepted: true };
|
|
341
|
+
}
|
|
342
|
+
if (b.sequence !== c.batches.length)
|
|
343
|
+
throw new ApiError('precondition_failed', 'An earlier event batch is missing.');
|
|
344
|
+
const next = { ...c, batches: [...c.batches, { sequence: b.sequence, events: b.events, hash: digest }] };
|
|
345
|
+
bounded(next, 8_000_000);
|
|
346
|
+
if (await this.store.settings.replaceIf(keyOf('command', commandId), c, next))
|
|
347
|
+
return { accepted: true };
|
|
348
|
+
}
|
|
349
|
+
throw new ApiError('home_busy', 'Event recording is busy.');
|
|
350
|
+
}
|
|
351
|
+
async complete(id, commandId, input) {
|
|
352
|
+
const b = object(input);
|
|
353
|
+
bounded(b, REMOTE_COMPLETION_BODY_BYTES);
|
|
354
|
+
if ((b.error !== undefined && !text(b.error, 4096)) || (b.error === undefined && b.result === undefined))
|
|
355
|
+
throw new ApiError('input_invalid', 'A remote result or bounded error is required.');
|
|
356
|
+
const digest = hash(JSON.stringify({ result: b.result ?? null, error: b.error ?? null }));
|
|
357
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
358
|
+
const c = await this.leased(id, commandId, b.lease_token, true);
|
|
359
|
+
if (c.state === 'complete') {
|
|
360
|
+
if (c.completion_hash !== digest)
|
|
361
|
+
throw new ApiError('idempotency_mismatch', 'The completed command result changed.');
|
|
362
|
+
return { accepted: true };
|
|
363
|
+
}
|
|
364
|
+
const next = { ...c, state: 'complete', completion_hash: digest, ...(b.error ? { error: b.error } : { result: b.result }) };
|
|
365
|
+
if (await this.store.settings.replaceIf(keyOf('command', commandId), c, next))
|
|
366
|
+
return { accepted: true };
|
|
367
|
+
}
|
|
368
|
+
throw new ApiError('home_busy', 'Result recording is busy.');
|
|
369
|
+
}
|
|
370
|
+
async request(binding, type, payload, options = {}) {
|
|
371
|
+
await this.assertReady(binding);
|
|
372
|
+
options.signal?.throwIfAborted();
|
|
373
|
+
bounded(payload);
|
|
374
|
+
const id = opaque('cmd'), now = this.now();
|
|
375
|
+
const command = { command_id: id, connector_id: binding.remote.connector_id, target_id: binding.remote.target_id, type, payload, ...(options.sessionKey ? { session_key: options.sessionKey } : {}), created_at: now, deadline_at: now + Math.min(Math.max(options.timeoutMs ?? 180_000, 1), 600_000), state: 'queued', batches: [] };
|
|
376
|
+
const waiting = (await this.store.settings.all({ prefix: keyOf('command', ''), connectorId: command.connector_id })).filter(row => ['queued', 'leased'].includes(row.value.state));
|
|
377
|
+
if (waiting.length >= 32)
|
|
378
|
+
throw new ApiError('home_busy', 'The source connector already has its maximum active requests.');
|
|
379
|
+
const key = keyOf('command', id);
|
|
380
|
+
await this.store.settings.put(key, command);
|
|
381
|
+
let seen = 0;
|
|
382
|
+
try {
|
|
383
|
+
while (true) {
|
|
384
|
+
options.signal?.throwIfAborted();
|
|
385
|
+
const c = await this.store.settings.get(key);
|
|
386
|
+
for (; seen < c.batches.length; seen++)
|
|
387
|
+
for (const event of c.batches[seen].events)
|
|
388
|
+
await options.onEvent?.(event);
|
|
389
|
+
if (c.state === 'complete') {
|
|
390
|
+
if (c.error)
|
|
391
|
+
throw new Error(c.error);
|
|
392
|
+
return c.result;
|
|
393
|
+
}
|
|
394
|
+
if (['unknown', 'cancelled'].includes(c.state))
|
|
395
|
+
throw new Error(c.error ?? 'The remote command ended without a result.');
|
|
396
|
+
const connector = await this.connector(c.connector_id);
|
|
397
|
+
if (connector.revoked || connector.expires <= this.now())
|
|
398
|
+
throw new Error('The source connector was revoked.');
|
|
399
|
+
if (c.deadline_at <= this.now() || c.state === 'leased' && (c.lease_expires_at ?? 0) <= this.now())
|
|
400
|
+
throw new Error('The remote command expired; its outcome may be unknown. Inspect the source before retrying.');
|
|
401
|
+
await delay(100, undefined, { signal: options.signal });
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
finally {
|
|
405
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
406
|
+
const current = await this.store.settings.get(key);
|
|
407
|
+
if (current?.state === 'complete') {
|
|
408
|
+
const { result: _r, ...receipt } = current;
|
|
409
|
+
await this.store.settings.replaceIf(key, current, { ...receipt, payload: {}, batches: [] });
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
if (!current || !['queued', 'leased'].includes(current.state))
|
|
413
|
+
break;
|
|
414
|
+
if (await this.store.settings.replaceIf(key, current, { ...current, state: 'cancelled', error: 'The requesting run stopped; cancel the source operation.' }))
|
|
415
|
+
break;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
export function checkedPrepared(before, result) {
|
|
421
|
+
const value = object(result);
|
|
422
|
+
let target;
|
|
423
|
+
try {
|
|
424
|
+
target = nativeBindingOf({ ...value.target, remote: before.remote, connected: true });
|
|
425
|
+
}
|
|
426
|
+
catch {
|
|
427
|
+
throw new Error('The source returned invalid native metadata.');
|
|
428
|
+
}
|
|
429
|
+
if (target.runtime !== before.runtime || target.machine_id !== before.machine_id || target.project !== before.project || JSON.stringify(target.selector) !== JSON.stringify(before.selector))
|
|
430
|
+
throw new Error('The source returned a different agent.');
|
|
431
|
+
let instructions = value.instructions;
|
|
432
|
+
if (!instructions || typeof instructions.text !== 'string' || Buffer.byteLength(instructions.text) > 70_000 || typeof instructions.truncated !== 'boolean' || !Array.isArray(instructions.files))
|
|
433
|
+
throw new Error('The source returned invalid instruction evidence.');
|
|
434
|
+
// Older bridges may return task-ready metadata without the current policy coverage checks. Keep their evidence and
|
|
435
|
+
// ordinary launch capability, but never advertise it as complete enough for automatic learning.
|
|
436
|
+
const protocol = NATIVE_RUNTIME_FACTS[target.runtime].protocol;
|
|
437
|
+
const unchecked = protocol === 'codex-json' && instructions.codexConfigurationChecked !== true
|
|
438
|
+
? 'This source bridge did not check Codex custom policy configuration.'
|
|
439
|
+
: protocol === 'claude-json' && instructions.claudeConfigurationChecked !== true
|
|
440
|
+
? 'This source bridge did not check Claude settings precedence.'
|
|
441
|
+
: protocol === 'claude-json' && instructions.claudePolicySourcesChecked !== true
|
|
442
|
+
? 'This source bridge did not check imported or additional Claude policy files.'
|
|
443
|
+
: undefined;
|
|
444
|
+
if (unchecked && !instructions.incomplete)
|
|
445
|
+
instructions = { ...instructions, incomplete: unchecked };
|
|
446
|
+
if (instructions.incomplete || instructions.truncated)
|
|
447
|
+
target = { ...target, capabilities: { ...target.capabilities, notes: false, skills: false }, issues: [...target.issues, `Self-improvement is unavailable: ${instructions.incomplete ?? 'the source instruction snapshot exceeds the grading evidence limit.'} Native jobs remain available; no incomplete policy is automatically graded.`] };
|
|
448
|
+
return { target, instructions };
|
|
449
|
+
}
|
|
450
|
+
function validUsage(value) {
|
|
451
|
+
const usage = object(value);
|
|
452
|
+
return ['input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_write_tokens'].every(key => usage[key] === null || Number.isSafeInteger(usage[key]) && usage[key] >= 0) && (usage.cost_usd === null || typeof usage.cost_usd === 'number' && Number.isFinite(usage.cost_usd) && usage.cost_usd >= 0);
|
|
453
|
+
}
|
|
454
|
+
function validEvent(value) {
|
|
455
|
+
const e = object(value);
|
|
456
|
+
if (e.type === 'session')
|
|
457
|
+
return text(e.sessionId, 4096);
|
|
458
|
+
if (e.type === 'text')
|
|
459
|
+
return typeof e.text === 'string' && Buffer.byteLength(e.text) <= 256_000;
|
|
460
|
+
if (e.type === 'usage')
|
|
461
|
+
return validUsage(e.usage);
|
|
462
|
+
if (e.type === 'tool')
|
|
463
|
+
return text(e.id, 4096) && text(e.name, 4096) && ['started', 'completed', 'failed'].includes(e.status);
|
|
464
|
+
if (e.type === 'approval')
|
|
465
|
+
return text(e.id, 4096) && text(e.tool, 4096);
|
|
466
|
+
return false;
|
|
467
|
+
}
|
|
468
|
+
export function remoteResult(value) {
|
|
469
|
+
const r = object(value);
|
|
470
|
+
if (!text(r.sessionId, 4096) || typeof r.answer !== 'string' || !validUsage(r.usage) || (r.model !== undefined && !text(r.model, 4096)) || (r.permission_denials !== undefined && (!Array.isArray(r.permission_denials) || !r.permission_denials.every((v) => text(v, 4096)))))
|
|
471
|
+
throw new Error('The remote native runtime returned an invalid result.');
|
|
472
|
+
return r;
|
|
473
|
+
}
|
|
474
|
+
export async function verifyRemote(store, entry) {
|
|
475
|
+
const binding = nativeOf(entry.revision?.body);
|
|
476
|
+
if (!binding?.remote)
|
|
477
|
+
throw new ApiError('not_found', 'No remote connection.');
|
|
478
|
+
const prepared = checkedPrepared(binding, await new RemoteConnectors(store).request(binding, 'prepare', {}, { timeoutMs: 30_000 }));
|
|
479
|
+
return updateNative(store, entry, { ...prepared.target, connected: binding.connected });
|
|
480
|
+
}
|
|
481
|
+
/** A session transport only. Task/reflection/grading policy remains in the native loop and source runtime. */
|
|
482
|
+
export async function openRemoteSession(broker, target, options) {
|
|
483
|
+
const sessionKey = opaque('session');
|
|
484
|
+
await broker.request(target, 'open', { context: options.context ?? '', skills: options.skills ?? [], run_id: options.runId, expected_fingerprint: target.fingerprint }, { signal: options.signal, sessionKey, timeoutMs: 30_000 });
|
|
485
|
+
return {
|
|
486
|
+
send: async (prompt, sendOptions = {}) => remoteResult(await broker.request(target, 'send', { prompt, reflection: sendOptions.reflection ?? false, timeout_ms: sendOptions.timeoutMs ?? 180_000 }, { signal: sendOptions.signal ?? options.signal, sessionKey, timeoutMs: (sendOptions.timeoutMs ?? 180_000) + 5000, onEvent: options.onEvent })),
|
|
487
|
+
close: async () => { try {
|
|
488
|
+
await broker.request(target, 'close', {}, { sessionKey, timeoutMs: 5000 });
|
|
489
|
+
}
|
|
490
|
+
catch { /* lease loss already requires the worker to close its session */ } },
|
|
491
|
+
};
|
|
492
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { NativeBinding, NativeEvent, NativeSession, NativeTarget } from "./types.js";
|
|
2
|
+
/** A stop kills the source immediately, then gives its already reported events this long to finish recording. */
|
|
3
|
+
export declare const NATIVE_EVENT_DRAIN_MS = 5000;
|
|
4
|
+
export declare class NativeRuntimeError extends Error {
|
|
5
|
+
readonly code: "unavailable" | "protocol" | "failed" | "timeout" | "aborted" | "approval_required";
|
|
6
|
+
readonly sessionId?: string | undefined;
|
|
7
|
+
constructor(message: string, code: "unavailable" | "protocol" | "failed" | "timeout" | "aborted" | "approval_required", sessionId?: string | undefined);
|
|
8
|
+
}
|
|
9
|
+
/** CLI JSON mode preserves normal native resolution. An unavailable approval is denied, never upgraded. */
|
|
10
|
+
export declare function openNativeSession(options: {
|
|
11
|
+
target: NativeTarget | NativeBinding;
|
|
12
|
+
env?: NodeJS.ProcessEnv;
|
|
13
|
+
sessionId?: string;
|
|
14
|
+
context?: string;
|
|
15
|
+
onEvent?: (event: NativeEvent) => Promise<void> | void;
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
}): Promise<NativeSession>;
|