jg-agent-hq 10.8.0 → 10.9.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 (44) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +1 -1
  3. package/api/README.md +21 -14
  4. package/dist/actions/live/live.d.ts +11 -0
  5. package/dist/actions/live/live.js +15 -0
  6. package/dist/contracts/types.d.ts +26 -0
  7. package/dist/contracts/types.js +8 -1
  8. package/dist/providers/claude/agents/agents.d.ts +14 -10
  9. package/dist/providers/claude/agents/agents.js +67 -5
  10. package/dist/providers/claude/agents/index.d.ts +1 -0
  11. package/dist/providers/claude/agents/types.d.ts +19 -0
  12. package/dist/providers/claude/agents/types.js +2 -0
  13. package/dist/providers/claude/background/background.d.ts +11 -0
  14. package/dist/providers/claude/background/background.js +175 -0
  15. package/dist/providers/claude/background/constants.d.ts +9 -0
  16. package/dist/providers/claude/background/constants.js +24 -0
  17. package/dist/providers/claude/background/index.d.ts +3 -0
  18. package/dist/providers/claude/background/index.js +4 -0
  19. package/dist/providers/claude/background/types.d.ts +56 -0
  20. package/dist/providers/claude/background/types.js +46 -0
  21. package/dist/providers/claude/background/utilities.d.ts +17 -0
  22. package/dist/providers/claude/background/utilities.js +65 -0
  23. package/dist/providers/claude/history/history.model.d.ts +5 -0
  24. package/dist/providers/claude/history/history.model.js +27 -4
  25. package/dist/providers/claude/history/index.d.ts +1 -0
  26. package/dist/providers/claude/history/index.js +2 -0
  27. package/dist/providers/claude/history/types.d.ts +10 -0
  28. package/dist/providers/claude/history/utilities.d.ts +10 -0
  29. package/dist/providers/claude/history/utilities.js +63 -1
  30. package/dist/providers/codex/transformers.js +2 -0
  31. package/dist/providers/types.d.ts +2 -0
  32. package/dist/runtime/runtime.js +22 -4
  33. package/dist/sessions/sessions.d.ts +4 -4
  34. package/dist/sessions/sessions.js +21 -11
  35. package/dist/sessions/types.d.ts +6 -0
  36. package/dist/store/sessions/sessions.model.d.ts +14 -2
  37. package/dist/store/sessions/sessions.model.js +36 -10
  38. package/dist/store/sessions/types.d.ts +2 -0
  39. package/dist/store/sessions/types.js +3 -2
  40. package/dist/store/store.js +2 -1
  41. package/dist/store/store.worker.js +4 -1
  42. package/dist/store/types.d.ts +27 -2
  43. package/dist/store/types.js +15 -1
  44. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 10.9.0
4
+
5
+ - Report on every session summary how many background commands the session runs, as `backgroundCommands`. A session HQ runs reports the count Claude last reported. A Claude session a terminal runs reports the commands and agents its transcript records as started since its Claude process started and not yet ended. The `claude agents --json` poll counts before it records states, within one 67,108,864-byte read budget per run, and a `thread` read reads the transcript again first. Codex sessions report 0.
6
+ - List idle sessions that run background commands in `active-sessions`, beside the running and waiting ones.
7
+ - Report on a Claude session's summary the session its chat continues in, as `continuedIn`, when Claude Code moved the chat into a new session and left a `continued-in` record at the old transcript's end with no message after it. Other summaries carry null.
8
+ - Store nothing new: the counts and answers are kept in memory, so the schema and existing databases are unchanged.
9
+
3
10
  ## 10.8.0
4
11
 
5
12
  - Report how many commands a session runs in the background. The `live-items` window carries `backgroundCommands`, the count Claude last reported for a session HQ controls, 0 once its process stopped or when its provider reports none, and a change of it is a new revision, so a client that follows the window sees a command keep running after the turn that started it ended, until Claude resumes the session. Providers report it through a new `background` event.
