gestalt-mobile 0.65.8 → 0.66.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.
Files changed (52) hide show
  1. package/README.md +28 -4
  2. package/dist/client/assets/index-BDsGojoG.js +128 -0
  3. package/dist/client/assets/{index-VDRT2Esv.css → index-DxsD-jG4.css} +1 -1
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/server/cli.js +2 -1
  6. package/dist/server/server/composition.contracts.js +179 -84
  7. package/dist/server/server/composition.js +65 -5
  8. package/dist/server/server/features/sessions/application/session-scratch.js +6 -0
  9. package/dist/server/server/features/sessions/clean-tmp/endpoint.js +68 -0
  10. package/dist/server/server/features/sessions/clean-tmp/use-case.js +82 -0
  11. package/dist/server/server/features/sessions/forget-session/endpoint.js +10 -2
  12. package/dist/server/server/features/sessions/forget-session/use-case.js +75 -0
  13. package/dist/server/server/features/sessions/get-session/endpoint.js +2 -1
  14. package/dist/server/server/features/sessions/list-sessions/endpoint.js +3 -0
  15. package/dist/server/server/features/sessions/promote-recent-thread/use-case.js +4 -1
  16. package/dist/server/server/features/sessions/register-routes.js +29 -2
  17. package/dist/server/server/features/sessions/start-session/endpoint.js +7 -0
  18. package/dist/server/server/features/sessions/start-session/use-case.js +4 -1
  19. package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +19 -1
  20. package/dist/server/server/platform/codex/codex-playwright.js +41 -3
  21. package/dist/server/server/platform/codex/codex-process-launcher.js +24 -2
  22. package/dist/server/server/platform/codex/codex-serena.js +2 -1
  23. package/dist/server/server/platform/codex/managed-playwright.js +48 -36
  24. package/dist/server/server/platform/codex/session-runtime.js +134 -4
  25. package/dist/server/server/platform/git/command.js +7 -1
  26. package/dist/server/server/platform/host-tests/runner.js +47 -6
  27. package/dist/server/server/platform/kimi/kimi-session-runtime.js +41 -0
  28. package/dist/server/server/platform/kimi/kimi-web-server-manager.js +13 -17
  29. package/dist/server/server/platform/maintenance/managed-upgrade.js +2 -1
  30. package/dist/server/server/platform/persistence/migrate.js +24 -0
  31. package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +67 -0
  32. package/dist/server/server/platform/persistence/sqlite-session-repository.js +4 -0
  33. package/dist/server/server/platform/plans/org-plan-discovery.js +2 -0
  34. package/dist/server/server/platform/plans/plan-measurement-command.js +5 -1
  35. package/dist/server/server/platform/retrieval/codex-xerj.js +8 -1
  36. package/dist/server/server/platform/retrieval/managed-xerj.js +2 -1
  37. package/dist/server/server/platform/retrieval/repository-readiness.js +2 -1
  38. package/dist/server/server/platform/retrieval/xerj-indexer.js +21 -11
  39. package/dist/server/server/platform/scratch/child-environment.js +21 -0
  40. package/dist/server/server/platform/scratch/containment-fence.js +262 -0
  41. package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +247 -0
  42. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +360 -0
  43. package/dist/server/server/platform/scratch/legacy-scratch-layouts.js +22 -0
  44. package/dist/server/server/platform/scratch/managed-scratch-owner.js +148 -0
  45. package/dist/server/server/platform/scratch/owned-process-group.js +53 -0
  46. package/dist/server/server/platform/scratch/owner-fence.js +27 -0
  47. package/dist/server/server/platform/scratch/scratch-filesystem.js +53 -0
  48. package/dist/server/server/platform/self-debug/workspace.js +3 -0
  49. package/dist/server/shared/contracts/session-forget.js +6 -0
  50. package/dist/server/shared/contracts/tmp-cleanup.js +6 -0
  51. package/package.json +1 -1
  52. package/dist/client/assets/index-CKJWzSwH.js +0 -128
