jg-agent-hq 10.9.1 → 10.9.3

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,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 10.9.3
4
+
5
+ - Clear a finished turn's saved items from the live window without waiting on a client's history read. A saved item used to stay `awaiting-flush` until some `items` read happened to cover it, so a session nobody read while it worked kept its items, and a client that read only its newest pages later showed them after the newest items. When a turn ends, the runtime now reads that turn's history itself, newest first and at most 8 pages of 128, until none of its finished items remain, and once more 2 seconds later when some do, since Codex's saved state can trail its turn's end. A failed read leaves them to the next history read, as before.
6
+
7
+ ## 10.9.2
8
+
9
+ - Read a Claude transcript whose compaction names a record the transcript doesn't hold before the boundary. Such a transcript was refused whole, its history unavailable and its `thread` read failing: a chat Claude Code moved into a new session, whose boundary names the old session's record, and a transcript whose boundary named a record written after it. The chain now starts at that boundary. Every Claude history is indexed again once, so the transcripts refused before are read.
10
+
3
11
  ## 10.9.1
4
12
 
5
13
  - Forget a terminal Claude session's background-command count when a `thread` read of it finishes after the `claude agents --json` poll stopped listing it. The read used to leave the session's transcript scan in memory, where nothing removed it.
package/api/README.md CHANGED
@@ -241,7 +241,7 @@ The existing SQLite worker incrementally records file identity, complete-line of
241
241
 
242
242
  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.
243
243
 
244
- 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. Claude Code links each tool result to its own call, so parallel calls whose results finish out of order would leave the later calls and results on a side branch; such a result follows the latest record of its call's turn instead, keeping every call of the response and all their results on the chain without changing its revision. Text is reread from the native file for the selected page and normalized as plain text. Thinking blocks are left out, and a record holding only thinking is hidden, as are `<task-notification>` records and a subagent's sidechain records. Live items leave a subagent's stream frames out likewise, and those frames start no turn, though a subagent's tool results still settle the approvals it asked for. Compaction summaries, `<local-command-stdout>` output and interruption markers are `notice` items, and a slash command is a `user-message` reading `/name args`. A `!` shell input and its output are `command` items, the output's `callId` being the input's UUID. A tool call shows its native name and input, with the block's ID as `callId`, which is null for a record calling several tools; its result is a `tool` item carrying that ID, `failed` when it has `is_error` and `succeeded` otherwise. An Edit or Write result whose metadata has a `filePath` and a `structuredPatch` is a `file-change` item reading the path and its patch lines, or a created file's content, every line of which counts as added. A result Claude Code saved to a file reads `Output too large (<size>), saved to a file` followed by its preview, without the file's path. A result made of content blocks, such as a screenshot with its caption, reads as its text blocks, each image as `[Image]`. Other non-text content has explicit native block labels. The index stores each entry's presented kind and visibility, so evidence kind filters match `items` and hidden records never shorten a page. 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.
244
+ 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. A compaction's boundary has no parent and names the record before it, which the chain follows back to the start of the conversation; when the transcript holds no such record before the boundary, as in a chat Claude Code moved into a new session, whose boundary names the old session's record, the chain starts at the boundary. Claude Code links each tool result to its own call, so parallel calls whose results finish out of order would leave the later calls and results on a side branch; such a result follows the latest record of its call's turn instead, keeping every call of the response and all their results on the chain without changing its revision. Text is reread from the native file for the selected page and normalized as plain text. Thinking blocks are left out, and a record holding only thinking is hidden, as are `<task-notification>` records and a subagent's sidechain records. Live items leave a subagent's stream frames out likewise, and those frames start no turn, though a subagent's tool results still settle the approvals it asked for. Compaction summaries, `<local-command-stdout>` output and interruption markers are `notice` items, and a slash command is a `user-message` reading `/name args`. A `!` shell input and its output are `command` items, the output's `callId` being the input's UUID. A tool call shows its native name and input, with the block's ID as `callId`, which is null for a record calling several tools; its result is a `tool` item carrying that ID, `failed` when it has `is_error` and `succeeded` otherwise. An Edit or Write result whose metadata has a `filePath` and a `structuredPatch` is a `file-change` item reading the path and its patch lines, or a created file's content, every line of which counts as added. A result Claude Code saved to a file reads `Output too large (<size>), saved to a file` followed by its preview, without the file's path. A result made of content blocks, such as a screenshot with its caption, reads as its text blocks, each image as `[Image]`. Other non-text content has explicit native block labels. The index stores each entry's presented kind and visibility, so evidence kind filters match `items` and hidden records never shorten a page. 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.
245
245
 