package/README.md CHANGED
@@ -109,7 +109,7 @@ The [qualification matrix](api/README.md#qualification) records native journeys,
109
109
  - `src/runtime/`: trusted configuration and lifetime ownership.
110
110
  - `src/ipc/` and `src/cli/`: private local commands and the installed executable.
111
111
  - `src/providers/codex/`: the shared app-server daemon connection, native history and account protocol.
112
- - `src/providers/claude/`: native structured control and usage, the identity-validated, worker-owned local history reader and the active-session poll.
112
+ - `src/providers/claude/`: native structured control and usage, the identity-validated, worker-owned local history reader, the active-session poll and the background-task counter it reads transcripts with.
113
113
  - `src/providers/registry/`: lazy factories, normalized provider evidence, bounded lifecycle and source isolation.
114
114
  - `src/providers/inputs/` and `src/providers/results/`: checked file delivery and complete native result validation.
115
115
  - `src/providers/configuration/` and `src/providers/lineage/`: bounded native choices and confirmed immutable session relationships.
package/api/README.md CHANGED
@@ -358,9 +358,15 @@ Every session has a live state: `running`, `waiting` (on the operator), `idle`,
358
358
 
359
359
  A Claude session's summary carries `terminal`: `{ kind: 'interactive' }`, or `{ kind: 'background', attachId }` with the short ID `claude attach` takes, while the latest `claude agents --json` run lists it with a `pid`, and null otherwise; Codex summaries always carry null. While it is set, `thread-adopt` and `thread-resume` of the session, and input to it, are refused with JG_AGENT_HQ_ACTION_CONFLICT, so a session HQ runs that a terminal resumed takes nothing from HQ until the terminal closes it. An approval request of a Codex turn reaches every client the daemon serves; when another answers first, HQ's prompt expires.
360
360
 
361
+ Every summary carries `backgroundCommands`, the background tasks the session runs, after which Claude resumes it on its own: commands it runs or moved to the background, and agents it launched there. A session HQ runs reports the count Claude last reported in `system/background_tasks_changed`, the same count its `live-items` window carries. A Claude session a terminal runs reports the tasks its transcript records since its listed process's `startedAt`, as the active-session poll below counts them. Codex sessions, and Claude sessions no run lists, report 0.
362
+
363
+ Every summary also carries `continuedIn`. When Claude Code moves a chat into a new session, it ends the old session's transcript with a `continued-in` record naming the new session in `continuedInSessionId`. A Claude session's summary from its indexed transcript carries that session's ID when the record is in the transcript's last 65,536 bytes with no `user` or `assistant` record after it, and the named session's transcript is in the same Claude project directory; otherwise, and for managed, Codex and `active-sessions` summaries, it is null. A session resumed after the move wrote messages after the record, so it continues in none. The answer is kept in memory per transcript, at most 1,024 of them, and read again once the transcript's size or modification time changes.
364
+
361
365
  - **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`. A session already running when the connection opens reports no change, so each time the connection opens, including after a reconnect, HQ reads the daemon's loaded threads (`thread/loaded/list`, 128 a page, at most 8 pages) and records each one's state from its status. 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.
362
366
  - **Claude.** While the runtime runs, HQ runs `claude agents --json` every 30 seconds, or every 5 seconds at the `live` pace, each run limited to 10 seconds and 65,536 bytes of output, and joins its entries to Claude discovery by `sessionId`. An entry without a `pid` isn't running, whatever its `state` says, so it counts as missing. Otherwise `status: "busy"` and a background session's `state: "working"` are running, `status: "waiting"` (a question or a permission prompt, for either kind of session) and an interactive `status: "blocked"` are waiting, `status: "idle"` is idle, and anything else is unknown; an entry missing from a run is closed. Entries whose `pid` is a native process this runtime started, its managed sessions and its metadata process, are left out. A failed, late, oversized or malformed run changes nothing. Sessions HQ manages keep their managed records.
363
367
 
368
+ Before a run records its states, it counts each listed session's background tasks from its transcript. That transcript is the one in the Claude project directory of the entry's `cwd`, or else of the workspace its indexed transcript was found in. A task starts with a tool result whose `toolUseResult` holds a `backgroundTaskId`, or an `isAsync` agent launch with its `agentId`, written at or after the entry's `startedAt`. It ends with a `<task-notification>` naming its `<task-id>`, in a message or a queued input, a `task_status` attachment whose status isn't `running`, or a TaskStop or KillShell call whose result isn't an error, in whichever order the call and result were written. Sidechain records and `api-request-blob` copies are skipped, and at most 256 tasks are tracked per session. Each run reads only what the transcripts gained since the last one, in 65,536-byte chunks and at most 67,108,864 bytes across all listed sessions, parsing only lines that hold one of those records. A session whose transcript the budget stopped short of its end reports 0 until a later run finishes it, and a transcript that can't be read reports 0. A `thread` read of a listed session reads its transcript first, with its own 67,108,864-byte budget, so a task that started after the latest run counts at once. The counts are kept in memory and rebuilt after a restart.
369
+
364
370
  `{ 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`. Every page also returns `latestSequence`, the highest sequence ever issued, or 0 before the first, so a reader can start after it to follow only new transitions, and `isReset`, true when the reader can't continue exactly after `afterSequence`: it is above `latestSequence`, as after a fresh state root or the restore of an older snapshot, or it is above 0 and its own transition was pruned. The page still holds the transitions after `afterSequence` that remain.
365
371
 
366
372
  | Reason | When |
@@ -376,7 +382,7 @@ A Claude session's summary carries `terminal`: `{ kind: 'interactive' }`, or `{
376
382
 
377
383
  Transitions survive restarts. Each new transition deletes up to 128 transitions older than seven days, and closed observed sessions are forgotten after seven days. A managed session's stopping phase records no transition of its own.
378
384
 
379
- `{ kind: 'active-sessions' }` returns every running and waiting session, managed and observed, at most 128 and newest state change first, with `isTruncated` when more are active. Each comes as the summary `threads` returns, with its workspace root, name and timestamps. A managed session reads them from its HQ record. An observed Claude session's workspace is the `cwd` the latest `claude agents --json` run reported, so it is left out until the first run after the runtime starts lists it; its name and timestamps come from its indexed transcript, and are null and its state's change time while the transcript isn't indexed. An observed Codex session's summary comes from `thread/read`, and other providers' observed sessions from their optional `readObservedThread`. A session outside the allowed workspaces, or one its provider can't read, is left out.
385
+ `{ kind: 'active-sessions' }` returns every running and waiting session, managed and observed, and every idle session with `backgroundCommands` above 0, at most 128 and newest state change first, with `isTruncated` when more are active. Each comes as the summary `threads` returns, with its workspace root, name and timestamps. A managed session reads them from its HQ record. An observed Claude session's workspace is the `cwd` the latest `claude agents --json` run reported, so it is left out until the first run after the runtime starts lists it; its name and timestamps come from its indexed transcript, and are null and its state's change time while the transcript isn't indexed. An observed Codex session's summary comes from `thread/read`, and other providers' observed sessions from their optional `readObservedThread`. A session outside the allowed workspaces, or one its provider can't read, is left out.
380
386
 
381
387
  `{ kind: 'unstarted-threads', provider, workspaceRoot }` returns that workspace's managed threads that no turn has started, at most 32 and newest first, with `isTruncated` when more exist: each was created empty with `thread-create`, has a native ID and no active or last turn, and is neither archived nor closed. Forks and adopted sessions start with native history, so they never count. Each comes as the summary `threads` returns, from its HQ record. `thread` answers for such a thread from its record too, and `items` with an empty page, so its session opens before the provider has written any history.
382
388
 
@@ -432,19 +438,20 @@ Live reads accept `afterRevision`. A matching revision returns `unchanged: true`
432
438
 
433
439
  The operation matrix describes the implemented native interfaces and their explicit unavailable surfaces. Executed qualification is narrower than every possible model, configuration and account state. Native versions below are observations, never admission rules.
434
440
 
435
- | Area | Executed evidence | Boundary |
436
- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
437
- | Provider integration | Public contract tests route a third provider, isolate unavailable providers and tolerate additive fields and future version labels. Native lifecycle, configuration, files, account and extension checks are listed in their sections above. | Each additional adapter needs its own native qualification. |
438
- | Identity and native interaction | Both providers retained managed/native identities after compaction and reconnect with a fresh runtime epoch. Codex interruption and continuation passed. Claude AskUserQuestion and scoped MCP permission replies used exact native identities. | A timed-out compaction retained uncertain delivery even when completion later arrived; it was not resent. Explicit resume followed confirmed controller shutdown. |
439
- | Recovery | After removing all eight qualification transcripts, offline recovery retained the host preference and providers stayed idle. | Native transcripts, repository files and authentication remain separate recovery responsibilities. |
440
- | 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 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. |
441
- | Codex across restarts | Codex 0.166.0 on 2026-11-01: a turn whose client closed its connection mid-turn ran to completion in the daemon, which kept the session loaded and idle. A command approval that arrived before the connection closed stayed pending, with the session `waitingOnApproval`; after a new connection joined with `thread/resume`, the daemon sent it again under the same request ID, and answering it completed the turn. |
442
- | Claude permission requests | Claude Code 2.1.316 on 2026-11-01, in the default permission mode: a Write request carried `description`, `display_name`, `input`, `permission_suggestions`, `subtype`, `tool_name` and `tool_use_id`, and an error reply was recorded in the transcript as the tool call's failed result with the reply's text. | Fields such as `decision_reason_code` and `tool_kind` appear only in other modes, so their shape comes from the CLI's own code, not an observed request. |
443
- | Claude turns it starts itself | Claude Code 2.1.316 on 2026-11-01, in the auto permission mode with its input held open: when a background command finished after its turn, Claude sent `system:task_notification` and started a turn of its own, `system:init` then stream and assistant frames, ending in a `result` without `user_message_uuid`. Input written during that turn was replayed after its result as its own turn. Each HQ input's replayed message came before its turn's first stream and assistant frames. An interrupt ended such a turn with the interruption marker, then an `error_during_execution` result. `system:background_tasks_changed` listed the background commands running, and was empty once the last one ended. | The frame order is an observation of this version, not a native contract. |
444
- | Approvals on other clients' sessions | Codex 0.166.0 on 2026-11-01, on the shared daemon: connection A joined a thread connection B started, with `thread/resume`. When B's turn asked to run a command, the daemon sent the same approval request, with the same request ID, to both connections, and sent both `serverRequest/resolved` once B answered. | A thread only accepts `thread/resume` once its first turn has written its rollout. |
445
- | Large file inputs | Claude Code 2.1.316 and Codex 0.166.0 on 2026-11-02. Claude took one message with a 15,814,657-byte, three-page PDF and a 262,144-byte text file, 16,076,801 bytes in all, and answered from both; its transcript held the message as a 21,355,974-byte record, which history read on a page of its own. Codex took one message with seven PNG images of about 2.4 MB each and a text file, 16,531,190 bytes in all, sent to the shared daemon in 1,048,576-byte WebSocket fragments, and answered from every image. In each session a text-only follow-up turn then completed, and its history pages and every message's item detail read. | The provider's own limits on PDF pages and image sizes were not reached. A Claude session keeps each attachment in its transcript, so it grows by the attachments' base64 size. |
446
- | 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. |
447
- | Host coverage | Linux x86_64 package checks passed on Node 24.15.0 and 24.22.1. Identity, native interaction and recovery ran on the floor and on 24.22.1. | No macOS host was available for this run. Windows is outside the declared host contract. |
441
+ | Area | Executed evidence | Boundary |
442
+ | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
443
+ | Provider integration | Public contract tests route a third provider, isolate unavailable providers and tolerate additive fields and future version labels. Native lifecycle, configuration, files, account and extension checks are listed in their sections above. | Each additional adapter needs its own native qualification. |
444
+ | Identity and native interaction | Both providers retained managed/native identities after compaction and reconnect with a fresh runtime epoch. Codex interruption and continuation passed. Claude AskUserQuestion and scoped MCP permission replies used exact native identities. | A timed-out compaction retained uncertain delivery even when completion later arrived; it was not resent. Explicit resume followed confirmed controller shutdown. |
445
+ | Recovery | After removing all eight qualification transcripts, offline recovery retained the host preference and providers stayed idle. | Native transcripts, repository files and authentication remain separate recovery responsibilities. |
446
+ | 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 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. |
447
+ | Codex across restarts | Codex 0.166.0 on 2026-11-01: a turn whose client closed its connection mid-turn ran to completion in the daemon, which kept the session loaded and idle. A command approval that arrived before the connection closed stayed pending, with the session `waitingOnApproval`; after a new connection joined with `thread/resume`, the daemon sent it again under the same request ID, and answering it completed the turn. |
448
+ | Claude permission requests | Claude Code 2.1.316 on 2026-11-01, in the default permission mode: a Write request carried `description`, `display_name`, `input`, `permission_suggestions`, `subtype`, `tool_name` and `tool_use_id`, and an error reply was recorded in the transcript as the tool call's failed result with the reply's text. | Fields such as `decision_reason_code` and `tool_kind` appear only in other modes, so their shape comes from the CLI's own code, not an observed request. |
449
+ | Claude turns it starts itself | Claude Code 2.1.316 on 2026-11-01, in the auto permission mode with its input held open: when a background command finished after its turn, Claude sent `system:task_notification` and started a turn of its own, `system:init` then stream and assistant frames, ending in a `result` without `user_message_uuid`. Input written during that turn was replayed after its result as its own turn. Each HQ input's replayed message came before its turn's first stream and assistant frames. An interrupt ended such a turn with the interruption marker, then an `error_during_execution` result. `system:background_tasks_changed` listed the background commands running, and was empty once the last one ended. | The frame order is an observation of this version, not a native contract. |
450
+ | Approvals on other clients' sessions | Codex 0.166.0 on 2026-11-01, on the shared daemon: connection A joined a thread connection B started, with `thread/resume`. When B's turn asked to run a command, the daemon sent the same approval request, with the same request ID, to both connections, and sent both `serverRequest/resolved` once B answered. | A thread only accepts `thread/resume` once its first turn has written its rollout. |
451
+ | Large file inputs | Claude Code 2.1.316 and Codex 0.166.0 on 2026-11-02. Claude took one message with a 15,814,657-byte, three-page PDF and a 262,144-byte text file, 16,076,801 bytes in all, and answered from both; its transcript held the message as a 21,355,974-byte record, which history read on a page of its own. Codex took one message with seven PNG images of about 2.4 MB each and a text file, 16,531,190 bytes in all, sent to the shared daemon in 1,048,576-byte WebSocket fragments, and answered from every image. In each session a text-only follow-up turn then completed, and its history pages and every message's item detail read. | The provider's own limits on PDF pages and image sizes were not reached. A Claude session keeps each attachment in its transcript, so it grows by the attachments' base64 size. |
452
+ | 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. |
453
+ | Claude background tasks and moved chats | Claude Code 2.1.317 records a command run in or moved to the background as a tool result whose `toolUseResult` holds `backgroundTaskId`, and an agent launched there as one with `isAsync` and `agentId`. A task's end is a `<task-notification>` with its `<task-id>` and `<status>` (`completed`, `failed`, `killed`, `stopped`), written as a message and as a queued input, or a `task_status` attachment after a compaction. A TaskStop result often comes with no notification, and can be written before the assistant record that holds its call. Moving a chat into a new session ends the old transcript with `continued-in` and `continuedInSessionId`, followed only by `ephemeral` and `cost-state` records. Before 10.9.0, the count matched the Bash tool shells of every idle listed session, of a running background command, and of one stopped with TaskStop. | Monitor tasks are not counted. A record shape another version changes counts as absent, which leaves a task's start or end unseen. |
454
+ | Host coverage | Linux x86_64 package checks passed on Node 24.15.0 and 24.22.1. Identity, native interaction and recovery ran on the floor and on 24.22.1. | No macOS host was available for this run. Windows is outside the declared host contract. |
448
455
 
449
456
  The 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.
450
457
 
@@ -10,6 +10,17 @@ export declare class LiveItems {
10
10
  put(nativeId: string, item: IHistoryItem, isComplete: boolean): void;
11
11
  /** Records how many commands a session runs in the background, a change of its window. */
12
12
  setBackgroundCommands(nativeId: string, count: number): void;
13
+ /**
14
+ * Reads how many commands a session runs in the background, as its provider last reported.
15
+ * @param nativeId The session's key.
16
+ * @returns The count, or 0 for a session without a window.
17
+ */
18
+ backgroundCommandsOf(nativeId: string): number;
19
+ /**
20
+ * Lists the sessions that run commands in the background.
21
+ * @returns Their keys.
22
+ */
23
+ backgroundKeys(): string[];
13
24
  /** Clears a reverted presentation and requires a fresh native history read. */
14
25
  reset(nativeId: string): void;
15
26
  /** Marks missing native stream evidence without discarding the surviving presentation. */
@@ -58,6 +58,21 @@ export class LiveItems {
58
58
  thread.backgroundCommands = count;
59
59
  thread.revision = ++this.__revision;
60
60
  }
61
+ /**
62
+ * Reads how many commands a session runs in the background, as its provider last reported.
63
+ * @param nativeId The session's key.
64
+ * @returns The count, or 0 for a session without a window.
65
+ */
66
+ backgroundCommandsOf(nativeId) {
67
+ return this.__threads.get(nativeId)?.backgroundCommands ?? 0;
68
+ }
69
+ /**
70
+ * Lists the sessions that run commands in the background.
71
+ * @returns Their keys.
72
+ */
73
+ backgroundKeys() {
74
+ return [...this.__threads].flatMap(([key, thread]) => thread.backgroundCommands > 0 ? [key] : []);
75
+ }
61
76
  /** Clears a reverted presentation and requires a fresh native history read. */
62
77
  reset(nativeId) {
63
78
  // the session's background commands outlive its reverted presentation
@@ -508,6 +508,8 @@ export declare const ThreadSummarySchema: z.ZodObject<{
508
508
  kind: z.ZodLiteral<"background">;
509
509
  attachId: z.ZodString;
510
510
  }, z.core.$strip>], "kind">>;
511
+ backgroundCommands: z.ZodNumber;
512
+ continuedIn: z.ZodNullable<z.ZodString>;
511
513
  }, z.core.$strip>;
512
514
  export type IThreadSummary = z.infer<typeof ThreadSummarySchema>;
513
515
  export declare const ActiveSessionsSchema: z.ZodObject<{
@@ -554,6 +556,8 @@ export declare const ActiveSessionsSchema: z.ZodObject<{
554
556
  kind: z.ZodLiteral<"background">;
555
557
  attachId: z.ZodString;
556
558
  }, z.core.$strip>], "kind">>;
559
+ backgroundCommands: z.ZodNumber;
560
+ continuedIn: z.ZodNullable<z.ZodString>;
557
561
  }, z.core.$strip>>;
558
562
  isTruncated: z.ZodBoolean;
559
563
  }, z.core.$strip>;
@@ -602,6 +606,8 @@ export declare const UnstartedThreadsSchema: z.ZodObject<{
602
606
  kind: z.ZodLiteral<"background">;
603
607
  attachId: z.ZodString;
604
608
  }, z.core.$strip>], "kind">>;
