session-peer 0.3.6 → 0.5.0
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/CONTRIBUTING.md +6 -4
- package/PARITY.md +431 -6
- package/README.ja.md +14 -8
- package/README.ko.md +14 -8
- package/README.md +14 -8
- package/README.zh-CN.md +14 -8
- package/RELEASING.md +109 -0
- package/VALIDATION.md +806 -1
- package/dist/app-server.d.ts +207 -0
- package/dist/app-server.js +1044 -0
- package/dist/cli.js +229 -39
- package/dist/handoff-ledger.d.ts +103 -0
- package/dist/handoff-ledger.js +791 -0
- package/dist/handoff-observer-probe.d.ts +1 -0
- package/dist/handoff-observer-probe.js +170 -0
- package/dist/handoff-operations.d.ts +29 -0
- package/dist/handoff-operations.js +496 -0
- package/dist/handoff-writer-probe.d.ts +1 -0
- package/dist/handoff-writer-probe.js +146 -0
- package/dist/handoff.d.ts +112 -0
- package/dist/handoff.js +261 -0
- package/dist/help.js +18 -0
- package/dist/linux-native-probe.d.ts +1 -0
- package/dist/linux-native-probe.js +51 -0
- package/dist/linux-proc.d.ts +55 -0
- package/dist/linux-proc.js +150 -0
- package/dist/metadata-observation.d.ts +49 -0
- package/dist/metadata-observation.js +250 -0
- package/dist/native-profiles.d.ts +25 -0
- package/dist/native-profiles.js +62 -0
- package/dist/output.js +7 -1
- package/dist/process.d.ts +28 -0
- package/dist/process.js +284 -2
- package/dist/protocol.d.ts +2 -2
- package/dist/protocol.js +1 -1
- package/dist/send.d.ts +18 -1
- package/dist/send.js +91 -6
- package/dist/skill-metadata.js +7 -4
- package/dist/ssh-response.d.ts +11 -0
- package/dist/ssh-response.js +78 -2
- package/dist/ssh.d.ts +2 -1
- package/dist/ssh.js +37 -2
- package/dist/windows.d.ts +28 -0
- package/dist/windows.js +149 -1
- package/docs/api.md +255 -4
- package/docs/design/typescript-skill-compatibility.md +55 -2
- package/docs/guide.ja.md +36 -16
- package/docs/guide.ko.md +39 -19
- package/docs/guide.md +46 -20
- package/docs/guide.zh-CN.md +36 -16
- package/docs/shorthand.md +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,1044 @@
|
|
|
1
|
+
// Bounded queue-only mechanics and metadata-only client foundation.
|
|
2
|
+
// No live owner/delivery observation route is qualified.
|
|
3
|
+
// Official Codex schemas generated separately with isolated HOME/CODEX_HOME:
|
|
4
|
+
// https://learn.chatgpt.com/docs/app-server (schema is version-specific).
|
|
5
|
+
// queue/list returns QueuedSubmission.input; item/started returns full content;
|
|
6
|
+
// turn/completed returns Turn.items. These are not metadata-only observers.
|
|
7
|
+
// queue/add echoes only its OWN submitted input and can be validated as an
|
|
8
|
+
// effect receipt separately; it does not read other requests or thread history.
|
|
9
|
+
// A fresh app-server process is never evidence that it owns an existing writer.
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import { lstatSync, realpathSync, statSync } from 'node:fs';
|
|
12
|
+
import { basename, isAbsolute, join } from 'node:path';
|
|
13
|
+
import { performance } from 'node:perf_hooks';
|
|
14
|
+
import { TextDecoder } from 'node:util';
|
|
15
|
+
import { run } from './process.js';
|
|
16
|
+
import { CANDIDATE_PROFILES, NATIVE_PROFILES, platformProfiled, selectNativeProfile, validateNativeProfiles } from './native-profiles.js';
|
|
17
|
+
import { procOwnedFiles } from './linux-proc.js';
|
|
18
|
+
import { fileURLToPath } from 'node:url';
|
|
19
|
+
export const APP_SERVER_EVIDENCE = Object.freeze({
|
|
20
|
+
version: '0.160.1', inspectedPlatform: 'darwin-arm64',
|
|
21
|
+
officialSourceCommit: 'd27764b82f7118f674371e6d6e76271d9d606edb',
|
|
22
|
+
scope: 'generated_schema_only',
|
|
23
|
+
queueAddParamsSha256: '60f25b7d3e3357c215bef9d2fe7047200f545e030dca9e00527ac0620cd0c88f',
|
|
24
|
+
queueAddResponseSha256: 'c11b9772788427b19c9f9decf0765e2b41cbdead1aa9c3d39f42fdd70b339314',
|
|
25
|
+
itemStartedSha256: '7574788d2a352747f50d44be3ef649011cb8de8069da4c655faff14d0aee32c4',
|
|
26
|
+
turnCompletedSha256: '016870158603b0f84bd9f8f65f927161c9fd5128e5ec632087616462dc44e085',
|
|
27
|
+
});
|
|
28
|
+
// Darwin entries qualify queue-only mechanics on that exact native version and
|
|
29
|
+
// platform. The linux-arm64 entry is generated-schema data for the
|
|
30
|
+
// non-selectable candidate only; it is consumed by profile selection and tests
|
|
31
|
+
// and qualifies nothing while no Linux row is selectable. Neither generated
|
|
32
|
+
// schemas nor isolated unloaded-thread fixtures qualify a live writer
|
|
33
|
+
// endpoint, metadata-only observer or delivery/ACK.
|
|
34
|
+
export const APP_SERVER_QUEUE_EVIDENCE = Object.freeze([
|
|
35
|
+
APP_SERVER_EVIDENCE,
|
|
36
|
+
Object.freeze({
|
|
37
|
+
version: '0.162.1', inspectedPlatform: 'darwin-arm64',
|
|
38
|
+
officialSourceCommit: '092d3acd6bec3e3a14bdc7e7a2810ab628ab759d',
|
|
39
|
+
scope: 'generated_schema_only',
|
|
40
|
+
queueAddParamsSha256: '60f25b7d3e3357c215bef9d2fe7047200f545e030dca9e00527ac0620cd0c88f',
|
|
41
|
+
queueAddResponseSha256: 'c11b9772788427b19c9f9decf0765e2b41cbdead1aa9c3d39f42fdd70b339314',
|
|
42
|
+
itemStartedSha256: '692c5876f44a4c12a9b9211912860ceddb65d34497ab4fe9aa46cbebe1a63166',
|
|
43
|
+
turnCompletedSha256: '69413578ec3ecd02691424bdeb9d640c7244b4ca4c5c3ef26f69a2efe7c37db8',
|
|
44
|
+
}),
|
|
45
|
+
// Generated on the Linux arm64 host from the exact pinned musl artifact with
|
|
46
|
+
// an isolated CODEX_HOME; byte-identical to the darwin-arm64 0.162.1 schemas.
|
|
47
|
+
// Schema evidence only: no linux-arm64 profile row is selectable yet.
|
|
48
|
+
Object.freeze({
|
|
49
|
+
version: '0.162.1', inspectedPlatform: 'linux-arm64',
|
|
50
|
+
officialSourceCommit: '092d3acd6bec3e3a14bdc7e7a2810ab628ab759d',
|
|
51
|
+
scope: 'generated_schema_only',
|
|
52
|
+
queueAddParamsSha256: '60f25b7d3e3357c215bef9d2fe7047200f545e030dca9e00527ac0620cd0c88f',
|
|
53
|
+
queueAddResponseSha256: 'c11b9772788427b19c9f9decf0765e2b41cbdead1aa9c3d39f42fdd70b339314',
|
|
54
|
+
itemStartedSha256: '692c5876f44a4c12a9b9211912860ceddb65d34497ab4fe9aa46cbebe1a63166',
|
|
55
|
+
turnCompletedSha256: '69413578ec3ecd02691424bdeb9d640c7244b4ca4c5c3ef26f69a2efe7c37db8',
|
|
56
|
+
}),
|
|
57
|
+
]);
|
|
58
|
+
// Exact (version, platform) schema evidence; another platform's row is never inherited.
|
|
59
|
+
function queueEvidence(version, platform) {
|
|
60
|
+
return APP_SERVER_QUEUE_EVIDENCE.find(profile => profile.version === version && profile.inspectedPlatform === platform);
|
|
61
|
+
}
|
|
62
|
+
// Every production or candidate profile row must carry its own exact schema evidence row.
|
|
63
|
+
if ([...NATIVE_PROFILES, ...CANDIDATE_PROFILES].some(row => !queueEvidence(row.version, row.platform)))
|
|
64
|
+
throw new Error('native profile lacks queue evidence');
|
|
65
|
+
export const APP_SERVER_LIMITS = Object.freeze({
|
|
66
|
+
frameBytes: 65536, receivedBytes: 1024 * 1024, sentBytes: 256 * 1024,
|
|
67
|
+
frames: 512, notifications: 256, requests: 16, observations: 64, messageBytes: 32768,
|
|
68
|
+
lifetimeMs: 60000, cleanupMs: 250,
|
|
69
|
+
});
|
|
70
|
+
export function appServerCapability(context) {
|
|
71
|
+
const qualified = selectNativeProfile({ platform: context.platform, version: context.version }) !== undefined &&
|
|
72
|
+
queueEvidence(context.version, context.platform) !== undefined;
|
|
73
|
+
return { supported: false, schema: qualified ? 'version_qualified' : 'version_unqualified', route: 'route_unsupported',
|
|
74
|
+
reason: qualified ? 'metadata_only_owner_route_unvalidated' : 'version_unqualified', attempted: false, queueSupported: qualified };
|
|
75
|
+
}
|
|
76
|
+
// Hard production gate: do not spawn/connect a native endpoint even if a caller
|
|
77
|
+
// supplies an owner tuple. Queue-only mechanics use the separate nativeQueueOnce
|
|
78
|
+
// entry point; no metadata-only owner observation transport is claimed.
|
|
79
|
+
export async function connectAppServer(context, _open, _deadlineMs) {
|
|
80
|
+
return appServerCapability(context);
|
|
81
|
+
}
|
|
82
|
+
export class AppServerFault extends Error {
|
|
83
|
+
code;
|
|
84
|
+
attempted;
|
|
85
|
+
fallbackEligible;
|
|
86
|
+
constructor(code, attempted) {
|
|
87
|
+
super(code);
|
|
88
|
+
this.code = code;
|
|
89
|
+
this.attempted = attempted;
|
|
90
|
+
this.fallbackEligible = !attempted && ['unsupported_transport', 'unsupported_version'].includes(code);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export function nativeQueueCapability(context) {
|
|
94
|
+
const qualified = appServerCapability(context).queueSupported;
|
|
95
|
+
return { queueSupported: qualified, observationSupported: false,
|
|
96
|
+
qualification: qualified ? 'mechanics_from_isolated_fixture' : 'unsupported', reason: qualified ? 'queue_only' : 'version_unqualified' };
|
|
97
|
+
}
|
|
98
|
+
// All methods from each exact experimental ServerNotification schema (83 for
|
|
99
|
+
// 0.160.1, 84 for 0.162.1) are suppressed before queue/add. A notification
|
|
100
|
+
// reaching us is a qualification failure, not an invitation to inspect/filter
|
|
101
|
+
// its body or perform another RPC.
|
|
102
|
+
export const NATIVE_QUEUE_NOTIFICATION_OPTOUTS = Object.freeze([
|
|
103
|
+
'account/gatewayOAuth/changed', 'account/login/completed', 'account/rateLimits/updated', 'account/updated', 'app/list/updated',
|
|
104
|
+
'autoApprovalReview/strictReviewRequired', 'command/exec/outputDelta', 'configWarning', 'deprecationNotice', 'error',
|
|
105
|
+
'externalAgentConfig/import/completed', 'externalAgentConfig/import/progress', 'fs/changed', 'fuzzyFileSearch/sessionCompleted',
|
|
106
|
+
'fuzzyFileSearch/sessionUpdated', 'guardianWarning', 'hook/completed', 'hook/started', 'item/agentMessage/delta',
|
|
107
|
+
'item/autoApprovalReview/completed', 'item/autoApprovalReview/started', 'item/commandExecution/outputDelta',
|
|
108
|
+
'item/commandExecution/terminalInteraction', 'item/completed', 'item/fileChange/outputDelta', 'item/fileChange/patchUpdated',
|
|
109
|
+
'item/mcpToolCall/progress', 'item/plan/delta', 'item/reasoning/summaryPartAdded', 'item/reasoning/summaryTextDelta',
|
|
110
|
+
'item/reasoning/textDelta', 'item/started', 'mcpServer/event/stream/notification', 'mcpServer/oauthLogin/completed',
|
|
111
|
+
'mcpServer/startupStatus/updated', 'model/rerouted', 'model/safetyBuffering/updated', 'model/verification',
|
|
112
|
+
'modelProvider/authRecoveryCompleted', 'modelProvider/authRecoveryStarted', 'process/exited', 'process/outputDelta',
|
|
113
|
+
'project/changed', 'remoteControl/status/changed', 'serverRequest/resolved', 'skills/changed', 'thread/archived',
|
|
114
|
+
'thread/attachment/updated', 'thread/closed', 'thread/compacted', 'thread/deleted', 'thread/environment/connected',
|
|
115
|
+
'thread/environment/disconnected', 'thread/goal/cleared', 'thread/goal/updated', 'thread/name/updated', 'thread/project/updated',
|
|
116
|
+
'thread/queue/changed', 'thread/realtime/closed', 'thread/realtime/error', 'thread/realtime/item/completed',
|
|
117
|
+
'thread/realtime/item/started', 'thread/realtime/item/transcript/delta', 'thread/realtime/itemAdded',
|
|
118
|
+
'thread/realtime/outputAudio/delta', 'thread/realtime/sdp', 'thread/realtime/started', 'thread/realtime/transcript/delta',
|
|
119
|
+
'thread/realtime/transcript/done', 'thread/reverted', 'thread/settings/updated', 'thread/started', 'thread/status/changed',
|
|
120
|
+
'thread/tokenUsage/updated', 'thread/unarchived', 'turn/completed', 'turn/diff/updated', 'turn/moderationMetadata',
|
|
121
|
+
'turn/plan/updated', 'turn/started', 'warning', 'windows/worldWritableWarning', 'windowsSandbox/setupCompleted',
|
|
122
|
+
]);
|
|
123
|
+
export const NATIVE_QUEUE_01621_NOTIFICATION_OPTOUTS = Object.freeze([
|
|
124
|
+
...NATIVE_QUEUE_NOTIFICATION_OPTOUTS, 'thread/prediction/updated',
|
|
125
|
+
]);
|
|
126
|
+
function nativeNotifications(version) {
|
|
127
|
+
if (version === '0.160.1')
|
|
128
|
+
return NATIVE_QUEUE_NOTIFICATION_OPTOUTS;
|
|
129
|
+
if (version === '0.162.1')
|
|
130
|
+
return NATIVE_QUEUE_01621_NOTIFICATION_OPTOUTS;
|
|
131
|
+
throw new AppServerFault('unsupported_version', false);
|
|
132
|
+
}
|
|
133
|
+
function disposeTransport(transport) {
|
|
134
|
+
return new Promise(resolve => {
|
|
135
|
+
const timer = setTimeout(resolve, APP_SERVER_LIMITS.cleanupMs);
|
|
136
|
+
Promise.resolve().then(() => transport.close()).catch(() => { }).finally(() => { clearTimeout(timer); resolve(); });
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
function object(value, keys) {
|
|
140
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) ||
|
|
141
|
+
Object.keys(value).length !== keys.length || keys.some(key => !Object.hasOwn(value, key)))
|
|
142
|
+
throw new Error('invalid');
|
|
143
|
+
return value;
|
|
144
|
+
}
|
|
145
|
+
function safeId(value, maximum = 128) {
|
|
146
|
+
return typeof value === 'string' && Buffer.byteLength(value) >= 1 && Buffer.byteLength(value) <= maximum &&
|
|
147
|
+
!/[\x00-\x1f\x7f-\x9f]/u.test(value) && [...value].every(char => {
|
|
148
|
+
const cp = char.codePointAt(0);
|
|
149
|
+
return cp < 0xd800 || cp > 0xdfff;
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
function validateQueueInput(input, attempted) {
|
|
153
|
+
if (!safeId(input.clientUserMessageId) || typeof input.message !== 'string' || !input.message ||
|
|
154
|
+
Buffer.byteLength(input.message) > APP_SERVER_LIMITS.messageBytes || input.message.includes('\0') ||
|
|
155
|
+
[...input.message].some(char => { const cp = char.codePointAt(0); return cp >= 0xd800 && cp <= 0xdfff; })) {
|
|
156
|
+
throw new AppServerFault('invalid_input', attempted);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
function scopeValue(value) {
|
|
160
|
+
const v = object(value, ['codexHome', 'threadId', 'generation', 'ownerIdentity']);
|
|
161
|
+
if (!safeId(v.codexHome, 4096) || !isAbsolute(v.codexHome) || !safeId(v.threadId) ||
|
|
162
|
+
!safeId(v.generation, 256) || !safeId(v.ownerIdentity, 512))
|
|
163
|
+
throw new Error('invalid');
|
|
164
|
+
return Object.freeze({ codexHome: v.codexHome, threadId: v.threadId, generation: v.generation, ownerIdentity: v.ownerIdentity });
|
|
165
|
+
}
|
|
166
|
+
function matches(left, right) {
|
|
167
|
+
return left.codexHome === right.codexHome && left.threadId === right.threadId &&
|
|
168
|
+
left.generation === right.generation && left.ownerIdentity === right.ownerIdentity;
|
|
169
|
+
}
|
|
170
|
+
export function parseMetadataEvent(value, original) {
|
|
171
|
+
try {
|
|
172
|
+
const kind = value?.kind;
|
|
173
|
+
const v = object(value, kind === 'injected' ? ['kind', 'scope', 'clientUserMessageId', 'itemId', 'turnId'] :
|
|
174
|
+
['kind', 'scope', 'clientUserMessageId', 'turnId', 'status']);
|
|
175
|
+
const scope = scopeValue(v.scope);
|
|
176
|
+
if (!matches(scope, original))
|
|
177
|
+
throw new AppServerFault('owner_changed', false);
|
|
178
|
+
if (!safeId(v.clientUserMessageId) || !safeId(v.turnId))
|
|
179
|
+
throw new Error('invalid');
|
|
180
|
+
if (kind === 'injected' && safeId(v.itemId))
|
|
181
|
+
return { kind, scope, clientUserMessageId: v.clientUserMessageId, itemId: v.itemId, turnId: v.turnId };
|
|
182
|
+
if (kind === 'turn' && typeof v.status === 'string' && ['running', 'completed', 'failed', 'interrupted', 'unknown'].includes(v.status)) {
|
|
183
|
+
return { kind, scope, clientUserMessageId: v.clientUserMessageId, turnId: v.turnId, status: v.status };
|
|
184
|
+
}
|
|
185
|
+
throw new Error('invalid');
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
if (error instanceof AppServerFault)
|
|
189
|
+
throw error;
|
|
190
|
+
throw new AppServerFault('frame_invalid', false);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
// Token-aware scanner rejects duplicate keys, non-integer numbers, deep input
|
|
194
|
+
// and trailing frames before JSON.parse loses that information. Native message
|
|
195
|
+
// text is outbound only; this parser accepts metadata fixture frames only.
|
|
196
|
+
function parseFrame(bytes) {
|
|
197
|
+
const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
198
|
+
let offset = 0;
|
|
199
|
+
const whitespace = () => { while (/[ \t\r\n]/.test(text[offset] ?? '\0'))
|
|
200
|
+
offset++; };
|
|
201
|
+
function string() {
|
|
202
|
+
const start = offset++;
|
|
203
|
+
while (offset < text.length) {
|
|
204
|
+
const char = text[offset++];
|
|
205
|
+
if (char === '\\')
|
|
206
|
+
offset++;
|
|
207
|
+
else if (char === '"')
|
|
208
|
+
return JSON.parse(text.slice(start, offset));
|
|
209
|
+
}
|
|
210
|
+
throw new Error('invalid');
|
|
211
|
+
}
|
|
212
|
+
function value(depth) {
|
|
213
|
+
if (depth > 8)
|
|
214
|
+
throw new Error('invalid');
|
|
215
|
+
whitespace();
|
|
216
|
+
const char = text[offset];
|
|
217
|
+
if (char === '"') {
|
|
218
|
+
string();
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (char === '{') {
|
|
222
|
+
offset++;
|
|
223
|
+
whitespace();
|
|
224
|
+
const keys = new Set();
|
|
225
|
+
if (text[offset] === '}') {
|
|
226
|
+
offset++;
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
while (true) {
|
|
230
|
+
whitespace();
|
|
231
|
+
if (text[offset] !== '"')
|
|
232
|
+
throw new Error('invalid');
|
|
233
|
+
const key = string();
|
|
234
|
+
if (keys.has(key))
|
|
235
|
+
throw new Error('invalid');
|
|
236
|
+
keys.add(key);
|
|
237
|
+
whitespace();
|
|
238
|
+
if (text[offset++] !== ':')
|
|
239
|
+
throw new Error('invalid');
|
|
240
|
+
value(depth + 1);
|
|
241
|
+
whitespace();
|
|
242
|
+
const end = text[offset++];
|
|
243
|
+
if (end === '}')
|
|
244
|
+
return;
|
|
245
|
+
if (end !== ',')
|
|
246
|
+
throw new Error('invalid');
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (char === '[') {
|
|
250
|
+
offset++;
|
|
251
|
+
whitespace();
|
|
252
|
+
if (text[offset] === ']') {
|
|
253
|
+
offset++;
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
while (true) {
|
|
257
|
+
value(depth + 1);
|
|
258
|
+
whitespace();
|
|
259
|
+
const end = text[offset++];
|
|
260
|
+
if (end === ']')
|
|
261
|
+
return;
|
|
262
|
+
if (end !== ',')
|
|
263
|
+
throw new Error('invalid');
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
for (const token of ['true', 'false', 'null'])
|
|
267
|
+
if (text.startsWith(token, offset)) {
|
|
268
|
+
offset += token.length;
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
const token = /^-?(?:0|[1-9][0-9]*)/.exec(text.slice(offset))?.[0];
|
|
272
|
+
if (!token || !Number.isSafeInteger(Number(token)))
|
|
273
|
+
throw new Error('invalid');
|
|
274
|
+
offset += token.length;
|
|
275
|
+
}
|
|
276
|
+
value(0);
|
|
277
|
+
whitespace();
|
|
278
|
+
if (offset !== text.length)
|
|
279
|
+
throw new Error('invalid');
|
|
280
|
+
return JSON.parse(text);
|
|
281
|
+
}
|
|
282
|
+
export class BoundedAppServerClient {
|
|
283
|
+
scope;
|
|
284
|
+
transport;
|
|
285
|
+
deadlineMs;
|
|
286
|
+
verifyOwner;
|
|
287
|
+
nativeQueue;
|
|
288
|
+
beforeEffect;
|
|
289
|
+
pending = new Map();
|
|
290
|
+
observers = new Set();
|
|
291
|
+
operations = new Set();
|
|
292
|
+
buffer = Buffer.alloc(0);
|
|
293
|
+
received = 0;
|
|
294
|
+
sent = 0;
|
|
295
|
+
frames = 0;
|
|
296
|
+
notifications = 0;
|
|
297
|
+
requests = 0;
|
|
298
|
+
reserved = false;
|
|
299
|
+
attempted = false;
|
|
300
|
+
clientId;
|
|
301
|
+
observations = 0;
|
|
302
|
+
observed = { injectionObserved: false };
|
|
303
|
+
injectedItemId;
|
|
304
|
+
fault;
|
|
305
|
+
closing;
|
|
306
|
+
timer;
|
|
307
|
+
constructor(scope, transport, deadlineMs, verifyOwner, nativeQueue = false, beforeEffect = async () => { }) {
|
|
308
|
+
this.scope = scope;
|
|
309
|
+
this.transport = transport;
|
|
310
|
+
this.deadlineMs = deadlineMs;
|
|
311
|
+
this.verifyOwner = verifyOwner;
|
|
312
|
+
this.nativeQueue = nativeQueue;
|
|
313
|
+
this.beforeEffect = beforeEffect;
|
|
314
|
+
this.timer = setTimeout(() => this.fail('deadline'), Math.max(1, deadlineMs - performance.now()));
|
|
315
|
+
transport.input.on('data', this.receive);
|
|
316
|
+
transport.input.once('end', this.ended);
|
|
317
|
+
transport.input.once('error', this.errored);
|
|
318
|
+
transport.output.on('error', this.writeErrored);
|
|
319
|
+
}
|
|
320
|
+
static async connectMetadataFixture(scope, transport, deadlineMs, verifyOwner) {
|
|
321
|
+
return this.connectWire(scope, transport, deadlineMs, verifyOwner, false);
|
|
322
|
+
}
|
|
323
|
+
// Hermetic test hook for the exact native RPC profile. It does not qualify a
|
|
324
|
+
// binary, platform or writer. Production callers use nativeQueueOnce instead.
|
|
325
|
+
// The profile table defaults to the frozen production rows; a hermetic test
|
|
326
|
+
// may supply a validated synthetic table, which never qualifies production.
|
|
327
|
+
static async connectNativeQueueFixture(scope, transport, deadlineMs, verifyOwner, beforeEffect, nativeVersion = APP_SERVER_EVIDENCE.version, platform = APP_SERVER_EVIDENCE.inspectedPlatform, profiles = NATIVE_PROFILES) {
|
|
328
|
+
return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, selectNativeProfile({ platform, version: nativeVersion }, validateNativeProfiles(profiles)));
|
|
329
|
+
}
|
|
330
|
+
static async connectNativeQueueWire(scope, transport, deadlineMs, verifyOwner, beforeEffect, profile) {
|
|
331
|
+
return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, profile);
|
|
332
|
+
}
|
|
333
|
+
static async connectWire(scope, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect = async () => { }, profile) {
|
|
334
|
+
let original;
|
|
335
|
+
try {
|
|
336
|
+
original = scopeValue(scope);
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
await disposeTransport(transport);
|
|
340
|
+
throw new AppServerFault('invalid_scope', false);
|
|
341
|
+
}
|
|
342
|
+
if (transport.qualification !== 'hermetic_fixture_only' && !(nativeQueue && transport.qualification === 'native_queue_only_stdio')) {
|
|
343
|
+
await disposeTransport(transport);
|
|
344
|
+
throw new AppServerFault('unsupported_transport', false);
|
|
345
|
+
}
|
|
346
|
+
const remaining = deadlineMs - performance.now();
|
|
347
|
+
if (!Number.isFinite(remaining) || remaining <= 0 || remaining > APP_SERVER_LIMITS.lifetimeMs) {
|
|
348
|
+
await disposeTransport(transport);
|
|
349
|
+
throw new AppServerFault('deadline', false);
|
|
350
|
+
}
|
|
351
|
+
const client = new BoundedAppServerClient(original, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect);
|
|
352
|
+
try {
|
|
353
|
+
await client.owner();
|
|
354
|
+
if (nativeQueue) {
|
|
355
|
+
if (!profile)
|
|
356
|
+
throw new AppServerFault('unsupported_version', false);
|
|
357
|
+
const nativeVersion = profile.version, notifications = nativeNotifications(nativeVersion);
|
|
358
|
+
const hello = object(await client.request('initialize', {
|
|
359
|
+
clientInfo: { name: 'session-peer-native-queue', version: '1' },
|
|
360
|
+
capabilities: { experimentalApi: true, optOutNotificationMethods: [...notifications] },
|
|
361
|
+
}), ['codexHome', 'platformFamily', 'platformOs', 'userAgent']);
|
|
362
|
+
if (hello.codexHome !== original.codexHome || hello.platformFamily !== 'unix' || hello.platformOs !== profile.platformOs ||
|
|
363
|
+
!safeId(hello.userAgent, 4096))
|
|
364
|
+
throw new AppServerFault('owner_changed', false);
|
|
365
|
+
// The queue process itself reports its compiled build; the earlier
|
|
366
|
+
// pathname's --version process cannot qualify a replacement process.
|
|
367
|
+
if (!hello.userAgent.startsWith(`session-peer-native-queue/${nativeVersion} (`))
|
|
368
|
+
throw new AppServerFault('unsupported_version', false);
|
|
369
|
+
client.notification('initialized');
|
|
370
|
+
}
|
|
371
|
+
else {
|
|
372
|
+
const hello = object(await client.request('session-peer/metadata/initialize', { scope: original }), ['scope', 'metadataOnly']);
|
|
373
|
+
if (hello.metadataOnly !== true || !matches(scopeValue(hello.scope), original))
|
|
374
|
+
throw new AppServerFault('owner_changed', false);
|
|
375
|
+
}
|
|
376
|
+
return client;
|
|
377
|
+
}
|
|
378
|
+
catch (error) {
|
|
379
|
+
client.fail(error instanceof AppServerFault ? error.code : 'frame_invalid');
|
|
380
|
+
await client.close();
|
|
381
|
+
throw client.fault;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
check() {
|
|
385
|
+
if (this.fault)
|
|
386
|
+
throw this.fault;
|
|
387
|
+
if (performance.now() >= this.deadlineMs) {
|
|
388
|
+
this.fail('deadline');
|
|
389
|
+
throw this.fault;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
async owner() {
|
|
393
|
+
this.check();
|
|
394
|
+
// The external verifier is the authority; echoed protocol tuples cannot
|
|
395
|
+
// qualify an endpoint or prove the live writer's ownership by themselves.
|
|
396
|
+
const result = await this.bounded(this.verifyOwner(this.scope));
|
|
397
|
+
this.check();
|
|
398
|
+
if (!result) {
|
|
399
|
+
this.fail('owner_changed');
|
|
400
|
+
throw this.fault;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
bounded(promise, failureCode = 'owner_changed') {
|
|
404
|
+
return new Promise((resolve, reject) => {
|
|
405
|
+
const wait = { reject };
|
|
406
|
+
this.operations.add(wait);
|
|
407
|
+
promise.then(value => { this.operations.delete(wait); resolve(value); }, () => {
|
|
408
|
+
this.operations.delete(wait);
|
|
409
|
+
this.fail(failureCode);
|
|
410
|
+
reject(this.fault);
|
|
411
|
+
});
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
ended = () => { this.fail(this.buffer.length ? 'frame_invalid' : 'connection_closed'); };
|
|
415
|
+
errored = () => { this.fail('connection_closed'); };
|
|
416
|
+
writeErrored = () => { this.fail('write_failed'); };
|
|
417
|
+
receive = (chunk) => {
|
|
418
|
+
if (this.fault)
|
|
419
|
+
return;
|
|
420
|
+
const bytes = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
|
|
421
|
+
this.received += bytes.length;
|
|
422
|
+
if (this.received > APP_SERVER_LIMITS.receivedBytes) {
|
|
423
|
+
this.fail('traffic_limit');
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
let start = 0;
|
|
427
|
+
while (start < bytes.length && !this.fault) {
|
|
428
|
+
const end = bytes.indexOf(10, start), stop = end < 0 ? bytes.length : end + 1;
|
|
429
|
+
if (this.buffer.length + stop - start > APP_SERVER_LIMITS.frameBytes) {
|
|
430
|
+
this.fail('frame_limit');
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
this.buffer = Buffer.concat([this.buffer, bytes.subarray(start, stop)]);
|
|
434
|
+
start = stop;
|
|
435
|
+
if (end >= 0) {
|
|
436
|
+
const frame = this.buffer;
|
|
437
|
+
this.buffer = Buffer.alloc(0);
|
|
438
|
+
try {
|
|
439
|
+
if (++this.frames > APP_SERVER_LIMITS.frames) {
|
|
440
|
+
this.fail('traffic_limit');
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
this.frame(parseFrame(frame));
|
|
444
|
+
}
|
|
445
|
+
catch (error) {
|
|
446
|
+
this.fail(error instanceof AppServerFault ? error.code : 'frame_invalid');
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
frame(value) {
|
|
452
|
+
if (value && typeof value === 'object' && Object.hasOwn(value, 'method')) {
|
|
453
|
+
if (this.nativeQueue)
|
|
454
|
+
throw new AppServerFault('unsupported_transport', this.attempted);
|
|
455
|
+
const event = object(value, ['method', 'params']);
|
|
456
|
+
if (event.method !== 'session-peer/metadata/event')
|
|
457
|
+
throw new Error('invalid');
|
|
458
|
+
if (++this.notifications > APP_SERVER_LIMITS.notifications) {
|
|
459
|
+
this.fail('notification_limit');
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
const metadata = parseMetadataEvent(event.params, this.scope);
|
|
463
|
+
if (metadata.clientUserMessageId !== this.clientId)
|
|
464
|
+
return;
|
|
465
|
+
if (metadata.kind === 'injected') {
|
|
466
|
+
if (this.observed.injectionObserved) {
|
|
467
|
+
if (this.injectedItemId !== metadata.itemId || this.observed.turn?.id !== metadata.turnId)
|
|
468
|
+
throw new Error('invalid');
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
this.injectedItemId = metadata.itemId;
|
|
472
|
+
this.observed = { injectionObserved: true, clientUserMessageId: this.clientId, turn: { id: metadata.turnId, status: 'unknown' } };
|
|
473
|
+
}
|
|
474
|
+
else if (this.observed.injectionObserved && this.observed.turn?.id === metadata.turnId) {
|
|
475
|
+
this.observed = { ...this.observed, turn: { id: metadata.turnId, status: metadata.status } };
|
|
476
|
+
}
|
|
477
|
+
else
|
|
478
|
+
return; // Turn completion or a queue disappearance never proves injection.
|
|
479
|
+
for (const observer of this.observers)
|
|
480
|
+
observer.resolve(this.snapshot());
|
|
481
|
+
this.observers.clear();
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
const response = object(value, Object.hasOwn(value, 'error') ? ['id', 'error'] : ['id', 'result']);
|
|
485
|
+
if (typeof response.id !== 'number' || !Number.isSafeInteger(response.id) || response.id < 1)
|
|
486
|
+
throw new Error('invalid');
|
|
487
|
+
const pending = this.pending.get(response.id);
|
|
488
|
+
if (!pending)
|
|
489
|
+
throw new Error('invalid');
|
|
490
|
+
if (Object.hasOwn(response, 'error')) {
|
|
491
|
+
if (!this.nativeQueue) {
|
|
492
|
+
const error = object(response.error, ['code']);
|
|
493
|
+
if (!['unsupported', 'refused', 'failed'].includes(String(error.code)))
|
|
494
|
+
throw new Error('invalid');
|
|
495
|
+
} // Native RPC error text/data may be sensitive and is never exposed.
|
|
496
|
+
this.pending.delete(response.id);
|
|
497
|
+
pending.reject(new AppServerFault('remote_refused', this.attempted));
|
|
498
|
+
}
|
|
499
|
+
else {
|
|
500
|
+
this.pending.delete(response.id);
|
|
501
|
+
pending.resolve(response.result);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
notification(method) {
|
|
505
|
+
this.check();
|
|
506
|
+
const bytes = Buffer.from(JSON.stringify({ method }) + '\n');
|
|
507
|
+
this.sent += bytes.length;
|
|
508
|
+
if (this.sent > APP_SERVER_LIMITS.sentBytes) {
|
|
509
|
+
this.fail('frame_limit');
|
|
510
|
+
throw this.fault;
|
|
511
|
+
}
|
|
512
|
+
try {
|
|
513
|
+
this.transport.output.write(bytes, error => { if (error)
|
|
514
|
+
this.fail('write_failed'); });
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
this.fail('write_failed');
|
|
518
|
+
throw this.fault;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
async request(method, params, effect = false) {
|
|
522
|
+
this.check();
|
|
523
|
+
if (++this.requests > APP_SERVER_LIMITS.requests) {
|
|
524
|
+
this.fail('request_limit');
|
|
525
|
+
return Promise.reject(this.fault);
|
|
526
|
+
}
|
|
527
|
+
const id = this.requests, bytes = Buffer.from(JSON.stringify({ id, method, params }) + '\n');
|
|
528
|
+
this.sent += bytes.length;
|
|
529
|
+
if (bytes.length > APP_SERVER_LIMITS.frameBytes || this.sent > APP_SERVER_LIMITS.sentBytes) {
|
|
530
|
+
this.fail('frame_limit');
|
|
531
|
+
return Promise.reject(this.fault);
|
|
532
|
+
}
|
|
533
|
+
if (effect) {
|
|
534
|
+
try {
|
|
535
|
+
await this.bounded(this.beforeEffect(), 'effect_guard_failed');
|
|
536
|
+
}
|
|
537
|
+
catch {
|
|
538
|
+
this.fail('effect_guard_failed');
|
|
539
|
+
throw this.fault;
|
|
540
|
+
}
|
|
541
|
+
// Durable intent/effect fencing can await I/O. Recheck the ORIGINAL
|
|
542
|
+
// owner after that await, before marking an attempt or writing the RPC.
|
|
543
|
+
// The ledger may already be fenced; this never authorizes a new effect.
|
|
544
|
+
await this.owner();
|
|
545
|
+
this.check();
|
|
546
|
+
}
|
|
547
|
+
return new Promise((resolve, reject) => {
|
|
548
|
+
if (effect)
|
|
549
|
+
this.attempted = true; // Before write, after local frame/budget validation.
|
|
550
|
+
this.pending.set(id, { resolve, reject });
|
|
551
|
+
try {
|
|
552
|
+
this.transport.output.write(bytes, error => { if (error)
|
|
553
|
+
this.fail('write_failed'); });
|
|
554
|
+
}
|
|
555
|
+
catch {
|
|
556
|
+
this.fail('write_failed');
|
|
557
|
+
}
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
async queueOnce(input) {
|
|
561
|
+
this.check();
|
|
562
|
+
validateQueueInput(input, this.attempted);
|
|
563
|
+
if (this.reserved)
|
|
564
|
+
throw new AppServerFault('already_attempted', true);
|
|
565
|
+
this.reserved = true;
|
|
566
|
+
try {
|
|
567
|
+
await this.owner();
|
|
568
|
+
this.check();
|
|
569
|
+
this.clientId = input.clientUserMessageId;
|
|
570
|
+
if (this.nativeQueue) {
|
|
571
|
+
const result = object(await this.request('thread/queue/add', {
|
|
572
|
+
threadId: this.scope.threadId, clientUserMessageId: input.clientUserMessageId,
|
|
573
|
+
input: [{ type: 'text', text: input.message, text_elements: [] }],
|
|
574
|
+
}, true), ['queuedSubmission']);
|
|
575
|
+
const queued = object(result.queuedSubmission, ['id', 'input', 'clientUserMessageId']);
|
|
576
|
+
if (!safeId(queued.id) || queued.clientUserMessageId !== input.clientUserMessageId || !Array.isArray(queued.input) || queued.input.length !== 1)
|
|
577
|
+
throw new Error('invalid');
|
|
578
|
+
const ownInput = object(queued.input[0], Object.hasOwn(queued.input[0], 'text_elements') ? ['type', 'text', 'text_elements'] : ['type', 'text']);
|
|
579
|
+
if (ownInput.type !== 'text' || ownInput.text !== input.message || (Object.hasOwn(ownInput, 'text_elements') &&
|
|
580
|
+
(!Array.isArray(ownInput.text_elements) || ownInput.text_elements.length)))
|
|
581
|
+
throw new Error('invalid');
|
|
582
|
+
return { queueId: queued.id, clientUserMessageId: input.clientUserMessageId };
|
|
583
|
+
}
|
|
584
|
+
const result = object(await this.request('session-peer/metadata/queue', {
|
|
585
|
+
scope: this.scope, clientUserMessageId: input.clientUserMessageId, input: [{ type: 'text', text: input.message }],
|
|
586
|
+
}, true), ['scope', 'queueId', 'clientUserMessageId']);
|
|
587
|
+
if (!matches(scopeValue(result.scope), this.scope) || result.clientUserMessageId !== this.clientId || !safeId(result.queueId))
|
|
588
|
+
throw new Error('invalid');
|
|
589
|
+
return { queueId: result.queueId, clientUserMessageId: this.clientId };
|
|
590
|
+
}
|
|
591
|
+
catch (error) {
|
|
592
|
+
this.fail(error instanceof AppServerFault ? error.code : 'frame_invalid');
|
|
593
|
+
await this.close();
|
|
594
|
+
throw this.fault;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
snapshot() { return { ...this.observed, ...(this.observed.turn ? { turn: { ...this.observed.turn } } : {}) }; }
|
|
598
|
+
async observe(clientUserMessageId) {
|
|
599
|
+
this.check();
|
|
600
|
+
if (this.nativeQueue)
|
|
601
|
+
throw new AppServerFault('unsupported_transport', this.attempted);
|
|
602
|
+
if (!safeId(clientUserMessageId) || clientUserMessageId !== this.clientId || !this.attempted)
|
|
603
|
+
throw new AppServerFault('invalid_input', this.attempted);
|
|
604
|
+
if (++this.observations > APP_SERVER_LIMITS.observations) {
|
|
605
|
+
this.fail('request_limit');
|
|
606
|
+
throw this.fault;
|
|
607
|
+
}
|
|
608
|
+
if (this.observed.injectionObserved)
|
|
609
|
+
return this.snapshot();
|
|
610
|
+
return new Promise((resolve, reject) => { this.observers.add({ resolve, reject }); });
|
|
611
|
+
}
|
|
612
|
+
fail(code) {
|
|
613
|
+
if (this.fault)
|
|
614
|
+
return;
|
|
615
|
+
this.fault = new AppServerFault(code, this.attempted);
|
|
616
|
+
clearTimeout(this.timer);
|
|
617
|
+
for (const wait of this.pending.values())
|
|
618
|
+
wait.reject(this.fault);
|
|
619
|
+
this.pending.clear();
|
|
620
|
+
for (const observer of this.observers)
|
|
621
|
+
observer.reject(this.fault);
|
|
622
|
+
this.observers.clear();
|
|
623
|
+
for (const operation of this.operations)
|
|
624
|
+
operation.reject(this.fault);
|
|
625
|
+
this.operations.clear();
|
|
626
|
+
void this.close();
|
|
627
|
+
}
|
|
628
|
+
close() {
|
|
629
|
+
if (this.closing)
|
|
630
|
+
return this.closing;
|
|
631
|
+
clearTimeout(this.timer);
|
|
632
|
+
if (!this.fault) {
|
|
633
|
+
this.fault = new AppServerFault('connection_closed', this.attempted);
|
|
634
|
+
for (const wait of this.pending.values())
|
|
635
|
+
wait.reject(this.fault);
|
|
636
|
+
this.pending.clear();
|
|
637
|
+
for (const observer of this.observers)
|
|
638
|
+
observer.reject(this.fault);
|
|
639
|
+
this.observers.clear();
|
|
640
|
+
for (const operation of this.operations)
|
|
641
|
+
operation.reject(this.fault);
|
|
642
|
+
this.operations.clear();
|
|
643
|
+
}
|
|
644
|
+
this.transport.input.removeListener('data', this.receive);
|
|
645
|
+
this.transport.input.removeListener('end', this.ended);
|
|
646
|
+
this.transport.input.removeListener('error', this.errored);
|
|
647
|
+
// Keep a safe error listener during disposal so pipe shutdown cannot become
|
|
648
|
+
// an uncaught exception. Never retain native stderr or message text.
|
|
649
|
+
this.transport.input.on('error', () => { });
|
|
650
|
+
this.transport.output.removeListener('error', this.writeErrored);
|
|
651
|
+
this.transport.output.on('error', () => { });
|
|
652
|
+
this.closing = disposeTransport(this.transport);
|
|
653
|
+
return this.closing;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
async function beforeDeadline(deadlineMs, operation, code) {
|
|
657
|
+
const remaining = deadlineMs - performance.now();
|
|
658
|
+
if (!Number.isFinite(remaining) || remaining <= 0 || remaining > APP_SERVER_LIMITS.lifetimeMs)
|
|
659
|
+
throw new AppServerFault('deadline', false);
|
|
660
|
+
return new Promise((resolve, reject) => {
|
|
661
|
+
const timer = setTimeout(() => reject(new AppServerFault('deadline', false)), remaining);
|
|
662
|
+
Promise.resolve().then(operation).then(value => { clearTimeout(timer); resolve(value); }, () => {
|
|
663
|
+
clearTimeout(timer);
|
|
664
|
+
reject(new AppServerFault(code, false));
|
|
665
|
+
});
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
async function verifyOwnedSqliteBinding(pid, home, deadlineMs) {
|
|
669
|
+
if (!pid || pid < 2 || performance.now() >= deadlineMs)
|
|
670
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
671
|
+
verifyOpenedSqlite(await darwinOpenedFiles(pid, deadlineMs), home);
|
|
672
|
+
}
|
|
673
|
+
async function darwinOpenedFiles(pid, deadlineMs) {
|
|
674
|
+
// Only the owned app-server PID is queried, never a session inventory/PID scan.
|
|
675
|
+
// An exact managed requirement can override both env and CLI sqlite_home.
|
|
676
|
+
// initialize.codexHome does not attest to effective SQLite storage; require
|
|
677
|
+
// actual opened state/queue paths before authorizing the root effect guard.
|
|
678
|
+
const remaining = deadlineMs - performance.now();
|
|
679
|
+
if (remaining <= 0)
|
|
680
|
+
throw new AppServerFault('deadline', false);
|
|
681
|
+
const result = await run('/usr/sbin/lsof', ['-a', '-p', String(pid), '-F0fDin'], {
|
|
682
|
+
timeout: remaining, limit: 65536,
|
|
683
|
+
env: { PATH: '/usr/bin:/bin:/usr/sbin:/sbin', LC_ALL: 'C', LANG: 'C' },
|
|
684
|
+
});
|
|
685
|
+
if (performance.now() >= deadlineMs)
|
|
686
|
+
throw new AppServerFault('deadline', false);
|
|
687
|
+
if (result.code !== 0 || result.interrupted)
|
|
688
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
689
|
+
const files = [];
|
|
690
|
+
let current;
|
|
691
|
+
for (const raw of result.stdout.split('\0')) {
|
|
692
|
+
const field = raw.replace(/^\n/, '');
|
|
693
|
+
if (field.startsWith('f')) {
|
|
694
|
+
current = {};
|
|
695
|
+
files.push(current);
|
|
696
|
+
}
|
|
697
|
+
else if (current && field.startsWith('n'))
|
|
698
|
+
current.name = lsofFilename(field.slice(1));
|
|
699
|
+
else if (current && /^D0x[0-9a-f]+$/i.test(field))
|
|
700
|
+
current.dev = BigInt(field.slice(1));
|
|
701
|
+
else if (current && /^i[0-9]+$/.test(field))
|
|
702
|
+
current.ino = BigInt(field.slice(1));
|
|
703
|
+
}
|
|
704
|
+
return files;
|
|
705
|
+
}
|
|
706
|
+
// Exact canonical state/queue paths (and only their own WAL/SHM sidecars) must
|
|
707
|
+
// be opened by the owned PID with the inode now at that canonical path.
|
|
708
|
+
function verifyOpenedSqlite(files, home) {
|
|
709
|
+
const required = ['state_5.sqlite', 'queue_1.sqlite'];
|
|
710
|
+
for (const file of required) {
|
|
711
|
+
const expected = join(home, file);
|
|
712
|
+
const opened = files.filter(row => row.name && [file, file + '-wal', file + '-shm'].includes(basename(row.name)));
|
|
713
|
+
if (!opened.some(row => row.name === expected))
|
|
714
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
715
|
+
for (const row of opened) {
|
|
716
|
+
if (row.deleted || ![expected, expected + '-wal', expected + '-shm'].includes(row.name))
|
|
717
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
718
|
+
try {
|
|
719
|
+
const canonical = lstatSync(row.name, { bigint: true });
|
|
720
|
+
if (!canonical.isFile() || canonical.isSymbolicLink() || row.dev !== canonical.dev || row.ino !== canonical.ino)
|
|
721
|
+
throw new Error('storage identity changed');
|
|
722
|
+
}
|
|
723
|
+
catch {
|
|
724
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
// Synchronous native-profile I/O (executable digest, procfs walk) runs in an
|
|
730
|
+
// owned worker. Supervisor refusal boundary for that worker only: run()
|
|
731
|
+
// requests termination of its group (SIGKILL) at the original remaining
|
|
732
|
+
// budget and beforeDeadline() refuses at that deadline; actual reaping of a
|
|
733
|
+
// worker blocked in uninterruptible kernel I/O may occur later. Caller-side realpath/stat/lstat (executable identity,
|
|
734
|
+
// canonical SQLite paths) stay synchronous here, as on Darwin, and are only
|
|
735
|
+
// followed by deadline checks; they have no execution-time bound.
|
|
736
|
+
async function nativeWorker(args, deadlineMs) {
|
|
737
|
+
const extension = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
738
|
+
const worker = fileURLToPath(new URL('./linux-native-probe' + extension, import.meta.url));
|
|
739
|
+
return beforeDeadline(deadlineMs, async () => {
|
|
740
|
+
const result = await run(process.execPath, [...(extension === '.ts' ? ['--experimental-strip-types'] : []), worker, ...args], {
|
|
741
|
+
timeout: Math.max(1, deadlineMs - performance.now()), limit: 1024 * 1024,
|
|
742
|
+
env: { PATH: '/usr/bin:/bin', LC_ALL: 'C', LANG: 'C' }
|
|
743
|
+
});
|
|
744
|
+
if (result.code !== 0 || result.interrupted)
|
|
745
|
+
return undefined;
|
|
746
|
+
const value = JSON.parse(result.stdout);
|
|
747
|
+
return value && value.ok === true ? value : undefined;
|
|
748
|
+
}, 'unsupported_version');
|
|
749
|
+
}
|
|
750
|
+
// Complete pinned-executable digest within the original deadline.
|
|
751
|
+
export async function artifactDigest(path, deadlineMs, maxBytes = 512 * 1024 * 1024) {
|
|
752
|
+
const value = await nativeWorker(['digest', path, process.platform, process.arch, String(maxBytes)], deadlineMs);
|
|
753
|
+
if (performance.now() >= deadlineMs)
|
|
754
|
+
throw new AppServerFault('deadline', false);
|
|
755
|
+
if (typeof value?.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(value.sha256))
|
|
756
|
+
throw new AppServerFault('unsupported_version', false);
|
|
757
|
+
return value.sha256;
|
|
758
|
+
}
|
|
759
|
+
// Linux: read only the owned child's /proc entries. The executable inode is the
|
|
760
|
+
// selected native artifact, so a script/npm shim whose exe is an interpreter is
|
|
761
|
+
// refused rather than trusted to have exec'd the right storage owner. An
|
|
762
|
+
// injected reader (hermetic tests) runs in-process; production uses the worker.
|
|
763
|
+
export async function verifyProcfsSqliteBinding(pid, home, deadlineMs, binary, reader) {
|
|
764
|
+
if (!pid || pid < 2 || performance.now() >= deadlineMs)
|
|
765
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
766
|
+
let files;
|
|
767
|
+
const uid = process.getuid?.();
|
|
768
|
+
if (uid === undefined)
|
|
769
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
770
|
+
if (reader) {
|
|
771
|
+
try {
|
|
772
|
+
const exe = statSync(realpathSync(binary), { bigint: true });
|
|
773
|
+
files = procOwnedFiles(pid, process.pid, uid, { dev: exe.dev, ino: exe.ino }, reader);
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
else {
|
|
780
|
+
let value;
|
|
781
|
+
try {
|
|
782
|
+
value = await nativeWorker(['bind', String(pid), String(process.pid), String(uid), binary], deadlineMs);
|
|
783
|
+
}
|
|
784
|
+
catch (error) {
|
|
785
|
+
throw error instanceof AppServerFault && error.code === 'deadline' ? error : new AppServerFault('storage_binding_unverified', false);
|
|
786
|
+
}
|
|
787
|
+
if (!Array.isArray(value?.files))
|
|
788
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
789
|
+
try {
|
|
790
|
+
files = value.files.map(file => ({
|
|
791
|
+
name: file.name, dev: BigInt(file.dev), ino: BigInt(file.ino), deleted: file.deleted === true
|
|
792
|
+
}));
|
|
793
|
+
}
|
|
794
|
+
catch {
|
|
795
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
if (performance.now() >= deadlineMs)
|
|
799
|
+
throw new AppServerFault('deadline', false);
|
|
800
|
+
verifyOpenedSqlite(files, home);
|
|
801
|
+
}
|
|
802
|
+
// lsof field output escapes backslashes and non-ASCII bytes even with NUL field
|
|
803
|
+
// delimiters. Decode the protected system tool's filename representation, then
|
|
804
|
+
// compare exact canonical paths; never accept a prefix/substring match.
|
|
805
|
+
function lsofFilename(raw) {
|
|
806
|
+
const bytes = [];
|
|
807
|
+
for (let i = 0; i < raw.length; i++) {
|
|
808
|
+
if (raw[i] !== '\\') {
|
|
809
|
+
const char = String.fromCodePoint(raw.codePointAt(i));
|
|
810
|
+
bytes.push(...Buffer.from(char));
|
|
811
|
+
i += char.length - 1;
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
const next = raw[++i];
|
|
815
|
+
if (next === '\\') {
|
|
816
|
+
bytes.push(92);
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
if (next === 'x' && /^[0-9a-f]{2}$/i.test(raw.slice(i + 1, i + 3))) {
|
|
820
|
+
bytes.push(parseInt(raw.slice(i + 1, i + 3), 16));
|
|
821
|
+
i += 2;
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
825
|
+
}
|
|
826
|
+
try {
|
|
827
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(bytes));
|
|
828
|
+
}
|
|
829
|
+
catch {
|
|
830
|
+
throw new AppServerFault('storage_binding_unverified', false);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
function executableIdentity(binary) {
|
|
834
|
+
try {
|
|
835
|
+
const path = realpathSync(binary), info = statSync(path, { bigint: true });
|
|
836
|
+
if (!info.isFile())
|
|
837
|
+
throw new Error('not a file');
|
|
838
|
+
return JSON.stringify([path, info.dev.toString(), info.ino.toString(), info.size.toString(), info.mtimeNs.toString(), info.ctimeNs.toString()]);
|
|
839
|
+
}
|
|
840
|
+
catch {
|
|
841
|
+
throw new AppServerFault('unsupported_version', false);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
function verifyExecutableIdentity(binary, expected) {
|
|
845
|
+
if (executableIdentity(binary) !== expected)
|
|
846
|
+
throw new AppServerFault('unsupported_version', false);
|
|
847
|
+
}
|
|
848
|
+
// Queue mechanics were verified only for the exact listed versions/platform
|
|
849
|
+
// in a network-denied synthetic home. This is not a live delivery/ACK claim.
|
|
850
|
+
// Root integration owns generation, canonical home, storage and writer guards.
|
|
851
|
+
// This function never invokes thread start/resume/read/list or a model turn.
|
|
852
|
+
export function nativeQueueOnce(options) {
|
|
853
|
+
return nativeQueueOnceWithProfiles(options, NATIVE_PROFILES);
|
|
854
|
+
}
|
|
855
|
+
// Hermetic test hook: a synthetic, validated profile table exercises another
|
|
856
|
+
// platform's selection and binding path. Production uses only NATIVE_PROFILES.
|
|
857
|
+
export async function nativeQueueOnceWithProfiles(options, table) {
|
|
858
|
+
const profiles = validateNativeProfiles(table), platform = `${process.platform}-${process.arch}`;
|
|
859
|
+
if (!platformProfiled(platform, profiles))
|
|
860
|
+
throw new AppServerFault('unsupported_transport', false);
|
|
861
|
+
let original;
|
|
862
|
+
try {
|
|
863
|
+
original = scopeValue(options.scope);
|
|
864
|
+
}
|
|
865
|
+
catch {
|
|
866
|
+
throw new AppServerFault('invalid_scope', false);
|
|
867
|
+
}
|
|
868
|
+
if (!isAbsolute(options.binary) || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(original.threadId))
|
|
869
|
+
throw new AppServerFault('invalid_input', false);
|
|
870
|
+
// Reject malformed effect input before even a version probe or bootstrap can
|
|
871
|
+
// start the binary and access/create native files in the selected home.
|
|
872
|
+
validateQueueInput(options, false);
|
|
873
|
+
// In the qualified versions config.sqlite_home precedes CODEX_SQLITE_HOME. Pin BOTH env and
|
|
874
|
+
// a quoted CLI value so an ordinary config A->B->A load cannot redirect us.
|
|
875
|
+
// Managed policy can still supersede the CLI pin, hence the FD-path check.
|
|
876
|
+
const env = { ...(options.env ?? process.env), CODEX_HOME: original.codexHome,
|
|
877
|
+
CODEX_SQLITE_HOME: original.codexHome };
|
|
878
|
+
if (!await beforeDeadline(options.deadlineMs, () => options.verifyOwner(original), 'owner_changed'))
|
|
879
|
+
throw new AppServerFault('owner_changed', false);
|
|
880
|
+
if (performance.now() >= options.deadlineMs)
|
|
881
|
+
throw new AppServerFault('deadline', false);
|
|
882
|
+
const binaryIdentity = executableIdentity(options.binary);
|
|
883
|
+
const probeRemaining = options.deadlineMs - performance.now();
|
|
884
|
+
if (probeRemaining <= 0)
|
|
885
|
+
throw new AppServerFault('deadline', false);
|
|
886
|
+
const version = await run(options.binary, ['--version'], {
|
|
887
|
+
env, timeout: probeRemaining, limit: 4096,
|
|
888
|
+
});
|
|
889
|
+
if (performance.now() >= options.deadlineMs)
|
|
890
|
+
throw new AppServerFault('deadline', false);
|
|
891
|
+
const nativeVersion = version.stdout.trim().slice('codex-cli '.length);
|
|
892
|
+
const profile = selectNativeProfile({ platform, version: nativeVersion }, profiles);
|
|
893
|
+
if (version.interrupted || version.code !== 0 || !profile || version.stdout.trim() !== `codex-cli ${nativeVersion}`) {
|
|
894
|
+
throw new AppServerFault('unsupported_version', false);
|
|
895
|
+
}
|
|
896
|
+
verifyExecutableIdentity(options.binary, binaryIdentity);
|
|
897
|
+
if (performance.now() >= options.deadlineMs)
|
|
898
|
+
throw new AppServerFault('deadline', false);
|
|
899
|
+
if (profile.artifact) {
|
|
900
|
+
// Pinned executable bytes, hashed within the original deadline; the stable
|
|
901
|
+
// identity check below proves the hashed inode is the one spawned next.
|
|
902
|
+
let digest;
|
|
903
|
+
try {
|
|
904
|
+
digest = await artifactDigest(realpathSync(options.binary), options.deadlineMs);
|
|
905
|
+
}
|
|
906
|
+
catch {
|
|
907
|
+
throw new AppServerFault(performance.now() >= options.deadlineMs ? 'deadline' : 'unsupported_version', false);
|
|
908
|
+
}
|
|
909
|
+
if (digest !== profile.artifact.sha256)
|
|
910
|
+
throw new AppServerFault('unsupported_version', false);
|
|
911
|
+
verifyExecutableIdentity(options.binary, binaryIdentity);
|
|
912
|
+
if (performance.now() >= options.deadlineMs)
|
|
913
|
+
throw new AppServerFault('deadline', false);
|
|
914
|
+
}
|
|
915
|
+
const bind = async (pid) => profile.storageBinding === 'linux_procfs' ?
|
|
916
|
+
verifyProcfsSqliteBinding(pid, original.codexHome, options.deadlineMs, options.binary) :
|
|
917
|
+
verifyOwnedSqliteBinding(pid, original.codexHome, options.deadlineMs);
|
|
918
|
+
const transport = { qualification: 'native_queue_only_stdio',
|
|
919
|
+
...spawnOwnedStdio(options.binary, ['app-server', '--stdio', '-c', 'analytics.enabled=false',
|
|
920
|
+
'-c', `sqlite_home=${JSON.stringify(original.codexHome)}`], env, original.codexHome) };
|
|
921
|
+
let client;
|
|
922
|
+
try {
|
|
923
|
+
verifyExecutableIdentity(options.binary, binaryIdentity);
|
|
924
|
+
let effectGuarded = false;
|
|
925
|
+
client = await BoundedAppServerClient.connectNativeQueueWire(original, transport, options.deadlineMs, async (scope) => {
|
|
926
|
+
const valid = await options.verifyOwner(scope);
|
|
927
|
+
if (valid && effectGuarded) {
|
|
928
|
+
// Run after the LAST asynchronous owner verification. The durable guard
|
|
929
|
+
// and owner probe can both await I/O and change canonical file bindings.
|
|
930
|
+
verifyExecutableIdentity(options.binary, binaryIdentity);
|
|
931
|
+
await bind(transport.pid);
|
|
932
|
+
}
|
|
933
|
+
return valid;
|
|
934
|
+
}, async () => { await options.beforeEffect(); effectGuarded = true; }, profile);
|
|
935
|
+
await bind(transport.pid);
|
|
936
|
+
return await client.queueOnce({ clientUserMessageId: options.clientUserMessageId, message: options.message });
|
|
937
|
+
}
|
|
938
|
+
finally {
|
|
939
|
+
if (client)
|
|
940
|
+
await client.close();
|
|
941
|
+
else
|
|
942
|
+
await disposeTransport(transport);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
const ownedGroups = new Set();
|
|
946
|
+
const terminationSignals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
947
|
+
function reapOwned(pid) { try {
|
|
948
|
+
process.kill(-pid, 'SIGKILL');
|
|
949
|
+
}
|
|
950
|
+
catch { /* Already gone. */ } }
|
|
951
|
+
function processExit() { for (const pid of ownedGroups)
|
|
952
|
+
reapOwned(pid); }
|
|
953
|
+
function terminateOwned(signal) {
|
|
954
|
+
processExit();
|
|
955
|
+
ownedGroups.clear();
|
|
956
|
+
for (const name of terminationSignals)
|
|
957
|
+
process.removeListener(name, terminateOwned);
|
|
958
|
+
process.removeListener('exit', processExit);
|
|
959
|
+
process.kill(process.pid, signal);
|
|
960
|
+
}
|
|
961
|
+
function registerOwned(pid) {
|
|
962
|
+
if (!pid || ownedGroups.has(pid))
|
|
963
|
+
return;
|
|
964
|
+
if (!ownedGroups.size) {
|
|
965
|
+
for (const name of terminationSignals)
|
|
966
|
+
process.on(name, terminateOwned);
|
|
967
|
+
process.on('exit', processExit);
|
|
968
|
+
}
|
|
969
|
+
ownedGroups.add(pid);
|
|
970
|
+
}
|
|
971
|
+
function releaseOwned(pid) {
|
|
972
|
+
if (!pid || !ownedGroups.delete(pid) || ownedGroups.size)
|
|
973
|
+
return;
|
|
974
|
+
for (const name of terminationSignals)
|
|
975
|
+
process.removeListener(name, terminateOwned);
|
|
976
|
+
process.removeListener('exit', processExit);
|
|
977
|
+
}
|
|
978
|
+
// POSIX groups reap owned descendants. Only darwin-arm64 rows are selectable;
|
|
979
|
+
// Linux uses the same owned group in hermetic and candidate checks. Windows
|
|
980
|
+
// resource cleanup remains unqualified.
|
|
981
|
+
function spawnOwnedStdio(binary, args, env, cwd) {
|
|
982
|
+
if (process.platform === 'win32')
|
|
983
|
+
throw new AppServerFault('unsupported_transport', false);
|
|
984
|
+
const child = spawn(binary, args, { env, cwd, shell: false, detached: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
985
|
+
let stderrBytes = 0, closed = false, stopped = false;
|
|
986
|
+
let lifetime;
|
|
987
|
+
const register = () => {
|
|
988
|
+
if (closed || stopped || child.exitCode !== null || child.signalCode !== null)
|
|
989
|
+
return;
|
|
990
|
+
registerOwned(child.pid);
|
|
991
|
+
};
|
|
992
|
+
const stopOwned = () => {
|
|
993
|
+
if (stopped)
|
|
994
|
+
return;
|
|
995
|
+
stopped = true;
|
|
996
|
+
child.removeListener('spawn', register);
|
|
997
|
+
if (lifetime)
|
|
998
|
+
clearTimeout(lifetime);
|
|
999
|
+
if (child.pid && ownedGroups.has(child.pid))
|
|
1000
|
+
reapOwned(child.pid);
|
|
1001
|
+
releaseOwned(child.pid);
|
|
1002
|
+
};
|
|
1003
|
+
register();
|
|
1004
|
+
child.once('spawn', register);
|
|
1005
|
+
// Release the lifetime/registry as soon as this child exits; late close calls
|
|
1006
|
+
// must not reap a former PID again. Reap any remaining owned descendants now.
|
|
1007
|
+
child.once('exit', stopOwned);
|
|
1008
|
+
child.stdout.on('error', () => { });
|
|
1009
|
+
child.stdin.on('error', () => { });
|
|
1010
|
+
// Also bound a fixture transport whose caller fails before attaching a client.
|
|
1011
|
+
lifetime = setTimeout(() => { stopOwned(); child.stdin.destroy(); child.stdout.destroy(); child.stderr.destroy(); }, APP_SERVER_LIMITS.lifetimeMs);
|
|
1012
|
+
lifetime.unref();
|
|
1013
|
+
child.stderr.on('data', (bytes) => {
|
|
1014
|
+
stderrBytes += bytes.length;
|
|
1015
|
+
if (stderrBytes > APP_SERVER_LIMITS.receivedBytes) {
|
|
1016
|
+
stopOwned();
|
|
1017
|
+
child.stdout.destroy(new Error('traffic_limit'));
|
|
1018
|
+
}
|
|
1019
|
+
});
|
|
1020
|
+
child.on('error', () => { stopOwned(); child.stdout.destroy(new Error('connection_closed')); });
|
|
1021
|
+
return { pid: child.pid, input: child.stdout, output: child.stdin,
|
|
1022
|
+
close: () => new Promise(resolve => {
|
|
1023
|
+
if (closed) {
|
|
1024
|
+
resolve();
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
closed = true;
|
|
1028
|
+
stopOwned();
|
|
1029
|
+
child.stdin.destroy();
|
|
1030
|
+
child.stdout.destroy();
|
|
1031
|
+
child.stderr.destroy();
|
|
1032
|
+
if (child.exitCode !== null || child.signalCode !== null || child.pid === undefined) {
|
|
1033
|
+
resolve();
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
const timer = setTimeout(resolve, APP_SERVER_LIMITS.cleanupMs);
|
|
1037
|
+
child.once('exit', () => { clearTimeout(timer); resolve(); });
|
|
1038
|
+
}),
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
// Test-only metadata protocol transport; never inferred from a Codex process.
|
|
1042
|
+
export function spawnOwnedMetadataFixture(binary, args, env) {
|
|
1043
|
+
return { qualification: 'hermetic_fixture_only', ...spawnOwnedStdio(binary, args, env) };
|
|
1044
|
+
}
|