jg-agent-hq 2.0.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +14 -14
  3. package/api/README.md +97 -65
  4. package/dist/actions/actions.js +15 -0
  5. package/dist/cli/cli.js +28 -5
  6. package/dist/cli/utilities.d.ts +3 -0
  7. package/dist/cli/utilities.js +13 -0
  8. package/dist/collaboration/dispatch/types.d.ts +2 -2
  9. package/dist/contracts/actions/types.d.ts +4 -4
  10. package/dist/contracts/browser/index.d.ts +1 -3
  11. package/dist/contracts/browser/index.js +1 -3
  12. package/dist/contracts/browser/types.d.ts +15 -1447
  13. package/dist/contracts/browser/types.js +3 -112
  14. package/dist/contracts/index.d.ts +9 -11
  15. package/dist/contracts/index.js +6 -8
  16. package/dist/contracts/plans/index.d.ts +4 -6
  17. package/dist/contracts/plans/index.js +2 -4
  18. package/dist/contracts/plans/types.d.ts +38 -905
  19. package/dist/contracts/plans/types.js +13 -139
  20. package/dist/contracts/sessions/index.d.ts +2 -0
  21. package/dist/contracts/sessions/index.js +2 -0
  22. package/dist/contracts/sessions/types.d.ts +101 -0
  23. package/dist/contracts/sessions/types.js +43 -0
  24. package/dist/contracts/types.d.ts +551 -1035
  25. package/dist/contracts/types.js +32 -0
  26. package/dist/index.d.ts +2 -2
  27. package/dist/index.js +1 -1
  28. package/dist/plans/admission.d.ts +6 -6
  29. package/dist/plans/admission.js +1 -1
  30. package/dist/plans/authority.d.ts +2 -0
  31. package/dist/plans/authority.js +23 -13
  32. package/dist/plans/documents.d.ts +20 -17
  33. package/dist/plans/documents.js +29 -63
  34. package/dist/plans/files.d.ts +2 -2
  35. package/dist/plans/files.js +5 -5
  36. package/dist/plans/finalization.d.ts +6 -8
  37. package/dist/plans/finalization.js +25 -26
  38. package/dist/plans/index.d.ts +2 -3
  39. package/dist/plans/index.js +1 -2
  40. package/dist/plans/plans.d.ts +8 -8
  41. package/dist/plans/plans.js +36 -83
  42. package/dist/plans/projections.d.ts +2 -2
  43. package/dist/plans/projections.js +44 -82
  44. package/dist/plans/revisions.d.ts +4 -5
  45. package/dist/plans/revisions.js +5 -44
  46. package/dist/plans/types.d.ts +5 -281
  47. package/dist/plans/types.js +2 -30
  48. package/dist/plans/utilities.js +2 -11
  49. package/dist/providers/claude/agents/agents.d.ts +16 -0
  50. package/dist/providers/claude/agents/agents.js +80 -0
  51. package/dist/providers/claude/agents/constants.d.ts +3 -0
  52. package/dist/providers/claude/agents/constants.js +4 -0
  53. package/dist/providers/claude/agents/index.d.ts +1 -0
  54. package/dist/providers/claude/agents/index.js +2 -0
  55. package/dist/providers/claude/agents/types.d.ts +14 -0
  56. package/dist/providers/claude/agents/types.js +9 -0
  57. package/dist/providers/claude/claude.js +2 -0
  58. package/dist/providers/claude/history/history.model.js +2 -0
  59. package/dist/providers/claude/history/types.d.ts +115 -368
  60. package/dist/providers/claude/index.d.ts +1 -0
  61. package/dist/providers/claude/index.js +2 -0
  62. package/dist/providers/claude/transformers.js +14 -1
  63. package/dist/providers/codex/adapter.d.ts +1 -1
  64. package/dist/providers/codex/adapter.js +26 -3
  65. package/dist/providers/codex/codex.js +51 -18
  66. package/dist/providers/codex/events.d.ts +2 -1
  67. package/dist/providers/codex/events.js +8 -3
  68. package/dist/providers/codex/index.d.ts +1 -1
  69. package/dist/providers/codex/index.js +1 -1
  70. package/dist/providers/codex/rpc.d.ts +9 -4
  71. package/dist/providers/codex/rpc.js +109 -47
  72. package/dist/providers/codex/skill-roots/constants.d.ts +4 -0
  73. package/dist/providers/codex/skill-roots/constants.js +7 -0
  74. package/dist/providers/codex/skill-roots/index.d.ts +2 -0
  75. package/dist/providers/codex/skill-roots/index.js +4 -0
  76. package/dist/providers/codex/skill-roots/skill-roots.d.ts +35 -0
  77. package/dist/providers/codex/skill-roots/skill-roots.js +93 -0
  78. package/dist/providers/codex/transformers.d.ts +3 -1
  79. package/dist/providers/codex/transformers.js +41 -3
  80. package/dist/providers/codex/types.d.ts +38 -1
  81. package/dist/providers/codex/types.js +15 -3
  82. package/dist/providers/codex/websocket/constants.d.ts +11 -0
  83. package/dist/providers/codex/websocket/constants.js +18 -0
  84. package/dist/providers/codex/websocket/index.d.ts +1 -0
  85. package/dist/providers/codex/websocket/index.js +2 -0
  86. package/dist/providers/codex/websocket/websocket.d.ts +7 -0
  87. package/dist/providers/codex/websocket/websocket.js +219 -0
  88. package/dist/providers/index.d.ts +2 -2
  89. package/dist/providers/index.js +1 -1
  90. package/dist/providers/process.d.ts +2 -2
  91. package/dist/providers/process.js +37 -4
  92. package/dist/providers/registry/registry.js +2 -1
  93. package/dist/providers/types.d.ts +25 -2
  94. package/dist/runtime/runtime.js +11 -3
  95. package/dist/runtime/state/index.d.ts +1 -1
  96. package/dist/runtime/state/index.js +1 -1
  97. package/dist/runtime/state/state.d.ts +15 -0
  98. package/dist/runtime/state/state.js +92 -1
  99. package/dist/runtime/types.d.ts +0 -2
  100. package/dist/runtime/types.js +0 -3
  101. package/dist/sessions/sessions.js +2 -0
  102. package/dist/snapshots/archive/archive.d.ts +29 -0
  103. package/dist/snapshots/archive/archive.js +342 -0
  104. package/dist/snapshots/archive/constants.d.ts +5 -0
  105. package/dist/snapshots/archive/constants.js +8 -0
  106. package/dist/snapshots/archive/index.d.ts +1 -0
  107. package/dist/snapshots/archive/index.js +2 -0
  108. package/dist/snapshots/artifacts.d.ts +10 -1
  109. package/dist/snapshots/artifacts.js +38 -13
  110. package/dist/snapshots/capture.d.ts +15 -0
  111. package/dist/snapshots/capture.js +158 -0
  112. package/dist/snapshots/database.d.ts +2 -0
  113. package/dist/snapshots/database.js +35 -55
  114. package/dist/snapshots/fences.d.ts +10 -0
  115. package/dist/snapshots/fences.js +51 -0
  116. package/dist/snapshots/index.d.ts +1 -0
  117. package/dist/snapshots/index.js +2 -0
  118. package/dist/snapshots/snapshots.d.ts +7 -3
  119. package/dist/snapshots/snapshots.js +31 -117
  120. package/dist/snapshots/snapshots.worker.js +5 -1
  121. package/dist/snapshots/types.d.ts +35 -3
  122. package/dist/snapshots/types.js +19 -4
  123. package/dist/storage/index.d.ts +2 -1
  124. package/dist/storage/index.js +2 -1
  125. package/dist/storage/schema/constants.d.ts +2 -0
  126. package/dist/storage/schema/constants.js +9 -0
  127. package/dist/storage/schema/index.d.ts +3 -0
  128. package/dist/storage/schema/index.js +6 -0
  129. package/dist/storage/schema/schema.d.ts +18 -0
  130. package/dist/storage/schema/schema.js +59 -0
  131. package/dist/storage/schema/types.d.ts +7 -0
  132. package/dist/storage/schema/types.js +8 -0
  133. package/dist/storage/storage.d.ts +1 -1
  134. package/dist/storage/storage.js +2 -2
  135. package/dist/storage/types.d.ts +0 -5
  136. package/dist/storage/types.js +0 -6
  137. package/dist/store/collaboration/collaboration.model.d.ts +2 -2
  138. package/dist/store/control/types.d.ts +16 -16
  139. package/dist/store/plans/plans.model.d.ts +3 -105
  140. package/dist/store/plans/plans.model.js +6 -46
  141. package/dist/store/schema.js +7 -35
  142. package/dist/store/schema.sql +91 -16
  143. package/dist/store/sessions/index.d.ts +1 -0
  144. package/dist/store/sessions/index.js +2 -0
  145. package/dist/store/sessions/sessions.model.d.ts +28 -0
  146. package/dist/store/sessions/sessions.model.js +105 -0
  147. package/dist/store/store.js +13 -7
  148. package/dist/store/store.worker.js +16 -11
  149. package/dist/store/types.d.ts +134 -513
  150. package/dist/store/types.js +21 -7
  151. package/docs/recovery.md +8 -4
  152. package/errors/README.md +3 -3
  153. package/package.json +2 -2
  154. package/dist/plans/reconciliation.d.ts +0 -34
  155. package/dist/plans/reconciliation.js +0 -246
