jg-agent-hq 5.0.0 → 6.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 (53) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +2 -2
  3. package/api/README.md +12 -8
  4. package/dist/actions/actions.d.ts +2 -2
  5. package/dist/actions/actions.js +14 -2
  6. package/dist/cli/cli.js +2 -1
  7. package/dist/contracts/browser/types.d.ts +1 -0
  8. package/dist/contracts/index.d.ts +2 -2
  9. package/dist/contracts/index.js +1 -1
  10. package/dist/contracts/types.d.ts +227 -0
  11. package/dist/contracts/types.js +21 -1
  12. package/dist/providers/claude/agents/agents.d.ts +7 -5
  13. package/dist/providers/claude/agents/agents.js +29 -20
  14. package/dist/providers/claude/agents/types.d.ts +6 -0
  15. package/dist/providers/claude/agents/types.js +5 -0
  16. package/dist/providers/claude/control/stream.js +3 -0
  17. package/dist/providers/claude/history/history.model.js +27 -15
  18. package/dist/providers/claude/history/types.d.ts +76 -1
  19. package/dist/providers/claude/history/types.js +1 -1
  20. package/dist/providers/claude/history/utilities.d.ts +2 -1
  21. package/dist/providers/claude/history/utilities.js +4 -1
  22. package/dist/providers/codex/adapter.js +40 -15
  23. package/dist/providers/codex/codex.js +50 -16
  24. package/dist/providers/codex/constants.d.ts +5 -0
  25. package/dist/providers/codex/constants.js +8 -0
  26. package/dist/providers/codex/events.d.ts +1 -1
  27. package/dist/providers/codex/events.js +14 -3
  28. package/dist/providers/codex/rpc.d.ts +1 -0
  29. package/dist/providers/codex/rpc.js +1 -0
  30. package/dist/providers/codex/transformers.d.ts +5 -2
  31. package/dist/providers/codex/transformers.js +11 -2
  32. package/dist/providers/codex/types.d.ts +3 -0
  33. package/dist/providers/index.d.ts +1 -1
  34. package/dist/providers/index.js +1 -1
  35. package/dist/providers/process.d.ts +5 -0
  36. package/dist/providers/process.js +12 -0
  37. package/dist/providers/types.d.ts +6 -0
  38. package/dist/runtime/runtime.js +10 -5
  39. package/dist/sessions/index.d.ts +2 -1
  40. package/dist/sessions/index.js +1 -2
  41. package/dist/sessions/sessions.d.ts +15 -4
  42. package/dist/sessions/sessions.js +72 -8
  43. package/dist/sessions/types.d.ts +5 -1
  44. package/dist/store/control/constants.d.ts +1 -0
  45. package/dist/store/control/constants.js +8 -0
  46. package/dist/store/control/control.model.d.ts +14 -0
  47. package/dist/store/control/control.model.js +32 -1
  48. package/dist/store/sessions/sessions.model.js +11 -4
  49. package/dist/store/store.js +5 -0
  50. package/dist/store/store.worker.js +9 -0
  51. package/dist/store/types.d.ts +68 -0
  52. package/dist/store/types.js +12 -0
  53. package/package.json +1 -1
@@ -119,8 +119,18 @@ export const HqRequestSchema = z.discriminatedUnion('kind', [
119
119
  limit: z.number().int().min(1).max(128).default(32),
120
120
  }),
121
121
  z.strictObject({ kind: z.literal('active-sessions') }),
122
+ z.strictObject({
123
+ kind: z.literal('unstarted-threads'),
124
+ provider: TargetFields.provider,
125
+ workspaceRoot: TargetFields.workspaceRoot,
126
+ }),
122
127
  z.strictObject({ kind: z.literal('observation-pace'), pace: ObservationPaceSchema }),
123
128
  ]);
129
+ // how a terminal runs a Claude session: in its own window, or in Claude Code's background service
130
+ export const SessionTerminalSchema = z.discriminatedUnion('kind', [
131
+ z.object({ kind: z.literal('interactive') }),
132
+ z.object({ kind: z.literal('background'), attachId: z.string().min(1).max(64) }),
133
+ ]);
124
134
  // native discovery is external/read-only until explicitly adopted for control
