gestalt-mobile 0.46.2 → 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
 
@@ -3275,6 +3275,77 @@ describe('production composition', () => {
3275
3275
  });
3276
3276
  await app.close();
3277
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
+ });
3278
3349
  it('publishes an idle websocket status after saving a completed turn', async () => {
3279
3350
  const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
3280
3351
  const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-mobile-state-'));
@@ -4434,19 +4505,10 @@ describe('production composition', () => {
4434
4505
  payload: { workspaceId: workspace.id, profile: 'default', provider: 'codex' },
4435
4506
  });
4436
4507
  expect(created.statusCode).toBe(202);
4437
- expect(firstCalls).toEqual([
4438
- 'initialize',
4439
- 'model/list',
4440
- 'initialize',
4441
- 'model/list',
4442
- 'initialize',
4443
- 'skills/list',
4444
- 'initialize',
4445
- 'skills/list',
4446
- 'initialize',
4447
- 'thread/start',
4448
- 'thread/read',
4449
- ]);
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'));
4450
4512
  await first.close();
4451
4513
  const secondCalls = [];
4452
4514
  const second = await composeAuthorizedApp({
@@ -4463,8 +4525,9 @@ describe('production composition', () => {
4463
4525
  await expect
4464
4526
  .poll(() => secondCalls, { timeout: 1_000 })
4465
4527
  .toEqual(['initialize', 'skills/list']);
4466
- const restored = await second.inject(`/api/sessions/${created.json().id}`);
4467
- expect(restored.json()).toMatchObject({
4528
+ await expect
4529
+ .poll(async () => (await second.inject(`/api/sessions/${created.json().id}`)).json())
4530
+ .toMatchObject({
4468
4531
  threadId: 'thread-1',
4469
4532
  state: 'stopped',
4470
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();
@@ -754,7 +765,9 @@ export class CodexSessionRuntime {
754
765
  clientInfo: { name: 'gestalt-mobile', version: '0.1.0' },
755
766
  capabilities: { experimentalApi: true },
756
767
  });
768
+ await this.prepareRetrieval(resource, session);
757
769
  let result;
770
+ let missingRollout;
758
771
  try {
759
772
  await resource.process.rpc.request('thread/resume', {
760
773
  threadId: session.threadId,
@@ -782,14 +795,18 @@ export class CodexSessionRuntime {
782
795
  catch (error) {
783
796
  if (!canRebindMissingRollout(session, error))
784
797
  throw error;
798
+ missingRollout = error;
785
799
  const replacementThreadId = await this.startThread(resource.process, session, resource.skillsConfig, resource.modelConfig);
786
800
  result = rebindMissingRollout(session, error, replacementThreadId, now);
787
801
  }
788
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);
789
806
  this.sessions.get(session.id)?.dispose();
790
807
  this.sessions.set(session.id, resource);
791
808
  await this.writePendingThreadName(session.id);
792
- return result;
809
+ return { ...result, session: this.withEffectiveRetrieval(result.session, resource) };
793
810
  }
794
811
  catch (error) {
795
812
  resource.dispose();
@@ -884,6 +901,7 @@ export class CodexSessionRuntime {
884
901
  : { sandbox: selection };
885
902
  }
886
903
  async createResource(session) {
904
+ const deadline = xerjDeadline();
887
905
  const lease = this.planStatusSource
888
906
  ? await this.planStatusSource.open({ id: session.id, workspacePath: session.workspacePath }, (update) => this.onPlanStatus?.(session.id, update))
889
907
  : undefined;
@@ -914,6 +932,7 @@ export class CodexSessionRuntime {
914
932
  if (this.sessions.get(session.id) === resource)
915
933
  this.sessions.delete(session.id);
916
934
  });
935
+ resource.readinessDeadline = deadline;
917
936
  // Own process exit before resume/initialization can make this resource appear healthy.
918
937
  // A short-lived child could otherwise leave a durable ready session without a writer.
919
938
  const exitUnsubscribe = process.onExit?.(() => {
@@ -928,6 +947,15 @@ export class CodexSessionRuntime {
928
947
  const notificationUnsubscribe = process.rpc.onNotification((notification) => {
929
948
  if (!resource.active)
930
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
+ }
931
959
  const childModel = decodeThreadSettingsModel(notification);
932
960
  if (childModel &&
933
961
  (resource.spawnedAgentModels.has(childModel.threadId) ||
@@ -971,6 +999,69 @@ export class CodexSessionRuntime {
971
999
  throw error;
972
1000
  }
973
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
+ }
974
1065
  resolveNotificationOrigin(resource, notification) {
975
1066
  const params = asRecord(notification.params);
976
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.2",
3
+ "version": "0.47.0",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",