@parcha/agentrun-serve 0.1.0-beta.52 → 0.1.0-beta.53
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 +122 -1
- package/README.md +213 -24
- package/dist/agent-delete.d.ts +5 -6
- package/dist/agent-delete.js +30 -67
- package/dist/agent-package.d.ts +71 -0
- package/dist/agent-package.js +345 -0
- package/dist/agents-store.d.ts +26 -20
- package/dist/agents-store.js +41 -33
- package/dist/api-only.d.ts +26 -6
- package/dist/api-only.js +35 -13
- package/dist/claude-login.d.ts +1 -0
- package/dist/claude-login.js +1 -1
- package/dist/cli-learning/cli.d.ts +3 -0
- package/dist/cli-learning/cli.js +17 -3
- package/dist/cli-learning/connections.js +3 -2
- package/dist/cli-learning/schema.js +2 -1
- package/dist/cli.js +70 -7
- package/dist/composio-preset.d.ts +2 -1
- package/dist/composio-preset.js +4 -3
- package/dist/composio-triggers.d.ts +4 -0
- package/dist/composio-triggers.js +4 -1
- package/dist/computer-needs.d.ts +32 -0
- package/dist/computer-needs.js +80 -0
- package/dist/computer-setting.d.ts +1 -0
- package/dist/computer-setting.js +8 -1
- package/dist/console/assets/index-BFgyZzF_.js +734 -0
- package/dist/console/assets/index-DbilxljH.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +1 -0
- package/dist/console-links.js +2 -0
- package/dist/env-switch.d.ts +14 -0
- package/dist/env-switch.js +23 -0
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +3 -0
- package/dist/eval-previous.js +4 -3
- package/dist/fal-price.js +10 -13
- package/dist/handed-secret.d.ts +4 -0
- package/dist/handed-secret.js +10 -0
- package/dist/harness-archive.d.ts +15 -5
- package/dist/harness-archive.js +71 -34
- package/dist/harness-check.d.ts +2 -1
- package/dist/harness-check.js +36 -95
- package/dist/harness-egress.d.ts +23 -0
- package/dist/harness-egress.js +69 -0
- package/dist/harness-recipe-entry.d.ts +71 -0
- package/dist/harness-recipe-entry.js +184 -0
- package/dist/harness-recipe.d.ts +73 -6
- package/dist/harness-recipe.js +185 -31
- package/dist/harness-sign-in.d.ts +29 -0
- package/dist/harness-sign-in.js +122 -0
- package/dist/harness-table.d.ts +21 -0
- package/dist/harness-table.js +58 -3
- package/dist/harness-zip.d.ts +6 -0
- package/dist/harness-zip.js +203 -0
- package/dist/ids.d.ts +11 -0
- package/dist/ids.js +36 -0
- package/dist/learn/commit.d.ts +14 -1
- package/dist/learn/commit.js +156 -1
- package/dist/learn/compile.js +22 -8
- package/dist/learn/folder.d.ts +5 -0
- package/dist/learn/folder.js +10 -1
- package/dist/learn/learning.sh +15 -3
- package/dist/learn/promote.d.ts +2 -2
- package/dist/learn/secrets.js +30 -7
- package/dist/learning-routes.d.ts +23 -11
- package/dist/learning-routes.js +110 -20
- package/dist/learning.d.ts +9 -6
- package/dist/learning.js +9 -4
- package/dist/mcp-gateway.js +15 -2
- package/dist/mcp-probe.d.ts +3 -0
- package/dist/mcp-probe.js +7 -2
- package/dist/mcp-resources.d.ts +44 -0
- package/dist/mcp-resources.js +100 -0
- package/dist/mcp-servers-store.d.ts +16 -12
- package/dist/model.d.ts +4 -4
- package/dist/model.js +6 -6
- package/dist/native/cli.js +9 -2
- package/dist/native/connection.d.ts +2 -2
- package/dist/native/connection.js +5 -2
- package/dist/native/discovery.d.ts +2 -0
- package/dist/native/discovery.js +10 -6
- package/dist/native/remote-worker-bridge.js +36 -4
- package/dist/native/remote.d.ts +18 -1
- package/dist/native/remote.js +126 -37
- package/dist/native/schema.d.ts +6 -0
- package/dist/native/schema.js +31 -6
- package/dist/native/source-account.d.ts +13 -0
- package/dist/native/source-account.js +114 -0
- package/dist/native/source-capture-hooks.d.ts +5 -0
- package/dist/native/source-capture-hooks.js +102 -0
- package/dist/native/source-mcp-selection.d.ts +13 -0
- package/dist/native/source-mcp-selection.js +72 -0
- package/dist/native/source-runtime-tools.d.ts +19 -0
- package/dist/native/source-runtime-tools.js +103 -0
- package/dist/native/source-snapshot-types.d.ts +138 -0
- package/dist/native/source-snapshot-types.js +12 -0
- package/dist/native/source-snapshot.d.ts +8 -0
- package/dist/native/source-snapshot.js +1201 -0
- package/dist/observation/learning.js +3 -2
- package/dist/openapi.js +167 -36
- package/dist/print.js +1 -1
- package/dist/purged-workflow.d.ts +12 -0
- package/dist/purged-workflow.js +43 -0
- package/dist/run-keys.d.ts +46 -0
- package/dist/run-keys.js +109 -0
- package/dist/run-launch.d.ts +16 -1
- package/dist/run-launch.js +30 -1
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-model-key.d.ts +2 -2
- package/dist/run-model-key.js +5 -5
- package/dist/run-secrets.d.ts +2 -0
- package/dist/run-secrets.js +7 -4
- package/dist/run-view.d.ts +17 -0
- package/dist/run-view.js +25 -1
- package/dist/runner/adapter-loop.d.ts +11 -3
- package/dist/runner/adapter-loop.js +138 -22
- package/dist/runner/adapter-run-spec.js +25 -12
- package/dist/runner/audit.d.ts +2 -0
- package/dist/runner/audit.js +9 -1
- package/dist/runner/beside.js +2 -1
- package/dist/runner/claim-secrets.d.ts +29 -3
- package/dist/runner/claim-secrets.js +38 -4
- package/dist/runner/cli-run-spec.js +23 -12
- package/dist/runner/harness-loops.d.ts +6 -0
- package/dist/runner/harness-loops.js +11 -1
- package/dist/runner/held.d.ts +4 -0
- package/dist/runner/journal-kinds.d.ts +2 -0
- package/dist/runner/learned-first.d.ts +2 -0
- package/dist/runner/learned-first.js +1 -1
- package/dist/runner/learning-end.d.ts +7 -2
- package/dist/runner/learning-end.js +22 -10
- package/dist/runner/learning-seed.d.ts +9 -3
- package/dist/runner/learning-seed.js +2 -2
- package/dist/runner/main.d.ts +1 -0
- package/dist/runner/main.js +20 -13
- package/dist/runner/mcp-claim.js +6 -1
- package/dist/runner/mcp-run.d.ts +10 -7
- package/dist/runner/mcp-run.js +3 -5
- package/dist/runner/monid-run.js +9 -11
- package/dist/runner/project-checkpoint.d.ts +35 -0
- package/dist/runner/project-checkpoint.js +116 -0
- package/dist/runner/project-drain.d.ts +8 -0
- package/dist/runner/project-drain.js +25 -0
- package/dist/runner/project-host.d.ts +10 -0
- package/dist/runner/project-host.js +52 -0
- package/dist/runner/promotion.d.ts +14 -6
- package/dist/runner/promotion.js +98 -41
- package/dist/runner/redact.d.ts +13 -0
- package/dist/runner/redact.js +67 -1
- package/dist/runner/run-channel.d.ts +9 -0
- package/dist/runner/run-channel.js +15 -2
- package/dist/runner/run-child-host.d.ts +8 -4
- package/dist/runner/run-child-host.js +171 -41
- package/dist/runner/run-errors.js +2 -2
- package/dist/runner/runner-check.js +5 -2
- package/dist/runner/runner.js +26 -9
- package/dist/runner/store-secrets.js +7 -3
- package/dist/runner/workflow-first.d.ts +4 -0
- package/dist/runner/workflow-first.js +13 -0
- package/dist/runner/workflow-loop.d.ts +2 -1
- package/dist/runner/workflow-loop.js +2 -1
- package/dist/runner/workflow-spec.js +1 -1
- package/dist/runs-over-store.d.ts +34 -6
- package/dist/runs-over-store.js +133 -25
- package/dist/sdk/runs.d.ts +11 -1
- package/dist/sdk/runs.js +117 -26
- package/dist/sdk/schema.js +12 -2
- package/dist/sdk/workflows.d.ts +1 -1
- package/dist/server.d.ts +68 -32
- package/dist/server.js +600 -110
- package/dist/skills/agentrun-serve/SKILL.md +2 -1
- package/dist/source-sync/adoption.d.ts +15 -0
- package/dist/source-sync/adoption.js +36 -0
- package/dist/source-sync/auxiliary.d.ts +23 -0
- package/dist/source-sync/auxiliary.js +64 -0
- package/dist/source-sync/capture-git.d.ts +5 -0
- package/dist/source-sync/capture-git.js +272 -0
- package/dist/source-sync/capture-project.d.ts +53 -0
- package/dist/source-sync/capture-project.js +206 -0
- package/dist/source-sync/capture-refusal.d.ts +7 -0
- package/dist/source-sync/capture-refusal.js +16 -0
- package/dist/source-sync/capture.d.ts +11 -0
- package/dist/source-sync/capture.js +22 -0
- package/dist/source-sync/checkpoint-gate.d.ts +21 -0
- package/dist/source-sync/checkpoint-gate.js +52 -0
- package/dist/source-sync/checkpoints.d.ts +66 -0
- package/dist/source-sync/checkpoints.js +168 -0
- package/dist/source-sync/claim.d.ts +11 -0
- package/dist/source-sync/claim.js +48 -0
- package/dist/source-sync/destination.d.ts +47 -0
- package/dist/source-sync/destination.js +239 -0
- package/dist/source-sync/io.d.ts +15 -0
- package/dist/source-sync/io.js +52 -0
- package/dist/source-sync/local.d.ts +43 -0
- package/dist/source-sync/local.js +229 -0
- package/dist/source-sync/prepare.d.ts +59 -0
- package/dist/source-sync/prepare.js +93 -0
- package/dist/source-sync/projects.d.ts +61 -0
- package/dist/source-sync/projects.js +130 -0
- package/dist/source-sync/registry.d.ts +95 -0
- package/dist/source-sync/registry.js +226 -0
- package/dist/source-sync/service.d.ts +33 -0
- package/dist/source-sync/service.js +118 -0
- package/dist/source-sync/skill-edits.d.ts +12 -0
- package/dist/source-sync/skill-edits.js +122 -0
- package/dist/source-sync/snapshots.d.ts +48 -0
- package/dist/source-sync/snapshots.js +448 -0
- package/dist/source-sync/types.d.ts +9 -0
- package/dist/source-sync/types.js +14 -0
- package/dist/source-sync/workspace.d.ts +66 -0
- package/dist/source-sync/workspace.js +273 -0
- package/dist/store/agent-body.d.ts +4 -0
- package/dist/store/agent-body.js +16 -5
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/schema.d.ts +2 -1
- package/dist/store/schema.js +2 -1
- package/dist/store/seal.d.ts +5 -1
- package/dist/store/seal.js +12 -3
- package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
- package/dist/store/sqlite/project-checkpoints.js +70 -0
- package/dist/store/sqlite/run-launch.d.ts +4 -12
- package/dist/store/sqlite/run-launch.js +5 -19
- package/dist/store/sqlite/store.js +224 -170
- package/dist/store/store.d.ts +116 -39
- package/dist/store/store.js +14 -1
- package/dist/store-reads/learning.d.ts +2 -2
- package/dist/store-view.d.ts +3 -1
- package/dist/store-view.js +17 -5
- package/dist/template-import.d.ts +10 -2
- package/dist/template-import.js +116 -13
- package/dist/templates.d.ts +26 -5
- package/dist/templates.js +62 -10
- package/dist/timeline/index.d.ts +1 -1
- package/dist/timeline/index.js +1 -1
- package/dist/timeline/timeline.d.ts +5 -0
- package/dist/timeline/timeline.js +8 -0
- package/dist/tool-plane.d.ts +12 -12
- package/dist/tools.d.ts +8 -8
- package/dist/trigger-launch-hook.d.ts +47 -0
- package/dist/trigger-launch-hook.js +90 -0
- package/dist/trigger-targets.d.ts +14 -1
- package/dist/trigger-targets.js +20 -0
- package/dist/triggers.d.ts +54 -5
- package/dist/triggers.js +143 -8
- package/dist/uploads-archil.js +1 -1
- package/dist/uploads.js +1 -1
- package/dist/validate.js +1 -2
- package/dist/workspace/computer-for-claim.d.ts +2 -0
- package/dist/workspace/computer-for-claim.js +43 -0
- package/dist/workspace/paths.d.ts +6 -0
- package/dist/workspace/paths.js +6 -0
- package/dist/workspace/resolve-computer.d.ts +1 -0
- package/dist/workspace/run-tools.d.ts +2 -0
- package/dist/workspace/run-tools.js +8 -0
- package/launcher/agentrun-serve +1 -1
- package/package.json +10 -10
- package/skills/agentrun-serve/SKILL.md +2 -1
- package/templates/README.md +5 -2
- package/dist/console/assets/index-B-D0EM3j.js +0 -733
- package/dist/console/assets/index-DlQepP2J.css +0 -1
package/dist/native/remote.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { sourceKey } from "../source-sync/registry.js";
|
|
2
|
+
import { sourceSyncOf } from "../source-sync/types.js";
|
|
3
|
+
import { cliCaptureOf } from "../source-sync/capture.js";
|
|
4
4
|
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
5
5
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
6
|
import { ApiError } from '../errors.js';
|
|
@@ -26,12 +26,16 @@ const bounded = (v, max = MAX_COMMAND_BYTES) => { if (Buffer.byteLength(JSON.str
|
|
|
26
26
|
export class RemoteConnectors {
|
|
27
27
|
store;
|
|
28
28
|
now;
|
|
29
|
+
/** One HTTP request's authenticated epoch. Reading its body can await a concurrent owner rotation. */
|
|
30
|
+
authenticated;
|
|
29
31
|
constructor(store, now = Date.now) {
|
|
30
32
|
this.store = store;
|
|
31
33
|
this.now = now;
|
|
32
34
|
}
|
|
33
35
|
async connector(id) {
|
|
34
36
|
const row = await this.store.settings.get(keyOf('connector', id));
|
|
37
|
+
if (this.authenticated && (!row || this.authenticated.id !== id || this.authenticated.credentialHash !== row.credential_hash || row.revoked || row.expires <= this.now()))
|
|
38
|
+
throw new ApiError('unauthenticated', 'This request belongs to an expired or replaced connector credential.');
|
|
35
39
|
if (!row)
|
|
36
40
|
throw new ApiError('not_found', 'This connector does not exist.');
|
|
37
41
|
return row;
|
|
@@ -43,11 +47,11 @@ export class RemoteConnectors {
|
|
|
43
47
|
const targets = await this.targets(row.id);
|
|
44
48
|
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
49
|
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 },
|
|
50
|
+
capabilities: { observe: true, native_execution: row.native_execution, history_import: row.history_import === true, config_sync: row.config_sync === true },
|
|
47
51
|
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 };
|
|
52
|
+
const disconnected = t.owner_disconnected || t.target.connected === false && !t.sync_only;
|
|
53
|
+
const issue = t.owner_disconnected ? 'Disconnected by the owner. Reconnect this target before starting a run.' : t.target.connected === false && !t.history_only && !t.sync_only ? 'This source target is disconnected. Reconnect it before starting a run.' : null;
|
|
54
|
+
return { target_id: t.target_id, agent_id: t.agent_id, name: t.name, history_only: t.history_only === true, sync_only: t.sync_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
55
|
}) };
|
|
52
56
|
}
|
|
53
57
|
async list() {
|
|
@@ -62,14 +66,17 @@ export class RemoteConnectors {
|
|
|
62
66
|
if (b.label !== undefined && !text(b.label))
|
|
63
67
|
throw new ApiError('input_invalid', 'Choose a short name for this source machine.');
|
|
64
68
|
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')))
|
|
69
|
+
if (b.capabilities !== undefined && (Object.keys(requested).some(key => !['native_execution', 'history_import', 'config_sync'].includes(key)) || Object.values(requested).some(value => typeof value !== 'boolean')))
|
|
66
70
|
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)
|
|
71
|
+
const capabilities = { native_execution: requested.native_execution ?? true, history_import: requested.history_import ?? false, config_sync: requested.config_sync ?? true };
|
|
72
|
+
if (!capabilities.native_execution && !capabilities.history_import && !capabilities.config_sync)
|
|
69
73
|
throw new ApiError('input_invalid', 'Choose live execution, history import, or both.');
|
|
74
|
+
const replacing = b.connector_id === undefined ? undefined : validId(b.connector_id) ? await this.connector(b.connector_id) : undefined;
|
|
75
|
+
if (b.connector_id !== undefined && !replacing)
|
|
76
|
+
throw new ApiError('input_invalid', 'Choose the existing connector to authorize.');
|
|
70
77
|
const token = `ar_enroll_${randomBytes(32).toString('base64url')}`;
|
|
71
78
|
const expires = this.now() + 10 * 60_000;
|
|
72
|
-
await this.store.settings.put(keyOf('enrollment', hash(token)), { expires, label: b.label ?? 'Remote machine', capabilities });
|
|
79
|
+
await this.store.settings.put(keyOf('enrollment', hash(token)), { expires, label: b.label ?? 'Remote machine', capabilities, ...(replacing ? { replace_id: replacing.id, replace_credential_hash: replacing.credential_hash, replace_revoked: replacing.revoked } : {}) });
|
|
73
80
|
return { enrollment_token: token, expires_at: new Date(expires).toISOString(), workspace_id: 'local' };
|
|
74
81
|
}
|
|
75
82
|
async register(token, input) {
|
|
@@ -79,24 +86,42 @@ export class RemoteConnectors {
|
|
|
79
86
|
throw new ApiError('unauthenticated', 'The connection code expired or is invalid. Create another in the console.');
|
|
80
87
|
const b = object(input);
|
|
81
88
|
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'))
|
|
89
|
+
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') || (object(b.capabilities).config_sync !== undefined && typeof object(b.capabilities).config_sync !== 'boolean'))
|
|
83
90
|
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)
|
|
91
|
+
const requested = { native_execution: object(b.capabilities).native_execution === true, history_import: object(b.capabilities).history_import === true, config_sync: object(b.capabilities).config_sync === true };
|
|
92
|
+
if (!requested.native_execution && !requested.history_import && !requested.config_sync || requested.native_execution && enrollment.capabilities?.native_execution === false || requested.history_import && enrollment.capabilities?.history_import !== true || requested.config_sync && enrollment.capabilities?.config_sync !== true)
|
|
86
93
|
throw new ApiError('forbidden', 'The source requested capabilities not approved by the owner connection code.');
|
|
94
|
+
if (enrollment.replace_id && (await this.connector(enrollment.replace_id)).installation_id !== b.installation_id)
|
|
95
|
+
throw new ApiError("forbidden", "Authorize sync from this connector’s original installation.");
|
|
87
96
|
const requestHash = hash(JSON.stringify(b));
|
|
88
97
|
let id = enrollment.connector_id;
|
|
89
98
|
if (id && enrollment.request_hash !== requestHash)
|
|
90
99
|
throw new ApiError('idempotency_mismatch', 'This connection code has already been used for another request.');
|
|
91
100
|
if (!id) {
|
|
92
|
-
id = opaque('rc');
|
|
101
|
+
id = enrollment.replace_id ?? opaque('rc');
|
|
93
102
|
if (!await this.store.settings.replaceIf(key, enrollment, { ...enrollment, connector_id: id, request_hash: requestHash }))
|
|
94
103
|
throw new ApiError('idempotency_in_progress', 'Connection registration is in progress. Retry the same request.');
|
|
95
104
|
}
|
|
96
105
|
// Deterministically recover only this registration's reply after a lost HTTP response; no plaintext credential is stored.
|
|
97
106
|
const credential = `ar_connector_${createHmac('sha256', token).update(id).digest('base64url')}`;
|
|
98
107
|
const expires = this.now() + 30 * 24 * 60 * 60_000;
|
|
99
|
-
const
|
|
108
|
+
const candidate = { 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 };
|
|
109
|
+
let row;
|
|
110
|
+
if (enrollment.replace_id) {
|
|
111
|
+
row = await this.connector(id);
|
|
112
|
+
if (row.installation_id !== b.installation_id)
|
|
113
|
+
throw new ApiError('forbidden', 'Authorize sync from this connector’s original installation.');
|
|
114
|
+
if (row.credential_hash !== candidate.credential_hash) {
|
|
115
|
+
if (row.credential_hash !== enrollment.replace_credential_hash || row.revoked !== enrollment.replace_revoked)
|
|
116
|
+
throw new ApiError('forbidden', 'This connector changed after the owner issued its authorization. Request a new code.');
|
|
117
|
+
const next = { ...row, ...candidate, created_at: row.created_at };
|
|
118
|
+
if (!await this.store.settings.replaceIf(keyOf('connector', id), row, next, undefined, [{ key, fields: { connector_id: id, request_hash: requestHash, expires: enrollment.expires } }]))
|
|
119
|
+
throw new ApiError('idempotency_in_progress', 'The connector changed while being authorized. Retry the same request.');
|
|
120
|
+
row = next;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
else
|
|
124
|
+
row = await this.store.settings.putIfAbsent(keyOf('connector', id), candidate);
|
|
100
125
|
if (row.revoked || row.expires <= this.now())
|
|
101
126
|
throw new ApiError('forbidden', 'This connector is revoked. Create a new connection code.');
|
|
102
127
|
return { connector: await this.view(row), credential, credential_expires_at: new Date(row.expires).toISOString() };
|
|
@@ -106,22 +131,30 @@ export class RemoteConnectors {
|
|
|
106
131
|
const row = await this.store.settings.get(keyOf('connector', id));
|
|
107
132
|
if (!row || !token.startsWith('ar_connector_') || !timingSafeEqual(Buffer.from(hash(token)), Buffer.from(row.credential_hash)) || row.revoked || row.expires <= this.now())
|
|
108
133
|
throw new ApiError('unauthenticated', 'The connector credential is invalid, expired or revoked.');
|
|
134
|
+
this.authenticated = { id, credentialHash: row.credential_hash };
|
|
109
135
|
}
|
|
110
136
|
async revoke(id) {
|
|
137
|
+
let revoked;
|
|
111
138
|
for (let attempt = 0; attempt < 10; attempt++) {
|
|
112
139
|
const row = await this.connector(id);
|
|
113
|
-
if (row.revoked
|
|
140
|
+
if (row.revoked) {
|
|
141
|
+
revoked = row;
|
|
114
142
|
break;
|
|
143
|
+
}
|
|
144
|
+
const next = { ...row, revoked: true };
|
|
145
|
+
if (await this.store.settings.replaceIf(keyOf('connector', id), row, next)) {
|
|
146
|
+
revoked = next;
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
115
149
|
}
|
|
116
|
-
|
|
117
|
-
if (!row.revoked)
|
|
150
|
+
if (!revoked)
|
|
118
151
|
throw new ApiError('home_busy', 'The connector changed while it was being revoked; retry.');
|
|
119
152
|
for (const setting of await this.store.settings.all({ prefix: keyOf('command', ''), connectorId: id })) {
|
|
120
153
|
const command = setting.value;
|
|
121
154
|
if (setting.key.startsWith(keyOf('command', '')) && command.connector_id === id && ['queued', 'leased'].includes(command.state))
|
|
122
155
|
await this.store.settings.replaceIf(setting.key, command, { ...command, state: 'cancelled', error: 'Connector revoked.' });
|
|
123
156
|
}
|
|
124
|
-
return { connector: await this.view(
|
|
157
|
+
return { connector: await this.view(revoked) };
|
|
125
158
|
}
|
|
126
159
|
async assertReady(binding) {
|
|
127
160
|
if (!binding.connected || !binding.remote)
|
|
@@ -146,7 +179,7 @@ export class RemoteConnectors {
|
|
|
146
179
|
return { ...binding, state: 'needs_attention', capabilities: { ...binding.capabilities, launch: false }, issues: [...binding.issues, error instanceof Error ? error.message : 'The remote source is unavailable.'] };
|
|
147
180
|
}
|
|
148
181
|
}
|
|
149
|
-
async importTarget(id, input) {
|
|
182
|
+
async importTarget(id, input, resolveAdoption) {
|
|
150
183
|
const b = object(input);
|
|
151
184
|
bounded(b, 256_000);
|
|
152
185
|
if (b.history_only !== undefined && typeof b.history_only !== 'boolean')
|
|
@@ -168,26 +201,61 @@ export class RemoteConnectors {
|
|
|
168
201
|
const connector = await this.connector(id);
|
|
169
202
|
if (connector.revoked)
|
|
170
203
|
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)
|
|
204
|
+
const historyOnly = b.history_only === true, syncOnly = !connector.native_execution && !historyOnly && connector.config_sync === true;
|
|
205
|
+
if (historyOnly ? !connector.history_import || connector.native_execution : !connector.native_execution && !syncOnly)
|
|
173
206
|
throw new ApiError('forbidden', 'This connection code does not authorize the requested import mode.');
|
|
174
207
|
if (historyOnly)
|
|
175
208
|
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.'] };
|
|
209
|
+
if (syncOnly)
|
|
210
|
+
native = { ...native, connected: false, capabilities: { ...native.capabilities, launch: false } };
|
|
176
211
|
native = { ...native, remote: { connector_id: id, target_id: b.target_id } };
|
|
177
|
-
const
|
|
212
|
+
const adoption = b.cli_adoption === undefined ? undefined : resolveAdoption ? await resolveAdoption(id, b.target_id, native, b.cli_adoption) : undefined;
|
|
213
|
+
if (b.cli_adoption !== undefined && !adoption)
|
|
214
|
+
throw new ApiError('forbidden', 'This server cannot verify the existing CLI association.');
|
|
215
|
+
if (syncOnly && !adoption)
|
|
216
|
+
throw new ApiError('input_invalid', 'Enable capture for this source CLI first so sync can keep its existing agent and history.');
|
|
178
217
|
const targetKey = keyOf('target', `${id}.${b.target_id}`);
|
|
179
|
-
|
|
180
|
-
|
|
218
|
+
let prior = await this.store.settings.get(targetKey);
|
|
219
|
+
const sameSource = (saved) => saved.target.project === native.project && saved.target.runtime === native.runtime && saved.target.machine_id === native.machine_id && JSON.stringify(saved.target.selector) === JSON.stringify(native.selector);
|
|
220
|
+
if (prior && !sameSource(prior))
|
|
181
221
|
throw new ApiError('idempotency_mismatch', 'A target id cannot be reused for another source agent.');
|
|
222
|
+
if (prior && adoption && prior.agent_id !== adoption.agentId)
|
|
223
|
+
throw new ApiError('input_invalid', 'This target already has its own durable agent. Its history cannot be replaced by a different profile.');
|
|
224
|
+
const agentId = prior?.agent_id ?? adoption?.agentId ?? `remote-${hash(`${id}:${b.target_id}`).slice(0, 40)}`;
|
|
182
225
|
const name = b.name ?? `${native.runtime} · ${native.selector.name ?? native.project.split('/').filter(Boolean).at(-1) ?? 'project'}`;
|
|
226
|
+
const connectorGuard = { key: keyOf('connector', id), fields: { revoked: false, credential_hash: connector.credential_hash, expires: connector.expires } };
|
|
227
|
+
// Reserve the identity before creating anything. Concurrent imports cannot create two agents, and a crash after
|
|
228
|
+
// reservation is repairable by the same target's retry. A reservation alone grants no execution or export.
|
|
229
|
+
if (!prior) {
|
|
230
|
+
prior = await this.store.settings.putIfAbsent(targetKey, { target_id: b.target_id, agent_id: agentId, name, target: native, history_only: historyOnly, sync_only: syncOnly, owner_disconnected: false, ...(adoption ? { cli_connection_id: adoption.connectionId } : {}) });
|
|
231
|
+
if (prior.agent_id !== agentId || !sameSource(prior))
|
|
232
|
+
throw new ApiError('idempotency_mismatch', 'Another source association reserved this target.');
|
|
233
|
+
}
|
|
183
234
|
let entry = await getAgent(this.store, agentId);
|
|
235
|
+
if (prior.owner_disconnected)
|
|
236
|
+
native = { ...native, connected: false };
|
|
184
237
|
if (entry) {
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
238
|
+
const moved = sourceSyncOf(entry.revision?.body);
|
|
239
|
+
const captured = await cliCaptureOf(this.store, entry);
|
|
240
|
+
if (moved) {
|
|
241
|
+
const source = await this.store.settings.get(sourceKey(agentId));
|
|
242
|
+
if (!source || source.id !== moved.id || source.connection?.connector_id !== id || source.connection.target_id !== b.target_id)
|
|
243
|
+
throw new ApiError('forbidden', 'The managed agent no longer has this source association.');
|
|
244
|
+
// Metadata refresh is allowed after Move; execution never becomes native again.
|
|
245
|
+
}
|
|
246
|
+
else if (prior.cli_connection_id) {
|
|
247
|
+
if (captured?.binding.connection_id !== prior.cli_connection_id)
|
|
248
|
+
throw new ApiError('forbidden', 'The retained CLI profile no longer matches this target.');
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
if (nativeOf(entry.revision?.body)?.connected === false)
|
|
252
|
+
native = { ...native, connected: false };
|
|
253
|
+
entry = await updateNative(this.store, entry, native, [connectorGuard, { key: targetKey, fields: { agent_id: agentId, owner_disconnected: prior.owner_disconnected } }]);
|
|
254
|
+
}
|
|
189
255
|
}
|
|
190
256
|
else {
|
|
257
|
+
if (adoption || prior.cli_connection_id)
|
|
258
|
+
throw new ApiError('not_found', 'The existing CLI agent is no longer available.');
|
|
191
259
|
try {
|
|
192
260
|
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
261
|
}
|
|
@@ -199,15 +267,36 @@ export class RemoteConnectors {
|
|
|
199
267
|
throw error;
|
|
200
268
|
}
|
|
201
269
|
}
|
|
202
|
-
const savedTarget = {
|
|
203
|
-
if (prior)
|
|
204
|
-
|
|
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);
|
|
270
|
+
const savedTarget = { ...prior, name, target: native, history_only: historyOnly, sync_only: syncOnly };
|
|
271
|
+
if (!await this.store.settings.replaceIf(targetKey, prior, savedTarget, undefined, [connectorGuard, ...(adoption?.guards ?? [])]))
|
|
272
|
+
throw new ApiError('home_busy', 'The owner changed this target while it was being imported. Retry after reviewing its connection.');
|
|
209
273
|
return { agent_id: agentId, native };
|
|
210
274
|
}
|
|
275
|
+
async syncAuthority(id, targetId) {
|
|
276
|
+
const connector = await this.connector(id), targetKey = keyOf('target', `${id}.${targetId}`);
|
|
277
|
+
if (connector.revoked || connector.expires <= this.now() || connector.config_sync !== true)
|
|
278
|
+
throw new ApiError('forbidden', 'Authorize configuration sync on the source machine with a new owner connection code.');
|
|
279
|
+
const target = await this.store.settings.get(targetKey);
|
|
280
|
+
if (!target || target.owner_disconnected)
|
|
281
|
+
throw new ApiError('forbidden', 'This source target is unavailable or disconnected by its owner.');
|
|
282
|
+
const entry = await getAgent(this.store, target.agent_id);
|
|
283
|
+
if (!entry?.revision || entry.agent.archivedAt || entry.agent.purgedAt)
|
|
284
|
+
throw new ApiError('not_found', 'The connected agent is unavailable.');
|
|
285
|
+
const native = nativeOf(entry.revision.body), moved = sourceSyncOf(entry.revision.body), capture = await cliCaptureOf(this.store, entry);
|
|
286
|
+
const record = await this.store.settings.get(sourceKey(entry.agent.id));
|
|
287
|
+
if (moved ? record?.id !== moved.id || record?.connection?.connector_id !== id || record?.connection?.target_id !== targetId : target.cli_connection_id ? capture?.binding.connection_id !== target.cli_connection_id : native?.remote?.connector_id !== id || native.remote.target_id !== targetId)
|
|
288
|
+
throw new ApiError('forbidden', 'This connector no longer owns the agent’s source association.');
|
|
289
|
+
const guards = [{ key: keyOf('connector', id), fields: { revoked: false, config_sync: true, credential_hash: connector.credential_hash, expires: connector.expires } },
|
|
290
|
+
{ key: targetKey, fields: { agent_id: target.agent_id, owner_disconnected: target.owner_disconnected, cli_connection_id: target.cli_connection_id } }];
|
|
291
|
+
if (target.cli_connection_id) {
|
|
292
|
+
const row = await this.store.settings.get(`cli-learning-connection:${target.cli_connection_id}`);
|
|
293
|
+
if (!row?.active || row.agent_id !== target.agent_id)
|
|
294
|
+
throw new ApiError('forbidden', 'The source CLI capture connection was revoked.');
|
|
295
|
+
guards.push({ key: `cli-learning-connection:${target.cli_connection_id}`, fields: { active: true, generation: row.generation, agent_id: target.agent_id } });
|
|
296
|
+
}
|
|
297
|
+
const { runtime, machine_id, project, selector } = target.target;
|
|
298
|
+
return { agentId: target.agent_id, authority: { source: { runtime, machine_id, project, selector }, connection: { connector_id: id, target_id: targetId }, captureRevision: record?.capture_revision ?? entry.revision.id, guards } };
|
|
299
|
+
}
|
|
211
300
|
async disconnectTarget(binding) {
|
|
212
301
|
if (!binding.remote)
|
|
213
302
|
return;
|
package/dist/native/schema.d.ts
CHANGED
package/dist/native/schema.js
CHANGED
|
@@ -2,6 +2,7 @@ const text = { type: 'string' };
|
|
|
2
2
|
const nullableText = { type: ['string', 'null'] };
|
|
3
3
|
const strings = { type: 'array', items: text };
|
|
4
4
|
const object = (properties, required = Object.keys(properties)) => ({ type: 'object', additionalProperties: false, properties, required });
|
|
5
|
+
export const SOURCE_LOCAL_CONSENT = object({ version: { const: 1 }, scope: { type: 'string', pattern: '^[a-f0-9]{64}$' } });
|
|
5
6
|
export const NATIVE_SELECTOR = object({ kind: { enum: ['project', 'agent', 'profile'] }, name: text }, ['kind']);
|
|
6
7
|
export const NATIVE_USAGE = object({ input_tokens: { type: ['integer', 'null'] }, output_tokens: { type: ['integer', 'null'] }, cache_read_tokens: { type: ['integer', 'null'] }, cache_write_tokens: { type: ['integer', 'null'] }, cost_usd: { type: ['number', 'null'] } });
|
|
7
8
|
export const NATIVE_TARGET = object({ runtime: { enum: ['claude-code', 'codex'] }, project: text, selector: NATIVE_SELECTOR, machine_id: text, version: nullableText, model: nullableText, fingerprint: text, configuration: { type: 'array', items: object({ path: text, sha256: text }) }, skills: strings, mcp_servers: strings, state: { enum: ['needs_verification', 'needs_attention', 'ready'] }, issues: strings, capabilities: object({ launch: { type: 'boolean' }, learning: { type: 'boolean' }, workflows: { const: false }, approval: { enum: ['native', 'unavailable'] }, usage: { type: 'boolean' } }) });
|
|
@@ -13,29 +14,53 @@ const mark = { 'x-agentrun-serve': 'native/1', security: [{ bearer: [] }, { owne
|
|
|
13
14
|
const id = { $ref: '#/components/parameters/AgentId' };
|
|
14
15
|
export const NATIVE_PATHS = {
|
|
15
16
|
'/native/discover': { post: { ...mark, operationId: 'discoverNative', summary: 'Discover existing native projects on this source machine without running a model', requestBody: body(object({ project: text, runtime: { enum: ['claude-code', 'codex'] } }, ['project'])), responses: { '200': response(object({ machine_id: text, targets: { type: 'array', items: NATIVE_TARGET } })) } } },
|
|
16
|
-
'/native/connect': { post: { ...mark, operationId: 'connectNative', summary: 'Connect a native project using ordinary agent and revision storage', requestBody: body(object({ project: text, runtime: { enum: ['claude-code', 'codex'] }, selector: NATIVE_SELECTOR }, ['project', 'runtime'])), responses: { '200': response(object({ agent: { $ref: '#/components/schemas/Agent' }, native: NATIVE_BINDING })) } } },
|
|
17
|
+
'/native/connect': { post: { ...mark, operationId: 'connectNative', summary: 'Connect a native project using ordinary agent and revision storage', requestBody: body(object({ project: text, runtime: { enum: ['claude-code', 'codex'] }, selector: NATIVE_SELECTOR, source_sync: SOURCE_LOCAL_CONSENT }, ['project', 'runtime'])), responses: { '200': response(object({ agent: { $ref: '#/components/schemas/Agent' }, native: NATIVE_BINDING })) } } },
|
|
17
18
|
'/agents/{agent_id}/native': { get: { ...mark, operationId: 'getNative', summary: 'Read a native connection', parameters: [id], responses: { '200': response(object({ native: { oneOf: [NATIVE_BINDING, { type: 'null' }] } })) } } },
|
|
18
19
|
'/agents/{agent_id}/native/verify': { post: { ...mark, operationId: 'verifyNative', summary: 'Check native CLI and sign-in without a paid model call', parameters: [id], responses: { '200': response(object({ native: NATIVE_BINDING })) } } },
|
|
19
20
|
'/agents/{agent_id}/native/disconnect': { post: { ...mark, operationId: 'disconnectNative', summary: 'Disconnect future native jobs while retaining source configuration and history', parameters: [id], responses: { '200': response(object({ native: NATIVE_BINDING })) } } },
|
|
20
21
|
};
|
|
21
22
|
const targetId = { name: 'target_id', in: 'path', required: true, schema: text };
|
|
22
|
-
const scopes = object({ native_execution: { type: 'boolean' }, history_import: { type: 'boolean' } }, []);
|
|
23
|
+
const scopes = object({ native_execution: { type: 'boolean' }, history_import: { type: 'boolean' }, config_sync: { type: 'boolean' } }, []);
|
|
23
24
|
const connectorId = { name: 'connector_id', in: 'path', required: true, schema: text };
|
|
24
25
|
const commandId = { name: 'command_id', in: 'path', required: true, schema: text };
|
|
25
26
|
const opaqueObject = { type: 'object', additionalProperties: true };
|
|
26
|
-
const connector = object({ id: text, connector_id: text, label: text, created_at: text, last_seen_at: nullableText, status: { enum: ['online', 'offline', 'revoked'] }, capabilities: object({ observe: { const: true }, native_execution: { type: 'boolean' }, history_import: { type: 'boolean' } }), targets: { type: 'array', items: opaqueObject } });
|
|
27
|
+
const connector = object({ id: text, connector_id: text, label: text, created_at: text, last_seen_at: nullableText, status: { enum: ['online', 'offline', 'revoked'] }, capabilities: object({ observe: { const: true }, native_execution: { type: 'boolean' }, history_import: { type: 'boolean' }, config_sync: { type: 'boolean' } }), targets: { type: 'array', items: opaqueObject } });
|
|
27
28
|
const remoteMark = { ...mark, tags: ['connectors'], 'x-agentrun-serve': 'connectors/1' };
|
|
28
29
|
const workerMark = { ...remoteMark, security: [{ bearer: [] }] };
|
|
29
30
|
Object.assign(NATIVE_PATHS, {
|
|
30
31
|
'/connectors': {
|
|
31
32
|
get: { ...remoteMark, operationId: 'listRemoteConnectors', summary: 'List remote source machines and imported agent targets', responses: { '200': response(object({ connectors: { type: 'array', items: connector } })) } },
|
|
32
|
-
post: { ...workerMark, operationId: 'registerRemoteConnector', summary: 'Exchange a one-use enrollment code for a connector-scoped credential', requestBody: body(object({ installation_id: text, operation_id: text, label: text, capabilities: object({ native_execution: { type: 'boolean' }, history_import: { type: 'boolean' } }, ['native_execution']) }, ['installation_id', 'operation_id', 'capabilities'])), responses: { '200': response(object({ connector, credential: text, credential_expires_at: text })) } }
|
|
33
|
+
post: { ...workerMark, operationId: 'registerRemoteConnector', summary: 'Exchange a one-use enrollment code for a connector-scoped credential', requestBody: body(object({ installation_id: text, operation_id: text, label: text, capabilities: object({ native_execution: { type: 'boolean' }, history_import: { type: 'boolean' }, config_sync: { type: 'boolean' } }, ['native_execution']) }, ['installation_id', 'operation_id', 'capabilities'])), responses: { '200': response(object({ connector, credential: text, credential_expires_at: text })) } }
|
|
33
34
|
},
|
|
34
|
-
'/connectors/enrollment': { post: { ...remoteMark, operationId: 'enrollRemoteConnector', summary: 'Create a ten-minute one-use connection code', requestBody: body(object({ label: text, capabilities: scopes }, [])), responses: { '200': response(object({ enrollment_token: text, expires_at: text, workspace_id: { const: 'local' } })) } } },
|
|
35
|
+
'/connectors/enrollment': { post: { ...remoteMark, operationId: 'enrollRemoteConnector', summary: 'Create a ten-minute one-use connection code', requestBody: body(object({ label: text, capabilities: scopes, connector_id: text }, [])), responses: { '200': response(object({ enrollment_token: text, expires_at: text, workspace_id: { const: 'local' } })) } } },
|
|
35
36
|
'/connectors/{connector_id}': { delete: { ...remoteMark, operationId: 'revokeRemoteConnector', summary: 'Revoke a source connector and stop its outstanding commands', parameters: [connectorId], responses: { '200': response(object({ connector })) } } },
|
|
36
|
-
'/connectors/{connector_id}/import': { post: { ...workerMark, operationId: 'importRemoteTarget', summary: 'Import an explicitly selected source-native agent reference', parameters: [connectorId], requestBody: body(object({ target_id: text, name: text, target: NATIVE_BINDING, history_only: { type: 'boolean' } }, ['target_id', 'target'])), responses: { '200': response(object({ agent_id: text, native: NATIVE_BINDING })) } } },
|
|
37
|
+
'/connectors/{connector_id}/import': { post: { ...workerMark, operationId: 'importRemoteTarget', summary: 'Import an explicitly selected source-native agent reference', parameters: [connectorId], requestBody: body(object({ target_id: text, name: text, target: NATIVE_BINDING, history_only: { type: 'boolean' }, cli_adoption: object({ connection_id: text, credential_epoch: text, proof: text }) }, ['target_id', 'target'])), responses: { '200': response(object({ agent_id: text, native: NATIVE_BINDING })) } } },
|
|
37
38
|
'/connectors/{connector_id}/targets/{target_id}/history': { post: { ...workerMark, operationId: 'importRemoteHistory', summary: 'Import explicitly selected, redacted past sessions without running or learning from them', parameters: [connectorId, targetId], requestBody: body(object({ sessions: { type: 'array', minItems: 1, maxItems: 20, items: opaqueObject } })), responses: { '200': response(object({ agent_id: text, runs: { type: 'array', items: object({ session_id: text, run_id: text, already: { type: 'boolean' } }) }, imported: { type: 'integer' }, already: { type: 'integer' } })) } } },
|
|
38
39
|
'/connectors/{connector_id}/poll': { post: { ...workerMark, operationId: 'pollRemoteConnector', summary: 'Renew active source leases and claim one command without replay', parameters: [connectorId], requestBody: body(object({ worker_id: text, active: { type: 'array', items: object({ command_id: text, lease_token: text }) } }, ['worker_id'])), responses: { '200': response(object({ commands: { type: 'array', items: opaqueObject }, cancelled: strings, server_time: { type: 'number' }, lease_ttl_ms: { type: 'number' } })) } } },
|
|
39
40
|
'/connectors/{connector_id}/commands/{command_id}/events': { post: { ...workerMark, operationId: 'remoteCommandEvents', summary: 'Append an ordered idempotent native event batch for a valid command lease', parameters: [connectorId, commandId], requestBody: body(object({ lease_token: text, sequence: { type: 'integer', minimum: 0 }, events: { type: 'array', items: opaqueObject } })), responses: { '200': response(object({ accepted: { const: true } })) } } },
|
|
40
41
|
'/connectors/{connector_id}/commands/{command_id}/complete': { post: { ...workerMark, operationId: 'completeRemoteCommand', summary: 'Complete a source command once under its valid lease', parameters: [connectorId, commandId], requestBody: body(object({ lease_token: text, result: {}, error: text }, ['lease_token'])), responses: { '200': response(object({ accepted: { const: true } })) } } }
|
|
41
42
|
});
|
|
43
|
+
const sourceProjectIdentities = [
|
|
44
|
+
object({ run_id: text, entry_id: { type: 'integer', minimum: 1 } }),
|
|
45
|
+
object({ run_id: text, entry_id: { type: 'null' }, attempt_epoch: { type: 'integer', minimum: 1 } }),
|
|
46
|
+
];
|
|
47
|
+
const sourceProjectReceipt = { oneOf: sourceProjectIdentities };
|
|
48
|
+
const sourceProjectIssue = { oneOf: sourceProjectIdentities.map(identity => object({ ...identity.properties, status: { enum: ['pending', 'conflict', 'uncertain'] }, reason: text }, [...identity.required, 'status'])) };
|
|
49
|
+
const sourceStatus = object({ project_issues: { type: 'array', items: sourceProjectIssue }, enabled: { type: 'boolean' }, moved: { type: 'boolean' }, state: { enum: ['needs_connection', 'paused', 'syncing', 'needs_attention', 'ready', 'moved', 'conflict'] }, blockers: { type: 'array', items: object({ code: text, message: text, path: text }, ['code', 'message']) }, snapshot: text, current_snapshot: text, connection: object({ connector_id: text, target_id: text }), files: { type: 'integer' }, bytes: { type: 'integer' }, skills: { type: 'integer' }, tools: { type: 'integer' }, tool_connections: { type: 'array', items: object({ name: text, ready: { type: 'boolean' }, selected: text, candidates: { type: 'array', items: object({ name: text, auth: text }) } }, ['name', 'ready', 'candidates']) } }, ['enabled', 'moved', 'state', 'blockers']);
|
|
50
|
+
Object.assign(NATIVE_PATHS, {
|
|
51
|
+
'/connectors/{connector_id}/targets/{target_id}/sync/grant': { post: { ...workerMark, operationId: 'grantSourceSync', summary: 'Read or establish this explicitly authorized source sync grant without re-enabling a paused grant', parameters: [connectorId, targetId], requestBody: body(object({})), responses: { '200': response(opaqueObject) } } },
|
|
52
|
+
'/connectors/{connector_id}/targets/{target_id}/sync': { post: { ...workerMark, operationId: 'publishSourceSync', summary: 'Publish a bounded source snapshot under its grant and sequence', parameters: [connectorId, targetId], requestBody: body(object({ generation: text, sequence: { type: 'integer', minimum: 0 }, snapshot: opaqueObject })), responses: { '200': response(opaqueObject) } } },
|
|
53
|
+
'/connectors/{connector_id}/targets/{target_id}/sync/status': { post: { ...workerMark, operationId: 'sourceSyncFailure', summary: 'Record a fixed source failure while preserving its last complete snapshot', parameters: [connectorId, targetId], requestBody: body(object({ generation: text, sequence: { type: 'integer', minimum: 0 }, code: { enum: ['unsupported_platform', 'source_changed', 'source_unavailable', 'snapshot_too_large'] } })), responses: { '200': response(opaqueObject) } } },
|
|
54
|
+
'/agents/{agent_id}/source': {
|
|
55
|
+
get: { ...mark, operationId: 'getSourceSync', summary: 'Read source sync and managed Move readiness', parameters: [id], responses: { '200': response(sourceStatus) } },
|
|
56
|
+
patch: { ...mark, operationId: 'setSourceSync', summary: 'Enable or pause this agent’s source sync', parameters: [id], requestBody: body(object({ enabled: { type: 'boolean' } })), responses: { '200': response(sourceStatus) } }
|
|
57
|
+
},
|
|
58
|
+
'/agents/{agent_id}/source/move': { post: { ...mark, operationId: 'moveSourceAgent', summary: 'Move the same agent to server-managed execution from its complete synchronized setup', parameters: [id], requestBody: body(object({})), responses: { '200': response(object({ agent: { $ref: '#/components/schemas/Agent' }, source: sourceStatus })) } } },
|
|
59
|
+
'/agents/{agent_id}/source/tools': { post: { ...mark, operationId: 'bindSourceTool', summary: 'Choose the existing destination account for a required source tool', parameters: [id], requestBody: body(object({ tool: text, server: text })), responses: { '200': response(sourceStatus) } } }
|
|
60
|
+
});
|
|
61
|
+
Object.assign(NATIVE_PATHS, {
|
|
62
|
+
'/agents/{agent_id}/source/resolve': { post: { ...mark, operationId: 'resolveSourceSync', summary: 'Use an explicitly reviewed source snapshot while retaining the prior managed revision in history', parameters: [id], requestBody: body(object({ revision: text, snapshot: text })), responses: { '200': response(object({ agent: { $ref: '#/components/schemas/Agent' }, source: sourceStatus })) } } }
|
|
63
|
+
});
|
|
64
|
+
Object.assign(NATIVE_PATHS, {
|
|
65
|
+
'/agents/{agent_id}/source/project-review': { post: { ...mark, operationId: 'reviewSourceProject', summary: 'Acknowledge exact unresolved run receipts and allow later runs to use the saved project', parameters: [id], requestBody: body(object({ receipts: { type: 'array', minItems: 1, maxItems: 1000, items: sourceProjectReceipt } })), responses: { '200': response(sourceStatus) } } }
|
|
66
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Codex 0.171.0's local auth metadata rules, not authentication or token verification.
|
|
2
|
+
* login/auth/manager.rs resolved_mode and account_plan_type, token_data.rs, and
|
|
3
|
+
* manager/workspace_switching.rs selected_workspace_tokens define these projections.
|
|
4
|
+
* Native code itself decodes these saved claims without signature verification. We use them
|
|
5
|
+
* only to refuse unproven policy portability; destination sign-in remains independently required. */
|
|
6
|
+
import type { SourceNativeAccount } from "./source-snapshot-types.js";
|
|
7
|
+
/** Consumes a bounded private buffer. Returns fixed nonsecret labels only: no claims, IDs, email,
|
|
8
|
+
* expiry, token hashes or raw values. Unknown/refresh-due state cannot establish portability. */
|
|
9
|
+
export declare function sourceAccountMetadata(bytes: Uint8Array | null, now?: number): SourceNativeAccount;
|
|
10
|
+
export declare function sourceAccountMetadataValid(value: unknown): value is SourceNativeAccount;
|
|
11
|
+
/** Boolean-only private check, including escaped/percent/base64/hex spellings used by the existing
|
|
12
|
+
* held-secret scanner. The credential strings and matcher exist only for this bounded call. */
|
|
13
|
+
export declare function sourceAccountContainsSecret(bytes: Uint8Array, contents: Iterable<string>): boolean;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { valueMatcher } from "../learn/secrets.js";
|
|
2
|
+
import { keyShaped } from "../secret-name.js";
|
|
3
|
+
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
4
|
+
const unknown = () => ({ source: "codex-auth-file", mode: "unknown", plan: "unknown" });
|
|
5
|
+
const ordinary = new Set(["free", "go", "plus", "pro", "prolite", "promax"]);
|
|
6
|
+
const managed = new Set(["team", "self_serve_business_prolite", "self_serve_business_usage_based", "business", "ent26", "enterprise_cbp_automation", "enterprise_cbp_usage_based", "enterprise", "edu", "edu_plus", "edu_pro", "sci", "sci_plus"]);
|
|
7
|
+
function claims(value) {
|
|
8
|
+
if (typeof value !== "string" || value.length > 32_768)
|
|
9
|
+
return;
|
|
10
|
+
const parts = value.split(".");
|
|
11
|
+
if (parts.length !== 3 || parts.some(part => !part || !/^[A-Za-z0-9_-]+$/.test(part)))
|
|
12
|
+
return;
|
|
13
|
+
const payload = Buffer.from(parts[1], "base64url");
|
|
14
|
+
if (payload.toString("base64url") !== parts[1])
|
|
15
|
+
return;
|
|
16
|
+
try {
|
|
17
|
+
const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payload));
|
|
18
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
19
|
+
return;
|
|
20
|
+
const value = parsed, auth = value["https://api.openai.com/auth"], profile = value["https://api.openai.com/profile"];
|
|
21
|
+
const optionalText = (value) => value == null || typeof value === "string";
|
|
22
|
+
if (!optionalText(value.email) || profile != null && (typeof profile !== "object" || Array.isArray(profile) || !optionalText(profile.email))
|
|
23
|
+
|| auth != null && (typeof auth !== "object" || Array.isArray(auth)
|
|
24
|
+
|| ["chatgpt_plan_type", "chatgpt_user_id", "user_id", "chatgpt_account_id"].some(key => !optionalText(auth[key]))
|
|
25
|
+
|| auth.chatgpt_account_is_fedramp !== undefined && typeof auth.chatgpt_account_is_fedramp !== "boolean"))
|
|
26
|
+
return;
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
payload.fill(0);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Consumes a bounded private buffer. Returns fixed nonsecret labels only: no claims, IDs, email,
|
|
37
|
+
* expiry, token hashes or raw values. Unknown/refresh-due state cannot establish portability. */
|
|
38
|
+
export function sourceAccountMetadata(bytes, now = Date.now()) {
|
|
39
|
+
if (bytes === null)
|
|
40
|
+
return { source: "codex-auth-file", mode: "none", plan: null };
|
|
41
|
+
if (bytes.length > 65_536)
|
|
42
|
+
return unknown();
|
|
43
|
+
try {
|
|
44
|
+
const auth = object(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
|
|
45
|
+
const mode = auth.auth_mode ?? (auth.personal_access_token != null ? "personalAccessToken"
|
|
46
|
+
: auth.bedrock_api_key != null ? "bedrockApiKey" : auth.bedrock_access_keys != null ? "bedrockAccessKeys"
|
|
47
|
+
: auth.OPENAI_API_KEY != null ? "apikey" : "chatgpt");
|
|
48
|
+
if (mode === "apikey")
|
|
49
|
+
return typeof auth.OPENAI_API_KEY === "string" && auth.OPENAI_API_KEY.trim()
|
|
50
|
+
? { source: "codex-auth-file", mode: "apikey", plan: null } : unknown();
|
|
51
|
+
// External, keyring and host-owned credentials cannot be established by this file projection.
|
|
52
|
+
if (mode !== "chatgpt")
|
|
53
|
+
return unknown();
|
|
54
|
+
const tokens = object(auth.tokens), id = claims(tokens.id_token), access = claims(tokens.access_token);
|
|
55
|
+
if (!id || !access || typeof tokens.refresh_token !== "string" || !tokens.refresh_token
|
|
56
|
+
|| typeof auth.last_refresh !== "string" || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(auth.last_refresh) || !Number.isFinite(Date.parse(auth.last_refresh))
|
|
57
|
+
|| tokens.account_id != null && typeof tokens.account_id !== "string"
|
|
58
|
+
|| !Number.isSafeInteger(access.exp) || access.exp * 1000 > 8.64e15 || access.exp * 1000 <= now + 5 * 60_000)
|
|
59
|
+
return unknown();
|
|
60
|
+
let selected = object(id["https://api.openai.com/auth"]);
|
|
61
|
+
const current = object(access["https://api.openai.com/auth"]), account = tokens.account_id ?? null;
|
|
62
|
+
// The retained ID token may describe a previous workspace. Match native's account/user
|
|
63
|
+
// equality before taking the current access-token plan; an unresolved mismatch stays blocked.
|
|
64
|
+
if (account !== (selected.chatgpt_account_id ?? null)) {
|
|
65
|
+
if (account !== (current.chatgpt_account_id ?? null)
|
|
66
|
+
|| (current.chatgpt_user_id ?? current.user_id ?? null) !== (selected.chatgpt_user_id ?? selected.user_id ?? null))
|
|
67
|
+
return unknown();
|
|
68
|
+
selected = current;
|
|
69
|
+
}
|
|
70
|
+
const plan = selected.chatgpt_plan_type;
|
|
71
|
+
if (selected.chatgpt_account_is_fedramp === true)
|
|
72
|
+
return { source: "codex-auth-file", mode: "chatgpt", plan: "managed" };
|
|
73
|
+
return { source: "codex-auth-file", mode: "chatgpt", plan: ordinary.has(plan) ? "ordinary" : managed.has(plan) ? "managed" : "unknown" };
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return unknown();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export function sourceAccountMetadataValid(value) {
|
|
80
|
+
const v = object(value);
|
|
81
|
+
return Object.keys(v).length === 3 && v.source === "codex-auth-file"
|
|
82
|
+
&& (["none", "apikey"].includes(v.mode) ? v.plan === null : v.mode === "chatgpt" ? ["ordinary", "managed", "unknown"].includes(v.plan) : v.mode === "unknown" && v.plan === "unknown");
|
|
83
|
+
}
|
|
84
|
+
/** Boolean-only private check, including escaped/percent/base64/hex spellings used by the existing
|
|
85
|
+
* held-secret scanner. The credential strings and matcher exist only for this bounded call. */
|
|
86
|
+
export function sourceAccountContainsSecret(bytes, contents) {
|
|
87
|
+
if (bytes.length > 65_536)
|
|
88
|
+
return false; // No bytes of an oversized auth file are read.
|
|
89
|
+
const values = [];
|
|
90
|
+
try {
|
|
91
|
+
const pending = [JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes))];
|
|
92
|
+
for (let count = 0; pending.length; count++) {
|
|
93
|
+
if (count > 10_000)
|
|
94
|
+
return true;
|
|
95
|
+
const value = pending.pop();
|
|
96
|
+
if (!value || typeof value !== "object")
|
|
97
|
+
continue;
|
|
98
|
+
for (const [key, child] of Object.entries(value)) {
|
|
99
|
+
if (typeof child === "string" && child && keyShaped(key))
|
|
100
|
+
values.push(child);
|
|
101
|
+
else if (child && typeof child === "object")
|
|
102
|
+
pending.push(child);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const matches = valueMatcher(values);
|
|
106
|
+
for (const content of contents)
|
|
107
|
+
if (values.some(value => content.includes(value) || content.includes(JSON.stringify(value).slice(1, -1))) || matches(content))
|
|
108
|
+
return true;
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return false;
|
|
113
|
+
} // Malformed auth already makes the snapshot incomplete.
|
|
114
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** Pure verifier for the sole source-to-destination rewrite: remove exact installer-owned capture handlers.
|
|
2
|
+
* It never treats arbitrary hooks, a command substring, or a matching filename as owned AgentRun behavior. */
|
|
3
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
4
|
+
import { isAbsolute, basename } from 'node:path';
|
|
5
|
+
import { NATIVE_RUNTIME_FACTS } from "./runtimes.js";
|
|
6
|
+
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
7
|
+
const quote = (value) => `'${value.replaceAll("'", "'\"'\"'")}'`;
|
|
8
|
+
function argumentsOf(line) {
|
|
9
|
+
const values = [];
|
|
10
|
+
let offset = 0;
|
|
11
|
+
while (offset < line.length) {
|
|
12
|
+
if (line[offset++] !== "'")
|
|
13
|
+
return;
|
|
14
|
+
let value = '', closed = false;
|
|
15
|
+
while (offset < line.length) {
|
|
16
|
+
if (line.startsWith("'\"'\"'", offset)) {
|
|
17
|
+
value += "'";
|
|
18
|
+
offset += 5;
|
|
19
|
+
}
|
|
20
|
+
else if (line[offset] === "'") {
|
|
21
|
+
offset++;
|
|
22
|
+
closed = true;
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
else
|
|
26
|
+
value += line[offset++];
|
|
27
|
+
}
|
|
28
|
+
if (!closed)
|
|
29
|
+
return;
|
|
30
|
+
values.push(value);
|
|
31
|
+
if (offset < line.length && line[offset++] !== ' ')
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
return values.map(quote).join(' ') === line ? values : undefined;
|
|
35
|
+
}
|
|
36
|
+
const failure = () => { throw new Error('Source hooks are not an unchanged, complete AgentRun capture installation.'); };
|
|
37
|
+
export function removeOwnedCaptureHooks(original, receiptBytes, source) {
|
|
38
|
+
let config, receipt;
|
|
39
|
+
try {
|
|
40
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
41
|
+
config = JSON.parse(decoder.decode(original));
|
|
42
|
+
receipt = JSON.parse(decoder.decode(receiptBytes));
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return failure();
|
|
46
|
+
}
|
|
47
|
+
const events = NATIVE_RUNTIME_FACTS[source.runtime].protocol === 'codex-json' ? ['UserPromptSubmit', 'Stop', 'Interrupt', 'SessionEnd'] : ['UserPromptSubmit', 'Stop', 'StopFailure', 'SessionEnd'];
|
|
48
|
+
if (!object(config) || !object(config.hooks) || config.disableAllHooks === true || !object(receipt)
|
|
49
|
+
|| ![1, 2].includes(receipt.version) || receipt.runtime !== source.runtime || receipt.project !== source.project
|
|
50
|
+
|| typeof receipt.dataDir !== 'string' || !isAbsolute(receipt.dataDir) || receipt.dataDir === source.project || receipt.dataDir.startsWith(source.project + '/')
|
|
51
|
+
|| typeof receipt.url !== 'string' || typeof receipt.hadHooks !== 'boolean' || !Array.isArray(receipt.createdEvents)
|
|
52
|
+
|| receipt.createdEvents.some((event) => typeof event !== 'string' || !events.includes(event))
|
|
53
|
+
|| !object(receipt.handlers) || !isDeepStrictEqual(Object.keys(receipt.handlers).sort(), [...events].sort()) || receipt.legacy !== undefined)
|
|
54
|
+
return failure();
|
|
55
|
+
let url;
|
|
56
|
+
try {
|
|
57
|
+
url = new URL(receipt.url);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return failure();
|
|
61
|
+
}
|
|
62
|
+
if (!['http:', 'https:'].includes(url.protocol) || !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
|
|
63
|
+
|| url.username || url.password || url.search || url.hash || url.pathname !== '/')
|
|
64
|
+
return failure();
|
|
65
|
+
const configRoot = receipt.version === 1 ? source.project : receipt.configRoot;
|
|
66
|
+
if (typeof configRoot !== 'string' || !isAbsolute(configRoot) || receipt.version === 2 && (NATIVE_RUNTIME_FACTS[source.runtime].protocol !== 'codex-json' || receipt.format !== 'codex-shared-json' || configRoot === source.project))
|
|
67
|
+
return failure();
|
|
68
|
+
for (const event of events) {
|
|
69
|
+
const owned = receipt.handlers[event], groups = config.hooks[event];
|
|
70
|
+
if (!object(owned) || !isDeepStrictEqual(Object.keys(owned).sort(), ['command', 'timeout', 'type']) || owned.type !== 'command' || owned.timeout !== 5 || typeof owned.command !== 'string' || !Array.isArray(groups))
|
|
71
|
+
return failure();
|
|
72
|
+
const args = argumentsOf(owned.command), suffix = ['learning', 'hook', '--runtime', source.runtime, '--project', source.project, '--data', receipt.dataDir, '--url', receipt.url];
|
|
73
|
+
if (!args || args.length !== suffix.length + 2 || !isAbsolute(args[0]) || basename(args[0]) !== 'node' || !isAbsolute(args[1])
|
|
74
|
+
|| !args[1].endsWith('/cli-learning/entry.js') || !isDeepStrictEqual(args.slice(2), suffix))
|
|
75
|
+
return failure();
|
|
76
|
+
let found = false;
|
|
77
|
+
const kept = [];
|
|
78
|
+
for (const group of groups) {
|
|
79
|
+
if (!object(group) || !Array.isArray(group.hooks))
|
|
80
|
+
return failure();
|
|
81
|
+
const ownedGroup = group.matcher === undefined || group.matcher === '' || group.matcher === '*';
|
|
82
|
+
const hooks = group.hooks.filter((handler) => {
|
|
83
|
+
if (ownedGroup && isDeepStrictEqual(handler, owned)) {
|
|
84
|
+
found = true;
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
});
|
|
89
|
+
if (hooks.length)
|
|
90
|
+
kept.push({ ...group, hooks });
|
|
91
|
+
}
|
|
92
|
+
if (!found)
|
|
93
|
+
return failure();
|
|
94
|
+
if (kept.length)
|
|
95
|
+
config.hooks[event] = kept;
|
|
96
|
+
else
|
|
97
|
+
delete config.hooks[event];
|
|
98
|
+
}
|
|
99
|
+
if (!Object.keys(config.hooks).length)
|
|
100
|
+
delete config.hooks;
|
|
101
|
+
return { bytes: Buffer.from(JSON.stringify(config, null, 2) + '\n'), configRoot };
|
|
102
|
+
}
|