246
246
  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. A turn starts at a message the operator sends, including a slash command; task notifications, compaction summaries, local command output, interruption markers and `!` shell records belong to the turn before them. Grouping follows parent links and is not an authoritative execution boundary. A compaction starts a new chain whose first record names the record before it, so history reads on past the compaction to the start of the conversation.
247
247
 
@@ -346,7 +346,7 @@ The installed CLI exposes `managed-thread-name --name <name>` and `suggest-threa
346
346
 
347
347
  Control pages default to 32 and cap at 128. Seek cursors are bound to their complete query and ordering. Reads recheck allowed workspaces. Rejected controls retain their known thread association, and native availability failures appear in each affected thread's replay. Lifecycle replay contains metadata, not token or tool output. Each provider has a bounded native lifecycle backlog; overflow stops that source and marks its state uncertain rather than losing events silently. Other providers retain their independent connection and admission state.
348
348
 
349
- Live item presentation is bounded to 128 items per cached thread, 32 windows and 4 MiB of serialized presentation across the runtime, including escaped text and identifiers. This leaves room inside the IPC response limit. Display text uses the same truncation contract as native history. Eviction, an unavailable window or missing chunks sets `hasGap`. Completed items remain `awaiting-flush` after thread closure until a native history page holds the same item, with exactly matching normalized content or, for an item with an outcome, the same final outcome, or the bounded cache evicts them. The outcome is enough because Codex shortens long command output when it saves it. An item still streaming when its turn ended, such as a message an interrupt or a Codex steer cut, stays `awaiting-flush` until a native history page holds an item of that turn, since the provider may never save it; the history then shows what was saved of it. Read persisted history and the live window together after reconnect; a process restart cannot reconstruct unflushed in-memory content.
349
+ Live item presentation is bounded to 128 items per cached thread, 32 windows and 4 MiB of serialized presentation across the runtime, including escaped text and identifiers. This leaves room inside the IPC response limit. Display text uses the same truncation contract as native history. Eviction, an unavailable window or missing chunks sets `hasGap`. Completed items remain `awaiting-flush` after thread closure until a native history page holds the same item, with exactly matching normalized content or, for an item with an outcome, the same final outcome, or the bounded cache evicts them. The outcome is enough because Codex shortens long command output when it saves it. An item still streaming when its turn ended, such as a message an interrupt or a Codex steer cut, stays `awaiting-flush` until a native history page holds an item of that turn, since the provider may never save it; the history then shows what was saved of it. A client's `items` read is one such page, and when a turn ends the runtime reads that turn's own history too, newest first and at most 8 pages of 128, until none of its finished items remain, so the window doesn't wait on a client that never reads them. Codex's saved state can trail its turn's end, so a turn whose items remain is read once more 2 seconds later; a failed read leaves them to the next history read. A client that shows live items should therefore expect them to leave the window before its own history read holds them. Read persisted history and the live window together after reconnect; a process restart cannot reconstruct unflushed in-memory content.
350
350
 
351
351
  Items expose only normalized presentation fields, and one mapping per provider presents `items`, live items and `session-evidence` alike, as the provider's CLI shows them. Kinds are `user-message`, `agent-message`, `command`, `tool`, `file-change`, `notice` and `unsupported`. `callId` pairs a tool call with its result, or is null. `outcome` is `succeeded`, `failed`, or null when unknown or still running. `files` lists each file a file change touched, at most 128, with its added and removed lines, and is empty on other items. `outcome` and `files` come from the full native record, so `textLimit` never changes them. Unknown native kinds report `unsupported` without copying arbitrary payloads. Display text is bounded to 65,536 UTF-16 code units without splitting a surrogate pair; `isTruncated` reports omissions. An unsupported or oversized native transport frame fails explicitly. `createdAt` is the item's time in Unix milliseconds, or null when the provider records none. A Claude item takes its record's `timestamp`, and a live one the time its frame arrived. A Codex item takes its turn's times, which Codex records across all of its history: an operator message takes its turn's start and every other item its turn's end, or its start while the turn runs. A Codex history page reads the turns of its items newest first, 128 at a time and at most 8 times, so a recent page takes one read and an item whose turn lies further back has no time. A live Codex item takes its running turn's start.
352
352
 
@@ -1,4 +1,4 @@
1
- import type { IActionEnvelope, IActionReceipt, INativeApproval, INativeApprovalSummary, ILoginObservation, ISessionTerminal } from '../contracts/index.js';
1
+ import { type IActionEnvelope, type IActionReceipt, type INativeApproval, type INativeApprovalSummary, type ILoginObservation, type ISessionTerminal } from '../contracts/index.js';
2
2
  import { type createProviderRegistry } from '../providers/registry/index.js';
3
3
  import type { createSkills } from '../skills/index.js';
4
4
  import type { IStore } from '../store/index.js';
@@ -2,6 +2,7 @@ import { createHmac, randomUUID } from 'node:crypto';
2
2
  import { Exception, extractMessage, isException } from 'jg-exception';
3
3
  import { delay } from 'jg-utilities';
4
4
  import { z } from 'zod';
5
+ import { MAX_ITEM_TEXT_LENGTH, MAX_PAGE_SIZE, } from '../contracts/index.js';
5
6
  import { getErrorKind } from '../errors/index.js';
6
7
  import { retainNativeLineage, readInputFiles } from '../providers/index.js';
7
8
  import { capabilityUnavailable } from '../providers/registry/index.js';
@@ -14,6 +15,8 @@ const ITEM_OBSERVATIONS = new Set([
14
15
  'item-started',
15
16
  'item-completed',
16
17
  ]);
18
+ // the most history pages of 128 items a finished turn's own read takes, as a Codex page reads turns
19
+ const TURN_FLUSH_PAGES = 8;
17
20
  const NativeRejectionSchema = z.union([
18
21
  z.object({ nativeCode: z.number() }),
19
22
  z.object({ nativeRejection: z.literal(true) }),
@@ -458,9 +461,63 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
458
461
  : { kind: 'uncertain', actionId: receipt.id, requestId: receipt.nativeRequestId });
459
462
  }
460
463
  };
464
+ // finished turns whose own history is being read, so a turn is read by one task at a time
465
+ const flushing = new Set();
466
+ /*
467
+ * A saved item leaves the live window only once a native history page holds it, and a client may
468
+ * never read the pages that do, so a finished turn's own history is read here, newest first,
469
+ * until none of its saved items remain. Codex's saved state can trail its turn's end, so a turn
470
+ * whose items remain is read once more after the re-check wait. An aborted wait or a failed read
471
+ * leaves them to the next history read, as before, and never fails the session's events.
472
+ */
473
+ const flushTurn = (provider, nativeId, workspaceRoot, turnId) => {
474
+ const liveKey = key(provider, nativeId);
475
+ const flushKey = JSON.stringify([liveKey, turnId]);
476
+ if (flushing.has(flushKey))
477
+ return;
478
+ flushing.add(flushKey);
479
+ runOwned(async () => {
480
+ try {
481
+ for (let attempt = 0; attempt < 2; attempt += 1) {
482
+ if (attempt > 0)
483
+ await delay(RESYNC_REREAD_DELAY_SECONDS, { signal: resyncLifetime.signal });
484
+ const control = await registry.get(provider);
485
+ let cursor;
486
+ for (let page = 0; page < TURN_FLUSH_PAGES; page += 1) {
487
+ if (closing || !live.awaitsFlush(liveKey, turnId))
488
+ return;
489
+ const response = await control.readHistory({
490
+ kind: 'items',
491
+ provider,
492
+ workspaceRoot,
493
+ nativeId,
494
+ turnId,
495
+ limit: MAX_PAGE_SIZE,
496
+ cursor,
497
+ textLimit: MAX_ITEM_TEXT_LENGTH,
498
+ });
499
+ if (response.kind !== 'items')
500
+ return;
501
+ live.reconcile(liveKey, response.result.data);
502
+ if (response.result.nextCursor === null)
503
+ break;
504
+ cursor = response.result.nextCursor;
505
+ }
506
+ }
507
+ }
508
+ catch {
509
+ // the items wait for the next history read
510
+ }
511
+ finally {
512
+ flushing.delete(flushKey);
513
+ }
514
+ });
515
+ };
461
516
  const observe = async (observation) => {
462
517
  const result = await recordObservation(observation);
463
518
  if (observation.kind === 'turn-completed') {
519
+ if (result.thread && controlled.has(key(observation.provider, observation.nativeThreadId)))
520
+ flushTurn(observation.provider, observation.nativeThreadId, result.thread.workspaceRoot, observation.nativeTurnId);
464
521
  watched.delete(key(observation.provider, observation.nativeThreadId));
465
522
  for (const [id, prompt] of prompts)
466
523
  if (prompt.native.provider === observation.provider &&
@@ -487,7 +544,7 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
487
544
  live.completeTurn(key(provider, observation.nativeThreadId), observation.nativeTurnId);
488
545
  enqueue(provider, () => observe(observation));
489
546
  };
490
- // ends the waits of delayed re-checks when the runtime closes
547
+ // ends the waits of delayed re-checks and turn reads when the runtime closes
491
548
  const resyncLifetime = new AbortController();
492
549
  /*
493
550
  * Sessions a re-check after an unidentified loss left running, or skipped while an action was in
@@ -46,6 +46,13 @@ export declare class LiveItems {
46
46
  * finished goes once persisted history holds that turn, which then shows what was saved of it.
47
47
  */
48
48
  reconcile(nativeId: string, persisted: IHistoryItem[]): void;
49
+ /**
50
+ * Says whether a turn's window still holds a finished item no native history page has held.
51
+ * @param nativeId The session's key.
52
+ * @param turnId The native turn.
53
+ * @returns Whether such an item remains.
54
+ */
55
+ awaitsFlush(nativeId: string, turnId: string): boolean;
49
56
  /** Keeps a turn's partial items available until native history holds the turn. */
50
57
  completeTurn(nativeId: string, turnId: string): void;
51
58
  /** Releases one cached window when the bounded window collection must evict it. */
@@ -172,6 +172,21 @@ export class LiveItems {
172
172
  }
173
173
  }
174
174
  }
175
+ /**
176
+ * Says whether a turn's window still holds a finished item no native history page has held.
177
+ * @param nativeId The session's key.
178
+ * @param turnId The native turn.
179
+ * @returns Whether such an item remains.
180
+ */
181
+ awaitsFlush(nativeId, turnId) {
182
+ const thread = this.__threads.get(nativeId);
183
+ if (!thread)
184
+ return false;
185
+ for (const entry of thread.items.values())
186
+ if (entry.isComplete && entry.item.turnId === turnId)
187
+ return true;
188
+ return false;
189
+ }
175
190
  /** Keeps a turn's partial items available until native history holds the turn. */
176
191
  completeTurn(nativeId, turnId) {
177
192
  const thread = this.__threads.get(nativeId);
@@ -8,7 +8,7 @@ import { evidencePosition, buildEvidencePage, EVIDENCE_SOURCE_PAGE_SIZE, } from
8
8
  import { EntryRowSchema, EntrySeekSchema, FileRowSchema, RecordSchema, ApiRequestMetadataSchema, SeekSchema, } from './types.js';
9
9
  import { isClaudeAnswer, isClaudeCallFor, isClaudeRecordCwd, isClaudeWorkspaceCwd, openTranscript, projectDirectory, readClaudeParentUuid, readContinuedIn, toClaudeDetail, toClaudeImageData, toClaudeItem, } from './utilities.js';
10
10
  // identifies the path and record interpretation used by persisted projection entries
11
- const HISTORY_PROJECTION_VERSION = 9;
11
+ const HISTORY_PROJECTION_VERSION = 10;
12
12
  // the transcripts whose continuing session is remembered, oldest dropped first
13
13
  const MAX_CONTINUED_ANSWERS = 1_024;
14
14
  // one record, such as a tool result holding images, and an indexing read, which fits the largest
@@ -738,7 +738,13 @@ export class ClaudeHistoryModel {
738
738
  if (nativeParentUuid && !nativeParent) {
739
739
  if (visible)
740
740
  this.__unavailable();
741
- if (!isOrphanAllowed)
741
+ /*
742
+ * A compaction's boundary has no parent and names the record before it, which is indexed
743
+ * by then when this transcript holds it. Otherwise it is the old session's, in the
744
+ * transcript a moved chat continues from, or one Claude Code wrote after the boundary, so
745
+ * the boundary starts its chain at once rather than holding back the summary that follows.
746
+ */
747
+ if (!isOrphanAllowed && record.parentUuid != null)
742
748
  return nativeParentUuid;
743
749
  }
744
750
  const previous = statements.recordedParent.get(root, nativeId, record.uuid);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jg-agent-hq",
3
- "version": "10.9.1",
3
+ "version": "10.9.3",
4
4
  "description": "Native Claude Code and Codex session control, history, usage and recoverable local storage for Node.js apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",