gestalt-mobile 0.47.0 → 0.48.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 (27) hide show
  1. package/README.md +47 -2
  2. package/dist/client/assets/index-CE4-9CY1.css +1 -0
  3. package/dist/client/assets/index-DvIxykMj.js +112 -0
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/server/cli.js +15 -0
  6. package/dist/server/server/composition.contracts.js +9 -3
  7. package/dist/server/server/composition.js +37 -18
  8. package/dist/server/server/config.js +5 -0
  9. package/dist/server/server/features/catalog/get-bootstrap/use-case.js +1 -0
  10. package/dist/server/server/features/catalog/get-xerj-status/endpoint.js +11 -0
  11. package/dist/server/server/features/catalog/register-routes.js +3 -0
  12. package/dist/server/server/features/sessions/model/relay-session.js +1 -0
  13. package/dist/server/server/features/skills/model/skill-profile.js +4 -2
  14. package/dist/server/server/platform/codex/codex-capabilities.js +96 -0
  15. package/dist/server/server/platform/codex/codex-serena.js +159 -0
  16. package/dist/server/server/platform/codex/managed-serena.js +69 -0
  17. package/dist/server/server/platform/codex/normalizer.js +19 -0
  18. package/dist/server/server/platform/codex/session-runtime.js +52 -3
  19. package/dist/server/server/platform/retrieval/codex-xerj.js +2 -1
  20. package/dist/server/server/platform/retrieval/managed-xerj.js +2 -1
  21. package/dist/server/server/platform/retrieval/xerj-index-config.js +67 -0
  22. package/dist/server/server/platform/retrieval/xerj-indexer.js +256 -0
  23. package/dist/server/server/platform/skills/codex-skill-catalog.js +12 -4
  24. package/dist/server/shared/contracts/xerj-status.js +6 -0
  25. package/package.json +1 -1
  26. package/dist/client/assets/index-CGCxdtE6.js +0 -112
  27. package/dist/client/assets/index-s4qgQfcy.css +0 -1
@@ -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-CGCxdtE6.js"></script>
20
- <link rel="stylesheet" crossorigin href="/assets/index-s4qgQfcy.css">
19
+ <script type="module" crossorigin src="/assets/index-DvIxykMj.js"></script>
20
+ <link rel="stylesheet" crossorigin href="/assets/index-CE4-9CY1.css">
21
21
  </head>
22
22
  <body>
23
23
  <div id="app"></div>
@@ -29,6 +29,7 @@ Options:
29
29
  --disable-passkey-auth Disable passkey access control (unsafe on shared or network hosts)
30
30
  --data-dir <path> Directory for persistent application data
31
31
  --icon <path> SVG or PNG used as the installed PWA application icon
32
+ --xerj <mode> Source discovery: manual (default, no indexing), auto, off
32
33
  --skills <profile> Use a global skill profile for every session
33
34
  --skills list List saved global skill profiles without starting the server
34
35
  --help Show this help
@@ -36,6 +37,9 @@ Options:
36
37
  function managedVersion(value) {
37
38
  return value && /^[A-Za-z0-9][A-Za-z0-9.+_-]{0,99}$/.test(value) ? value : null;
38
39
  }
