gestalt-mobile 0.67.1 → 0.68.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.
Files changed (35) hide show
  1. package/dist/client/assets/index-BZ3ivopC.js +183 -0
  2. package/dist/client/assets/index-DRbCnCbk.css +1 -0
  3. package/dist/client/index.html +2 -2
  4. package/dist/server/server/composition.contracts.js +976 -0
  5. package/dist/server/server/composition.js +330 -57
  6. package/dist/server/server/features/autopilot/application/service.js +18 -1
  7. package/dist/server/server/features/plans/application/org-plan-launch-store.js +6 -0
  8. package/dist/server/server/features/plans/application/prepare-org-plan-settings.js +66 -0
  9. package/dist/server/server/features/plans/application/prepare-org-plan-supervision.js +86 -0
  10. package/dist/server/server/features/plans/application/start-org-plan-supervision.js +323 -0
  11. package/dist/server/server/features/plans/execute-plan/endpoint.js +27 -0
  12. package/dist/server/server/features/plans/get-workspace-plan/endpoint.js +2 -1
  13. package/dist/server/server/features/plans/open-plan/endpoint.js +2 -1
  14. package/dist/server/server/features/plans/prepare-supervision/endpoint.js +52 -0
  15. package/dist/server/server/features/plans/register-routes.js +6 -0
  16. package/dist/server/server/features/sessions/application/resolve-session-skills.js +35 -0
  17. package/dist/server/server/features/sessions/application/start-settings.js +2 -1
  18. package/dist/server/server/features/sessions/register-routes.js +1 -0
  19. package/dist/server/server/features/sessions/start-session/endpoint.js +5 -0
  20. package/dist/server/server/features/sessions/start-session/use-case.js +7 -32
  21. package/dist/server/server/features/sessions/start-turn/endpoint.js +9 -167
  22. package/dist/server/server/features/sessions/start-turn/use-case.js +243 -0
  23. package/dist/server/server/features/skills/application/read-global-profiles.js +34 -0
  24. package/dist/server/server/features/skills/list-profiles/endpoint.js +9 -33
  25. package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +11 -0
  26. package/dist/server/server/platform/codex/session-runtime.js +20 -6
  27. package/dist/server/server/platform/persistence/migrate.js +12 -0
  28. package/dist/server/server/platform/persistence/sqlite-org-plan-launch-store.js +215 -0
  29. package/dist/server/server/platform/plans/filesystem-org-plan-context.js +99 -0
  30. package/dist/server/server/platform/plans/filesystem-workspace-plan-catalog.js +36 -3
  31. package/dist/server/shared/contracts/org-plan-execution.js +46 -0
  32. package/dist/server/shared/contracts/session-defaults.js +33 -3
  33. package/package.json +1 -1
  34. package/dist/client/assets/index-DLp_epYd.js +0 -128
  35. package/dist/client/assets/index-DxsD-jG4.css +0 -1
