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