@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,922 @@
|
|
|
1
|
+
import { createManagedNativeInjection } from './native-managed-injection.mjs';
|
|
2
|
+
/** Durable Server command receiver over the existing TypeScript NativeKernel.
|
|
3
|
+
* No DSH loop, local permit issuer or Python process is involved. Local SQLite
|
|
4
|
+
* is a single-machine store, not evidence of a shared hosted SQL deployment. */
|
|
5
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
9
|
+
import { NativeKernel, canonical, configure, copy, invariant, parseNativeJson, scopeKey, terminal } from '@kingsoftcloud/agentkit-harness-core';
|
|
10
|
+
import { SqliteRunStore } from './sqlite-store.mjs';
|
|
11
|
+
import { createNativeChildHistory } from './child-history.mjs';
|
|
12
|
+
import { privateDirectory, privateFile, createPrivate } from './local-command-state.mjs';
|
|
13
|
+
import { nativeKernelFactId, projectNativeKernelEvent } from './native-kernel-events.mjs';
|
|
14
|
+
import { nativePlatformToolApproval } from './native-kernel-permit.mjs';
|
|
15
|
+
import { createManagedSessionFrames } from './native-managed-session-frames.mjs';
|
|
16
|
+
import { createManagedNativeInteractions } from './native-managed-interaction.mjs';
|
|
17
|
+
import { createManagedNativeScopedControls } from './native-managed-scoped-control.mjs';
|
|
18
|
+
import { createManagedNativeExecutionGrants, managedExecutionGrantId } from './native-managed-execution-grants.mjs';
|
|
19
|
+
import { createManagedNativeTeamsContexts } from './native-managed-teams-context.mjs';
|
|
20
|
+
import { createNativeTeamsCallbackAuthority } from './native-teams-callback-authority.mjs';
|
|
21
|
+
|
|
22
|
+
export const MANAGED_NATIVE_KERNEL_CONTRACT = 'agentkit.managed-native-kernel/v1';
|
|
23
|
+
const hash = value => createHash('sha256').update(canonical(value)).digest('hex');
|
|
24
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
25
|
+
const text = value => typeof value === 'string' && value.trim() && value.length <= 4096 && !value.includes('\0');
|
|
26
|
+
const uuid = value => typeof value === 'string' && /^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/iu.test(value);
|
|
27
|
+
const sourceKinds = new Set(['studio', 'responses', 'agui', 'a2a', 'parent_agent', 'scheduler', 'workflow', 'channel', 'system']);
|
|
28
|
+
const supported = new Set(['enqueue', 'interrupt', 'pause', 'resume', 'steer', 'inject', 'submit_interaction']);
|
|
29
|
+
const check = condition => invariant(condition, 'NATIVE_KERNEL_COMMAND_INVALID');
|
|
30
|
+
const platformCapability = (supported, reason = 'native_control_unsupported') => supported
|
|
31
|
+
? { supported: true, mode: 'native', reason: null } : { supported: false, mode: 'unavailable', reason };
|
|
32
|
+
const platformRunState = phase => {
|
|
33
|
+
if (phase === 'discarded' || terminal(phase)) return null;
|
|
34
|
+
if (phase === 'created' || phase === 'pending') return 'pending';
|
|
35
|
+
if (phase === 'awaiting_interaction' || phase === 'awaiting_reconciliation') return 'waiting';
|
|
36
|
+
return phase === 'paused' ? 'paused' : 'running';
|
|
37
|
+
};
|
|
38
|
+
function commandView(value) {
|
|
39
|
+
const command = copy(value);
|
|
40
|
+
check(object(command) && command.schema_version === 1 && uuid(command.command_id) && text(command.idempotency_key)
|
|
41
|
+
&& text(command.tenant_id) && text(command.agent_instance_id) && text(command.session_id)
|
|
42
|
+
&& object(command.payload) && text(command.authorization_ref) && text(command.submitted_at)
|
|
43
|
+
&& Number.isFinite(Date.parse(command.submitted_at)) && object(command.source)
|
|
44
|
+
&& sourceKinds.has(command.source.kind) && typeof command.source.ref === 'string');
|
|
45
|
+
command.command_id = command.command_id.toLowerCase();
|
|
46
|
+
check(['enqueue', 'interrupt', 'pause', 'resume', 'steer', 'inject', 'submit_interaction'].includes(command.command_type));
|
|
47
|
+
if (command.command_type === 'enqueue') check(Object.hasOwn(command.payload, 'content'));
|
|
48
|
+
if (command.command_type === 'inject') check(Object.keys(command.payload).sort().join(',') === 'content' && typeof command.payload.content === 'string');
|
|
49
|
+
if (command.command_type === 'steer') check(typeof command.payload.content === 'string' && command.payload.content.trim());
|
|
50
|
+
if (command.command_type === 'submit_interaction') check(text(command.payload.run_id) && text(command.payload.interaction_id)
|
|
51
|
+
&& text(command.payload.token_ref) && Object.hasOwn(command.payload, 'response'));
|
|
52
|
+
if (command.command_type === 'resume') check(object(command.payload.target)
|
|
53
|
+
&& ['run', 'checkpoint', 'continuation'].includes(command.payload.target.kind) && text(command.payload.target.id));
|
|
54
|
+
if (command.payload.run_id !== undefined && command.payload.run_id !== null) check(text(command.payload.run_id));
|
|
55
|
+
if (command.payload.scope_id !== undefined && command.payload.scope_id !== null) check(text(command.payload.scope_id));
|
|
56
|
+
return command;
|
|
57
|
+
}
|
|
58
|
+
function businessDigest(command) {
|
|
59
|
+
const value = copy(command); delete value.command_id; delete value.submitted_at; delete value.authorization_ref;
|
|
60
|
+
if (command.command_type !== 'inject') delete value.source.ref;
|
|
61
|
+
delete value.payload.session_context;
|
|
62
|
+
if (value.command_type === 'submit_interaction') delete value.payload.token_ref;
|
|
63
|
+
return hash(value);
|
|
64
|
+
}
|
|
65
|
+
export function managedNativeRunId(command) {
|
|
66
|
+
// Same stable original-command lookup used by execution_grant_run_id in the
|
|
67
|
+
// reference. JSON's ASCII escaping matters for non-ASCII session identifiers.
|
|
68
|
+
const parts = [command.tenant_id, command.agent_instance_id, command.session_id, command.command_id.toLowerCase()];
|
|
69
|
+
const encoded = JSON.stringify(parts).replace(/[\u007f-\uffff]/g, c => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'));
|
|
70
|
+
const bytes = createHash('sha1').update(Buffer.from('6ba7b8119dad11d180b400c04fd430c8', 'hex'))
|
|
71
|
+
.update('ksadk:execution-grant:' + encoded).digest();
|
|
72
|
+
bytes[6] = bytes[6] & 15 | 80; bytes[8] = bytes[8] & 63 | 128;
|
|
73
|
+
const hex = bytes.subarray(0, 16).toString('hex');
|
|
74
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
75
|
+
}
|
|
76
|
+
const rejection = (command, code, status = 'rejected') => ({ schema_version: 1, command_id: command.command_id,
|
|
77
|
+
status, error: { code, message: code, retryable: status === 'queue_full', details: {} } });
|
|
78
|
+
|
|
79
|
+
export function createManagedNativeKernel({ directory, target, permitVerifier, resolveBinding, authorizeInteraction, platformApprovals = false, scopedControl, teamsCallbackVerifier, assertCurrent,
|
|
80
|
+
queueLimit = 100, clock = Date.now, monotonic, autoStart = true, beforeCommit, beforeProjection, onWorkerError, projectSessionEvent } = {}) {
|
|
81
|
+
invariant(text(directory) && object(target) && text(target.tenantId) && text(target.agentInstanceId)
|
|
82
|
+
&& typeof permitVerifier?.verify === 'function' && typeof resolveBinding === 'function' && typeof assertCurrent === 'function'
|
|
83
|
+
&& Number.isSafeInteger(queueLimit) && queueLimit > 0 && typeof autoStart === 'boolean'
|
|
84
|
+
&& (onWorkerError === undefined || typeof onWorkerError === 'function')
|
|
85
|
+
&& (projectSessionEvent === undefined || typeof projectSessionEvent === 'function')
|
|
86
|
+
&& (monotonic === undefined || typeof monotonic === 'function')
|
|
87
|
+
&& (teamsCallbackVerifier === undefined || typeof teamsCallbackVerifier?.verify === 'function')
|
|
88
|
+
&& (scopedControl === undefined || typeof scopedControl?.prepare === 'function' && typeof scopedControl?.execute === 'function'),
|
|
89
|
+
'NATIVE_KERNEL_CONFIGURATION_INVALID');
|
|
90
|
+
const bindingTarget = copy(target), verifyPermit = permitVerifier.verify, owner = `native-server-${randomUUID()}`;
|
|
91
|
+
const runScopeAgentId = bindingTarget.runScopeAgentId ?? bindingTarget.agentInstanceId;
|
|
92
|
+
invariant(text(runScopeAgentId), 'NATIVE_KERNEL_COMMAND_INVALID');
|
|
93
|
+
const initialAuthority = assertCurrent();
|
|
94
|
+
if (initialAuthority && typeof initialAuthority.then === 'function') void Promise.resolve(initialAuthority).catch(() => {});
|
|
95
|
+
invariant(initialAuthority === true, 'NATIVE_KERNEL_AUTHORITY_LOST');
|
|
96
|
+
privateDirectory(directory, true);
|
|
97
|
+
for (const filename of ['commands.sqlite', 'runs.sqlite']) {
|
|
98
|
+
const path = join(directory, filename);
|
|
99
|
+
if (!privateFile(path, true)) {
|
|
100
|
+
try { createPrivate(path); } catch (error) { if (error.code !== 'EEXIST') throw error; privateFile(path); }
|
|
101
|
+
}
|
|
102
|
+
for (const suffix of ['-wal', '-shm', '-journal']) privateFile(path + suffix, true);
|
|
103
|
+
}
|
|
104
|
+
const db = new DatabaseSync(join(directory, 'commands.sqlite'));
|
|
105
|
+
try {
|
|
106
|
+
db.exec('PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;');
|
|
107
|
+
db.exec('BEGIN IMMEDIATE');
|
|
108
|
+
try {
|
|
109
|
+
db.exec('CREATE TABLE IF NOT EXISTS managed_schema (version INTEGER PRIMARY KEY)');
|
|
110
|
+
const versions = db.prepare('SELECT version FROM managed_schema').all();
|
|
111
|
+
invariant(!versions.length || versions.length === 1 && versions[0].version === 1, 'NATIVE_KERNEL_SCHEMA_UNSUPPORTED');
|
|
112
|
+
if (!versions.length) db.prepare('INSERT INTO managed_schema VALUES (1)').run();
|
|
113
|
+
db.exec(`CREATE TABLE IF NOT EXISTS managed_binding (id INTEGER PRIMARY KEY CHECK(id=1), data TEXT NOT NULL);
|
|
114
|
+
CREATE TABLE IF NOT EXISTS managed_event_source (id INTEGER PRIMARY KEY CHECK(id=1), epoch TEXT NOT NULL);
|
|
115
|
+
CREATE TABLE IF NOT EXISTS managed_nonces (nonce TEXT PRIMARY KEY, command_id TEXT NOT NULL, idem TEXT NOT NULL);
|
|
116
|
+
CREATE TABLE IF NOT EXISTS managed_commands (command_id TEXT PRIMARY KEY, session_id TEXT NOT NULL,
|
|
117
|
+
idem TEXT NOT NULL, digest TEXT NOT NULL, subject TEXT NOT NULL, data TEXT NOT NULL, receipt TEXT NOT NULL,
|
|
118
|
+
state TEXT NOT NULL DEFAULT 'accepted', UNIQUE(session_id,idem));
|
|
119
|
+
CREATE TABLE IF NOT EXISTS managed_runs (run_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, command_id TEXT NOT NULL,
|
|
120
|
+
scope TEXT NOT NULL, config TEXT NOT NULL, build_id TEXT NOT NULL, native_cursor INTEGER NOT NULL DEFAULT 0);
|
|
121
|
+
CREATE INDEX IF NOT EXISTS managed_runs_session ON managed_runs(session_id);
|
|
122
|
+
CREATE TABLE IF NOT EXISTS managed_session_cancels (run_id TEXT PRIMARY KEY);
|
|
123
|
+
CREATE TABLE IF NOT EXISTS managed_session_frames (run_id TEXT NOT NULL, seq INTEGER NOT NULL,
|
|
124
|
+
data TEXT NOT NULL, PRIMARY KEY(run_id,seq));
|
|
125
|
+
CREATE TABLE IF NOT EXISTS managed_events (session_id TEXT NOT NULL, seq INTEGER NOT NULL,
|
|
126
|
+
event_id TEXT UNIQUE NOT NULL, data TEXT NOT NULL, PRIMARY KEY(session_id,seq));`);
|
|
127
|
+
db.prepare('INSERT OR IGNORE INTO managed_binding VALUES (1,?)').run(canonical(bindingTarget));
|
|
128
|
+
db.prepare('INSERT OR IGNORE INTO managed_event_source VALUES (1,?)').run(randomUUID());
|
|
129
|
+
invariant(db.prepare('SELECT data FROM managed_binding WHERE id=1').get().data === canonical(bindingTarget), 'NATIVE_KERNEL_TARGET_CHANGED');
|
|
130
|
+
db.exec('COMMIT');
|
|
131
|
+
} catch (error) { db.exec('ROLLBACK'); throw error; }
|
|
132
|
+
} catch (error) { db.close(); throw error; }
|
|
133
|
+
let runStore;
|
|
134
|
+
try { runStore = new SqliteRunStore(join(directory, 'runs.sqlite')); }
|
|
135
|
+
catch (error) { db.close(); throw error; }
|
|
136
|
+
const eventSource = db.prepare('SELECT epoch FROM managed_event_source WHERE id=1').get().epoch;
|
|
137
|
+
const lifetime = new AbortController(), active = new Map(), kernels = new Map(), failures = new Map(), wakeWaiters = new Set(), executing = new Set();
|
|
138
|
+
let closed = false, closing, timer, retryTimer, generation = 0, schedulingEnabled = autoStart;
|
|
139
|
+
const retryAfter = new Map();
|
|
140
|
+
function guard() {
|
|
141
|
+
invariant(!closed && !lifetime.signal.aborted && permitVerifier.verify === verifyPermit, 'NATIVE_KERNEL_AUTHORITY_LOST');
|
|
142
|
+
const result = assertCurrent();
|
|
143
|
+
if (result && typeof result.then === 'function') void Promise.resolve(result).catch(() => {});
|
|
144
|
+
invariant(result === true, 'NATIVE_KERNEL_AUTHORITY_LOST'); return true;
|
|
145
|
+
}
|
|
146
|
+
const transaction = change => {
|
|
147
|
+
guard(); db.exec('BEGIN IMMEDIATE');
|
|
148
|
+
try { const result = change(); guard(); beforeCommit?.(); db.exec('COMMIT'); return result; }
|
|
149
|
+
catch (error) { db.exec('ROLLBACK'); throw error; }
|
|
150
|
+
};
|
|
151
|
+
const runRow = id => db.prepare('SELECT * FROM managed_runs WHERE run_id=?').get(id);
|
|
152
|
+
const commandRow = id => db.prepare('SELECT * FROM managed_commands WHERE command_id=?').get(id);
|
|
153
|
+
const grants = createManagedNativeExecutionGrants({ db, guard, transaction, target: bindingTarget, clock, monotonic, hash, wake: schedule,
|
|
154
|
+
readRun(id) {
|
|
155
|
+
const row = runRow(id); if (!row) return null;
|
|
156
|
+
try { return runStore.load(parseNativeJson(row.scope), id); }
|
|
157
|
+
catch (error) { if (error.code === 'run_not_found') return null; throw error; }
|
|
158
|
+
} });
|
|
159
|
+
let teamsContexts, teamsCallbacks;
|
|
160
|
+
try {
|
|
161
|
+
teamsContexts = createManagedNativeTeamsContexts({ db, guard, transaction, target: bindingTarget, validateCommand: commandView });
|
|
162
|
+
teamsCallbacks = teamsCallbackVerifier ? createNativeTeamsCallbackAuthority({ contexts: teamsContexts.api,
|
|
163
|
+
executionGrants: grants.api, verifier: teamsCallbackVerifier, expectedIncarnation: teamsContexts.api.incarnation() }) : null;
|
|
164
|
+
}
|
|
165
|
+
catch (error) { runStore.close(); db.close(); throw error; }
|
|
166
|
+
let injections;
|
|
167
|
+
try { injections = createManagedNativeInjection({ db, store: runStore, guard, transaction, target: bindingTarget }); }
|
|
168
|
+
catch (error) { runStore.close(); db.close(); throw error; }
|
|
169
|
+
const sessionFrames = createManagedSessionFrames(db, projectSessionEvent);
|
|
170
|
+
const sessionCancelPending = runId => !!db.prepare('SELECT 1 FROM managed_session_cancels WHERE run_id=?').get(runId);
|
|
171
|
+
function sessionRunPhase(scope, runId) {
|
|
172
|
+
try { return runStore.authority(scope, runId).snapshot.phase; }
|
|
173
|
+
catch (error) { if (error.code === 'run_not_found') return null; throw error; }
|
|
174
|
+
}
|
|
175
|
+
function submitSessionCancel(scope, runId, kernel = kernels.get(runId), phase = sessionRunPhase(scope, runId)) {
|
|
176
|
+
// The start transaction may not yet exist when the user stops a claimed
|
|
177
|
+
// SDK turn. The managed marker remains until the original Run settles.
|
|
178
|
+
if (phase === null || terminal(phase)) return;
|
|
179
|
+
const driver = kernel ?? new NativeKernel({ store: runStore, ports: {}, owner, digest: hash });
|
|
180
|
+
driver.submit(scope, runId, { commandId: `${runId}:host-session-cancel`, kind: 'cancel', payload: {} });
|
|
181
|
+
}
|
|
182
|
+
function append(sessionId, facts, command) {
|
|
183
|
+
let seq = db.prepare('SELECT COALESCE(MAX(seq),0) AS seq FROM managed_events WHERE session_id=?').get(sessionId).seq;
|
|
184
|
+
for (const fact of facts) {
|
|
185
|
+
const existing = db.prepare('SELECT data FROM managed_events WHERE event_id=?').get(fact.event_id);
|
|
186
|
+
if (existing) continue;
|
|
187
|
+
const value = { schema_version: 1, session_id: sessionId, seq: ++seq, timestamp: new Date(clock()).toISOString(),
|
|
188
|
+
causation_id: command.command_id, correlation_id: command.correlation_id ?? null, actor_ref: null, ...fact };
|
|
189
|
+
if (value.family === 'runtime') {
|
|
190
|
+
value.payload = { ...value.payload, event_id: value.event_id, seq: value.seq, timestamp: Date.parse(value.timestamp) / 1000,
|
|
191
|
+
source: { framework: 'ksadk', native_event_id: value.event_id, native_run_id: value.run_id,
|
|
192
|
+
metadata: { implementation: MANAGED_NATIVE_KERNEL_CONTRACT } } };
|
|
193
|
+
value.actor_ref = 'ksadk';
|
|
194
|
+
} else if (value.family === 'interaction') {
|
|
195
|
+
value.payload = { schema_version: 1, event_type: value.event_type, tenant_id: command.tenant_id,
|
|
196
|
+
agent_instance_id: command.agent_instance_id, session_id: sessionId, run_id: value.run_id,
|
|
197
|
+
timestamp: value.timestamp, ...value.payload };
|
|
198
|
+
}
|
|
199
|
+
db.prepare('INSERT INTO managed_events VALUES (?,?,?,?)').run(sessionId, value.seq, value.event_id, canonical(value));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function project(row) {
|
|
203
|
+
guard();
|
|
204
|
+
let record;
|
|
205
|
+
try { record = runStore.load(parseNativeJson(row.scope), row.run_id); }
|
|
206
|
+
catch (error) { if (error.code === 'run_not_found') return; throw error; }
|
|
207
|
+
transaction(() => {
|
|
208
|
+
const current = runRow(row.run_id), command = parseNativeJson(commandRow(row.command_id).data);
|
|
209
|
+
for (const event of record.events.filter(event => event.seq > current.native_cursor)) {
|
|
210
|
+
append(row.session_id, projectNativeKernelEvent(event, { scopeId: row.run_id, commandId: row.command_id }), command);
|
|
211
|
+
db.prepare('UPDATE managed_runs SET native_cursor=? WHERE run_id=?').run(event.seq, row.run_id);
|
|
212
|
+
}
|
|
213
|
+
sessionFrames.sync(record);
|
|
214
|
+
interactions.settle(row, record, command);
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
const interactions = createManagedNativeInteractions({ db, guard, transaction, append, hash, clock, lifetime,
|
|
218
|
+
lookup(query) {
|
|
219
|
+
const inspected = inspectSession(query);
|
|
220
|
+
invariant(inspected?.record, 'NATIVE_MANAGED_INTERACTION_UNAVAILABLE');
|
|
221
|
+
const source = query.sourceRunId === query.runId ? inspected.record
|
|
222
|
+
: readChildRecord({ ...query, childRunId: query.sourceRunId });
|
|
223
|
+
return { root: inspected.record, source, command: parseNativeJson(commandRow(inspected.commandId).data) };
|
|
224
|
+
} });
|
|
225
|
+
const scopedControls = createManagedNativeScopedControls({ db, guard, transaction, append, clock, lifetime, wake, control: scopedControl,
|
|
226
|
+
lookup(sessionId, runId) {
|
|
227
|
+
const run = runRow(runId);
|
|
228
|
+
invariant(run && run.session_id === sessionId, 'NATIVE_MANAGED_SCOPE_NOT_FOUND');
|
|
229
|
+
return inspectSession({ scope: parseNativeJson(run.scope), sessionId, runId });
|
|
230
|
+
} });
|
|
231
|
+
const scopedTimer = setInterval(() => {
|
|
232
|
+
if (schedulingEnabled && !closed) try {
|
|
233
|
+
scopedControls.drain();
|
|
234
|
+
// Observe cross-connection grant changes without resolving bindings or
|
|
235
|
+
// repeatedly trying a suspended FIFO head. No persisted expiry is an anchor.
|
|
236
|
+
for (const sessionId of grants.readySessions()) if (!active.has(sessionId)
|
|
237
|
+
&& (!failures.has(sessionId) || failures.get(sessionId).startsWith('execution_grant_'))) schedule();
|
|
238
|
+
} catch { /* A later trusted recovery retries the original durable delivery. */ }
|
|
239
|
+
}, 100);
|
|
240
|
+
scopedTimer.unref?.();
|
|
241
|
+
function projectAll() { for (const row of db.prepare('SELECT * FROM managed_runs ORDER BY rowid').all()) project(row); }
|
|
242
|
+
async function waitForCommand(version, snapshot, signal, changed) {
|
|
243
|
+
const scoped = signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal;
|
|
244
|
+
guard(); scoped.throwIfAborted(); if (generation !== version || changed?.()) return;
|
|
245
|
+
await new Promise((resolve, reject) => {
|
|
246
|
+
const wake = () => { cleanup(); resolve(); };
|
|
247
|
+
const abort = () => { cleanup(); reject(scoped.reason); };
|
|
248
|
+
const cleanup = () => { clearInterval(poll); wakeWaiters.delete(wake); scoped.removeEventListener('abort', abort); };
|
|
249
|
+
// The HTTP receiver and Session owner may be different local processes.
|
|
250
|
+
// A paused Run has no Native heartbeat, so observe its durable command
|
|
251
|
+
// queue without executing effects or relying on an in-memory wakeup.
|
|
252
|
+
const poll = setInterval(() => {
|
|
253
|
+
try {
|
|
254
|
+
guard(); const current = runStore.load(snapshot.scope, snapshot.runId);
|
|
255
|
+
if (changed ? changed(current) : current.snapshot.revision !== snapshot.revision || current.commands.some(row => !row.consumed)) wake();
|
|
256
|
+
} catch (error) { cleanup(); reject(error); }
|
|
257
|
+
}, 100);
|
|
258
|
+
wakeWaiters.add(wake); scoped.addEventListener('abort', abort, { once: true });
|
|
259
|
+
if (scoped.aborted) abort(); else if (generation !== version) wake();
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
function bindingRequest(command, run, stage) {
|
|
263
|
+
return { command: copy(command), recovery: stage === 'execute', stage,
|
|
264
|
+
runId: run?.run_id ?? managedNativeRunId(command), signal: lifetime.signal, store: runStore,
|
|
265
|
+
admission: run ? { scope: parseNativeJson(run.scope), buildId: run.build_id,
|
|
266
|
+
configuration: parseNativeJson(run.config) } : null };
|
|
267
|
+
}
|
|
268
|
+
function resolveOwnedBinding(request) {
|
|
269
|
+
guard();
|
|
270
|
+
// A binding lookup is Host-owned, never HTTP-owned. Retirement must stop
|
|
271
|
+
// waiting even if a credential/resource provider ignores its signal. A
|
|
272
|
+
// late resource cannot become execution authority and is released instead.
|
|
273
|
+
return new Promise((resolve, reject) => {
|
|
274
|
+
let settled = false;
|
|
275
|
+
const stop = () => { settled = true; reject(lifetime.signal.reason ?? new Error('Native owner closed')); };
|
|
276
|
+
lifetime.signal.addEventListener('abort', stop, { once: true });
|
|
277
|
+
Promise.resolve().then(() => { guard(); return resolveBinding(request); }).then(binding => {
|
|
278
|
+
if (settled) {
|
|
279
|
+
void Promise.resolve().then(() => binding?.release?.({ scope: binding.scope === undefined ? undefined : copy(binding.scope), sessionId: request.command.session_id,
|
|
280
|
+
runId: request.runId, stage: request.stage, signal: request.signal, reason: 'owner_retired' })).catch(() => {});
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
settled = true; lifetime.signal.removeEventListener('abort', stop); resolve(binding);
|
|
284
|
+
}, error => {
|
|
285
|
+
if (settled) return;
|
|
286
|
+
settled = true; lifetime.signal.removeEventListener('abort', stop); reject(error);
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
const receipt = (row, command, duplicate = false) => ({ ...parseNativeJson(row.receipt), command_id: command.command_id,
|
|
291
|
+
...(duplicate ? { status: 'duplicate' } : {}) });
|
|
292
|
+
async function authenticate(raw, permit, operation) {
|
|
293
|
+
guard(); const request = copy(raw), authorization = await verifyPermit.call(permitVerifier, copy(permit), request, operation); guard();
|
|
294
|
+
invariant(request.tenant_id === bindingTarget.tenantId && request.agent_instance_id === bindingTarget.agentInstanceId,
|
|
295
|
+
'NATIVE_KERNEL_PERMIT_INVALID');
|
|
296
|
+
return { request, authorization };
|
|
297
|
+
}
|
|
298
|
+
function existing(command, authorization) {
|
|
299
|
+
const byId = commandRow(command.command_id), byKey = db.prepare('SELECT * FROM managed_commands WHERE session_id=? AND idem=?')
|
|
300
|
+
.get(command.session_id, command.idempotency_key);
|
|
301
|
+
if (byId && (byId.session_id !== command.session_id || byId.idem !== command.idempotency_key))
|
|
302
|
+
return rejection(command, 'command_id_conflict');
|
|
303
|
+
const row = byKey ?? byId;
|
|
304
|
+
if (!row) return null;
|
|
305
|
+
if (row.digest !== businessDigest(command) || row.subject !== authorization.subjectRef) return rejection(command, 'idempotency_conflict');
|
|
306
|
+
return receipt(row, command, true);
|
|
307
|
+
}
|
|
308
|
+
function consumeNonce(authorization, command, write = true) {
|
|
309
|
+
const prior = db.prepare('SELECT * FROM managed_nonces WHERE nonce=?').get(authorization.nonce);
|
|
310
|
+
invariant(!prior || prior.command_id === command.command_id && prior.idem === command.idempotency_key, 'NATIVE_KERNEL_NONCE_REUSED');
|
|
311
|
+
if (write) db.prepare('INSERT OR IGNORE INTO managed_nonces VALUES (?,?,?)').run(authorization.nonce, command.command_id, command.idempotency_key);
|
|
312
|
+
}
|
|
313
|
+
async function receive(raw, permit) {
|
|
314
|
+
const attempt = copy(permit), command = commandView(raw), { authorization } = await authenticate(command, attempt, command.command_type);
|
|
315
|
+
managedExecutionGrantId(command);
|
|
316
|
+
const prior = transaction(() => {
|
|
317
|
+
consumeNonce(authorization, command, false); const value = existing(command, authorization);
|
|
318
|
+
if (value) consumeNonce(authorization, command); return value;
|
|
319
|
+
});
|
|
320
|
+
if (prior) {
|
|
321
|
+
if (command.command_type === 'inject') { injections.deliver(command.session_id); return prior; }
|
|
322
|
+
// A delivered control's duplicate is a read-only confirmation. Waking
|
|
323
|
+
// the idle owner here would withdraw a later, unrelated consent wait.
|
|
324
|
+
const queued = db.prepare('SELECT state FROM managed_commands WHERE session_id=? AND idem=?')
|
|
325
|
+
.get(command.session_id, command.idempotency_key);
|
|
326
|
+
if (prior.status === 'duplicate' && queued?.state === 'accepted') wake();
|
|
327
|
+
return prior;
|
|
328
|
+
}
|
|
329
|
+
// Reserving Teams facts does not authorize ordinary Server traffic into
|
|
330
|
+
// that Session. The dedicated trusted Teams ingress/policy is still needed.
|
|
331
|
+
if (teamsContexts.reserved(command.session_id)) return rejection(command, 'native_teams_ingress_required');
|
|
332
|
+
const scoped = command.command_type === 'interrupt' && command.payload.scope_id != null;
|
|
333
|
+
if (!supported.has(command.command_type) || command.payload.scope_id != null && (!scoped || !scopedControls.supported)
|
|
334
|
+
|| command.command_type === 'resume' && (command.payload.target.kind !== 'run' || command.payload.input != null)
|
|
335
|
+
|| command.command_type === 'enqueue' && ['legacy_history', 'execution_policy_ref', 'teams_context_ref']
|
|
336
|
+
.some(key => command.payload[key] != null)) return rejection(command, 'native_control_unsupported', 'unsupported');
|
|
337
|
+
let binding, injectionScope, interactionDigest, managedInteraction, scopedTarget, admitted = false;
|
|
338
|
+
try {
|
|
339
|
+
if (command.command_type === 'inject') {
|
|
340
|
+
injections.input(command);
|
|
341
|
+
const supplied = typeof resolveBinding.resolveInjectionScope === 'function'
|
|
342
|
+
? await resolveBinding.resolveInjectionScope({ command: copy(command), signal: lifetime.signal }) : undefined;
|
|
343
|
+
guard(); injectionScope = injections.scope(command, supplied);
|
|
344
|
+
}
|
|
345
|
+
if (scoped) {
|
|
346
|
+
const selected = command.payload.run_id ?? db.prepare("SELECT r.run_id FROM managed_runs r JOIN managed_commands c ON r.command_id=c.command_id WHERE r.session_id=? AND c.state='accepted' ORDER BY r.rowid LIMIT 1")
|
|
347
|
+
.get(command.session_id)?.run_id;
|
|
348
|
+
try { scopedTarget = await scopedControls.prepare(command, selected); }
|
|
349
|
+
catch (error) { if (['NATIVE_MANAGED_SCOPE_NOT_FOUND', 'NATIVE_MANAGED_SCOPE_UNAVAILABLE'].includes(error.code))
|
|
350
|
+
return rejection(command, 'native_child_scope_not_found'); throw error; }
|
|
351
|
+
}
|
|
352
|
+
if (command.command_type === 'submit_interaction') {
|
|
353
|
+
const row = runRow(command.payload.run_id);
|
|
354
|
+
if (!row || row.session_id !== command.session_id) return rejection(command, 'native_run_not_found');
|
|
355
|
+
let pending = interactions.pending(command);
|
|
356
|
+
managedInteraction = pending;
|
|
357
|
+
try { pending = runStore.load(parseNativeJson(row.scope), row.run_id).snapshot.pendingInteraction; }
|
|
358
|
+
catch (error) { if (error.code !== 'run_not_found') throw error; }
|
|
359
|
+
pending = managedInteraction ?? pending;
|
|
360
|
+
if (!pending || typeof authorizeInteraction !== 'function') return rejection(command, 'native_interaction_authority_unavailable');
|
|
361
|
+
const authorized = await authorizeInteraction({ command: copy(command), authorization, pending: copy(pending) }); guard();
|
|
362
|
+
if (authorized !== true) return rejection(command, 'native_interaction_authority_invalid');
|
|
363
|
+
interactionDigest = hash(pending);
|
|
364
|
+
}
|
|
365
|
+
if (command.command_type === 'enqueue') {
|
|
366
|
+
const grantError = transaction(() => grants.commandError(command));
|
|
367
|
+
if (grantError) return rejection(command, grantError);
|
|
368
|
+
binding = await resolveOwnedBinding(bindingRequest(command, null, 'admit')); guard();
|
|
369
|
+
check(object(binding) && object(binding.scope) && binding.scope.tenantId === command.tenant_id
|
|
370
|
+
&& binding.scope.agentId === runScopeAgentId && text(binding.buildId) && object(binding.ports));
|
|
371
|
+
binding = { ...binding, configuration: configure({ ...binding.configuration, sessionInjectionPolicy: 'next-turn-inbox/v1' }) };
|
|
372
|
+
check(Array.isArray(binding.configuration.inputMessages) && binding.configuration.inputMessages.length > 0);
|
|
373
|
+
}
|
|
374
|
+
// Binding/resource lookup may await network I/O. Expired or revoked Server
|
|
375
|
+
// authority cannot enter the admission transaction after that delay.
|
|
376
|
+
await authenticate(command, attempt, command.command_type);
|
|
377
|
+
const accepted = transaction(() => {
|
|
378
|
+
consumeNonce(authorization, command); const duplicate = existing(command, authorization); if (duplicate) return duplicate;
|
|
379
|
+
if (teamsContexts.reserved(command.session_id)) return rejection(command, 'native_teams_ingress_required');
|
|
380
|
+
let runId;
|
|
381
|
+
if (binding) {
|
|
382
|
+
const grantError = grants.commandError(command); if (grantError) return rejection(command, grantError);
|
|
383
|
+
const count = db.prepare("SELECT COUNT(*) AS n FROM managed_commands WHERE session_id=? AND state='accepted'")
|
|
384
|
+
.get(command.session_id).n;
|
|
385
|
+
if (count >= queueLimit) return rejection(command, 'native_queue_full', 'queue_full');
|
|
386
|
+
const previous = db.prepare('SELECT scope,build_id FROM managed_runs WHERE session_id=? ORDER BY rowid DESC LIMIT 1').get(command.session_id);
|
|
387
|
+
if (previous && (previous.scope !== canonical(binding.scope) || previous.build_id !== binding.buildId))
|
|
388
|
+
return rejection(command, 'native_session_binding_changed');
|
|
389
|
+
runId = managedNativeRunId(command);
|
|
390
|
+
db.prepare('INSERT INTO managed_runs(run_id,session_id,command_id,scope,config,build_id) VALUES (?,?,?,?,?,?)')
|
|
391
|
+
.run(runId, command.session_id, command.command_id, canonical(binding.scope), canonical(binding.configuration), binding.buildId);
|
|
392
|
+
} else if (injectionScope) {
|
|
393
|
+
// An injection is data admission, with no synthetic Run or active-turn lookup.
|
|
394
|
+
runId = null;
|
|
395
|
+
if (!injections.hasCapacity(command)) return rejection(command, 'native_injection_queue_full', 'queue_full');
|
|
396
|
+
injections.scope(command, injectionScope);
|
|
397
|
+
} else {
|
|
398
|
+
runId = scopedTarget?.runId ?? (command.command_type === 'resume' ? command.payload.target.id : command.payload.run_id);
|
|
399
|
+
if (!runId) runId = db.prepare('SELECT run_id FROM managed_runs WHERE session_id=? ORDER BY rowid DESC LIMIT 1').get(command.session_id)?.run_id;
|
|
400
|
+
const row = runId && runRow(runId);
|
|
401
|
+
if (!row || row.session_id !== command.session_id) return rejection(command, 'native_run_not_found');
|
|
402
|
+
try {
|
|
403
|
+
if (terminal(runStore.load(parseNativeJson(row.scope), runId).snapshot.phase)) return rejection(command, 'native_run_terminal');
|
|
404
|
+
} catch (error) { if (error.code !== 'run_not_found') throw error; }
|
|
405
|
+
if (command.command_type === 'submit_interaction') {
|
|
406
|
+
if (managedInteraction) {
|
|
407
|
+
try { interactions.validate(command, managedInteraction); }
|
|
408
|
+
catch (error) { if (['NATIVE_MANAGED_INTERACTION_CONFLICT', 'NATIVE_MANAGED_INTERACTION_UNAVAILABLE'].includes(error.code))
|
|
409
|
+
return rejection(command, 'native_interaction_conflict'); throw error; }
|
|
410
|
+
} else {
|
|
411
|
+
const snapshot = runStore.load(parseNativeJson(row.scope), runId).snapshot, pending = snapshot.pendingInteraction;
|
|
412
|
+
const platform = platformApprovals && nativePlatformToolApproval(command);
|
|
413
|
+
if (snapshot.phase !== 'awaiting_interaction' || !pending || hash(pending) !== interactionDigest || pending.interactionId !== command.payload.interaction_id
|
|
414
|
+
|| command.payload.expected_revision != null && command.payload.expected_revision !== 1
|
|
415
|
+
|| !platform && (command.payload.action != null && command.payload.action !== 'submit'
|
|
416
|
+
|| !['approve', 'reject'].includes(command.payload.response))) return rejection(command, 'native_interaction_conflict');
|
|
417
|
+
if (platform && db.prepare(`SELECT 1 FROM managed_commands WHERE session_id=?
|
|
418
|
+
AND state IN ('accepted', 'delivered') AND json_extract(data, '$.command_type')='submit_interaction'
|
|
419
|
+
AND json_extract(receipt, '$.run_id')=? AND json_extract(data, '$.payload.interaction_id')=? LIMIT 1`)
|
|
420
|
+
.get(command.session_id, runId, platform.interaction_id)) return rejection(command, 'native_interaction_conflict');
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
const seq = db.prepare('SELECT COUNT(*) AS n FROM managed_commands WHERE session_id=?').get(command.session_id).n + 1;
|
|
425
|
+
const result = { schema_version: 1, command_id: command.command_id, status: 'accepted', message_id: randomUUID(), run_id: runId, accepted_seq: seq };
|
|
426
|
+
db.prepare('INSERT INTO managed_commands(command_id,session_id,idem,digest,subject,data,receipt) VALUES (?,?,?,?,?,?,?)')
|
|
427
|
+
.run(command.command_id, command.session_id, command.idempotency_key, businessDigest(command), authorization.subjectRef, canonical(command), canonical(result));
|
|
428
|
+
append(command.session_id, [{ event_id: nativeKernelFactId(command.command_id, 'admission'), family: 'control', family_version: 1,
|
|
429
|
+
event_type: 'control.command_accepted', run_id: runId, payload: { command_id: command.command_id, message_id: result.message_id,
|
|
430
|
+
accepted_seq: seq, status: 'accepted', command_type: command.command_type } }], command);
|
|
431
|
+
if (injectionScope) injections.admit(command, injectionScope);
|
|
432
|
+
if (managedInteraction) interactions.resolve(command, managedInteraction, authorization);
|
|
433
|
+
if (scopedTarget) scopedControls.admit(command, scopedTarget, authorization);
|
|
434
|
+
return result;
|
|
435
|
+
});
|
|
436
|
+
admitted = accepted.status === 'accepted';
|
|
437
|
+
if (admitted && injectionScope) { injections.deliver(command.session_id); return accepted; }
|
|
438
|
+
if (admitted) {
|
|
439
|
+
applyControls(command.session_id); scopedControls.drain();
|
|
440
|
+
// A scoped control owns an independent delivery queue. Do not retire
|
|
441
|
+
// an unrelated pending question before cancellation is durable in its
|
|
442
|
+
// original A2A journal; delivery wakes the original receipt waiter.
|
|
443
|
+
if (!scopedTarget) wake();
|
|
444
|
+
}
|
|
445
|
+
return accepted;
|
|
446
|
+
} finally { await binding?.release?.({ scope: binding.scope === undefined ? undefined : copy(binding.scope), sessionId: command.session_id,
|
|
447
|
+
runId: managedNativeRunId(command), stage: 'admit', admitted, signal: lifetime.signal }); }
|
|
448
|
+
}
|
|
449
|
+
function nativeCommand(command) {
|
|
450
|
+
const payload = command.payload;
|
|
451
|
+
if (command.command_type === 'submit_interaction') {
|
|
452
|
+
const decision = (nativePlatformToolApproval(command)?.action ?? payload.response) === 'approve' ? 'allow' : 'deny';
|
|
453
|
+
return { commandId: command.command_id, kind: command.command_type, payload: { interactionId: payload.interaction_id, decision } };
|
|
454
|
+
}
|
|
455
|
+
return { commandId: command.command_id, kind: ({ interrupt: 'cancel' })[command.command_type] ?? command.command_type,
|
|
456
|
+
payload: command.command_type === 'steer' ? { text: payload.content } : {} };
|
|
457
|
+
}
|
|
458
|
+
function applyControls(sessionId) {
|
|
459
|
+
guard();
|
|
460
|
+
for (const row of db.prepare("SELECT * FROM managed_commands WHERE session_id=? AND state='accepted' ORDER BY rowid").all(sessionId)) {
|
|
461
|
+
const command = parseNativeJson(row.data); if (['enqueue', 'inject'].includes(command.command_type)) continue;
|
|
462
|
+
invariant(command.payload.scope_id == null, 'NATIVE_MANAGED_SCOPE_DELIVERY_INVALID');
|
|
463
|
+
if (command.command_type === 'submit_interaction' && interactions.owns(command)) {
|
|
464
|
+
transaction(() => db.prepare("UPDATE managed_commands SET state='delivered' WHERE command_id=?").run(command.command_id));
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
const id = parseNativeJson(row.receipt).run_id, run = runRow(id), scope = parseNativeJson(run.scope);
|
|
468
|
+
try { runStore.load(scope, id); } catch (error) { if (error.code === 'run_not_found') continue; throw error; }
|
|
469
|
+
// An interrupted process may stop after enqueue but before this ACK.
|
|
470
|
+
// Native's durable command identity makes replay safe in that window.
|
|
471
|
+
const kernel = kernels.get(id) ?? new NativeKernel({ store: runStore, ports: {}, owner, digest: hash });
|
|
472
|
+
const delivered = kernel.submit(scope, id, nativeCommand(command));
|
|
473
|
+
transaction(() => {
|
|
474
|
+
if (delivered.status === 'rejected') append(sessionId, [{ event_id: nativeKernelFactId(command.command_id, 'delivery-rejected'),
|
|
475
|
+
family: 'control', family_version: 1, event_type: 'control.command_rejected', run_id: id,
|
|
476
|
+
payload: { command_id: command.command_id, reason: 'native_control_rejected' } }], command);
|
|
477
|
+
db.prepare("UPDATE managed_commands SET state='delivered' WHERE command_id=?").run(command.command_id);
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
function portView(port, replacements) {
|
|
482
|
+
const read = key => {
|
|
483
|
+
if (Object.hasOwn(replacements, key)) return replacements[key];
|
|
484
|
+
const value = Reflect.get(port, key, port);
|
|
485
|
+
return typeof value === 'function' ? value.bind(port) : value;
|
|
486
|
+
};
|
|
487
|
+
// Proxy invariants forbid substituting a frozen target's own method or
|
|
488
|
+
// tokens property. Use a separate facade while preserving the real method
|
|
489
|
+
// receiver and its private state, including non-enumerable metadata.
|
|
490
|
+
return new Proxy(Object.create(Object.getPrototypeOf(port)), {
|
|
491
|
+
get: (_target, key) => read(key),
|
|
492
|
+
has: (_target, key) => Object.hasOwn(replacements, key) || key in port,
|
|
493
|
+
ownKeys: () => [...new Set([...Reflect.ownKeys(port), ...Reflect.ownKeys(replacements)])],
|
|
494
|
+
getOwnPropertyDescriptor(_target, key) {
|
|
495
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(port, key);
|
|
496
|
+
if (!descriptor && !Object.hasOwn(replacements, key)) return undefined;
|
|
497
|
+
return { configurable: true, enumerable: descriptor?.enumerable ?? true, writable: false, value: read(key) };
|
|
498
|
+
},
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
function ownedPort(port, name) {
|
|
502
|
+
if (!port?.[name]) return port;
|
|
503
|
+
const method = port[name];
|
|
504
|
+
const invoke = async (request, ...args) => {
|
|
505
|
+
guard(); const signal = request.signal ? AbortSignal.any([request.signal, lifetime.signal]) : lifetime.signal;
|
|
506
|
+
let onAbort;
|
|
507
|
+
const stopped = new Promise((_, reject) => { onAbort = () => reject(signal.reason ?? new Error('Native owner closed'));
|
|
508
|
+
signal.addEventListener('abort', onAbort, { once: true }); if (signal.aborted) onAbort(); });
|
|
509
|
+
try {
|
|
510
|
+
const work = Promise.resolve().then(() => { guard(); return method.call(port, { ...request, signal }, ...args); });
|
|
511
|
+
return await Promise.race([work, stopped]);
|
|
512
|
+
} finally { signal.removeEventListener('abort', onAbort); }
|
|
513
|
+
};
|
|
514
|
+
return portView(port, { [name]: invoke });
|
|
515
|
+
}
|
|
516
|
+
async function drive(sessionId) {
|
|
517
|
+
for (;;) {
|
|
518
|
+
guard(); injections.deliver(sessionId); applyControls(sessionId);
|
|
519
|
+
const row = db.prepare("SELECT * FROM managed_commands WHERE session_id=? AND state='accepted' ORDER BY rowid").all(sessionId)
|
|
520
|
+
.find(row => parseNativeJson(row.data).command_type === 'enqueue');
|
|
521
|
+
if (!row) return;
|
|
522
|
+
const command = parseNativeJson(row.data), id = parseNativeJson(row.receipt).run_id, run = runRow(id), scope = parseNativeJson(run.scope);
|
|
523
|
+
// Durable start qualification is serialized with revocation/admission.
|
|
524
|
+
// It precedes even asynchronous execution resource lookup, and survives
|
|
525
|
+
// a lost start ACK without changing the original Native Run identity.
|
|
526
|
+
if (!grants.qualify(row)) continue;
|
|
527
|
+
const resolved = await resolveOwnedBinding(bindingRequest(command, run, 'execute'));
|
|
528
|
+
try {
|
|
529
|
+
guard();
|
|
530
|
+
const storedConfiguration = parseNativeJson(run.config);
|
|
531
|
+
invariant(hash(configure({ ...resolved.configuration, ...(storedConfiguration.sessionInjectionPolicy
|
|
532
|
+
? { sessionInjectionPolicy: storedConfiguration.sessionInjectionPolicy } : {}) })) === hash(storedConfiguration)
|
|
533
|
+
&& canonical(resolved.scope) === run.scope && resolved.buildId === run.build_id, 'NATIVE_KERNEL_BINDING_CHANGED');
|
|
534
|
+
const ports = { ...resolved.ports };
|
|
535
|
+
for (const [port, methods] of Object.entries({ model: ['generate'], tools: ['execute', 'observeReceipt'], workspace: ['observe'],
|
|
536
|
+
input: ['prepare'], context: ['readSource', 'prepare'], verification: ['verify'], hooks: ['invoke'],
|
|
537
|
+
artifacts: ['write', 'read', 'search'], children: ['collect', 'reconcile', 'readyChildren', 'wakeControl', 'interruptedReceipts'],
|
|
538
|
+
background: ['observe'], browser: ['recoverSessions'] })) {
|
|
539
|
+
for (const method of methods) ports[port] = ownedPort(ports[port], method);
|
|
540
|
+
}
|
|
541
|
+
if (ports.context?.tokens) {
|
|
542
|
+
const tokens = ownedPort(ownedPort(ports.context.tokens, 'countRequest'), 'countText');
|
|
543
|
+
ports.context = portView(ports.context, { tokens });
|
|
544
|
+
}
|
|
545
|
+
let deliverCheckpoint, deliverStream;
|
|
546
|
+
const kernel = new NativeKernel({ store: runStore, ports, owner, digest: hash,
|
|
547
|
+
onStream: (identity, event, record) => { guard(); deliverStream?.(identity, event, record); },
|
|
548
|
+
onCheckpoint: async snapshot => { guard(); await deliverCheckpoint?.(copy(snapshot));
|
|
549
|
+
guard(); await beforeProjection?.(copy(snapshot)); guard(); project(run); } });
|
|
550
|
+
kernels.set(id, kernel);
|
|
551
|
+
try {
|
|
552
|
+
let prior;
|
|
553
|
+
try { prior = runStore.load(scope, id).snapshot; }
|
|
554
|
+
catch (error) { if (error.code !== 'run_not_found') throw error; }
|
|
555
|
+
const parentRunId = prior ? prior.parentRunId : runStore.sessionHead(scope, sessionId)?.runId ?? null;
|
|
556
|
+
const identity = { scope, runId: id, sessionId, turnId: command.command_id, buildId: run.build_id,
|
|
557
|
+
parentRunId, taskChainId: id };
|
|
558
|
+
let executed = false, boundaryOpen = true, snapshot;
|
|
559
|
+
const execute = async ({ signal, replayOnly = false, cancelOnly = false, onCheckpoint, onStream, onActive, onIdle } = {}) => {
|
|
560
|
+
guard(); invariant(boundaryOpen && !executed, 'NATIVE_KERNEL_EXECUTION_REENTERED'); executed = true;
|
|
561
|
+
invariant(!cancelOnly || signal?.aborted && !replayOnly, 'NATIVE_KERNEL_CANCEL_SIGNAL_REQUIRED');
|
|
562
|
+
if (replayOnly) {
|
|
563
|
+
snapshot = runStore.load(scope, id).snapshot;
|
|
564
|
+
invariant(terminal(snapshot.phase), 'NATIVE_KERNEL_OWNER_TERMINAL_MISMATCH'); project(run); return copy(snapshot);
|
|
565
|
+
}
|
|
566
|
+
invariant(onCheckpoint === undefined || typeof onCheckpoint === 'function', 'NATIVE_KERNEL_EXECUTION_CALLBACK_INVALID');
|
|
567
|
+
invariant(onStream === undefined || typeof onStream === 'function', 'NATIVE_KERNEL_EXECUTION_CALLBACK_INVALID');
|
|
568
|
+
invariant(onActive === undefined || typeof onActive === 'function', 'NATIVE_KERNEL_EXECUTION_CALLBACK_INVALID');
|
|
569
|
+
invariant(onIdle === undefined || typeof onIdle === 'function', 'NATIVE_KERNEL_EXECUTION_CALLBACK_INVALID');
|
|
570
|
+
deliverCheckpoint = onCheckpoint;
|
|
571
|
+
deliverStream = onStream;
|
|
572
|
+
executing.add(id);
|
|
573
|
+
kernel.start(identity, parseNativeJson(run.config));
|
|
574
|
+
if (sessionCancelPending(id)) submitSessionCancel(scope, id, kernel);
|
|
575
|
+
const cancel = () => {
|
|
576
|
+
if (closed || lifetime.signal.aborted) return;
|
|
577
|
+
kernel.submit(scope, id, { commandId: `${id}:host-session-cancel`, kind: 'cancel', payload: {} }); wake();
|
|
578
|
+
};
|
|
579
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
580
|
+
let releaseControls;
|
|
581
|
+
try {
|
|
582
|
+
if (signal?.aborted) cancel();
|
|
583
|
+
releaseControls = onActive?.({ kernel, scope: copy(scope), sessionId, runId: id, wake });
|
|
584
|
+
invariant(releaseControls === undefined || typeof releaseControls === 'function', 'NATIVE_KERNEL_EXECUTION_CALLBACK_INVALID');
|
|
585
|
+
for (;;) {
|
|
586
|
+
guard(); const version = generation; applyControls(sessionId);
|
|
587
|
+
snapshot = await kernel.runUntilIdle(scope, id); guard(); project(run);
|
|
588
|
+
if (terminal(snapshot.phase) || !resolved.withExecution) return copy(snapshot);
|
|
589
|
+
if (onIdle && snapshot.phase === 'awaiting_reconciliation') {
|
|
590
|
+
const idle = new AbortController(), scoped = AbortSignal.any([lifetime.signal, idle.signal, ...(signal ? [signal] : [])]);
|
|
591
|
+
const fence = runStore.load(scope, id).fence;
|
|
592
|
+
const changed = (current = runStore.load(scope, id)) => generation !== version
|
|
593
|
+
|| current.fence !== fence || current.snapshot.revision !== snapshot.revision
|
|
594
|
+
|| current.commands.some(row => !row.consumed)
|
|
595
|
+
|| Boolean(db.prepare("SELECT 1 FROM managed_commands WHERE session_id=? AND state='accepted' AND json_extract(data,'$.command_type')!='enqueue' AND json_extract(receipt,'$.run_id')=? LIMIT 1").get(sessionId, id));
|
|
596
|
+
try {
|
|
597
|
+
if (changed()) continue;
|
|
598
|
+
const waiting = waitForCommand(version, snapshot, idle.signal, changed);
|
|
599
|
+
const answer = Promise.resolve().then(() => { scoped.throwIfAborted();
|
|
600
|
+
return onIdle(copy(snapshot), { signal: scoped, assertCurrent() {
|
|
601
|
+
guard(); scoped.throwIfAborted(); invariant(!changed(), 'NATIVE_KERNEL_IDLE_AUTHORITY_LOST'); return true;
|
|
602
|
+
} }); }).then(command => ({ command }), error => {
|
|
603
|
+
// A durable answer or command retires this idle attempt.
|
|
604
|
+
// It can settle between the presenter's own authority
|
|
605
|
+
// check and this loop's re-check, so losing idle authority
|
|
606
|
+
// must re-derive from durable state instead of failing
|
|
607
|
+
// the Run with a transient NATIVE_KERNEL_IDLE_AUTHORITY_LOST.
|
|
608
|
+
if (error?.code === 'NATIVE_KERNEL_IDLE_AUTHORITY_LOST') return { woken: true };
|
|
609
|
+
throw error;
|
|
610
|
+
});
|
|
611
|
+
const result = await Promise.race([answer, waiting.then(() => ({ woken: true }))]);
|
|
612
|
+
guard();
|
|
613
|
+
if (result.woken || changed()) continue;
|
|
614
|
+
scoped.throwIfAborted();
|
|
615
|
+
if (result.command) {
|
|
616
|
+
// The Host may request the separately fenced read of this
|
|
617
|
+
// original receipt. It cannot approve or resume a Server
|
|
618
|
+
// interaction, create input, or re-run the original tool.
|
|
619
|
+
invariant(result.command.kind === 'reconcile_tool'
|
|
620
|
+
&& result.command.payload?.originalOperationKey === snapshot.toolReconciliation?.operationKey,
|
|
621
|
+
'NATIVE_KERNEL_IDLE_COMMAND_INVALID');
|
|
622
|
+
const receipt = kernel.submit(scope, id, result.command);
|
|
623
|
+
invariant(receipt.status !== 'rejected', 'NATIVE_KERNEL_IDLE_COMMAND_INVALID');
|
|
624
|
+
} else await waiting;
|
|
625
|
+
} catch (error) { guard(); if (!changed()) throw error; }
|
|
626
|
+
finally { idle.abort(new Error('Native idle attempt retired')); }
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
// A whole-Session owner stays open through pause/approval.
|
|
630
|
+
// Only this Native kernel consumes the durable next command.
|
|
631
|
+
await waitForCommand(version, snapshot);
|
|
632
|
+
}
|
|
633
|
+
} finally { try { if (typeof releaseControls === 'function') releaseControls(); }
|
|
634
|
+
finally { signal?.removeEventListener('abort', cancel); } }
|
|
635
|
+
};
|
|
636
|
+
invariant(resolved.withExecution === undefined || typeof resolved.withExecution === 'function', 'NATIVE_KERNEL_BINDING_CHANGED');
|
|
637
|
+
if ((!prior || !terminal(prior.phase)) && !sessionCancelPending(id)) await resolved.beforeExecute?.({
|
|
638
|
+
configDigest: hash(storedConfiguration), signal: lifetime.signal });
|
|
639
|
+
guard();
|
|
640
|
+
if (resolved.withExecution) {
|
|
641
|
+
let result;
|
|
642
|
+
try { result = await resolved.withExecution({ identity: copy(identity), configuration: parseNativeJson(run.config),
|
|
643
|
+
signal: lifetime.signal, execute }); }
|
|
644
|
+
finally { boundaryOpen = false; }
|
|
645
|
+
guard(); invariant(executed && snapshot && canonical(result) === canonical(snapshot), 'NATIVE_KERNEL_EXECUTION_RESULT_INVALID');
|
|
646
|
+
} else await execute();
|
|
647
|
+
if (!terminal(snapshot.phase)) { failures.delete(sessionId); return; }
|
|
648
|
+
await resolved.afterTerminal?.({ snapshot: copy(snapshot), signal: lifetime.signal });
|
|
649
|
+
guard(); failures.delete(sessionId);
|
|
650
|
+
transaction(() => {
|
|
651
|
+
db.prepare("UPDATE managed_commands SET state='settled' WHERE command_id=?").run(row.command_id);
|
|
652
|
+
db.prepare('DELETE FROM managed_session_cancels WHERE run_id=?').run(id);
|
|
653
|
+
});
|
|
654
|
+
} finally { executing.delete(id); if (kernels.get(id) === kernel) kernels.delete(id); }
|
|
655
|
+
} finally { await resolved?.release?.({ scope: copy(scope), sessionId, runId: id, stage: 'execute', signal: lifetime.signal }); }
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
function start(sessionId) {
|
|
659
|
+
if (active.has(sessionId)) return active.get(sessionId);
|
|
660
|
+
retryAfter.delete(sessionId);
|
|
661
|
+
const startedGeneration = generation;
|
|
662
|
+
const work = drive(sessionId).catch(error => {
|
|
663
|
+
// Trusted Host diagnostics only. An observer cannot replace the error,
|
|
664
|
+
// retry work, or authorize any Native effect by throwing/rejecting.
|
|
665
|
+
try { Promise.resolve(onWorkerError?.({ sessionId, error })).catch(() => {}); } catch {}
|
|
666
|
+
failures.set(sessionId, error.code?.startsWith('execution_grant_') ? error.code : ['NATIVE_KERNEL_BINDING_CHANGED', 'NATIVE_KERNEL_AUTHORITY_LOST', 'lease_busy', 'stale_fence'].includes(error.code)
|
|
667
|
+
? error.code : 'NATIVE_KERNEL_WORKER_FAILED');
|
|
668
|
+
if (error.code === 'NATIVE_KERNEL_REMOTE_HOST_RETRY' && schedulingEnabled && !closed)
|
|
669
|
+
retryAfter.set(sessionId, Date.now() + 2000);
|
|
670
|
+
if (error.code === 'lease_busy' && schedulingEnabled && !closed) {
|
|
671
|
+
// A cold Host can be ready before the killed process's durable lease
|
|
672
|
+
// expires. Wait for that boundary; a status read or replacement user
|
|
673
|
+
// command must not be needed to wake the original accepted command.
|
|
674
|
+
let expiresAt = Date.now() + 1000;
|
|
675
|
+
try {
|
|
676
|
+
const row = db.prepare("SELECT r.* FROM managed_runs r JOIN managed_commands c ON r.command_id=c.command_id WHERE c.session_id=? AND c.state='accepted' ORDER BY c.rowid LIMIT 1").get(sessionId);
|
|
677
|
+
if (row) expiresAt = runStore.load(parseNativeJson(row.scope), row.run_id).lease?.expiresAt ?? expiresAt;
|
|
678
|
+
} catch { /* Keep bounded retry; original error remains authoritative. */ }
|
|
679
|
+
retryAfter.set(sessionId, Date.now() + Math.max(50, Math.min(60000, expiresAt - Date.now() + 25)));
|
|
680
|
+
}
|
|
681
|
+
throw error;
|
|
682
|
+
})
|
|
683
|
+
.finally(() => { active.delete(sessionId); planRetry(); if (generation !== startedGeneration) schedule(); });
|
|
684
|
+
active.set(sessionId, work); void work.catch(() => {}); return work;
|
|
685
|
+
}
|
|
686
|
+
function planRetry() {
|
|
687
|
+
clearTimeout(retryTimer); retryTimer = undefined;
|
|
688
|
+
if (!schedulingEnabled || closed || !retryAfter.size) return;
|
|
689
|
+
let next = Infinity;
|
|
690
|
+
for (const deadline of retryAfter.values()) next = Math.min(next, deadline);
|
|
691
|
+
retryTimer = setTimeout(() => {
|
|
692
|
+
retryTimer = undefined;
|
|
693
|
+
if (closed) return;
|
|
694
|
+
try {
|
|
695
|
+
guard();
|
|
696
|
+
for (const [sessionId, deadline] of retryAfter) if (deadline <= Date.now()) {
|
|
697
|
+
retryAfter.delete(sessionId); void start(sessionId).catch(() => {});
|
|
698
|
+
}
|
|
699
|
+
planRetry();
|
|
700
|
+
} catch { /* Authority failure is visible through explicit status/drain. */ }
|
|
701
|
+
}, Math.max(0, next - Date.now()));
|
|
702
|
+
}
|
|
703
|
+
function schedule() {
|
|
704
|
+
if (!schedulingEnabled || closed || timer) return;
|
|
705
|
+
timer = setTimeout(() => { timer = undefined; if (closed) return;
|
|
706
|
+
try { guard(); for (const sessionId of grants.readySessions()) void start(sessionId).catch(() => {}); }
|
|
707
|
+
catch { /* Explicit status/drain reports authority failure. */ }
|
|
708
|
+
}, 0);
|
|
709
|
+
}
|
|
710
|
+
function wake() { generation++; for (const notify of [...wakeWaiters]) notify(); schedule(); }
|
|
711
|
+
async function drain(sessionId) { guard(); scopedControls.drain(); return start(sessionId); }
|
|
712
|
+
// Trusted Host-only reads. Unlike getStatus this does not project events or
|
|
713
|
+
// consume a Server nonce, and it never starts an accepted command. The HTTP
|
|
714
|
+
// transport deliberately does not expose this composition port.
|
|
715
|
+
function inspectSession({ scope, sessionId, runId }) {
|
|
716
|
+
guard(); scopeKey(scope);
|
|
717
|
+
invariant(scope.tenantId === bindingTarget.tenantId && scope.agentId === runScopeAgentId
|
|
718
|
+
&& text(sessionId) && (runId === undefined || text(runId)), 'NATIVE_MANAGED_STATUS_IDENTITY_MISMATCH');
|
|
719
|
+
const firstAccepted = db.prepare("SELECT r.* FROM managed_runs r JOIN managed_commands c ON r.command_id=c.command_id WHERE r.session_id=? AND c.state='accepted' ORDER BY r.rowid LIMIT 1").get(sessionId);
|
|
720
|
+
const row = runId === undefined ? firstAccepted
|
|
721
|
+
?? db.prepare('SELECT * FROM managed_runs WHERE session_id=? ORDER BY rowid DESC LIMIT 1').get(sessionId) : runRow(runId);
|
|
722
|
+
if (!row) return null;
|
|
723
|
+
invariant(row.session_id === sessionId && row.scope === canonical(scope), 'NATIVE_MANAGED_STATUS_IDENTITY_MISMATCH');
|
|
724
|
+
const command = commandRow(row.command_id), configuration = parseNativeJson(row.config);
|
|
725
|
+
invariant(command?.session_id === sessionId, 'NATIVE_MANAGED_STATUS_IDENTITY_MISMATCH');
|
|
726
|
+
let record = null;
|
|
727
|
+
try { record = runStore.load(scope, row.run_id); }
|
|
728
|
+
catch (error) { if (error.code !== 'run_not_found') throw error; }
|
|
729
|
+
invariant(!record || record.snapshot.sessionId === sessionId && record.snapshot.runId === row.run_id
|
|
730
|
+
&& record.snapshot.turnId === row.command_id && record.snapshot.buildId === row.build_id
|
|
731
|
+
&& record.snapshot.configDigest === hash(configuration) && canonical(record.configuration) === row.config,
|
|
732
|
+
'NATIVE_MANAGED_STATUS_IDENTITY_MISMATCH');
|
|
733
|
+
const phase = record?.snapshot.phase ?? 'admitted';
|
|
734
|
+
return { contract: MANAGED_NATIVE_KERNEL_CONTRACT, scope: copy(scope), sessionId, runId: row.run_id,
|
|
735
|
+
commandId: row.command_id, buildId: row.build_id, configDigest: hash(configuration),
|
|
736
|
+
commandState: command.state, record, active: active.has(sessionId) && firstAccepted?.run_id === row.run_id,
|
|
737
|
+
executing: executing.has(row.run_id),
|
|
738
|
+
executionGrant: grants.inspect(command),
|
|
739
|
+
workerError: failures.get(sessionId) ?? null,
|
|
740
|
+
retryable: command.state === 'accepted' && firstAccepted?.run_id === row.run_id && !active.has(sessionId)
|
|
741
|
+
&& !grants.claimError(command)
|
|
742
|
+
&& (!record?.lease || record.lease.expiresAt <= clock())
|
|
743
|
+
&& !['paused', 'awaiting_interaction', 'awaiting_reconciliation', 'interrupted'].includes(phase) };
|
|
744
|
+
}
|
|
745
|
+
function retryAcceptedRun(query) {
|
|
746
|
+
// Re-drive only the original durable admission. This cannot enqueue a
|
|
747
|
+
// resume/approval/reconciliation command or override an unknown effect.
|
|
748
|
+
invariant(text(query?.runId), 'NATIVE_MANAGED_STATUS_IDENTITY_MISMATCH');
|
|
749
|
+
const view = inspectSession(query);
|
|
750
|
+
invariant(view, 'NATIVE_MANAGED_STATUS_IDENTITY_MISMATCH');
|
|
751
|
+
if (view.commandState === 'settled' || view.active) return view;
|
|
752
|
+
invariant(view.retryable, 'NATIVE_MANAGED_SERVER_CONTROL_REQUIRED');
|
|
753
|
+
void start(query.sessionId).catch(() => {});
|
|
754
|
+
return inspectSession(query);
|
|
755
|
+
}
|
|
756
|
+
function readChildHistory(query, { result = false, inventory = false, liveTasks } = {}) {
|
|
757
|
+
const inspected = inspectSession(query);
|
|
758
|
+
invariant(inspected, 'NATIVE_MANAGED_STATUS_IDENTITY_MISMATCH');
|
|
759
|
+
const history = createNativeChildHistory({ scope: inspected.scope, store: runStore, liveTasks });
|
|
760
|
+
return history[inventory ? 'inventory' : result ? 'result' : 'list'](query);
|
|
761
|
+
}
|
|
762
|
+
function readChildRecord(query) {
|
|
763
|
+
const inspected = inspectSession(query);
|
|
764
|
+
invariant(inspected?.record, 'NATIVE_MANAGED_STATUS_IDENTITY_MISMATCH');
|
|
765
|
+
const history = createNativeChildHistory({ scope: inspected.scope, store: runStore,
|
|
766
|
+
liveTasks: id => {
|
|
767
|
+
const kernel = kernels.get(id);
|
|
768
|
+
return kernel && runStore.load(inspected.scope, id).configuration.childLifecyclePolicy === 'owned-background/v2'
|
|
769
|
+
? kernel.childTasks(inspected.scope, id) : [];
|
|
770
|
+
} });
|
|
771
|
+
return history.record({ ...query, runId: inspected.runId });
|
|
772
|
+
}
|
|
773
|
+
function facts(sessionId, after = 0, limit = null) {
|
|
774
|
+
guard(); invariant(text(sessionId) && Number.isSafeInteger(after) && after >= 0, 'NATIVE_KERNEL_CURSOR_INVALID');
|
|
775
|
+
invariant(limit === null || Number.isSafeInteger(limit) && limit >= 1 && limit <= 100, 'NATIVE_KERNEL_CURSOR_INVALID');
|
|
776
|
+
for (const row of db.prepare('SELECT * FROM managed_runs WHERE session_id=? ORDER BY rowid').all(sessionId)) project(row);
|
|
777
|
+
const rows = limit === null ? db.prepare('SELECT data FROM managed_events WHERE session_id=? AND seq>? ORDER BY seq').all(sessionId, after)
|
|
778
|
+
: db.prepare('SELECT data FROM managed_events WHERE session_id=? AND seq>? ORDER BY seq LIMIT ?').all(sessionId, after, limit);
|
|
779
|
+
return rows.map(row => parseNativeJson(row.data));
|
|
780
|
+
}
|
|
781
|
+
const events = Object.freeze({ async read(sessionId, after = 0, limit = 100, { signal } = {}) {
|
|
782
|
+
guard(); signal?.throwIfAborted();
|
|
783
|
+
const rows = facts(sessionId, after, limit);
|
|
784
|
+
signal?.throwIfAborted(); guard(); return rows;
|
|
785
|
+
}, async *subscribe(sessionId, after = 0, { signal, expiresAt, heartbeatMs } = {}) {
|
|
786
|
+
let cursor = after;
|
|
787
|
+
let lastOutput = Date.now();
|
|
788
|
+
for (;;) {
|
|
789
|
+
guard(); signal?.throwIfAborted();
|
|
790
|
+
if (expiresAt !== undefined && clock() >= expiresAt) return;
|
|
791
|
+
const page = facts(sessionId, cursor, 100);
|
|
792
|
+
for (const fact of page) {
|
|
793
|
+
signal?.throwIfAborted(); guard();
|
|
794
|
+
if (expiresAt !== undefined && clock() >= expiresAt) return;
|
|
795
|
+
cursor = fact.seq; lastOutput = Date.now(); yield fact;
|
|
796
|
+
}
|
|
797
|
+
if (page.length === 100) continue;
|
|
798
|
+
if (heartbeatMs && Date.now() - lastOutput >= heartbeatMs && clock() < expiresAt) { lastOutput = Date.now(); yield null; }
|
|
799
|
+
await delay(20, undefined, { signal: signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal });
|
|
800
|
+
}
|
|
801
|
+
} });
|
|
802
|
+
function phaseOf(row) {
|
|
803
|
+
try { return runStore.load(parseNativeJson(row.scope), row.run_id).snapshot.phase; }
|
|
804
|
+
catch (error) { if (error.code !== 'run_not_found') throw error; }
|
|
805
|
+
return commandRow(row.command_id).state === 'discarded' ? 'discarded' : 'pending';
|
|
806
|
+
}
|
|
807
|
+
function platformCapabilities() {
|
|
808
|
+
const unavailable = platformCapability(false);
|
|
809
|
+
return { schema_version: 1, cancel: platformCapability(true), pause: platformCapability(true), resume: platformCapability(true),
|
|
810
|
+
submit_interaction: platformCapability(platformApprovals), interaction_mode: platformApprovals ? 'durable_resume' : 'unavailable',
|
|
811
|
+
attach: unavailable, steer: platformCapability(true), inject: platformCapability(true), checkpoint: unavailable,
|
|
812
|
+
durable_restore: platformCapability(true), scoped_cancel: platformCapability(scopedControls.supported) };
|
|
813
|
+
}
|
|
814
|
+
async function platformStatus(query, permit) {
|
|
815
|
+
const { request, authorization } = await authenticate(query, permit, 'get_status');
|
|
816
|
+
const session = request.session_id ?? null;
|
|
817
|
+
check(request.schema_version === 1 && (session === null || text(session)));
|
|
818
|
+
invariant(authorization.sessionId === session, 'NATIVE_KERNEL_PERMIT_INVALID');
|
|
819
|
+
const rows = session === null ? db.prepare('SELECT * FROM managed_runs ORDER BY rowid').all()
|
|
820
|
+
: db.prepare('SELECT * FROM managed_runs WHERE session_id=? ORDER BY rowid').all(session);
|
|
821
|
+
let selected, phase;
|
|
822
|
+
for (const row of rows) {
|
|
823
|
+
if (session !== null) project(row);
|
|
824
|
+
const state = platformRunState(phaseOf(row));
|
|
825
|
+
if (state && (!selected || phase === 'pending' && state !== 'pending')) { selected = row; phase = state; }
|
|
826
|
+
}
|
|
827
|
+
const watermark = session === null ? null : db.prepare('SELECT COALESCE(MAX(seq),0) AS seq FROM managed_events WHERE session_id=?').get(session).seq;
|
|
828
|
+
const depth = session === null ? db.prepare("SELECT COUNT(*) AS count FROM managed_commands WHERE state='accepted'").get().count
|
|
829
|
+
: db.prepare("SELECT COUNT(*) AS count FROM managed_commands WHERE state='accepted' AND session_id=?").get(session).count;
|
|
830
|
+
return { schema_version: 1, agent_instance_id: bindingTarget.agentInstanceId,
|
|
831
|
+
instance_state: schedulingEnabled && !(session === null ? failures.size : failures.has(session)) ? 'ready' : 'degraded',
|
|
832
|
+
session_id: session ?? selected?.session_id ?? null, session_event_seq: watermark,
|
|
833
|
+
active_run_id: selected?.run_id ?? null, active_run_state: phase ?? null,
|
|
834
|
+
inbox_depth: depth, activation_id: null, lease_expires_at: null,
|
|
835
|
+
capability: platformCapabilities() };
|
|
836
|
+
}
|
|
837
|
+
async function platformEvents(query, permit, { signal } = {}) {
|
|
838
|
+
const { request, authorization } = await authenticate(query, permit, 'subscribe_events');
|
|
839
|
+
invariant(authorization.sessionId === request.session_id && Number.isSafeInteger(authorization.expiresAt), 'NATIVE_KERNEL_PERMIT_INVALID');
|
|
840
|
+
invariant(text(request.session_id) && Number.isSafeInteger(request.after_seq) && request.after_seq >= 0, 'NATIVE_KERNEL_CURSOR_INVALID');
|
|
841
|
+
invariant(db.prepare('SELECT 1 FROM managed_runs WHERE session_id=? LIMIT 1').get(request.session_id), 'NATIVE_KERNEL_SESSION_NOT_FOUND');
|
|
842
|
+
return { epoch: hash({ eventSource, sessionId: request.session_id }).slice(0, 32),
|
|
843
|
+
events: events.subscribe(request.session_id, request.after_seq, { signal, expiresAt: authorization.expiresAt, heartbeatMs: 15000 }) };
|
|
844
|
+
}
|
|
845
|
+
function sessionDeliveryBinding({ scope, sessionId, runId, configDigest }) {
|
|
846
|
+
guard();
|
|
847
|
+
const row = runRow(runId), configuration = row && parseNativeJson(row.config);
|
|
848
|
+
invariant(row?.session_id === sessionId && row.scope === canonical(scope)
|
|
849
|
+
&& configuration.hostRecoveryBinding?.sessionDelivery === true
|
|
850
|
+
&& hash(configuration) === configDigest, 'NATIVE_KERNEL_STATUS_IDENTITY_MISMATCH');
|
|
851
|
+
return { row, ref: configuration.hostRecoveryBinding.ref };
|
|
852
|
+
}
|
|
853
|
+
function readSessionFrames(request) {
|
|
854
|
+
const { runId, ref, after } = request;
|
|
855
|
+
invariant(text(ref) && Number.isSafeInteger(after) && after >= 0, 'NATIVE_KERNEL_CURSOR_INVALID');
|
|
856
|
+
invariant(sessionDeliveryBinding(request).ref === ref, 'NATIVE_KERNEL_STATUS_IDENTITY_MISMATCH');
|
|
857
|
+
return sessionFrames.read(runId, after);
|
|
858
|
+
}
|
|
859
|
+
function cancelSessionDelivery(request) {
|
|
860
|
+
const { scope, runId, ref } = request;
|
|
861
|
+
const binding = sessionDeliveryBinding(request);
|
|
862
|
+
invariant(binding.ref === ref, 'NATIVE_KERNEL_STATUS_IDENTITY_MISMATCH');
|
|
863
|
+
const state = commandRow(binding.row.command_id).state;
|
|
864
|
+
if (state === 'settled' || state === 'discarded') return { status: 'terminal' };
|
|
865
|
+
invariant(state === 'accepted', 'NATIVE_KERNEL_STATUS_IDENTITY_MISMATCH');
|
|
866
|
+
const phase = sessionRunPhase(scope, runId);
|
|
867
|
+
if (phase !== null && terminal(phase)) return { status: 'terminal' };
|
|
868
|
+
transaction(() => db.prepare('INSERT OR IGNORE INTO managed_session_cancels VALUES (?)').run(runId));
|
|
869
|
+
submitSessionCancel(scope, runId, kernels.get(runId), phase);
|
|
870
|
+
wake();
|
|
871
|
+
return { status: 'accepted' };
|
|
872
|
+
}
|
|
873
|
+
try { guard(); injections.deliver(); projectAll(); wake(); }
|
|
874
|
+
catch (error) { clearInterval(scopedTimer); runStore.close(); db.close(); throw error; }
|
|
875
|
+
return Object.freeze({ contract: MANAGED_NATIVE_KERNEL_CONTRACT, receive, drain, events, inspectSession, retryAcceptedRun, readChildHistory, readChildRecord,
|
|
876
|
+
readSessionFrames,
|
|
877
|
+
cancelSessionDelivery,
|
|
878
|
+
restoreSessionDelivery(request) {
|
|
879
|
+
const { row, ref } = sessionDeliveryBinding(request);
|
|
880
|
+
const command = parseNativeJson(commandRow(row.command_id).data);
|
|
881
|
+
return { ref, input: command.payload.content };
|
|
882
|
+
},
|
|
883
|
+
terminalSessionFrames(runId) { guard(); return sessionFrames.tail(runId); },
|
|
884
|
+
executionGrants: grants.api,
|
|
885
|
+
teamsContexts: teamsContexts.api,
|
|
886
|
+
teamsCallbacks,
|
|
887
|
+
presentA2aInteraction: request => interactions.present(request),
|
|
888
|
+
startRecovery() { guard(); schedulingEnabled = true; scopedControls.drain(); schedule(); },
|
|
889
|
+
capabilities: Object.freeze({ storage: 'single-machine/sqlite/v1', commands: Object.freeze([...supported]),
|
|
890
|
+
enqueueContentFormats: Object.freeze([...(resolveBinding.enqueueContentFormats ?? [])]),
|
|
891
|
+
inject: true, injectionPolicy: 'next-turn-inbox/v1', scopedInterrupt: scopedControls.supported, resumeTargets: Object.freeze(['run']), structuredInput: !platformApprovals && typeof authorizeInteraction === 'function',
|
|
892
|
+
approval: typeof authorizeInteraction === 'function', executionGrants: true,
|
|
893
|
+
teamsContextRegistry: true, teamsCallbackAuthorization: teamsCallbacks !== null, teamsContext: false, executionPolicy: false }),
|
|
894
|
+
async getStatus(query, permit) {
|
|
895
|
+
const { request } = await authenticate(query, permit, 'get_status');
|
|
896
|
+
check(text(request.session_id)); projectAll();
|
|
897
|
+
const rows = db.prepare('SELECT * FROM managed_runs WHERE session_id=? ORDER BY rowid').all(request.session_id);
|
|
898
|
+
return { contract: MANAGED_NATIVE_KERNEL_CONTRACT, runs: rows.map(row => ({ runId: row.run_id, phase: phaseOf(row) })),
|
|
899
|
+
workerError: failures.get(request.session_id) ?? null };
|
|
900
|
+
},
|
|
901
|
+
platformStatus,
|
|
902
|
+
platformEvents,
|
|
903
|
+
probePlatform() {
|
|
904
|
+
guard();
|
|
905
|
+
db.prepare('SELECT version FROM managed_schema LIMIT 1').get();
|
|
906
|
+
runStore.probe();
|
|
907
|
+
return { workerRunning: schedulingEnabled, capabilities: platformCapabilities() };
|
|
908
|
+
},
|
|
909
|
+
async subscribe(query, permit, options = {}) {
|
|
910
|
+
const { request } = await authenticate(query, permit, 'subscribe_events');
|
|
911
|
+
invariant(text(request.session_id) && Number.isSafeInteger(request.after_seq ?? 0) && (request.after_seq ?? 0) >= 0,
|
|
912
|
+
'NATIVE_KERNEL_CURSOR_INVALID');
|
|
913
|
+
return events.subscribe(request.session_id, request.after_seq ?? 0, options);
|
|
914
|
+
},
|
|
915
|
+
close() {
|
|
916
|
+
if (closing) return closing;
|
|
917
|
+
closed = true; clearTimeout(timer); clearTimeout(retryTimer); clearInterval(scopedTimer); retryAfter.clear(); lifetime.abort(new Error('Native owner closed'));
|
|
918
|
+
closing = Promise.allSettled([...active.values(), scopedControls.close()]).then(() => { runStore.close(); db.close(); });
|
|
919
|
+
return closing;
|
|
920
|
+
},
|
|
921
|
+
});
|
|
922
|
+
}
|