609
+ backgroundCommands: z.ZodNumber;
610
+ continuedIn: z.ZodNullable<z.ZodString>;
605
611
  }, z.core.$strip>>;
606
612
  isTruncated: z.ZodBoolean;
607
613
  }, z.core.$strip>;
@@ -1044,6 +1050,8 @@ export declare const HqResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
1044
1050
  kind: z.ZodLiteral<"background">;
1045
1051
  attachId: z.ZodString;
1046
1052
  }, z.core.$strip>], "kind">>;
1053
+ backgroundCommands: z.ZodNumber;
1054
+ continuedIn: z.ZodNullable<z.ZodString>;
1047
1055
  isNameTruncated: z.ZodBoolean;
1048
1056
  }, z.core.$strip>>;
1049
1057
  nextCursor: z.ZodNullable<z.ZodString>;
@@ -1954,6 +1962,8 @@ export declare const HqResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
1954
1962
  kind: z.ZodLiteral<"background">;
1955
1963
  attachId: z.ZodString;
1956
1964
  }, z.core.$strip>], "kind">>;
1965
+ backgroundCommands: z.ZodNumber;
1966
+ continuedIn: z.ZodNullable<z.ZodString>;
1957
1967
  }, z.core.$strip>>;
1958
1968
  }, z.core.$strip>;
