jg-agent-hq 4.0.0 → 4.0.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.0.2
4
+
5
+ - Read Claude sessions whose transcript holds a hidden record written before the record it follows, such as an instructions attachment or a scheduled-task event. The reader rejected the whole session, so HQ couldn't name or show it; it now holds the record back until its parent is indexed.
6
+ - Accept Claude transcript records up to 8 MiB, such as tool results holding images, instead of 1 MiB. Indexing reads up to 16 MiB per batch so the largest record fits, and a page always reads its first record.
7
+ - Re-index every Claude transcript once after the upgrade, so sessions the previous version rejected become readable.
8
+
9
+ ## 4.0.1
10
+
11
+ - Report an interactive Claude session that waits on a question or permission prompt as waiting. Claude Code lists it as `waiting`, which was recorded as an unknown state and reported as a disappearance.
12
+ - Never observe an ephemeral Codex session, which Codex doesn't save, such as a helper session Codex starts itself. It no longer appears in session states.
13
+
3
14
  ## 4.0.0
4
15
 
5
16
  - Run Codex sessions on Codex's shared app-server daemon, which also hosts terminal sessions, through `codex app-server proxy`. A keepalive notices a stopped daemon: affected sessions become uncertain, nothing is resent, and the next Codex read reconnects. Extra skill roots now travel with the threads HQ starts instead of changing every session on the daemon.
package/api/README.md CHANGED
@@ -150,7 +150,7 @@ Text chunks contain at most 32,768 UTF-8 bytes and shrink when escaping or metad
150
150
 
151
151
  `HistoryItemSchema` and evidence fragments expose `provenance: { origin, source, nativeInputId, actionId, contentBoundary: 'untrusted', grantsAuthority: false }`. Origins are operator, agent, tool, system or unknown. Native assistant/tool kinds establish only their observed category. A native user role, quoted operator text or an imported message cannot establish an operator. HQ correlates a submitted input only when its exact native message/client identity, thread/turn and complete normalized text hash match the acknowledged action ledger. Programmatic host submissions have source `host-action` and unknown actor. An authenticated browser submission additionally requires the same selected thread and text fingerprint, yielding `authenticated-host-action` and operator provenance. Unverifiable, modified, attachment-expanded or skill-expanded content stays unknown. Provenance remains historical evidence and grants no current approval, execution authority or tool permission; quotations remain inside its untrusted content boundary.
152
152
 
153
- Codex uses its native descending item API with unloaded thread metadata. It never reads Codex transcript files. Claude uses indexed current-chain byte locations, exact UUID lookups and separate bounded seeks per selected kind. Its cold index retains the existing 4 MiB batches and 30-second operation budget; selected evidence reads parse at most 4 MiB of records. Continuation revalidates and rereads one bounded native page to detect content changes rather than caching transcript bodies. Work and memory per read are bounded independently of history growth; reconstructing a large body may reread that source page. No conversation-body cache is maintained.
153
+ Codex uses its native descending item API with unloaded thread metadata. It never reads Codex transcript files. Claude uses indexed current-chain byte locations, exact UUID lookups and separate bounded seeks per selected kind. Its cold index uses 16 MiB batches and a 30-second operation budget; selected evidence reads parse at most 4 MiB of records beyond the first. Continuation revalidates and rereads one bounded native page to detect content changes rather than caching transcript bodies. Work and memory per read are bounded independently of history growth; reconstructing a large body may reread that source page. No conversation-body cache is maintained.
154
154
 
155
155
  ## Native accounts and extensions
156
156
 
