polygram 0.33.0 → 0.33.1

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,490 @@
1
+ 'use strict';
2
+
3
+ const {
4
+ codexError,
5
+ requiredString,
6
+ } = require('./codex-input');
7
+ const {
8
+ CODEX_APP_SERVER_NAMESPACE,
9
+ } = require('./sessions');
10
+ const SETTLEMENT_SOURCES = new Set([
11
+ 'managed-group-empty',
12
+ 'exclusive-takeover-grace',
13
+ ]);
14
+
15
+ function optionalString(value, label) {
16
+ if (value == null) return null;
17
+ return requiredString(value, label);
18
+ }
19
+
20
+ function requiredTimestamp(value) {
21
+ if (!Number.isSafeInteger(value) || value < 0) {
22
+ throw codexError(
23
+ 'Codex failed-generation settlement timestamp is invalid',
24
+ 'CODEX_PERSISTENCE_INPUT_INVALID',
25
+ );
26
+ }
27
+ return value;
28
+ }
29
+
30
+ function conflict(message) {
31
+ throw codexError(message, 'CODEX_FAILED_GENERATION_SETTLEMENT_CONFLICT');
32
+ }
33
+
34
+ function readCleanup(rawDb, generationId) {
35
+ return rawDb.prepare(`
36
+ SELECT 1
37
+ FROM codex_attempt_checkpoints
38
+ WHERE generation_id = ?
39
+ AND kind = 'containment-cleanup-completed'
40
+ LIMIT 1
41
+ `).get(generationId);
42
+ }
43
+
44
+ function settleCodexFailedGeneration(rawDb, input) {
45
+ const generationId = requiredString(input?.generation_id, 'generation ID');
46
+ const sessionKey = requiredString(input?.session_key, 'session key');
47
+ const stableHostId = requiredString(
48
+ input?.stable_host_id,
49
+ 'stable host identity',
50
+ );
51
+ const incidentBootSessionId = requiredString(
52
+ input?.incident_boot_session_id,
53
+ 'incident boot-session identity',
54
+ );
55
+ const currentBootSessionId = requiredString(
56
+ input?.current_boot_session_id,
57
+ 'current boot-session identity',
58
+ );
59
+ const providerSessionId = optionalString(
60
+ input?.provider_session_id,
61
+ 'provider session ID',
62
+ );
63
+ const appServerSessionId = optionalString(
64
+ input?.app_server_session_id,
65
+ 'app-server session ID',
66
+ );
67
+ const reason = requiredString(input?.reason, 'containment reason');
68
+ const source = input?.source;
69
+ if (!SETTLEMENT_SOURCES.has(source)) {
70
+ throw codexError(
71
+ 'Codex failed-generation settlement source is invalid',
72
+ 'CODEX_PERSISTENCE_INPUT_INVALID',
73
+ );
74
+ }
75
+ const allowMissingGeneration = input?.allow_missing_generation === true;
76
+ if (allowMissingGeneration && source !== 'managed-group-empty') {
77
+ throw codexError(
78
+ 'Only managed cleanup can settle a non-durable generation',
79
+ 'CODEX_PERSISTENCE_INPUT_INVALID',
80
+ );
81
+ }
82
+ const ts = requiredTimestamp(input?.ts ?? Date.now());
83
+
84
+ return rawDb.transaction(() => {
85
+ let generation = rawDb.prepare(`
86
+ SELECT * FROM codex_generations WHERE generation_id = ?
87
+ `).get(generationId);
88
+
89
+ if (generation && readCleanup(rawDb, generationId)) {
90
+ if (
91
+ generation.session_key !== sessionKey
92
+ || generation.stable_host_id !== stableHostId
93
+ || generation.boot_session_id !== incidentBootSessionId
94
+ ) {
95
+ conflict('Codex cleanup marker belongs to another generation owner');
96
+ }
97
+ return {
98
+ committed: true,
99
+ disposition: 'failed-settled',
100
+ generationId,
101
+ };
102
+ }
103
+
104
+ const identity = rawDb.prepare(`
105
+ SELECT stable_host_id, last_boot_session_id
106
+ FROM codex_runtime_identity
107
+ WHERE singleton = 1
108
+ `).get();
109
+ if (
110
+ !identity
111
+ || identity.stable_host_id !== stableHostId
112
+ || identity.last_boot_session_id !== incidentBootSessionId
113
+ ) {
114
+ conflict('Codex runtime identity does not match the failed generation');
115
+ }
116
+
117
+ const lease = rawDb.prepare(`
118
+ SELECT * FROM codex_daemon_lease WHERE singleton = 1
119
+ `).get();
120
+
121
+ if (!generation) {
122
+ if (!allowMissingGeneration) {
123
+ conflict('Codex failed generation is not durable');
124
+ }
125
+ if (lease && lease.status !== 'clear') {
126
+ conflict('Another Codex generation owns the daemon lease');
127
+ }
128
+ const conflictingGeneration = rawDb.prepare(`
129
+ SELECT generation_id
130
+ FROM codex_generations
131
+ WHERE session_key = ?
132
+ AND settled_ts IS NULL
133
+ AND state IN ('created', 'active', 'containment-failed',
134
+ 'durability-blocked')
135
+ LIMIT 1
136
+ `).get(sessionKey);
137
+ if (conflictingGeneration) {
138
+ conflict('Another Codex generation owns the failed session');
139
+ }
140
+ rawDb.prepare(`
141
+ INSERT INTO codex_generations (
142
+ generation_id, session_key, thread_id, app_server_session_id,
143
+ stable_host_id, boot_session_id, state, containment_reason,
144
+ created_ts, updated_ts, settled_ts
145
+ ) VALUES (?, ?, ?, ?, ?, ?, 'containment-failed', ?, ?, ?, ?)
146
+ `).run(
147
+ generationId,
148
+ sessionKey,
149
+ providerSessionId,
150
+ appServerSessionId,
151
+ stableHostId,
152
+ incidentBootSessionId,
153
+ reason,
154
+ ts,
155
+ ts,
156
+ ts,
157
+ );
158
+ generation = rawDb.prepare(`
159
+ SELECT * FROM codex_generations WHERE generation_id = ?
160
+ `).get(generationId);
161
+ } else {
162
+ if (
163
+ generation.session_key !== sessionKey
164
+ || generation.stable_host_id !== stableHostId
165
+ || generation.boot_session_id !== incidentBootSessionId
166
+ || (
167
+ generation.state !== 'containment-failed'
168
+ && !(
169
+ [
170
+ 'exclusive-takeover-grace',
171
+ 'managed-group-empty',
172
+ ].includes(source)
173
+ && generation.state === 'active'
174
+ )
175
+ )
176
+ || (
177
+ generation.thread_id != null
178
+ && generation.thread_id !== providerSessionId
179
+ )
180
+ || (
181
+ generation.app_server_session_id != null
182
+ && generation.app_server_session_id !== appServerSessionId
183
+ )
184
+ ) {
185
+ conflict('Codex failed generation identity is inconsistent');
186
+ }
187
+ if (
188
+ !lease
189
+ || !['active', 'quarantined'].includes(lease.status)
190
+ || lease.generation_id !== generationId
191
+ || lease.stable_host_id !== stableHostId
192
+ || lease.boot_session_id !== incidentBootSessionId
193
+ ) {
194
+ conflict('Codex daemon lease does not belong to the failed generation');
195
+ }
196
+ rawDb.prepare(`
197
+ UPDATE codex_generations
198
+ SET state = 'containment-failed',
199
+ thread_id = COALESCE(thread_id, ?),
200
+ app_server_session_id = COALESCE(app_server_session_id, ?),
201
+ containment_reason = COALESCE(containment_reason, ?),
202
+ updated_ts = ?,
203
+ settled_ts = COALESCE(settled_ts, ?)
204
+ WHERE generation_id = ?
205
+ `).run(
206
+ providerSessionId,
207
+ appServerSessionId,
208
+ reason,
209
+ ts,
210
+ ts,
211
+ generationId,
212
+ );
213
+ }
214
+
215
+ const provider = rawDb.prepare(`
216
+ SELECT provider, provider_session_id, app_server_session_id,
217
+ generation_id
218
+ FROM agent_runtime_sessions
219
+ WHERE session_key = ?
220
+ AND namespace = ?
221
+ `).get(sessionKey, CODEX_APP_SERVER_NAMESPACE);
222
+ if (provider) {
223
+ if (
224
+ provider.provider !== 'codex'
225
+ || providerSessionId == null
226
+ || provider.provider_session_id !== providerSessionId
227
+ || provider.app_server_session_id !== appServerSessionId
228
+ ) {
229
+ conflict('Codex provider session does not match the failed generation');
230
+ }
231
+ const deleted = rawDb.prepare(`
232
+ DELETE FROM agent_runtime_sessions
233
+ WHERE session_key = ?
234
+ AND namespace = ?
235
+ AND provider = 'codex'
236
+ AND provider_session_id = ?
237
+ AND app_server_session_id IS ?
238
+ AND generation_id IS ?
239
+ `).run(
240
+ sessionKey,
241
+ CODEX_APP_SERVER_NAMESPACE,
242
+ providerSessionId,
243
+ appServerSessionId,
244
+ provider.generation_id,
245
+ );
246
+ if (deleted.changes !== 1) {
247
+ conflict('Codex provider session changed during settlement');
248
+ }
249
+ }
250
+
251
+ rawDb.prepare(`
252
+ UPDATE codex_turn_attempts
253
+ SET recovery_state = 'cancelled',
254
+ terminal_status = COALESCE(terminal_status, 'failed'),
255
+ updated_ts = ?,
256
+ settled_ts = COALESCE(settled_ts, ?)
257
+ WHERE generation_id = ?
258
+ AND delivery_state = 'prepared'
259
+ AND recovery_state NOT IN ('settled', 'cancelled')
260
+ `).run(ts, ts, generationId);
261
+ rawDb.prepare(`
262
+ UPDATE codex_turn_attempts
263
+ SET recovery_state = 'ambiguous',
264
+ updated_ts = ?,
265
+ settled_ts = NULL,
266
+ ambiguous_ts = COALESCE(ambiguous_ts, ?)
267
+ WHERE generation_id = ?
268
+ AND delivery_state != 'prepared'
269
+ AND recovery_state NOT IN ('settled', 'cancelled')
270
+ `).run(ts, ts, generationId);
271
+
272
+ const selectedAttempts = rawDb.prepare(`
273
+ SELECT session_key, telegram_source_message_id, recovery_state
274
+ FROM codex_turn_attempts
275
+ WHERE generation_id = ?
276
+ AND telegram_source_message_id IS NOT NULL
277
+ AND (
278
+ recovery_state = 'ambiguous'
279
+ OR (recovery_state = 'cancelled' AND settled_ts = ?)
280
+ )
281
+ `).all(generationId, ts);
282
+ for (const attempt of selectedAttempts) {
283
+ const locations = rawDb.prepare(`
284
+ SELECT selection.bot_name,
285
+ selection.telegram_chat_id,
286
+ selection.telegram_message_id,
287
+ message.handler_status
288
+ FROM inbound_runtime_selections selection
289
+ LEFT JOIN messages message
290
+ ON message.direction = 'in'
291
+ AND message.bot_name = selection.bot_name
292
+ AND message.chat_id = selection.telegram_chat_id
293
+ AND CAST(message.msg_id AS TEXT) =
294
+ selection.telegram_message_id
295
+ WHERE selection.session_key = ?
296
+ AND selection.provider = 'codex'
297
+ AND selection.telegram_message_id = ?
298
+ `).all(
299
+ attempt.session_key,
300
+ attempt.telegram_source_message_id,
301
+ );
302
+ if (locations.length !== 1 || locations[0].handler_status == null) {
303
+ conflict('Codex attempt has no unique inbound selection binding');
304
+ }
305
+ const location = locations[0];
306
+ const handlerStatus = attempt.recovery_state === 'ambiguous'
307
+ ? 'codex-ambiguous'
308
+ : 'failed';
309
+ if (location.handler_status === handlerStatus) continue;
310
+ if (![
311
+ 'received',
312
+ 'dispatched',
313
+ 'processing',
314
+ 'replay-pending',
315
+ ].includes(location.handler_status)) {
316
+ conflict('Codex attempt inbound selection is already terminal');
317
+ }
318
+ const updated = rawDb.prepare(`
319
+ UPDATE messages
320
+ SET handler_status = ?
321
+ WHERE direction = 'in'
322
+ AND bot_name = ?
323
+ AND chat_id = ?
324
+ AND CAST(msg_id AS TEXT) = ?
325
+ AND handler_status = ?
326
+ `).run(
327
+ handlerStatus,
328
+ location.bot_name,
329
+ location.telegram_chat_id,
330
+ location.telegram_message_id,
331
+ location.handler_status,
332
+ );
333
+ if (updated.changes !== 1) {
334
+ conflict('Codex attempt inbound selection changed during settlement');
335
+ }
336
+ }
337
+
338
+ rawDb.prepare(`
339
+ UPDATE codex_dispatch_reservations
340
+ SET state = CASE
341
+ WHEN state = 'steer-accepted'
342
+ OR EXISTS (
343
+ SELECT 1
344
+ FROM codex_turn_attempts attempt
345
+ WHERE attempt.attempt_id IN (
346
+ codex_dispatch_reservations.steer_attempt_id,
347
+ codex_dispatch_reservations.target_attempt_id
348
+ )
349
+ AND attempt.recovery_state = 'ambiguous'
350
+ )
351
+ THEN 'ambiguous'
352
+ ELSE 'cancelled'
353
+ END,
354
+ updated_ts = ?,
355
+ settled_ts = CASE
356
+ WHEN state = 'steer-accepted'
357
+ OR EXISTS (
358
+ SELECT 1
359
+ FROM codex_turn_attempts attempt
360
+ WHERE attempt.attempt_id IN (
361
+ codex_dispatch_reservations.steer_attempt_id,
362
+ codex_dispatch_reservations.target_attempt_id
363
+ )
364
+ AND attempt.recovery_state = 'ambiguous'
365
+ )
366
+ THEN NULL
367
+ ELSE ?
368
+ END
369
+ WHERE generation_id = ?
370
+ AND state IN ('reserved', 'steer-accepted', 'queue-authorized')
371
+ `).run(ts, ts, generationId);
372
+
373
+ rawDb.prepare(`
374
+ UPDATE codex_linked_inputs
375
+ SET state = CASE
376
+ WHEN EXISTS (
377
+ SELECT 1
378
+ FROM codex_turn_attempts attempt
379
+ WHERE attempt.attempt_id IN (
380
+ codex_linked_inputs.attempt_id,
381
+ codex_linked_inputs.target_attempt_id
382
+ )
383
+ AND attempt.recovery_state = 'ambiguous'
384
+ )
385
+ THEN 'ambiguous'
386
+ ELSE 'failed'
387
+ END,
388
+ settled_ts = ?
389
+ WHERE generation_id = ?
390
+ AND state = 'linked'
391
+ `).run(ts, generationId);
392
+
393
+ rawDb.prepare(`
394
+ UPDATE messages
395
+ SET handler_status = CASE
396
+ WHEN EXISTS (
397
+ SELECT 1
398
+ FROM codex_dispatch_reservations reservation
399
+ WHERE reservation.generation_id = ?
400
+ AND reservation.state = 'ambiguous'
401
+ AND reservation.bot_name = messages.bot_name
402
+ AND reservation.telegram_chat_id = messages.chat_id
403
+ AND reservation.telegram_message_id =
404
+ CAST(messages.msg_id AS TEXT)
405
+ )
406
+ THEN 'codex-ambiguous'
407
+ ELSE 'failed'
408
+ END
409
+ WHERE direction = 'in'
410
+ AND handler_status IN (
411
+ 'received', 'dispatched', 'processing', 'replay-pending'
412
+ )
413
+ AND EXISTS (
414
+ SELECT 1
415
+ FROM codex_dispatch_reservations reservation
416
+ WHERE reservation.generation_id = ?
417
+ AND reservation.bot_name = messages.bot_name
418
+ AND reservation.telegram_chat_id = messages.chat_id
419
+ AND reservation.telegram_message_id =
420
+ CAST(messages.msg_id AS TEXT)
421
+ )
422
+ `).run(generationId, generationId);
423
+
424
+ rawDb.prepare(`
425
+ INSERT INTO codex_attempt_checkpoints (
426
+ generation_id, kind, thread_id, detail_json, ts
427
+ ) VALUES (?, 'containment-cleanup-completed', ?, ?, ?)
428
+ `).run(
429
+ generationId,
430
+ providerSessionId,
431
+ JSON.stringify({ source, reason }),
432
+ ts,
433
+ );
434
+
435
+ if (lease && lease.status !== 'clear') {
436
+ const released = rawDb.prepare(`
437
+ UPDATE codex_daemon_lease
438
+ SET generation_id = NULL,
439
+ stable_host_id = ?,
440
+ boot_session_id = ?,
441
+ status = 'clear',
442
+ quarantine_reason = NULL,
443
+ updated_ts = ?,
444
+ released_ts = ?
445
+ WHERE singleton = 1
446
+ AND generation_id = ?
447
+ AND stable_host_id = ?
448
+ AND boot_session_id = ?
449
+ AND status IN ('active', 'quarantined')
450
+ `).run(
451
+ stableHostId,
452
+ currentBootSessionId,
453
+ ts,
454
+ ts,
455
+ generationId,
456
+ stableHostId,
457
+ incidentBootSessionId,
458
+ );
459
+ if (released.changes !== 1) {
460
+ conflict('Codex daemon lease changed during settlement');
461
+ }
462
+ }
463
+
464
+ const identityUpdated = rawDb.prepare(`
465
+ UPDATE codex_runtime_identity
466
+ SET last_boot_session_id = ?, updated_ts = ?
467
+ WHERE singleton = 1
468
+ AND stable_host_id = ?
469
+ AND last_boot_session_id = ?
470
+ `).run(
471
+ currentBootSessionId,
472
+ ts,
473
+ stableHostId,
474
+ incidentBootSessionId,
475
+ );
476
+ if (identityUpdated.changes !== 1) {
477
+ conflict('Codex runtime identity changed during settlement');
478
+ }
479
+
480
+ return {
481
+ committed: true,
482
+ disposition: 'failed-settled',
483
+ generationId,
484
+ };
485
+ })();
486
+ }
487
+
488
+ module.exports = {
489
+ settleCodexFailedGeneration,
490
+ };
@@ -0,0 +1,26 @@
1
+ 'use strict';
2
+
3
+ function codexError(message, code) {
4
+ const error = new Error(message);
5
+ error.code = code;
6
+ return error;
7
+ }
8
+
9
+ function requiredString(value, label) {
10
+ if (
11
+ typeof value !== 'string'
12
+ || value.length === 0
13
+ || value.length > 512
14
+ ) {
15
+ throw codexError(
16
+ `Codex ${label} must be a non-empty bounded string`,
17
+ 'CODEX_PERSISTENCE_INPUT_INVALID',
18
+ );
19
+ }
20
+ return value;
21
+ }
22
+
23
+ module.exports = {
24
+ codexError,
25
+ requiredString,
26
+ };