gestalt-mobile 0.50.2 → 0.52.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/dist/client/assets/{index-DEzZEQhF.css → index-BEI00R5B.css} +1 -1
- package/dist/client/assets/{index-BePEZpgl.js → index-CW063wzC.js} +36 -36
- package/dist/client/index.html +2 -2
- package/dist/server/server/app.js +8 -1
- package/dist/server/server/composition.contracts.js +48 -0
- package/dist/server/server/composition.js +26 -3
- package/dist/server/server/features/autopilot/application/policy.js +9 -2
- package/dist/server/server/features/catalog/get-codex-allowance/endpoint.js +20 -0
- package/dist/server/server/features/catalog/register-routes.js +3 -0
- package/dist/server/server/features/control-plane-trace/export-trace.js +3 -0
- package/dist/server/server/features/sessions/session-events/endpoint.js +2 -3
- package/dist/server/server/platform/codex/codex-allowance.js +92 -0
- package/dist/server/server/platform/events/replay.js +1 -1
- package/dist/server/server/platform/http/chat-transport-diagnostics.js +31 -0
- package/dist/server/server/platform/persistence/migrate.js +7 -0
- package/dist/server/server/platform/persistence/sqlite-event-journal.js +41 -0
- package/dist/server/server/platform/persistence/sqlite-transport-diagnostics.js +78 -0
- package/dist/server/shared/contracts/chat-transport-diagnostics.js +6 -0
- package/dist/server/shared/contracts/codex-allowance.js +6 -0
- package/package.json +1 -1
package/dist/client/index.html
CHANGED
|
@@ -16,8 +16,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
16
16
|
<link rel="icon" href="/icons/gestalt-mobile-192.png" />
|
|
17
17
|
<link rel="apple-touch-icon" href="/icons/gestalt-mobile-180.png" />
|
|
18
18
|
<title>Gestalt Mobile</title>
|
|
19
|
-
<script type="module" crossorigin src="/assets/index-
|
|
20
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
19
|
+
<script type="module" crossorigin src="/assets/index-CW063wzC.js"></script>
|
|
20
|
+
<link rel="stylesheet" crossorigin href="/assets/index-BEI00R5B.css">
|
|
21
21
|
</head>
|
|
22
22
|
<body>
|
|
23
23
|
<div id="app"></div>
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
4
|
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
5
|
*/
|
|
6
|
+
import { registerChatTransportDiagnostics } from './platform/http/chat-transport-diagnostics.js';
|
|
6
7
|
import fastifyStatic from '@fastify/static';
|
|
7
8
|
import fastifyCookie from '@fastify/cookie';
|
|
8
9
|
import fastify, {} from 'fastify';
|
|
@@ -33,6 +34,8 @@ export async function buildApp(deps) {
|
|
|
33
34
|
reply.header('Permissions-Policy', 'publickey-credentials-get=(self), publickey-credentials-create=(self)');
|
|
34
35
|
return payload;
|
|
35
36
|
});
|
|
37
|
+
if (deps.transportDiagnostic)
|
|
38
|
+
registerChatTransportDiagnostics(app, deps.transportDiagnostic);
|
|
36
39
|
await app.register(fastifyCookie);
|
|
37
40
|
if (deps.pwaIcon)
|
|
38
41
|
registerPwaRoutes(app, deps.pwaIcon);
|
|
@@ -46,7 +49,11 @@ export async function buildApp(deps) {
|
|
|
46
49
|
});
|
|
47
50
|
registerGetHealth(app, deps.health);
|
|
48
51
|
registerAuthRoutes(app, deps);
|
|
49
|
-
registerCatalogRoutes(app, {
|
|
52
|
+
registerCatalogRoutes(app, {
|
|
53
|
+
bootstrap: deps.bootstrap,
|
|
54
|
+
sessionDefaults: deps.sessionDefaults,
|
|
55
|
+
codexAllowance: deps.codexAllowance,
|
|
56
|
+
});
|
|
50
57
|
registerSessionRoutes(app, deps);
|
|
51
58
|
if (deps.selfDebug)
|
|
52
59
|
registerSelfDebug(app, deps.selfDebug);
|
|
@@ -17,6 +17,7 @@ import { composeRelayApp } from './composition.js';
|
|
|
17
17
|
import { autopilotExecutorLaunchPrompt } from './features/autopilot/application/policy.js';
|
|
18
18
|
import { CodexJsonRpcError } from './platform/codex/json-rpc-client.js';
|
|
19
19
|
import { SqliteAuthorizationStore } from './platform/auth/sqlite-authorization-store.js';
|
|
20
|
+
import { SqliteEventJournal } from './platform/persistence/sqlite-event-journal.js';
|
|
20
21
|
import { authorizationSessionId, authorizedDeviceId, localOwnerId, webAuthnCredentialId, } from './features/auth/domain/identifiers.js';
|
|
21
22
|
import { deviceNickname } from './features/auth/domain/device-nickname.js';
|
|
22
23
|
import { workspaceId } from './platform/catalog/workspace-id.js';
|
|
@@ -4058,6 +4059,8 @@ describe('production composition', () => {
|
|
|
4058
4059
|
['DELETE', '/api/auth/devices/:deviceId', '/api/auth/devices/device-1', 'protected'],
|
|
4059
4060
|
['GET', '/api/bootstrap', '/api/bootstrap', 'protected'],
|
|
4060
4061
|
['HEAD', '/api/bootstrap', '/api/bootstrap', 'protected'],
|
|
4062
|
+
['GET', '/api/codex/allowance', '/api/codex/allowance', 'protected'],
|
|
4063
|
+
['HEAD', '/api/codex/allowance', '/api/codex/allowance', 'protected'],
|
|
4061
4064
|
['GET', '/api/xerj', '/api/xerj', 'protected'],
|
|
4062
4065
|
['HEAD', '/api/xerj', '/api/xerj', 'protected'],
|
|
4063
4066
|
['GET', '/api/session-defaults', '/api/session-defaults', 'protected'],
|
|
@@ -4422,6 +4425,51 @@ describe('production composition', () => {
|
|
|
4422
4425
|
});
|
|
4423
4426
|
});
|
|
4424
4427
|
describeCompositionConcern('sessions', () => {
|
|
4428
|
+
it('hydrates chat and resyncs a large replay without materializing the journal', async () => {
|
|
4429
|
+
const fixture = await createProductionAutopilotFixture();
|
|
4430
|
+
const { app, sessionId } = fixture;
|
|
4431
|
+
onTestFinished(() => app.close());
|
|
4432
|
+
const database = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
|
|
4433
|
+
const journal = new SqliteEventJournal(database);
|
|
4434
|
+
for (let index = 0; index < 250; index++)
|
|
4435
|
+
journal.append(sessionId, 'agent.activity.updated', { synthetic: 'x'.repeat(4096) }, new Date().toISOString());
|
|
4436
|
+
const activity = journal.append(sessionId, 'activity.updated', { id: 'command', label: 'Command', detail: 'completed' }, new Date().toISOString());
|
|
4437
|
+
database.close();
|
|
4438
|
+
const fullRead = vi.spyOn(SqliteEventJournal.prototype, 'since').mockImplementation(() => {
|
|
4439
|
+
throw new Error('Unbounded journal reads must not be used by Chat');
|
|
4440
|
+
});
|
|
4441
|
+
onTestFinished(() => fullRead.mockRestore());
|
|
4442
|
+
const history = await app.inject(`/api/sessions/${sessionId}/history`);
|
|
4443
|
+
expect(history.statusCode).toBe(200);
|
|
4444
|
+
expect(history.json()).toMatchObject({
|
|
4445
|
+
baseSequence: expect.any(Number),
|
|
4446
|
+
activities: expect.arrayContaining([
|
|
4447
|
+
expect.objectContaining({ id: 'command', detail: 'completed' }),
|
|
4448
|
+
]),
|
|
4449
|
+
});
|
|
4450
|
+
expect(history.json().baseSequence).toBeGreaterThanOrEqual(activity.sequence);
|
|
4451
|
+
await app.listen({ host: '127.0.0.1', port: 0 });
|
|
4452
|
+
const address = app.server.address();
|
|
4453
|
+
if (!address || typeof address === 'string')
|
|
4454
|
+
throw new Error('Expected TCP listener');
|
|
4455
|
+
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/api/sessions/${sessionId}/events?after=0`, {
|
|
4456
|
+
headers: {
|
|
4457
|
+
origin: relyingParty.publicOrigin,
|
|
4458
|
+
cookie: 'gestalt_mobile_session=test-session',
|
|
4459
|
+
},
|
|
4460
|
+
});
|
|
4461
|
+
try {
|
|
4462
|
+
const [data] = await once(socket, 'message');
|
|
4463
|
+
expect(JSON.parse(String(data))).toMatchObject({
|
|
4464
|
+
type: 'relay.resyncRequired',
|
|
4465
|
+
currentSequence: expect.any(Number),
|
|
4466
|
+
});
|
|
4467
|
+
expect(fullRead).not.toHaveBeenCalled();
|
|
4468
|
+
}
|
|
4469
|
+
finally {
|
|
4470
|
+
socket.close();
|
|
4471
|
+
}
|
|
4472
|
+
});
|
|
4425
4473
|
it('starts Self DEBUG with the source root model and exact skill profile instead of executor defaults', async () => {
|
|
4426
4474
|
const root = await mkdtemp(join(tmpdir(), 'gestalt-debug-root-'));
|
|
4427
4475
|
const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-debug-state-'));
|
|
@@ -10,6 +10,7 @@ import { FilesystemSessionDefaults } from './platform/persistence/filesystem-ses
|
|
|
10
10
|
import { SessionModelConfig } from './platform/codex/session-model-config.js';
|
|
11
11
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
12
12
|
import { debuglog } from 'node:util';
|
|
13
|
+
import { SqliteTransportDiagnostics } from './platform/persistence/sqlite-transport-diagnostics.js';
|
|
13
14
|
import { buildApp } from './app.js';
|
|
14
15
|
import { ManagedUpgrade } from './platform/maintenance/managed-upgrade.js';
|
|
15
16
|
import { SelfDebugWorkspace } from './platform/self-debug/workspace.js';
|
|
@@ -20,6 +21,7 @@ import { FilesystemWorkspaceFiles } from './platform/filesystem/filesystem-works
|
|
|
20
21
|
import { protocolCompatibility } from './platform/codex/protocol-compatibility.js';
|
|
21
22
|
import { launchCodexAppServer } from './platform/codex/codex-process-launcher.js';
|
|
22
23
|
import { CodexModelCatalog } from './platform/codex/codex-model-catalog.js';
|
|
24
|
+
import { CodexAllowanceReader } from './platform/codex/codex-allowance.js';
|
|
23
25
|
import { ProviderModelCatalog } from './platform/catalog/provider-model-catalog.js';
|
|
24
26
|
import { createRecentThreadLister } from './platform/codex/recent-thread-lister.js';
|
|
25
27
|
import { CodexSessionRuntime } from './platform/codex/session-runtime.js';
|
|
@@ -1245,7 +1247,9 @@ export async function composeRelayApp(options) {
|
|
|
1245
1247
|
}
|
|
1246
1248
|
let app;
|
|
1247
1249
|
try {
|
|
1250
|
+
const transportDiagnostics = new SqliteTransportDiagnostics(database);
|
|
1248
1251
|
app = await buildApp({
|
|
1252
|
+
transportDiagnostic: (id, event) => transportDiagnostics.record(id, event),
|
|
1249
1253
|
upgrade: new ManagedUpgrade(options.root),
|
|
1250
1254
|
...(authorization
|
|
1251
1255
|
? {
|
|
@@ -1304,6 +1308,15 @@ export async function composeRelayApp(options) {
|
|
|
1304
1308
|
pwaIcon: options.pwaIcon,
|
|
1305
1309
|
recentThreads: recentThreadsForRelay,
|
|
1306
1310
|
sessionDefaults,
|
|
1311
|
+
codexAllowance: options.installedCodexVersion === null
|
|
1312
|
+
? {
|
|
1313
|
+
read: async () => ({
|
|
1314
|
+
weeklyRemainingPercent: null,
|
|
1315
|
+
weeklyResetsAt: null,
|
|
1316
|
+
resetsAvailable: null,
|
|
1317
|
+
}),
|
|
1318
|
+
}
|
|
1319
|
+
: new CodexAllowanceReader(root, options.launchAppServer ?? launchCodexAppServer),
|
|
1307
1320
|
bootstrap: {
|
|
1308
1321
|
xerj: () => xerjIndexer.status(),
|
|
1309
1322
|
sessionDefaults,
|
|
@@ -1473,8 +1486,8 @@ export async function composeRelayApp(options) {
|
|
|
1473
1486
|
return owner.readHistory(session);
|
|
1474
1487
|
}
|
|
1475
1488
|
: undefined,
|
|
1476
|
-
currentSequence: (sessionId) => journal.
|
|
1477
|
-
activityHistory: (sessionId, throughSequence) => journal.
|
|
1489
|
+
currentSequence: (sessionId) => journal.currentSequence(sessionId),
|
|
1490
|
+
activityHistory: (sessionId, throughSequence) => journal.activityHistory(sessionId, throughSequence),
|
|
1478
1491
|
interruptTurn: runtime || kimiRuntime
|
|
1479
1492
|
? (session, turnId) => {
|
|
1480
1493
|
const owner = ownerRuntime(session);
|
|
@@ -1579,7 +1592,17 @@ export async function composeRelayApp(options) {
|
|
|
1579
1592
|
},
|
|
1580
1593
|
sessionEvents: {
|
|
1581
1594
|
exists: (id) => sessions.find(id) !== null,
|
|
1582
|
-
|
|
1595
|
+
replay: (id, after) => {
|
|
1596
|
+
const started = performance.now();
|
|
1597
|
+
const result = journal.replay(id, after);
|
|
1598
|
+
transportDiagnostics.record(id, {
|
|
1599
|
+
kind: result.kind,
|
|
1600
|
+
after,
|
|
1601
|
+
durationMs: performance.now() - started,
|
|
1602
|
+
...(result.kind === 'replay' ? { count: result.events.length } : {}),
|
|
1603
|
+
});
|
|
1604
|
+
return result;
|
|
1605
|
+
},
|
|
1583
1606
|
subscribe: (id, listener) => events.subscribe(id, listener),
|
|
1584
1607
|
},
|
|
1585
1608
|
planRoutes: {
|
|
@@ -81,8 +81,15 @@ function classifySupervisedActivity(activity, plan) {
|
|
|
81
81
|
if (!match)
|
|
82
82
|
return true;
|
|
83
83
|
const historical = Number(match[1]) < position;
|
|
84
|
-
const
|
|
85
|
-
|
|
84
|
+
const assignedStep = plan.steps[Number(match[1]) - 1];
|
|
85
|
+
// Reopening a dependency can move execution behind an already accepted
|
|
86
|
+
// milestone. Its unloaded executor is terminal evidence, just like a
|
|
87
|
+
// completed earlier executor, unless it still owns live work.
|
|
88
|
+
const completedLater = Number(match[1]) > position &&
|
|
89
|
+
assignedStep?.state === 'DONE' &&
|
|
90
|
+
assignedStep.reviewStatus === 'REVIEWED';
|
|
91
|
+
const suspended = assignedStep?.state === 'SUSPENDED';
|
|
92
|
+
if ((suspended || completedLater) &&
|
|
86
93
|
['idle', 'blocked', 'disconnected'].includes(child.state) &&
|
|
87
94
|
!child.ownedProcesses?.some((process) => process.state === 'running' || process.state === 'detached-active'))
|
|
88
95
|
return false;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
import { problem } from '../../../platform/http/problem.js';
|
|
7
|
+
export function registerGetCodexAllowance(app, reader) {
|
|
8
|
+
app.get('/api/codex/allowance', async (_request, reply) => {
|
|
9
|
+
reply.header('Cache-Control', 'no-store');
|
|
10
|
+
try {
|
|
11
|
+
return await reader.read();
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return reply
|
|
15
|
+
.code(503)
|
|
16
|
+
.type('application/problem+json')
|
|
17
|
+
.send(problem('CODEX_ALLOWANCE_UNAVAILABLE', 503, 'Codex allowance is temporarily unavailable.'));
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|
|
@@ -6,9 +6,12 @@
|
|
|
6
6
|
import { registerXerjStatus } from './get-xerj-status/endpoint.js';
|
|
7
7
|
import { registerGetBootstrap } from './get-bootstrap/endpoint.js';
|
|
8
8
|
import { registerSessionDefaults } from './session-defaults/endpoint.js';
|
|
9
|
+
import { registerGetCodexAllowance, } from './get-codex-allowance/endpoint.js';
|
|
9
10
|
export function registerCatalogRoutes(app, deps) {
|
|
10
11
|
if (deps.bootstrap)
|
|
11
12
|
registerGetBootstrap(app, deps.bootstrap);
|
|
13
|
+
if (deps.codexAllowance)
|
|
14
|
+
registerGetCodexAllowance(app, deps.codexAllowance);
|
|
12
15
|
if (deps.bootstrap?.xerj)
|
|
13
16
|
registerXerjStatus(app, deps.bootstrap.xerj);
|
|
14
17
|
if (deps.sessionDefaults)
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
4
|
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
5
|
*/
|
|
6
|
+
import { readTransportDiagnostics } from '../../platform/persistence/sqlite-transport-diagnostics.js';
|
|
6
7
|
import { DatabaseSync } from 'node:sqlite';
|
|
7
8
|
const relevant = /^(?:org-plan\.|autopilot\.|agent\.activity\.|session\.status\.)/;
|
|
8
9
|
const statusTypes = ['autopilot.updated', 'agent.activity.updated', 'session.status.updated'];
|
|
@@ -144,6 +145,7 @@ export function exportControlPlaneTrace(databasePath, sessionId, generatedAt = n
|
|
|
144
145
|
});
|
|
145
146
|
return {
|
|
146
147
|
schemaVersion: 1,
|
|
148
|
+
transport: readTransportDiagnostics(database, sessionId, Date.parse(generatedAt)),
|
|
147
149
|
sessionId,
|
|
148
150
|
generatedAt,
|
|
149
151
|
events,
|
|
@@ -165,6 +167,7 @@ export function formatControlPlaneTrace(trace) {
|
|
|
165
167
|
`Control-plane trace for ${trace.sessionId}`,
|
|
166
168
|
`Generated: ${trace.generatedAt}`,
|
|
167
169
|
`Omitted by export limits: ${trace.selection.omittedStatusEvents} status snapshots, ${trace.selection.omittedTransitionEvents} transitions.`,
|
|
170
|
+
`Transport: ${trace.transport?.records.length ?? 0} retained records; coverage is retained-only, not proof of absence.`,
|
|
168
171
|
'',
|
|
169
172
|
];
|
|
170
173
|
for (const event of trace.events) {
|
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
5
|
*/
|
|
6
6
|
import { WebSocketServer } from 'ws';
|
|
7
|
-
import { replayOrResync } from '../../../platform/events/replay.js';
|
|
8
7
|
import { isSlowClient } from '../../../platform/events/slow-client.js';
|
|
9
8
|
import { installWebSocketHeartbeat } from '../../../platform/events/websocket-heartbeat.js';
|
|
10
9
|
export function registerSessionEvents(app, deps) {
|
|
@@ -59,9 +58,9 @@ export function registerSessionEvents(app, deps) {
|
|
|
59
58
|
else
|
|
60
59
|
send(event);
|
|
61
60
|
});
|
|
62
|
-
const replay =
|
|
61
|
+
const replay = deps.replay(sessionId, after);
|
|
63
62
|
if (replay.kind === 'resync') {
|
|
64
|
-
const currentSequence =
|
|
63
|
+
const currentSequence = replay.currentSequence;
|
|
65
64
|
connection.send(JSON.stringify({ type: 'relay.resyncRequired', currentSequence }));
|
|
66
65
|
cleanup();
|
|
67
66
|
connection.close();
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { launchCodexAppServer } from './codex-process-launcher.js';
|
|
8
|
+
const windowSchema = z.object({
|
|
9
|
+
windowDurationMins: z.literal(10_080),
|
|
10
|
+
usedPercent: z.number().finite(),
|
|
11
|
+
resetsAt: z.unknown().optional(),
|
|
12
|
+
});
|
|
13
|
+
const recordSchema = z.record(z.string(), z.unknown());
|
|
14
|
+
/** Return only account-wide counters, never account identifiers or credit details. */
|
|
15
|
+
export function decodeCodexAllowance(value) {
|
|
16
|
+
const response = recordSchema.safeParse(value);
|
|
17
|
+
const data = response.success ? response.data : {};
|
|
18
|
+
const buckets = recordSchema.safeParse(data.rateLimitsByLimitId);
|
|
19
|
+
const bucket = recordSchema.safeParse(buckets.success && 'codex' in buckets.data ? buckets.data.codex : data.rateLimits);
|
|
20
|
+
const limits = bucket.success && (bucket.data.limitId == null || bucket.data.limitId === 'codex')
|
|
21
|
+
? bucket.data
|
|
22
|
+
: {};
|
|
23
|
+
const weekly = [limits.primary, limits.secondary]
|
|
24
|
+
.map((window) => windowSchema.safeParse(window))
|
|
25
|
+
.find((window) => window.success);
|
|
26
|
+
const credits = z
|
|
27
|
+
.object({ availableCount: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) })
|
|
28
|
+
.safeParse(data.rateLimitResetCredits);
|
|
29
|
+
const reset = z
|
|
30
|
+
.number()
|
|
31
|
+
.int()
|
|
32
|
+
.nonnegative()
|
|
33
|
+
.max(8_640_000_000_000)
|
|
34
|
+
.safeParse(weekly?.success ? weekly.data.resetsAt : null);
|
|
35
|
+
return {
|
|
36
|
+
weeklyRemainingPercent: weekly?.success
|
|
37
|
+
? Math.round(Math.max(0, Math.min(100, 100 - weekly.data.usedPercent)))
|
|
38
|
+
: null,
|
|
39
|
+
resetsAvailable: credits.success ? credits.data.availableCount : null,
|
|
40
|
+
weeklyResetsAt: reset.success ? reset.data : null,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** A bounded account read also works before a user has opened a session. */
|
|
44
|
+
export class CodexAllowanceReader {
|
|
45
|
+
cwd;
|
|
46
|
+
launch;
|
|
47
|
+
timeoutMs;
|
|
48
|
+
pending;
|
|
49
|
+
cached;
|
|
50
|
+
constructor(cwd, launch = launchCodexAppServer, timeoutMs = 5_000) {
|
|
51
|
+
this.cwd = cwd;
|
|
52
|
+
this.launch = launch;
|
|
53
|
+
this.timeoutMs = timeoutMs;
|
|
54
|
+
}
|
|
55
|
+
read() {
|
|
56
|
+
if (this.cached && this.cached.expires > Date.now())
|
|
57
|
+
return Promise.resolve(this.cached.value);
|
|
58
|
+
if (this.pending)
|
|
59
|
+
return this.pending;
|
|
60
|
+
this.pending = this.readFresh()
|
|
61
|
+
.then((value) => {
|
|
62
|
+
this.cached = { value, expires: Date.now() + 30_000 };
|
|
63
|
+
return value;
|
|
64
|
+
})
|
|
65
|
+
.finally(() => {
|
|
66
|
+
this.pending = undefined;
|
|
67
|
+
});
|
|
68
|
+
return this.pending;
|
|
69
|
+
}
|
|
70
|
+
async readFresh() {
|
|
71
|
+
const server = this.launch({ profile: '', cwd: this.cwd });
|
|
72
|
+
let timer;
|
|
73
|
+
try {
|
|
74
|
+
return await Promise.race([
|
|
75
|
+
(async () => {
|
|
76
|
+
await server.rpc.request('initialize', {
|
|
77
|
+
clientInfo: { name: 'gestalt-mobile', version: '0.1.0' },
|
|
78
|
+
capabilities: null,
|
|
79
|
+
});
|
|
80
|
+
return decodeCodexAllowance(await server.rpc.request('account/rateLimits/read', {}));
|
|
81
|
+
})(),
|
|
82
|
+
new Promise((_, reject) => {
|
|
83
|
+
timer = setTimeout(() => reject(new Error('CODEX_ALLOWANCE_UNAVAILABLE')), this.timeoutMs);
|
|
84
|
+
}),
|
|
85
|
+
]);
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
server.close();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -7,6 +7,6 @@ export function replayOrResync(events, after) {
|
|
|
7
7
|
if (!events.length)
|
|
8
8
|
return { kind: 'replay', events: [] };
|
|
9
9
|
return events[0].sequence > after + 1
|
|
10
|
-
? { kind: 'resync' }
|
|
10
|
+
? { kind: 'resync', currentSequence: events.at(-1).sequence }
|
|
11
11
|
: { kind: 'replay', events: events.filter((event) => event.sequence > after) };
|
|
12
12
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
export function registerChatTransportDiagnostics(app, record) {
|
|
7
|
+
app.addHook('onResponse', async (request, reply) => {
|
|
8
|
+
if (request.routeOptions.url !== '/api/sessions/:id/history' || request.method !== 'GET')
|
|
9
|
+
return;
|
|
10
|
+
// Do not record unauthorized requests or retain arbitrary paths, headers, bodies, or errors.
|
|
11
|
+
if (reply.statusCode === 401 || reply.statusCode === 403 || reply.statusCode === 404)
|
|
12
|
+
return;
|
|
13
|
+
const observation = {};
|
|
14
|
+
for (const key of ['attempts', 'coalesced']) {
|
|
15
|
+
const raw = request.headers[`x-gestalt-history-${key}`];
|
|
16
|
+
if (typeof raw === 'string' && /^[0-9]{1,15}$/.test(raw))
|
|
17
|
+
observation[key] = Number(raw);
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
record(request.params.id, {
|
|
21
|
+
kind: 'history',
|
|
22
|
+
durationMs: reply.elapsedTime,
|
|
23
|
+
status: reply.statusCode,
|
|
24
|
+
...observation,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
/* Diagnostic sinks cannot change request outcomes. */
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
@@ -28,6 +28,13 @@ function migrateWorkspaceGitDefaults(database) {
|
|
|
28
28
|
}
|
|
29
29
|
export function migrate(database) {
|
|
30
30
|
database.exec(schema);
|
|
31
|
+
database.exec(`CREATE TABLE IF NOT EXISTS chat_transport_diagnostics (
|
|
32
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
33
|
+
session_id TEXT NOT NULL REFERENCES relay_sessions(id) ON DELETE CASCADE,
|
|
34
|
+
occurred_at INTEGER NOT NULL,
|
|
35
|
+
metadata_json TEXT NOT NULL
|
|
36
|
+
); CREATE INDEX IF NOT EXISTS chat_transport_session ON chat_transport_diagnostics(session_id, id);`);
|
|
37
|
+
database.exec("CREATE INDEX IF NOT EXISTS session_events_chat_activity ON session_events(session_id, sequence) WHERE type = 'activity.updated'");
|
|
31
38
|
database.exec('CREATE INDEX IF NOT EXISTS session_events_retention ON session_events(session_id, julianday(occurred_at))');
|
|
32
39
|
database.exec('CREATE TABLE IF NOT EXISTS autopilot_state_quarantine (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL REFERENCES relay_sessions(id) ON DELETE CASCADE, record_json TEXT NOT NULL, created_at TEXT NOT NULL)');
|
|
33
40
|
database.exec("CREATE INDEX IF NOT EXISTS session_events_autopilot_audit_tail_v3 ON session_events(session_id, type, sequence DESC) WHERE type IN ('autopilot.continuation-scheduled','autopilot.control-issued','autopilot.turn-started','autopilot.turn-failed','autopilot.progress-reset','autopilot.final-rejected','autopilot.executor-resumed','autopilot.process-monitoring','autopilot.process-result-consumed','autopilot.process-terminated','autopilot.updated','org-plan.attention-required','org-plan.attention-resolved')");
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { boundedAttentionReport } from '../../../shared/contracts/attention-report.js';
|
|
7
7
|
import { eventRetentionCutoff } from './retention.js';
|
|
8
|
+
import { replayOrResync } from '../events/replay.js';
|
|
8
9
|
export const autopilotAuditEventTypes = [
|
|
9
10
|
'autopilot.turn-started',
|
|
10
11
|
'autopilot.turn-failed',
|
|
@@ -93,6 +94,46 @@ export class SqliteEventJournal {
|
|
|
93
94
|
throw error;
|
|
94
95
|
}
|
|
95
96
|
}
|
|
97
|
+
currentSequence(sessionId) {
|
|
98
|
+
const row = this.db
|
|
99
|
+
.prepare('SELECT sequence FROM session_events WHERE session_id = ? ORDER BY sequence DESC LIMIT 1')
|
|
100
|
+
.get(sessionId);
|
|
101
|
+
return row?.sequence ?? 0;
|
|
102
|
+
}
|
|
103
|
+
/** Snapshot activity excludes large agent projections and unrelated journal payloads. */
|
|
104
|
+
activityHistory(sessionId, throughSequence) {
|
|
105
|
+
const rows = this.db
|
|
106
|
+
.prepare("SELECT sequence,type,occurred_at,payload_json FROM session_events WHERE session_id = ? AND type = 'activity.updated' AND sequence <= ? ORDER BY sequence")
|
|
107
|
+
.all(sessionId, throughSequence);
|
|
108
|
+
return rows.map((row) => ({
|
|
109
|
+
sessionId,
|
|
110
|
+
sequence: row.sequence,
|
|
111
|
+
type: row.type,
|
|
112
|
+
occurredAt: row.occurred_at,
|
|
113
|
+
payload: JSON.parse(row.payload_json),
|
|
114
|
+
}));
|
|
115
|
+
}
|
|
116
|
+
/** Decide resync from bounded metadata before allocating or decoding replay payloads. */
|
|
117
|
+
replay(sessionId, after) {
|
|
118
|
+
const currentSequence = this.currentSequence(sessionId);
|
|
119
|
+
const rows = this.db
|
|
120
|
+
.prepare('SELECT sequence,length(CAST(payload_json AS BLOB)) AS bytes FROM session_events WHERE session_id = ? AND sequence > ? AND sequence <= ? ORDER BY sequence LIMIT 201')
|
|
121
|
+
.all(sessionId, after, currentSequence);
|
|
122
|
+
if (rows.length > 200 ||
|
|
123
|
+
rows.reduce((bytes, row) => bytes + row.bytes, 0) > 512 * 1024 ||
|
|
124
|
+
(rows.length > 0 && rows[0].sequence !== after + 1))
|
|
125
|
+
return { kind: 'resync', currentSequence };
|
|
126
|
+
const events = this.db
|
|
127
|
+
.prepare('SELECT sequence,type,occurred_at,payload_json FROM session_events WHERE session_id = ? AND sequence > ? AND sequence <= ? ORDER BY sequence LIMIT 200')
|
|
128
|
+
.all(sessionId, after, currentSequence);
|
|
129
|
+
return replayOrResync(events.map((row) => ({
|
|
130
|
+
sessionId,
|
|
131
|
+
sequence: row.sequence,
|
|
132
|
+
type: row.type,
|
|
133
|
+
occurredAt: row.occurred_at,
|
|
134
|
+
payload: JSON.parse(row.payload_json),
|
|
135
|
+
})), after);
|
|
136
|
+
}
|
|
96
137
|
since(sessionId, after) {
|
|
97
138
|
return this.db
|
|
98
139
|
.prepare('SELECT sequence,type,occurred_at,payload_json FROM session_events WHERE session_id = ? AND sequence > ? ORDER BY sequence')
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
export const transportLimit = 2048;
|
|
7
|
+
export const transportRetentionMs = 48 * 60 * 60 * 1000;
|
|
8
|
+
/** Separate from the replay journal: recording transport must never generate transport traffic. */
|
|
9
|
+
export class SqliteTransportDiagnostics {
|
|
10
|
+
database;
|
|
11
|
+
constructor(database) {
|
|
12
|
+
this.database = database;
|
|
13
|
+
}
|
|
14
|
+
record(sessionId, value, now = Date.now()) {
|
|
15
|
+
// Diagnostics are best effort; storage failures cannot fail a history read or socket.
|
|
16
|
+
try {
|
|
17
|
+
const fields = safeMetadata(value);
|
|
18
|
+
if (!fields)
|
|
19
|
+
return;
|
|
20
|
+
this.database
|
|
21
|
+
.prepare('INSERT INTO chat_transport_diagnostics(session_id, occurred_at, metadata_json) VALUES (?, ?, ?)')
|
|
22
|
+
.run(sessionId, now, JSON.stringify(fields));
|
|
23
|
+
this.database
|
|
24
|
+
.prepare('DELETE FROM chat_transport_diagnostics WHERE occurred_at < ? OR id <= COALESCE((SELECT id FROM chat_transport_diagnostics ORDER BY id DESC LIMIT 1 OFFSET ?), 0)')
|
|
25
|
+
.run(now - transportRetentionMs, transportLimit);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
/* Optional telemetry must not change delivery semantics. */
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function readTransportDiagnostics(database, sessionId, now = Date.now()) {
|
|
33
|
+
const available = Boolean(database
|
|
34
|
+
.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='chat_transport_diagnostics'")
|
|
35
|
+
.get());
|
|
36
|
+
const rows = available
|
|
37
|
+
? database
|
|
38
|
+
.prepare('SELECT id, occurred_at AS occurredAt, metadata_json FROM chat_transport_diagnostics WHERE session_id = ? AND occurred_at >= ? ORDER BY id DESC LIMIT ?')
|
|
39
|
+
.all(sessionId, now - transportRetentionMs, transportLimit)
|
|
40
|
+
.reverse()
|
|
41
|
+
: [];
|
|
42
|
+
return {
|
|
43
|
+
available,
|
|
44
|
+
coverage: 'retained-only',
|
|
45
|
+
globalRecordLimit: transportLimit,
|
|
46
|
+
retentionMs: transportRetentionMs,
|
|
47
|
+
records: rows.flatMap((row) => {
|
|
48
|
+
try {
|
|
49
|
+
const metadata = safeMetadata(JSON.parse(String(row.metadata_json)));
|
|
50
|
+
return metadata
|
|
51
|
+
? [{ id: Number(row.id), occurredAt: Number(row.occurredAt), ...metadata }]
|
|
52
|
+
: [];
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
}),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function safeMetadata(value) {
|
|
61
|
+
if (!value || typeof value !== 'object')
|
|
62
|
+
return null;
|
|
63
|
+
const input = value;
|
|
64
|
+
if (input.kind !== 'history' && input.kind !== 'replay' && input.kind !== 'resync')
|
|
65
|
+
return null;
|
|
66
|
+
const fields = {
|
|
67
|
+
kind: input.kind,
|
|
68
|
+
};
|
|
69
|
+
for (const key of ['durationMs', 'status', 'after', 'count', 'attempts', 'coalesced']) {
|
|
70
|
+
const number = input[key];
|
|
71
|
+
if (typeof number === 'number' &&
|
|
72
|
+
Number.isFinite(number) &&
|
|
73
|
+
number >= 0 &&
|
|
74
|
+
number <= Number.MAX_SAFE_INTEGER)
|
|
75
|
+
fields[key] = number;
|
|
76
|
+
}
|
|
77
|
+
return fields;
|
|
78
|
+
}
|