@@ -211,15 +211,15 @@ Selected action receipts expose nullable `result: { state, format, text, structu
211
211
 
212
212
  Claude connects on its first read through `claude --print --input-format stream-json --output-format stream-json --verbose`. No user prompt, bare mode, permission bypass or SDK dependency is used. Runtime status reports this adapter as `idle`, `ready` or `unavailable`, with its observed CLI version. An unavailable native lane requires restarting the host after resolving the native problem.
213
213
 
214
- The structured CLI interface has no session-history listing operation. The Claude-owned reader therefore uses direct UUID JSONL files in the native project's directory beneath `CLAUDE_CONFIG_DIR`, or the normal `.claude` directory. CLI and transcript version labels do not gate reads. Required session identity, workspace, parent links, timestamps and message roles are validated, while additive fields and mixed version labels are tolerated. Encoded project keys longer than 200 characters, directory/file links, malformed required fields and records larger than 1 MiB report unavailable. Discovery never recurses into subdirectories, including excluded directories. Unsupported discovered sessions have `historyState: unavailable`; they do not prevent supported sessions from being listed.
214
+ The structured CLI interface has no session-history listing operation. The Claude-owned reader therefore uses direct UUID JSONL files in the native project's directory beneath `CLAUDE_CONFIG_DIR`, or the normal `.claude` directory. CLI and transcript version labels do not gate reads. Required session identity, workspace, parent links, timestamps and message roles are validated, while additive fields and mixed version labels are tolerated. Claude Code can write a hidden record, such as an attachment or a scheduled-task event, a few lines before the record it follows; the reader holds it back until that parent is indexed, and one whose parent the read doesn't reach starts a turn of its own. A message whose parent is unknown is never accepted. Encoded project keys longer than 200 characters, directory/file links, malformed required fields and records larger than 8 MiB report unavailable. Discovery never recurses into subdirectories, including excluded directories. Unsupported discovered sessions have `historyState: unavailable`; they do not prevent supported sessions from being listed.
215
215
 
216
216
  Discovery verifies the workspace recorded inside each transcript before returning its identity or title. A matching native directory name alone is insufficient because punctuation replacement can produce colliding directory keys. Native working directories may be the selected workspace or its subdirectories, including removed subdirectories. The nearest existing path ancestor must resolve inside the workspace without excluded segments; sibling paths and symlink escapes are rejected. Foreign workspaces are omitted. If a file's workspace cannot be established, discovery reports unavailable rather than inventing an empty result.
217
217
 
218
- The existing SQLite worker incrementally records file identity, complete-line offsets, message identities and parent links. It does not save message bodies. File identity includes the current reader projection revision and a native prefix hash, so source changes invalidate the derived projection. Each worker batch inspects at most 128 directory entries and reads at most 4 MiB of new transcript bytes, one file at a time. The adapter continues batches with a host-event-loop yield between them, within a 30-second operation budget. If that budget is reached, the read reports unavailable and subsequent reads continue indexing. At most four incomplete discovery iterators remain open. Shutdown closes them. Discovery continuations use that projection without starting another directory scan; start a fresh first page to refresh discovery. Removed files are discarded from the projection after a complete refresh. No additional cache infrastructure or browser cache is used.
218
+ The existing SQLite worker incrementally records file identity, complete-line offsets, message identities and parent links. It does not save message bodies. File identity includes the current reader projection revision and a native prefix hash, so source changes invalidate the derived projection. Each worker batch inspects at most 128 directory entries and reads at most 16 MiB of new transcript bytes, one file at a time, which fits the largest record. The adapter continues batches with a host-event-loop yield between them, within a 30-second operation budget. If that budget is reached, the read reports unavailable and subsequent reads continue indexing. At most four incomplete discovery iterators remain open. Shutdown closes them. Discovery continuations use that projection without starting another directory scan; start a fresh first page to refresh discovery. Removed files are discarded from the projection after a complete refresh. No additional cache infrastructure or browser cache is used.
219
219
 
220
220
  Current-chain membership and turn starts are indexed as metadata. Ordinary item and turn continuations seek those indexes; they do not walk the full chain per page. A changed branch rebuilds membership before exposing that revision. Repeated native message identities can replace content while retaining their parent; a changed parent for the same identity is an unsupported format.
221
221
 
222
- Selected history reads refresh only that file, retain incomplete tails, and detect truncation or replaced identity. Changed branch/file revisions invalidate item and turn continuations. Only the current parent-linked conversation chain is returned. Text is reread from the native file for the selected page and normalized as plain text. Tool calls show their native name and input; tool results have kind `tool`. Other non-text content has explicit native block labels. An unknown record containing content is returned as an `unsupported` item when its identity and chain are trustworthy; it cannot imply an agent response, idle state or completion. Each selected page reads at most 4 MiB of record bytes and returns at most 4 MiB of serialized item presentation, so a large-text page can contain fewer rows than its requested limit.
222
+ Selected history reads refresh only that file, retain incomplete tails, and detect truncation or replaced identity. Changed branch/file revisions invalidate item and turn continuations. Only the current parent-linked conversation chain is returned. Text is reread from the native file for the selected page and normalized as plain text. Tool calls show their native name and input; tool results have kind `tool`. Other non-text content has explicit native block labels. An unknown record containing content is returned as an `unsupported` item when its identity and chain are trustworthy; it cannot imply an agent response, idle state or completion. Each selected page reads at most 4 MiB of record bytes beyond its first record and returns at most 4 MiB of serialized item presentation, so a large-text page can contain fewer rows than its requested limit.
223
223
 
224
224
  File timestamps and records do not prove that a native process is idle or a turn completed. Claude file-backed thread and turn states are therefore `unknown`, with no invented completion timestamp. Explicit native custom titles are preserved; a missing title remains null. File-backed grouping follows native user records and parent links, including generated user-record markers; it is not an authoritative execution boundary.
225
225
 
@@ -323,8 +323,8 @@ Items expose only normalized presentation fields. User/agent text, commands and
323
323
 
324
324
  Every session has a live state: `running`, `waiting` (on the operator), `idle`, `closed`, `failed` or `unknown`. A managed session reports it from its HQ record. A session another client drives is observed and listed with `ownership: 'external'`; HQ sends it no input. Hand it over with `thread-adopt` once it is closed in its terminal, which Codex reports as unloaded.
325
325
 
326
- - **Codex.** The shared daemon broadcasts every thread's status. HQ records the states of sessions inside the allowed workspaces, reading each session's workspace once, and their items stay readable with `items`. Observation runs while the Codex connection is open; the connection opens on the first Codex request.
327
- - **Claude.** While the runtime runs, HQ runs `claude agents --json` every 5 seconds, each run limited to 10 seconds and 65,536 bytes of output, and joins its entries to Claude discovery by `sessionId`. `busy` is running, `blocked` is waiting and `idle` is idle; an entry missing from a run is closed. A failed, late, oversized or malformed run changes nothing. Sessions HQ manages keep their managed records.
326
+ - **Codex.** The shared daemon broadcasts every thread's status. HQ records the states of sessions inside the allowed workspaces, reading each session's workspace once, and their items stay readable with `items`. An ephemeral session, which Codex doesn't save, such as a helper session Codex starts itself, is never observed. Observation runs while the Codex connection is open; the connection opens on the first Codex request.
327
+ - **Claude.** While the runtime runs, HQ runs `claude agents --json` every 5 seconds, each run limited to 10 seconds and 65,536 bytes of output, and joins its entries to Claude discovery by `sessionId`. `busy` is running, `waiting` (an interactive session's question or permission prompt) and `blocked` (a background session) are waiting, and `idle` is idle; an entry missing from a run is closed. A failed, late, oversized or malformed run changes nothing. Sessions HQ manages keep their managed records.
328
328
 
329
329
  `{ kind: 'session-states', afterSequence?, limit? }` returns state transitions in sequence order after `afterSequence` (default 0), at most `limit` per page (default 32, maximum 128), with `hasMore`. Continue after the last returned `sequence`. Each transition has `sequence`, `provider`, nullable `nativeId`, nullable `threadId` (managed sessions only), `ownership`, nullable `previousState`, `state`, `reason` and `recordedAt`.
330
330
 
@@ -593,7 +593,7 @@ The operation matrix describes the implemented native interfaces and their expli
593
593
  | Reports and recovery | Six final reports matched complete native outcomes byte for byte. A 46,464-byte report was found through indexed search and read in two chunks. After removing all eight qualification transcripts, offline recovery retained those reports and the host preference; tasks were paused and providers stayed idle. | Native transcripts, repository files and authentication remain separate recovery responsibilities. |
594
594
  | Optional skills | All fourteen explicit workflows ran in both providers, including verified delegation and standalone use. Skill-based parent returns ran in both directions. An unissued grant was rejected without creating its request. | Later approvals remain required. Claude signed publication used a disposable bare remote; the qualified Codex sandbox denied Git metadata writes. |
595
595
  | Shared Codex daemon | Codex 0.164.0: a terminal `codex` session ran on the shared daemon and appeared in `thread/list`. Without subscribing, HQ saw its `thread/status/changed`; after rejoining with `thread/resume`, HQ received the terminal's live turn and item notifications. A thread HQ created appeared in the terminal's `codex resume` picker, and closing HQ's connection left the daemon and the terminal session running. The daemon confirmed HQ's interrupt and close. Per-thread skill roots, dynamic agent tools and output schemas worked on HQ threads, while another client's catalog and thread never saw the roots. Sessions read their own thread ID from `CODEX_THREAD_ID`. | A terminal started with `-c` overrides runs its thread in its own process (`source: cli`): it is listed, but a second writer is refused, so it cannot be followed live. The restart check ran against a separate app-server on its own socket rather than the shared daemon, which was serving other work: within one keepalive interval the session became uncertain and nothing was resent. A session Codex reloads from disk loses its capability roots. |
596
- | Claude active sessions | Claude Code 2.1.310 answered `claude agents --json` in 0.16 s. Interactive entries carry `status` (`busy`, `idle`) and `pid`; background entries carry `id` and `state` (`blocked`). Sessions HQ starts in structured mode are listed as interactive under their HQ name and disappear after close. | The list describes running processes only; history still comes from transcripts. |
596
+ | Claude active sessions | Claude Code 2.1.310 answered `claude agents --json` in 0.16 s. Interactive entries carry `status` (`busy`, `waiting`, `idle`) and `pid`; background entries carry `id` and `state` (`blocked`). Sessions HQ starts in structured mode are listed as interactive under their HQ name and disappear after close. | The list describes running processes only; history still comes from transcripts. |
597
597
  | Host coverage | Linux x86_64 package checks passed on Node 24.15.0 and 24.22.1. Integrated delegation ran on the floor; identity, native interaction and recovery also ran on 24.22.1. | No macOS host was available for this run. Windows is outside the declared host contract. |
598
598
 
599
599
  The integrated delegation, identity and recovery checks used gpt-6.1-sol with medium effort and claude-opus-5-5 with medium effort in disposable workspaces on 2026-10-23. The shared-daemon and Claude active-session checks ran on 2026-10-25 with the installed CLIs' default models in disposable workspaces. The [Node release index](https://nodejs.org/dist/index.json) identified 24.22.1 as the current LTS patch at qualification time. Local checks do not establish a published npm release or a deployed website.
@@ -1,6 +1,9 @@
1
1
  import type { ISessionState } from '../../../contracts/index.js';
2
2
  import { type IClaudeAgent } from './types.js';
3
- /** Maps a native busy, blocked or idle report to the shared session state. */
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`.
6
+ */
4
7
  export declare const toAgentState: (agent: IClaudeAgent) => ISessionState;
