gestalt-mobile 0.46.1 → 0.47.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/README.md CHANGED
@@ -123,11 +123,37 @@ configuration or skill files. Exact skill paths remain authoritative, while
123
123
  paths inside Codex's versioned plugin cache are rebound to the currently
124
124
  discovered plugin version when their marketplace, plugin, and skill-relative
125
125
  path still match. Skills named `$gestalt:*` are session infrastructure: Mobile
126
- always enables and advertises every freshly discovered one, including skills
126
+ always enables and advertises the fixed workflow skills, including skills
127
127
  added after a profile was saved. The editor labels them **Always advertised**
128
128
  and does not offer a disable control. Refresh discovery and start a new session
129
129
  after upgrading Gestalt Agents; running sessions retain their startup catalog.
130
130
 
131
+ `gestalt:xerj` is conditional retrieval infrastructure. For Codex, Mobile checks
132
+ the manager's shared readiness contract and the owning thread's native MCP
133
+ connection before accepting its first turn. Ready retrieval is mandatory even
134
+ when a saved profile excluded it; unavailable retrieval is excluded even when
135
+ a legacy selection enabled it. Fresh runtimes, resumes and process recovery
136
+ repeat the check. Native child agents inherit their parent's configuration and
137
+ open their own MCP connections. A connection failure appears in the existing
138
+ chat activity; use `rg` and current source reads until the next runtime check.
139
+ Instructions already delivered during a turn cannot be retroactively removed.
140
+
141
+ Managed launch provides `GESTALT_MANAGER_BIN`. Direct Mobile launch discovers
142
+ `gestalt` on `PATH`, or accepts an absolute executable path through that same
143
+ environment variable. Without a manager or installed xerj, chat starts normally.
144
+ `XERJ_READY_TIMEOUT_MS` bounds optional readiness, including discovery and the
145
+ actual connection, with a five-second default. Startup never installs xerj,
146
+ downloads models or indexes repositories. Install explicitly with
147
+ `gestalt xerj install`; inspect readiness with `gestalt xerj status`.
148
+
149
+ The manager owns one authenticated loopback backend shared by CLI and Mobile.
150
+ Closing either client closes only its native MCP proxies. Use
151
+ `gestalt xerj stop` for explicit managed shutdown; a later eligible runtime can
152
+ start the installed backend again. An empty index remains ready: index only
153
+ repositories you explicitly select, verify repository identity and freshness,
154
+ and confirm retrieval results against current source. See the manager's
155
+ [xerj setup and lifetime documentation](https://github.com/dyne/gestalt/blob/main/start/install.md).
156
+
131
157
  ## Kimi provider
132
158
 
133
159
  When the `kimi` CLI is found on `PATH`, the Session tab shows a **Provider**
@@ -157,6 +183,14 @@ enabled never share a runtime. Authentication is shared by symlinking it from
157
183
  Kimi sessions stay on core chat: org-plan/autopilot tooling (the Plan tab,
158
184
  autopilot controls) remains Codex-only and is hidden for Kimi sessions.
159
185
 
186
+ Xerj retrieval is unavailable through Mobile's supported `kimi web` path.
187
+ Although the terminal CLI accepts ad-hoc MCP configuration, web workers load
188
+ only their global MCP file and expose no native per-session connection-readiness
189
+ gate. Mobile does not materialize the conditional skill or add a tool bridge.
190
+ Profile runtimes and authentication isolation remain unchanged. This limitation
191
+ is grounded in the provider's [web command](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/cli/web.py)
192
+ and [worker MCP loading](https://github.com/MoonshotAI/kimi-cli/blob/main/src/kimi_cli/web/runner/worker.py).
193
+
160
194
  Kimi threads have no CLI resume command, so recent Kimi threads offer **Open**
161
195
  but no **Copy**, and the session card carries a **Kimi** badge instead.
162
196
 
@@ -2070,7 +2070,97 @@ describe('production composition', () => {
2070
2070
  expect(fixture.handles.flatMap((candidate) => candidate.requests.filter((call) => call.method === 'turn/start'))[0]?.params).toMatchObject({ threadId: 'child-1' });
2071
2071
  await fixture.app.close();
2072
2072
  });
2073
- it('production treats only a confirmed missing rollout as an executor rejection and starts one fenced replacement', async () => {
2073
+ it('production resumes an unloaded executor without leaving its command issued or replacing it', async () => {
2074
+ const timers = [];
2075
+ const fixture = await createProductionAutopilotFixture({
2076
+ autopilotActivity: (sessionId) => {
2077
+ const observedAt = new Date().toISOString();
2078
+ return {
2079
+ sessionId,
2080
+ rootThreadId: 'thread-1',
2081
+ root: {
2082
+ state: 'idle',
2083
+ reason: 'turnCompleted',
2084
+ observedAt,
2085
+ lastActivityAt: observedAt,
2086
+ },
2087
+ subagents: [
2088
+ {
2089
+ id: 'child-1',
2090
+ threadId: 'child-1',
2091
+ taskPath: '/root/l1',
2092
+ canonicalTaskName: 'l1',
2093
+ canonicalPosition: 'L1',
2094
+ continuationGeneration: 1,
2095
+ outcome: 'partial',
2096
+ ownedProcesses: [],
2097
+ state: 'idle',
2098
+ reason: 'turnCompleted',
2099
+ observedAt,
2100
+ lastActivityAt: observedAt,
2101
+ },
2102
+ ],
2103
+ aggregateSubagents: 'idle',
2104
+ confidence: 'fresh',
2105
+ };
2106
+ },
2107
+ autopilotSchedule: (callback) => {
2108
+ const timer = { callback, cancelled: false };
2109
+ timers.push(timer);
2110
+ return () => {
2111
+ timer.cancelled = true;
2112
+ };
2113
+ },
2114
+ });
2115
+ onTestFinished(() => fixture.app.close());
2116
+ for (const handle of fixture.handles) {
2117
+ let loaded = false;
2118
+ handle.respond = (method, params) => {
2119
+ if (params.threadId !== 'child-1')
2120
+ return undefined;
2121
+ if (method === 'thread/resume') {
2122
+ loaded = true;
2123
+ return { thread: { id: 'child-1' } };
2124
+ }
2125
+ if (method === 'turn/start') {
2126
+ if (!loaded)
2127
+ throw new CodexJsonRpcError(-32600, 'thread not found: child-1');
2128
+ return { turn: { id: 'child-turn' } };
2129
+ }
2130
+ return undefined;
2131
+ };
2132
+ }
2133
+ expect((await fixture.app.inject({
2134
+ method: 'PUT',
2135
+ url: `/api/sessions/${fixture.sessionId}/autopilot`,
2136
+ payload: { enabled: true },
2137
+ })).statusCode).toBe(200);
2138
+ await vi.waitFor(() => expect(timers.some((timer) => !timer.cancelled)).toBe(true));
2139
+ timers.find((timer) => !timer.cancelled).callback();
2140
+ const database = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
2141
+ onTestFinished(() => database.close());
2142
+ await vi.waitFor(() => {
2143
+ const row = database
2144
+ .prepare('SELECT lifecycle_json FROM autopilot_sessions WHERE session_id = ?')
2145
+ .get(fixture.sessionId);
2146
+ expect(JSON.parse(row.lifecycle_json)).toMatchObject({
2147
+ executor: {
2148
+ continuationCount: 1,
2149
+ commands: [expect.objectContaining({ status: 'accepted', threadId: 'child-1' })],
2150
+ },
2151
+ });
2152
+ });
2153
+ const calls = fixture.handles
2154
+ .flatMap((handle) => handle.requests)
2155
+ .filter((call) => call.params.threadId === 'child-1');
2156
+ expect(calls.filter((call) => call.method === 'turn/start')).toHaveLength(2);
2157
+ expect(calls.filter((call) => call.method === 'thread/resume')).toHaveLength(1);
2158
+ const failures = database
2159
+ .prepare("SELECT count(*) AS count FROM session_events WHERE session_id = ? AND type IN ('autopilot.operation-failed', 'autopilot.executor-replacement-scheduled')")
2160
+ .get(fixture.sessionId);
2161
+ expect(failures.count).toBe(0);
2162
+ });
2163
+ it.each(['missing rollout', 'unloaded child without rollout'])('production treats %s as an executor rejection and starts one fenced replacement', async (scenario) => {
2074
2164
  const timers = [];
2075
2165
  const fixture = await createProductionAutopilotFixture({
2076
2166
  autopilotActivity: (sessionId) => {
@@ -2116,7 +2206,11 @@ describe('production composition', () => {
2116
2206
  // every live writer that can own the executor continuation.
2117
2207
  for (const handle of fixture.handles)
2118
2208
  handle.respond = (method, params) => {
2119
- if (method === 'turn/start' && params.threadId === 'child-1')
2209
+ if (params.threadId !== 'child-1')
2210
+ return undefined;
2211
+ if (method === 'turn/start' && scenario === 'unloaded child without rollout')
2212
+ throw new CodexJsonRpcError(-32600, 'thread not found: child-1');
2213
+ if (method === 'turn/start' || method === 'thread/resume')
2120
2214
  throw new CodexJsonRpcError(-32600, 'no rollout found for thread id child-1');
2121
2215
  return undefined;
2122
2216
  };
@@ -2191,7 +2285,10 @@ describe('production composition', () => {
2191
2285
  expect(replacements.count).toBe(1);
2192
2286
  await fixture.app.close();
2193
2287
  });
2194
- it('production leaves a transport-lost executor command issued and never replays it as a replacement', async () => {
2288
+ it.each([
2289
+ ['transport-lost', new Error('CODEX_CONNECTION_LOST')],
2290
+ ['ambiguous RPC failure', new CodexJsonRpcError(-32603, 'internal error')],
2291
+ ])('production leaves a %s executor command issued and never replays it as a replacement', async (_scenario, failure) => {
2195
2292
  const timers = [];
2196
2293
  const fixture = await createProductionAutopilotFixture({
2197
2294
  autopilotActivity: (sessionId) => {
@@ -2236,7 +2333,7 @@ describe('production composition', () => {
2236
2333
  for (const handle of fixture.handles)
2237
2334
  handle.respond = (method, params) => {
2238
2335
  if (method === 'turn/start' && params.threadId === 'child-1')
2239
- throw new Error('transport dropped after request write');
2336
+ throw failure;
2240
2337
  return undefined;
2241
2338
  };
2242
2339
  expect((await fixture.app.inject({
@@ -3178,6 +3275,77 @@ describe('production composition', () => {
3178
3275
  });
3179
3276
  await app.close();
3180
3277
  });
3278
+ it('drains an in-flight capacity recovery before closing its session database', async () => {
3279
+ const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
3280
+ const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-mobile-state-'));
3281
+ ownTemporaryPaths(root, dataDir);
3282
+ await mkdir(join(root, 'workspace'));
3283
+ const handles = [];
3284
+ const launch = liveAppServer(handles);
3285
+ let blockResume = false;
3286
+ let resumeStarted;
3287
+ let releaseResume;
3288
+ const resumeStarting = new Promise((resolve) => (resumeStarted = resolve));
3289
+ const resumeGate = new Promise((resolve) => (releaseResume = resolve));
3290
+ const app = await composeAuthorizedApp({
3291
+ root,
3292
+ dataDir,
3293
+ relyingParty,
3294
+ installedCodexVersion: 'codex-cli 0.144.3',
3295
+ startAppServers: true,
3296
+ launchAppServer: () => {
3297
+ const server = launch();
3298
+ const handle = handles.at(-1);
3299
+ handle.respond = async (method, params) => {
3300
+ if (!blockResume || method !== 'thread/resume')
3301
+ return undefined;
3302
+ resumeStarted();
3303
+ await resumeGate;
3304
+ return { thread: { id: params.threadId } };
3305
+ };
3306
+ return server;
3307
+ },
3308
+ profiles: {
3309
+ list: async () => [],
3310
+ require: async () => ({
3311
+ name: 'default',
3312
+ state: 'ok',
3313
+ status: 'ready',
3314
+ }),
3315
+ },
3316
+ });
3317
+ const sessionId = await createComposedSession(app);
3318
+ const first = handles.find((candidate) => candidate.calls.includes('thread/start'));
3319
+ const started = await app.inject({
3320
+ method: 'POST',
3321
+ url: `/api/sessions/${sessionId}/turns`,
3322
+ payload: { text: 'continue supervised work' },
3323
+ });
3324
+ const turnId = started.json().activeTurnId;
3325
+ const threadId = (await app.inject(`/api/sessions/${sessionId}`)).json().threadId;
3326
+ first.notify?.({ method: 'turn/started', params: { threadId, turn: { id: turnId } } });
3327
+ blockResume = true;
3328
+ await expect(first.request({
3329
+ id: 92,
3330
+ method: 'item/tool/call',
3331
+ params: {
3332
+ threadId,
3333
+ turnId,
3334
+ tool: 'gestalt_agent_capacity_recovery',
3335
+ arguments: { version: 1, reason: 'agentThreadLimit' },
3336
+ },
3337
+ })).resolves.toMatchObject({ success: true });
3338
+ await resumeStarting;
3339
+ let closed = false;
3340
+ const close = app.close().then(() => {
3341
+ closed = true;
3342
+ });
3343
+ await new Promise((resolve) => setTimeout(resolve, 25));
3344
+ const closedBeforeRecoverySettled = closed;
3345
+ releaseResume();
3346
+ await close;
3347
+ expect(closedBeforeRecoverySettled).toBe(false);
3348
+ });
3181
3349
  it('publishes an idle websocket status after saving a completed turn', async () => {
3182
3350
  const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
3183
3351
  const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-mobile-state-'));
@@ -4337,19 +4505,10 @@ describe('production composition', () => {
4337
4505
  payload: { workspaceId: workspace.id, profile: 'default', provider: 'codex' },
4338
4506
  });
4339
4507
  expect(created.statusCode).toBe(202);
4340
- expect(firstCalls).toEqual([
4341
- 'initialize',
4342
- 'model/list',
4343
- 'initialize',
4344
- 'model/list',
4345
- 'initialize',
4346
- 'skills/list',
4347
- 'initialize',
4348
- 'skills/list',
4349
- 'initialize',
4350
- 'thread/start',
4351
- 'thread/read',
4352
- ]);
4508
+ expect(firstCalls.filter((method) => method === 'thread/start')).toHaveLength(1);
4509
+ expect(firstCalls).not.toContain('thread/resume');
4510
+ expect(firstCalls.indexOf('skills/list')).toBeLessThan(firstCalls.indexOf('thread/start'));
4511
+ expect(firstCalls.indexOf('config/read')).toBeLessThan(firstCalls.indexOf('thread/start'));
4353
4512
  await first.close();
4354
4513
  const secondCalls = [];
4355
4514
  const second = await composeAuthorizedApp({
@@ -4366,8 +4525,9 @@ describe('production composition', () => {
4366
4525
  await expect
4367
4526
  .poll(() => secondCalls, { timeout: 1_000 })
4368
4527
  .toEqual(['initialize', 'skills/list']);
4369
- const restored = await second.inject(`/api/sessions/${created.json().id}`);
4370
- expect(restored.json()).toMatchObject({
4528
+ await expect
4529
+ .poll(async () => (await second.inject(`/api/sessions/${created.json().id}`)).json())
4530
+ .toMatchObject({
4371
4531
  threadId: 'thread-1',
4372
4532
  state: 'stopped',
4373
4533
  agentActivity: { confidence: 'stale', root: { state: 'disconnected' } },
@@ -60,6 +60,8 @@ 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 { ManagedXerj, xerjDeadline } from './platform/retrieval/managed-xerj.js';
64
+ import { CodexXerj } from './platform/retrieval/codex-xerj.js';
63
65
  import { compileSkillOverride } from './features/skills/model/skill-profile.js';
64
66
  import { SupervisedPlanRegistry } from './features/plans/application/supervised-plan-registry.js';
65
67
  import { FilesystemPlanStatusSource } from './platform/plans/filesystem-plan-status-source.js';
@@ -412,10 +414,29 @@ export async function composeRelayApp(options) {
412
414
  // kimi discovery is workspace-scoped, not profile-scoped: the profile only
413
415
  // decides which discovered skills a session's server materializes.
414
416
  const kimiSkillCatalog = new KimiSkillCatalog(kimiManager ?? null, kimiManager != null);
417
+ const retrievalCapability = options.retrievalCapability ?? new ManagedXerj();
418
+ const xerj = new CodexXerj(retrievalCapability);
415
419
  const skillCatalog = (provider, profile) => provider === 'kimi'
416
420
  ? kimiSkillCatalog
417
421
  : new CodexSkillCatalog(profile, options.launchAppServer ?? launchCodexAppServer);
418
- const editorSkillCatalog = new CachedSkillCatalog((provider, profile, workspace) => skillCatalog(provider, profile).list(workspace));
422
+ const editorSkillCatalog = new CachedSkillCatalog((provider, profile, workspace) => provider === 'codex'
423
+ ? new CodexSkillCatalog(profile, options.launchAppServer ?? launchCodexAppServer, 5_000, xerj).list(workspace)
424
+ : kimiSkillCatalog.list(workspace), async (provider, _profile, workspace, result) => {
425
+ if (provider !== 'codex' ||
426
+ !result.skills.some((skill) => skill.name === 'gestalt:xerj' && skill.enabled))
427
+ 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
+ };
439
+ });
419
440
  const workspacePlanCatalog = new FilesystemWorkspacePlanCatalog();
420
441
  const planArchiver = new FilesystemPlanArchiver();
421
442
  const resolveSkills = async (session) => {
@@ -472,6 +493,9 @@ export async function composeRelayApp(options) {
472
493
  let recoverExitedSession = () => { };
473
494
  let recoverExitedKimiSession = () => { };
474
495
  let scheduleAgentCapacityRecovery = () => false;
496
+ const capacityRecoveries = new Set();
497
+ const capacityRecoveryTimers = new Map();
498
+ const capacityRecoveryTasks = new Map();
475
499
  let planMeasurementRefresh;
476
500
  const publishInteractionResolved = (sessionId, requestId, occurredAt, outcome) => {
477
501
  const interaction = interactions
@@ -963,7 +987,27 @@ export async function composeRelayApp(options) {
963
987
  failPendingCheckpointHandoffs(sessionId, false);
964
988
  dismissPendingInteractions(sessionId, new Date().toISOString(), 'failed');
965
989
  recoverExitedSession(sessionId);
966
- }, resolveSkills, planStatusSource, acceptPlanUpdate, options.planMeasurementBaseUrl, 30_000, 64, root, (session) => sessionModelConfig.resolve(session))
990
+ }, undefined, planStatusSource, acceptPlanUpdate, options.planMeasurementBaseUrl, 30_000, 64, root, (session) => sessionModelConfig.resolve(session), {
991
+ prepare: async (session, rpc, config, deadline) => {
992
+ const catalog = await new CodexSkillCatalog(session.profile, options.launchAppServer ?? launchCodexAppServer, Math.max(1, deadline - Date.now())).list(session.workspacePath);
993
+ const project = await skillProfiles.readWorkspaceDefault(session.workspacePath);
994
+ const selected = compileSkillOverride({
995
+ discovered: catalog.skills,
996
+ explicit: session.effectiveSkillSelection?.skills ?? options.explicitSkillProfile?.skills,
997
+ project: project?.skills,
998
+ });
999
+ return xerj.prepare({
1000
+ cwd: session.workspacePath,
1001
+ rpc,
1002
+ config,
1003
+ deadline,
1004
+ skills: catalog.skills,
1005
+ skillsConfig: selected.skillsConfig,
1006
+ start: true,
1007
+ });
1008
+ },
1009
+ verify: (rpc, threadId, state) => xerj.verify(rpc, threadId, state),
1010
+ })
967
1011
  : null;
968
1012
  const handleKimiNotification = (sessionId, event) => {
969
1013
  const occurredAt = new Date().toISOString();
@@ -1084,13 +1128,13 @@ export async function composeRelayApp(options) {
1084
1128
  /** Routes a session to the runtime owning its provider's llm service. */
1085
1129
  const ownerRuntime = (session) => session.provider === 'kimi' ? kimiRuntime : runtime;
1086
1130
  if (runtime) {
1087
- const capacityRecoveries = new Set();
1088
1131
  scheduleAgentCapacityRecovery = (sessionId, acknowledge) => {
1089
- if (capacityRecoveries.has(sessionId) || !acknowledge())
1132
+ if (closing || capacityRecoveries.has(sessionId) || !acknowledge())
1090
1133
  return false;
1091
1134
  capacityRecoveries.add(sessionId);
1092
- setTimeout(() => {
1093
- void (async () => {
1135
+ const timer = setTimeout(() => {
1136
+ capacityRecoveryTimers.delete(sessionId);
1137
+ const task = Promise.resolve().then(async () => {
1094
1138
  try {
1095
1139
  if (closing)
1096
1140
  return;
@@ -1112,9 +1156,12 @@ export async function composeRelayApp(options) {
1112
1156
  }
1113
1157
  finally {
1114
1158
  capacityRecoveries.delete(sessionId);
1159
+ capacityRecoveryTasks.delete(sessionId);
1115
1160
  }
1116
- })();
1161
+ });
1162
+ capacityRecoveryTasks.set(sessionId, task);
1117
1163
  }, 500);
1164
+ capacityRecoveryTimers.set(sessionId, timer);
1118
1165
  return true;
1119
1166
  };
1120
1167
  const supervisor = new SessionSupervisor(async (sessionId) => {
@@ -1817,6 +1864,15 @@ export async function composeRelayApp(options) {
1817
1864
  });
1818
1865
  app.addHook('onClose', async () => {
1819
1866
  closing = true;
1867
+ for (const [sessionId, timer] of capacityRecoveryTimers) {
1868
+ clearTimeout(timer);
1869
+ capacityRecoveries.delete(sessionId);
1870
+ }
1871
+ capacityRecoveryTimers.clear();
1872
+ // Capacity recovery owns an app-server recycle that can still persist its
1873
+ // result after an await. Drain accepted operations before stopping runtimes
1874
+ // or closing the session database they use.
1875
+ await Promise.allSettled([...capacityRecoveryTasks.values()]);
1820
1876
  planMeasurementRefresh?.stopAll();
1821
1877
  for (const session of sessions.list()) {
1822
1878
  autopilot.dispose(session.id);
@@ -41,7 +41,7 @@ export function registerListAvailableSkills(app, deps) {
41
41
  source: project ? 'project' : 'native',
42
42
  errors: discovered.errors.map(({ message }) => ({ message })),
43
43
  skills: skills
44
- .filter((skill) => !isAlwaysAdvertisedSkill(skill))
44
+ .filter((skill) => !isAlwaysAdvertisedSkill(skill) && skill.name !== 'gestalt:xerj')
45
45
  .sort((left, right) => left.path.localeCompare(right.path))
46
46
  .map((skill) => ({
47
47
  name: skill.name,
@@ -56,7 +56,7 @@ 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);
59
+ return isGestaltSkillName(skill.name) && (skill.name !== 'gestalt:xerj' || skill.enabled);
60
60
  }
61
61
  export function isGestaltSkillName(name) {
62
62
  return name.startsWith('gestalt:');
@@ -159,7 +159,11 @@ export function applySkillSelectionSnapshot(discovered, selection) {
159
159
  const enabledByPath = new Map(createSkillSelection(selection).map((entry) => [entry.path, entry.enabled]));
160
160
  return catalog.map((skill) => ({
161
161
  ...skill,
162
- enabled: isAlwaysAdvertisedSkill(skill) ? true : (enabledByPath.get(skill.path) ?? false),
162
+ enabled: skill.name === 'gestalt:xerj'
163
+ ? skill.enabled
164
+ : isAlwaysAdvertisedSkill(skill)
165
+ ? true
166
+ : (enabledByPath.get(skill.path) ?? false),
163
167
  }));
164
168
  }
165
169
  /** Explicit session selection takes precedence over a workspace default. */
@@ -6,6 +6,23 @@
6
6
  import { countDiffLines } from '../../../shared/contracts/file-change.js';
7
7
  import { relative } from 'node:path';
8
8
  export function normalizeCodexNotification(sessionId, sequence, occurredAt, notification, workspacePath, activeTurnId, origin = { kind: 'root' }) {
9
+ const connection = record(notification.params);
10
+ if (notification.method === 'mcpServer/statusUpdated' &&
11
+ connection?.name === 'gestalt-xerj' &&
12
+ ['failed', 'cancelled'].includes(String(connection.status))) {
13
+ return {
14
+ sessionId,
15
+ sequence,
16
+ occurredAt,
17
+ type: 'activity.updated',
18
+ payload: {
19
+ id: 'gestalt-xerj-availability',
20
+ label: 'Xerj unavailable',
21
+ detail: 'Retrieval is unavailable. Check gestalt xerj status. Use rg and current source reads; readiness will be checked when the runtime resumes.',
22
+ ...(activeTurnId ? { turnId: activeTurnId } : {}),
23
+ },
24
+ };
25
+ }
9
26
  const decoded = decodeNotification(notification);
10
27
  if (!decoded)
11
28
  return null;
@@ -18,13 +18,17 @@ import { threadPlanName } from './thread-plan-name.js';
18
18
  import { WriterAcquisitionError, } from '../../features/sessions/application/writer-acquisition.js';
19
19
  import { CodexJsonRpcError, isCodexThreadWriterBusy, isMissingCodexThreadRollout, } from './json-rpc-client.js';
20
20
  import { resolvedServerRequestId } from './server-request.js';
21
+ import { xerjDeadline } from '../retrieval/managed-xerj.js';
21
22
  /** Sticky thread config keeps skill paths out of the app-server process argv. */
22
23
  export function threadSkillConfig(skillsConfig, modelConfig = {}) {
24
+ const conditional = modelConfig.skills?.config ?? [];
23
25
  return {
24
26
  config: {
25
27
  ...modelConfig,
26
28
  'tools.update_plan.enabled': true,
27
- ...(skillsConfig === undefined ? {} : { skills: { config: skillsConfig } }),
29
+ ...(skillsConfig === undefined
30
+ ? {}
31
+ : { skills: { config: [...skillsConfig, ...conditional] } }),
28
32
  },
29
33
  };
30
34
  }
@@ -62,6 +66,9 @@ class SessionResource {
62
66
  this.unregister = unregister;
63
67
  this.onDisposed = onDisposed;
64
68
  }
69
+ retrieval;
70
+ retrievalFailureReported = false;
71
+ readinessDeadline = xerjDeadline();
65
72
  dispose() {
66
73
  if (this.disposed)
67
74
  return false;
@@ -102,13 +109,14 @@ export class CodexSessionRuntime {
102
109
  maxPendingRequests;
103
110
  readerCwd;
104
111
  resolveModelConfig;
112
+ retrieval;
105
113
  serverResponseListeners = new Set();
106
114
  constructor(launch,
107
115
  // Kept as an ignored compatibility slot while callers migrate from the old
108
116
  // correlated-map constructor shape. Live ownership is `sessions` only.
109
117
  _legacyProcesses = undefined, onNotification, onServerRequest, onProcessExit, resolveSkills, planStatusSource, onPlanStatus, planMeasurementBaseUrl,
110
118
  // Compatibility slot: blocking app-server requests wait for explicit input.
111
- _legacyRequestTimeoutMs = undefined, maxPendingRequests = 64, readerCwd, resolveModelConfig) {
119
+ _legacyRequestTimeoutMs = undefined, maxPendingRequests = 64, readerCwd, resolveModelConfig, retrieval) {
112
120
  this.launch = launch;
113
121
  this.onNotification = onNotification;
114
122
  this.onServerRequest = onServerRequest;
@@ -120,6 +128,7 @@ export class CodexSessionRuntime {
120
128
  this.maxPendingRequests = maxPendingRequests;
121
129
  this.readerCwd = readerCwd;
122
130
  this.resolveModelConfig = resolveModelConfig;
131
+ this.retrieval = retrieval;
123
132
  void _legacyProcesses;
124
133
  void _legacyRequestTimeoutMs;
125
134
  }
@@ -134,13 +143,15 @@ export class CodexSessionRuntime {
134
143
  clientInfo: { name: 'gestalt-mobile', version: '0.1.0' },
135
144
  capabilities: { experimentalApi: true },
136
145
  });
146
+ await this.prepareRetrieval(resource, session);
137
147
  const startedThreadId = await this.startThread(resource.process, session, resource.skillsConfig, resource.modelConfig);
138
148
  resource.threadId = startedThreadId;
149
+ await this.verifyRetrieval(resource, session, true);
139
150
  this.sessions.set(session.id, resource);
140
151
  await this.writePendingThreadName(session.id);
141
- return RelaySession.rehydrate(session)
142
- .bindThread(startedThreadId, now)
143
- .supportsAttentionTool(now).snapshot;
152
+ return this.withEffectiveRetrieval(RelaySession.rehydrate(session)
153
+ .bindThread(resource.threadId, now)
154
+ .supportsAttentionTool(now).snapshot, resource);
144
155
  }
145
156
  catch (error) {
146
157
  resource.dispose();
@@ -246,7 +257,7 @@ export class CodexSessionRuntime {
246
257
  const resource = this.sessions.get(session.id);
247
258
  if (!resource)
248
259
  throw new Error('CODEX_SESSION_NOT_RUNNING');
249
- const result = decodeTurnStart(await resource.process.rpc.request('turn/start', {
260
+ const params = {
250
261
  threadId: childThreadId,
251
262
  input: [{ type: 'text', text, text_elements: [] }],
252
263
  clientUserMessageId,
@@ -256,7 +267,24 @@ export class CodexSessionRuntime {
256
267
  ...(session.modelSettings?.executorReasoningEffort
257
268
  ? { effort: session.modelSettings.executorReasoningEffort }
258
269
  : {}),
259
- }));
270
+ };
271
+ let response;
272
+ try {
273
+ response = await resource.process.rpc.request('turn/start', params);
274
+ }
275
+ catch (error) {
276
+ // Codex 0.160 rejects a durable child absent from this writer's live
277
+ // registry. Load that same thread without overriding its role/config.
278
+ // Only this exact rejection permits one retry; transport loss may hide
279
+ // accepted work and must retain the durable issued fence.
280
+ if (!(error instanceof CodexJsonRpcError) ||
281
+ error.code !== -32600 ||
282
+ error.message !== `thread not found: ${childThreadId}`)
283
+ throw error;
284
+ await resource.process.rpc.request('thread/resume', { threadId: childThreadId });
285
+ response = await resource.process.rpc.request('turn/start', params);
286
+ }
287
+ const result = decodeTurnStart(response);
260
288
  if (resource.turnThreads.has(result) || resource.turnThreads.size < 256)
261
289
  resource.turnThreads.set(result, childThreadId);
262
290
  return result;
@@ -737,7 +765,9 @@ export class CodexSessionRuntime {
737
765
  clientInfo: { name: 'gestalt-mobile', version: '0.1.0' },
738
766
  capabilities: { experimentalApi: true },
739
767
  });
768
+ await this.prepareRetrieval(resource, session);
740
769
  let result;
770
+ let missingRollout;
741
771
  try {
742
772
  await resource.process.rpc.request('thread/resume', {
743
773
  threadId: session.threadId,
@@ -765,14 +795,18 @@ export class CodexSessionRuntime {
765
795
  catch (error) {
766
796
  if (!canRebindMissingRollout(session, error))
767
797
  throw error;
798
+ missingRollout = error;
768
799
  const replacementThreadId = await this.startThread(resource.process, session, resource.skillsConfig, resource.modelConfig);
769
800
  result = rebindMissingRollout(session, error, replacementThreadId, now);
770
801
  }
771
802
  resource.threadId = result.session.threadId;
803
+ await this.verifyRetrieval(resource, session, result.replacementCreated);
804
+ if (result.replacementCreated && resource.threadId !== result.session.threadId)
805
+ result = rebindMissingRollout(session, missingRollout, resource.threadId, now);
772
806
  this.sessions.get(session.id)?.dispose();
773
807
  this.sessions.set(session.id, resource);
774
808
  await this.writePendingThreadName(session.id);
775
- return result;
809
+ return { ...result, session: this.withEffectiveRetrieval(result.session, resource) };
776
810
  }
777
811
  catch (error) {
778
812
  resource.dispose();
@@ -867,6 +901,7 @@ export class CodexSessionRuntime {
867
901
  : { sandbox: selection };
868
902
  }
869
903
  async createResource(session) {
904
+ const deadline = xerjDeadline();
870
905
  const lease = this.planStatusSource
871
906
  ? await this.planStatusSource.open({ id: session.id, workspacePath: session.workspacePath }, (update) => this.onPlanStatus?.(session.id, update))
872
907
  : undefined;
@@ -897,6 +932,7 @@ export class CodexSessionRuntime {
897
932
  if (this.sessions.get(session.id) === resource)
898
933
  this.sessions.delete(session.id);
899
934
  });
935
+ resource.readinessDeadline = deadline;
900
936
  // Own process exit before resume/initialization can make this resource appear healthy.
901
937
  // A short-lived child could otherwise leave a durable ready session without a writer.
902
938
  const exitUnsubscribe = process.onExit?.(() => {
@@ -911,6 +947,15 @@ export class CodexSessionRuntime {
911
947
  const notificationUnsubscribe = process.rpc.onNotification((notification) => {
912
948
  if (!resource.active)
913
949
  return;
950
+ if (notification.method === 'mcpServer/statusUpdated') {
951
+ const status = notification.params;
952
+ if (status?.name === 'gestalt-xerj' &&
953
+ ['failed', 'cancelled'].includes(status.status ?? '')) {
954
+ if (resource.retrievalFailureReported)
955
+ return;
956
+ resource.retrievalFailureReported = true;
957
+ }
958
+ }
914
959
  const childModel = decodeThreadSettingsModel(notification);
915
960
  if (childModel &&
916
961
  (resource.spawnedAgentModels.has(childModel.threadId) ||
@@ -954,6 +999,69 @@ export class CodexSessionRuntime {
954
999
  throw error;
955
1000
  }
956
1001
  }
1002
+ withEffectiveRetrieval(session, resource) {
1003
+ if (!resource.retrieval || !session.effectiveSkillSelection)
1004
+ return session;
1005
+ return {
1006
+ ...session,
1007
+ effectiveSkillSelection: {
1008
+ ...session.effectiveSkillSelection,
1009
+ skills: session.effectiveSkillSelection.skills.map((skill) => skill.name === 'gestalt:xerj' ? { ...skill, enabled: resource.retrieval.ready } : skill),
1010
+ },
1011
+ };
1012
+ }
1013
+ async prepareRetrieval(resource, session) {
1014
+ if (!this.retrieval)
1015
+ return;
1016
+ const state = await this.retrieval.prepare(session, resource.process.rpc, resource.modelConfig, resource.readinessDeadline);
1017
+ resource.retrieval = state;
1018
+ resource.skillsConfig = state.skillsConfig;
1019
+ resource.modelConfig = state.config;
1020
+ if (state.diagnostic && !resource.retrievalFailureReported) {
1021
+ resource.retrievalFailureReported = true;
1022
+ this.onNotification?.(session.id, {
1023
+ method: 'mcpServer/statusUpdated',
1024
+ params: { name: 'gestalt-xerj', status: 'failed' },
1025
+ }, { kind: 'root' });
1026
+ }
1027
+ }
1028
+ async verifyRetrieval(resource, session, fresh = false) {
1029
+ const state = resource.retrieval;
1030
+ if (!state?.ready || !resource.threadId || !this.retrieval)
1031
+ return;
1032
+ if (await this.retrieval.verify(resource.process.rpc, resource.threadId, state))
1033
+ return;
1034
+ state.fallback();
1035
+ if (!resource.retrievalFailureReported) {
1036
+ resource.retrievalFailureReported = true;
1037
+ this.onNotification?.(session.id, {
1038
+ method: 'mcpServer/statusUpdated',
1039
+ params: {
1040
+ name: 'gestalt-xerj',
1041
+ status: 'failed',
1042
+ },
1043
+ }, { kind: 'root' });
1044
+ }
1045
+ resource.skillsConfig = state.skillsConfig;
1046
+ resource.modelConfig = state.config;
1047
+ // A fresh Codex thread has no durable rollout until its first turn, so it
1048
+ // cannot be resumed. Release its connection and create the fallback root
1049
+ // before publishing a thread ID. Persisted resumes retain their identity.
1050
+ if (fresh) {
1051
+ await resource.process.rpc.request('thread/unsubscribe', { threadId: resource.threadId });
1052
+ resource.threadId = await this.startThread(resource.process, session, resource.skillsConfig, resource.modelConfig);
1053
+ return;
1054
+ }
1055
+ await resource.process.rpc.request('thread/resume', {
1056
+ threadId: resource.threadId,
1057
+ cwd: session.workspacePath,
1058
+ ...threadSkillConfig(resource.skillsConfig, resource.modelConfig),
1059
+ ...(session.executionPolicy?.approvalPolicy
1060
+ ? { approvalPolicy: session.executionPolicy.approvalPolicy }
1061
+ : {}),
1062
+ ...this.permissionParams(session),
1063
+ });
1064
+ }
957
1065
  resolveNotificationOrigin(resource, notification) {
958
1066
  const params = asRecord(notification.params);
959
1067
  if (!params)
@@ -45,6 +45,15 @@ export class KimiSkillCatalog {
45
45
  const skill = wire;
46
46
  if (!skill || typeof skill !== 'object' || typeof skill.name !== 'string')
47
47
  continue;
48
+ // kimi web workers accept only global MCP configuration and expose no
49
+ // per-session native connection readiness gate. Never materialize
50
+ // conditional retrieval guidance without that verified connection.
51
+ if (skill.name === 'gestalt:xerj') {
52
+ errors.push({
53
+ message: 'Xerj retrieval is unavailable for Kimi web: native session readiness is unsupported.',
54
+ });
55
+ continue;
56
+ }
48
57
  // The shared catalog contract canonicalizes skill paths as absolute
49
58
  // filesystem paths (profile snapshots and overrides resolve against
50
59
  // them). kimi built-ins report no path and cannot be materialized per
@@ -0,0 +1,156 @@
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
+ export const xerjServerName = 'gestalt-xerj';
8
+ export const xerjTools = ['xerj_search', 'xerj_map', 'xerj_code_search'];
9
+ /** Ephemeral native thread configuration; no installation or daemon ownership. */
10
+ export class CodexXerj {
11
+ capability;
12
+ constructor(capability) {
13
+ this.capability = capability;
14
+ }
15
+ async prepare(input) {
16
+ const skill = input.skills.find((entry) => entry.name === 'gestalt:xerj');
17
+ const state = {
18
+ ready: false,
19
+ deadline: input.deadline,
20
+ config: { ...input.config },
21
+ skillsConfig: input.skillsConfig.map((entry) => ({
22
+ ...entry,
23
+ enabled: entry.path === skill?.path ? false : entry.enabled,
24
+ })),
25
+ fallback: () => { },
26
+ };
27
+ let native = {};
28
+ let compatible = false;
29
+ try {
30
+ const read = (await beforeDeadline(input.rpc.request('config/read', { includeLayers: false }), input.deadline));
31
+ native = read.config ?? {};
32
+ compatible = read.config !== undefined;
33
+ }
34
+ catch {
35
+ /* An incompatible runtime cannot safely advertise retrieval. */
36
+ }
37
+ const servers = native.mcp_servers && typeof native.mcp_servers === 'object'
38
+ ? native.mcp_servers
39
+ : {};
40
+ const mcp = {};
41
+ // Disable aliases of the managed connection without disturbing unrelated MCP.
42
+ for (const [name, server] of Object.entries(servers)) {
43
+ if (server?.args?.[0] === 'xerj' && server.args[1] === 'mcp')
44
+ mcp[name] = { ...server, enabled: false, required: false };
45
+ }
46
+ const instructions = typeof native.developer_instructions === 'string' ? native.developer_instructions : '';
47
+ state.fallback = () => {
48
+ state.ready = false;
49
+ state.skillsConfig = state.skillsConfig.map((entry) => ({
50
+ ...entry,
51
+ enabled: entry.path === skill?.path ? false : entry.enabled,
52
+ }));
53
+ state.config = {
54
+ ...input.config,
55
+ skills: { config: [{ name: 'gestalt:xerj', enabled: false }] },
56
+ mcp_servers: {
57
+ ...mcp,
58
+ [xerjServerName]: {
59
+ command: 'gestalt',
60
+ args: ['xerj', 'mcp'],
61
+ enabled: false,
62
+ required: false,
63
+ },
64
+ },
65
+ developer_instructions: `${instructions}\n<gestalt_xerj_unavailable>\nXerj retrieval is unavailable in this runtime. Earlier retrieval guidance is inactive; use rg and current source reads.\n</gestalt_xerj_unavailable>`,
66
+ };
67
+ };
68
+ state.fallback();
69
+ if (!compatible || !skill || Date.now() >= input.deadline)
70
+ return state;
71
+ try {
72
+ const ready = await this.capability.check({
73
+ cwd: input.cwd,
74
+ deadline: input.deadline,
75
+ start: input.start,
76
+ });
77
+ if (ready.status !== 'ready') {
78
+ if (ready.status === 'unavailable')
79
+ state.diagnostic = 'backend-unavailable';
80
+ return state;
81
+ }
82
+ const guidance = await beforeDeadline(readFile(skill.path, 'utf8'), input.deadline);
83
+ if (guidance.length > 16_384)
84
+ return state;
85
+ state.skillsConfig = state.skillsConfig.map((entry) => ({
86
+ ...entry,
87
+ enabled: entry.path === skill.path ? true : entry.enabled,
88
+ }));
89
+ state.config = {
90
+ ...input.config,
91
+ skills: { config: [{ name: 'gestalt:xerj', enabled: true }] },
92
+ mcp_servers: {
93
+ ...mcp,
94
+ [xerjServerName]: {
95
+ command: ready.manager,
96
+ args: ['xerj', 'mcp', '--url', ready.endpoint],
97
+ env_vars: ['GESTALT_HOME', 'XERJ_API_KEY', 'XERJ_AUTH'],
98
+ enabled: true,
99
+ required: false,
100
+ startup_readiness: 'connection',
101
+ startup_timeout_ms: Math.max(1, input.deadline - Date.now()),
102
+ enabled_tools: xerjTools,
103
+ default_tools_approval_mode: 'approve',
104
+ },
105
+ },
106
+ developer_instructions: `${instructions}\n<gestalt_xerj_capability>\n${guidance}\n</gestalt_xerj_capability>`,
107
+ };
108
+ state.ready = true;
109
+ }
110
+ catch {
111
+ state.fallback();
112
+ state.diagnostic = 'connection-unavailable';
113
+ }
114
+ return state;
115
+ }
116
+ async verify(rpc, threadId, state) {
117
+ if (!state.ready)
118
+ return false;
119
+ try {
120
+ while (Date.now() < state.deadline) {
121
+ const result = (await beforeDeadline(rpc.request('mcpServerStatus/list', {
122
+ threadId,
123
+ serverName: xerjServerName,
124
+ detail: 'full',
125
+ }), state.deadline));
126
+ const server = result.data?.find((entry) => entry.name === xerjServerName);
127
+ if (server?.runtimeStatus === 'connected' &&
128
+ !server.toolsError &&
129
+ xerjTools.every((tool) => Object.hasOwn(server.tools ?? {}, tool)))
130
+ return true;
131
+ if (server?.runtimeStatus !== 'starting')
132
+ return false;
133
+ await beforeDeadline(new Promise((resolve) => setTimeout(resolve, 25)), state.deadline);
134
+ }
135
+ return false;
136
+ }
137
+ catch {
138
+ return false;
139
+ }
140
+ }
141
+ }
142
+ export async function beforeDeadline(promise, deadline) {
143
+ let timer;
144
+ try {
145
+ return await Promise.race([
146
+ promise,
147
+ new Promise((_, reject) => {
148
+ timer = setTimeout(() => reject(new Error('XERJ_READINESS_TIMEOUT')), Math.max(0, deadline - Date.now()));
149
+ }),
150
+ ]);
151
+ }
152
+ finally {
153
+ if (timer)
154
+ clearTimeout(timer);
155
+ }
156
+ }
@@ -0,0 +1,119 @@
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 { spawn } from 'node:child_process';
7
+ import { access } from 'node:fs/promises';
8
+ import { constants } from 'node:fs';
9
+ import { isAbsolute, join } from 'node:path';
10
+ /** The manager alone owns backend identity, authentication and shared lifetime. */
11
+ export class ManagedXerj {
12
+ environment;
13
+ constructor(environment = process.env) {
14
+ this.environment = environment;
15
+ }
16
+ async check(input) {
17
+ const manager = await this.manager();
18
+ if (!manager)
19
+ return { status: 'absent' };
20
+ const remaining = input.deadline - Date.now();
21
+ // The shipped manager rejects sub-100ms operations because it reserves
22
+ // cleanup time inside the overall deadline. Do not spend the remaining
23
+ // budget spawning a request that cannot satisfy that contract.
24
+ if (remaining < minimumXerjTimeoutMs)
25
+ return { status: 'unavailable', reason: 'readiness-timeout' };
26
+ return new Promise((resolve) => {
27
+ const child = spawn(manager, ['xerj', input.start ? 'ensure-ready' : 'probe'], {
28
+ cwd: input.cwd,
29
+ env: { ...this.environment, XERJ_READY_TIMEOUT_MS: String(remaining) },
30
+ shell: false,
31
+ stdio: ['ignore', 'pipe', 'ignore'],
32
+ });
33
+ let output = '';
34
+ let finished = false;
35
+ const settle = (result) => {
36
+ if (finished)
37
+ return;
38
+ finished = true;
39
+ clearTimeout(timer);
40
+ resolve(result);
41
+ };
42
+ const unavailable = (reason) => ({
43
+ status: 'unavailable',
44
+ reason,
45
+ });
46
+ const timer = setTimeout(() => {
47
+ // Reap the owned probe; never signal the manager's shared backend.
48
+ child.kill('SIGTERM');
49
+ const kill = setTimeout(() => child.kill('SIGKILL'), 100).unref();
50
+ child.once('close', () => clearTimeout(kill));
51
+ settle(unavailable('readiness-timeout'));
52
+ }, remaining);
53
+ child.on('error', () => settle(unavailable('manager-unavailable')));
54
+ child.stdout.on('data', (data) => {
55
+ output += data.toString();
56
+ if (output.length > 16_384) {
57
+ child.kill('SIGKILL');
58
+ settle(unavailable('invalid-manager-response'));
59
+ }
60
+ });
61
+ child.once('close', (code) => {
62
+ try {
63
+ const value = JSON.parse(output);
64
+ if (code !== 0 || value.schemaVersion !== 1)
65
+ throw new Error();
66
+ if (value.status === 'absent')
67
+ return settle({ status: 'absent' });
68
+ if (value.status === 'unavailable')
69
+ return settle(unavailable('managed-backend-unavailable'));
70
+ if (value.status !== 'ready' ||
71
+ value.version !== '1.0.0-rc.87' ||
72
+ typeof value.endpoint !== 'string' ||
73
+ !/^http:\/\/(127\.0\.0\.1|\[::1\])(?::\d{1,5})?$/.test(value.endpoint))
74
+ throw new Error();
75
+ const url = new URL(value.endpoint);
76
+ if (Number(url.port || 80) < 1 || Number(url.port || 80) > 65535)
77
+ throw new Error();
78
+ settle({ status: 'ready', manager, endpoint: value.endpoint });
79
+ }
80
+ catch {
81
+ settle(unavailable('invalid-manager-response'));
82
+ }
83
+ });
84
+ });
85
+ }
86
+ async manager() {
87
+ const explicit = this.environment.GESTALT_MANAGER_BIN;
88
+ const paths = explicit
89
+ ? [explicit]
90
+ : (this.environment.PATH ?? '')
91
+ .split(':')
92
+ .filter(Boolean)
93
+ .map((path) => join(path, 'gestalt'));
94
+ for (const path of paths) {
95
+ if (!isAbsolute(path))
96
+ continue;
97
+ try {
98
+ await access(path, constants.X_OK);
99
+ return path;
100
+ }
101
+ catch {
102
+ /* Try next established executable path. */
103
+ }
104
+ }
105
+ return undefined;
106
+ }
107
+ }
108
+ export function xerjDeadline(environment = process.env) {
109
+ const configured = Number(environment.XERJ_READY_TIMEOUT_MS);
110
+ return (Date.now() +
111
+ (Number.isInteger(configured) &&
112
+ configured >= minimumXerjTimeoutMs &&
113
+ configured <= maximumXerjTimeoutMs
114
+ ? configured
115
+ : defaultXerjTimeoutMs));
116
+ }
117
+ const minimumXerjTimeoutMs = 100;
118
+ const maximumXerjTimeoutMs = 60_000;
119
+ const defaultXerjTimeoutMs = 5_000;
@@ -8,6 +8,8 @@ import { resolve } from 'node:path';
8
8
  import { availableSkillSchema, } from '../../features/skills/model/skill-profile.js';
9
9
  import { SkillProfileError } from '../../features/skills/model/errors.js';
10
10
  import { launchCodexAppServer } from '../codex/codex-process-launcher.js';
11
+ import { xerjDeadline } from '../retrieval/managed-xerj.js';
12
+ import { threadSkillConfig } from '../codex/session-runtime.js';
11
13
  const optionalString = z.preprocess((value) => (value === null ? undefined : value), z.string().optional());
12
14
  const optionalObject = (schema) => z.preprocess((value) => (value === null ? undefined : value), schema.optional());
13
15
  const toolSchema = z.object({
@@ -43,20 +45,23 @@ export class CodexSkillCatalog {
43
45
  profile;
44
46
  launch;
45
47
  timeoutMs;
46
- constructor(profile, launch = launchCodexAppServer, timeoutMs = 5_000) {
48
+ retrieval;
49
+ constructor(profile, launch = launchCodexAppServer, timeoutMs = 5_000, retrieval) {
47
50
  this.profile = profile;
48
51
  this.launch = launch;
49
52
  this.timeoutMs = timeoutMs;
53
+ this.retrieval = retrieval;
50
54
  }
51
55
  async list(workspace) {
56
+ const deadline = Math.min(xerjDeadline(), Date.now() + this.timeoutMs);
52
57
  const canonicalWorkspace = resolve(workspace);
53
58
  const server = this.launch({ profile: this.profile, cwd: canonicalWorkspace });
54
59
  try {
55
60
  await this.withTimeout(server.rpc.request('initialize', {
56
61
  clientInfo: { name: 'gestalt-mobile', version: '0.1.0' },
57
62
  capabilities: null,
58
- }));
59
- const result = await this.withTimeout(server.rpc.request('skills/list', { cwds: [canonicalWorkspace], forceReload: true }));
63
+ }), deadline);
64
+ const result = await this.withTimeout(server.rpc.request('skills/list', { cwds: [canonicalWorkspace], forceReload: true }), deadline);
60
65
  const parsed = resultSchema.safeParse(result);
61
66
  if (!parsed.success)
62
67
  throw new SkillProfileError('INVALID_SKILL_DISCOVERY', 'Invalid Codex skill catalog response.');
@@ -67,8 +72,38 @@ export class CodexSkillCatalog {
67
72
  const stable = availableSkillSchema.safeParse(skill);
68
73
  if (!stable.success)
69
74
  throw new SkillProfileError('INVALID_SKILL_DISCOVERY', 'Invalid Codex skill metadata.');
70
- return stable.data;
75
+ return stable.data.name === 'gestalt:xerj'
76
+ ? { ...stable.data, enabled: false }
77
+ : stable.data;
71
78
  });
79
+ if (this.retrieval && skills.some((skill) => skill.name === 'gestalt:xerj')) {
80
+ const state = await this.retrieval.prepare({
81
+ cwd: canonicalWorkspace,
82
+ deadline,
83
+ rpc: server.rpc,
84
+ skills,
85
+ skillsConfig: skills.map(({ path, enabled }) => ({ path, enabled })),
86
+ config: {},
87
+ start: false,
88
+ });
89
+ if (state.ready) {
90
+ try {
91
+ const result = (await this.withTimeout(server.rpc.request('thread/start', {
92
+ cwd: canonicalWorkspace,
93
+ ...threadSkillConfig(state.skillsConfig, state.config),
94
+ ephemeral: true,
95
+ }), deadline));
96
+ const ready = result.thread?.id &&
97
+ (await this.retrieval.verify(server.rpc, result.thread.id, state));
98
+ for (const skill of skills)
99
+ if (skill.name === 'gestalt:xerj')
100
+ skill.enabled = Boolean(ready);
101
+ }
102
+ catch {
103
+ /* Discovery remains usable without optional retrieval. */
104
+ }
105
+ }
106
+ }
72
107
  return {
73
108
  skills,
74
109
  errors: entry.errors.map((error) => ({
@@ -90,13 +125,13 @@ export class CodexSkillCatalog {
90
125
  server.close();
91
126
  }
92
127
  }
93
- async withTimeout(promise) {
128
+ async withTimeout(promise, deadline) {
94
129
  let timer;
95
130
  try {
96
131
  return await Promise.race([
97
132
  promise,
98
133
  new Promise((_, reject) => {
99
- timer = setTimeout(() => reject(new Error('timeout')), this.timeoutMs);
134
+ timer = setTimeout(() => reject(new Error('timeout')), Math.max(0, deadline - Date.now()));
100
135
  }),
101
136
  ]);
102
137
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.46.1",
3
+ "version": "0.47.0",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",