1959
1969
  }, z.core.$strip>, z.ZodObject<{
@@ -2001,6 +2011,8 @@ export declare const HqResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
2001
2011
  kind: z.ZodLiteral<"background">;
2002
2012
  attachId: z.ZodString;
2003
2013
  }, z.core.$strip>], "kind">>;
2014
+ backgroundCommands: z.ZodNumber;
2015
+ continuedIn: z.ZodNullable<z.ZodString>;
2004
2016
  }, z.core.$strip>;
2005
2017
  }, z.core.$strip>, z.ZodObject<{
2006
2018
  kind: z.ZodLiteral<"turns">;
@@ -3086,6 +3098,8 @@ export declare const HqResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
3086
3098
  kind: z.ZodLiteral<"background">;
3087
3099
  attachId: z.ZodString;
3088
3100
  }, z.core.$strip>], "kind">>;
3101
+ backgroundCommands: z.ZodNumber;
3102
+ continuedIn: z.ZodNullable<z.ZodString>;
3089
3103
  }, z.core.$strip>>;
3090
3104
  isTruncated: z.ZodBoolean;
3091
3105
  }, z.core.$strip>;
@@ -3135,6 +3149,8 @@ export declare const HqResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
3135
3149
  kind: z.ZodLiteral<"background">;