5
8
  /**
6
9
  * Polls `claude agents --json` while the runtime runs and records the complete list of active
@@ -4,12 +4,15 @@ import { resolveWorkspaceTarget } from '../../../runtime/state/index.js';
4
4
  import { AGENTS_DEADLINE_MS, AGENTS_OUTPUT_BYTES, AGENTS_POLL_INTERVAL_MS } from './constants.js';
5
5
  import { ClaudeAgentsSchema } from './types.js';
6
6
  const run = promisify(execFile);
7
- /** Maps a native busy, blocked or idle report to the shared session state. */
7
+ /**
8
+ * Maps a native report to the shared session state: an interactive session reports `waiting` on a
9
+ * question or permission prompt, and a background one `blocked`.
10
+ */
8
11
  export const toAgentState = (agent) => {
9
12
  const reported = agent.status ?? agent.state;
10
13
  return reported === 'busy'
11
14
  ? 'running'
12
- : reported === 'blocked'
15
+ : reported === 'waiting' || reported === 'blocked'
13
16
  ? 'waiting'
14
17
  : reported === 'idle'
15
18
  ? 'idle'
@@ -28,6 +28,15 @@ export declare class ClaudeHistoryModel {
28
28
  private __identity;
29
29
  private __refresh;
30
30
  private __inspect;
31
+ /**
32
+ * Indexes one transcript record. Claude Code can write a hidden record, such as an attachment
33
+ * or a scheduled-task event, a few lines before the record it follows; such a record is held
34
+ * back unless `isOrphanAllowed`, and the caller retries it once its parent is indexed.
35
+ * @returns Null once the record is indexed, or the UUID of the parent a held-back record awaits.
36
+ * @throws
37
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
38
+ */
31
39
  private __record;
40
+ private __hasEntry;
32
41
  private __unavailable;
33
42
  }
@@ -8,9 +8,14 @@ import { evidencePosition, buildEvidencePage, EVIDENCE_SOURCE_PAGE_SIZE, } from
8
8
  import { EntryRowSchema, EntrySeekSchema, FileRowSchema, RecordSchema, ApiRequestMetadataSchema, SeekSchema, } from './types.js';
9
9
  import { isClaudeWorkspaceCwd, openTranscript, projectDirectory, toClaudeItem, } from './utilities.js';
10
10
  // identifies the path and record interpretation used by persisted projection entries
11
- const HISTORY_PROJECTION_VERSION = 3;
12
- const MAX_RECORD_BYTES = 1_048_576;
13
- const MAX_REFRESH_BYTES = 4_194_304;
11
+ const HISTORY_PROJECTION_VERSION = 4;
12
+ // one record, such as a tool result holding images, and an indexing read, which fits the largest
13
+ const MAX_RECORD_BYTES = 8_388_608;
14
+ const MAX_REFRESH_BYTES = 16_777_216;
15
+ // the record bytes and serialized items of one page, which stays inside the 8 MiB IPC frame
16
+ const MAX_PAGE_BYTES = 4_194_304;
17
+ // hidden records awaiting a parent later in the file; Claude Code writes them a few lines early
18
+ const MAX_HELD_BACK_RECORDS = 64;
14
19
  const CHAIN = `WITH RECURSIVE current_chain AS (
15
20
  SELECT workspace_root, native_id, uuid, parent_uuid, turn_id, byte_offset, byte_length, created_at, is_visible
16
21
  FROM hq_claude_entry WHERE workspace_root = ? AND native_id = ? AND uuid = ?
@@ -174,7 +179,8 @@ export class ClaudeHistoryModel {
174
179
  let readBytes = 0;
175
180
  let lastOffset = offset;
176
181
  for (const entry of page) {
177
- if (readBytes + entry.byte_length > MAX_REFRESH_BYTES)
182
+ // a page always reads its first record, which can be larger than the page budget
183
+ if (readBytes > 0 && readBytes + entry.byte_length > MAX_PAGE_BYTES)
178
184
  break;
179
185
  readBytes += entry.byte_length;
180
186
  const bytes = Buffer.alloc(entry.byte_length);
@@ -185,7 +191,7 @@ export class ClaudeHistoryModel {
185
191
  this.__unavailable();
186
192
  const item = toClaudeItem(record, entry.turn_id);
187
193
  const itemSize = Buffer.byteLength(JSON.stringify(item));
188
- if (size + itemSize > MAX_REFRESH_BYTES)
194
+ if (size + itemSize > MAX_PAGE_BYTES)
189
195
  break;
190
196
  size += itemSize;
191
197
  lastOffset = entry.byte_offset;
@@ -255,7 +261,7 @@ export class ClaudeHistoryModel {
255
261
  if (this.__identity(fd) !== row.identity || fstatSync(fd).size < row.file_size)
256
262
  this.__unavailable();
257
263
  for (const entry of entries.slice(0, EVIDENCE_SOURCE_PAGE_SIZE)) {
258
- if (readBytes + entry.byte_length > MAX_REFRESH_BYTES)
264
+ if (readBytes > 0 && readBytes + entry.byte_length > MAX_PAGE_BYTES)
259
265
  break;
260
266
  const bytes = Buffer.alloc(entry.byte_length);
261
267
  if (readSync(fd, bytes, 0, bytes.length, entry.byte_offset) !== bytes.length)
@@ -396,6 +402,31 @@ export class ClaudeHistoryModel {
396
402
  let lineStart = position;
397
403
  let tail = Buffer.alloc(0);
398
404
  const chunk = Buffer.alloc(65_536);
405
+ // hidden records whose parent comes later in the file, by location and awaited parent
406
+ const heldBack = [];
407
+ const reread = (offset, length) => {
408
+ const bytes = Buffer.alloc(length);
409
+ if (readSync(fd, bytes, 0, length, offset) !== length)
410
+ this.__unavailable();
411
+ return bytes;
412
+ };
413
+ const isReleasable = ({ parentUuid }) => this.__hasEntry(root, nativeId, parentUuid);
414
+ const indexRecord = (bytes, offset) => {
415
+ const parentUuid = this.__record(root, nativeId, row, bytes, offset, false);
416
+ if (parentUuid !== null) {
417
+ if (heldBack.length >= MAX_HELD_BACK_RECORDS)
418
+ this.__unavailable();
419
+ heldBack.push({ offset, length: bytes.length, parentUuid });
420
+ return;
421
+ }
422
+ // a released record can be the parent of another held-back one
423
+ for (let held = heldBack.findIndex(isReleasable); held !== -1;) {
424
+ const [record] = heldBack.splice(held, 1);
425
+ if (record)
426
+ this.__record(root, nativeId, row, reread(record.offset, record.length), record.offset, false);
427
+ held = heldBack.findIndex(isReleasable);
428
+ }
429
+ };
399
430
  this.__database.exec('BEGIN IMMEDIATE');
400
431
  try {
401
432
  while (position < stat.size && remaining() > 0) {
@@ -409,13 +440,20 @@ export class ClaudeHistoryModel {
409
440
  if (end > MAX_RECORD_BYTES)
410
441
  this.__unavailable();
411
442
  if (end > 0)
412
- this.__record(root, nativeId, row, tail.subarray(0, end), lineStart);
443
+ indexRecord(tail.subarray(0, end), lineStart);
413
444
  lineStart += end + 1;
414
445
  tail = tail.subarray(end + 1);
415
446
  }
416
447
  if (tail.length > MAX_RECORD_BYTES)
417
448
  this.__unavailable();
418
449
  }
450
+ /*
451
+ * A parent this read didn't reach is indexed as the root of its own turn: the projection
452
+ * keeps no position before byte_offset to retry from, and a hidden record only groups
453
+ * the records that follow it.
454
+ */
455
+ for (const record of heldBack)
456
+ this.__record(root, nativeId, row, reread(record.offset, record.length), record.offset, true);
419
457
  row.byte_offset = lineStart;
420
458
  this.__database
421
459
  .prepare(`UPDATE hq_claude_file SET byte_offset = ?, file_size = ?, leaf_id = ?, name = ?,
@@ -440,14 +478,22 @@ export class ClaudeHistoryModel {
440
478
  closeSync(fd);
441
479
  }
442
480
  }