40
+ function semanticVersion(value) {
41
+ return value && /^\d+\.\d+\.\d+$/.test(value) ? value : null;
42
+ }
39
43
  export function componentVersions(mobileVersion, codexVersion, environment = process.env) {
40
44
  return [
41
45
  {
@@ -55,6 +59,16 @@ export function componentVersions(mobileVersion, codexVersion, environment = pro
55
59
  version: managedVersion(environment.GESTALT_CONTEXT_MODE_VERSION),
56
60
  },
57
61
  { id: 'codex', label: 'Codex CLI', version: codexVersion },
62
+ { id: 'xerj', label: 'xerj', version: managedVersion(environment.GESTALT_XERJ_VERSION) },
63
+ { id: 'serena', label: 'Serena', version: semanticVersion(environment.GESTALT_SERENA_VERSION) },
64
+ { id: 'uv', label: 'uv', version: semanticVersion(environment.GESTALT_UV_VERSION) },
65
+ {
66
+ id: 'serena-python',
67
+ label: 'Serena Python',
68
+ version: /^3\.13\.\d+$/.test(environment.GESTALT_SERENA_PYTHON_VERSION ?? '')
69
+ ? environment.GESTALT_SERENA_PYTHON_VERSION
70
+ : null,
71
+ },
58
72
  ];
59
73
  }
60
74
  export async function runStartupDoctor(cwd) {
@@ -272,6 +286,7 @@ export async function runCli(dependencies = {}) {
272
286
  const mobileVersion = await packageVersion(moduleUrl);
273
287
  const app = await (dependencies.compose ?? composeRelayApp)({
274
288
  root: config.root,
289
+ xerj: config.xerj,
275
290
  dataDir: config.dataDir,
276
291
  relyingParty: config.relyingParty,
277
292
  passkeyAuthEnabled: config.passkeyAuthEnabled,
@@ -3259,9 +3259,13 @@ describe('production composition', () => {
3259
3259
  ],
3260
3260
  });
3261
3261
  await expect.poll(() => handles.length).toBeGreaterThan(handlesBeforeRecovery);
3262
- const replacement = handles.find((candidate) => candidate !== first &&
3263
- candidate.requests.some((request) => request.method === 'thread/resume'));
3264
- expect(replacement?.requests).toContainEqual({
3262
+ // Launching the replacement precedes its asynchronous thread resume.
3263
+ // Wait for the recovery operation, not merely the new process handle.
3264
+ await expect
3265
+ .poll(() => handles
3266
+ .filter((candidate) => candidate !== first)
3267
+ .flatMap((candidate) => candidate.requests))
3268
+ .toContainEqual({
3265
3269
  method: 'thread/resume',
3266
3270
  params: expect.objectContaining({ threadId, cwd: join(root, 'workspace') }),
3267
3271
  });
@@ -3613,6 +3617,8 @@ describe('production composition', () => {
3613
3617
  ['DELETE', '/api/auth/devices/:deviceId', '/api/auth/devices/device-1', 'protected'],
3614
3618
  ['GET', '/api/bootstrap', '/api/bootstrap', 'protected'],
3615
3619
  ['HEAD', '/api/bootstrap', '/api/bootstrap', 'protected'],
3620
+ ['GET', '/api/xerj', '/api/xerj', 'protected'],
3621
+ ['HEAD', '/api/xerj', '/api/xerj', 'protected'],
3616
3622
  ['GET', '/api/session-defaults', '/api/session-defaults', 'protected'],
3617
3623
  ['HEAD', '/api/session-defaults', '/api/session-defaults', 'protected'],
3618
3624
  ['PUT', '/api/session-defaults', '/api/session-defaults', 'protected'],
@@ -60,8 +60,12 @@ import { promoteRecentThread } from './features/sessions/promote-recent-thread/u
60
60
  import { FilesystemSkillProfileStore } from './platform/skills/filesystem-skill-profile-store.js';
61
61
  import { CodexSkillCatalog } from './platform/skills/codex-skill-catalog.js';
62
62
  import { CachedSkillCatalog } from './platform/skills/cached-skill-catalog.js';
63
+ import { XerjIndexer } from './platform/retrieval/xerj-indexer.js';
63
64
  import { ManagedXerj, xerjDeadline } from './platform/retrieval/managed-xerj.js';
64
65
  import { CodexXerj } from './platform/retrieval/codex-xerj.js';
66
+ import { CodexSerena } from './platform/codex/codex-serena.js';
67
+ import { ManagedSerena } from './platform/codex/managed-serena.js';
68
+ import { CodexCapabilities } from './platform/codex/codex-capabilities.js';
65
69
  import { compileSkillOverride } from './features/skills/model/skill-profile.js';
66
70
  import { SupervisedPlanRegistry } from './features/plans/application/supervised-plan-registry.js';
67
71
  import { FilesystemPlanStatusSource } from './platform/plans/filesystem-plan-status-source.js';
@@ -414,28 +418,36 @@ export async function composeRelayApp(options) {
414
418
  // kimi discovery is workspace-scoped, not profile-scoped: the profile only
415
419
  // decides which discovered skills a session's server materializes.
416
420
  const kimiSkillCatalog = new KimiSkillCatalog(kimiManager ?? null, kimiManager != null);
417
- const retrievalCapability = options.retrievalCapability ?? new ManagedXerj();
421
+ const retrievalCapability = options.xerj === 'off'
422
+ ? { check: async () => ({ status: 'absent' }) }
423
+ : (options.retrievalCapability ?? new ManagedXerj());
424
+ const xerjIndexer = new XerjIndexer(root, options.xerj ?? 'manual', retrievalCapability);
418
425
  const xerj = new CodexXerj(retrievalCapability);
426
+ const serenaInstallation = new ManagedSerena();
427
+ const capabilities = new CodexCapabilities(xerj, new CodexSerena(serenaInstallation));
419
428
  const skillCatalog = (provider, profile) => provider === 'kimi'
420
429
  ? kimiSkillCatalog
421
430
  : new CodexSkillCatalog(profile, options.launchAppServer ?? launchCodexAppServer);
422
431
  const editorSkillCatalog = new CachedSkillCatalog((provider, profile, workspace) => provider === 'codex'
423
- ? new CodexSkillCatalog(profile, options.launchAppServer ?? launchCodexAppServer, 5_000, xerj).list(workspace)
432
+ ? new CodexSkillCatalog(profile, options.launchAppServer ?? launchCodexAppServer, 5_000, capabilities).list(workspace)
424
433
  : kimiSkillCatalog.list(workspace), async (provider, _profile, workspace, result) => {
425
- if (provider !== 'codex' ||
426
- !result.skills.some((skill) => skill.name === 'gestalt:xerj' && skill.enabled))
434
+ if (provider !== 'codex')
427
435
  return result;
428
- const current = await retrievalCapability.check({
429
- cwd: workspace,
430
- deadline: xerjDeadline(),
431
- start: false,
432
- });
433
- return current.status === 'ready'
434
- ? result
435
- : {
436
- ...result,
437
- skills: result.skills.map((skill) => skill.name === 'gestalt:xerj' ? { ...skill, enabled: false } : skill),
438
- };
436
+ const [xerjStatus, serenaStatus] = await Promise.all([
437
+ result.skills.some((skill) => skill.name === 'gestalt:xerj' && skill.enabled)
438
+ ? retrievalCapability.check({ cwd: workspace, deadline: xerjDeadline(), start: false })
439
+ : undefined,
440
+ result.skills.some((skill) => skill.name === 'gestalt:serena' && skill.enabled)
441
+ ? serenaInstallation.check()
442
+ : undefined,
443
+ ]);
444
+ return {
445
+ ...result,
446
+ skills: result.skills.map((skill) => (skill.name === 'gestalt:xerj' && xerjStatus && xerjStatus.status !== 'ready') ||
447
+ (skill.name === 'gestalt:serena' && serenaStatus && serenaStatus.status !== 'installed')
448
+ ? { ...skill, enabled: false }
449
+ : skill),
450
+ };
439
451
  });
440
452
  const workspacePlanCatalog = new FilesystemWorkspacePlanCatalog();
441
453
  const planArchiver = new FilesystemPlanArchiver();
@@ -993,10 +1005,13 @@ export async function composeRelayApp(options) {
993
1005
  const project = await skillProfiles.readWorkspaceDefault(session.workspacePath);
994
1006
  const selected = compileSkillOverride({
995
1007
  discovered: catalog.skills,
996
- explicit: session.effectiveSkillSelection?.skills ?? options.explicitSkillProfile?.skills,
1008
+ explicit: session.effectiveSkillSelection?.skills.map((skill) => skill.name === 'gestalt:serena' &&
1009
+ session.effectiveSkillSelection?.serenaSelected !== undefined
1010
+ ? { ...skill, enabled: session.effectiveSkillSelection.serenaSelected }
1011
+ : skill) ?? options.explicitSkillProfile?.skills,
997
1012
  project: project?.skills,
998
1013
  });
999
- return xerj.prepare({
1014
+ return capabilities.prepare({
1000
1015
  cwd: session.workspacePath,
1001
1016
  rpc,
1002
1017
  config,
@@ -1006,7 +1021,7 @@ export async function composeRelayApp(options) {
1006
1021
  start: true,
1007
1022
  });
1008
1023
  },
1009
- verify: (rpc, threadId, state) => xerj.verify(rpc, threadId, state),
1024
+ verify: (rpc, threadId, state) => capabilities.verify(rpc, threadId, state),
1010
1025
  })
1011
1026
  : null;
1012
1027
  const handleKimiNotification = (sessionId, event) => {
@@ -1260,6 +1275,7 @@ export async function composeRelayApp(options) {
1260
1275
  recentThreads: recentThreadsForRelay,
1261
1276
  sessionDefaults,
1262
1277
  bootstrap: {
1278
+ xerj: () => xerjIndexer.status(),
1263
1279
  sessionDefaults,
1264
1280
  workspaces,
1265
1281
  profiles: options.profiles,
@@ -1836,6 +1852,8 @@ export async function composeRelayApp(options) {
1836
1852
  });
1837
1853
  };
1838
1854
  app.addHook('onListen', async () => {
1855
+ if (options.xerj)
1856
+ xerjIndexer.start();
1839
1857
  const profile = (await options.profiles.list()).find((item) => item.state === 'ok')?.name;
1840
1858
  if (profile)
1841
1859
  await editorSkillCatalog.refresh('codex', profile, root);
@@ -1864,6 +1882,7 @@ export async function composeRelayApp(options) {
1864
1882
  });
1865
1883
  app.addHook('onClose', async () => {
1866
1884
  closing = true;
1885
+ await xerjIndexer.close();
1867
1886
  for (const [sessionId, timer] of capacityRecoveryTimers) {
1868
1887
  clearTimeout(timer);
1869
1888
  capacityRecoveries.delete(sessionId);
@@ -16,6 +16,7 @@ const optionNames = new Set([
16
16
  '--public-origin',
17
17
  '--skills',
18
18
  '--icon',
19
+ '--xerj',
19
20
  ]);
20
21
  const flagNames = new Set(['--disable-passkey-auth']);
21
22
  export function parseConfig(args, cwd = process.cwd()) {
@@ -41,6 +42,9 @@ export function parseConfig(args, cwd = process.cwd()) {
41
42
  values.set(option, value);
42
43
  index += 1;
43
44
  }
45
+ const xerj = values.get('--xerj') ?? 'manual';
46
+ if (xerj !== 'auto' && xerj !== 'manual' && xerj !== 'off')
47
+ throw new CliUsageError('--xerj must be auto, manual, or off');
44
48
  const portValue = values.get('--port') ?? '3000';
45
49
  const port = Number(portValue);
46
50
  if (!Number.isInteger(port) || port < 1 || port > 65535)
@@ -53,6 +57,7 @@ export function parseConfig(args, cwd = process.cwd()) {
53
57
  return {
54
58
  host,
55
59
  port,
60
+ xerj,
56
61
  passkeyAuthEnabled,
57
62
  relyingParty: createRelyingPartyConfig(publicOrigin),
58
63
  root: resolve(cwd, values.get('--cwd') ?? '.'),
@@ -22,6 +22,7 @@ export async function getBootstrap(deps) {
22
22
  }
23
23
  return {
24
24
  ...(deps.sessionDefaults ? { sessionDefaults, sessionDefaultsError } : {}),
25
+ ...(deps.xerj ? { xerj: deps.xerj() } : {}),
25
26
  workspaces,
26
27
  profiles,
27
28
  models: { codex: codexModels, kimi: kimiModels },
@@ -0,0 +1,11 @@
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 registerXerjStatus(app, status) {
7
+ app.get('/api/xerj', async (_request, reply) => {
8
+ reply.header('Cache-Control', 'no-store');
9
+ return status();
10
+ });
11
+ }
@@ -3,11 +3,14 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
+ import { registerXerjStatus } from './get-xerj-status/endpoint.js';
6
7
  import { registerGetBootstrap } from './get-bootstrap/endpoint.js';
7
8
  import { registerSessionDefaults } from './session-defaults/endpoint.js';
8
9
  export function registerCatalogRoutes(app, deps) {
9
10
  if (deps.bootstrap)
10
11
  registerGetBootstrap(app, deps.bootstrap);
12
+ if (deps.bootstrap?.xerj)
13
+ registerXerjStatus(app, deps.bootstrap.xerj);
11
14
  if (deps.sessionDefaults)
12
15
  registerSessionDefaults(app, deps.sessionDefaults);
13
16
  }
@@ -40,6 +40,7 @@ export function createEffectiveSkillSelection(input) {
40
40
  ...(input.selectedProfileName === undefined
41
41
  ? {}
42
42
  : { selectedProfileName: normalizeSkillProfileName(input.selectedProfileName) }),
43
+ ...(typeof input.serenaSelected === 'boolean' ? { serenaSelected: input.serenaSelected } : {}),
43
44
  skills: createSkillSelection(input.skills),
44
45
  ...(warnings.length > 0 ? { warnings: warnings.slice(0, 50) } : {}),
45
46
  };
@@ -56,7 +56,9 @@ export const availableSkillSchema = z
56
56
  .strict();
57
57
  /** Gestalt workflow skills are session infrastructure, not optional profile entries. */
58
58
  export function isAlwaysAdvertisedSkill(skill) {
59
- return isGestaltSkillName(skill.name) && (skill.name !== 'gestalt:xerj' || skill.enabled);
59
+ return (skill.name !== 'gestalt:serena' &&
60
+ isGestaltSkillName(skill.name) &&
61
+ (skill.name !== 'gestalt:xerj' || skill.enabled));
60
62
  }
61
63
  export function isGestaltSkillName(name) {
62
64
  return name.startsWith('gestalt:');
@@ -219,7 +221,7 @@ export function createSkillProfile(input) {
219
221
  // Gestalt skills are mandatory thread infrastructure. Legacy profiles are
220
222
  // normalized on read so they cannot pin a stale plugin-cache version or
221
223
  // expose a meaningless enable/disable control in the editor.
222
- skills: createSkillSelection(input.skills.filter((skill) => !isGestaltSkillName(skill.name))),
224
+ skills: createSkillSelection(input.skills.filter((skill) => skill.name === 'gestalt:serena' || !isGestaltSkillName(skill.name))),
223
225
  };
224
226
  }
225
227
  /** Parse the version-1 YAML document without performing filesystem access. */
@@ -0,0 +1,96 @@
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 { CodexXerj } from '../retrieval/codex-xerj.js';
7
+ import { CodexSerena } from './codex-serena.js';
8
+ /** The two managed capabilities share lifecycle, but never share availability or approvals. */
9
+ export class CodexCapabilities {
10
+ xerj;
11
+ serena;
12
+ states = new WeakMap();
13
+ constructor(xerj, serena) {
14
+ this.xerj = xerj;
15
+ this.serena = serena;
16
+ }
17
+ async prepare(input) {
18
+ // Connection verification is a separate bounded phase for Serena. A slow
19
+ // optional XERJ probe must not spend Serena's entire connection allowance.
20
+ const serenaVerificationMs = Math.max(1, Math.min(5_000, input.deadline - Date.now()));
21
+ const [xerj, serena] = await Promise.all([
22
+ this.xerj.prepare(input),
23
+ this.serena.prepare(input),
24
+ ]);
25
+ if (serena.ready)
26
+ serena.deadline = Date.now() + serenaVerificationMs;
27
+ const serenaPath = input.skills.find((skill) => skill.name === 'gestalt:serena')?.path;
28
+ const state = {
29
+ deadline: Math.max(input.deadline, serena.ready ? serena.deadline : input.deadline),
30
+ get ready() {
31
+ return xerj.ready || serena.ready;
32
+ },
33
+ get capabilities() {
34
+ return [
35
+ {
36
+ skillName: 'gestalt:xerj',
37
+ serverName: 'gestalt-xerj',
38
+ ready: xerj.ready,
39
+ diagnostic: xerj.diagnostic,
40
+ },
41
+ {
42
+ skillName: 'gestalt:serena',
43
+ serverName: 'gestalt-serena',
44
+ ready: serena.ready,
45
+ diagnostic: serena.diagnostic,
46
+ },
47
+ ];
48
+ },
49
+ get skillsConfig() {
50
+ return xerj.skillsConfig.map((entry) => entry.path === serenaPath
51
+ ? (serena.skillsConfig.find((candidate) => candidate.path === serenaPath) ?? entry)
52
+ : entry);
53
+ },
54
+ get config() {
55
+ const xerjInstructions = String(xerj.config.developer_instructions ?? '');
56
+ const serenaInstructions = String(serena.config.developer_instructions ?? '');
57
+ return {
58
+ ...input.config,
59
+ mcp_servers: {
60
+ ...xerj.config.mcp_servers,
61
+ ...serena.config.mcp_servers,
62
+ },
63
+ skills: {
64
+ config: [
65
+ ...(xerj.config.skills?.config ?? []),
66
+ ...(serena.config.skills?.config ?? []),
67
+ ],
68
+ },
69
+ developer_instructions: `${xerjInstructions}\n${serenaInstructions.slice(serenaInstructions.indexOf('<gestalt_serena_'))}`,
70
+ };
71
+ },
72
+ // verify already disables only the failed connection; runtime rebinds the composed config.
73
+ fallback() { },
74
+ };
75
+ this.states.set(state, { xerj, serena });
76
+ return state;
77
+ }
78
+ async verify(rpc, threadId, state) {
79
+ const pair = this.states.get(state);
80
+ if (!pair)
81
+ return false;
82
+ const [xerj, serena] = await Promise.all([
83
+ pair.xerj.ready ? this.xerj.verify(rpc, threadId, pair.xerj) : true,
84
+ pair.serena.ready ? this.serena.verify(rpc, threadId, pair.serena) : true,
85
+ ]);
86
+ if (!xerj) {
87
+ pair.xerj.fallback();
88
+ pair.xerj.diagnostic = 'connection-unavailable';
89
+ }
90
+ if (!serena) {
91
+ pair.serena.fallback();
92
+ pair.serena.diagnostic = 'connection-unavailable';
93
+ }
94
+ return xerj && serena;
95
+ }
96
+ }
@@ -0,0 +1,159 @@
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 { readFile } from 'node:fs/promises';
7
+ import { beforeDeadline, } from '../retrieval/codex-xerj.js';
8
+ import { ManagedSerena, serenaTools } from './managed-serena.js';
9
+ export const serenaServerName = 'gestalt-serena';
10
+ // config/read includes unset defaults as null. Thread overrides cannot encode
11
+ // those as TOML values; retain explicit settings, including tool approvals.
12
+ function omitUnsetConfig(value) {
13
+ if (Array.isArray(value))
14
+ return value.map(omitUnsetConfig);
15
+ if (value !== null && typeof value === 'object')
16
+ return Object.fromEntries(Object.entries(value)
17
+ .filter(([, entry]) => entry !== null && entry !== undefined)
18
+ .map(([key, entry]) => [key, omitUnsetConfig(entry)]));
19
+ return value;
20
+ }
21
+ /** Connection availability only. Native model calls establish effective sandbox authority. */
22
+ export class CodexSerena {
23
+ installation;
24
+ constructor(installation = new ManagedSerena()) {
25
+ this.installation = installation;
26
+ }
27
+ async prepare(input) {
28
+ const skill = input.skills.find((entry) => entry.name === 'gestalt:serena');
29
+ let native = {};
30
+ let compatible = false;
31
+ try {
32
+ const read = (await beforeDeadline(input.rpc.request('config/read', { includeLayers: false }), input.deadline));
33
+ native = read.config ?? {};
34
+ compatible = read.config !== undefined;
35
+ }
36
+ catch {
37
+ /* Fail closed on an incompatible runtime. */
38
+ }
39
+ const servers = omitUnsetConfig(native.mcp_servers ?? {});
40
+ const reserved = servers[serenaServerName] ?? {};
41
+ const mcp = {};
42
+ for (const [name, server] of Object.entries(servers)) {
43
+ const args = server?.args;
44
+ if (args?.[0] === 'serena' && args[1] === 'mcp')
45
+ mcp[name] = { ...server, enabled: false, required: false };
46
+ }
47
+ const instructions = typeof native.developer_instructions === 'string' ? native.developer_instructions : '';
48
+ const state = {
49
+ ready: false,
50
+ deadline: input.deadline,
51
+ config: {},
52
+ skillsConfig: input.skillsConfig,
53
+ fallback: () => {
54
+ state.ready = false;
55
+ state.skillsConfig = input.skillsConfig.map((entry) => ({
56
+ ...entry,
57
+ enabled: entry.path === skill?.path ? false : entry.enabled,
58
+ }));
59
+ state.config = {
60
+ ...input.config,
61
+ skills: { config: [{ name: 'gestalt:serena', enabled: false }] },
62
+ mcp_servers: {
63
+ ...mcp,
64
+ // Disabled entries still require a transport in Codex. Keep this
65
+ // override on resume so a previous thread connection stays disabled.
66
+ [serenaServerName]: {
67
+ ...reserved,
68
+ ...(reserved.command || reserved.url
69
+ ? {}
70
+ : { command: 'gestalt', args: ['serena', 'mcp', '--cwd', input.cwd] }),
71
+ enabled: false,
72
+ required: false,
73
+ },
74
+ },
75
+ developer_instructions: `${instructions}\n<gestalt_serena_unavailable>\nSerena is unavailable in this runtime. Earlier Serena guidance is inactive; use native code tools.\n</gestalt_serena_unavailable>`,
76
+ };
77
+ },
78
+ };
79
+ state.fallback();
80
+ const rules = native.skills;
81
+ const selected = input.skillsConfig.find((entry) => entry.path === skill?.path);
82
+ const conflict = reserved.enabled === false ||
83
+ (reserved.env && Object.keys(reserved.env).length) ||
84
+ reserved.enabled_tools ||
85
+ reserved.disabled_tools?.length ||
86
+ Object.values((reserved.tools ?? {})).some((tool) => tool.enabled !== undefined);
87
+ if (!compatible ||
88
+ !skill ||
89
+ !selected?.enabled ||
90
+ rules?.include_instructions === false ||
91
+ native.features?.hooks !== true ||
92
+ rules?.config?.filter((rule) => rule.name === skill.name || rule.path === skill.path).at(-1)
93
+ ?.enabled === false ||
94
+ conflict ||
95
+ Date.now() >= input.deadline)
96
+ return state;
97
+ try {
98
+ const install = await beforeDeadline(this.installation.check(), input.deadline);
99
+ if (install.status !== 'installed') {
100
+ state.diagnostic = 'installation-unavailable';
101
+ return state;
102
+ }
103
+ const guidance = await beforeDeadline(readFile(skill.path, 'utf8'), input.deadline);
104
+ if (guidance.length > 16_384)
105
+ return state;
106
+ state.config = {
107
+ ...input.config,
108
+ skills: { config: [{ name: 'gestalt:serena', enabled: true }] },
109
+ mcp_servers: {
110
+ ...mcp,
111
+ [serenaServerName]: {
112
+ ...reserved,
113
+ command: install.manager,
114
+ args: ['serena', 'mcp', '--cwd', input.cwd],
115
+ cwd: input.cwd,
116
+ env_vars: ['CODEX_HOME', 'GESTALT_HOME'],
117
+ enabled: true,
118
+ required: false,
119
+ startup_readiness: 'connection',
120
+ startup_timeout_ms: Math.max(1, input.deadline - Date.now()),
121
+ },
122
+ },
123
+ developer_instructions: `${instructions}\n<gestalt_serena_capability>\nSerena is bound to this workspace. Connection and listed tools do not prove language readiness. First call get_symbols_overview on a current project source file and verify success before semantic editing; on failure use native code tools. Native session and child permissions and approvals apply. Plan mode prohibits edits. Do not switch projects or modes.\n${guidance}\n</gestalt_serena_capability>`,
124
+ };
125
+ state.skillsConfig = input.skillsConfig;
126
+ state.ready = true;
127
+ }
128
+ catch {
129
+ state.fallback();
130
+ state.diagnostic = 'connection-unavailable';
131
+ }
132
+ return state;
133
+ }
134
+ async verify(rpc, threadId, state) {
135
+ if (!state.ready)
136
+ return false;
137
+ try {
138
+ while (Date.now() < state.deadline) {
139
+ const result = (await beforeDeadline(rpc.request('mcpServerStatus/list', {
140
+ threadId,
141
+ serverName: serenaServerName,
142
+ detail: 'full',
143
+ }), state.deadline));
144
+ const server = result.data?.find((entry) => entry.name === serenaServerName);
145
+ if (server?.runtimeStatus === 'connected' &&
146
+ !server.toolsError &&
147
+ serenaTools.every((tool) => Object.hasOwn(server.tools ?? {}, tool)))
148
+ return true;
149
+ if (server?.runtimeStatus !== 'starting')
150
+ return false;
151
+ await beforeDeadline(new Promise((resolve) => setTimeout(resolve, 25)), state.deadline);
152
+ }
153
+ }
154
+ catch {
155
+ /* Optional connection failure must not prevent a session. */
156
+ }
157
+ return false;
158
+ }
159
+ }
@@ -0,0 +1,69 @@
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 { constants } from 'node:fs';
7
+ import { access, readFile, stat } from 'node:fs/promises';
8
+ import { homedir } from 'node:os';
9
+ import { isAbsolute, join } from 'node:path';
10
+ export const serenaTools = [
11
+ 'get_symbols_overview',
12
+ 'find_symbol',
13
+ 'initial_instructions',
14
+ 'replace_symbol_body',
15
+ ];
16
+ /** Read shared executable metadata only; never prepare a project with operator authority. */
17
+ export class ManagedSerena {
18
+ environment;
19
+ constructor(environment = process.env) {
20
+ this.environment = environment;
21
+ }
22
+ async check() {
23
+ const home = this.environment.GESTALT_HOME ?? join(this.environment.HOME ?? homedir(), '.gestalt');
24
+ try {
25
+ const path = join(home, 'serena', 'active.json');
26
+ if ((await stat(path)).size > 262_144)
27
+ return { status: 'unavailable' };
28
+ const install = JSON.parse(await readFile(path, 'utf8'));
29
+ if (install.schemaVersion !== 1 ||
30
+ install.contractVersion !== 1 ||
31
+ !/^\d+\.\d+\.\d+$/.test(install.version) ||
32
+ !Array.isArray(install.tools) ||
33
+ !serenaTools.every((name) => install.tools.some((tool) => tool.name === name && tool.inputSchema?.type === 'object')))
34
+ return { status: 'unavailable' };
35
+ for (const executable of [install.executable, install.python, install.uv]) {
36
+ if (typeof executable !== 'string' || !isAbsolute(executable))
37
+ return { status: 'unavailable' };
38
+ await access(executable, constants.X_OK);
39
+ }
40
+ if (typeof install.pythonInstallDir !== 'string' ||
41
+ !isAbsolute(install.pythonInstallDir) ||
42
+ !(await stat(install.pythonInstallDir)).isDirectory())
43
+ return { status: 'unavailable' };
44
+ const candidates = this.environment.GESTALT_MANAGER_BIN
45
+ ? [this.environment.GESTALT_MANAGER_BIN]
46
+ : (this.environment.PATH ?? '')
47
+ .split(':')
48
+ .filter(Boolean)
49
+ .map((path) => join(path, 'gestalt'));
50
+ for (const manager of candidates) {
51
+ if (!isAbsolute(manager))
52
+ continue;
53
+ try {
54
+ await access(manager, constants.X_OK);
55
+ return { status: 'installed', manager, version: install.version };
56
+ }
57
+ catch {
58
+ /* Try the next established manager path. */
59
+ }
60
+ }
61
+ return { status: 'unavailable' };
62
+ }
63
+ catch (error) {
64
+ return {
65
+ status: error.code === 'ENOENT' ? 'absent' : 'unavailable',
66
+ };
67
+ }
68
+ }
69
+ }
@@ -23,6 +23,25 @@ export function normalizeCodexNotification(sessionId, sequence, occurredAt, noti
23
23
  },
24
24
  };
25
25
  }
26
+ if (notification.method === 'mcpServer/statusUpdated' &&
27
+ connection?.name === 'gestalt-serena' &&
28
+ ['connected', 'failed', 'cancelled'].includes(String(connection.status))) {
29
+ const connected = connection.status === 'connected';
30
+ return {
31
+ sessionId,
32
+ sequence,
33
+ occurredAt,
34
+ type: 'activity.updated',
35
+ payload: {
36
+ id: 'gestalt-serena-availability',
37
+ label: connected ? 'Serena connected' : 'Serena unavailable',
38
+ detail: connected
39
+ ? 'Connection verified. Before semantic editing, call get_symbols_overview on a current source file and verify success; language readiness is still unverified.'
40
+ : 'Serena is unavailable in this session. Use native code tools; connection availability will be checked when the runtime resumes. Operators can inspect installation with gestalt serena doctor.',
41
+ ...(activeTurnId ? { turnId: activeTurnId } : {}),
42
+ },
43
+ };
44
+ }
26
45
  const decoded = decodeNotification(notification);
27
46
  if (!decoded)
28
47
  return null;