@@ -3,176 +3,18 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- import { createHash } from 'node:crypto';
7
- import { RelaySession } from '../model/relay-session.js';
8
- import { WriterAcquisitionError, writerAcquisitionProblem, } from '../application/writer-acquisition.js';
6
+ import { createStartTurn } from './use-case.js';
9
7
  export function registerStartTurn(app, deps) {
10
- const inflight = new Map();
11
- const sessionOperations = new Map();
12
- // Durable idempotency results are session-scoped and replay for as long as the
13
- // store retains them; a reused key with a different prompt is rejected.
14
- // Text is capped at 100,000 characters; leave room for JSON encoding only.
8
+ const submit = deps.submit ?? createStartTurn(deps);
15
9
  app.post('/api/sessions/:id/turns', { bodyLimit: 128 * 1024 }, async (request, reply) => {
16
- const session = deps.find(request.params.id);
17
- if (!session)
18
- return reply.code(404).send({ code: 'SESSION_NOT_FOUND' });
19
- const text = request.body.text?.trim() ?? '';
20
- if (text.length > 100_000)
21
- return reply.code(400).send({ code: 'TURN_INPUT_TOO_LONG' });
22
- if (!text)
23
- return reply.code(409).send({ code: 'SESSION_NOT_READY' });
24
10
  const key = request.headers['idempotency-key'];
25
- if (typeof key === 'string' && key && deps.idempotency) {
26
- const scope = `start-turn:${session.id}`;
27
- const fingerprint = createHash('sha256').update(text).digest('hex');
28
- const cached = deps.idempotency.get(scope, key);
29
- if (cached)
30
- return replay(cached, fingerprint, reply);
31
- const inflightKey = `${scope}:${key}`;
32
- const operation = inflight.get(inflightKey) ??
33
- (async () => {
34
- return serializeSession(sessionOperations, session.id, async () => {
35
- const current = deps.find(session.id);
36
- if (!current)
37
- return { statusCode: 404, body: JSON.stringify({ code: 'SESSION_NOT_FOUND' }) };
38
- const durable = deps.idempotency.get(scope, key);
39
- if (durable)
40
- return durable;
41
- if (current.state === 'turnActive')
42
- return { statusCode: 409, body: JSON.stringify({ code: 'SESSION_TURN_ACTIVE' }) };
43
- let started;
44
- try {
45
- started = await startWithWriter(deps, current, text, key);
46
- }
47
- catch (error) {
48
- if (error instanceof StartTurnProblem)
49
- return error.result;
50
- throw error;
51
- }
52
- const result = {
53
- statusCode: 202,
54
- body: JSON.stringify({ fingerprint, response: started }),
55
- };
56
- deps.idempotency.put(scope, key, result.statusCode, result.body);
57
- return result;
58
- });
59
- })();
60
- inflight.set(inflightKey, operation);
61
- try {
62
- return replay(await operation, fingerprint, reply);
63
- }
64
- finally {
65
- inflight.delete(inflightKey);
66
- }
67
- }
68
- return serializeSession(sessionOperations, session.id, async () => {
69
- const current = deps.find(session.id);
70
- if (!current)
71
- return reply.code(404).send({ code: 'SESSION_NOT_FOUND' });
72
- if (current.state === 'turnActive')
73
- return reply.code(409).send({ code: 'SESSION_TURN_ACTIVE' });
74
- try {
75
- return reply
76
- .code(202)
77
- .send(await startWithWriter(deps, current, text, typeof key === 'string' ? key : undefined));
78
- }
79
- catch (error) {
80
- if (error instanceof StartTurnProblem)
81
- return reply.code(error.result.statusCode).send(JSON.parse(error.result.body));
82
- throw error;
83
- }
11
+ const result = await submit({
12
+ sessionId: request.params.id,
13
+ text: request.body.text ?? '',
14
+ ...(typeof key === 'string' ? { key } : {}),
84
15
  });
16
+ return result.kind === 'accepted'
17
+ ? reply.code(202).send(result.session)
18
+ : reply.code(result.statusCode).send(result.problem);
85
19
  });
86
20
  }
87
- async function startWithWriter(deps, session, text, key) {
88
- const writable = await ensureWriter(deps, session);
89
- if ('body' in writable)
90
- throw new StartTurnProblem(writable);
91
- try {
92
- if (writable.session !== session)
93
- deps.save(writable.session);
94
- }
95
- catch (error) {
96
- await cleanupAcquiredWriter(deps, writable.session, session);
97
- throw error;
98
- }
99
- try {
100
- const started = await deps.start(writable.session, text, key);
101
- deps.save(started);
102
- deps.onStarted?.(started);
103
- return started;
104
- }
105
- catch (error) {
106
- if (writable.session !== session)
107
- await cleanupAcquiredWriter(deps, writable.session, session);
108
- throw error;
109
- }
110
- }
111
- class StartTurnProblem extends Error {
112
- result;
113
- constructor(result) {
114
- super('START_TURN_PROBLEM');
115
- this.result = result;
116
- }
117
- }
118
- async function serializeSession(operations, sessionId, operation) {
119
- const prior = operations.get(sessionId) ?? Promise.resolve();
120
- let release;
121
- const current = new Promise((resolve) => {
122
- release = resolve;
123
- });
124
- operations.set(sessionId, current);
125
- await prior;
126
- try {
127
- return await operation();
128
- }
129
- finally {
130
- release();
131
- if (operations.get(sessionId) === current)
132
- operations.delete(sessionId);
133
- }
134
- }
135
- /** Cleanup is best effort: never replace the original start/persistence error. */
136
- async function cleanupAcquiredWriter(deps, acquired, original) {
137
- try {
138
- await deps.releaseWriter?.(acquired.id);
139
- }
140
- catch {
141
- // Process loss is already a valid release outcome.
142
- }
143
- try {
144
- deps.save(original);
145
- }
146
- catch {
147
- // The original I/O failure remains the observable failure.
148
- }
149
- }
150
- async function ensureWriter(deps, session) {
151
- if (!deps.ensureWriter) {
152
- if (session.state === 'ready')
153
- return { session, replacementCreated: false };
154
- return failure('runtimeUnavailable');
155
- }
156
- try {
157
- return await deps.ensureWriter(session);
158
- }
159
- catch (error) {
160
- if (error instanceof WriterAcquisitionError &&
161
- error.kind === 'writerBusy' &&
162
- session.state !== 'stopped')
163
- deps.save(RelaySession.rehydrate(session).stop(new Date().toISOString()).snapshot);
164
- return failure(error instanceof WriterAcquisitionError ? error.kind : 'runtimeUnavailable');
165
- }
166
- }
167
- function failure(kind) {
168
- const problem = writerAcquisitionProblem(kind);
169
- return { statusCode: problem.status, body: JSON.stringify(problem) };
170
- }
171
- function replay(result, fingerprint, reply) {
172
- const cached = JSON.parse(result.body);
173
- if (cached.fingerprint === undefined)
174
- return reply.code(result.statusCode).send(cached);
175
- if (cached.fingerprint !== fingerprint)
176
- return reply.code(409).send({ code: 'IDEMPOTENCY_KEY_REUSED' });
177
- return reply.code(result.statusCode).send(cached.response);
178
- }
@@ -0,0 +1,243 @@
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 { createHash } from 'node:crypto';
7
+ import { RelaySession } from '../model/relay-session.js';
8
+ import { WriterAcquisitionError, writerAcquisitionProblem, } from '../application/writer-acquisition.js';
9
+ /** Ordinary turn acceptance, shared by HTTP and application callers with one serialization boundary. */
10
+ export function createStartTurn(deps) {
11
+ const inflight = new Map();
12
+ const sessionOperations = new Map();
13
+ const pending = new Map();
14
+ const submit = async ({ sessionId, text: rawText, key }) => {
15
+ const session = deps.find(sessionId);
16
+ if (!session)
17
+ return { kind: 'rejected', statusCode: 404, problem: { code: 'SESSION_NOT_FOUND' } };
18
+ const text = rawText.trim();
19
+ if (text.length > 100_000)
20
+ return { kind: 'rejected', statusCode: 400, problem: { code: 'TURN_INPUT_TOO_LONG' } };
21
+ if (!text)
22
+ return { kind: 'rejected', statusCode: 409, problem: { code: 'SESSION_NOT_READY' } };
23
+ if (key && deps.idempotency) {
24
+ const scope = `start-turn:${session.id}`;
25
+ const fingerprint = createHash('sha256').update(text).digest('hex');
26
+ const cached = deps.idempotency.get(scope, key);
27
+ if (cached)
28
+ return replay(cached, fingerprint);
29
+ const inflightKey = `${scope}:${key}`;
30
+ const operation = inflight.get(inflightKey) ??
31
+ serializeSession(sessionOperations, session.id, async () => {
32
+ const current = deps.find(session.id);
33
+ if (!current)
34
+ return { statusCode: 404, body: JSON.stringify({ code: 'SESSION_NOT_FOUND' }) };
35
+ const durable = deps.idempotency.get(scope, key);
36
+ if (durable)
37
+ return durable;
38
+ if (current.state === 'turnActive')
39
+ return { statusCode: 409, body: JSON.stringify({ code: 'SESSION_TURN_ACTIVE' }) };
40
+ let started;
41
+ try {
42
+ started = await startWithWriter(deps, current, text, key);
43
+ }
44
+ catch (error) {
45
+ if (error instanceof StartTurnProblem)
46
+ return error.result;
47
+ throw error;
48
+ }
49
+ const result = {
50
+ statusCode: 202,
51
+ body: JSON.stringify({ fingerprint, response: started }),
52
+ };
53
+ return result;
54
+ });
55
+ inflight.set(inflightKey, operation);
56
+ try {
57
+ return replay(await operation, fingerprint);
58
+ }
59
+ finally {
60
+ inflight.delete(inflightKey);
61
+ }
62
+ }
63
+ return serializeSession(sessionOperations, session.id, async () => {
64
+ const current = deps.find(session.id);
65
+ if (!current)
66
+ return {
67
+ kind: 'rejected',
68
+ statusCode: 404,
69
+ problem: { code: 'SESSION_NOT_FOUND' },
70
+ };
71
+ if (current.state === 'turnActive')
72
+ return {
73
+ kind: 'rejected',
74
+ statusCode: 409,
75
+ problem: { code: 'SESSION_TURN_ACTIVE' },
76
+ };
77
+ try {
78
+ return {
79
+ kind: 'accepted',
80
+ session: await startWithWriter(deps, current, text, key),
81
+ };
82
+ }
83
+ catch (error) {
84
+ if (error instanceof StartTurnProblem)
85
+ return {
86
+ kind: 'rejected',
87
+ statusCode: error.result.statusCode,
88
+ problem: JSON.parse(error.result.body),
89
+ };
90
+ throw error;
91
+ }
92
+ });
93
+ };
94
+ return Object.assign(async (input) => {
95
+ pending.set(input.sessionId, (pending.get(input.sessionId) ?? 0) + 1);
96
+ try {
97
+ return await submit(input);
98
+ }
99
+ finally {
100
+ const count = (pending.get(input.sessionId) ?? 1) - 1;
101
+ if (count)
102
+ pending.set(input.sessionId, count);
103
+ else {
104
+ pending.delete(input.sessionId);
105
+ deps.onSettled?.(input.sessionId);
106
+ }
107
+ }
108
+ }, { pending: (id) => pending.has(id) });
109
+ }
110
+ async function startWithWriter(deps, session, text, key) {
111
+ const writable = await ensureWriter(deps, session);
112
+ if ('body' in writable)
113
+ throw new StartTurnProblem(writable);
114
+ if (writable.persisted) {
115
+ const current = deps.find(session.id);
116
+ if (current?.desiredState !== 'active' || current.threadId !== writable.session.threadId)
117
+ throw new StartTurnProblem({
118
+ statusCode: 409,
119
+ body: JSON.stringify({ code: 'SESSION_NOT_READY' }),
120
+ });
121
+ }
122
+ try {
123
+ if (writable.session !== session && !writable.persisted)
124
+ deps.save(writable.session);
125
+ }
126
+ catch (error) {
127
+ await cleanupAcquiredWriter(deps, writable.session, session);
128
+ throw error;
129
+ }
130
+ let accepted = false;
131
+ try {
132
+ const started = await deps.start(writable.session, text, key);
133
+ accepted = true;
134
+ const current = deps.find(session.id);
135
+ if (!current)
136
+ return started;
137
+ // Persist the normal acceptance receipt before a later snapshot/event write can fail.
138
+ if (key)
139
+ deps.idempotency?.put(`start-turn:${session.id}`, key, 202, JSON.stringify({ fingerprint: fingerprintTurnInput(text), response: started }));
140
+ deps.onAccepted?.(started, key);
141
+ if (current?.desiredState === 'stopped')
142
+ deps.save(current);
143
+ else {
144
+ deps.save(started);
145
+ deps.onStarted?.(started);
146
+ }
147
+ return started;
148
+ }
149
+ catch (error) {
150
+ if (!accepted && writable.session !== session && !writable.persisted)
151
+ await cleanupAcquiredWriter(deps, writable.session, session);
152
+ throw error;
153
+ }
154
+ }
155
+ export function fingerprintTurnInput(text) {
156
+ return createHash('sha256').update(text.trim()).digest('hex');
157
+ }
158
+ /** Reads a durable ordinary receipt without activating a writer or submitting a turn. */
159
+ export function readAcceptedTurn(store, sessionId, key, fingerprint) {
160
+ const result = store.get(`start-turn:${sessionId}`, key);
161
+ if (!result || result.statusCode !== 202)
162
+ return null;
163
+ try {
164
+ const body = JSON.parse(result.body);
165
+ return body.fingerprint === fingerprint &&
166
+ body.response?.id === sessionId &&
167
+ typeof body.response.activeTurnId === 'string' &&
168
+ body.response.activeTurnId
169
+ ? body.response
170
+ : null;
171
+ }
172
+ catch {
173
+ return null;
174
+ }
175
+ }
176
+ class StartTurnProblem extends Error {
177
+ result;
178
+ constructor(result) {
179
+ super('START_TURN_PROBLEM');
180
+ this.result = result;
181
+ }
182
+ }
183
+ async function serializeSession(operations, sessionId, operation) {
184
+ const prior = operations.get(sessionId) ?? Promise.resolve();
185
+ let release;
186
+ const current = new Promise((resolve) => {
187
+ release = resolve;
188
+ });
189
+ operations.set(sessionId, current);
190
+ await prior;
191
+ try {
192
+ return await operation();
193
+ }
194
+ finally {
195
+ release();
196
+ if (operations.get(sessionId) === current)
197
+ operations.delete(sessionId);
198
+ }
199
+ }
200
+ /** Cleanup is best effort: never replace the original start/persistence error. */
201
+ async function cleanupAcquiredWriter(deps, acquired, original) {
202
+ try {
203
+ await deps.releaseWriter?.(acquired.id);
204
+ }
205
+ catch {
206
+ // Process loss is already a valid release outcome.
207
+ }
208
+ try {
209
+ deps.save(original);
210
+ }
211
+ catch {
212
+ // The original I/O failure remains the observable failure.
213
+ }
214
+ }
215
+ async function ensureWriter(deps, session) {
216
+ if (!deps.ensureWriter) {
217
+ if (session.state === 'ready')
218
+ return { session, replacementCreated: false };
219
+ return failure('runtimeUnavailable');
220
+ }
221
+ try {
222
+ return await deps.ensureWriter(session);
223
+ }
224
+ catch (error) {
225
+ if (error instanceof WriterAcquisitionError &&
226
+ error.kind === 'writerBusy' &&
227
+ session.state !== 'stopped')
228
+ deps.save(RelaySession.rehydrate(session).stop(new Date().toISOString()).snapshot);
229
+ return failure(error instanceof WriterAcquisitionError ? error.kind : 'runtimeUnavailable');
230
+ }
231
+ }
232
+ function failure(kind) {
233
+ const problem = writerAcquisitionProblem(kind);
234
+ return { statusCode: problem.status, body: JSON.stringify(problem) };
235
+ }
236
+ function replay(result, fingerprint) {
237
+ const cached = JSON.parse(result.body);
238
+ if (cached.fingerprint === undefined)
239
+ return { kind: 'rejected', statusCode: result.statusCode, problem: cached };
240
+ if (cached.fingerprint !== fingerprint)
241
+ return { kind: 'rejected', statusCode: 409, problem: { code: 'IDEMPOTENCY_KEY_REUSED' } };
242
+ return { kind: 'accepted', session: cached.response };
243
+ }
@@ -0,0 +1,34 @@
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
+ /** Shared list semantics: retain invalid/disappeared profiles as recoverable read errors. */
7
+ export async function readGlobalSkillProfiles(store) {
8
+ const names = await store.listGlobalProfileNames();
9
+ return Promise.all(names
10
+ .sort((a, b) => a.localeCompare(b))
11
+ .map(async (name) => {
12
+ try {
13
+ const profile = await store.readGlobalProfile(name);
14
+ return profile
15
+ ? { name: profile.name, profile }
16
+ : {
17
+ name,
18
+ error: {
19
+ code: 'INVALID_SKILL_PROFILE',
20
+ message: 'Profile disappeared while reading.',
21
+ },
22
+ };
23
+ }
24
+ catch (error) {
25
+ return {
26
+ name,
27
+ error: {
28
+ code: 'INVALID_SKILL_PROFILE',
29
+ message: error instanceof Error ? error.message : 'Invalid profile.',
30
+ },
31
+ };
32
+ }
33
+ }));
34
+ }
@@ -4,43 +4,19 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { problem } from '../../../platform/http/problem.js';
7
+ import { readGlobalSkillProfiles } from '../application/read-global-profiles.js';
7
8
  export function registerListSkillProfiles(app, deps) {
8
9
  app.get('/api/skill-profiles', async (_request, reply) => {
9
10
  try {
10
- const names = await deps.listGlobalProfileNames();
11
- const profiles = await Promise.all(names
12
- .sort((a, b) => a.localeCompare(b))
13
- .map(async (name) => {
14
- try {
15
- const profile = await deps.readGlobalProfile(name);
16
- return profile
17
- ? {
18
- name: profile.name,
19
- version: profile.version,
20
- path: deps.profilePath(name),
21
- skills: profile.skills,
22
- ...(profile.capabilities ? { capabilities: profile.capabilities } : {}),
23
- }
24
- : {
25
- name,
26
- path: deps.profilePath(name),
27
- error: {
28
- code: 'INVALID_SKILL_PROFILE',
29
- message: 'Profile disappeared while reading.',
30
- },
31
- };
11
+ const profiles = (await readGlobalSkillProfiles(deps)).map((entry) => 'profile' in entry
12
+ ? {
13
+ name: entry.profile.name,
14
+ version: entry.profile.version,
15
+ path: deps.profilePath(entry.name),
16
+ skills: entry.profile.skills,
17
+ ...(entry.profile.capabilities ? { capabilities: entry.profile.capabilities } : {}),
32
18
  }
33
- catch (error) {
34
- return {
35
- name,
36
- path: deps.profilePath(name),
37
- error: {
38
- code: 'INVALID_SKILL_PROFILE',
39
- message: error instanceof Error ? error.message : 'Invalid profile.',
40
- },
41
- };
42
- }
43
- }));
19
+ : { name: entry.name, path: deps.profilePath(entry.name), error: entry.error });
44
20
  return { profiles };
45
21
  }
46
22
  catch {
@@ -15,6 +15,17 @@ export class FilesystemWorkspaceCatalog {
15
15
  async list() {
16
16
  return [(await this.tree()).option];
17
17
  }
18
+ /** One authorized traversal with canonical identity/path pairs for internal consumers. */
19
+ async snapshot() {
20
+ const entries = [];
21
+ const collect = (entry) => {
22
+ entries.push({ id: entry.option.id, name: entry.option.name, realPath: entry.realPath });
23
+ for (const child of entry.children)
24
+ collect(child);
25
+ };
26
+ collect(await this.tree());
27
+ return entries;
28
+ }
18
29
  /** Keep canonical catalog identities without treating owned scratch as workspaces. */
19
30
  async knownWorkspacePaths() {
20
31
  const paths = [];
@@ -191,22 +191,35 @@ export class CodexSessionRuntime {
191
191
  repositories,
192
192
  };
193
193
  }
194
- async start(session, now) {
194
+ async start(session, now, fence) {
195
+ fence?.assertCurrent();
195
196
  const resource = await this.createResource(session);
197
+ const assertCurrent = () => {
198
+ fence?.assertCurrent();
199
+ if (fence && !resource.active)
200
+ throw new Error('CODEX_SESSION_START_FENCED');
201
+ };
202
+ const beforeThreadStart = () => {
203
+ assertCurrent();
204
+ fence?.beforeThreadStart();
205
+ };
196
206
  try {
207
+ assertCurrent();
197
208
  await resource.process.rpc.request('initialize', {
198
209
  clientInfo: { name: 'gestalt-mobile', version: '0.1.0' },
199
210
  capabilities: { experimentalApi: true },
200
211
  });
201
212
  await this.prepareRetrieval(resource, session);
202
- const startedThreadId = await this.startThread(resource.process, session, resource.skillsConfig, resource.modelConfig);
213
+ const startedThreadId = await this.startThread(resource.process, session, resource.skillsConfig, resource.modelConfig, beforeThreadStart);
203
214
  resource.threadId = startedThreadId;
204
215
  if (resource.retrieval)
205
216
  this.retrieval?.bound?.(resource.retrieval, startedThreadId);
206
- await this.verifyRetrieval(resource, session, true);
217
+ await this.verifyRetrieval(resource, session, true, beforeThreadStart);
207
218
  await this.scratch?.associateProviderThread(session, 'codex', resource.threadId);
219
+ assertCurrent();
208
220
  this.sessions.set(session.id, resource);
209
221
  await this.writePendingThreadName(session.id);
222
+ assertCurrent();
210
223
  return this.withEffectiveRetrieval(RelaySession.rehydrate(session)
211
224
  .bindThread(resource.threadId, now)
212
225
  .supportsAttentionTool(now).snapshot, resource);
@@ -1387,7 +1400,8 @@ export class CodexSessionRuntime {
1387
1400
  }
1388
1401
  });
1389
1402
  }
1390
- async startThread(process, session, skillsConfig, modelConfig = {}) {
1403
+ async startThread(process, session, skillsConfig, modelConfig = {}, beforeRequest) {
1404
+ beforeRequest?.();
1391
1405
  return decodeThreadStart(await process.rpc.request('thread/start', this.threadStartParams(session, skillsConfig, modelConfig)));
1392
1406
  }
1393
1407
  threadStartParams(session, skillsConfig, modelConfig = {}) {
@@ -1684,7 +1698,7 @@ export class CodexSessionRuntime {
1684
1698
  }, { kind: 'root' });
1685
1699
  }
1686
1700
  }
1687
- async verifyRetrieval(resource, session, fresh = false) {
1701
+ async verifyRetrieval(resource, session, fresh = false, beforeThreadStart) {
1688
1702
  const state = resource.retrieval;
1689
1703
  if (!state?.ready || !resource.threadId || !this.retrieval)
1690
1704
  return;
@@ -1724,7 +1738,7 @@ export class CodexSessionRuntime {
1724
1738
  // before publishing a thread ID. Persisted resumes retain their identity.
1725
1739
  if (fresh) {
1726
1740
  await resource.process.rpc.request('thread/unsubscribe', { threadId: resource.threadId });
1727
- resource.threadId = await this.startThread(resource.process, session, resource.skillsConfig, resource.modelConfig);
1741
+ resource.threadId = await this.startThread(resource.process, session, resource.skillsConfig, resource.modelConfig, beforeThreadStart);
1728
1742
  this.retrieval.bound?.(state, resource.threadId);
1729
1743
  return;
1730
1744
  }
@@ -28,6 +28,18 @@ function migrateWorkspaceGitDefaults(database) {
28
28
  }
29
29
  export function migrate(database) {
30
30
  database.exec(schema);
31
+ database.exec(`CREATE TABLE IF NOT EXISTS org_plan_launches (
32
+ launch_id TEXT PRIMARY KEY,
33
+ canonical_path TEXT UNIQUE,
34
+ session_id TEXT NOT NULL UNIQUE,
35
+ phase TEXT NOT NULL CHECK(phase IN ('reserved','creating','session','submitting','accepted')),
36
+ record_json TEXT NOT NULL
37
+ );`);
38
+ database.exec(`CREATE TABLE IF NOT EXISTS org_plan_initial_activations (
39
+ session_id TEXT PRIMARY KEY,
40
+ revision INTEGER NOT NULL,
41
+ phase TEXT NOT NULL CHECK(phase IN ('idle','preparing','requested','retryable','completed'))
42
+ );`);
31
43
  database.exec(`CREATE TABLE IF NOT EXISTS session_forget_operations (
32
44
  session_id TEXT PRIMARY KEY CHECK(length(session_id) BETWEEN 1 AND 256),
33
45
  operation_id TEXT NOT NULL UNIQUE CHECK(length(operation_id) = 36),