3136
3150
  attachId: z.ZodString;
3137
3151
  }, z.core.$strip>], "kind">>;
3152
+ backgroundCommands: z.ZodNumber;
3153
+ continuedIn: z.ZodNullable<z.ZodString>;
3138
3154
  }, z.core.$strip>>;
3139
3155
  isTruncated: z.ZodBoolean;
3140
3156
  }, z.core.$strip>;
@@ -3755,6 +3771,8 @@ export declare const IpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
3755
3771
  kind: z.ZodLiteral<"background">;
3756
3772
  attachId: z.ZodString;
3757
3773
  }, z.core.$strip>], "kind">>;
3774
+ backgroundCommands: z.ZodNumber;
3775
+ continuedIn: z.ZodNullable<z.ZodString>;
3758
3776
  isNameTruncated: z.ZodBoolean;
3759
3777
  }, z.core.$strip>>;
3760
3778
  nextCursor: z.ZodNullable<z.ZodString>;
@@ -4665,6 +4683,8 @@ export declare const IpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
4665
4683
  kind: z.ZodLiteral<"background">;
4666
4684
  attachId: z.ZodString;
4667
4685
  }, z.core.$strip>], "kind">>;
4686
+ backgroundCommands: z.ZodNumber;
4687
+ continuedIn: z.ZodNullable<z.ZodString>;
4668
4688
  }, z.core.$strip>>;
