durebak 0.1.0-alpha.2 → 0.1.0-alpha.22
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/README.md +10 -4
- package/SECURITY.md +2 -1
- package/dist/bridge-heartbeat.d.ts +14 -0
- package/dist/bridge-heartbeat.js +49 -0
- package/dist/cli.js +56 -2
- package/dist/client.d.ts +4 -2
- package/dist/client.js +2 -2
- package/dist/codex-owned-host.d.ts +26 -0
- package/dist/codex-owned-host.js +190 -0
- package/dist/codex-rpc.d.ts +36 -0
- package/dist/codex-rpc.js +142 -0
- package/dist/codex-turns.d.ts +101 -0
- package/dist/codex-turns.js +207 -0
- package/dist/collaboration-status.d.ts +38 -0
- package/dist/collaboration-status.js +14 -0
- package/dist/continuations.d.ts +36 -0
- package/dist/continuations.js +103 -0
- package/dist/database.js +24 -5
- package/dist/doctor.d.ts +17 -16
- package/dist/doctor.js +33 -9
- package/dist/execution-driver.d.ts +165 -0
- package/dist/execution-driver.js +233 -0
- package/dist/harnesses/catalog.d.ts +28 -0
- package/dist/harnesses/catalog.js +16 -0
- package/dist/health.d.ts +23 -0
- package/dist/health.js +12 -0
- package/dist/managed-control.d.ts +128 -0
- package/dist/managed-control.js +119 -0
- package/dist/mcp.js +58 -1
- package/dist/message-queue.d.ts +7 -0
- package/dist/message-queue.js +58 -0
- package/dist/migrations.d.ts +1 -1
- package/dist/migrations.js +189 -1
- package/dist/native-bootstrap-sandbox.d.ts +10 -0
- package/dist/native-bootstrap-sandbox.js +83 -0
- package/dist/native-peer-inspector.d.ts +29 -0
- package/dist/native-peer-inspector.js +131 -0
- package/dist/native-profile-fence.d.ts +29 -0
- package/dist/native-profile-fence.js +142 -0
- package/dist/opencode-http.d.ts +15 -0
- package/dist/opencode-http.js +143 -0
- package/dist/opencode-outcomes.d.ts +10 -0
- package/dist/opencode-outcomes.js +72 -0
- package/dist/opencode-owned-host.d.ts +41 -0
- package/dist/opencode-owned-host.js +230 -0
- package/dist/opencode-readiness.d.ts +8 -0
- package/dist/opencode-readiness.js +32 -0
- package/dist/opencode-turns.d.ts +130 -0
- package/dist/opencode-turns.js +238 -0
- package/dist/owned-native-command.d.ts +20 -0
- package/dist/owned-native-command.js +92 -0
- package/dist/owned-peer-connector.d.ts +19 -0
- package/dist/owned-peer-connector.js +79 -0
- package/dist/protected-tasks.d.ts +37 -0
- package/dist/protected-tasks.js +87 -0
- package/dist/request-preview.d.ts +55 -0
- package/dist/request-preview.js +77 -0
- package/dist/requests.d.ts +250 -0
- package/dist/requests.js +303 -0
- package/dist/runtime.d.ts +190 -0
- package/dist/runtime.js +138 -6
- package/dist/scoped-attachments.d.ts +92 -0
- package/dist/scoped-attachments.js +75 -0
- package/dist/setup.d.ts +4 -0
- package/dist/setup.js +1 -1
- package/dist/skill-content.d.ts +3 -0
- package/dist/skill-content.js +125 -0
- package/dist/skills.d.ts +14 -0
- package/dist/skills.js +82 -0
- package/dist/store.d.ts +469 -0
- package/dist/store.js +109 -52
- package/dist/verification.d.ts +245 -0
- package/dist/verification.js +113 -0
- package/dist/work-input.d.ts +97 -0
- package/dist/work-input.js +83 -0
- package/dist/work-reservations.d.ts +56 -0
- package/dist/work-reservations.js +169 -0
- package/docs/USAGE.md +115 -1
- package/package.json +2 -2
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { TextDecoder } from 'node:util';
|
|
2
|
+
const ignoreLateStreamError = () => { };
|
|
3
|
+
// Internal transport only, not execution authority. The owned driver must
|
|
4
|
+
// validate native identity, permission provenance and durable attempt receipts.
|
|
5
|
+
export class CodexRpc {
|
|
6
|
+
input;
|
|
7
|
+
output;
|
|
8
|
+
options;
|
|
9
|
+
pending = new Map();
|
|
10
|
+
sequence = 0;
|
|
11
|
+
buffer = Buffer.alloc(0);
|
|
12
|
+
closed = false;
|
|
13
|
+
timeoutMs;
|
|
14
|
+
maxLineBytes;
|
|
15
|
+
maxPending;
|
|
16
|
+
constructor(input, output, options = {}) {
|
|
17
|
+
this.input = input;
|
|
18
|
+
this.output = output;
|
|
19
|
+
this.options = options;
|
|
20
|
+
this.timeoutMs = options.timeoutMs ?? 20000;
|
|
21
|
+
this.maxLineBytes = options.maxLineBytes ?? 262144;
|
|
22
|
+
this.maxPending = options.maxPending ?? 32;
|
|
23
|
+
for (const n of [this.timeoutMs, this.maxLineBytes, this.maxPending])
|
|
24
|
+
if (!Number.isSafeInteger(n) || n < 1)
|
|
25
|
+
throw new Error('rpc_invalid_limits');
|
|
26
|
+
input.on('data', this.data);
|
|
27
|
+
input.on('end', this.end);
|
|
28
|
+
input.on('close', this.end);
|
|
29
|
+
input.on('error', this.readError);
|
|
30
|
+
output.on('error', this.writeError);
|
|
31
|
+
output.on('close', this.end);
|
|
32
|
+
}
|
|
33
|
+
terminate(code) { if (this.closed)
|
|
34
|
+
return; this.closed = true; this.buffer = Buffer.alloc(0); for (const p of this.pending.values()) {
|
|
35
|
+
clearTimeout(p.timer);
|
|
36
|
+
p.reject(new Error(code));
|
|
37
|
+
} this.pending.clear(); this.detach(); }
|
|
38
|
+
end = () => this.terminate('rpc_closed');
|
|
39
|
+
readError = () => this.terminate('rpc_read_failed');
|
|
40
|
+
writeError = () => this.terminate('rpc_write_failed');
|
|
41
|
+
write(value) { const bytes = Buffer.from(JSON.stringify(value) + '\n'); if (bytes.length - 1 > this.maxLineBytes)
|
|
42
|
+
throw new Error('rpc_frame_too_large'); try {
|
|
43
|
+
if (!this.output.write(bytes, error => { if (error)
|
|
44
|
+
this.writeError(); }))
|
|
45
|
+
this.terminate('rpc_backpressure');
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
this.writeError();
|
|
49
|
+
} }
|
|
50
|
+
message(raw) {
|
|
51
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
52
|
+
throw new Error('rpc_protocol_error');
|
|
53
|
+
const m = raw, hasId = Object.hasOwn(m, 'id'), hasMethod = Object.hasOwn(m, 'method'), hasResult = Object.hasOwn(m, 'result'), hasError = Object.hasOwn(m, 'error');
|
|
54
|
+
if (hasId && !(typeof m.id === 'string' || Number.isSafeInteger(m.id)))
|
|
55
|
+
throw new Error('rpc_protocol_error');
|
|
56
|
+
if (hasMethod) {
|
|
57
|
+
if (typeof m.method !== 'string' || !m.method.length || hasResult || hasError)
|
|
58
|
+
throw new Error('rpc_protocol_error');
|
|
59
|
+
// Host requests use a separate id namespace. Never treat an approval or
|
|
60
|
+
// dynamic tool request as a response; no peer data grants local execution.
|
|
61
|
+
if (hasId) {
|
|
62
|
+
this.write({ id: m.id, error: { code: -32601, message: 'unsupported_host_request' } });
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
this.options.onNotification?.({ method: m.method, ...(Object.hasOwn(m, 'params') ? { params: m.params } : {}) });
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
throw new Error('rpc_notification_failed');
|
|
70
|
+
}
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (!hasId || hasResult === hasError || Object.hasOwn(m, 'params'))
|
|
74
|
+
throw new Error('rpc_protocol_error');
|
|
75
|
+
if (hasError && (!m.error || typeof m.error !== 'object' || !Number.isSafeInteger(m.error.code)))
|
|
76
|
+
throw new Error('rpc_protocol_error');
|
|
77
|
+
const p = typeof m.id === 'number' ? this.pending.get(m.id) : undefined;
|
|
78
|
+
if (!p)
|
|
79
|
+
return;
|
|
80
|
+
this.pending.delete(m.id);
|
|
81
|
+
clearTimeout(p.timer);
|
|
82
|
+
if (hasError)
|
|
83
|
+
p.reject(new Error(`rpc_remote_error:${m.error.code}`));
|
|
84
|
+
else
|
|
85
|
+
p.resolve(m.result);
|
|
86
|
+
}
|
|
87
|
+
data = (chunk) => {
|
|
88
|
+
if (this.closed)
|
|
89
|
+
return;
|
|
90
|
+
try {
|
|
91
|
+
this.buffer = Buffer.concat([this.buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
|
|
92
|
+
let newline;
|
|
93
|
+
while ((newline = this.buffer.indexOf(10)) >= 0) {
|
|
94
|
+
if (newline > this.maxLineBytes)
|
|
95
|
+
throw new Error('rpc_frame_too_large');
|
|
96
|
+
const line = this.buffer.subarray(0, newline);
|
|
97
|
+
this.buffer = this.buffer.subarray(newline + 1);
|
|
98
|
+
this.message(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(line)));
|
|
99
|
+
if (this.closed)
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (this.buffer.length > this.maxLineBytes)
|
|
103
|
+
throw new Error('rpc_frame_too_large');
|
|
104
|
+
this.buffer = this.buffer.length ? Buffer.from(this.buffer) : Buffer.alloc(0);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
this.terminate(error instanceof Error && ['rpc_frame_too_large', 'rpc_notification_failed'].includes(error.message) ? error.message : 'rpc_protocol_error');
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
call(method, params) {
|
|
111
|
+
if (this.closed)
|
|
112
|
+
return Promise.reject(new Error('rpc_closed'));
|
|
113
|
+
if (typeof method !== 'string' || !method.length)
|
|
114
|
+
return Promise.reject(new Error('rpc_invalid_method'));
|
|
115
|
+
if (this.pending.size >= this.maxPending)
|
|
116
|
+
return Promise.reject(new Error('rpc_pending_limit'));
|
|
117
|
+
const id = ++this.sequence;
|
|
118
|
+
let frame;
|
|
119
|
+
try {
|
|
120
|
+
frame = Buffer.from(JSON.stringify({ id, method, params }) + '\n');
|
|
121
|
+
if (frame.length - 1 > this.maxLineBytes)
|
|
122
|
+
throw new Error('rpc_frame_too_large');
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return Promise.reject(new Error('rpc_frame_too_large'));
|
|
126
|
+
}
|
|
127
|
+
return new Promise((resolve, reject) => { const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('rpc_timeout')); }, this.timeoutMs); this.pending.set(id, { resolve, reject, timer }); try {
|
|
128
|
+
if (!this.output.write(frame, error => { if (error)
|
|
129
|
+
this.writeError(); }))
|
|
130
|
+
this.terminate('rpc_backpressure');
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
this.writeError();
|
|
134
|
+
} });
|
|
135
|
+
}
|
|
136
|
+
notify(method, params) { if (this.closed)
|
|
137
|
+
throw new Error('rpc_closed'); this.write({ method, params }); }
|
|
138
|
+
detach() { this.input.off('data', this.data); this.input.off('end', this.end); this.input.off('close', this.end); this.input.off('error', this.readError); this.output.off('error', this.writeError); this.output.off('close', this.end); for (const stream of [this.input, this.output])
|
|
139
|
+
if (!stream.listeners('error').includes(ignoreLateStreamError))
|
|
140
|
+
stream.on('error', ignoreLateStreamError); }
|
|
141
|
+
close() { this.terminate('rpc_closed'); }
|
|
142
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { CodexRpc } from './codex-rpc.js';
|
|
3
|
+
import { NativeProfileFence } from './native-profile-fence.js';
|
|
4
|
+
declare const bindingSchema: z.ZodObject<{
|
|
5
|
+
bindingId: z.ZodString;
|
|
6
|
+
epoch: z.ZodNumber;
|
|
7
|
+
instance: z.ZodString;
|
|
8
|
+
profile: z.ZodString;
|
|
9
|
+
nativeId: z.ZodString;
|
|
10
|
+
}, z.core.$strict>;
|
|
11
|
+
declare const identitySchema: z.ZodObject<{
|
|
12
|
+
bindingId: z.ZodString;
|
|
13
|
+
epoch: z.ZodNumber;
|
|
14
|
+
instance: z.ZodString;
|
|
15
|
+
profile: z.ZodString;
|
|
16
|
+
nativeId: z.ZodString;
|
|
17
|
+
attemptId: z.ZodString;
|
|
18
|
+
sourceDigest: z.ZodString;
|
|
19
|
+
}, z.core.$strict>;
|
|
20
|
+
type Binding = z.infer<typeof bindingSchema>;
|
|
21
|
+
type Identity = z.infer<typeof identitySchema>;
|
|
22
|
+
interface Options {
|
|
23
|
+
binding: Binding;
|
|
24
|
+
cwd: string;
|
|
25
|
+
permissionProfile: string;
|
|
26
|
+
}
|
|
27
|
+
export declare class CodexTurns {
|
|
28
|
+
private fence;
|
|
29
|
+
private rpc;
|
|
30
|
+
private db;
|
|
31
|
+
private ownerId;
|
|
32
|
+
private closed;
|
|
33
|
+
private submissions;
|
|
34
|
+
private binding;
|
|
35
|
+
private cwd;
|
|
36
|
+
private permissionProfile;
|
|
37
|
+
constructor(fence: NativeProfileFence, rpc: CodexRpc, options: Options);
|
|
38
|
+
private assertOwner;
|
|
39
|
+
private identity;
|
|
40
|
+
private row;
|
|
41
|
+
private outcome;
|
|
42
|
+
private unknown;
|
|
43
|
+
private thread;
|
|
44
|
+
health(): Promise<{
|
|
45
|
+
readiness: "busy" | "ready" | "unknown";
|
|
46
|
+
auth: "present" | "required";
|
|
47
|
+
entitlement: 'unverified';
|
|
48
|
+
} | {
|
|
49
|
+
readiness: 'unknown';
|
|
50
|
+
auth: 'unknown';
|
|
51
|
+
entitlement: 'unverified';
|
|
52
|
+
}>;
|
|
53
|
+
private readiness;
|
|
54
|
+
submit(raw: Identity, source: string): Promise<{
|
|
55
|
+
attemptId: string;
|
|
56
|
+
epoch: number;
|
|
57
|
+
instance: string;
|
|
58
|
+
sourceDigest: string;
|
|
59
|
+
turnId: string | null;
|
|
60
|
+
accepted: boolean | null;
|
|
61
|
+
state: "failed" | "not_accepted" | "prepared" | "running" | "stopped" | "submitting" | "succeeded" | "unknown";
|
|
62
|
+
}>;
|
|
63
|
+
private save;
|
|
64
|
+
observe(raw: Identity): Promise<{
|
|
65
|
+
attemptId: string;
|
|
66
|
+
epoch: number;
|
|
67
|
+
instance: string;
|
|
68
|
+
sourceDigest: string;
|
|
69
|
+
turnId: string | null;
|
|
70
|
+
accepted: boolean | null;
|
|
71
|
+
state: "failed" | "not_accepted" | "prepared" | "running" | "stopped" | "submitting" | "succeeded" | "unknown";
|
|
72
|
+
}>;
|
|
73
|
+
readOutput(raw: Identity, offset?: number, limit?: number): Promise<{
|
|
74
|
+
content: string;
|
|
75
|
+
offset: number;
|
|
76
|
+
next: number;
|
|
77
|
+
total_bytes: number;
|
|
78
|
+
has_more: boolean;
|
|
79
|
+
attemptId: string;
|
|
80
|
+
epoch: number;
|
|
81
|
+
instance: string;
|
|
82
|
+
sourceDigest: string;
|
|
83
|
+
turnId: string | null;
|
|
84
|
+
accepted: boolean | null;
|
|
85
|
+
state: "failed" | "not_accepted" | "prepared" | "running" | "stopped" | "submitting" | "succeeded" | "unknown";
|
|
86
|
+
itemId: string;
|
|
87
|
+
phase: "final_answer" | "unknown";
|
|
88
|
+
digest: string;
|
|
89
|
+
}>;
|
|
90
|
+
interrupt(raw: Identity): Promise<{
|
|
91
|
+
attemptId: string;
|
|
92
|
+
epoch: number;
|
|
93
|
+
instance: string;
|
|
94
|
+
sourceDigest: string;
|
|
95
|
+
turnId: string | null;
|
|
96
|
+
accepted: boolean | null;
|
|
97
|
+
state: "failed" | "not_accepted" | "prepared" | "running" | "stopped" | "submitting" | "succeeded" | "unknown";
|
|
98
|
+
}>;
|
|
99
|
+
close(): void;
|
|
100
|
+
}
|
|
101
|
+
export {};
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import { closeSync, constants, lstatSync, openSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { fail, hash, short } from './domain.js';
|
|
6
|
+
import { transaction } from './transactions.js';
|
|
7
|
+
import { range } from './content.js';
|
|
8
|
+
const bindingSchema = z.object({ bindingId: short, epoch: z.number().int().positive(), instance: short, profile: short, nativeId: short }).strict();
|
|
9
|
+
const identitySchema = bindingSchema.extend({ attemptId: short, sourceDigest: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
|
|
10
|
+
const turnSchema = z.object({ id: short, status: z.enum(['inProgress', 'completed', 'failed', 'interrupted']), items: z.array(z.unknown()) });
|
|
11
|
+
const terminal = (state) => ['succeeded', 'failed', 'stopped', 'not_accepted'].includes(state);
|
|
12
|
+
// Internal native protocol/intent layer only. It has no controller authority.
|
|
13
|
+
// A caller must own the host and verify its scope before offering model input.
|
|
14
|
+
// Health proves contact/auth presence, never entitlement or tool isolation.
|
|
15
|
+
export class CodexTurns {
|
|
16
|
+
fence;
|
|
17
|
+
rpc;
|
|
18
|
+
db;
|
|
19
|
+
ownerId;
|
|
20
|
+
closed = false;
|
|
21
|
+
submissions = new Set();
|
|
22
|
+
binding;
|
|
23
|
+
cwd;
|
|
24
|
+
permissionProfile;
|
|
25
|
+
constructor(fence, rpc, options) {
|
|
26
|
+
this.fence = fence;
|
|
27
|
+
this.rpc = rpc;
|
|
28
|
+
this.binding = bindingSchema.parse(options.binding);
|
|
29
|
+
this.cwd = realpathSync.native(options.cwd);
|
|
30
|
+
this.permissionProfile = short.parse(options.permissionProfile);
|
|
31
|
+
const owner = fence.status();
|
|
32
|
+
this.ownerId = owner.id;
|
|
33
|
+
this.assertOwner();
|
|
34
|
+
const file = join(fence.profile, '.durebak-turns.sqlite');
|
|
35
|
+
let fresh = false;
|
|
36
|
+
try {
|
|
37
|
+
const fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
38
|
+
closeSync(fd);
|
|
39
|
+
fresh = true;
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (error.code !== 'EEXIST')
|
|
43
|
+
fail('native_ledger_unavailable');
|
|
44
|
+
const stat = lstatSync(file);
|
|
45
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())
|
|
46
|
+
fail('native_ledger_unsafe');
|
|
47
|
+
}
|
|
48
|
+
this.db = new DatabaseSync(file);
|
|
49
|
+
const scope = hash(JSON.stringify({ owner: this.ownerId, binding: this.binding, cwd: this.cwd, permissions: this.permissionProfile }));
|
|
50
|
+
try {
|
|
51
|
+
if (fresh) {
|
|
52
|
+
this.db.exec("PRAGMA synchronous=FULL; PRAGMA journal_mode=DELETE; CREATE TABLE scope(digest TEXT NOT NULL) STRICT; CREATE TABLE turns(attempt_id TEXT PRIMARY KEY,source_digest TEXT NOT NULL,native_id TEXT NOT NULL,turn_id TEXT UNIQUE,accepted INTEGER NOT NULL DEFAULT 0,state TEXT NOT NULL CHECK(state IN ('prepared','submitting','running','unknown','succeeded','failed','stopped','not_accepted')),stop_requested INTEGER NOT NULL DEFAULT 0,interrupt_claimed INTEGER NOT NULL DEFAULT 0) STRICT; CREATE UNIQUE INDEX single_active_turn ON turns((1)) WHERE state IN ('prepared','submitting','running','unknown'); PRAGMA user_version=1;");
|
|
53
|
+
this.db.prepare('INSERT INTO scope VALUES(?)').run(scope);
|
|
54
|
+
}
|
|
55
|
+
const rows = this.db.prepare('SELECT digest FROM scope').all();
|
|
56
|
+
const version = this.db.prepare('PRAGMA user_version').get().user_version;
|
|
57
|
+
if (![1, 2].includes(version) || rows.length !== 1 || rows[0]?.digest !== scope)
|
|
58
|
+
fail('native_ledger_scope_conflict');
|
|
59
|
+
if (version === 1)
|
|
60
|
+
transaction(this.db, () => { this.db.exec("CREATE TABLE IF NOT EXISTS turn_outputs(attempt_id TEXT PRIMARY KEY,item_id TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('final_answer','unknown')),text TEXT NOT NULL CHECK(length(CAST(text AS BLOB)) BETWEEN 1 AND 65536),digest TEXT NOT NULL CHECK(length(digest)=64)) STRICT; PRAGMA user_version=2;"); });
|
|
61
|
+
this.db.prepare('SELECT attempt_id,item_id,phase,text,digest FROM turn_outputs LIMIT 0').all();
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
this.db.close();
|
|
65
|
+
fail('native_ledger_invalid');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
assertOwner() { if (this.closed)
|
|
69
|
+
fail('native_driver_closed'); const owner = this.fence.status(); if (owner.id !== this.ownerId || owner.state !== 'owned' || owner.epoch !== this.binding.epoch || owner.instance !== this.binding.instance || owner.native_id !== this.binding.nativeId || this.fence.profile !== this.binding.profile)
|
|
70
|
+
fail('driver_identity_mismatch'); }
|
|
71
|
+
identity(raw) { const id = identitySchema.parse(raw); this.assertOwner(); for (const key of ['bindingId', 'epoch', 'instance', 'profile', 'nativeId'])
|
|
72
|
+
if (id[key] !== this.binding[key])
|
|
73
|
+
fail('driver_identity_mismatch'); return id; }
|
|
74
|
+
row(id) { const row = this.db.prepare('SELECT * FROM turns WHERE attempt_id=?').get(id.attemptId); if (!row)
|
|
75
|
+
fail('native_intent_missing'); if (row.native_id !== id.nativeId || row.source_digest !== id.sourceDigest)
|
|
76
|
+
fail('idempotency_conflict'); return row; }
|
|
77
|
+
outcome(id, row) { return { attemptId: id.attemptId, epoch: id.epoch, instance: id.instance, sourceDigest: id.sourceDigest, turnId: row.turn_id, accepted: row.accepted ? true : row.state === 'not_accepted' ? false : null, state: ['prepared', 'submitting'].includes(row.state) ? 'unknown' : row.state }; }
|
|
78
|
+
unknown(id) { this.assertOwner(); this.db.prepare("UPDATE turns SET state='unknown' WHERE attempt_id=? AND state IN ('submitting','running','unknown')").run(id.attemptId); return this.outcome(id, this.row(id)); }
|
|
79
|
+
async thread(includeTurns = false) { const result = z.object({ thread: z.object({ id: short, cliVersion: z.literal('0.146.0'), cwd: z.string(), modelProvider: z.literal('openai'), status: z.object({ type: z.enum(['idle', 'active', 'notLoaded', 'systemError']) }), turns: z.array(turnSchema).max(1000) }) }).parse(await this.rpc.call('thread/read', { threadId: this.binding.nativeId, includeTurns })); this.assertOwner(); if (result.thread.id !== this.binding.nativeId || realpathSync.native(result.thread.cwd) !== this.cwd)
|
|
80
|
+
fail('native_thread_conflict'); return result.thread; }
|
|
81
|
+
async health() { return this.readiness(); }
|
|
82
|
+
async readiness(ignoreAttempt = null) { this.assertOwner(); try {
|
|
83
|
+
const thread = await this.thread(), account = z.object({ requiresOpenaiAuth: z.literal(true), account: z.object({ type: z.enum(['chatgpt', 'apiKey']) }).nullable() }).parse(await this.rpc.call('account/read', { refreshToken: false }));
|
|
84
|
+
this.assertOwner();
|
|
85
|
+
const auth = account.account ? 'present' : 'required';
|
|
86
|
+
const active = this.db.prepare("SELECT attempt_id FROM turns WHERE state IN ('prepared','submitting','running','unknown') AND (? IS NULL OR attempt_id<>?)").get(ignoreAttempt, ignoreAttempt);
|
|
87
|
+
return { readiness: thread.status.type === 'active' || active ? 'busy' : thread.status.type === 'idle' && auth === 'present' ? 'ready' : 'unknown', auth, entitlement: 'unverified' };
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
this.assertOwner();
|
|
91
|
+
return { readiness: 'unknown', auth: 'unknown', entitlement: 'unverified' };
|
|
92
|
+
} }
|
|
93
|
+
async submit(raw, source) {
|
|
94
|
+
const id = this.identity(raw);
|
|
95
|
+
if (typeof source !== 'string' || Buffer.byteLength(source) > 16384 || hash(source) !== id.sourceDigest)
|
|
96
|
+
fail('source_changed');
|
|
97
|
+
transaction(this.db, () => { if (this.db.prepare('SELECT attempt_id FROM turns WHERE attempt_id=?').get(id.attemptId))
|
|
98
|
+
fail('submission_uncertain'); if (this.db.prepare("SELECT attempt_id FROM turns WHERE state IN ('prepared','submitting','running','unknown')").get())
|
|
99
|
+
fail('native_busy'); if (this.db.prepare('SELECT count(*) n FROM turns').get().n >= 30)
|
|
100
|
+
fail('native_turn_limit'); this.db.prepare("INSERT INTO turns(attempt_id,source_digest,native_id,state) VALUES(?,?,?,'prepared')").run(id.attemptId, id.sourceDigest, id.nativeId); });
|
|
101
|
+
this.submissions.add(id.attemptId);
|
|
102
|
+
const health = await this.readiness(id.attemptId);
|
|
103
|
+
this.assertOwner();
|
|
104
|
+
if (this.row(id).state === 'not_accepted')
|
|
105
|
+
return this.outcome(id, this.row(id));
|
|
106
|
+
if (health.readiness !== 'ready') {
|
|
107
|
+
this.db.prepare("UPDATE turns SET state='not_accepted' WHERE attempt_id=? AND state='prepared'").run(id.attemptId);
|
|
108
|
+
fail(health.readiness === 'busy' ? 'host_busy' : health.auth === 'required' ? 'native_auth_required' : 'host_unknown');
|
|
109
|
+
}
|
|
110
|
+
if (this.db.prepare("UPDATE turns SET state='submitting' WHERE attempt_id=? AND state='prepared' AND stop_requested=0").run(id.attemptId).changes !== 1)
|
|
111
|
+
return this.outcome(id, this.row(id));
|
|
112
|
+
try {
|
|
113
|
+
const result = z.object({ turn: turnSchema }).parse(await this.rpc.call('turn/start', { threadId: id.nativeId, cwd: this.cwd, permissions: this.permissionProfile, approvalPolicy: 'never', input: [{ type: 'text', text: source }] }));
|
|
114
|
+
this.assertOwner();
|
|
115
|
+
if (this.db.prepare('SELECT attempt_id FROM turns WHERE turn_id=?').get(result.turn.id))
|
|
116
|
+
return this.unknown(id);
|
|
117
|
+
this.db.prepare('UPDATE turns SET turn_id=?,accepted=1 WHERE attempt_id=?').run(result.turn.id, id.attemptId);
|
|
118
|
+
const outcome = this.save(id, result.turn);
|
|
119
|
+
return this.row(id).stop_requested && !terminal(outcome.state) ? this.interrupt(id) : outcome;
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
this.assertOwner();
|
|
123
|
+
return this.unknown(id);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
save(id, turn) { this.assertOwner(); const row = this.row(id); if (terminal(row.state))
|
|
127
|
+
return this.outcome(id, row); if (row.turn_id !== turn.id)
|
|
128
|
+
fail('native_turn_conflict'); const state = turn.status === 'completed' ? 'succeeded' : turn.status === 'failed' ? 'failed' : turn.status === 'interrupted' ? 'stopped' : row.stop_requested ? 'unknown' : 'running'; this.db.prepare('UPDATE turns SET state=? WHERE attempt_id=?').run(state, id.attemptId); return this.outcome(id, this.row(id)); }
|
|
129
|
+
async observe(raw) { const id = this.identity(raw), row = this.row(id); if (terminal(row.state))
|
|
130
|
+
return this.outcome(id, row); if (!row.turn_id)
|
|
131
|
+
return this.unknown(id); try {
|
|
132
|
+
const thread = await this.thread(true), matches = thread.turns.filter(t => t.id === row.turn_id);
|
|
133
|
+
if (matches.length !== 1)
|
|
134
|
+
return this.unknown(id);
|
|
135
|
+
return this.save(id, matches[0]);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
this.assertOwner();
|
|
139
|
+
return this.unknown(id);
|
|
140
|
+
} }
|
|
141
|
+
// A successful host turn is not request completion or verification. Freeze only
|
|
142
|
+
// its selected answer; never expose reasoning, tool output or adjacent turns.
|
|
143
|
+
async readOutput(raw, offset = 0, limit = 4096) {
|
|
144
|
+
const id = this.identity(raw);
|
|
145
|
+
z.number().int().min(0).max(65536).parse(offset);
|
|
146
|
+
z.number().int().min(4).max(4096).parse(limit);
|
|
147
|
+
const intent = this.row(id);
|
|
148
|
+
if (!intent.turn_id || !intent.accepted || ['failed', 'stopped', 'not_accepted', 'prepared', 'submitting'].includes(intent.state))
|
|
149
|
+
fail('native_output_unavailable');
|
|
150
|
+
const snapshotSchema = z.object({ item_id: short, phase: z.enum(['final_answer', 'unknown']), text: z.string(), digest: z.string().regex(/^[a-f0-9]{64}$/) });
|
|
151
|
+
const cached = () => this.db.prepare('SELECT item_id,phase,text,digest FROM turn_outputs WHERE attempt_id=?').get(id.attemptId);
|
|
152
|
+
let snapshot = cached();
|
|
153
|
+
if (!snapshot) {
|
|
154
|
+
const thread = await this.thread(true), matches = thread.turns.filter(turn => turn.id === intent.turn_id);
|
|
155
|
+
if (matches.length !== 1 || matches[0].status !== 'completed')
|
|
156
|
+
fail('native_output_not_ready');
|
|
157
|
+
const turn = matches[0], messages = turn.items.filter(item => item && typeof item === 'object' && 'type' in item && item.type === 'agentMessage').map(item => z.object({ id: short, text: z.string(), phase: z.enum(['commentary', 'final_answer']).nullable().optional() }).parse(item));
|
|
158
|
+
if (new Set(messages.map(m => m.id)).size !== messages.length)
|
|
159
|
+
fail('native_output_ambiguous');
|
|
160
|
+
const finals = messages.filter(m => m.phase === 'final_answer'), unknowns = messages.filter(m => m.phase == null), selected = finals.length ? finals : unknowns;
|
|
161
|
+
if (selected.length !== 1)
|
|
162
|
+
fail('native_output_ambiguous');
|
|
163
|
+
const answer = selected[0], bytes = Buffer.byteLength(answer.text);
|
|
164
|
+
if (!bytes || bytes > 65536)
|
|
165
|
+
fail('native_output_size');
|
|
166
|
+
const digest = hash(answer.text), phase = answer.phase === 'final_answer' ? 'final_answer' : 'unknown';
|
|
167
|
+
transaction(this.db, () => { this.assertOwner(); const outcome = this.save(id, turn); if (outcome.state !== 'succeeded')
|
|
168
|
+
fail('native_output_unavailable'); const existing = cached(); if (existing) {
|
|
169
|
+
if (existing.digest !== digest || existing.item_id !== answer.id || existing.phase !== phase)
|
|
170
|
+
fail('native_output_changed');
|
|
171
|
+
}
|
|
172
|
+
else
|
|
173
|
+
this.db.prepare('INSERT INTO turn_outputs VALUES(?,?,?,?,?)').run(id.attemptId, answer.id, phase, answer.text, digest); });
|
|
174
|
+
snapshot = cached();
|
|
175
|
+
}
|
|
176
|
+
this.assertOwner();
|
|
177
|
+
const result = snapshotSchema.parse(snapshot);
|
|
178
|
+
if (this.row(id).state !== 'succeeded' || hash(result.text) !== result.digest || !Buffer.byteLength(result.text) || Buffer.byteLength(result.text) > 65536)
|
|
179
|
+
fail('native_output_invalid');
|
|
180
|
+
return { ...this.outcome(id, this.row(id)), itemId: result.item_id, phase: result.phase, digest: result.digest, ...range(result.text, offset, limit) };
|
|
181
|
+
}
|
|
182
|
+
async interrupt(raw) { const id = this.identity(raw), row = this.row(id); if (terminal(row.state))
|
|
183
|
+
return this.outcome(id, row); if (row.state === 'prepared') {
|
|
184
|
+
this.db.prepare("UPDATE turns SET state='not_accepted',stop_requested=1 WHERE attempt_id=? AND state='prepared'").run(id.attemptId);
|
|
185
|
+
return this.outcome(id, this.row(id));
|
|
186
|
+
} this.db.prepare('UPDATE turns SET stop_requested=1 WHERE attempt_id=?').run(id.attemptId); if (!row.turn_id)
|
|
187
|
+
return this.unknown(id); if (this.db.prepare('UPDATE turns SET interrupt_claimed=1 WHERE attempt_id=? AND interrupt_claimed=0').run(id.attemptId).changes !== 1)
|
|
188
|
+
return this.observe(id); try {
|
|
189
|
+
await this.rpc.call('turn/interrupt', { threadId: id.nativeId, turnId: row.turn_id });
|
|
190
|
+
this.assertOwner();
|
|
191
|
+
return this.observe(id);
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
this.assertOwner();
|
|
195
|
+
return this.unknown(id);
|
|
196
|
+
} }
|
|
197
|
+
close() { if (this.closed)
|
|
198
|
+
return; this.closed = true; try {
|
|
199
|
+
transaction(this.db, () => { for (const attempt of this.submissions) {
|
|
200
|
+
this.db.prepare("UPDATE turns SET state='not_accepted' WHERE attempt_id=? AND state='prepared'").run(attempt);
|
|
201
|
+
this.db.prepare("UPDATE turns SET state='unknown' WHERE attempt_id=? AND state IN ('submitting','running')").run(attempt);
|
|
202
|
+
} });
|
|
203
|
+
}
|
|
204
|
+
finally {
|
|
205
|
+
this.db.close();
|
|
206
|
+
} }
|
|
207
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { SessionHealth } from './health.js';
|
|
2
|
+
export interface CollaborationStatus {
|
|
3
|
+
mode: 'cooperative';
|
|
4
|
+
auto_wake: false;
|
|
5
|
+
observed_at: number;
|
|
6
|
+
self: SessionHealth;
|
|
7
|
+
sessions: {
|
|
8
|
+
items: {
|
|
9
|
+
id: string;
|
|
10
|
+
alias: string;
|
|
11
|
+
alias_truncated: boolean;
|
|
12
|
+
provider: string;
|
|
13
|
+
availability: string;
|
|
14
|
+
bridge: string;
|
|
15
|
+
duplicate_bridge: boolean;
|
|
16
|
+
last_contact_at: number | null;
|
|
17
|
+
}[];
|
|
18
|
+
next: string;
|
|
19
|
+
has_more: boolean;
|
|
20
|
+
};
|
|
21
|
+
requests: {
|
|
22
|
+
items: {
|
|
23
|
+
id: string;
|
|
24
|
+
state: string;
|
|
25
|
+
version: number;
|
|
26
|
+
creator: string;
|
|
27
|
+
recipient: string;
|
|
28
|
+
deadline_at: number;
|
|
29
|
+
task_state: string | null;
|
|
30
|
+
task_version: number | null;
|
|
31
|
+
verification: string;
|
|
32
|
+
needs_attention: boolean;
|
|
33
|
+
}[];
|
|
34
|
+
next: string;
|
|
35
|
+
has_more: boolean;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export declare function renderCollaborationStatus(view: CollaborationStatus): string;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// JSON quoting preserves label boundaries. Escape bidi controls explicitly too.
|
|
2
|
+
function label(value) { return JSON.stringify(value).replace(/[\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, c => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`); }
|
|
3
|
+
export function renderCollaborationStatus(view) {
|
|
4
|
+
return [`Durebak | mode=${view.mode} | auto_wake=${view.auto_wake} | host=${view.self.host}`,
|
|
5
|
+
`Snapshot: ${new Date(view.observed_at).toISOString()} | self bridge=${view.self.bridge.state} | availability=${view.self.availability}`,
|
|
6
|
+
'', 'Sessions (contact is not host readiness)',
|
|
7
|
+
...view.sessions.items.map(s => `${s.id} | ${label(s.alias)}${s.alias_truncated ? ' [truncated]' : ''} | ${s.provider} | ${s.availability} | bridge=${s.bridge}${s.duplicate_bridge ? ' [duplicate]' : ''}`),
|
|
8
|
+
...(view.sessions.has_more ? [`More sessions: collaboration_status sessionAfter=${view.sessions.next}`] : []),
|
|
9
|
+
'', 'Your requests (completion is a submitted result)',
|
|
10
|
+
...view.requests.items.map(q => `${q.id} | ${q.state} v${q.version} | task=${q.task_state ?? 'none'}${q.task_version === null ? '' : ` v${q.task_version}`} | verification=${q.verification} | deadline=${new Date(q.deadline_at).toISOString()}${q.needs_attention ? ' [attention]' : ''}`),
|
|
11
|
+
...(!view.requests.items.length ? ['No participant requests in this page.'] : []),
|
|
12
|
+
...(view.requests.has_more ? [`More requests: collaboration_status requestAfter=${view.requests.next}`] : []),
|
|
13
|
+
'', 'Host readiness/progress: unknown. Evidence is self_reported. Snapshot does not receive, acknowledge or execute.', ''].join('\n');
|
|
14
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { requestCreateSchema } from './requests.js';
|
|
4
|
+
export interface ExecutionOrigin {
|
|
5
|
+
binding: {
|
|
6
|
+
id: string;
|
|
7
|
+
session_id: string;
|
|
8
|
+
workspace: string;
|
|
9
|
+
epoch: number;
|
|
10
|
+
instance: string;
|
|
11
|
+
};
|
|
12
|
+
attempt: {
|
|
13
|
+
id: string;
|
|
14
|
+
request_id: string;
|
|
15
|
+
state: string;
|
|
16
|
+
driver_outcome: string | null;
|
|
17
|
+
input_accepted: number;
|
|
18
|
+
stop_requested: number;
|
|
19
|
+
source: string;
|
|
20
|
+
policy_digest: string;
|
|
21
|
+
root_policy_digest: string;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export declare class Continuations {
|
|
25
|
+
private db;
|
|
26
|
+
private clock;
|
|
27
|
+
constructor(db: DatabaseSync, clock: {
|
|
28
|
+
now(): number;
|
|
29
|
+
});
|
|
30
|
+
private policy;
|
|
31
|
+
private repository;
|
|
32
|
+
create(origin: ExecutionOrigin, input: z.input<typeof requestCreateSchema>): import("./requests.js").CollaborationRequest;
|
|
33
|
+
wait(origin: ExecutionOrigin, requestId: string): void;
|
|
34
|
+
}
|
|
35
|
+
export declare function expireWaiters(db: DatabaseSync, now: number): void;
|
|
36
|
+
export declare function childPermission(db: DatabaseSync, requestId: string, now: number): string | null;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { fail, hash } from './domain.js';
|
|
2
|
+
import { managedPolicyDigest } from './managed-control.js';
|
|
3
|
+
import { RequestRepository, requestCreateSchema } from './requests.js';
|
|
4
|
+
import { ScopedAttachments } from './scoped-attachments.js';
|
|
5
|
+
import { ProtectedTasks } from './protected-tasks.js';
|
|
6
|
+
import { RequestPreviewRepository } from './request-preview.js';
|
|
7
|
+
import { messageQueue } from './message-queue.js';
|
|
8
|
+
export class Continuations {
|
|
9
|
+
db;
|
|
10
|
+
clock;
|
|
11
|
+
constructor(db, clock) {
|
|
12
|
+
this.db = db;
|
|
13
|
+
this.clock = clock;
|
|
14
|
+
}
|
|
15
|
+
policy(id) { const p = this.db.prepare('SELECT * FROM managed_policies WHERE binding_id=?').get(id); if (!p || !p.enabled || p.expired || p.expires_at === null || p.expires_at <= this.clock.now())
|
|
16
|
+
fail('policy_off'); return p; }
|
|
17
|
+
repository() { const attachments = new ScopedAttachments(this.db), preview = new RequestPreviewRepository(this.db, this.clock, attachments); return new RequestRepository(this.db, this.clock, (actor, input, now) => messageQueue(this.db).enqueue(actor, input, now), (actor, id, input, now) => { preview.validate(actor, id, input, now); }, new ProtectedTasks(this.db), attachments); }
|
|
18
|
+
create(origin, input) {
|
|
19
|
+
if (!this.db.isTransaction)
|
|
20
|
+
fail('transaction_required');
|
|
21
|
+
const data = requestCreateSchema.parse(input), digest = hash(JSON.stringify(data)), { binding: b, attempt: a } = origin, actor = this.db.prepare('SELECT id,workspace,alias,provider,revoked FROM sessions WHERE id=?').get(b.session_id), repository = this.repository();
|
|
22
|
+
const old = this.db.prepare('SELECT id FROM requests WHERE creator=? AND key=?').get(actor.id, data.key);
|
|
23
|
+
if (old) {
|
|
24
|
+
const child = this.db.prepare('SELECT parent_attempt,intent_digest FROM work_children WHERE request_id=?').get(old.id);
|
|
25
|
+
if (!child || child.parent_attempt !== a.id)
|
|
26
|
+
fail('execution_origin_conflict');
|
|
27
|
+
if (child.intent_digest !== digest)
|
|
28
|
+
fail('idempotency_conflict');
|
|
29
|
+
return repository.get(actor, old.id);
|
|
30
|
+
}
|
|
31
|
+
if (a.state !== 'submitting' || a.driver_outcome !== 'running' || !a.input_accepted || a.stop_requested || actor.revoked)
|
|
32
|
+
fail('execution_not_running');
|
|
33
|
+
const owner = this.db.prepare('SELECT execution_state FROM native_bindings WHERE id=?').get(b.id);
|
|
34
|
+
if (owner.execution_state === 'unknown')
|
|
35
|
+
fail('execution_unknown');
|
|
36
|
+
const q = this.db.prepare('SELECT state,deadline_at FROM requests WHERE id=?').get(a.request_id);
|
|
37
|
+
const incoming = JSON.parse(a.source);
|
|
38
|
+
const resumed = !!this.db.prepare("SELECT request_id FROM work_waiters WHERE claim_attempt=? AND status='claimed'").get(a.id);
|
|
39
|
+
if (q.state !== 'accepted' && !(q.state === 'completed' && resumed && incoming.trigger.kind === 'result'))
|
|
40
|
+
fail('parent_request_not_accepted');
|
|
41
|
+
const parent = this.db.prepare('SELECT * FROM work_scopes WHERE request_id=?').get(a.request_id), rootId = parent.root_request_id ?? a.request_id, rootScope = this.db.prepare('SELECT * FROM work_scopes WHERE request_id=?').get(rootId);
|
|
42
|
+
const policy = this.policy(b.id), root = this.policy(rootScope.owner_binding);
|
|
43
|
+
if (a.policy_digest !== managedPolicyDigest(policy) || a.root_policy_digest !== managedPolicyDigest(root))
|
|
44
|
+
fail('policy_changed');
|
|
45
|
+
if (!JSON.parse(policy.allowed_peers).includes(data.to) || (data.to !== (this.db.prepare('SELECT session_id FROM native_bindings WHERE id=?').get(rootScope.owner_binding).session_id) && !JSON.parse(root.allowed_peers).includes(data.to)))
|
|
46
|
+
fail('peer_not_allowed');
|
|
47
|
+
const rootRequest = this.db.prepare('SELECT state,deadline_at FROM requests WHERE id=?').get(rootId);
|
|
48
|
+
if (!['pending', 'accepted'].includes(rootRequest.state))
|
|
49
|
+
fail('root_request_closed');
|
|
50
|
+
const now = this.clock.now(), deadline = Math.min(now + data.deadlineMs, q.deadline_at, rootRequest.deadline_at, parent.expires_at, policy.expires_at, root.expires_at);
|
|
51
|
+
if (deadline <= now)
|
|
52
|
+
fail('request_closed');
|
|
53
|
+
const child = repository.createWithinTransaction(actor, { ...data, deadlineMs: deadline - now });
|
|
54
|
+
this.db.prepare('INSERT INTO work_children(request_id,parent_attempt,root_request_id,intent_digest) VALUES(?,?,?,?)').run(child.id, a.id, rootId, digest);
|
|
55
|
+
this.db.prepare('INSERT INTO work_scopes(request_id,scope_id,owner_binding,max_turns,max_concurrent,expires_at,root_request_id) VALUES(?,?,?,?,?,?,?)').run(child.id, rootScope.scope_id, rootScope.owner_binding, rootScope.max_turns, rootScope.max_concurrent, deadline, rootId);
|
|
56
|
+
return child;
|
|
57
|
+
}
|
|
58
|
+
wait(origin, requestId) {
|
|
59
|
+
if (!this.db.isTransaction)
|
|
60
|
+
fail('transaction_required');
|
|
61
|
+
const { binding: b, attempt: a } = origin, child = this.db.prepare('SELECT r.creator,r.state,r.deadline_at,c.parent_attempt,s.owner_binding FROM requests r JOIN work_children c ON c.request_id=r.id JOIN work_scopes s ON s.request_id=r.id WHERE r.id=?').get(requestId);
|
|
62
|
+
if (!child || child.creator !== b.session_id || child.parent_attempt !== a.id)
|
|
63
|
+
fail('waiting_origin_mismatch');
|
|
64
|
+
const p = this.policy(b.id), root = this.policy(child.owner_binding);
|
|
65
|
+
if (a.policy_digest !== managedPolicyDigest(p) || a.root_policy_digest !== managedPolicyDigest(root))
|
|
66
|
+
fail('policy_changed');
|
|
67
|
+
const ancestor = this.db.prepare('SELECT r.state,r.deadline_at FROM requests r JOIN work_children c ON c.root_request_id=r.id WHERE c.request_id=?').get(requestId);
|
|
68
|
+
if (!['pending', 'accepted'].includes(ancestor.state) || ancestor.deadline_at <= this.clock.now())
|
|
69
|
+
fail('root_request_closed');
|
|
70
|
+
if (child.deadline_at <= this.clock.now() || !['pending', 'accepted', 'completed'].includes(child.state) || a.stop_requested)
|
|
71
|
+
fail('request_closed');
|
|
72
|
+
this.db.prepare("INSERT INTO work_waiters(request_id,origin_attempt,binding_id,epoch,instance,policy_digest,root_policy_digest,deadline_at,status) VALUES(?,?,?,?,?,?,?,?,'waiting')").run(requestId, a.id, b.id, b.epoch, b.instance, managedPolicyDigest(p), managedPolicyDigest(root), Math.min(child.deadline_at, p.expires_at, root.expires_at));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
// Observation latches closure independently of the following rejected operation.
|
|
76
|
+
export function expireWaiters(db, now) { db.prepare("UPDATE work_waiters SET status='expired' WHERE status IN ('waiting','claimed') AND deadline_at<=?").run(now); db.exec("UPDATE work_waiters SET status='cancelled' WHERE status IN ('waiting','claimed') AND (binding_id IN (SELECT binding_id FROM managed_policies WHERE enabled=0 OR expired=1) OR request_id IN (SELECT s.request_id FROM work_scopes s JOIN requests r ON r.id=s.root_request_id JOIN managed_policies p ON p.binding_id=s.owner_binding WHERE r.state NOT IN ('pending','accepted') OR p.enabled=0 OR p.expired=1) OR request_id IN (SELECT id FROM requests WHERE state IN ('cancelled','timed_out','rejected','failed')))"); }
|
|
77
|
+
export function childPermission(db, requestId, now) {
|
|
78
|
+
const child = db.prepare('SELECT r.recipient,a.binding_id,c.root_request_id FROM work_children c JOIN requests r ON r.id=c.request_id JOIN work_attempts a ON a.id=c.parent_attempt WHERE c.request_id=?').get(requestId);
|
|
79
|
+
if (!child)
|
|
80
|
+
return null;
|
|
81
|
+
const ancestors = db.prepare(`WITH RECURSIVE lineage(id) AS (SELECT a.request_id FROM work_children c JOIN work_attempts a ON a.id=c.parent_attempt WHERE c.request_id=? UNION SELECT a.request_id FROM lineage l JOIN work_children c ON c.request_id=l.id JOIN work_attempts a ON a.id=c.parent_attempt) SELECT r.state,r.deadline_at FROM lineage l JOIN requests r ON r.id=l.id`).all(requestId);
|
|
82
|
+
for (const ancestor of ancestors) {
|
|
83
|
+
if (ancestor.deadline_at <= now)
|
|
84
|
+
return 'request_deadline';
|
|
85
|
+
if (['cancelled', 'timed_out', 'rejected', 'failed'].includes(ancestor.state))
|
|
86
|
+
return 'ancestor_request_closed';
|
|
87
|
+
}
|
|
88
|
+
const root = db.prepare('SELECT owner_binding FROM work_scopes WHERE request_id=?').get(child.root_request_id);
|
|
89
|
+
for (const id of new Set([child.binding_id, root.owner_binding])) {
|
|
90
|
+
const grant = db.prepare('SELECT p.enabled,p.expired,p.expires_at,p.allowed_peers,b.session_id,s.revoked,s.availability FROM managed_policies p JOIN native_bindings b ON b.id=p.binding_id JOIN sessions s ON s.id=b.session_id WHERE p.binding_id=?').get(id);
|
|
91
|
+
if (grant.revoked)
|
|
92
|
+
return 'binding_revoked';
|
|
93
|
+
if (grant.availability === 'paused')
|
|
94
|
+
return 'recipient_paused';
|
|
95
|
+
if (!grant.enabled)
|
|
96
|
+
return 'root_policy_off';
|
|
97
|
+
if (grant.expired || grant.expires_at === null || grant.expires_at <= now)
|
|
98
|
+
return 'grant_expired';
|
|
99
|
+
if (grant.session_id !== child.recipient && !JSON.parse(grant.allowed_peers).includes(child.recipient))
|
|
100
|
+
return 'peer_not_allowed';
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|