@@ -0,0 +1,82 @@
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 emptyScratchCounts() {
7
+ return {
8
+ removed: 0,
9
+ skipped: 0,
10
+ failed: 0,
11
+ reasons: { protected: 0, busy: 0, lease: 0, unrecognized: 0, unsafe: 0, unavailable: 0, io: 0 },
12
+ };
13
+ }
14
+ /** Read the authoritative roster again inside each storage fence, never a UI snapshot. */
15
+ export class CleanSessionScratch {
16
+ deps;
17
+ constructor(deps) {
18
+ this.deps = deps;
19
+ }
20
+ async execute() {
21
+ const result = {
22
+ status: 'complete',
23
+ workspaces: { cleaned: 0, removed: 0, skipped: 0, failed: 0, unavailable: 0 },
24
+ folders: emptyScratchCounts(),
25
+ };
26
+ const paths = new Set(this.deps.sessions().map((session) => session.workspacePath));
27
+ const sources = [() => this.deps.knownWorkspacePaths()];
28
+ if (this.deps.additionalWorkspacePaths)
29
+ sources.push(() => this.deps.additionalWorkspacePaths());
30
+ for (const source of sources) {
31
+ try {
32
+ for (const path of await source())
33
+ paths.add(path);
34
+ }
35
+ catch {
36
+ // A failed catalog is an unknown discovery scope, not an invented folder
37
+ // or workspace count. Other durable/catalog sources remain usable.
38
+ result.status = 'partial';
39
+ result.folders.reasons.unavailable++;
40
+ }
41
+ }
42
+ const seen = new Set();
43
+ for (const path of paths) {
44
+ let canonical;
45
+ try {
46
+ canonical = await this.deps.storage.canonicalWorkspace(path);
47
+ }
48
+ catch (error) {
49
+ const unsafe = error instanceof Error && error.message.startsWith('SESSION_SCRATCH_');
50
+ result.workspaces[unsafe ? 'skipped' : 'unavailable']++;
51
+ result.folders.reasons[unsafe ? 'unsafe' : 'unavailable']++;
52
+ continue;
53
+ }
54
+ if (seen.has(canonical))
55
+ continue;
56
+ seen.add(canonical);
57
+ try {
58
+ const counts = await this.deps.storage.cleanWorkspace(canonical, () => this.deps.sessions());
59
+ result.folders.removed += counts.removed;
60
+ if (counts.removed)
61
+ result.workspaces.removed++;
62
+ result.folders.skipped += counts.skipped;
63
+ result.folders.failed += counts.failed;
64
+ for (const reason of Object.keys(counts.reasons))
65
+ result.folders.reasons[reason] += counts.reasons[reason];
66
+ result.workspaces[counts.failed ? 'failed' : counts.skipped ? 'skipped' : 'cleaned']++;
67
+ }
68
+ catch (error) {
69
+ const unsafe = error instanceof Error && error.message.startsWith('SESSION_SCRATCH_');
70
+ const unavailable = ['ENOENT', 'EACCES', 'EPERM'].includes(error.code ?? '');
71
+ result.workspaces[unsafe ? 'skipped' : unavailable ? 'unavailable' : 'failed']++;
72
+ result.folders.reasons[unsafe ? 'unsafe' : unavailable ? 'unavailable' : 'io']++;
73
+ }
74
+ }
75
+ if (result.workspaces.failed ||
76
+ result.workspaces.unavailable ||
77
+ result.folders.reasons.unsafe ||
78
+ result.folders.reasons.io)
79
+ result.status = 'partial';
80
+ return result;
81
+ }
82
+ }
@@ -6,10 +6,18 @@
6
6
  export function registerForgetSession(app, deps) {
7
7
  app.delete('/api/sessions/:id', async (request, reply) => {
8
8
  const id = request.params.id;
9
+ if (deps.forget) {
10
+ const operation = await deps.forget(id);
11
+ if (!operation)
12
+ return reply.code(404).send({ code: 'SESSION_NOT_FOUND' });
13
+ if (operation.phase !== 'completed')
14
+ return reply.code(503).send({ code: 'SESSION_FORGET_FAILED', operation });
15
+ return reply.code(204).send();
16
+ }
9
17
  if (!deps.find(id))
10
18
  return reply.code(404).send({ code: 'SESSION_NOT_FOUND' });
11
- await deps.close(id);
12
- deps.remove(id);
19
+ await deps.close?.(id);
20
+ deps.remove?.(id);
13
21
  return reply.code(204).send();
14
22
  });
15
23
  }