4669
4689
  }, z.core.$strip>;
4670
4690
  }, z.core.$strip>, z.ZodObject<{
@@ -4712,6 +4732,8 @@ export declare const IpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
4712
4732
  kind: z.ZodLiteral<"background">;
4713
4733
  attachId: z.ZodString;
4714
4734
  }, z.core.$strip>], "kind">>;
4735
+ backgroundCommands: z.ZodNumber;
4736
+ continuedIn: z.ZodNullable<z.ZodString>;
4715
4737
  }, z.core.$strip>;
4716
4738
  }, z.core.$strip>, z.ZodObject<{
4717
4739
  kind: z.ZodLiteral<"turns">;
@@ -5797,6 +5819,8 @@ export declare const IpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
5797
5819
  kind: z.ZodLiteral<"background">;
5798
5820
  attachId: z.ZodString;
5799
5821
  }, z.core.$strip>], "kind">>;
5822
+ backgroundCommands: z.ZodNumber;
5823
+ continuedIn: z.ZodNullable<z.ZodString>;
5800
5824
  }, z.core.$strip>>;
5801
5825
  isTruncated: z.ZodBoolean;
5802
5826
  }, z.core.$strip>;
@@ -5846,6 +5870,8 @@ export declare const IpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
5846
5870
  kind: z.ZodLiteral<"background">;
5847
5871
  attachId: z.ZodString;
5848
5872
  }, z.core.$strip>], "kind">>;
5873
+ backgroundCommands: z.ZodNumber;
5874
+ continuedIn: z.ZodNullable<z.ZodString>;
5849
5875
  }, z.core.$strip>>;
5850
5876
  isTruncated: z.ZodBoolean;
5851
5877
  }, z.core.$strip>;
@@ -169,8 +169,15 @@ export const ThreadSummarySchema = z.object({
169
169
  historyState: z.enum(['available', 'unavailable']),
170
170
  // the terminal that runs the session, while one does; always null for Codex
171
171
  terminal: SessionTerminalSchema.nullable(),
172
+ // the background tasks the session runs, which Claude resumes it after; 0 when none or unknown
173
+ backgroundCommands: z.number().int().nonnegative(),
174
+ // the session a Claude session's chat continues in, when its transcript names one beside it
175
+ continuedIn: NativeIdSchema.nullable(),
172
176
  });
173
- // every running and waiting session, newest state change first, with whether more are active
177
+ /*
178
+ * Every running and waiting session, and every idle one that runs background commands, newest
179
+ * state change first, with whether more are active.
180
+ */
174
181
  export const ActiveSessionsSchema = z.object({
175
182
  data: z.array(ThreadSummarySchema).max(MAX_PAGE_SIZE),
176
183
  isTruncated: z.boolean(),
@@ -1,5 +1,5 @@
1
- import type { IObservationPace, ISessionState, ISessionTerminal } from '../../../contracts/index.js';
2
- import { type IClaudeAgent } from './types.js';
1
+ import type { ISessionState } from '../../../contracts/index.js';
2
+ import { type IClaudeAgent, type IClaudeAgentsObserver } from './types.js';
3
3
  /**
4
4
  * Maps a running session's report to the shared session state. A session waiting on a question or
5
5
  * a permission prompt reports `status: "waiting"`, as an interactive one may also report
@@ -11,15 +11,19 @@ export declare const toAgentState: (agent: IClaudeAgent) => ISessionState;
11
11
  * sessions inside the allowed workspaces, so a session missing from a run is closed. A failed,
12
12
  * late, oversized or malformed run changes nothing. Runs follow one another at the `background`
13
13
  * pace until `setPace` selects another, which takes effect with an immediate run.
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.
14
+ *
15
+ * Before it records their states, each run counts every listed session's background tasks from
16
+ * its transcript, read since its Claude process started, within one byte budget for the whole run.
17
+ * A transcript is looked for in the Claude project directory of the session's `cwd`, then in that
18
+ * of the workspace `locateTranscript` resolves for its indexed transcript.
19
+ * @param record Records the states of the sessions a run listed.
20
+ * @param allowedRoots The workspaces whose sessions are observed.
21
+ * @param locateTranscript Resolves to the workspace root of a session's indexed transcript, or null.
22
+ * @returns A handle that sets the pace, reports each listed session's `cwd`, the terminal that runs
23
+ * it and its background tasks from the latest run, reads a session's tasks again on request, and
24
+ * whose close stops polling and waits for a run in progress.
16
25
  */
17
26
  export declare const observeClaudeAgents: (record: (sessions: {
18
27
  nativeId: string;
19
28
  state: ISessionState;
20
- }[]) => Promise<void>, allowedRoots: string[]) => {
21
- setPace(pace: IObservationPace): void;
22
- workspaceOf(nativeId: string): string | undefined;
23
- terminalOf(nativeId: string): ISessionTerminal | null;
24
- close(): Promise<void>;
25
- };
29
+ }[]) => Promise<void>, allowedRoots: string[], locateTranscript: (nativeId: string) => Promise<string | null>) => IClaudeAgentsObserver;
@@ -1,10 +1,15 @@
1
1
  import { execFile } from 'node:child_process';