443
- __record(root, nativeId, row, bytes, offset) {
481
+ /**
482
+ * Indexes one transcript record. Claude Code can write a hidden record, such as an attachment
483
+ * or a scheduled-task event, a few lines before the record it follows; such a record is held
484
+ * back unless `isOrphanAllowed`, and the caller retries it once its parent is indexed.
485
+ * @returns Null once the record is indexed, or the UUID of the parent a held-back record awaits.
486
+ * @throws
487
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
488
+ */
489
+ __record(root, nativeId, row, bytes, offset, isOrphanAllowed) {
444
490
  const input = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
445
491
  const metadata = ApiRequestMetadataSchema.safeParse(input);
446
492
  if (metadata.success) {
447
493
  if (metadata.data.sessionId !== nativeId ||
448
494
  (metadata.data.cwd !== undefined && !isClaudeWorkspaceCwd(metadata.data.cwd, root)))
449
495
  this.__unavailable();
450
- return;
496
+ return null;
451
497
  }
452
498
  const record = RecordSchema.parse(input);
453
499
  if (record.cwd !== undefined) {
@@ -461,14 +507,14 @@ export class ClaudeHistoryModel {
461
507
  if (record.sessionId !== nativeId || record.customTitle === undefined)
462
508
  this.__unavailable();
463
509
  row.name = record.customTitle;
464
- return;
510
+ return null;
465
511
  }
466
512
  if (record.isSidechain)
467
- return;
513
+ return null;
468
514
  if (!record.uuid) {
469
515
  if (record.message !== undefined || record.type === 'user' || record.type === 'assistant')
470
516
  this.__unavailable();
471
- return;
517
+ return null;
472
518
  }
473
519
  if ((record.type === 'user' || record.type === 'assistant') &&
474
520
  record.message?.role !== record.type)
@@ -485,6 +531,15 @@ export class ClaudeHistoryModel {
485
531
  WHERE workspace_root = ? AND native_id = ? AND uuid = ?`)
486
532
  .get(root, nativeId, record.parentUuid)
487
533
  : undefined;
534
+ const visible = record.message !== undefined && !record.isMeta;
535
+ if (record.parentUuid === record.uuid)
536
+ this.__unavailable();
537
+ if (record.parentUuid && !parent) {
538
+ if (visible)
539
+ this.__unavailable();
540
+ if (!isOrphanAllowed)
541
+ return record.parentUuid;
542
+ }
488
543
  const textPrompt = record.type === 'user' &&
489
544
  !record.isMeta &&
490
545
  (typeof record.message?.content === 'string' ||
@@ -495,11 +550,6 @@ export class ClaudeHistoryModel {
495
550
  : typeof parent?.turn_id === 'string'
496
551
  ? parent.turn_id
497
552
  : record.uuid;
498
- const visible = record.message !== undefined && !record.isMeta;
499
- if (record.parentUuid === record.uuid)
500
- this.__unavailable();
501
- if (record.parentUuid && !parent)
502
- this.__unavailable();
503
553
  const previous = this.__database
504
554
  .prepare('SELECT parent_uuid FROM hq_claude_entry WHERE workspace_root = ? AND native_id = ? AND uuid = ?')
505
555
  .get(root, nativeId, record.uuid);
@@ -542,6 +592,12 @@ export class ClaudeHistoryModel {
542
592
  }
543
593
  row.created_at = Math.min(row.created_at, createdAt);
544
594
  row.updated_at = Math.max(row.updated_at, createdAt);
595
+ return null;
596
+ }
597
+ __hasEntry(root, nativeId, uuid) {
598
+ return (this.__database
599
+ .prepare('SELECT 1 FROM hq_claude_entry WHERE workspace_root = ? AND native_id = ? AND uuid = ?')
600
+ .get(root, nativeId, uuid) !== undefined);
545
601
  }
546
602
  __unavailable() {
547
603
  throw new Exception('The Claude history is unavailable', {
@@ -17,7 +17,7 @@ export const createCodexProviderFactory = (extraSkillRoots) => ({
17
17
  id: 'codex',
18
18
  async create(context) {
19
19
  const native = await createCodexProvider(extraSkillRoots, context.agentTools);
20
- // whether each observed session's workspace is allowed, read once per session
20
+ // whether each session is observed, read once: Codex saves it and it's inside an allowed workspace
21
21
  const allowedSessions = new Map();
22
22
  let observations = Promise.resolve();
23
23
  const observeSession = (nativeId, state) => {
@@ -25,10 +25,12 @@ export const createCodexProviderFactory = (extraSkillRoots) => ({
25
25
  .then(async () => {
26
26
  let isAllowed = allowedSessions.get(nativeId);
27
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);
28
+ const thread = await native.readObservedThread(nativeId);
29
+ isAllowed =
30
+ !thread.isEphemeral &&
31
+ (await resolveWorkspaceTarget(thread.workspaceRoot, context.allowedRoots)
32
+ .then(() => true)
33
+ .catch(() => false));
32
34
  if (allowedSessions.size >= 1024)
33
35
  allowedSessions.delete(allowedSessions.keys().next().value);
34
36
  allowedSessions.set(nativeId, isAllowed);
@@ -351,6 +351,10 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
351
351
  const result = parseNative(z.object({ thread: NativeThreadSchema.refine((thread) => thread.id === nativeId) }), await connection.request('thread/read', { threadId: nativeId, includeTurns: false }));
352
352
  return toThreadSummary(result.thread);
353
353
  },
354
+ async readObservedThread(nativeId) {
355
+ const { thread } = parseNative(z.object({ thread: NativeThreadSchema.refine((thread) => thread.id === nativeId) }), await connection.request('thread/read', { threadId: nativeId, includeTurns: false }));
356
+ return { workspaceRoot: thread.cwd, isEphemeral: thread.ephemeral === true };
357
+ },
354
358
  async listTurns(nativeId, limit, cursor) {
355
359
  const page = parseNative(NativeTurnPageSchema, await connection.request('thread/turns/list', {
356
360
  threadId: nativeId,
@@ -11,6 +11,7 @@ export declare const NativeThreadSchema: z.ZodObject<{
11
11
  forkedFromId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
12
12
  cwd: z.ZodString;
13
13
  name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
14
+ ephemeral: z.ZodOptional<z.ZodBoolean>;
14
15
  createdAt: z.ZodNumber;
15
16
  updatedAt: z.ZodNumber;
16
17
  status: z.ZodObject<{
@@ -49,6 +50,7 @@ export declare const NativeThreadPageSchema: z.ZodObject<{
49
50
  forkedFromId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
50
51
  cwd: z.ZodString;
51
52
  name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
53
+ ephemeral: z.ZodOptional<z.ZodBoolean>;
52
54
  createdAt: z.ZodNumber;
53
55
  updatedAt: z.ZodNumber;
54
56
  status: z.ZodObject<{
@@ -191,6 +193,11 @@ export type ICodexProvider = {
191
193
  readonly isAvailable: boolean;
192
194
  listThreads(workspaceRoot: string, limit: number, cursor?: string, search?: string): Promise<INativePage<IThreadSummary>>;
193
195
  readThread(nativeId: string): Promise<IThreadSummary>;
196
+ /** @returns A session's workspace and whether Codex doesn't save it, which decide observation. */
197
+ readObservedThread(nativeId: string): Promise<{
198
+ workspaceRoot: string;
199
+ isEphemeral: boolean;
200
+ }>;
194
201
  listTurns(nativeId: string, limit: number, cursor?: string): Promise<INativePage<ITurnSummary>>;
195
202
  listItems(nativeId: string, limit: number, cursor?: string, turnId?: string, evidence?: boolean): Promise<INativePage<IHistoryItem>>;
196
203
  readUsage(): Promise<IUsageSnapshot>;
@@ -8,6 +8,8 @@ export const NativeThreadSchema = z.object({
8
8
  forkedFromId: z.string().min(1).max(4096).nullable().optional(),
9
9
  cwd: z.string().min(1).max(4096),
10
10
  name: z.string().nullable().optional(),
11
+ // a session Codex doesn't save, such as the helper sessions it starts itself
12
+ ephemeral: z.boolean().optional(),
11
13
  createdAt: z.number().int().safe(),
12
14
  updatedAt: z.number().int().safe(),
13
15
  status: z.object({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jg-agent-hq",
3
- "version": "4.0.0",
3
+ "version": "4.0.2",
4
4
  "description": "Native coding-agent session control, agent streams and durable collaboration for Node.js apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",