@@ -0,0 +1,75 @@
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 class ForgetSession {
7
+ deps;
8
+ pending = new Map();
9
+ constructor(deps) {
10
+ this.deps = deps;
11
+ }
12
+ execute(id) {
13
+ const prior = this.pending.get(id);
14
+ if (prior)
15
+ return prior;
16
+ const operation = this.run(id);
17
+ this.pending.set(id, operation);
18
+ void operation
19
+ .finally(() => {
20
+ if (this.pending.get(id) === operation)
21
+ this.pending.delete(id);
22
+ })
23
+ .catch(() => undefined);
24
+ return operation;
25
+ }
26
+ async drain() {
27
+ await Promise.allSettled([...this.pending.values()]);
28
+ }
29
+ async run(id) {
30
+ const initial = this.deps.operations.begin(id);
31
+ if (!initial || initial.phase === 'completed')
32
+ return initial;
33
+ let operation = initial;
34
+ const advance = (phase) => {
35
+ operation = this.deps.operations.update({
36
+ operationId: operation.operationId,
37
+ sessionId: id,
38
+ phase,
39
+ updatedAt: this.deps.now(),
40
+ });
41
+ this.deps.changed(operation);
42
+ return operation;
43
+ };
44
+ let failureCode = 'SESSION_RELEASE_UNCONFIRMED';
45
+ try {
46
+ const session = this.deps.find(id);
47
+ if (!session)
48
+ throw new Error('SESSION_FORGET_FAILED');
49
+ // Restart/retry re-enters release. Prior timestamps and process IDs prove nothing.
50
+ if (advance('stopping').phase === 'completed')
51
+ return operation;
52
+ await this.deps.release(session);
53
+ failureCode = 'SESSION_CLEANUP_FAILED';
54
+ if (advance('cleaning').phase === 'completed')
55
+ return operation;
56
+ await this.deps.clean(session, operation.operationId);
57
+ failureCode = 'SESSION_FORGET_FAILED';
58
+ if (advance('finalizing').phase === 'completed')
59
+ return operation;
60
+ operation = this.deps.operations.finalize({ ...operation, updatedAt: this.deps.now() });
61
+ this.deps.changed(operation);
62
+ return operation;
63
+ }
64
+ catch {
65
+ operation = this.deps.operations.update({
66
+ ...operation,
67
+ phase: 'failed',
68
+ failureCode,
69
+ updatedAt: this.deps.now(),
70
+ });
71
+ this.deps.changed(operation);
72
+ return operation;
73
+ }
74
+ }
75
+ }
@@ -6,7 +6,7 @@
6
6
  import { buildResumeCommand } from '../application/resume-command.js';
7
7
  import { toAgentActivityDto } from '../../agent-activity/activity-dto.js';
8
8
  import { deriveSessionStatus } from '../session-status.js';