125
135
  export const ThreadSummarySchema = z.object({
126
136
  provider: ProviderIdSchema,
@@ -135,12 +145,19 @@ export const ThreadSummarySchema = z.object({
135
145
  ownership: z.enum(['external', 'managed', 'uncertain']),
136
146
  managedId: z.uuid().nullable(),
137
147
  historyState: z.enum(['available', 'unavailable']),
148
+ // the terminal that runs the session, while one does; always null for Codex
149
+ terminal: SessionTerminalSchema.nullable(),
138
150
  });
139
151
  // every running and waiting session, newest state change first, with whether more are active
140
152
  export const ActiveSessionsSchema = z.object({
141
153
  data: z.array(ThreadSummarySchema).max(MAX_PAGE_SIZE),
142
154
  isTruncated: z.boolean(),
143
155
  });
156
+ // one workspace's managed threads that no turn has started yet, newest first, with whether more exist
157
+ export const UnstartedThreadsSchema = z.object({
158
+ data: z.array(ThreadSummarySchema).max(DEFAULT_PAGE_SIZE),
159
+ isTruncated: z.boolean(),
160
+ });
144
161
  export const TurnSummarySchema = z.object({
145
162
  nativeId: NativeIdSchema,
146
163
  state: z.enum(['completed', 'interrupted', 'failed', 'inProgress', 'unknown']),
@@ -157,7 +174,8 @@ export const HistoryFileSchema = z.object({
157
174
  * Explicit presentation fields; unknown native item kinds are labeled unsupported. `callId` pairs
158
175
  * a tool call with its result, `outcome` is what the provider recorded, null when unknown or
159
176
  * running, and `files` lists a file change's files; both come from the full record, so cutting
160
- * the text never changes them.
177
+ * the text never changes them. `createdAt` is the item's time in Unix milliseconds, or null when
178
+ * the provider records none.
161
179
  */
162
180
  export const HistoryItemSchema = z.object({
163
181
  nativeId: NativeIdSchema,
@@ -170,6 +188,7 @@ export const HistoryItemSchema = z.object({
170
188
  callId: z.string().min(1).max(4096).nullable(),
171
189
  outcome: z.enum(['succeeded', 'failed']).nullable(),
172
190
  files: z.array(HistoryFileSchema).max(MAX_PAGE_SIZE),
191
+ createdAt: z.number().int().nullable(),
173
192
  });
174
193
  export const LiveItemsSchema = z.object({
175
194
  revision: z.number().int().nonnegative(),
@@ -323,6 +342,7 @@ export const HqResponseSchema = z.discriminatedUnion('kind', [
323
342
  z.object({ kind: z.literal('live-items'), result: LiveItemsSchema }),
324
343
  z.object({ kind: z.literal('session-states'), result: SessionTransitionPageSchema }),
325
344
  z.object({ kind: z.literal('active-sessions'), result: ActiveSessionsSchema }),
345
+ z.object({ kind: z.literal('unstarted-threads'), result: UnstartedThreadsSchema }),
326
346
  z.object({
327
347
  kind: z.literal('observation-pace'),
328
348
  result: z.object({ pace: ObservationPaceSchema }),
@@ -1,8 +1,9 @@
1
- import type { IObservationPace, ISessionState } from '../../../contracts/index.js';
1
+ import type { IObservationPace, ISessionState, ISessionTerminal } from '../../../contracts/index.js';
2
2
  import { type IClaudeAgent } from './types.js';
3
3
  /**
4
- * Maps a native report to the shared session state: an interactive session reports `waiting` on a
5
- * question or permission prompt, and a background one `blocked`.
4
+ * Maps a running session's report to the shared session state. A session waiting on a question or
5
+ * a permission prompt reports `status: "waiting"`, as an interactive one may also report
6
+ * `blocked`; a background session at work reports `state: "working"` and no status.
6
7
  */
7
8
  export declare const toAgentState: (agent: IClaudeAgent) => ISessionState;
8
9
  /**
@@ -10,8 +11,8 @@ export declare const toAgentState: (agent: IClaudeAgent) => ISessionState;
10
11
  * sessions inside the allowed workspaces, so a session missing from a run is closed. A failed,
11
12
  * late, oversized or malformed run changes nothing. Runs follow one another at the `background`
12
13
  * pace until `setPace` selects another, which takes effect with an immediate run.
13
- * @returns A handle that sets the pace, reports each listed session's `cwd` from the latest run,
14
- * and whose close stops polling and waits for a run in progress.
14
+ * @returns A handle that sets the pace, reports each listed session's `cwd` and the terminal that
15
+ * runs it from the latest run, and whose close stops polling and waits for a run in progress.
15
16
  */
16
17
  export declare const observeClaudeAgents: (record: (sessions: {
17
18
  nativeId: string;
@@ -19,5 +20,6 @@ export declare const observeClaudeAgents: (record: (sessions: {
19
20
  }[]) => Promise<void>, allowedRoots: string[]) => {
20
21
  setPace(pace: IObservationPace): void;
21
22
  workspaceOf(nativeId: string): string | undefined;
23
+ terminalOf(nativeId: string): ISessionTerminal | null;
22
24
  close(): Promise<void>;
23
25
  };
@@ -1,38 +1,37 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
3
  import { delay } from 'jg-utilities';
4
+ import { isOwnedProcess } from '../../process.js';
4
5
  import { resolveWorkspaceTarget } from '../../../runtime/state/index.js';
5
6
  import { AGENTS_BACKGROUND_SECONDS, AGENTS_DEADLINE_MS, AGENTS_LIVE_SECONDS, AGENTS_OUTPUT_BYTES, } from './constants.js';
6
7
  import { ClaudeAgentsSchema } from './types.js';
7
8
  const run = promisify(execFile);
8
9
  /**
9
- * Maps a native report to the shared session state: an interactive session reports `waiting` on a
10
- * question or permission prompt, and a background one `blocked`.
10
+ * Maps a running session's report to the shared session state. A session waiting on a question or
11
+ * a permission prompt reports `status: "waiting"`, as an interactive one may also report
12
+ * `blocked`; a background session at work reports `state: "working"` and no status.
11
13
  */
12
- export const toAgentState = (agent) => {
13
- const reported = agent.status ?? agent.state;
14
- return reported === 'busy'
15
- ? 'running'
16
- : reported === 'waiting' || reported === 'blocked'
17
- ? 'waiting'
18
- : reported === 'idle'
19
- ? 'idle'
20
- : 'unknown';
21
- };
14
+ export const toAgentState = (agent) => agent.status === 'busy' || agent.state === 'working'
15
+ ? 'running'
16
+ : agent.status === 'waiting' || agent.status === 'blocked'
17
+ ? 'waiting'
18
+ : agent.status === 'idle'
19
+ ? 'idle'
20
+ : 'unknown';
22
21
  /**
23
22
  * Polls `claude agents --json` while the runtime runs and records the complete list of active
24
23
  * sessions inside the allowed workspaces, so a session missing from a run is closed. A failed,
25
24
  * late, oversized or malformed run changes nothing. Runs follow one another at the `background`
26
25
  * pace until `setPace` selects another, which takes effect with an immediate run.
27
- * @returns A handle that sets the pace, reports each listed session's `cwd` from the latest run,
28
- * and whose close stops polling and waits for a run in progress.
26
+ * @returns A handle that sets the pace, reports each listed session's `cwd` and the terminal that
27
+ * runs it from the latest run, and whose close stops polling and waits for a run in progress.
29
28
  */
30
29
  export const observeClaudeAgents = (record, allowedRoots) => {
31
30
  const lifetime = new AbortController();
32
31
  // whether each session directory is inside an allowed workspace, checked once per directory
33
32
  const allowedDirectories = new Map();
34
- // the cwd of each session the latest run listed, which no other source reports
35
- let workspaces = new Map();
33
+ // the cwd and terminal of each session the latest run listed, which no other source reports
34
+ let listedSessions = new Map();
36
35
  let pace = 'background';
37
36
  let wait = new AbortController();
38
37
  const isAllowed = async (directory) => {
@@ -62,14 +61,23 @@ export const observeClaudeAgents = (record, allowedRoots) => {
62
61
  }
63
62
  const sessions = [];
64
63
  const listed = new Map();
64
+ /*
65
+ * An entry without a PID isn't running, whatever its state says, so it counts as missing; the
66
+ * processes this runtime started, managed sessions and the metadata process, are its own.
67
+ */
65
68
  for (const agent of agents)
66
- if (await isAllowed(agent.cwd)) {
69
+ if (agent.pid !== undefined && !isOwnedProcess(agent.pid) && (await isAllowed(agent.cwd))) {
67
70
  sessions.push({ nativeId: agent.sessionId, state: toAgentState(agent) });
68
- listed.set(agent.sessionId, agent.cwd);
71
+ listed.set(agent.sessionId, {
72
+ cwd: agent.cwd,
73
+ terminal: agent.kind === 'background' && agent.id
74
+ ? { kind: 'background', attachId: agent.id }
75
+ : { kind: 'interactive' },
76
+ });
69
77
  }
70
78
  if (lifetime.signal.aborted)
71
79
  return;
72
- workspaces = listed;
80
+ listedSessions = listed;
73
81
  await record(sessions);
74
82
  };
75
83
  const running = (async () => {
@@ -88,7 +96,8 @@ export const observeClaudeAgents = (record, allowedRoots) => {
88
96
  pace = next;
89
97
  wait.abort();
90
98
  },
91
- workspaceOf: (nativeId) => workspaces.get(nativeId),
99
+ workspaceOf: (nativeId) => listedSessions.get(nativeId)?.cwd,
100
+ terminalOf: (nativeId) => listedSessions.get(nativeId)?.terminal ?? null,
92
101
  async close() {
93
102
  lifetime.abort();
94
103
  await running;
@@ -1,14 +1,20 @@
1
1
  import { z } from 'zod';
2
2
  export declare const ClaudeAgentSchema: z.ZodObject<{
3
+ id: z.ZodOptional<z.ZodString>;
4
+ kind: z.ZodOptional<z.ZodString>;
3
5
  sessionId: z.ZodString;
4
6
  cwd: z.ZodString;
7
+ pid: z.ZodOptional<z.ZodNumber>;
5
8
  status: z.ZodOptional<z.ZodString>;
6
9
  state: z.ZodOptional<z.ZodString>;
7
10
  }, z.core.$strip>;
8
11
  export type IClaudeAgent = z.infer<typeof ClaudeAgentSchema>;
9
12
  export declare const ClaudeAgentsSchema: z.ZodArray<z.ZodObject<{
13
+ id: z.ZodOptional<z.ZodString>;
14
+ kind: z.ZodOptional<z.ZodString>;
10
15
  sessionId: z.ZodString;
11
16
  cwd: z.ZodString;
17
+ pid: z.ZodOptional<z.ZodNumber>;
12
18
  status: z.ZodOptional<z.ZodString>;
13
19
  state: z.ZodOptional<z.ZodString>;
14
20
  }, z.core.$strip>>;
@@ -1,8 +1,13 @@
1
1
  import { z } from 'zod';
2
2
  // one active session; interactive entries report a status and background entries a state
3
3
  export const ClaudeAgentSchema = z.object({
4
+ // the short ID `claude attach` takes, which only background sessions report
5
+ id: z.string().min(1).max(64).optional(),
6
+ kind: z.string().max(64).optional(),
4
7
  sessionId: z.string().min(1).max(4096),
5
8
  cwd: z.string().min(1).max(4096),
9
+ // present only while the session's process runs
10
+ pid: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
6
11
  status: z.string().max(64).optional(),
7
12
  state: z.string().max(64).optional(),
8
13
  });
@@ -109,6 +109,8 @@ export const receiveClaudeMessage = (session, raw, events) => {
109
109
  uuid: message.uuid,
110
110
  message: message.message,
111
111
  toolUseResult: message.tool_use_result,
112
+ // a live item is timed when its frame arrives
113
+ timestamp: new Date().toISOString(),
112
114
  }), input.id);
113
115
  // final wrappers may share an API message ID while containing different content blocks
114
116
  const content = z
@@ -180,6 +182,7 @@ export const receiveClaudeMessage = (session, raw, events) => {
180
182
  type: 'assistant',
181
183
  uuid: id,
182
184
  message: { role: 'assistant', content: [block.content_block] },
185
+ timestamp: new Date().toISOString(),
183
186
  }, input.id);
184
187
  // a block the CLI leaves out, such as thinking, has no preview to show or replace
185
188
  if (preview) {
@@ -97,10 +97,10 @@ export class ClaudeHistoryModel {
97
97
  const rows = this.__database
98
98
  .prepare(`SELECT native_id, workspace_root, identity, file_size, byte_offset, revision,
99
99
  leaf_id, name, created_at, updated_at, supported, workspace_state FROM hq_claude_file
100
- WHERE workspace_root = ? AND workspace_state = 'matching' AND (? IS NULL OR created_at < ? OR (created_at = ? AND native_id < ?))
100
+ WHERE workspace_root = ? AND workspace_state = 'matching' AND (? IS NULL OR updated_at < ? OR (updated_at = ? AND native_id < ?))
101
101
  AND (? IS NULL OR instr(lower(coalesce(name, '')), lower(?)) > 0)
102
- ORDER BY created_at DESC, native_id DESC LIMIT ?`)
103
- .all(root, seek?.createdAt ?? null, seek?.createdAt ?? null, seek?.createdAt ?? null, seek?.nativeId ?? null, command.search ?? null, command.search ?? null, command.limit + 1)
102
+ ORDER BY updated_at DESC, native_id DESC LIMIT ?`)
103
+ .all(root, seek?.updatedAt ?? null, seek?.updatedAt ?? null, seek?.updatedAt ?? null, seek?.nativeId ?? null, command.search ?? null, command.search ?? null, command.limit + 1)
104
104
  .map((row) => FileRowSchema.parse(row));
105
105
  const page = rows.slice(0, command.limit);
106
106
  const last = page.at(-1);
@@ -110,7 +110,7 @@ export class ClaudeHistoryModel {
110
110
  data: page.map((row) => this.__summary(row)),
111
111
  source: 'native',
112
112
  nextCursor: encodeHistoryCursor(rows.length > command.limit && last
113
- ? JSON.stringify({ createdAt: last.created_at, nativeId: last.native_id })
113
+ ? JSON.stringify({ updatedAt: last.updated_at, nativeId: last.native_id })
114
114
  : null, filters),
115
115
  },
116
116
  });
@@ -231,8 +231,9 @@ export class ClaudeHistoryModel {
231
231
  updatedAt: row.updated_at,
232
232
  nativeState: 'unknown',
233
233
  nativeLineage: { sessionId: row.native_id, parentThreadId: null, forkedFromId: null },
234
- // claude agents observations supply the live state
234
+ // claude agents observations supply the live state and the terminal that runs it
235
235
  state: 'unknown',
236
+ terminal: null,
236
237
  ownership: 'external',
237
238
  managedId: null,
238
239
  historyState: row.supported === 1 ? 'available' : 'unavailable',
@@ -408,12 +409,19 @@ export class ClaudeHistoryModel {
408
409
  row.updated_at = Math.max(row.updated_at, Math.trunc(stat.mtimeMs));
409
410
  let position = row.byte_offset;
410
411
  let lineStart = position;
411
- let tail = Buffer.alloc(0);
412
412
  const chunk = Buffer.alloc(65_536);
413
413
  // hidden records whose parent comes later in the file, by location and awaited parent
414
414
  const heldBack = [];
415
+ /*
416
+ * A record read again, because it spans chunks or was held back, lands in one buffer that
417
+ * grows to the longest such record. Each read replaces the last one's bytes, which
418
+ * `__record` has decoded by then.
419
+ */
420
+ let spill = Buffer.alloc(0);
415
421
  const reread = (offset, length) => {
416
- const bytes = Buffer.alloc(length);
422
+ if (spill.length < length)
423
+ spill = Buffer.allocUnsafe(length);
424
+ const bytes = spill.subarray(0, length);
417
425
  if (readSync(fd, bytes, 0, length, offset) !== length)
418
426
  this.__unavailable();
419
427
  return bytes;
@@ -441,18 +449,22 @@ export class ClaudeHistoryModel {
441
449
  const count = readSync(fd, chunk, 0, Math.min(chunk.length, stat.size - position, remaining()), position);
442
450
  if (count === 0)
443
451
  break;
452
+ const chunkStart = position;
444
453
  position += count;
445
454
  consume(count);
446
- tail = Buffer.concat([tail, chunk.subarray(0, count)]);
447
- for (let end = tail.indexOf(10); end !== -1; end = tail.indexOf(10)) {
448
- if (end > MAX_RECORD_BYTES)
455
+ // a record that started in an earlier chunk is read again whole, not joined from chunks
456
+ const read = chunk.subarray(0, count);
457
+ for (let end = read.indexOf(10); end !== -1; end = read.indexOf(10, end + 1)) {
458
+ const length = chunkStart + end - lineStart;
459
+ if (length > MAX_RECORD_BYTES)
449
460
  this.__unavailable();
450
- if (end > 0)
451
- indexRecord(tail.subarray(0, end), lineStart);
452
- lineStart += end + 1;
453
- tail = tail.subarray(end + 1);
461
+ if (length > 0)
462
+ indexRecord(lineStart >= chunkStart
463
+ ? read.subarray(lineStart - chunkStart, end)
464
+ : reread(lineStart, length), lineStart);
465
+ lineStart = chunkStart + end + 1;
454
466
  }
455
- if (tail.length > MAX_RECORD_BYTES)
467
+ if (position - lineStart > MAX_RECORD_BYTES)
456
468
  this.__unavailable();
457
469
  }
458
470
  /*
@@ -105,6 +105,12 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
105
105
  unavailable: "unavailable";
106
106
  available: "available";
107
107
  }>;
108
+ terminal: z.ZodNullable<z.ZodDiscriminatedUnion<[z.ZodObject<{
109
+ kind: z.ZodLiteral<"interactive">;
110
+ }, z.core.$strip>, z.ZodObject<{
111
+ kind: z.ZodLiteral<"background">;
112
+ attachId: z.ZodString;
113
+ }, z.core.$strip>], "kind">>;
108
114
  isNameTruncated: z.ZodBoolean;
109
115
  }, z.core.$strip>>;
110
116
  nextCursor: z.ZodNullable<z.ZodString>;
@@ -3840,6 +3846,12 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
3840
3846
  unavailable: "unavailable";
3841
3847
  available: "available";
3842
3848
  }>;
3849
+ terminal: z.ZodNullable<z.ZodDiscriminatedUnion<[z.ZodObject<{
3850
+ kind: z.ZodLiteral<"interactive">;
3851
+ }, z.core.$strip>, z.ZodObject<{
3852
+ kind: z.ZodLiteral<"background">;
3853
+ attachId: z.ZodString;
3854
+ }, z.core.$strip>], "kind">>;
3843
3855
  }, z.core.$strip>>;
3844
3856
  }, z.core.$strip>;
3845
3857
  }, z.core.$strip>, z.ZodObject<{
@@ -3881,6 +3893,12 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
3881
3893
  unavailable: "unavailable";
3882
3894
  available: "available";
3883
3895
  }>;
3896
+ terminal: z.ZodNullable<z.ZodDiscriminatedUnion<[z.ZodObject<{
3897
+ kind: z.ZodLiteral<"interactive">;
3898
+ }, z.core.$strip>, z.ZodObject<{
3899
+ kind: z.ZodLiteral<"background">;
3900
+ attachId: z.ZodString;
3901
+ }, z.core.$strip>], "kind">>;
3884
3902
  }, z.core.$strip>;
3885
3903
  }, z.core.$strip>, z.ZodObject<{
3886
3904
  kind: z.ZodLiteral<"turns">;
@@ -3951,6 +3969,7 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
3951
3969
  added: z.ZodNumber;
3952
3970
  removed: z.ZodNumber;
3953
3971
  }, z.core.$strip>>;
3972
+ createdAt: z.ZodNullable<z.ZodNumber>;
3954
3973
  }, z.core.$strip>>;
3955
3974
  }, z.core.$strip>;
3956
3975
  }, z.core.$strip>, z.ZodObject<{
@@ -4714,6 +4733,7 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
4714
4733
  added: z.ZodNumber;
4715
4734
  removed: z.ZodNumber;
4716
4735
  }, z.core.$strip>>;
4736
+ createdAt: z.ZodNullable<z.ZodNumber>;
4717
4737
  state: z.ZodEnum<{
4718
4738
  active: "active";
4719
4739
  "awaiting-flush": "awaiting-flush";
@@ -4804,6 +4824,61 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
4804
4824
  unavailable: "unavailable";
4805
4825
  available: "available";
4806
4826
  }>;
4827
+ terminal: z.ZodNullable<z.ZodDiscriminatedUnion<[z.ZodObject<{
4828
+ kind: z.ZodLiteral<"interactive">;
4829
+ }, z.core.$strip>, z.ZodObject<{
4830
+ kind: z.ZodLiteral<"background">;
4831
+ attachId: z.ZodString;
4832
+ }, z.core.$strip>], "kind">>;
4833
+ }, z.core.$strip>>;
4834
+ isTruncated: z.ZodBoolean;
4835
+ }, z.core.$strip>;
4836
+ }, z.core.$strip>, z.ZodObject<{
4837
+ kind: z.ZodLiteral<"unstarted-threads">;
4838
+ result: z.ZodObject<{
4839
+ data: z.ZodArray<z.ZodObject<{
4840
+ provider: z.ZodString;
4841
+ nativeId: z.ZodString;
4842
+ nativeLineage: z.ZodNullable<z.ZodObject<{
4843
+ sessionId: z.ZodNullable<z.ZodString>;
4844
+ parentThreadId: z.ZodNullable<z.ZodString>;
4845
+ forkedFromId: z.ZodNullable<z.ZodString>;
4846
+ }, z.core.$strip>>;
4847
+ workspaceRoot: z.ZodString;
4848
+ name: z.ZodNullable<z.ZodString>;
4849
+ createdAt: z.ZodNumber;
4850
+ updatedAt: z.ZodNumber;
4851
+ nativeState: z.ZodEnum<{
4852
+ unknown: "unknown";
4853
+ idle: "idle";
4854
+ active: "active";
4855
+ notLoaded: "notLoaded";
4856
+ systemError: "systemError";
4857
+ }>;
4858
+ state: z.ZodEnum<{
4859
+ unknown: "unknown";
4860
+ idle: "idle";
4861
+ failed: "failed";
4862
+ running: "running";
4863
+ waiting: "waiting";
4864
+ closed: "closed";
4865
+ }>;
4866
+ ownership: z.ZodEnum<{
4867
+ external: "external";
4868
+ managed: "managed";
4869
+ uncertain: "uncertain";
4870
+ }>;
4871
+ managedId: z.ZodNullable<z.ZodUUID>;
4872
+ historyState: z.ZodEnum<{
4873
+ unavailable: "unavailable";
4874
+ available: "available";
4875
+ }>;
4876
+ terminal: z.ZodNullable<z.ZodDiscriminatedUnion<[z.ZodObject<{
4877
+ kind: z.ZodLiteral<"interactive">;
4878
+ }, z.core.$strip>, z.ZodObject<{
4879
+ kind: z.ZodLiteral<"background">;
4880
+ attachId: z.ZodString;
4881
+ }, z.core.$strip>], "kind">>;
4807
4882
  }, z.core.$strip>>;
4808
4883
  isTruncated: z.ZodBoolean;
4809
4884
  }, z.core.$strip>;
@@ -4886,7 +4961,7 @@ export declare const FilePatchSchema: z.ZodObject<{
4886
4961
  }, z.core.$strip>;
4887
4962
  export type IFilePatch = z.infer<typeof FilePatchSchema>;
4888
4963
  export declare const SeekSchema: z.ZodObject<{
4889
- createdAt: z.ZodNumber;
4964
+ updatedAt: z.ZodNumber;
4890
4965
  nativeId: z.ZodUUID;
4891
4966
  }, z.core.$strict>;
4892
4967
  export declare const EntrySeekSchema: z.ZodObject<{
@@ -66,7 +66,7 @@ export const FilePatchSchema = z.object({
66
66
  })),
67
67
  });
68
68
  export const SeekSchema = z.strictObject({
69
- createdAt: z.number().int(),
69
+ updatedAt: z.number().int(),
70
70
  nativeId: z.uuid(),
71
71
  });
72
72
  export const EntrySeekSchema = z.strictObject({
@@ -21,7 +21,8 @@ export declare const isClaudeWorkspaceCwd: (cwd: string | undefined, workspaceRo
21
21
  export declare const openTranscript: (directory: string, nativeId: string) => number;
22
22
  /**
23
23
  * Presents one native record as the CLI shows it, shared by history pages, live items and
24
- * evidence. Outcome and files come from the full record, before the text is cut.
24
+ * evidence. Outcome and files come from the full record, before the text is cut, and its time
25
+ * from the record's `timestamp`.
25
26
  * @returns The item, or null for a record the CLI leaves out, such as thinking or a task notification.
26
27
  * @throws
27
28
  * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
@@ -244,7 +244,8 @@ const toPresentation = (record) => {
244
244
  };
245
245
  /**
246
246
  * Presents one native record as the CLI shows it, shared by history pages, live items and
247
- * evidence. Outcome and files come from the full record, before the text is cut.
247
+ * evidence. Outcome and files come from the full record, before the text is cut, and its time
248
+ * from the record's `timestamp`.
248
249
  * @returns The item, or null for a record the CLI leaves out, such as thinking or a task notification.
249
250
  * @throws
250
251
  * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
@@ -264,6 +265,7 @@ export const toClaudeItem = (record, turnId, fullBody = false) => {
264
265
  let end = fullBody ? text.length : Math.min(text.length, MAX_ITEM_TEXT_LENGTH);
265
266
  if (end < text.length && /[\uD800-\uDBFF]/.test(text.charAt(end - 1)))
266
267
  end -= 1;
268
+ const createdAt = Date.parse(record.timestamp ?? '');
267
269
  return {
268
270
  ...presentation,
269
271
  nativeId: record.uuid,
@@ -271,5 +273,6 @@ export const toClaudeItem = (record, turnId, fullBody = false) => {
271
273
  provenance: nativeProvenance(presentation.kind, presentation.kind === 'user-message' ? record.uuid : null),
272
274
  text: text.slice(0, end),
273
275
  isTruncated: end < text.length,
276
+ createdAt: Number.isFinite(createdAt) ? createdAt : null,
274
277
  };
275
278
  };
@@ -8,6 +8,7 @@ import { buildEvidencePage, evidencePosition, EVIDENCE_SOURCE_PAGE_SIZE, } from
8
8
  import { PROVIDER_INPUT_SCHEMA, SUPPORTED_PROVIDER_OPERATION, } from '../index.js';
9
9
  import { capabilityUnavailable } from '../registry/index.js';
10
10
  import { createCodexProvider } from './codex.js';
11
+ import { MAX_LOADED_THREAD_PAGES } from './constants.js';
11
12
  import { createCodexEvents, toProviderThread } from './events.js';
12
13
  /**
13
14
  * Describes current Codex controls and lazily owns a connection to the shared app-server daemon.
@@ -20,28 +21,52 @@ export const createCodexProviderFactory = (extraSkillRoots) => ({
20
21
  // whether each session is observed, read once: Codex saves it and it's inside an allowed workspace
21
22
  const allowedSessions = new Map();
22
23
  let observations = Promise.resolve();
24
+ // records a session's state, read from Codex when no status change reported it
25
+ const record = async (nativeId, reported) => {
26
+ let isAllowed = allowedSessions.get(nativeId);
27
+ let state = reported;
28
+ if (isAllowed === undefined || state === null) {
29
+ const observed = await native.readObservedThread(nativeId);
30
+ state ??= observed.thread.state;
31
+ isAllowed =
32
+ !observed.isEphemeral &&
33
+ (await resolveWorkspaceTarget(observed.thread.workspaceRoot, context.allowedRoots)
34
+ .then(() => true)
35
+ .catch(() => false));
36
+ if (allowedSessions.size >= 1024)
37
+ allowedSessions.delete(allowedSessions.keys().next().value);
38
+ allowedSessions.set(nativeId, isAllowed);
39
+ }
40
+ if (isAllowed)
41
+ context.events.session(nativeId, state);
42
+ };
23
43
  const observeSession = (nativeId, state) => {
44
+ observations = observations
45
+ .then(() => record(nativeId, state))
46
+ // an unreadable session stays unobserved until its next status change
47
+ .catch(() => undefined);
48
+ };
49
+ /*
50
+ * A session the daemon already ran when this connection opened reports no status change until
51
+ * it next changes, so every loaded thread's state is read on each connect.
52
+ */
53
+ const observeLoaded = () => {
24
54
  observations = observations
25
55
  .then(async () => {
26
- let isAllowed = allowedSessions.get(nativeId);
27
- if (isAllowed === undefined) {
28
- const observed = await native.readObservedThread(nativeId);
29
- isAllowed =
30
- !observed.isEphemeral &&
31
- (await resolveWorkspaceTarget(observed.thread.workspaceRoot, context.allowedRoots)
32
- .then(() => true)
33
- .catch(() => false));
34
- if (allowedSessions.size >= 1024)
35
- allowedSessions.delete(allowedSessions.keys().next().value);
36
- allowedSessions.set(nativeId, isAllowed);
56
+ let cursor;
57
+ for (let page = 0; page < MAX_LOADED_THREAD_PAGES; page += 1) {
58
+ const loaded = await native.listLoadedThreads(cursor);
59
+ for (const nativeId of loaded.data)
60
+ await record(nativeId, null).catch(() => undefined);
61
+ if (loaded.nextCursor === null)
62
+ return;
63
+ cursor = loaded.nextCursor;
37
64
  }
38
- if (isAllowed)
39
- context.events.session(nativeId, state);
40
65
  })
41
- // an unreadable session stays unobserved until its next status change
42
66
  .catch(() => undefined);
43
67
  };
44
- native.setEvents(createCodexEvents(native, context.events, observeSession));
68
+ native.setEvents(createCodexEvents(native, context.events, observeSession, observeLoaded));
69
+ observeLoaded();
45
70
  const verifyRoot = async (workspaceRoot, expectedRoot) => {
46
71
  if ((await resolveWorkspaceTarget(workspaceRoot, context.allowedRoots)) !== expectedRoot)
47
72
  throw new Exception('The HQ target is outside the allowed workspaces', {