2
+ import { access } from 'node:fs/promises';
3
+ import { join } from 'node:path';
2
4
  import { promisify } from 'node:util';
3
5
  import { delay } from 'jg-utilities';
6
+ import { z } from 'zod';
4
7
  import { isOwnedProcess } from '../../process.js';
5
8
  import { resolveWorkspaceTarget } from '../../../runtime/state/index.js';
9
+ import { createClaudeBackgroundTasks, READ_BUDGET_BYTES } from '../background/index.js';
10
+ import { projectDirectory } from '../history/index.js';
6
11
  import { AGENTS_BACKGROUND_SECONDS, AGENTS_DEADLINE_MS, AGENTS_LIVE_SECONDS, AGENTS_OUTPUT_BYTES, } from './constants.js';
7
- import { ClaudeAgentsSchema } from './types.js';
12
+ import { ClaudeAgentsSchema, } from './types.js';
8
13
  const run = promisify(execFile);
9
14
  /**
10
15
  * Maps a running session's report to the shared session state. A session waiting on a question or
@@ -23,15 +28,25 @@ export const toAgentState = (agent) => agent.status === 'busy' || agent.state ==
23
28
  * sessions inside the allowed workspaces, so a session missing from a run is closed. A failed,
24
29
  * late, oversized or malformed run changes nothing. Runs follow one another at the `background`
25
30
  * pace until `setPace` selects another, which takes effect with an immediate run.
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.
31
+ *
32
+ * Before it records their states, each run counts every listed session's background tasks from
33
+ * its transcript, read since its Claude process started, within one byte budget for the whole run.
34
+ * A transcript is looked for in the Claude project directory of the session's `cwd`, then in that
35
+ * of the workspace `locateTranscript` resolves for its indexed transcript.
36
+ * @param record Records the states of the sessions a run listed.
37
+ * @param allowedRoots The workspaces whose sessions are observed.
38
+ * @param locateTranscript Resolves to the workspace root of a session's indexed transcript, or null.
39
+ * @returns A handle that sets the pace, reports each listed session's `cwd`, the terminal that runs
40
+ * it and its background tasks from the latest run, reads a session's tasks again on request, and
41
+ * whose close stops polling and waits for a run in progress.
28
42
  */