9
- export function registerGetSession(app, find, activity, autopilot, plan, toolEfficiency, currentSequence) {
9
+ export function registerGetSession(app, find, activity, autopilot, plan, toolEfficiency, currentSequence, forgetOperation) {
10
10
  app.get('/api/sessions/:id', async (request, reply) => {
11
11
  const session = find(request.params.id);
12
12
  if (!session)
@@ -16,6 +16,7 @@ export function registerGetSession(app, find, activity, autopilot, plan, toolEff
16
16
  const retainedPlan = plan?.(session.id) ?? null;
17
17
  return reply.send({
18
18
  ...session,
19
+ ...(forgetOperation?.(session.id) ? { forgetOperation: forgetOperation(session.id) } : {}),
19
20
  ...(currentSequence ? { currentSequence: currentSequence(session.id) } : {}),
20
21
  ...(activitySnapshot ? { agentActivity: toAgentActivityDto(activitySnapshot) } : {}),
21
22
  ...(autopilotSnapshot ? { autopilot: autopilotSnapshot } : {}),
@@ -13,6 +13,9 @@ export function registerListSessions(app, deps) {
13
13
  const autopilot = deps.autopilot?.(session.id) ?? null;
14
14
  return {
15
15
  ...session,
16
+ ...(deps.forgetOperation?.(session.id)
17
+ ? { forgetOperation: deps.forgetOperation(session.id) }
18
+ : {}),
16
19
  ...(activity ? { agentActivity: toAgentActivityDto(activity) } : {}),
17
20
  ...(autopilot ? { autopilot } : {}),
18
21
  ...(plan ? { plan } : {}),
@@ -68,6 +68,9 @@ async function promote(thread, deps) {
68
68
  catch {
69
69
  throw new RecentThreadHistoryUnavailable();
70
70
  }
71
- deps.save(imported);
71
+ if (deps.publish)
72
+ await deps.publish(imported);
73
+ else
74
+ deps.save(imported);
72
75
  return imported;
73
76
  }
@@ -24,8 +24,10 @@ import { registerStartTurn } from './start-turn/endpoint.js';
24
24
  import { registerStopSession } from './stop-session/endpoint.js';
25
25
  import { registerRefreshActivity } from './refresh-activity/endpoint.js';
26
26
  import { registerGetRetrievalReadiness } from './get-retrieval-readiness/endpoint.js';
27
+ import { registerCleanTmp } from './clean-tmp/endpoint.js';
27
28
  export function registerSessionRoutes(app, deps) {
28
29
  const sessions = deps.sessionRoutes;
30
+ registerCleanTmp(app, deps.tmpCleanup);
29
31
  if (deps.recentThreads) {
30
32
  registerListRecentThreads(app, {
31
33
  ...deps.recentThreads,
@@ -48,6 +50,29 @@ export function registerSessionRoutes(app, deps) {
48
50
  });
49
51
  }
50
52
  if (sessions) {
53
+ const conflict = (request) => {
54
+ if (!request.routeOptions.url?.startsWith('/api/sessions/:id'))
55
+ return null;
56
+ if (['GET', 'HEAD'].includes(request.method))
57
+ return null;
58
+ if (request.method === 'DELETE' && request.routeOptions.url === '/api/sessions/:id')
59
+ return null;
60
+ const id = request.params?.id;
61
+ return id ? sessions.forgetOperation?.(id) : null;
62
+ };
63
+ app.addHook('preHandler', async (request, reply) => {
64
+ const operation = conflict(request);
65
+ if (operation)
66
+ return reply.code(409).send({ code: 'SESSION_FORGET_IN_PROGRESS', operation });
67
+ });
68
+ app.addHook('preSerialization', async (request, reply, payload) => {
69
+ const operation = reply.statusCode < 400 ? conflict(request) : null;
70
+ if (operation) {
71
+ reply.code(409);
72
+ return { code: 'SESSION_FORGET_IN_PROGRESS', operation };
73
+ }
74
+ return payload;
75
+ });
51
76
  if (sessions.retrievalReadiness)
52
77
  registerGetRetrievalReadiness(app, {
53
78
  exists: (id) => sessions.find(id) !== null,
@@ -59,7 +84,7 @@ export function registerSessionRoutes(app, deps) {
59
84
  ...sessions,
60
85
  reportFailure: (operation, error) => deps.logger.error(`${operation} failed: ${safeErrorLabel(error)}`),
61
86
  });
62
- registerGetSession(app, sessions.find, sessions.agentActivity, sessions.autopilotSnapshot, sessions.plan, sessions.toolEfficiency, sessions.currentSequence);
87
+ registerGetSession(app, sessions.find, sessions.agentActivity, sessions.autopilotSnapshot, sessions.plan, sessions.toolEfficiency, sessions.currentSequence, sessions.forgetOperation);
63
88
  if (sessions.refreshActivity)
64
89
  registerRefreshActivity(app, {
65
90
  exists: (id) => sessions.find(id) !== null,
@@ -68,6 +93,7 @@ export function registerSessionRoutes(app, deps) {
68
93
  if (sessions.list)
69
94
  registerListSessions(app, {
70
95
  list: sessions.list,
96
+ forgetOperation: sessions.forgetOperation,
71
97
  activity: sessions.agentActivity,
72
98
  autopilot: sessions.autopilotSnapshot,
73
99
  plan: sessions.plan,
@@ -124,11 +150,12 @@ export function registerSessionRoutes(app, deps) {
124
150
  close: sessions.close,
125
151
  idempotency: sessions.idempotency,
126
152
  });
127
- if (sessions.remove && sessions.close)
153
+ if (sessions.forget || (sessions.remove && sessions.close))
128
154
  registerForgetSession(app, {
129
155
  find: sessions.find,
130
156
  close: sessions.close,
131
157
  remove: sessions.remove,
158
+ forget: sessions.forget,
132
159
  });
133
160
  if (sessions.close)
134
161
  registerStopSession(app, {
@@ -30,6 +30,13 @@ export function registerStartSession(app, deps) {
30
30
  }
31
31
  catch (error) {
32
32
  deps.reportFailure?.('start-session', error);
33
+ if (error instanceof Error &&
34
+ (error.message.startsWith('SESSION_SCRATCH_') ||
35
+ error.message.startsWith('SCRATCH_CLEANUP_')))
36
+ return reply
37
+ .code(503)
38
+ .type('application/problem+json')
39
+ .send(problem('SESSION_WORKSPACE_UNAVAILABLE', 503, 'The selected workspace is busy or its temporary ownership could not be confirmed. Retry shortly.', true));
33
40
  if (error instanceof Error &&
34
41
  ['ORG_EXECUTOR_PROFILE_UNAVAILABLE', 'ORG_EXECUTOR_PROFILE_INVALID'].includes(error.message))
35
42
  return reply
@@ -84,7 +84,10 @@ export async function startSession(input, deps) {
84
84
  effectiveSkillSelection,
85
85
  now: deps.now(),
86
86
  }).snapshot;
87
- deps.save(session);
87
+ if (deps.publish)
88
+ await deps.publish(session);
89
+ else
90
+ deps.save(session);
88
91
  if (!deps.activate)
89
92
  return session;
90
93
  const active = await deps.activate(session, { provider: session.provider });
@@ -6,6 +6,7 @@
6
6
  import { createHash } from 'node:crypto';
7
7
  import { readdir, realpath, stat } from 'node:fs/promises';
8
8
  import { isAbsolute, join, relative, sep } from 'node:path';
9
+ import { isManagedScratchOwnerDirectory } from '../scratch/managed-scratch-owner.js';
9
10
  export class FilesystemWorkspaceCatalog {
10
11
  root;
11
12
  constructor(root) {
@@ -14,6 +15,17 @@ export class FilesystemWorkspaceCatalog {
14
15
  async list() {
15
16
  return [(await this.tree()).option];
16
17
  }
18
+ /** Keep canonical catalog identities without treating owned scratch as workspaces. */
19
+ async knownWorkspacePaths() {
20
+ const paths = [];
21
+ const collect = (entry) => {
22
+ paths.push(entry.realPath);
23
+ for (const child of entry.children)
24
+ collect(child);
25
+ };
26
+ collect(await this.tree(true));
27
+ return paths;
28
+ }
17
29
  async resolve(id) {
18
30
  const root = await this.root;
19
31
  if (id === this.id(root))
@@ -33,7 +45,7 @@ export class FilesystemWorkspaceCatalog {
33
45
  }
34
46
  : null;
35
47
  }
36
- async tree() {
48
+ async tree(cleanupDiscovery = false) {
37
49
  const root = await this.root;
38
50
  return ((await this.visit({
39
51
  root,
@@ -42,12 +54,17 @@ export class FilesystemWorkspaceCatalog {
42
54
  relativePath: '.',
43
55
  visited: new Set(),
44
56
  isRoot: true,
57
+ cleanupDiscovery,
45
58
  })) ?? this.entry(root, '/', '.', false, []));
46
59
  }
47
60
  async visit(input) {
48
61
  if (input.visited.has(input.realPath))
49
62
  return null;
50
63
  input.visited.add(input.realPath);
64
+ if (input.cleanupDiscovery &&
65
+ !input.isRoot &&
66
+ (await isManagedScratchOwnerDirectory(input.realPath)))
67
+ return null;
51
68
  const isGitRepository = await this.isGitRepository(input.realPath);
52
69
  if (isGitRepository) {
53
70
  return this.entry(input.realPath, input.name, input.relativePath, true, []);
@@ -79,6 +96,7 @@ export class FilesystemWorkspaceCatalog {
79
96
  name: child.name,
80
97
  relativePath: childRelativePath,
81
98
  visited: input.visited,
99
+ cleanupDiscovery: input.cleanupDiscovery,
82
100
  });
83
101
  if (visitedChild)
84
102
  children.push(visitedChild);
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { readFile, realpath } from 'node:fs/promises';
7
7
  import { isAbsolute } from 'node:path';
8
+ import { sessionScratchEnvironmentKeys } from '../scratch/child-environment.js';
8
9
  import { managedPlaywrightRequestSchema } from '../../../shared/contracts/managed-playwright.js';
9
10
  import { profileCapabilitiesSchema } from '../../../shared/contracts/profile-capabilities.js';
10
11
  import { beforeDeadline } from '../retrieval/codex-xerj.js';
@@ -12,10 +13,47 @@ import { ManagedPlaywright, playwrightServerName, playwrightTools, } from './man
12
13
  /** One browser owner per relay root. This is a capability adapter, not a global MCP registry. */
13
14
  export class CodexPlaywright {
14
15
  installation;
16
+ scratch;
15
17
  bindings = new Map();
16
18
  prepared = new WeakMap();
17
- constructor(installation) {
19
+ readinessWork = new Map();
20
+ constructor(installation, scratch) {
18
21
  this.installation = installation;
22
+ this.scratch = scratch;
23
+ }
24
+ readiness(session, manager, workspace, deadline, options) {
25
+ const task = (async () => {
26
+ const context = await this.scratch?.allocate(session);
27
+ const lease = await this.scratch?.borrow?.(session);
28
+ let started = false;
29
+ try {
30
+ this.scratch?.assertAvailable?.(session.id);
31
+ started = true;
32
+ // Production ready() resolves only after its actual process group is absent.
33
+ const result = await this.installation.ready(manager, workspace, deadline, options, context?.environment);
34
+ await lease?.release();
35
+ return result;
36
+ }
37
+ catch (error) {
38
+ if (!started)
39
+ await lease?.release();
40
+ throw error;
41
+ }
42
+ })();
43
+ const pending = this.readinessWork.get(session.id) ?? new Set();
44
+ pending.add(task);
45
+ this.readinessWork.set(session.id, pending);
46
+ void task
47
+ .finally(() => {
48
+ pending.delete(task);
49
+ if (!pending.size)
50
+ this.readinessWork.delete(session.id);
51
+ })
52
+ .catch(() => undefined);
53
+ return task;
54
+ }
55
+ async waitForRelease(sessionId) {
56
+ await Promise.allSettled([...(this.readinessWork.get(sessionId) ?? [])]);
19
57
  }
20
58
  async binding(authority) {
21
59
  const workspace = await realpath(authority.session.workspacePath);
@@ -228,7 +266,7 @@ export class CodexPlaywright {
228
266
  validArgs) {
229
267
  guidance = await beforeDeadline(readFile(skill.path, 'utf8'), input.deadline);
230
268
  if (guidance.length <= 16_384) {
231
- const readiness = await beforeDeadline(this.installation.ready(manager, binding.workspace, input.deadline, options), input.deadline);
269
+ const readiness = await beforeDeadline(this.readiness(authority.session, manager, binding.workspace, input.deadline, options), input.deadline);
232
270
  enabled = readiness.ready;
233
271
  binding.packageStatus =
234
272
  readiness.package === 'unknown' ? 'installed' : readiness.package;
@@ -291,7 +329,7 @@ export class CodexPlaywright {
291
329
  ...reserved,
292
330
  ...disabled,
293
331
  enabled: true,
294
- env_vars: ['GESTALT_HOME'],
332
+ env_vars: ['GESTALT_HOME', ...sessionScratchEnvironmentKeys],
295
333
  startup_readiness: 'connection',
296
334
  startup_timeout_ms: Math.max(1, input.deadline - Date.now()),
297
335
  }
@@ -6,6 +6,8 @@
6
6
  import { spawn } from 'node:child_process';
7
7
  import { JsonRpcClient } from './json-rpc-client.js';
8
8
  import { profileAppServerCommand } from '../catalog/profile-command.js';
9
+ import { withoutSessionScratch } from '../scratch/child-environment.js';
10
+ import { stopOwnedProcessGroup } from '../scratch/owned-process-group.js';
9
11
  export function launchCodexAppServer(input) {
10
12
  const launch = profileAppServerCommand();
11
13
  const child = spawn(launch.command, launch.args, {
@@ -13,14 +15,19 @@ export function launchCodexAppServer(input) {
13
15
  env: codexChildEnvironment(input.environment),
14
16
  shell: false,
15
17
  stdio: 'pipe',
18
+ detached: true,
16
19
  });
17
20
  const rpc = new JsonRpcClient(child.stdout, child.stdin);
21
+ const exited = new Promise((resolve) => {
22
+ child.once('exit', () => resolve());
23
+ });
18
24
  child.once('error', (error) => rpc.fail(error));
19
25
  child.stdin.on('error', (error) => rpc.fail(error));
20
26
  // App-server diagnostics are not protocol output. Drain them without retaining
21
27
  // potentially sensitive contents or letting a full stderr pipe block shutdown.
22
28
  child.stderr.resume();
23
29
  let closing = false;
30
+ let confirmation;
24
31
  let shutdownTimer;
25
32
  child.once('exit', () => {
26
33
  clearTimeout(shutdownTimer);
@@ -28,7 +35,7 @@ export function launchCodexAppServer(input) {
28
35
  });
29
36
  // close follows stdout drainage; exit alone can precede a final RPC response.
30
37
  child.once('close', () => rpc.fail(new Error('CODEX_APP_SERVER_EXITED')));
31
- return {
38
+ const result = {
32
39
  child,
33
40
  rpc,
34
41
  close: () => {
@@ -47,15 +54,30 @@ export function launchCodexAppServer(input) {
47
54
  }, 3_000);
48
55
  shutdownTimer.unref();
49
56
  },
57
+ closeAndWait: () => {
58
+ if (confirmation)
59
+ return confirmation;
60
+ result.close();
61
+ confirmation = (async () => {
62
+ if (!(await stopOwnedProcessGroup(child, 4000, 2000)))
63
+ throw new Error('SESSION_RELEASE_UNCONFIRMED');
64
+ await exited;
65
+ })().catch((error) => {
66
+ confirmation = undefined;
67
+ throw error;
68
+ });
69
+ return confirmation;
70
+ },
50
71
  onExit: (listener) => {
51
72
  child.once('exit', listener);
52
73
  return () => child.off('exit', listener);
53
74
  },
54
75
  };
76
+ return result;
55
77
  }
56
78
  /** Prevents a relay's own ambient status path from reaching discovery-only children. */
57
79
  export function codexChildEnvironment(environment, launchEnvironment = process.env) {
58
- const inherited = { ...launchEnvironment };
80
+ const inherited = withoutSessionScratch(launchEnvironment);
59
81
  delete inherited.GESTALT_MOBILE_ORG_PLAN_CAPABILITIES;
60
82
  delete inherited.GESTALT_MOBILE_ORG_PLAN_STATUS_FILE;
61
83
  delete inherited.GESTALT_MOBILE_ORG_PLAN_STATUS_DIRECTORY;
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { readFile } from 'node:fs/promises';
7
+ import { sessionScratchEnvironmentKeys } from '../scratch/child-environment.js';
7
8
  import { beforeDeadline, } from '../retrieval/codex-xerj.js';
8
9
  import { ManagedSerena, serenaTools } from './managed-serena.js';
9
10
  import { ReadinessEvidence } from '../retrieval/readiness-evidence.js';
@@ -122,7 +123,7 @@ export class CodexSerena {
122
123
  command: install.manager,
123
124
  args: ['serena', 'mcp', '--cwd', input.cwd],
124
125
  cwd: input.cwd,
125
- env_vars: ['CODEX_HOME', 'GESTALT_HOME'],
126
+ env_vars: ['CODEX_HOME', 'GESTALT_HOME', ...sessionScratchEnvironmentKeys],
126
127
  enabled: true,
127
128
  required: false,
128
129
  startup_readiness: 'connection',
@@ -8,6 +8,8 @@ import { access, readFile, realpath, stat } from 'node:fs/promises';
8
8
  import { homedir } from 'node:os';
9
9
  import { basename, dirname, isAbsolute, join } from 'node:path';
10
10
  import { spawn } from 'node:child_process';
11
+ import { withoutSessionScratch } from '../scratch/child-environment.js';
12
+ import { stopOwnedProcessGroup } from '../scratch/owned-process-group.js';
11
13
  export const playwrightServerName = 'gestalt-playwright';
12
14
  export const playwrightTools = [
13
15
  'browser_navigate',
@@ -74,13 +76,15 @@ export class ManagedPlaywright {
74
76
  }
75
77
  }
76
78
  /** Doctor performs no repair, installation or browser launch. Output never escapes this adapter. */
77
- async ready(manager, cwd, deadline, options = []) {
79
+ async ready(manager, cwd, deadline, options = [], scratchEnvironment) {
78
80
  if (Date.now() >= deadline)
79
81
  return unknownReadiness();
80
- const env = Object.fromEntries(['PATH', 'HOME', 'TMPDIR', 'GESTALT_HOME']
81
- .filter((key) => this.environment[key] !== undefined)
82
- .map((key) => [key, this.environment[key]]));
83
- return new Promise((resolve) => {
82
+ const independent = withoutSessionScratch(this.environment);
83
+ const env = Object.fromEntries(['PATH', 'HOME', 'GESTALT_HOME', 'TMPDIR', 'TMP', 'TEMP']
84
+ .filter((key) => independent[key] !== undefined)
85
+ .map((key) => [key, independent[key]]));
86
+ Object.assign(env, scratchEnvironment);
87
+ return new Promise((resolve, reject) => {
84
88
  const child = spawn(manager, ['playwright', 'doctor', '--json', '--cwd', cwd, ...options], {
85
89
  cwd,
86
90
  env,
@@ -90,7 +94,7 @@ export class ManagedPlaywright {
90
94
  });
91
95
  let output = '', overflow = false;
92
96
  const kill = () => {
93
- if (child.pid)
97
+ if (child.pid && child.exitCode === null && child.signalCode === null)
94
98
  try {
95
99
  process.kill(-child.pid, 'SIGKILL');
96
100
  }
@@ -109,41 +113,49 @@ export class ManagedPlaywright {
109
113
  });
110
114
  child.once('error', () => {
111
115
  clearTimeout(timer);
112
- resolve(unknownReadiness());
116
+ if (!child.pid)
117
+ resolve(unknownReadiness());
118
+ else {
119
+ overflow = true;
120
+ kill();
121
+ }
113
122
  });
114
123
  child.once('close', (code) => {
115
124
  clearTimeout(timer);
116
- kill();
117
- try {
118
- const value = JSON.parse(output);
119
- if (overflow || value.schemaVersion !== 1 || value.contractVersion !== 1) {
125
+ void (async () => {
126
+ if (!(await stopOwnedProcessGroup(child, 0, 1000)))
127
+ throw new Error('SESSION_RELEASE_UNCONFIRMED');
128
+ try {
129
+ const value = JSON.parse(output);
130
+ if (overflow || value.schemaVersion !== 1 || value.contractVersion !== 1) {
131
+ resolve(unknownReadiness());
132
+ return;
133
+ }
134
+ const status = (ready) => ready === true
135
+ ? 'ready'
136
+ : ready === false
137
+ ? 'unavailable'
138
+ : 'unknown';
139
+ resolve({
140
+ ready: code === 0 &&
141
+ value.ready === true &&
142
+ value.package?.ready === true &&
143
+ value.chrome?.ready === true &&
144
+ value.node?.ready === true,
145
+ package: status(value.package?.ready),
146
+ chrome: status(value.chrome?.ready),
147
+ node: status(value.node?.ready),
148
+ chromeVersion: typeof value.chrome?.version === 'string' &&
149
+ value.chrome.version.length <= 64 &&
150
+ /^\d+(?:\.\d+){1,3}$/.test(value.chrome.version)
151
+ ? value.chrome.version
152
+ : null,
153
+ });
154
+ }
155
+ catch {
120
156
  resolve(unknownReadiness());
121
- return;
122
157
  }
123
- const status = (ready) => ready === true
124
- ? 'ready'
125
- : ready === false
126
- ? 'unavailable'
127
- : 'unknown';
128
- resolve({
129
- ready: code === 0 &&
130
- value.ready === true &&
131
- value.package?.ready === true &&
132
- value.chrome?.ready === true &&
133
- value.node?.ready === true,
134
- package: status(value.package?.ready),
135
- chrome: status(value.chrome?.ready),
136
- node: status(value.node?.ready),
137
- chromeVersion: typeof value.chrome?.version === 'string' &&
138
- value.chrome.version.length <= 64 &&
139
- /^\d+(?:\.\d+){1,3}$/.test(value.chrome.version)
140
- ? value.chrome.version
141
- : null,
142
- });
143
- }
144
- catch {
145
- resolve(unknownReadiness());
146
- }
158
+ })().catch(reject);
147
159
  });
148
160
  });
149
161
  }