@@ -27,8 +27,19 @@ export const toClaudeUsageSnapshot = (result, observedAt) => {
27
27
  window: row.group === 'session' ? 'primary' : 'secondary',
28
28
  usedPercent: row.percent,
29
29
  remainingPercent: Math.max(0, 100 - row.percent),
30
- durationMinutes: null,
30
+ durationMinutes: row.group === 'session' ? 300 : row.group === 'weekly' ? 10080 : null,
31
31
  resetsAt: row.resets_at === null ? null : Date.parse(row.resets_at),
32
+ period: row.group === 'session' ? 'five-hour' : row.group === 'weekly' ? 'seven-day' : 'other',
33
+ nativeKind: row.kind,
34
+ group: row.group,
35
+ scope: row.scope
36
+ ? {
37
+ model: row.scope.model
38
+ ? { id: row.scope.model.id, displayName: row.scope.model.display_name }
39
+ : null,
40
+ surface: row.scope.surface,
41
+ }
42
+ : null,
32
43
  });
33
44
  }
34
45
  return {
@@ -37,6 +48,8 @@ export const toClaudeUsageSnapshot = (result, observedAt) => {
37
48
  observedAt,
38
49
  ordinaryUsageAllowed: null,
39
50
  windows,
51
+ credits: null,
52
+ resetCredits: null,
40
53
  state: !result.rate_limits_available || windows.length === 0
41
54
  ? 'unavailable'
42
55
  : result.rate_limits?.limits.some((row) => row.is_active && row.percent !== null && row.percent >= 100)
@@ -1,6 +1,6 @@
1
1
  import { type IAgentProviderFactory } from '../index.js';
2
2
  /**
3
- * Describes current Codex controls and lazily owns their native app-server connection.
3
+ * Describes current Codex controls and lazily owns a connection to the shared app-server daemon.
4
4
  * @returns A built-in factory that preserves native settings, authentication and permission policy.
5
5
  */
6
6
  export declare const createCodexProviderFactory: (extraSkillRoots: string[]) => IAgentProviderFactory;
@@ -10,14 +10,36 @@ import { capabilityUnavailable } from '../registry/index.js';
10
10
  import { createCodexProvider } from './codex.js';
11
11
  import { createCodexEvents, toProviderThread } from './events.js';
12
12
  /**
13
- * Describes current Codex controls and lazily owns their native app-server connection.
13
+ * Describes current Codex controls and lazily owns a connection to the shared app-server daemon.
14
14
  * @returns A built-in factory that preserves native settings, authentication and permission policy.
15
15
  */
16
16
  export const createCodexProviderFactory = (extraSkillRoots) => ({
17
17
  id: 'codex',
18
18
  async create(context) {
19
19
  const native = await createCodexProvider(extraSkillRoots, context.agentTools);
20
- native.setEvents(createCodexEvents(native, context.events));
20
+ // whether each observed session's workspace is allowed, read once per session
21
+ const allowedSessions = new Map();
22
+ let observations = Promise.resolve();
23
+ const observeSession = (nativeId, state) => {
24
+ observations = observations
25
+ .then(async () => {
26
+ let isAllowed = allowedSessions.get(nativeId);
27
+ if (isAllowed === undefined) {
28
+ const thread = await native.readThread(nativeId);
29
+ isAllowed = await resolveWorkspaceTarget(thread.workspaceRoot, context.allowedRoots)
30
+ .then(() => true)
31
+ .catch(() => false);
32
+ if (allowedSessions.size >= 1024)
33
+ allowedSessions.delete(allowedSessions.keys().next().value);
34
+ allowedSessions.set(nativeId, isAllowed);
35
+ }
36
+ if (isAllowed)
37
+ context.events.session(nativeId, state);
38
+ })
39
+ // an unreadable session stays unobserved until its next status change
40
+ .catch(() => undefined);
41
+ };
42
+ native.setEvents(createCodexEvents(native, context.events, observeSession));
21
43
  const verifyRoot = async (workspaceRoot, expectedRoot) => {
22
44
  if ((await resolveWorkspaceTarget(workspaceRoot, context.allowedRoots)) !== expectedRoot)
23
45
  throw new Exception('The HQ target is outside the allowed workspaces', {
@@ -233,6 +255,7 @@ export const createCodexProviderFactory = (extraSkillRoots) => ({
233
255
  await verifyRoot(thread.workspaceRoot, workspaceRoot);
234
256
  return {
235
257
  thread,
258
+ // handover: a session another client drives becomes adoptable once it is closed there
236
259
  canAdopt: thread.nativeState === 'notLoaded',
237
260
  canResume: thread.nativeState === 'idle',
238
261
  };
@@ -266,7 +289,7 @@ export const createCodexProviderFactory = (extraSkillRoots) => ({
266
289
  await native.cleanTerminals(`${randomUUID()}:shutdown-clean`, nativeId);
267
290
  await native.verifyTerminalsClosed(nativeId);
268
291
  },
269
- stopControl: () => native.close(),
292
+ stopControl: () => native.disconnect(),
270
293
  close: () => native.close(),
271
294
  };
272
295
  },
@@ -10,6 +10,7 @@ import { NativeBucketSchema, NativeSkillsSchema, NativeItemPageSchema, NativeThr
10
10
  import { toHistoryItem, toThreadSummary, toTurnSummary, toUsageSnapshot } from './transformers.js';
11
11
  import { parseNative } from './validations.js';
12
12
  import { toCodexModels } from './models/index.js';
13
+ import { HOST_SKILL_SCOPE, readSkillRoots, toCapabilityRoots } from './skill-roots/index.js';
13
14
  import { toCodexConfiguration, toCodexSessionSettings, readCodexConfigurationObservation, } from './configuration/index.js';
14
15
  /**
15
16
  * Connects native history, account observations and explicitly admitted runtime controls.
@@ -26,6 +27,8 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
26
27
  observedAt: null,
27
28
  ordinaryUsageAllowed: null,
28
29
  windows: [],
30
+ credits: null,
31
+ resetCredits: null,
29
32
  };
30
33
  let rpc;
31
34
  let refresh;
@@ -218,6 +221,8 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
218
221
  observedAt: null,
219
222
  ordinaryUsageAllowed: null,
220
223
  windows: [],
224
+ credits: null,
225
+ resetCredits: null,
221
226
  };
222
227
  }
223
228
  if (method === 'account/rateLimits/updated' &&
@@ -229,7 +234,7 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
229
234
  latest = { ...latest, state: latest.observedAt === null ? 'unavailable' : 'stale' };
230
235
  void readUsage();
231
236
  },
232
- }, extraSkillRoots);
237
+ });
233
238
  const connection = rpc;
234
239
  authentication = createCodexAuthentication(connection, (outcome) => events?.controlOutcome(outcome));
235
240
  return {
@@ -270,7 +275,9 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
270
275
  throw error;
271
276
  }
272
277
  },
273
- userAgent: connection.userAgent,
278
+ get userAgent() {
279
+ return connection.userAgent;
280
+ },
274
281
  get isAvailable() {
275
282
  return connection.isAvailable;
276
283
  },
@@ -392,24 +399,40 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
392
399
  kind: 'agent-unavailable',
393
400
  },
394
401
  });
402
+ // native discovery never lists a thread's capability roots, so HQ adds its own; native wins
403
+ const roots = await readSkillRoots(extraSkillRoots);
404
+ const nativeNames = new Set(entry.skills.map((skill) => skill.name));
395
405
  return {
396
- unavailableCount: entry.errors.length,
406
+ unavailableCount: entry.errors.length + roots.unavailableCount,
397
407
  observedAt: Date.now(),
398
- skills: entry.skills.map((skill) => ({
399
- name: skill.name,
400
- description: skill.description,
401
- argumentHint: null,
402
- kind: 'skill',
403
- path: skill.path,
404
- scope: skill.scope,
405
- isEnabled: skill.enabled,
406
- requiresExplicitInvocation: null,
407
- prerequisites: skill.dependencies?.tools.map((tool) => ({
408
- type: tool.type,
409
- name: tool.value,
410
- description: tool.description ?? null,
411
- })) ?? null,
412
- })),
408
+ skills: [
409
+ ...entry.skills.map((skill) => ({
410
+ name: skill.name,
411
+ description: skill.description,
412
+ argumentHint: null,
413
+ kind: 'skill',
414
+ path: skill.path,
415
+ scope: skill.scope,
416
+ isEnabled: skill.enabled,
417
+ requiresExplicitInvocation: null,
418
+ prerequisites: skill.dependencies?.tools.map((tool) => ({
419
+ type: tool.type,
420
+ name: tool.value,
421
+ description: tool.description ?? null,
422
+ })) ?? null,
423
+ })),
424
+ ...roots.skills
425
+ .filter((skill) => !nativeNames.has(skill.name))
426
+ .map((skill) => ({
427
+ ...skill,
428
+ argumentHint: null,
429
+ kind: 'skill',
430
+ scope: HOST_SKILL_SCOPE,
431
+ isEnabled: true,
432
+ requiresExplicitInvocation: null,
433
+ prerequisites: null,
434
+ })),
435
+ ],
413
436
  };
414
437
  },
415
438
  setEvents: (handlers) => {
@@ -420,6 +443,10 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
420
443
  const response = await connection.request('thread/start', {
421
444
  cwd: workspaceRoot,
422
445
  ...toCodexSessionSettings(selected),
446
+ // per-thread roots; forks inherit them, and other daemon sessions never see them
447
+ ...(extraSkillRoots.length
448
+ ? { selectedCapabilityRoots: toCapabilityRoots(extraSkillRoots) }
449
+ : {}),
423
450
  ...(agentTools
424
451
  ? {
425
452
  dynamicTools: agentTools
@@ -537,6 +564,12 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
537
564
  },
538
565
  reply: connection.reply,
539
566
  reject: connection.reject,
567
+ // a lost daemon leaves no controlled session; the next request reconnects
568
+ disconnect: async () => {
569
+ await connection.disconnect();
570
+ for (const nativeId of [...controlled])
571
+ releaseControlState(nativeId);
572
+ },
540
573
  close: async () => {
541
574
  toolLifetime.abort();
542
575
  await connection.close();
@@ -1,3 +1,4 @@
1
+ import { type ISessionState } from '../../contracts/index.js';
1
2
  import type { IAgentProviderEvents, IProviderThread } from '../index.js';
2
3
  import type { ICodexEvents, ICodexProvider, INativeThread } from './types.js';
3
4
  /** @returns Exact native session metadata normalized to the common control boundary. */
@@ -6,4 +7,4 @@ export declare const toProviderThread: (thread: INativeThread) => IProviderThrea
6
7
  * Converts Codex protocol events to provider-bound evidence without owning action ledger state.
7
8
  * @returns The callbacks installed on the native Codex connection.
8
9
  */
9
- export declare const createCodexEvents: (native: ICodexProvider, events: IAgentProviderEvents) => ICodexEvents;
10
+ export declare const createCodexEvents: (native: ICodexProvider, events: IAgentProviderEvents, observeSession: (nativeId: string, state: ISessionState) => void) => ICodexEvents;
@@ -1,10 +1,10 @@
1
1
  import { z } from 'zod';
2
- import { MAX_RESULT_BYTES } from '../../contracts/index.js';
2
+ import { MAX_RESULT_BYTES, } from '../../contracts/index.js';
3
3
  import { toTurnResult } from '../results/index.js';
4
4
  import { NativeIdSchema } from '../../contracts/identities/index.js';
5
5
  import { NativeItemSchema, NativeThreadSchema, NativeTurnSchema } from './types.js';
6
6
  import { parseNative } from './validations.js';
7
- import { toHistoryItem, toNativeLineage } from './transformers.js';
7
+ import { toHistoryItem, toNativeLineage, toSessionState } from './transformers.js';
8
8
  import { buildCodexReply, parseCodexPrompt, toApprovalPresentation } from './approvals/index.js';
9
9
  const TargetSchema = z.object({ threadId: NativeIdSchema, turnId: NativeIdSchema });
10
10
  const DeltaSchema = TargetSchema.extend({ itemId: NativeIdSchema, delta: z.string() });
@@ -22,7 +22,7 @@ export const toProviderThread = (thread) => ({
22
22
  * Converts Codex protocol events to provider-bound evidence without owning action ledger state.
23
23
  * @returns The callbacks installed on the native Codex connection.
24
24
  */
25
- export const createCodexEvents = (native, events) => {
25
+ export const createCodexEvents = (native, events, observeSession) => {
26
26
  const turns = new Map();
27
27
  return {
28
28
  controlOutcome: (outcome) => events.outcome(outcome),
@@ -121,6 +121,11 @@ export const createCodexEvents = (native, events) => {
121
121
  captured.usage = { ...usage.data.tokenUsage.last, scope: 'turn' };
122
122
  }
123
123
  }
124
+ else if (method === 'thread/status/changed') {
125
+ // the daemon broadcasts every thread's status, including sessions other clients drive
126
+ const { threadId, status } = parseNative(z.object({ threadId: NativeIdSchema, status: NativeThreadSchema.shape.status }), params);
127
+ observeSession(threadId, toSessionState(status));
128
+ }
124
129
  else if (method === 'serverRequest/resolved') {
125
130
  const { threadId, requestId } = parseNative(z.object({
126
131
  threadId: NativeIdSchema,
@@ -2,7 +2,7 @@ export { createCodexProvider } from './codex.js';
2
2
  export { createCodexProviderFactory } from './adapter.js';
3
3
  export type { ICodexProvider, ICodexEvents } from './types.js';
4
4
  export { NativeThreadSchema, NativeTurnSchema, NativeItemSchema } from './types.js';
5
- export { toHistoryItem } from './transformers.js';
5
+ export { toHistoryItem, toSessionState } from './transformers.js';
6
6
  export { parseNative } from './validations.js';
7
7
  export { parseCodexPrompt, buildCodexReply, toApprovalPresentation } from './approvals/index.js';
8
8
  export type { ICodexPrompt } from './approvals/index.js';
@@ -2,6 +2,6 @@
2
2
  export { createCodexProvider } from './codex.js';
3
3
  export { createCodexProviderFactory } from './adapter.js';
4
4
  export { NativeThreadSchema, NativeTurnSchema, NativeItemSchema } from './types.js';
5
- export { toHistoryItem } from './transformers.js';
5
+ export { toHistoryItem, toSessionState } from './transformers.js';
6
6
  export { parseNative } from './validations.js';
7
7
  export { parseCodexPrompt, buildCodexReply, toApprovalPresentation } from './approvals/index.js';
@@ -1,5 +1,8 @@
1
1
  /**
2
- * Connects to the installed CLI's stdio app-server with bounded pending requests.
2
+ * Connects to the installed CLI's shared app-server daemon through its stdio proxy, starting the
3
+ * daemon when no terminal session has, with bounded pending requests. The daemon's control socket
4
+ * speaks WebSocket, which the proxy forwards as raw bytes. When the daemon restarts, the lost
5
+ * connection's requests fail and the next request reconnects; nothing is sent again.
3
6
  * @returns An initialized transport with exact action IDs and late-response callbacks.
4
7
  * @throws
5
8
  * - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
@@ -10,11 +13,13 @@ export declare const createCodexRpc: (handlers: {
10
13
  request(id: string | number, method: string, params: unknown): void;
11
14
  lateResponse(id: string, result: unknown, error: unknown): void;
12
15
  unavailable(): void;
13
- }, extraSkillRoots?: string[]) => Promise<{
14
- userAgent: string | null;
16
+ }) => Promise<{
17
+ readonly userAgent: string | null;
15
18
  readonly isAvailable: boolean;
16
- request: (method: string, params: unknown, actionRequestId?: string) => Promise<unknown>;
19
+ request(method: string, params: unknown, actionRequestId?: string): Promise<unknown>;
17
20
  reply: (id: string | number, result: unknown) => Promise<void>;
18
21
  reject: (id: string | number) => Promise<void>;
22
+ /** Stops the current transport; the next request opens a new one. */
23
+ disconnect(): Promise<void>;
19
24
  close(): Promise<void>;
20
25
  }>;
@@ -1,7 +1,11 @@
1
+ import { execFile } from 'node:child_process';
1
2
  import { readFile } from 'node:fs/promises';
3
+ import { promisify } from 'node:util';
2
4
  import { Exception, extractMessage } from 'jg-exception';
3
5
  import { z } from 'zod';
4
6
  import { createProviderProcess } from '../index.js';
7
+ import { createWebSocketFraming } from './websocket/index.js';
8
+ const run = promisify(execFile);
5
9
  const EnvelopeSchema = z.object({
6
10
  id: z.union([z.number().int(), z.string()]).optional(),
7
11
  method: z.string().optional(),
@@ -10,17 +14,21 @@ const EnvelopeSchema = z.object({
10
14
  error: z.object({ code: z.number(), message: z.string() }).optional(),
11
15
  });
12
16
  /**
13
- * Connects to the installed CLI's stdio app-server with bounded pending requests.
17
+ * Connects to the installed CLI's shared app-server daemon through its stdio proxy, starting the
18
+ * daemon when no terminal session has, with bounded pending requests. The daemon's control socket
19
+ * speaks WebSocket, which the proxy forwards as raw bytes. When the daemon restarts, the lost
20
+ * connection's requests fail and the next request reconnects; nothing is sent again.
14
21
  * @returns An initialized transport with exact action IDs and late-response callbacks.
15
22
  * @throws
16
23
  * - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
17
24
  * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
18
25
  */
19
- export const createCodexRpc = async (handlers, extraSkillRoots = []) => {
26
+ export const createCodexRpc = async (handlers) => {
20
27
  const manifest = z
21
28
  .object({ version: z.string() })
22
29
  .parse(JSON.parse(await readFile(new URL('../../../package.json', import.meta.url), 'utf8')));
23
30
  let sequence = 0;
31
+ let isClosed = false;
24
32
  const pending = new Map();
25
33
  const stopped = (cause) => {
26
34
  handlers.unavailable();
@@ -34,7 +42,7 @@ export const createCodexRpc = async (handlers, extraSkillRoots = []) => {
34
42
  }
35
43
  pending.clear();
36
44
  };
37
- const transport = createProviderProcess('codex', ['app-server', '--listen', 'stdio://'], (message) => {
45
+ const receive = (message) => {
38
46
  const parsed = EnvelopeSchema.safeParse(message);
39
47
  if (!parsed.success)
40
48
  throw new Exception('The Codex integration failed', {
@@ -76,8 +84,14 @@ export const createCodexRpc = async (handlers, extraSkillRoots = []) => {
76
84
  }));
77
85
  else
78
86
  entry.resolve(envelope.result);
79
- }, stopped);
80
- const request = async (method, params, actionRequestId) => {
87
+ };
88
+ /**
89
+ * Sends one request on the given transport and waits for its response.
90
+ * @returns The native result.
91
+ * @throws
92
+ * - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
93
+ */
94
+ const send = (transport, method, params, actionRequestId) => {
81
95
  if (!transport.isRunning || pending.size >= 32)
82
96
  throw new Exception('The Codex integration failed', {
83
97
  code: 'JG_AGENT_HQ_CODEX_FAILED',
@@ -114,58 +128,106 @@ export const createCodexRpc = async (handlers, extraSkillRoots = []) => {
114
128
  });
115
129
  });
116
130
  };
117
- try {
118
- const initialized = z
119
- .object({ userAgent: z.string().max(4096).nullable().optional().catch(null) })
120
- .safeParse(await request('initialize', {
121
- clientInfo: { name: 'jg_agent_hq', title: 'JG Agent HQ', version: manifest.version },
122
- capabilities: { experimentalApi: true },
123
- }));
124
- if (!initialized.success)
125
- throw new Exception('The Codex integration failed', {
131
+ /**
132
+ * Opens and initializes one proxy connection; terminal sessions and HQ share one daemon,
133
+ * which outlives it.
134
+ * @returns The open transport and the daemon's user agent.
135
+ * @throws
136
+ * - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
137
+ * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
138
+ */
139
+ const open = async () => {
140
+ try {
141
+ await run('codex', ['app-server', 'daemon', 'start'], { timeout: 30_000, maxBuffer: 65_536 });
142
+ }
143
+ catch (cause) {
144
+ throw new Exception(`The Codex integration failed: ${extractMessage(cause)}`, {
126
145
  code: 'JG_AGENT_HQ_CODEX_FAILED',
127
146
  data: { kind: 'agent-unavailable' },
128
- cause: initialized.error,
147
+ cause,
129
148
  });
130
- await transport.write({ method: 'initialized', params: {} });
131
- if (extraSkillRoots.length) {
132
- const roots = z
133
- .object({})
134
- .safeParse(await request('skills/extraRoots/set', { extraRoots: extraSkillRoots }));
135
- if (!roots.success)
149
+ }
150
+ const transport = createProviderProcess('codex', ['app-server', 'proxy'], receive, stopped, undefined, createWebSocketFraming());
151
+ try {
152
+ const initialized = z
153
+ .object({ userAgent: z.string().max(4096).nullable().optional().catch(null) })
154
+ .safeParse(await send(transport, 'initialize', {
155
+ clientInfo: { name: 'jg_agent_hq', title: 'JG Agent HQ', version: manifest.version },
156
+ capabilities: { experimentalApi: true },
157
+ }));
158
+ if (!initialized.success)
136
159
  throw new Exception('The Codex integration failed', {
137
160
  code: 'JG_AGENT_HQ_CODEX_FAILED',
138
161
  data: { kind: 'agent-unavailable' },
139
- cause: roots.error,
162
+ cause: initialized.error,
140
163
  });
164
+ await transport.write({ method: 'initialized', params: {} });
165
+ return { transport, userAgent: initialized.data.userAgent ?? null };
141
166
  }
142
- return {
143
- userAgent: initialized.data.userAgent ?? null,
144
- get isAvailable() {
145
- return transport.isRunning;
146
- },
147
- request,
148
- reply: (id, result) => transport.write({ id, result }),
149
- reject: (id) => transport.write({ id, error: { code: -32601, message: 'Unsupported request' } }),
150
- async close() {
151
- stopped(new Exception('The Codex integration failed: connection closed', {
152
- code: 'JG_AGENT_HQ_CODEX_FAILED',
153
- }));
167
+ catch (error) {
168
+ try {
154
169
  await transport.close();
155
- },
156
- };
157
- }
158
- catch (error) {
159
- try {
160
- await transport.close();
170
+ }
171
+ catch (cleanup) {
172
+ throw new Exception(`The Codex integration failed: ${extractMessage(cleanup)}`, {
173
+ code: 'JG_AGENT_HQ_CODEX_FAILED',
174
+ data: { kind: 'agent-unavailable', cleanupUnconfirmed: true },
175
+ cause: error,
176
+ });
177
+ }
178
+ throw error;
161
179
  }
162
- catch (cleanup) {
163
- throw new Exception(`The Codex integration failed: ${extractMessage(cleanup)}`, {
180
+ };
181
+ let connection = await open();
182
+ let reopening;
183
+ /**
184
+ * Reconnects once after the transport stopped, sharing one attempt between callers.
185
+ * @throws
186
+ * - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
187
+ * - JG_AGENT_HQ_TRANSPORT_FAILED: The HQ transport failed
188
+ */
189
+ const ensureOpen = async () => {
190
+ if (connection.transport.isRunning)
191
+ return;
192
+ if (isClosed)
193
+ throw new Exception('The Codex integration failed: connection closed', {
164
194
  code: 'JG_AGENT_HQ_CODEX_FAILED',
165
- data: { kind: 'agent-unavailable', cleanupUnconfirmed: true },
166
- cause: error,
195
+ data: { kind: 'agent-unavailable' },
167
196
  });
168
- }
169
- throw error;
170
- }
197
+ reopening ??= (async () => {
198
+ try {
199
+ connection = await open();
200
+ }
201
+ finally {
202
+ reopening = undefined;
203
+ }
204
+ })();
205
+ await reopening;
206
+ };
207
+ return {
208
+ get userAgent() {
209
+ return connection.userAgent;
210
+ },
211
+ // false while disconnected; the next request reconnects until the connection is closed
212
+ get isAvailable() {
213
+ return connection.transport.isRunning;
214
+ },
215
+ async request(method, params, actionRequestId) {
216
+ await ensureOpen();
217
+ return send(connection.transport, method, params, actionRequestId);
218
+ },
219
+ reply: (id, result) => connection.transport.write({ id, result }),
220
+ reject: (id) => connection.transport.write({ id, error: { code: -32601, message: 'Unsupported request' } }),
221
+ /** Stops the current transport; the next request opens a new one. */
222
+ async disconnect() {
223
+ await connection.transport.close();
224
+ },
225
+ async close() {
226
+ isClosed = true;
227
+ stopped(new Exception('The Codex integration failed: connection closed', {
228
+ code: 'JG_AGENT_HQ_CODEX_FAILED',
229
+ }));
230
+ await connection.transport.close();
231
+ },
232
+ };
171
233
  };
@@ -0,0 +1,4 @@
1
+ export declare const LOCAL_ENVIRONMENT_ID = "local";
2
+ export declare const MAX_ROOT_SKILLS = 128;
3
+ export declare const MAX_SKILL_FILE_BYTES = 65536;
4
+ export declare const HOST_SKILL_SCOPE = "host";
@@ -0,0 +1,7 @@
1
+ // Codex resolves capability roots in an execution environment; local threads use this one
2
+ export const LOCAL_ENVIRONMENT_ID = 'local';
3
+ // bounded inventory read from each operator-supplied root
4
+ export const MAX_ROOT_SKILLS = 128;
5
+ export const MAX_SKILL_FILE_BYTES = 65_536;
6
+ // catalog scope for skills HQ adds from its extra roots, which native discovery doesn't list
7
+ export const HOST_SKILL_SCOPE = 'host';
@@ -0,0 +1,2 @@
1
+ export { HOST_SKILL_SCOPE } from './constants.js';
2
+ export { parseSkillFrontmatter, readSkillRoots, toCapabilityRoots } from './skill-roots.js';
@@ -0,0 +1,4 @@
1
+ // constants
2
+ export { HOST_SKILL_SCOPE } from './constants.js';
3
+ // skill roots
4
+ export { parseSkillFrontmatter, readSkillRoots, toCapabilityRoots } from './skill-roots.js';
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Reads a skill's single-line `name` and `description` frontmatter, the only fields HQ takes from
3
+ * skill files.
4
+ * @returns The skill identity, or null when the frontmatter is missing or not plain single-line.
5
+ */
6
+ export declare const parseSkillFrontmatter: (source: string) => {
7
+ name: string;
8
+ description: string;
9
+ } | null;
10
+ /**
11
+ * Builds the per-thread capability roots Codex resolves for a thread HQ starts, so HQ's skills
12
+ * never reach other sessions on the shared daemon.
13
+ * @returns One local-environment root per operator-supplied directory.
14
+ */
15
+ export declare const toCapabilityRoots: (roots: string[]) => {
16
+ id: string;
17
+ location: {
18
+ type: string;
19
+ environmentId: string;
20
+ path: string;
21
+ };
22
+ }[];
23
+ /**
24
+ * Lists the skills in operator-supplied roots, one directory per skill holding a regular
25
+ * `SKILL.md`. Linked directories and files are not followed.
26
+ * @returns The readable skills and how many entries could not be read.
27
+ */
28
+ export declare const readSkillRoots: (roots: string[]) => Promise<{
29
+ skills: {
30
+ name: string;
31
+ description: string;
32
+ path: string;
33
+ }[];
34
+ unavailableCount: number;
35
+ }>;