29
- export const observeClaudeAgents = (record, allowedRoots) => {
43
+ export const observeClaudeAgents = (record, allowedRoots, locateTranscript) => {
30
44
  const lifetime = new AbortController();
31
45
  // whether each session directory is inside an allowed workspace, checked once per directory
32
46
  const allowedDirectories = new Map();
33
- // the cwd and terminal of each session the latest run listed, which no other source reports
47
+ // what the latest run listed about each session, which no other source reports
34
48
  let listedSessions = new Map();
49
+ const background = createClaudeBackgroundTasks();
35
50
  let pace = 'background';
36
51
  let wait = new AbortController();
37
52
  const isAllowed = async (directory) => {
@@ -46,6 +61,26 @@ export const observeClaudeAgents = (record, allowedRoots) => {
46
61
  }
47
62
  return isInside;
48
63
  };
64
+ // the Claude project directory that holds a session's transcript, or null when none does
65
+ const findDirectory = async (nativeId, cwd) => {
66
+ if (!z.uuid().safeParse(nativeId).success)
67
+ return null;
68
+ try {
69
+ const directory = projectDirectory(cwd);
70
+ await access(join(directory, `${nativeId}.jsonl`));
71
+ return directory;
72
+ }
73
+ catch {
74
+ // the session may have started in another folder, whose project directory holds it
75
+ }
76
+ try {
77
+ const root = await locateTranscript(nativeId);
78
+ return root === null ? null : projectDirectory(root);
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ };
49
84
  const poll = async () => {
50
85
  let agents;
51
86
  try {
@@ -73,10 +108,25 @@ export const observeClaudeAgents = (record, allowedRoots) => {
73
108
  terminal: agent.kind === 'background' && agent.id
74
109
  ? { kind: 'background', attachId: agent.id }
75
110
  : { kind: 'interactive' },
111
+ startedAt: agent.startedAt ?? null,
112
+ directory: null,
113
+ backgroundCommands: 0,
76
114
  });
77
115
  }
116
+ // counts are current before the states they explain are recorded
117
+ const budget = { remaining: READ_BUDGET_BYTES };
118
+ for (const [nativeId, session] of listed) {
119
+ if (lifetime.signal.aborted)
120
+ return;
121
+ session.directory = await findDirectory(nativeId, session.cwd);
122
+ if (session.directory !== null)
123
+ session.backgroundCommands = await background.update(nativeId, session.directory, session.startedAt, budget);
124
+ }
78
125
  if (lifetime.signal.aborted)
79
126
  return;
127
+ for (const nativeId of listedSessions.keys())
128
+ if (!listed.has(nativeId))
129
+ background.forget(nativeId);
80
130
  listedSessions = listed;
81
131
  await record(sessions);
82
132
  };
@@ -98,6 +148,18 @@ export const observeClaudeAgents = (record, allowedRoots) => {
98
148
  },
99
149
  workspaceOf: (nativeId) => listedSessions.get(nativeId)?.cwd,
100
150
  terminalOf: (nativeId) => listedSessions.get(nativeId)?.terminal ?? null,
151
+ backgroundCommandsOf: (nativeId) => listedSessions.get(nativeId)?.backgroundCommands ?? 0,
152
+ async refreshBackgroundCommands(nativeId) {
153
+ const session = listedSessions.get(nativeId);
154
+ if (!session)
155
+ return 0;
156
+ session.directory ??= await findDirectory(nativeId, session.cwd);
157
+ if (session.directory === null)
158
+ return 0;
159
+ session.backgroundCommands = await background.update(nativeId, session.directory, session.startedAt, { remaining: READ_BUDGET_BYTES });
160
+ return session.backgroundCommands;
161
+ },
162
+ backgroundSessionIds: () => [...listedSessions].flatMap(([nativeId, session]) => session.backgroundCommands > 0 ? [nativeId] : []),
101
163
  async close() {
102
164
  lifetime.abort();
103
165
  await running;
@@ -1 +1,2 @@
1
+ export type { IClaudeAgentsObserver } from './types.js';
1
2
  export { observeClaudeAgents, toAgentState } from './agents.js';
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import type { IObservationPace, ISessionTerminal } from '../../../contracts/index.js';
2
3
  export declare const ClaudeAgentSchema: z.ZodObject<{
3
4
  id: z.ZodOptional<z.ZodString>;
4
5
  kind: z.ZodOptional<z.ZodString>;
@@ -7,6 +8,7 @@ export declare const ClaudeAgentSchema: z.ZodObject<{
7
8
  pid: z.ZodOptional<z.ZodNumber>;
8
9
  status: z.ZodOptional<z.ZodString>;
9
10
  state: z.ZodOptional<z.ZodString>;
11
+ startedAt: z.ZodOptional<z.ZodNumber>;
10
12
  }, z.core.$strip>;
11
13
  export type IClaudeAgent = z.infer<typeof ClaudeAgentSchema>;
12
14
  export declare const ClaudeAgentsSchema: z.ZodArray<z.ZodObject<{
@@ -17,4 +19,21 @@ export declare const ClaudeAgentsSchema: z.ZodArray<z.ZodObject<{
17
19
  pid: z.ZodOptional<z.ZodNumber>;
18
20
  status: z.ZodOptional<z.ZodString>;
19
21
  state: z.ZodOptional<z.ZodString>;
22
+ startedAt: z.ZodOptional<z.ZodNumber>;
20
23
  }, z.core.$strip>>;
24
+ export type IListedSession = {
25
+ cwd: string;
26
+ terminal: ISessionTerminal;
27
+ startedAt: number | null;
28
+ directory: string | null;
29
+ backgroundCommands: number;
30
+ };
31
+ export type IClaudeAgentsObserver = {
32
+ setPace(pace: IObservationPace): void;
33
+ workspaceOf(nativeId: string): string | undefined;
34
+ terminalOf(nativeId: string): ISessionTerminal | null;
35
+ backgroundCommandsOf(nativeId: string): number;
36
+ refreshBackgroundCommands(nativeId: string): Promise<number>;
37
+ backgroundSessionIds(): string[];
38
+ close(): Promise<void>;
39
+ };
@@ -10,5 +10,7 @@ export const ClaudeAgentSchema = z.object({
10
10
  pid: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
11
11
  status: z.string().max(64).optional(),
12
12
  state: z.string().max(64).optional(),
13
+ // when the session's Claude process started, in Unix milliseconds
14
+ startedAt: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
13
15
  });
14
16
  export const ClaudeAgentsSchema = z.array(ClaudeAgentSchema).max(1024);
@@ -0,0 +1,11 @@
1
+ import type { IClaudeBackgroundTasks } from './types.js';
2
+ /**
3
+ * Counts each Claude session's background tasks from its transcript, reading only what was written
4
+ * since the last read, in chunks, within the byte budget the caller shares across reads. A
5
+ * replaced or shortened transcript, or a new Claude process, is read again from its start. A
6
+ * line longer than the history reader's record limit is skipped.
7
+ * @returns The counter: `update` resolves to the session's running tasks, or 0 while its read
8
+ * hasn't reached the transcript's end or the transcript can't be read; updates of one session run
9
+ * one at a time, and `forget` drops a session's state.
10
+ */
11
+ export declare const createClaudeBackgroundTasks: () => IClaudeBackgroundTasks;