@kingsoftcloud/agentkit-harness-node 0.0.17 → 0.0.19
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/dist/engine-view.html +642 -0
- package/dist/index.mjs +18 -10
- package/dist/rpc-entry.mjs +18 -10
- package/package.json +16 -2
- package/src/native/activity-status.mjs +13 -8
- package/src/native/browser-workspace-server.mjs +22 -7
- package/src/native/child-owner.mjs +8 -4
- package/src/native/children.mjs +12 -7
- package/src/native/command-shell.mjs +28 -3
- package/src/native/engine-client.mjs +83 -0
- package/src/native/engine-context.mjs +47 -0
- package/src/native/engine-delivery-evidence.mjs +37 -0
- package/src/native/engine-hooks.mjs +53 -0
- package/src/native/engine-host-effects.mjs +98 -0
- package/src/native/engine-managed-delivery.mjs +65 -0
- package/src/native/engine-managed-host.mjs +75 -0
- package/src/native/engine-managed-service.mjs +249 -0
- package/src/native/engine-runtime.mjs +480 -0
- package/src/native/engine-server.mjs +540 -0
- package/src/native/engine-service.mjs +281 -0
- package/src/native/engine-tool-policy.mjs +29 -0
- package/src/native/engine-verification.mjs +111 -0
- package/src/native/engine-view-store.mjs +63 -0
- package/src/native/instruction-assembly.mjs +67 -3
- package/src/native/local-background-supervisor.mjs +1 -1
- package/src/native/local-background.mjs +4 -3
- package/src/native/local-command-tools.mjs +10 -7
- package/src/native/native-kernel-events.mjs +103 -0
- package/src/native/native-kernel-permit.mjs +95 -0
- package/src/native/native-managed-execution-grants.mjs +232 -0
- package/src/native/native-managed-injection.mjs +53 -0
- package/src/native/native-managed-interaction.mjs +192 -0
- package/src/native/native-managed-kernel-http.mjs +122 -0
- package/src/native/native-managed-kernel.mjs +922 -0
- package/src/native/native-managed-scoped-control.mjs +116 -0
- package/src/native/native-managed-session-frames.mjs +43 -0
- package/src/native/native-managed-teams-context.mjs +126 -0
- package/src/native/native-teams-callback-authority.mjs +73 -0
- package/src/native/native-teams-context-contract.mjs +272 -0
- package/src/native/native-teams-json.mjs +38 -0
- package/src/native/native-terminal-failure.mjs +53 -0
- package/src/native/sqlite-store.mjs +1 -0
- package/src/native/workspace-tools.mjs +2 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/** Durable delivery of a Server control to its original A2A scope. This queue
|
|
2
|
+
* never submits Native root cancellation or retries an unknown remote effect;
|
|
3
|
+
* the original A2A control journal owns its own effect admission/reconciliation. */
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { canonical, copy, invariant, parseNativeJson, terminal } from '@kingsoftcloud/agentkit-harness-core';
|
|
6
|
+
import { nativeKernelFactId } from './native-kernel-events.mjs';
|
|
7
|
+
|
|
8
|
+
export const MANAGED_NATIVE_SCOPED_CONTROL = 'agentkit.managed-native-scoped-control/v1';
|
|
9
|
+
export function createManagedNativeScopedControls({ db, guard, transaction, append, lookup, control, clock, lifetime, wake }) {
|
|
10
|
+
invariant(control === undefined || typeof control?.prepare === 'function' && typeof control?.execute === 'function',
|
|
11
|
+
'NATIVE_KERNEL_CONFIGURATION_INVALID');
|
|
12
|
+
db.exec(`CREATE TABLE IF NOT EXISTS managed_scoped_controls (command_id TEXT PRIMARY KEY, session_id TEXT NOT NULL,
|
|
13
|
+
run_id TEXT NOT NULL, data TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'queued', result TEXT, owner_id TEXT,
|
|
14
|
+
owner_until INTEGER NOT NULL DEFAULT 0)`);
|
|
15
|
+
const owner = randomUUID(), work = new Map();
|
|
16
|
+
let closed = false;
|
|
17
|
+
const row = id => db.prepare('SELECT * FROM managed_scoped_controls WHERE command_id=?').get(id);
|
|
18
|
+
function current(data) {
|
|
19
|
+
guard();
|
|
20
|
+
const value = lookup(data.command.session_id, data.runId), snapshot = value.record?.snapshot;
|
|
21
|
+
invariant(value && snapshot && !terminal(snapshot.phase) && value.configDigest === data.configDigest
|
|
22
|
+
&& canonical(value.scope) === canonical(data.scope), 'NATIVE_MANAGED_SCOPE_UNAVAILABLE');
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
async function prepare(command, runId) {
|
|
26
|
+
invariant(control, 'NATIVE_MANAGED_SCOPE_UNSUPPORTED');
|
|
27
|
+
const value = lookup(command.session_id, runId);
|
|
28
|
+
const data = { contract: MANAGED_NATIVE_SCOPED_CONTROL, command: copy(command), runId,
|
|
29
|
+
scope: copy(value.scope), configDigest: value.configDigest };
|
|
30
|
+
current(data);
|
|
31
|
+
const target = await control.prepare({ command: copy(command), run: copy(value), signal: lifetime.signal });
|
|
32
|
+
current(data);
|
|
33
|
+
invariant(target && typeof target === 'object' && target.scopeId === command.payload.scope_id
|
|
34
|
+
&& Buffer.byteLength(canonical(target)) <= 1024 * 1024, 'NATIVE_MANAGED_SCOPE_NOT_FOUND');
|
|
35
|
+
return { ...data, target: copy(target) };
|
|
36
|
+
}
|
|
37
|
+
// Called in the same transaction as command admission/receipt/fact.
|
|
38
|
+
function admit(command, data, authorization) {
|
|
39
|
+
current(data);
|
|
40
|
+
db.prepare('INSERT INTO managed_scoped_controls(command_id,session_id,run_id,data) VALUES (?,?,?,?)')
|
|
41
|
+
.run(command.command_id, command.session_id, data.runId, canonical({ ...data, actor: authorization.subjectRef }));
|
|
42
|
+
db.prepare("UPDATE managed_commands SET state='delivered' WHERE command_id=?").run(command.command_id);
|
|
43
|
+
}
|
|
44
|
+
async function deliver(found) {
|
|
45
|
+
const stop = new AbortController(), signal = AbortSignal.any([lifetime.signal, stop.signal]);
|
|
46
|
+
const data = parseNativeJson(found.data);
|
|
47
|
+
let timer;
|
|
48
|
+
const assertCurrent = () => {
|
|
49
|
+
signal.throwIfAborted(); current(data);
|
|
50
|
+
const saved = row(found.command_id);
|
|
51
|
+
invariant(!closed && saved?.state === 'queued' && saved.owner_id === owner && saved.owner_until > clock(),
|
|
52
|
+
'NATIVE_MANAGED_SCOPE_AUTHORITY_LOST');
|
|
53
|
+
return true;
|
|
54
|
+
};
|
|
55
|
+
try {
|
|
56
|
+
assertCurrent();
|
|
57
|
+
timer = setInterval(() => {
|
|
58
|
+
try { transaction(() => {
|
|
59
|
+
assertCurrent();
|
|
60
|
+
db.prepare('UPDATE managed_scoped_controls SET owner_until=? WHERE command_id=? AND owner_id=?')
|
|
61
|
+
.run(clock() + 2000, found.command_id, owner);
|
|
62
|
+
}); } catch (error) { stop.abort(error); }
|
|
63
|
+
}, 100);
|
|
64
|
+
let abort;
|
|
65
|
+
const retired = new Promise((_, reject) => { abort = () => reject(signal.reason); signal.addEventListener('abort', abort, { once: true }); });
|
|
66
|
+
let result;
|
|
67
|
+
try { result = await Promise.race([Promise.resolve().then(() => { assertCurrent();
|
|
68
|
+
return control.execute({ command: copy(data.command), target: copy(data.target), actor: data.actor,
|
|
69
|
+
run: copy(current(data)), signal, assertCurrent }); }), retired]); }
|
|
70
|
+
finally { signal.removeEventListener('abort', abort); }
|
|
71
|
+
assertCurrent();
|
|
72
|
+
transaction(() => { assertCurrent();
|
|
73
|
+
db.prepare("UPDATE managed_scoped_controls SET state='delivered',result=?,owner_until=0 WHERE command_id=? AND owner_id=?")
|
|
74
|
+
.run(canonical(result ?? null), found.command_id, owner); });
|
|
75
|
+
wake();
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (!signal.aborted && !closed) {
|
|
78
|
+
// These errors precede delivery or denote permanent authority loss.
|
|
79
|
+
// Retrying transport/business errors uses the SAME original A2A command
|
|
80
|
+
// identity, whose private journal refuses uncertain effect resends.
|
|
81
|
+
const permanent = ['NATIVE_MANAGED_SCOPE_UNAVAILABLE', 'NATIVE_MANAGED_SCOPE_NOT_FOUND',
|
|
82
|
+
'NATIVE_MANAGED_SCOPE_TARGET_CHANGED', 'STUDIO_NATIVE_A2A_PRESET_CHANGED', 'STUDIO_NATIVE_A2A_PERMISSION_UNAVAILABLE',
|
|
83
|
+
'studio_native_recovery_preset_changed', 'studio_native_recovery_identity_mismatch', 'stored_configuration_mismatch',
|
|
84
|
+
'studio_native_recovery_binding_invalid', 'studio_native_recovery_binding_missing',
|
|
85
|
+
'A2A_CONTROL_PERMISSION_DENIED', 'A2A_CONTROL_IDEMPOTENCY_CONFLICT', 'A2A_CALL_IDENTITY_CONFLICT', 'A2A_CALL_NOT_FOUND'].includes(error?.code);
|
|
86
|
+
transaction(() => {
|
|
87
|
+
if (row(found.command_id)?.owner_id !== owner) return;
|
|
88
|
+
db.prepare('UPDATE managed_scoped_controls SET state=?,owner_until=?,result=? WHERE command_id=? AND owner_id=?')
|
|
89
|
+
.run(permanent ? 'rejected' : 'queued', permanent ? 0 : clock() + 1000,
|
|
90
|
+
canonical({ error: permanent ? 'native_child_scope_unavailable' : 'native_scope_delivery_pending' }), found.command_id, owner);
|
|
91
|
+
if (permanent) append(found.session_id, [{ event_id: nativeKernelFactId(found.command_id, 'scoped-delivery-rejected'),
|
|
92
|
+
family: 'control', family_version: 1, event_type: 'control.command_rejected', run_id: found.run_id,
|
|
93
|
+
payload: { command_id: found.command_id, reason: 'native_child_scope_unavailable' } }], data.command);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
} finally {
|
|
97
|
+
clearInterval(timer); stop.abort(new Error('Scoped control attempt retired'));
|
|
98
|
+
if (!closed && !lifetime.signal.aborted) transaction(() => db.prepare('UPDATE managed_scoped_controls SET owner_id=NULL WHERE command_id=? AND owner_id=?')
|
|
99
|
+
.run(found.command_id, owner));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function drain() {
|
|
103
|
+
if (closed || !control) return;
|
|
104
|
+
guard();
|
|
105
|
+
for (const found of db.prepare("SELECT * FROM managed_scoped_controls WHERE state='queued' AND owner_until<=? ORDER BY rowid").all(clock())) {
|
|
106
|
+
if (work.has(found.command_id)) continue;
|
|
107
|
+
const claimed = transaction(() => db.prepare("UPDATE managed_scoped_controls SET owner_id=?,owner_until=? WHERE command_id=? AND state='queued' AND owner_until<=?")
|
|
108
|
+
.run(owner, clock() + 2000, found.command_id, clock()).changes);
|
|
109
|
+
if (!claimed) continue;
|
|
110
|
+
const task = deliver(found); work.set(found.command_id, task);
|
|
111
|
+
void task.finally(() => work.delete(found.command_id)).catch(() => {});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return Object.freeze({ prepare, admit, drain, supported: Boolean(control),
|
|
115
|
+
async close() { closed = true; await Promise.allSettled([...work.values()]); } });
|
|
116
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { canonical, invariant, parseNativeJson } from '@kingsoftcloud/agentkit-harness-core';
|
|
2
|
+
|
|
3
|
+
const pageLimit = 1024 ** 2;
|
|
4
|
+
const tailLimit = 3 * 1024 ** 2;
|
|
5
|
+
|
|
6
|
+
/** Freeze presentation in the same transaction as the public event cursor.
|
|
7
|
+
* A reconnect after an Engine upgrade can still read the identical frames. */
|
|
8
|
+
export function createManagedSessionFrames(db, projectEvent) {
|
|
9
|
+
const enabled = configuration => projectEvent && configuration?.hostRecoveryBinding?.sessionDelivery === true;
|
|
10
|
+
const last = db.prepare('SELECT COALESCE(MAX(seq),0) AS seq FROM managed_session_frames WHERE run_id=?');
|
|
11
|
+
const insert = db.prepare('INSERT INTO managed_session_frames (run_id, seq, data) VALUES (?,?,?)');
|
|
12
|
+
const page = db.prepare('SELECT data FROM managed_session_frames WHERE run_id=? AND seq>? ORDER BY seq LIMIT 128');
|
|
13
|
+
const tail = db.prepare('SELECT data FROM managed_session_frames WHERE run_id=? ORDER BY seq DESC LIMIT 2000');
|
|
14
|
+
|
|
15
|
+
function collect(rows, limit) {
|
|
16
|
+
const events = [];
|
|
17
|
+
let bytes = 0;
|
|
18
|
+
for (const { data } of rows) {
|
|
19
|
+
bytes += Buffer.byteLength(data) + 1;
|
|
20
|
+
if (bytes > limit) break;
|
|
21
|
+
events.push(parseNativeJson(data));
|
|
22
|
+
}
|
|
23
|
+
return events;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
sync(record) {
|
|
28
|
+
if (!enabled(record.configuration)) return;
|
|
29
|
+
const runId = record.snapshot.runId;
|
|
30
|
+
const cursor = last.get(runId).seq;
|
|
31
|
+
for (const event of record.events) {
|
|
32
|
+
if (event.seq <= cursor) continue;
|
|
33
|
+
const frame = projectEvent(event, record.configuration);
|
|
34
|
+
invariant(frame.seq === event.seq, 'NATIVE_KERNEL_FRAME_SEQUENCE_INVALID');
|
|
35
|
+
const data = canonical(frame);
|
|
36
|
+
invariant(Buffer.byteLength(data) < pageLimit, 'NATIVE_KERNEL_FRAME_TOO_LARGE');
|
|
37
|
+
insert.run(runId, event.seq, data);
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
read(runId, after) { return collect(page.iterate(runId, after), pageLimit); },
|
|
41
|
+
tail(runId) { return collect(tail.iterate(runId), tailLimit).reverse(); },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/** Durable Teams facts in the original managed command database. Registry
|
|
2
|
+
* records, nonces and callbacks are NOT execution authority. The trusted Host
|
|
3
|
+
* must verify current permits/grants and resolve policy at every actual use. */
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { canonical, copy, invariant, parseNativeJson } from '@kingsoftcloud/agentkit-harness-core';
|
|
6
|
+
import { validatePreparedTeamsContext, validateTeamsCallbackPermit, teamsSessionOwnerDigest } from './native-teams-context-contract.mjs';
|
|
7
|
+
|
|
8
|
+
export const MANAGED_NATIVE_TEAMS_CONTEXT_CONTRACT = 'agentkit.managed-native-teams-context/v1';
|
|
9
|
+
const identifier = value => typeof value === 'string' && value.length > 0 && value.length <= 512 && value === value.trim() && !value.includes('\0');
|
|
10
|
+
const revision = value => Number.isSafeInteger(value) && value >= 1;
|
|
11
|
+
const check = condition => invariant(condition, 'NATIVE_TEAMS_CONTEXT_CONFLICT');
|
|
12
|
+
|
|
13
|
+
export function createManagedNativeTeamsContexts({ db, guard, transaction, target, validateCommand } = {}) {
|
|
14
|
+
// A standalone metadata file cannot impersonate the original Kernel store.
|
|
15
|
+
db.prepare('SELECT command_id FROM managed_commands LIMIT 1').get();
|
|
16
|
+
guard(); db.exec('BEGIN IMMEDIATE');
|
|
17
|
+
try {
|
|
18
|
+
db.exec(`CREATE TABLE IF NOT EXISTS managed_teams_identity (id INTEGER PRIMARY KEY CHECK(id=1), incarnation TEXT NOT NULL);
|
|
19
|
+
CREATE TABLE IF NOT EXISTS managed_teams_extensions (name TEXT PRIMARY KEY, identity TEXT NOT NULL);
|
|
20
|
+
CREATE TABLE IF NOT EXISTS managed_teams_owners (session_id TEXT PRIMARY KEY, digest TEXT NOT NULL);
|
|
21
|
+
CREATE TABLE IF NOT EXISTS managed_teams_contexts (context_ref TEXT PRIMARY KEY, session_id TEXT NOT NULL,
|
|
22
|
+
command_id TEXT NOT NULL, idem TEXT NOT NULL, policy_ref TEXT UNIQUE NOT NULL, data TEXT NOT NULL,
|
|
23
|
+
UNIQUE(session_id,command_id), UNIQUE(session_id,idem));
|
|
24
|
+
CREATE TABLE IF NOT EXISTS managed_teams_callbacks (context_ref TEXT NOT NULL, revision INTEGER NOT NULL,
|
|
25
|
+
data TEXT NOT NULL, PRIMARY KEY(context_ref,revision));
|
|
26
|
+
CREATE TABLE IF NOT EXISTS managed_teams_nonces (nonce TEXT PRIMARY KEY, command_id TEXT NOT NULL, idem TEXT NOT NULL);`);
|
|
27
|
+
db.prepare('INSERT OR IGNORE INTO managed_teams_identity VALUES (1,?)').run(randomUUID());
|
|
28
|
+
guard(); db.exec('COMMIT');
|
|
29
|
+
} catch (error) { db.exec('ROLLBACK'); throw error; }
|
|
30
|
+
const initial = db.prepare('SELECT incarnation FROM managed_teams_identity WHERE id=1').get()?.incarnation;
|
|
31
|
+
invariant(identifier(initial), 'NATIVE_TEAMS_STORE_IDENTITY_MISMATCH');
|
|
32
|
+
function identity(expected) {
|
|
33
|
+
guard();
|
|
34
|
+
invariant(identifier(expected) && expected === initial
|
|
35
|
+
&& db.prepare('SELECT incarnation FROM managed_teams_identity WHERE id=1').get()?.incarnation === initial,
|
|
36
|
+
'NATIVE_TEAMS_STORE_IDENTITY_MISMATCH');
|
|
37
|
+
return initial;
|
|
38
|
+
}
|
|
39
|
+
function context(ref) {
|
|
40
|
+
const row = db.prepare('SELECT * FROM managed_teams_contexts WHERE context_ref=?').get(ref);
|
|
41
|
+
if (!row) return null;
|
|
42
|
+
const prepared = validatePreparedTeamsContext(parseNativeJson(row.data), { target, validateCommand });
|
|
43
|
+
invariant(prepared.context_ref === ref && prepared.ref.sessionId === row.session_id && prepared.ref.commandId === row.command_id
|
|
44
|
+
&& prepared.ref.idempotencyKey === row.idem && prepared.policy_ref === row.policy_ref, 'NATIVE_TEAMS_STORE_IDENTITY_MISMATCH');
|
|
45
|
+
invariant(db.prepare('SELECT digest FROM managed_teams_owners WHERE session_id=?').get(prepared.ref.sessionId)?.digest
|
|
46
|
+
=== teamsSessionOwnerDigest(prepared), 'NATIVE_TEAMS_STORE_IDENTITY_MISMATCH');
|
|
47
|
+
return prepared;
|
|
48
|
+
}
|
|
49
|
+
const api = Object.freeze({ contract: MANAGED_NATIVE_TEAMS_CONTEXT_CONTRACT,
|
|
50
|
+
durable: true, sharedAcrossHosts: false,
|
|
51
|
+
incarnation() { return transaction(() => identity(initial)); },
|
|
52
|
+
ownsSession(sessionId) {
|
|
53
|
+
check(identifier(sessionId)); return transaction(() => { identity(initial);
|
|
54
|
+
return Boolean(db.prepare('SELECT 1 FROM managed_teams_owners WHERE session_id=?').get(sessionId)); });
|
|
55
|
+
},
|
|
56
|
+
put(raw, { expectedIncarnation } = {}) {
|
|
57
|
+
const prepared = validatePreparedTeamsContext(raw, { target, validateCommand }), body = canonical(prepared);
|
|
58
|
+
return transaction(() => {
|
|
59
|
+
identity(expectedIncarnation);
|
|
60
|
+
const ownerDigest = teamsSessionOwnerDigest(prepared);
|
|
61
|
+
// A prepared context cannot take over a Session which already contains
|
|
62
|
+
// ordinary managed work. Product Session ownership is checked again by
|
|
63
|
+
// the eventual trusted ingress/policy composition, never inferred here.
|
|
64
|
+
const ordinary = db.prepare('SELECT data FROM managed_commands WHERE session_id=?').all(prepared.ref.sessionId)
|
|
65
|
+
.some(row => parseNativeJson(row.data).payload.teams_context_ref == null);
|
|
66
|
+
check(!ordinary);
|
|
67
|
+
db.prepare('INSERT OR IGNORE INTO managed_teams_owners VALUES (?,?)').run(prepared.ref.sessionId, ownerDigest);
|
|
68
|
+
check(db.prepare('SELECT digest FROM managed_teams_owners WHERE session_id=?').get(prepared.ref.sessionId)?.digest === ownerDigest);
|
|
69
|
+
db.prepare('INSERT OR IGNORE INTO managed_teams_contexts VALUES (?,?,?,?,?,?)')
|
|
70
|
+
.run(prepared.context_ref, prepared.ref.sessionId, prepared.ref.commandId, prepared.ref.idempotencyKey, prepared.policy_ref, body);
|
|
71
|
+
check(db.prepare('SELECT data FROM managed_teams_contexts WHERE context_ref=?').get(prepared.context_ref)?.data === body);
|
|
72
|
+
});
|
|
73
|
+
},
|
|
74
|
+
get(ref, { expectedIncarnation } = {}) {
|
|
75
|
+
check(identifier(ref)); return transaction(() => { identity(expectedIncarnation); return context(ref); });
|
|
76
|
+
},
|
|
77
|
+
extensionIdentity(name, { expectedIncarnation } = {}) {
|
|
78
|
+
check(identifier(name)); return transaction(() => { identity(expectedIncarnation);
|
|
79
|
+
return db.prepare('SELECT identity FROM managed_teams_extensions WHERE name=?').get(name)?.identity ?? null; });
|
|
80
|
+
},
|
|
81
|
+
bindExtensionIdentity(name, value, { expectedIncarnation } = {}) {
|
|
82
|
+
check(identifier(name) && typeof value === 'string' && value.length > 0 && value.length <= 4096 && !value.includes('\0'));
|
|
83
|
+
return transaction(() => {
|
|
84
|
+
identity(expectedIncarnation);
|
|
85
|
+
db.prepare('INSERT OR IGNORE INTO managed_teams_extensions VALUES (?,?)').run(name, value);
|
|
86
|
+
invariant(db.prepare('SELECT identity FROM managed_teams_extensions WHERE name=?').get(name)?.identity === value,
|
|
87
|
+
'NATIVE_TEAMS_STORE_IDENTITY_MISMATCH');
|
|
88
|
+
});
|
|
89
|
+
},
|
|
90
|
+
registerNonce(nonce, commandId, idempotencyKey, { expectedIncarnation } = {}) {
|
|
91
|
+
check(identifier(nonce) && identifier(commandId) && identifier(idempotencyKey));
|
|
92
|
+
return transaction(() => {
|
|
93
|
+
identity(expectedIncarnation);
|
|
94
|
+
db.prepare('INSERT OR IGNORE INTO managed_teams_nonces VALUES (?,?,?)').run(nonce, commandId, idempotencyKey);
|
|
95
|
+
const row = db.prepare('SELECT * FROM managed_teams_nonces WHERE nonce=?').get(nonce);
|
|
96
|
+
return row.command_id === commandId && row.idem === idempotencyKey;
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
putCallback(ref, raw, { expectedIncarnation } = {}) {
|
|
100
|
+
check(identifier(ref)); const permit = validateTeamsCallbackPermit(raw);
|
|
101
|
+
return transaction(() => {
|
|
102
|
+
identity(expectedIncarnation); const prepared = context(ref); check(prepared);
|
|
103
|
+
// This detects cross-context storage errors, not signature authority.
|
|
104
|
+
check(['groupId', 'teamRunId', 'memberId', 'commandId', 'sessionId', 'attemptEpoch', 'leaderEpoch', 'bundleDigest']
|
|
105
|
+
.every(key => permit[key] === prepared.ref[key])
|
|
106
|
+
&& permit.agentInstanceId === prepared.command.agent_instance_id && permit.policyDigest === prepared.policy_digest
|
|
107
|
+
&& permit.authorityId === prepared.ref.authorityId);
|
|
108
|
+
const previous = db.prepare('SELECT data FROM managed_teams_callbacks WHERE context_ref=? AND revision=?').get(ref, permit.grantRevision);
|
|
109
|
+
if (previous && Date.parse(validateTeamsCallbackPermit(parseNativeJson(previous.data)).expiresAt) >= Date.parse(permit.expiresAt)) return;
|
|
110
|
+
db.prepare('INSERT INTO managed_teams_callbacks VALUES (?,?,?) ON CONFLICT(context_ref,revision) DO UPDATE SET data=excluded.data')
|
|
111
|
+
.run(ref, permit.grantRevision, canonical(permit));
|
|
112
|
+
});
|
|
113
|
+
},
|
|
114
|
+
getCallback(ref, grantRevision, { expectedIncarnation } = {}) {
|
|
115
|
+
check(identifier(ref) && revision(grantRevision)); return transaction(() => {
|
|
116
|
+
identity(expectedIncarnation);
|
|
117
|
+
const row = db.prepare('SELECT data FROM managed_teams_callbacks WHERE context_ref=? AND revision=?').get(ref, grantRevision);
|
|
118
|
+
return row ? copy(validateTeamsCallbackPermit(parseNativeJson(row.data))) : null;
|
|
119
|
+
});
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
return { api,
|
|
123
|
+
// Used inside the admission transaction, never by the model or public HTTP.
|
|
124
|
+
reserved(sessionId) { identity(initial); return Boolean(db.prepare('SELECT 1 FROM managed_teams_owners WHERE session_id=?').get(sessionId)); },
|
|
125
|
+
};
|
|
126
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/** Trusted Host callback authorization. A registry record is deliberately
|
|
2
|
+
* insufficient: every use checks the live original grant and Server signature.
|
|
3
|
+
* No signing key, request-supplied key, endpoint or public management API. */
|
|
4
|
+
import { createPublicKey, verify as verifySignature } from 'node:crypto';
|
|
5
|
+
import { canonical, copy, invariant } from '@kingsoftcloud/agentkit-harness-core';
|
|
6
|
+
import { validateTeamsCallbackPermit } from './native-teams-context-contract.mjs';
|
|
7
|
+
import { canonicalTeamsJson } from './native-teams-json.mjs';
|
|
8
|
+
|
|
9
|
+
export const NATIVE_TEAMS_CALLBACK_AUTHORITY_CONTRACT = 'agentkit.native-teams-callback-authority/v1';
|
|
10
|
+
const code = 'NATIVE_TEAMS_CALLBACK_UNAUTHORIZED';
|
|
11
|
+
const check = condition => invariant(condition, code);
|
|
12
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
13
|
+
const required = ['authorityId', 'agentInstanceId', 'sessionId', 'commandId', 'policyDigest', 'attemptEpoch', 'grantRevision',
|
|
14
|
+
'groupId', 'teamRunId', 'memberId', 'bundleDigest', 'leaderEpoch'];
|
|
15
|
+
|
|
16
|
+
export function nativeTeamsCallbackPermitBytes(raw) {
|
|
17
|
+
const permit = validateTeamsCallbackPermit(raw); delete permit.signature;
|
|
18
|
+
// Teams uses RFC8785 / UTF16 key order, unlike legacy AgentControl permits.
|
|
19
|
+
return Buffer.from(canonicalTeamsJson(permit));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createNativeTeamsCallbackPermitVerifier({ verificationKeys, issuer, clock = Date.now } = {}) {
|
|
23
|
+
check(typeof verificationKeys === 'function' && typeof issuer === 'string' && issuer.length > 0 && typeof clock === 'function');
|
|
24
|
+
return Object.freeze({ async verify(raw, { operation, expected, grantExpiresAt } = {}) {
|
|
25
|
+
try {
|
|
26
|
+
// The caller and rotating key source may be asynchronous. Freeze exactly
|
|
27
|
+
// the claims being authenticated before yielding to either of them.
|
|
28
|
+
const permit = validateTeamsCallbackPermit(raw), scope = copy(expected);
|
|
29
|
+
check(object(scope) && required.every(key => Object.hasOwn(scope, key)) && permit.issuer === issuer
|
|
30
|
+
&& typeof operation === 'string' && permit.allowedOperations.includes(operation)
|
|
31
|
+
&& Object.entries(scope).every(([key, value]) => Object.hasOwn(permit, key) && canonical(permit[key]) === canonical(value)));
|
|
32
|
+
const deadline = grantExpiresAt === null ? null : Date.parse(grantExpiresAt);
|
|
33
|
+
if (permit.permitKind === 'execute') check(typeof grantExpiresAt === 'string' && Number.isFinite(deadline)
|
|
34
|
+
&& Date.parse(permit.expiresAt) <= deadline);
|
|
35
|
+
const keys = await verificationKeys(), pem = keys instanceof Map ? keys.get(permit.kid)
|
|
36
|
+
: object(keys) && Object.hasOwn(keys, permit.kid) ? keys[permit.kid] : null;
|
|
37
|
+
check(typeof pem === 'string' && Buffer.byteLength(pem) <= 64 * 1024);
|
|
38
|
+
const publicKey = createPublicKey(pem), signature = Buffer.from(permit.signature, 'base64url');
|
|
39
|
+
check(publicKey.asymmetricKeyType === 'ed25519' && signature.length === 64 && signature.toString('base64url') === permit.signature
|
|
40
|
+
&& verifySignature(null, nativeTeamsCallbackPermitBytes(permit), publicKey, signature));
|
|
41
|
+
const now = clock(); check(Number.isSafeInteger(now) && Date.parse(permit.issuedAt) <= now && now < Date.parse(permit.expiresAt)
|
|
42
|
+
&& (permit.permitKind !== 'execute' || now < deadline));
|
|
43
|
+
return permit;
|
|
44
|
+
} catch { invariant(false, code); }
|
|
45
|
+
} });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function createNativeTeamsCallbackAuthority({ contexts, executionGrants, verifier, expectedIncarnation } = {}) {
|
|
49
|
+
check(contexts?.contract === 'agentkit.managed-native-teams-context/v1'
|
|
50
|
+
&& executionGrants?.contract === 'agentkit.managed-native-execution-grants/v1' && typeof verifier?.verify === 'function'
|
|
51
|
+
&& typeof expectedIncarnation === 'string' && contexts.incarnation() === expectedIncarnation);
|
|
52
|
+
const opts = Object.freeze({ expectedIncarnation });
|
|
53
|
+
function expected(context, grant) {
|
|
54
|
+
return { authorityId: context.ref.authorityId, agentInstanceId: context.grant.agent_instance_id,
|
|
55
|
+
sessionId: context.ref.sessionId, commandId: context.ref.commandId, policyDigest: context.policy_digest,
|
|
56
|
+
attemptEpoch: context.ref.attemptEpoch, grantRevision: grant.revision, groupId: context.ref.groupId,
|
|
57
|
+
teamRunId: context.ref.teamRunId, memberId: context.ref.memberId, bundleDigest: context.ref.bundleDigest, leaderEpoch: context.ref.leaderEpoch };
|
|
58
|
+
}
|
|
59
|
+
return Object.freeze({ contract: NATIVE_TEAMS_CALLBACK_AUTHORITY_CONTRACT,
|
|
60
|
+
async authorize(contextRef, operation) {
|
|
61
|
+
const context = contexts.get(contextRef, opts); check(context);
|
|
62
|
+
const grant = executionGrants.require(context.grant), permit = contexts.getCallback(contextRef, grant.revision, opts);
|
|
63
|
+
check(permit && permit.permitKind === 'execute');
|
|
64
|
+
const verified = await verifier.verify(permit, { operation, expected: expected(context, grant), grantExpiresAt: grant.expires_at });
|
|
65
|
+
// Key refresh must never hide revocation, suspension, store replacement
|
|
66
|
+
// or a new grant revision that committed while verification was awaiting.
|
|
67
|
+
const current = executionGrants.require(context.grant), original = contexts.get(contextRef, opts);
|
|
68
|
+
check(current.revision === grant.revision && canonical(original) === canonical(context)
|
|
69
|
+
&& canonical(verified) === canonical(permit));
|
|
70
|
+
return { context: copy(original), grant: copy(current), permit: copy(verified) };
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// Bounded standalone wire-validation adapter for Teams host context facts.
|
|
2
|
+
//
|
|
3
|
+
// This module only validates and copies JSON wire data. It never authorizes,
|
|
4
|
+
// verifies signatures, touches the database, or interprets records as
|
|
5
|
+
// executable tools or permissions. The Host must independently verify the
|
|
6
|
+
// callback signature, the live grant, the current attempt, and the persisted
|
|
7
|
+
// operation on every use. See ksadk/kernel/teams_execution_context.py,
|
|
8
|
+
// ksadk/plugins/teams/cloud_contracts.py and cloud_permits.py for the source
|
|
9
|
+
// of truth. Teams transport uses its own RFC8785 codec; no compatibility
|
|
10
|
+
// with old Python database serialization is required.
|
|
11
|
+
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { invariant } from '@kingsoftcloud/agentkit-harness-core';
|
|
14
|
+
import { canonicalTeamsJson, copyTeamsJson as copy } from './native-teams-json.mjs';
|
|
15
|
+
|
|
16
|
+
const CONTEXT_INVALID = 'NATIVE_TEAMS_CONTEXT_INVALID';
|
|
17
|
+
const CONTEXT_CONFLICT = 'NATIVE_TEAMS_CONTEXT_CONFLICT';
|
|
18
|
+
const CALLBACK_INVALID = 'NATIVE_TEAMS_CALLBACK_INVALID';
|
|
19
|
+
|
|
20
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
21
|
+
const DIGEST_RE = /^sha256:[0-9a-f]{64}$/;
|
|
22
|
+
const TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
23
|
+
const BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
|
|
24
|
+
|
|
25
|
+
function isPlainObject(v) {
|
|
26
|
+
return typeof v === 'object' && v !== null &&
|
|
27
|
+
(Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
|
|
28
|
+
}
|
|
29
|
+
function isOpaqueId(v) {
|
|
30
|
+
return typeof v === 'string' && v.length >= 1 && v.length <= 256 && /^[^\s\0]+$/.test(v);
|
|
31
|
+
}
|
|
32
|
+
const isOperationKey = v => typeof v === 'string' && v.length >= 1 && v.length <= 200 && v.trim().length > 0 && !v.includes('\0');
|
|
33
|
+
function isDigest(v) { return typeof v === 'string' && DIGEST_RE.test(v); }
|
|
34
|
+
function isUuid(v) { return typeof v === 'string' && UUID_RE.test(v); }
|
|
35
|
+
function isPositiveSafeInt(v) { return Number.isSafeInteger(v) && v >= 1; }
|
|
36
|
+
function isTimestamp(v) {
|
|
37
|
+
return typeof v === 'string' && TIMESTAMP_RE.test(v) && Number.isFinite(Date.parse(v)) && new Date(v).toISOString() === v;
|
|
38
|
+
}
|
|
39
|
+
function isBase64url(v) { return typeof v === 'string' && BASE64URL_RE.test(v); }
|
|
40
|
+
function reject(code) { invariant(false, code); }
|
|
41
|
+
function noUnknownKeys(obj, allowed, code) {
|
|
42
|
+
for (const k of Object.keys(obj)) invariant(allowed.includes(k), code);
|
|
43
|
+
}
|
|
44
|
+
function requireKeys(obj, keys, code) {
|
|
45
|
+
for (const k of keys) invariant(k in obj, code);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function teamsContextDigest(value) {
|
|
49
|
+
return 'sha256:' + createHash('sha256').update(canonicalTeamsJson(value)).digest('hex');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function teamsSessionOwnerDigest(prepared) {
|
|
53
|
+
invariant(isPlainObject(prepared), CONTEXT_INVALID);
|
|
54
|
+
invariant(isPlainObject(prepared.grant), CONTEXT_INVALID);
|
|
55
|
+
invariant(isPlainObject(prepared.ref), CONTEXT_INVALID);
|
|
56
|
+
invariant(typeof prepared.grant.tenant_id === 'string' && prepared.grant.tenant_id.length > 0, CONTEXT_INVALID);
|
|
57
|
+
invariant(typeof prepared.owner_subject === 'string' && prepared.owner_subject.length > 0, CONTEXT_INVALID);
|
|
58
|
+
invariant(typeof prepared.ref.authorityId === 'string' && prepared.ref.authorityId.length > 0, CONTEXT_INVALID);
|
|
59
|
+
invariant(typeof prepared.ref.groupId === 'string' && prepared.ref.groupId.length > 0, CONTEXT_INVALID);
|
|
60
|
+
invariant(typeof prepared.ref.teamRunId === 'string' && prepared.ref.teamRunId.length > 0, CONTEXT_INVALID);
|
|
61
|
+
invariant(typeof prepared.ref.runMemberId === 'string' && prepared.ref.runMemberId.length > 0, CONTEXT_INVALID);
|
|
62
|
+
invariant(typeof prepared.ref.bindingRef === 'string' && prepared.ref.bindingRef.length > 0, CONTEXT_INVALID);
|
|
63
|
+
invariant(typeof prepared.grant.agent_instance_id === 'string' && prepared.grant.agent_instance_id.length > 0, CONTEXT_INVALID);
|
|
64
|
+
return teamsContextDigest({
|
|
65
|
+
tenant: prepared.grant.tenant_id,
|
|
66
|
+
owner: prepared.owner_subject,
|
|
67
|
+
authority: prepared.ref.authorityId,
|
|
68
|
+
group: prepared.ref.groupId,
|
|
69
|
+
teamRun: prepared.ref.teamRunId,
|
|
70
|
+
member: prepared.ref.runMemberId,
|
|
71
|
+
binding: prepared.ref.bindingRef,
|
|
72
|
+
instance: prepared.grant.agent_instance_id,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const REF_KEYS = ['authorityId','groupId','teamRunId','memberId','runMemberId','taskId','attemptId','deliveryId','bindingRef','providerRef','sessionId','commandId','idempotencyKey','schedulerEpoch','leaderEpoch','dispatchEpoch','attemptEpoch','target','bundleDigest','contractDigest','capabilitiesDigest','nativeRunId'];
|
|
77
|
+
const REF_REQUIRED = ['authorityId','groupId','teamRunId','memberId','runMemberId','attemptId','deliveryId','bindingRef','providerRef','sessionId','commandId','idempotencyKey','schedulerEpoch','leaderEpoch','dispatchEpoch','attemptEpoch','target','bundleDigest','contractDigest','capabilitiesDigest'];
|
|
78
|
+
const REF_ID_KEYS = ['authorityId','groupId','teamRunId','memberId','runMemberId','attemptId','deliveryId','bindingRef','providerRef','sessionId'];
|
|
79
|
+
const REF_EPOCH_KEYS = ['schedulerEpoch','leaderEpoch','dispatchEpoch','attemptEpoch'];
|
|
80
|
+
const REF_DIGEST_KEYS = ['bundleDigest','contractDigest','capabilitiesDigest'];
|
|
81
|
+
|
|
82
|
+
function validateTarget(target) {
|
|
83
|
+
invariant(isPlainObject(target), CONTEXT_INVALID);
|
|
84
|
+
invariant(target.kind === 'node' || target.kind === 'cloud_agent', CONTEXT_INVALID);
|
|
85
|
+
if (target.kind === 'node') {
|
|
86
|
+
noUnknownKeys(target, ['kind','nodeId','nodeGeneration'], CONTEXT_INVALID);
|
|
87
|
+
requireKeys(target, ['nodeId','nodeGeneration'], CONTEXT_INVALID);
|
|
88
|
+
invariant(isOpaqueId(target.nodeId), CONTEXT_INVALID);
|
|
89
|
+
invariant(isPositiveSafeInt(target.nodeGeneration), CONTEXT_INVALID);
|
|
90
|
+
return { kind: 'node', nodeId: target.nodeId, nodeGeneration: target.nodeGeneration };
|
|
91
|
+
}
|
|
92
|
+
noUnknownKeys(target, ['kind','agentId','versionId','runtimeId','agentInstanceId'], CONTEXT_INVALID);
|
|
93
|
+
requireKeys(target, ['agentId','versionId','runtimeId','agentInstanceId'], CONTEXT_INVALID);
|
|
94
|
+
for (const k of ['agentId','versionId','runtimeId','agentInstanceId']) invariant(isOpaqueId(target[k]), CONTEXT_INVALID);
|
|
95
|
+
return { kind: 'cloud_agent', agentId: target.agentId, versionId: target.versionId, runtimeId: target.runtimeId, agentInstanceId: target.agentInstanceId };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function validateRef(ref) {
|
|
99
|
+
invariant(isPlainObject(ref), CONTEXT_INVALID);
|
|
100
|
+
noUnknownKeys(ref, REF_KEYS, CONTEXT_INVALID);
|
|
101
|
+
requireKeys(ref, REF_REQUIRED, CONTEXT_INVALID);
|
|
102
|
+
for (const k of REF_ID_KEYS) invariant(isOpaqueId(ref[k]), CONTEXT_INVALID);
|
|
103
|
+
invariant(isOperationKey(ref.idempotencyKey), CONTEXT_INVALID);
|
|
104
|
+
invariant(isUuid(ref.commandId), CONTEXT_INVALID);
|
|
105
|
+
for (const k of REF_EPOCH_KEYS) invariant(isPositiveSafeInt(ref[k]), CONTEXT_INVALID);
|
|
106
|
+
for (const k of REF_DIGEST_KEYS) invariant(isDigest(ref[k]), CONTEXT_INVALID);
|
|
107
|
+
const taskId = ref.taskId === undefined || ref.taskId === null ? null : ref.taskId;
|
|
108
|
+
invariant(taskId === null || isOpaqueId(taskId), CONTEXT_INVALID);
|
|
109
|
+
const nativeRunId = ref.nativeRunId === undefined || ref.nativeRunId === null ? null : ref.nativeRunId;
|
|
110
|
+
invariant(nativeRunId === null || isOpaqueId(nativeRunId), CONTEXT_INVALID);
|
|
111
|
+
const target = validateTarget(ref.target);
|
|
112
|
+
return {
|
|
113
|
+
authorityId: ref.authorityId, groupId: ref.groupId, teamRunId: ref.teamRunId,
|
|
114
|
+
memberId: ref.memberId, runMemberId: ref.runMemberId, taskId,
|
|
115
|
+
attemptId: ref.attemptId, deliveryId: ref.deliveryId, bindingRef: ref.bindingRef,
|
|
116
|
+
providerRef: ref.providerRef, sessionId: ref.sessionId, commandId: ref.commandId,
|
|
117
|
+
idempotencyKey: ref.idempotencyKey, schedulerEpoch: ref.schedulerEpoch,
|
|
118
|
+
leaderEpoch: ref.leaderEpoch, dispatchEpoch: ref.dispatchEpoch,
|
|
119
|
+
attemptEpoch: ref.attemptEpoch, target, bundleDigest: ref.bundleDigest,
|
|
120
|
+
contractDigest: ref.contractDigest, capabilitiesDigest: ref.capabilitiesDigest,
|
|
121
|
+
nativeRunId,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const GRANT_KEYS = ['grant_id','tenant_id','session_id','agent_instance_id','owner_ref','attempt_epoch'];
|
|
126
|
+
const GRANT_ID_KEYS = ['grant_id','tenant_id','session_id','agent_instance_id','owner_ref'];
|
|
127
|
+
|
|
128
|
+
function validateGrant(grant) {
|
|
129
|
+
invariant(isPlainObject(grant), CONTEXT_INVALID);
|
|
130
|
+
noUnknownKeys(grant, GRANT_KEYS, CONTEXT_INVALID);
|
|
131
|
+
requireKeys(grant, GRANT_KEYS, CONTEXT_INVALID);
|
|
132
|
+
for (const k of GRANT_ID_KEYS) invariant(isOpaqueId(grant[k]), CONTEXT_INVALID);
|
|
133
|
+
invariant(isPositiveSafeInt(grant.attempt_epoch), CONTEXT_INVALID);
|
|
134
|
+
return {
|
|
135
|
+
grant_id: grant.grant_id, tenant_id: grant.tenant_id, session_id: grant.session_id,
|
|
136
|
+
agent_instance_id: grant.agent_instance_id, owner_ref: grant.owner_ref,
|
|
137
|
+
attempt_epoch: grant.attempt_epoch,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function validateCommandLocal(command) {
|
|
142
|
+
invariant(isPlainObject(command), CONTEXT_INVALID);
|
|
143
|
+
invariant(command.schema_version === 1 && isOpaqueId(command.authorization_ref) && isTimestamp(command.submitted_at), CONTEXT_INVALID);
|
|
144
|
+
invariant(isPlainObject(command.source) && ['studio', 'responses', 'agui', 'a2a', 'parent_agent', 'scheduler', 'workflow', 'channel', 'system']
|
|
145
|
+
.includes(command.source.kind) && typeof command.source.ref === 'string', CONTEXT_INVALID);
|
|
146
|
+
invariant(typeof command.command_type === 'string', CONTEXT_INVALID);
|
|
147
|
+
invariant(isUuid(command.command_id), CONTEXT_INVALID);
|
|
148
|
+
invariant(isOpaqueId(command.session_id), CONTEXT_INVALID);
|
|
149
|
+
invariant(isOperationKey(command.idempotency_key), CONTEXT_INVALID);
|
|
150
|
+
invariant(isOpaqueId(command.agent_instance_id), CONTEXT_INVALID);
|
|
151
|
+
invariant(isOpaqueId(command.tenant_id), CONTEXT_INVALID);
|
|
152
|
+
invariant(isPlainObject(command.payload), CONTEXT_INVALID);
|
|
153
|
+
invariant(Object.hasOwn(command.payload, 'content'), CONTEXT_INVALID);
|
|
154
|
+
invariant(isOpaqueId(command.payload.execution_grant_id), CONTEXT_INVALID);
|
|
155
|
+
invariant(isPositiveSafeInt(command.payload.execution_grant_attempt_epoch), CONTEXT_INVALID);
|
|
156
|
+
invariant(isOpaqueId(command.payload.execution_policy_ref), CONTEXT_INVALID);
|
|
157
|
+
invariant(isOpaqueId(command.payload.teams_context_ref), CONTEXT_INVALID);
|
|
158
|
+
return command;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const TOP_KEYS = ['context_ref','context_digest','policy_ref','policy_digest','owner_subject','ref','grant','command','context','material_manifest_ref','material_manifest_digest'];
|
|
162
|
+
const TOP_REQUIRED = ['context_ref','context_digest','policy_ref','policy_digest','owner_subject','ref','grant','command'];
|
|
163
|
+
|
|
164
|
+
export function validatePreparedTeamsContext(raw, opts = {}) {
|
|
165
|
+
try { raw = copy(raw); } catch { reject(CONTEXT_INVALID); }
|
|
166
|
+
const options = opts || {};
|
|
167
|
+
const trustedTarget = options.target;
|
|
168
|
+
const validateCommand = options.validateCommand;
|
|
169
|
+
invariant(isPlainObject(raw), CONTEXT_INVALID);
|
|
170
|
+
noUnknownKeys(raw, TOP_KEYS, CONTEXT_INVALID);
|
|
171
|
+
requireKeys(raw, TOP_REQUIRED, CONTEXT_INVALID);
|
|
172
|
+
invariant(isOpaqueId(raw.context_ref), CONTEXT_INVALID);
|
|
173
|
+
invariant(isDigest(raw.context_digest), CONTEXT_INVALID);
|
|
174
|
+
invariant(isOpaqueId(raw.policy_ref), CONTEXT_INVALID);
|
|
175
|
+
invariant(isDigest(raw.policy_digest), CONTEXT_INVALID);
|
|
176
|
+
invariant(isOpaqueId(raw.owner_subject), CONTEXT_INVALID);
|
|
177
|
+
const ref = validateRef(raw.ref);
|
|
178
|
+
const grant = validateGrant(raw.grant);
|
|
179
|
+
const context = raw.context === undefined ? {} : raw.context;
|
|
180
|
+
invariant(isPlainObject(context), CONTEXT_INVALID);
|
|
181
|
+
const materialRef = raw.material_manifest_ref === undefined || raw.material_manifest_ref === null ? null : raw.material_manifest_ref;
|
|
182
|
+
const materialDigest = raw.material_manifest_digest === undefined || raw.material_manifest_digest === null ? null : raw.material_manifest_digest;
|
|
183
|
+
invariant((materialRef === null) === (materialDigest === null), CONTEXT_INVALID);
|
|
184
|
+
invariant(materialRef === null || isOpaqueId(materialRef), CONTEXT_INVALID);
|
|
185
|
+
invariant(materialDigest === null || isDigest(materialDigest), CONTEXT_INVALID);
|
|
186
|
+
let command = validateCommandLocal(raw.command);
|
|
187
|
+
if (typeof validateCommand === 'function') {
|
|
188
|
+
command = validateCommand(command);
|
|
189
|
+
invariant(isPlainObject(command), CONTEXT_INVALID);
|
|
190
|
+
invariant(isPlainObject(command.payload), CONTEXT_INVALID);
|
|
191
|
+
validateCommandLocal(command);
|
|
192
|
+
}
|
|
193
|
+
invariant(typeof command.command_type === 'string', CONTEXT_INVALID);
|
|
194
|
+
invariant(command.command_type === 'enqueue', CONTEXT_CONFLICT);
|
|
195
|
+
invariant(command.command_id === ref.commandId, CONTEXT_CONFLICT);
|
|
196
|
+
invariant(command.session_id === ref.sessionId, CONTEXT_CONFLICT);
|
|
197
|
+
invariant(command.idempotency_key === ref.idempotencyKey, CONTEXT_CONFLICT);
|
|
198
|
+
invariant(grant.agent_instance_id === command.agent_instance_id, CONTEXT_CONFLICT);
|
|
199
|
+
invariant(grant.session_id === command.session_id, CONTEXT_CONFLICT);
|
|
200
|
+
invariant(grant.tenant_id === command.tenant_id, CONTEXT_CONFLICT);
|
|
201
|
+
invariant(grant.attempt_epoch === ref.attemptEpoch, CONTEXT_CONFLICT);
|
|
202
|
+
invariant(command.payload.execution_grant_id === grant.grant_id, CONTEXT_CONFLICT);
|
|
203
|
+
invariant(command.payload.execution_grant_attempt_epoch === ref.attemptEpoch, CONTEXT_CONFLICT);
|
|
204
|
+
invariant(command.payload.execution_policy_ref === raw.policy_ref, CONTEXT_CONFLICT);
|
|
205
|
+
invariant(command.payload.teams_context_ref === raw.context_ref, CONTEXT_CONFLICT);
|
|
206
|
+
if (ref.target.kind === 'cloud_agent') {
|
|
207
|
+
invariant(ref.target.agentInstanceId === command.agent_instance_id, CONTEXT_CONFLICT);
|
|
208
|
+
}
|
|
209
|
+
let computedContextDigest = null;
|
|
210
|
+
try { computedContextDigest = teamsContextDigest(context); }
|
|
211
|
+
catch { reject(CONTEXT_INVALID); }
|
|
212
|
+
invariant(raw.context_digest === computedContextDigest, CONTEXT_CONFLICT);
|
|
213
|
+
if (trustedTarget !== undefined && trustedTarget !== null) {
|
|
214
|
+
invariant(isPlainObject(trustedTarget), CONTEXT_INVALID);
|
|
215
|
+
invariant(typeof trustedTarget.tenantId === 'string' && trustedTarget.tenantId.length > 0, CONTEXT_INVALID);
|
|
216
|
+
invariant(typeof trustedTarget.agentInstanceId === 'string' && trustedTarget.agentInstanceId.length > 0, CONTEXT_INVALID);
|
|
217
|
+
invariant(grant.tenant_id === trustedTarget.tenantId, CONTEXT_CONFLICT);
|
|
218
|
+
invariant(grant.agent_instance_id === trustedTarget.agentInstanceId, CONTEXT_CONFLICT);
|
|
219
|
+
}
|
|
220
|
+
const prepared = {
|
|
221
|
+
context_ref: raw.context_ref, context_digest: raw.context_digest,
|
|
222
|
+
policy_ref: raw.policy_ref, policy_digest: raw.policy_digest,
|
|
223
|
+
owner_subject: raw.owner_subject, ref, grant, command,
|
|
224
|
+
context, material_manifest_ref: materialRef, material_manifest_digest: materialDigest,
|
|
225
|
+
};
|
|
226
|
+
return copy(prepared);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const PERMIT_KEYS = ['schemaVersion','audience','permitKind','issuer','kid','authorityId','issuedAt','expiresAt','nonce','signature','groupId','teamRunId','memberId','commandId','sessionId','agentInstanceId','bundleDigest','policyDigest','attemptEpoch','leaderEpoch','grantRevision','allowedOperations'];
|
|
230
|
+
const PERMIT_ID_KEYS = ['issuer','kid','authorityId','nonce','groupId','teamRunId','memberId','sessionId','agentInstanceId'];
|
|
231
|
+
const PERMIT_EPOCH_KEYS = ['attemptEpoch','leaderEpoch','grantRevision'];
|
|
232
|
+
const EXECUTE_OPS = new Set(['policy','invoke','effects','read_material','create_artifact','upload_artifact','finalize_artifact']);
|
|
233
|
+
const RECOVERY_OPS = new Set(['append_effect_evidence']);
|
|
234
|
+
|
|
235
|
+
export function validateTeamsCallbackPermit(raw) {
|
|
236
|
+
try { raw = copy(raw); } catch { reject(CALLBACK_INVALID); }
|
|
237
|
+
invariant(isPlainObject(raw), CALLBACK_INVALID);
|
|
238
|
+
noUnknownKeys(raw, PERMIT_KEYS, CALLBACK_INVALID);
|
|
239
|
+
requireKeys(raw, PERMIT_KEYS, CALLBACK_INVALID);
|
|
240
|
+
invariant(raw.schemaVersion === 1, CALLBACK_INVALID);
|
|
241
|
+
invariant(raw.audience === 'agentengine-teams-callback', CALLBACK_INVALID);
|
|
242
|
+
invariant(raw.permitKind === 'execute' || raw.permitKind === 'recovery', CALLBACK_INVALID);
|
|
243
|
+
for (const k of PERMIT_ID_KEYS) invariant(isOpaqueId(raw[k]), CALLBACK_INVALID);
|
|
244
|
+
invariant(isUuid(raw.commandId), CALLBACK_INVALID);
|
|
245
|
+
for (const k of ['bundleDigest','policyDigest']) invariant(isDigest(raw[k]), CALLBACK_INVALID);
|
|
246
|
+
invariant(isTimestamp(raw.issuedAt), CALLBACK_INVALID);
|
|
247
|
+
invariant(isTimestamp(raw.expiresAt), CALLBACK_INVALID);
|
|
248
|
+
invariant(typeof raw.signature === 'string' && raw.signature.length >= 1 && raw.signature.length <= 128 && isBase64url(raw.signature), CALLBACK_INVALID);
|
|
249
|
+
for (const k of PERMIT_EPOCH_KEYS) invariant(isPositiveSafeInt(raw[k]), CALLBACK_INVALID);
|
|
250
|
+
const ttl = (Date.parse(raw.expiresAt) - Date.parse(raw.issuedAt)) / 1000;
|
|
251
|
+
invariant(ttl > 0 && ttl <= 30, CALLBACK_INVALID);
|
|
252
|
+
invariant(Array.isArray(raw.allowedOperations), CALLBACK_INVALID);
|
|
253
|
+
invariant(raw.allowedOperations.length >= 1 && raw.allowedOperations.length <= 8, CALLBACK_INVALID);
|
|
254
|
+
const allowedOps = raw.permitKind === 'execute' ? EXECUTE_OPS : RECOVERY_OPS;
|
|
255
|
+
for (const op of raw.allowedOperations) {
|
|
256
|
+
invariant(typeof op === 'string', CALLBACK_INVALID);
|
|
257
|
+
invariant(allowedOps.has(op), CALLBACK_INVALID);
|
|
258
|
+
}
|
|
259
|
+
invariant(new Set(raw.allowedOperations).size === raw.allowedOperations.length, CALLBACK_INVALID);
|
|
260
|
+
const permit = {
|
|
261
|
+
schemaVersion: raw.schemaVersion, audience: raw.audience, permitKind: raw.permitKind,
|
|
262
|
+
issuer: raw.issuer, kid: raw.kid, authorityId: raw.authorityId,
|
|
263
|
+
issuedAt: raw.issuedAt, expiresAt: raw.expiresAt, nonce: raw.nonce,
|
|
264
|
+
signature: raw.signature, groupId: raw.groupId, teamRunId: raw.teamRunId,
|
|
265
|
+
memberId: raw.memberId, commandId: raw.commandId, sessionId: raw.sessionId,
|
|
266
|
+
agentInstanceId: raw.agentInstanceId, bundleDigest: raw.bundleDigest,
|
|
267
|
+
policyDigest: raw.policyDigest, attemptEpoch: raw.attemptEpoch,
|
|
268
|
+
leaderEpoch: raw.leaderEpoch, grantRevision: raw.grantRevision,
|
|
269
|
+
allowedOperations: [...raw.allowedOperations],
|
|
270
|
+
};
|
|
271
|
+
return copy(permit);
|
|
272
|
+
}
|