jg-agent-hq 4.0.2 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +4 -4
  3. package/api/README.md +20 -12
  4. package/dist/cli/cli.js +23 -2
  5. package/dist/contracts/agent-tools/types.d.ts +2 -0
  6. package/dist/contracts/browser/types.d.ts +11 -0
  7. package/dist/contracts/constants.d.ts +1 -0
  8. package/dist/contracts/constants.js +2 -0
  9. package/dist/contracts/evidence/types.d.ts +4 -0
  10. package/dist/contracts/evidence/types.js +2 -1
  11. package/dist/contracts/index.d.ts +5 -5
  12. package/dist/contracts/index.js +3 -3
  13. package/dist/contracts/sessions/index.d.ts +2 -2
  14. package/dist/contracts/sessions/index.js +1 -1
  15. package/dist/contracts/sessions/types.d.ts +5 -0
  16. package/dist/contracts/sessions/types.js +2 -0
  17. package/dist/contracts/types.d.ts +242 -0
  18. package/dist/contracts/types.js +37 -5
  19. package/dist/providers/claude/agents/agents.d.ts +7 -3
  20. package/dist/providers/claude/agents/agents.js +33 -19
  21. package/dist/providers/claude/agents/constants.d.ts +2 -1
  22. package/dist/providers/claude/agents/constants.js +3 -2
  23. package/dist/providers/claude/claude.js +80 -30
  24. package/dist/providers/claude/control/control.d.ts +44 -5
  25. package/dist/providers/claude/control/control.js +425 -228
  26. package/dist/providers/claude/control/stream.js +22 -6
  27. package/dist/providers/claude/control/types.d.ts +7 -0
  28. package/dist/providers/claude/history/history.model.js +23 -17
  29. package/dist/providers/claude/history/types.d.ts +88 -0
  30. package/dist/providers/claude/history/types.js +15 -0
  31. package/dist/providers/claude/history/utilities.d.ts +6 -4
  32. package/dist/providers/claude/history/utilities.js +146 -52
  33. package/dist/providers/codex/adapter.js +33 -4
  34. package/dist/providers/codex/codex.js +5 -4
  35. package/dist/providers/codex/events.js +3 -1
  36. package/dist/providers/codex/transformers.d.ts +4 -2
  37. package/dist/providers/codex/transformers.js +80 -21
  38. package/dist/providers/codex/types.d.ts +4 -3
  39. package/dist/providers/registry/registry.js +12 -9
  40. package/dist/providers/registry/types.d.ts +1 -1
  41. package/dist/providers/registry/validations.js +7 -0
  42. package/dist/providers/types.d.ts +7 -1
  43. package/dist/runtime/runtime.js +20 -4
  44. package/dist/sessions/evidence/utilities.js +3 -1
  45. package/dist/sessions/index.d.ts +2 -2
  46. package/dist/sessions/index.js +3 -3
  47. package/dist/sessions/sessions.d.ts +11 -1
  48. package/dist/sessions/sessions.js +89 -7
  49. package/dist/sessions/utilities.d.ts +15 -0
  50. package/dist/sessions/utilities.js +19 -0
  51. package/dist/store/schema.sql +1 -1
  52. package/dist/store/sessions/index.d.ts +2 -0
  53. package/dist/store/sessions/index.js +2 -0
  54. package/dist/store/sessions/sessions.model.d.ts +9 -0
  55. package/dist/store/sessions/sessions.model.js +55 -0
  56. package/dist/store/sessions/types.d.ts +67 -0
  57. package/dist/store/sessions/types.js +36 -0
  58. package/dist/store/store.js +2 -0
  59. package/dist/store/store.worker.js +3 -0
  60. package/dist/store/types.d.ts +40 -0
  61. package/dist/store/types.js +1 -0
  62. package/package.json +1 -1
@@ -353,7 +353,7 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
353
353
  },
354
354
  async readObservedThread(nativeId) {
355
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 };
356
+ return { thread: toThreadSummary(thread), isEphemeral: thread.ephemeral === true };
357
357
  },
358
358
  async listTurns(nativeId, limit, cursor) {
359
359
  const page = parseNative(NativeTurnPageSchema, await connection.request('thread/turns/list', {
@@ -372,13 +372,13 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
372
372
  });
373
373
  return { data: page.data.map(toTurnSummary), nextCursor: page.nextCursor };
374
374
  },
375
- async listItems(nativeId, limit, cursor, turnId, evidence = false) {
375
+ async listItems(nativeId, limit, cursor, turnId, fullBody = false) {
376
376
  const page = parseNative(NativeItemPageSchema, await connection.request('thread/items/list', {
377
377
  threadId: nativeId,
378
378
  turnId,
379
379
  limit,
380
380
  cursor,
381
- sortDirection: evidence ? 'desc' : 'asc',
381
+ sortDirection: 'desc',
382
382
  }));
383
383
  if (page.data.length > limit)
384
384
  throw new Exception('The Codex integration failed', {
@@ -388,7 +388,8 @@ export const createCodexProvider = async (extraSkillRoots = [], agentTools) => {
388
388
  },
389
389
  });
390
390
  return {
391
- data: page.data.map((item) => toHistoryItem(item, evidence)),
391
+ // reasoning is left out, so a page can hold fewer items than its limit
392
+ data: page.data.flatMap((item) => toHistoryItem(item, fullBody) ?? []),
392
393
  nextCursor: page.nextCursor,
393
394
  };
394
395
  },
@@ -101,7 +101,9 @@ export const createCodexEvents = (native, events, observeSession) => {
101
101
  captured.text = message.text;
102
102
  }
103
103
  }
104
- events.item(threadId, toHistoryItem({ turnId, item }), method === 'item/completed');
104
+ const presented = toHistoryItem({ turnId, item });
105
+ if (presented)
106
+ events.item(threadId, presented, method === 'item/completed');
105
107
  }
106
108
  else if (method === 'item/agentMessage/delta' ||
107
109
  method === 'item/commandExecution/outputDelta') {
@@ -17,11 +17,13 @@ export declare const toThreadSummary: (thread: INativeThread) => IThreadSummary;
17
17
  */
18
18
  export declare const toTurnSummary: (turn: INativeTurn) => ITurnSummary;
19
19
  /**
20
- * Produces explicit history presentation fields and marks truncated/unsupported content.
20
+ * Presents one native item as the CLI shows it, shared by history pages, live items and evidence.
21
+ * Outcome and files come from the full item, before the text is cut.
22
+ * @returns The item, or null for reasoning, which the CLI leaves out of history.
21
23
  * @throws
22
24
  * - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
23
25
  */
24
- export declare const toHistoryItem: ({ turnId, item }: INativeItem, fullBody?: boolean) => IHistoryItem;
26
+ export declare const toHistoryItem: ({ turnId, item }: INativeItem, fullBody?: boolean) => IHistoryItem | null;
25
27
  /**
26
28
  * Preserves actual bucket/window identities and reset boundaries without inventing missing data.
27
29
  * @throws
@@ -1,7 +1,8 @@
1
1
  import { z } from 'zod';
2
- import { UsageSnapshotSchema, UsageCreditsSchema, ThreadSummarySchema, TurnSummarySchema, HistoryItemSchema, } from '../../contracts/index.js';
3
- import { parseNative } from './validations.js';
2
+ import { UsageSnapshotSchema, UsageCreditsSchema, ThreadSummarySchema, TurnSummarySchema, HistoryItemSchema, MAX_ITEM_TEXT_LENGTH, } from '../../contracts/index.js';
3
+ import { countLines } from '../../sessions/index.js';
4
4
  import { nativeProvenance } from '../../sessions/evidence/index.js';
5
+ import { parseNative } from './validations.js';
5
6
  /** Preserves exact native tree identities independently of managed-agent relationships. */
6
7
  export const toNativeLineage = (thread) => ({
7
8
  sessionId: thread.sessionId ?? null,
@@ -57,22 +58,61 @@ const TextPartsSchema = z.object({
57
58
  .max(128),
58
59
  });
59
60
  const MessageSchema = z.object({ text: z.string() });
61
+ const StatusSchema = z.object({ status: z.string() });
60
62
  const CommandSchema = z.object({
61
63
  command: z.string(),
62
64
  aggregatedOutput: z.string().nullable().optional(),
63
65
  });
64
66
  const ChangesSchema = z.object({
65
- changes: z.array(z.object({ path: z.string(), diff: z.string() })).max(128),
67
+ changes: z
68
+ .array(z.object({
69
+ path: z.string().min(1).max(4096),
70
+ kind: z.object({ type: z.string() }),
71
+ diff: z.string(),
72
+ }))
73
+ .max(128),
74
+ });
75
+ const ToolSchema = z.object({
76
+ tool: z.string(),
77
+ server: z.string().optional(),
78
+ status: z.string(),
79
+ arguments: z.unknown(),
80
+ result: z.unknown().optional(),
81
+ error: z.unknown().optional(),
82
+ contentItems: z.unknown().optional(),
66
83
  });
84
+ /** Counts one change's lines; an added or deleted file without hunks is its whole content. */
85
+ const toHistoryFile = (change) => {
86
+ const lines = change.diff.split('\n');
87
+ const hunk = lines.findIndex((line) => line.startsWith('@@'));
88
+ if (hunk === -1)
89
+ return {
90
+ path: change.path,
91
+ added: change.kind.type === 'add' ? countLines(change.diff) : 0,
92
+ removed: change.kind.type === 'delete' ? countLines(change.diff) : 0,
93
+ };
94
+ const body = lines.slice(hunk);
95
+ return {
96
+ path: change.path,
97
+ added: body.filter((line) => line.startsWith('+') && !line.startsWith('+++')).length,
98
+ removed: body.filter((line) => line.startsWith('-') && !line.startsWith('---')).length,
99
+ };
100
+ };
67
101
  /**
68
- * Produces explicit history presentation fields and marks truncated/unsupported content.
102
+ * Presents one native item as the CLI shows it, shared by history pages, live items and evidence.
103
+ * Outcome and files come from the full item, before the text is cut.
104
+ * @returns The item, or null for reasoning, which the CLI leaves out of history.
69
105
  * @throws
70
106
  * - JG_AGENT_HQ_CODEX_FAILED: The Codex integration failed
71
107
  */
72
108
  export const toHistoryItem = ({ turnId, item }, fullBody = false) => {
73
109
  let kind = 'unsupported';
74
110
  let text = '';
111
+ let files = [];
112
+ let outcome = null;
75
113
  switch (item.type) {
114
+ case 'reasoning':
115
+ return null;
76
116
  case 'userMessage':
77
117
  kind = 'user-message';
78
118
  text = parseNative(TextPartsSchema, item)
@@ -83,6 +123,10 @@ export const toHistoryItem = ({ turnId, item }, fullBody = false) => {
83
123
  kind = 'agent-message';
84
124
  text = parseNative(MessageSchema, item).text;
85
125
  break;
126
+ case 'contextCompaction':
127
+ // Codex records no summary of what it compacted
128
+ kind = 'notice';
129
+ break;
86
130
  case 'commandExecution': {
87
131
  kind = 'command';
88
132
  const command = parseNative(CommandSchema, item);
@@ -92,26 +136,39 @@ export const toHistoryItem = ({ turnId, item }, fullBody = false) => {
92
136
  case 'mcpToolCall':
93
137
  case 'dynamicToolCall': {
94
138
  kind = 'tool';
95
- const tool = parseNative(z.object({
96
- tool: z.string(),
97
- server: z.string().optional(),
98
- status: z.string(),
99
- arguments: z.unknown(),
100
- result: z.unknown().optional(),
101
- error: z.unknown().optional(),
102
- contentItems: z.unknown().optional(),
103
- }), item);
139
+ const tool = parseNative(ToolSchema, item);
104
140
  text = `${tool.server ? tool.server + '/' : ''}${tool.tool} (${tool.status})\n${JSON.stringify(tool.arguments)}\n${JSON.stringify(tool.result ?? tool.contentItems ?? tool.error ?? null)}`;
105
141
  break;
106
142
  }
107
- case 'fileChange':
143
+ case 'webSearch':
144
+ kind = 'tool';
145
+ text = parseNative(z.object({ query: z.string() }), item).query;
146
+ break;
147
+ case 'imageView':
148
+ kind = 'tool';
149
+ text = parseNative(z.object({ path: z.string() }), item).path;
150
+ break;
151
+ case 'fileChange': {
108
152
  kind = 'file-change';
109
- text = parseNative(ChangesSchema, item)
110
- .changes.map((change) => `${change.path}\n${change.diff}`)
111
- .join('\n');
153
+ const { changes } = parseNative(ChangesSchema, item);
154
+ text = changes.map((change) => `${change.path}\n${change.diff}`).join('\n');
155
+ files = changes.map(toHistoryFile);
112
156
  break;
157
+ }
158
+ }
159
+ if (item.type === 'commandExecution' ||
160
+ item.type === 'fileChange' ||
161
+ item.type === 'mcpToolCall' ||
162
+ item.type === 'dynamicToolCall') {
163
+ const { status } = parseNative(StatusSchema, item);
164
+ outcome =
165
+ status === 'completed'
166
+ ? 'succeeded'
167
+ : status === 'failed' || status === 'declined'
168
+ ? 'failed'
169
+ : null;
113
170
  }
114
- let end = fullBody ? text.length : Math.min(text.length, 65_536);
171
+ let end = fullBody ? text.length : Math.min(text.length, MAX_ITEM_TEXT_LENGTH);
115
172
  const last = text.charCodeAt(end - 1);
116
173
  if (end < text.length && last >= 0xd800 && last <= 0xdbff)
117
174
  end -= 1;
@@ -120,11 +177,13 @@ export const toHistoryItem = ({ turnId, item }, fullBody = false) => {
120
177
  turnId,
121
178
  nativeType: item.type,
122
179
  kind,
123
- provenance: item.type === 'contextCompaction'
124
- ? { ...nativeProvenance(kind), origin: 'system', source: 'native-kind' }
125
- : nativeProvenance(kind, kind === 'user-message' && typeof item.clientId === 'string' ? item.clientId : null),
180
+ provenance: nativeProvenance(kind, kind === 'user-message' && typeof item.clientId === 'string' ? item.clientId : null),
126
181
  text: text.slice(0, end),
127
182
  isTruncated: end < text.length,
183
+ // a Codex item holds its call and its result together
184
+ callId: null,
185
+ outcome,
186
+ files,
128
187
  });
129
188
  };
130
189
  /**
@@ -193,13 +193,14 @@ export type ICodexProvider = {
193
193
  readonly isAvailable: boolean;
194
194
  listThreads(workspaceRoot: string, limit: number, cursor?: string, search?: string): Promise<INativePage<IThreadSummary>>;
195
195
  readThread(nativeId: string): Promise<IThreadSummary>;
196
- /** @returns A session's workspace and whether Codex doesn't save it, which decide observation. */
196
+ /** @returns A session's summary, with its workspace, and whether Codex doesn't save it. */
197
197
  readObservedThread(nativeId: string): Promise<{
198
- workspaceRoot: string;
198
+ thread: IThreadSummary;
199
199
  isEphemeral: boolean;
200
200
  }>;
201
201
  listTurns(nativeId: string, limit: number, cursor?: string): Promise<INativePage<ITurnSummary>>;
202
- listItems(nativeId: string, limit: number, cursor?: string, turnId?: string, evidence?: boolean): Promise<INativePage<IHistoryItem>>;
202
+ /** @returns One page of items newest first, with full text when `fullBody` is set. */
203
+ listItems(nativeId: string, limit: number, cursor?: string, turnId?: string, fullBody?: boolean): Promise<INativePage<IHistoryItem>>;
203
204
  readUsage(): Promise<IUsageSnapshot>;
204
205
  /**
205
206
  * Reads one native model page without starting inference.
@@ -1,7 +1,7 @@
1
1
  import { Exception, isException } from 'jg-exception';
2
2
  import { abortable, createDeadline } from 'jg-utilities';
3
3
  import { z } from 'zod';
4
- import { HistoryItemSchema, MAX_PROVIDERS, ApprovalPresentationSchema, AccountObservationSchema, LoginObservationSchema, NativeControlResultSchema, MAX_MCP_CATALOG_BYTES, ProviderCapabilitySetSchema, ProviderIdSchema, ProviderStatusSchema, ProviderModelPageSchema, SessionConfigurationSchema, SessionStateSchema, UsageSnapshotSchema, } from '../../contracts/index.js';
4
+ import { HistoryItemSchema, ThreadSummarySchema, MAX_PROVIDERS, ApprovalPresentationSchema, AccountObservationSchema, LoginObservationSchema, NativeControlResultSchema, MAX_MCP_CATALOG_BYTES, ProviderCapabilitySetSchema, ProviderIdSchema, ProviderStatusSchema, ProviderModelPageSchema, SessionConfigurationSchema, SessionStateSchema, UsageSnapshotSchema, } from '../../contracts/index.js';
5
5
  import { NativeIdSchema } from '../../contracts/identities/index.js';
6
6
  import { MAX_FRAME_BYTES } from '../../ipc/index.js';
7
7
  import { nativeProvenance } from '../../sessions/evidence/index.js';
@@ -145,14 +145,7 @@ export const createProviderRegistry = (registrations, allowedRoots, runtimeEpoch
145
145
  }),
146
146
  item: (nativeId, item, complete, replacedIds) => deliver(() => {
147
147
  const normalized = HistoryItemSchema.parse(item);
148
- const observed = normalized.provenance;
149
- normalized.provenance = nativeProvenance(normalized.kind, observed.nativeInputId);
150
- if (observed.origin === 'system' && observed.source === 'native-kind')
151
- normalized.provenance = {
152
- ...normalized.provenance,
153
- origin: 'system',
154
- source: 'native-kind',
155
- };
148
+ normalized.provenance = nativeProvenance(normalized.kind, normalized.provenance.nativeInputId);
156
149
  handlers?.item(provider, NativeIdSchema.parse(nativeId), normalized, z.boolean().parse(complete), replacedIds === undefined
157
150
  ? undefined
158
151
  : z.array(NativeIdSchema).max(128).parse(replacedIds));
@@ -338,6 +331,16 @@ export const createProviderRegistry = (registrations, allowedRoots, runtimeEpoch
338
331
  return ProviderMcpResourcesSchema.parse(raw);
339
332
  }),
340
333
  readHistory: (command) => invoke(async (call) => validateProviderHistory(await adapter.readHistory(command, call), command, provider)),
334
+ ...(adapter.readObservedThread
335
+ ? {
336
+ readObservedThread: (nativeId) => invoke(async (call) => {
337
+ const thread = ThreadSummarySchema.parse(await adapter.readObservedThread(nativeId, call));
338
+ if (thread.provider !== provider || thread.nativeId !== nativeId)
339
+ rejectProviderResponse();
340
+ return thread;
341
+ }),
342
+ }
343
+ : {}),
341
344
  readModels: (command) => invoke(async (call) => {
342
345
  const page = ProviderModelPageSchema.parse(await adapter.readModels(command, call));
343
346
  if (page.provider !== provider || page.data.length > command.limit)
@@ -6,7 +6,7 @@ export type IProviderRegistration = {
6
6
  isBuiltIn: boolean;
7
7
  };
8
8
  export type IBoundAgentProvider = {
9
- [K in keyof IAgentProvider]: IAgentProvider[K] extends (...inputs: infer TInputs) => infer TResult ? TInputs extends [...infer TOperationInputs, IProviderCall] ? (...inputs: TOperationInputs) => TResult : IAgentProvider[K] : IAgentProvider[K];
9
+ [K in keyof IAgentProvider]: NonNullable<IAgentProvider[K]> extends (...inputs: infer TInputs) => infer TResult ? TInputs extends [...infer TOperationInputs, IProviderCall] ? (...inputs: TOperationInputs) => TResult : IAgentProvider[K] : IAgentProvider[K];
10
10
  };
11
11
  export type IProviderRegistryEvents = {
12
12
  [K in keyof IAgentProviderEvents]: K extends 'outcome' ? (provider: IProviderId, outcome: INativeOutcome, thread?: IProviderThread) => void : (provider: IProviderId, ...inputs: Parameters<IAgentProviderEvents[K]>) => void;
@@ -124,6 +124,13 @@ export const validateProviderHistory = (input, command, provider) => {
124
124
  item.reference.itemId !== command.nativeItemId) ||
125
125
  (command.kinds !== undefined && !command.kinds.includes(item.kind)))))
126
126
  rejectProviderResponse();
127
+ // items stay within the requested turn, and one item read is that item alone
128
+ if (response.kind === 'items' &&
129
+ (command.kind !== 'items' ||
130
+ (command.nativeItemId !== undefined && response.result.data.length > 1) ||
131
+ response.result.data.some((item) => (command.turnId !== undefined && item.turnId !== command.turnId) ||
132
+ (command.nativeItemId !== undefined && item.nativeId !== command.nativeItemId))))
133
+ rejectProviderResponse();
127
134
  }
128
135
  else
129
136
  rejectProviderResponse();
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import type { IActionCommand, IManagedThread, IApprovalPresentation, ISkill, IHqResponse, IProviderId, IProviderCapabilitySet, IHistoryItem, IUsageSnapshot, INativeSkillInput, IProviderModelsRequest, IProviderModelPage, ISessionSettings, ITurnSettings, IConfigurationRequest, ISessionConfiguration, IPreparedInput, IAccountObservation, IAccountControlCommand, IExtensionControlCommand, ILoginObservation, INativeControlResult, ISessionState } from '../contracts/index.js';
2
+ import type { IActionCommand, IManagedThread, IApprovalPresentation, ISkill, IHqResponse, IProviderId, IProviderCapabilitySet, IHistoryItem, IUsageSnapshot, INativeSkillInput, IProviderModelsRequest, IProviderModelPage, ISessionSettings, ITurnSettings, IConfigurationRequest, ISessionConfiguration, IPreparedInput, IAccountObservation, IAccountControlCommand, IExtensionControlCommand, ILoginObservation, INativeControlResult, ISessionState, IThreadSummary } from '../contracts/index.js';
3
3
  import type { IProviderInputFile } from './inputs/index.js';
4
4
  import type { IProviderMcpServerPage, IProviderMcpTools, IProviderMcpResources } from './extensions/index.js';
5
5
  import type { IHistoryRequest } from '../sessions/index.js';
@@ -116,6 +116,12 @@ export type IAgentProvider = {
116
116
  revertThread(requestId: string, nativeId: string, beforeTurnId: string, call: IProviderCall): Promise<IProviderThread>;
117
117
  /** @returns One authorized, bounded native history response with query-bound continuation. */
118
118
  readHistory(command: IHistoryRequest, call: IProviderCall): Promise<IHqResponse>;
119
+ /**
120
+ * Reads a session another client drives by its identity alone, for active-session reads; a
121
+ * provider without it has its observed sessions left out of them.
122
+ * @returns The session's summary, whose workspace is where it runs.
123
+ */
124
+ readObservedThread?(nativeId: string, call: IProviderCall): Promise<IThreadSummary>;
119
125
  /** @returns Verified native metadata and explicit eligibility for adoption or reattachment. */
120
126
  inspectThread(nativeId: string, workspaceRoot: string, call: IProviderCall): Promise<IProviderInspection>;
121
127
  /** @returns Native quota observations without starting a model turn. */
@@ -12,7 +12,7 @@ import { createAgentTools } from '../agent-tools/index.js';
12
12
  import { CONTROL_SOCKET, createIpcServer } from '../ipc/index.js';
13
13
  import { createCodexProviderFactory, createClaudeProviderFactory, observeClaudeAgents, } from '../providers/index.js';
14
14
  import { createProviderRegistry } from '../providers/registry/index.js';
15
- import { readNativeHistory } from '../sessions/index.js';
15
+ import { limitItemText, readActiveSessions, readNativeHistory } from '../sessions/index.js';
16
16
  import { suggestThreadName } from '../sessions/names/index.js';
17
17
  import { createSkills } from '../skills/index.js';
18
18
  import { createStore } from '../store/index.js';
@@ -302,11 +302,27 @@ export const createAgentHq = async (options) => {
302
302
  kind: 'session-states',
303
303
  result: await projection.listSessionTransitions(command.afterSequence, command.limit),
304
304
  };
305
+ case 'active-sessions':
306
+ return {
307
+ kind: 'active-sessions',
308
+ result: await readActiveSessions(providers, projection, allowedRoots, (nativeId) => claudeAgents.workspaceOf(nativeId)),
309
+ };
310
+ case 'observation-pace':
311
+ claudeAgents.setPace(command.pace);
312
+ return { kind: 'observation-pace', result: { pace: command.pace } };
305
313
  default: {
306
314
  const response = await readNativeHistory(command, providers, projection, allowedRoots);
307
- if (command.kind === 'items' && response.kind === 'items')
308
- actions.live.reconcile(JSON.stringify([command.provider, command.nativeId]), response.result.data);
309
- return response;
315
+ if (command.kind !== 'items' || response.kind !== 'items')
316
+ return response;
317
+ // live items reconcile against the persisted text before it is cut
318
+ actions.live.reconcile(JSON.stringify([command.provider, command.nativeId]), response.result.data);
319
+ return {
320
+ ...response,
321
+ result: {
322
+ ...response.result,
323
+ data: limitItemText(response.result.data, command.textLimit),
324
+ },
325
+ };
310
326
  }
311
327
  }
312
328
  };
@@ -12,7 +12,9 @@ export const nativeProvenance = (kind, nativeInputId = null) => ({
12
12
  ? 'agent'
13
13
  : kind === 'tool' || kind === 'command' || kind === 'file-change'
14
14
  ? 'tool'
15
- : 'unknown',
15
+ : kind === 'notice'
16
+ ? 'system'
17
+ : 'unknown',
16
18
  source: kind === 'unsupported' || kind === 'user-message' ? 'unknown' : 'native-kind',
17
19
  nativeInputId,
18
20
  actionId: null,
@@ -1,3 +1,3 @@
1
- export { decodeHistoryCursor, encodeHistoryCursor } from './utilities.js';
2
- export { readNativeHistory } from './sessions.js';
1
+ export { decodeHistoryCursor, encodeHistoryCursor, limitItemText, countLines, } from './utilities.js';
2
+ export { readActiveSessions, readNativeHistory } from './sessions.js';
3
3
  export type { IHistoryRequest } from './types.js';
@@ -1,4 +1,4 @@
1
- // native history continuations
2
- export { decodeHistoryCursor, encodeHistoryCursor } from './utilities.js';
1
+ // native history continuations, item text limits and line counts
2
+ export { decodeHistoryCursor, encodeHistoryCursor, limitItemText, countLines, } from './utilities.js';
3
3
  // scoped read orchestration
4
- export { readNativeHistory } from './sessions.js';
4
+ export { readActiveSessions, readNativeHistory } from './sessions.js';
@@ -1,4 +1,4 @@
1
- import { type IHqResponse, type IHqRequest } from '../contracts/index.js';
1
+ import { type IActiveSessions, type IHqResponse, type IHqRequest } from '../contracts/index.js';
2
2
  import type { createProviderRegistry } from '../providers/registry/index.js';
3
3
  import type { IStore } from '../store/index.js';
4
4
  import type { IHistoryRequest } from './types.js';
@@ -19,3 +19,13 @@ import type { IHistoryRequest } from './types.js';
19
19
  export declare const readNativeHistory: (command: IHistoryRequest | Extract<IHqRequest, {
20
20
  kind: "sessions";
21
21
  }>, registry: ReturnType<typeof createProviderRegistry>, projection: IStore, allowedRoots: string[]) => Promise<IHqResponse>;
22
+ /**
23
+ * Reads every running and waiting session, managed and observed, newest state change first, each
24
+ * as the summary `threads` returns. An observed Claude session's workspace is the `cwd` the
25
+ * latest `claude agents --json` run reported, and other observed sessions' come from their
26
+ * provider's `readObservedThread`.
27
+ * @returns At most 128 summaries and whether more sessions are active.
28
+ * @throws
29
+ * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
30
+ */
31
+ export declare const readActiveSessions: (registry: ReturnType<typeof createProviderRegistry>, projection: IStore, allowedRoots: string[], claudeWorkspaceOf: (nativeId: string) => string | undefined) => Promise<IActiveSessions>;
@@ -1,5 +1,5 @@
1
1
  import { Exception } from 'jg-exception';
2
- import { HqResponseSchema } from '../contracts/index.js';
2
+ import { HqResponseSchema, MAX_PAGE_SIZE, } from '../contracts/index.js';
3
3
  import { retainNativeLineage } from '../providers/index.js';
4
4
  import { resolveWorkspaceTarget } from '../runtime/state/index.js';
5
5
  import { evidencePosition, verifyEvidencePage, evidenceCursor, evidenceHash, utf8Chunk, nativeProvenance, EVIDENCE_SOURCE_PAGE_SIZE, } from './evidence/index.js';
@@ -106,12 +106,8 @@ export const readNativeHistory = async (command, registry, projection, allowedRo
106
106
  const items = response.kind === 'session-evidence' || response.kind === 'items' ? response.result.data : [];
107
107
  if (items.length && 'nativeId' in command) {
108
108
  // provider assertions alone never establish an operator or an HQ action link
109
- for (const item of items) {
110
- const observed = item.provenance;
111
- item.provenance = nativeProvenance(item.kind, observed.nativeInputId);
112
- if (observed.origin === 'system' && observed.source === 'native-kind')
113
- item.provenance = { ...item.provenance, origin: 'system', source: 'native-kind' };
114
- }
109
+ for (const item of items)
110
+ item.provenance = nativeProvenance(item.kind, item.provenance.nativeInputId);
115
111
  const origins = await projection.getEvidenceOrigins({
116
112
  provider: command.provider,
117
113
  nativeId: command.nativeId,
@@ -134,3 +130,89 @@ export const readNativeHistory = async (command, registry, projection, allowedRo
134
130
  });
135
131
  return HqResponseSchema.parse(response);
136
132
  };
133
+ /**
134
+ * Summarizes one active session, or returns null for one left out: outside the allowed workspaces,
135
+ * an observed Claude session the latest `claude agents --json` run didn't list, and an observed
136
+ * session its provider can't read, as observation itself leaves such a session out.
137
+ */
138
+ const toActiveSummary = async (record, registry, resolveRoot, claudeWorkspaceOf) => {
139
+ const base = { provider: record.provider, nativeId: record.nativeId, state: record.state };
140
+ if (record.thread) {
141
+ const workspaceRoot = await resolveRoot(record.thread.workspaceRoot);
142
+ if (workspaceRoot === null)
143
+ return null;
144
+ return {
145
+ ...base,
146
+ nativeLineage: record.thread.nativeLineage,
147
+ workspaceRoot,
148
+ name: record.thread.name,
149
+ createdAt: record.thread.createdAt,
150
+ updatedAt: record.thread.updatedAt,
151
+ nativeState: 'unknown',
152
+ ownership: record.thread.ownership,
153
+ managedId: record.thread.id,
154
+ historyState: 'available',
155
+ };
156
+ }
157
+ if (record.provider === 'claude') {
158
+ const cwd = claudeWorkspaceOf(record.nativeId);
159
+ const workspaceRoot = cwd === undefined ? null : await resolveRoot(cwd);
160
+ if (workspaceRoot === null)
161
+ return null;
162
+ return {
163
+ ...base,
164
+ nativeLineage: { sessionId: record.nativeId, parentThreadId: null, forkedFromId: null },
165
+ workspaceRoot,
166
+ name: record.history?.name ?? null,
167
+ createdAt: record.history?.createdAt ?? record.changedAt,
168
+ updatedAt: record.history?.updatedAt ?? record.changedAt,
169
+ nativeState: 'unknown',
170
+ ownership: 'external',
171
+ managedId: null,
172
+ historyState: record.history?.isSupported === false ? 'unavailable' : 'available',
173
+ };
174
+ }
175
+ let thread;
176
+ try {
177
+ const adapter = await registry.get(record.provider);
178
+ if (!adapter.readObservedThread)
179
+ return null;
180
+ thread = await adapter.readObservedThread(record.nativeId);
181
+ }
182
+ catch {
183
+ return null;
184
+ }
185
+ const workspaceRoot = await resolveRoot(thread.workspaceRoot);
186
+ if (workspaceRoot === null)
187
+ return null;
188
+ return { ...thread, ...base, workspaceRoot, ownership: 'external', managedId: null };
189
+ };
190
+ /**
191
+ * Reads every running and waiting session, managed and observed, newest state change first, each
192
+ * as the summary `threads` returns. An observed Claude session's workspace is the `cwd` the
193
+ * latest `claude agents --json` run reported, and other observed sessions' come from their
194
+ * provider's `readObservedThread`.
195
+ * @returns At most 128 summaries and whether more sessions are active.
196
+ * @throws
197
+ * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
198
+ */
199
+ export const readActiveSessions = async (registry, projection, allowedRoots, claudeWorkspaceOf) => {
200
+ const records = await projection.listActiveSessions(MAX_PAGE_SIZE);
201
+ // each directory is authorized once per read
202
+ const roots = new Map();
203
+ const resolveRoot = (directory) => {
204
+ let root = roots.get(directory);
205
+ if (!root) {
206
+ root = resolveWorkspaceTarget(directory, allowedRoots).catch(() => null);
207
+ roots.set(directory, root);
208
+ }
209
+ return root;
210
+ };
211
+ const data = [];
212
+ for (const record of records.data) {
213
+ const summary = await toActiveSummary(record, registry, resolveRoot, claudeWorkspaceOf);
214
+ if (summary)
215
+ data.push(summary);
216
+ }
217
+ return { data, isTruncated: records.isTruncated };
218
+ };
@@ -1,3 +1,4 @@
1
+ import type { IHistoryItem } from '../contracts/index.js';
1
2
  /**
2
3
  * Checks query binding before a native continuation is used. Authorization is checked separately.
3
4
  * @returns The provider-owned cursor, without interpreting its format.
@@ -7,3 +8,17 @@
7
8
  export declare const decodeHistoryCursor: (cursor: string | undefined, filters: object) => string | undefined;
8
9
  /** Encodes a validated native continuation with the exact request filters. */
9
10
  export declare const encodeHistoryCursor: (nativeCursor: string | null, filters: object) => string | null;
11
+ /**
12
+ * Cuts each item's text to a limit on a code-point boundary, marking the items it cut, after
13
+ * everything that compares the persisted text, such as live-item reconciliation, has read it.
14
+ * @param items The items as their provider presents them.
15
+ * @param textLimit The most UTF-16 code units of text an item keeps.
16
+ * @returns The items with their text cut.
17
+ */
18
+ export declare const limitItemText: (items: IHistoryItem[], textLimit: number) => IHistoryItem[];
19
+ /**
20
+ * Counts a text's lines, as a file holding it has them.
21
+ * @param text The text, whose final newline ends its last line.
22
+ * @returns The number of lines, zero for an empty text.
23
+ */
24
+ export declare const countLines: (text: string) => number;
@@ -46,3 +46,22 @@ export const decodeHistoryCursor = (cursor, filters) => {
46
46
  export const encodeHistoryCursor = (nativeCursor, filters) => nativeCursor === null
47
47
  ? null
48
48
  : Buffer.from(JSON.stringify(ContinuationSchema.parse({ version: 1, filterHash: hashFilters(filters), nativeCursor }))).toString('base64url');
49
+ /**
50
+ * Cuts each item's text to a limit on a code-point boundary, marking the items it cut, after
51
+ * everything that compares the persisted text, such as live-item reconciliation, has read it.
52
+ * @param items The items as their provider presents them.
53
+ * @param textLimit The most UTF-16 code units of text an item keeps.
54
+ * @returns The items with their text cut.
55
+ */
56
+ export const limitItemText = (items, textLimit) => items.map((item) => {
57
+ if (item.text.length <= textLimit)
58
+ return item;
59
+ const end = /[\uD800-\uDBFF]/.test(item.text.charAt(textLimit - 1)) ? textLimit - 1 : textLimit;
60
+ return { ...item, text: item.text.slice(0, end), isTruncated: true };
61
+ });
62
+ /**
63
+ * Counts a text's lines, as a file holding it has them.
64
+ * @param text The text, whose final newline ends its last line.
65
+ * @returns The number of lines, zero for an empty text.
66
+ */
67
+ export const countLines = (text) => text === '' ? 0 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
@@ -205,7 +205,7 @@ CREATE TABLE hq_claude_entry (
205
205
  workspace_root TEXT NOT NULL, native_id TEXT NOT NULL, uuid TEXT NOT NULL,
206
206
  parent_uuid TEXT, turn_id TEXT NOT NULL, byte_offset INTEGER NOT NULL, byte_length INTEGER NOT NULL,
207
207
  created_at INTEGER NOT NULL, is_visible INTEGER NOT NULL,
208
- item_kind TEXT NOT NULL CHECK (item_kind IN ('user-message','agent-message','command','tool','file-change','unsupported')),
208
+ item_kind TEXT NOT NULL CHECK (item_kind IN ('user-message','agent-message','command','tool','file-change','notice','unsupported')),
209
209
  is_current INTEGER NOT NULL, turn_start_offset INTEGER, anchor_id TEXT,
210
210
  CONSTRAINT hq_pk_ce__workspace_root_native_id_uuid PRIMARY KEY (workspace_root, native_id, uuid),
211
211
  CONSTRAINT hq_fk_ce__workspace_root_native_id FOREIGN KEY (workspace_root, native_id)
@@ -1 +1,3 @@
1
1
  export { SessionsModel } from './sessions.model.js';
2
+ export { ActiveSessionRecordSchema, ActiveSessionRecordsSchema } from './types.js';
3
+ export type { IActiveSessionRecord } from './types.js';
@@ -1,2 +1,4 @@
1
1
  // worker-owned observed sessions and transitions
2
2
  export { SessionsModel } from './sessions.model.js';
3
+ // active session records
4
+ export { ActiveSessionRecordSchema, ActiveSessionRecordsSchema } from './types.js';
@@ -1,5 +1,6 @@
1
1
  import type { DatabaseSync } from 'node:sqlite';
2
2
  import { type ISessionState, type ISessionTransition } from '../../contracts/index.js';
3
+ import { type IActiveSessionRecord } from './types.js';
3
4
  /** Owns observed session states and the session transition log on the SQLite worker. */
4
5
  export declare class SessionsModel {
5
6
  private readonly __database;
@@ -20,6 +21,14 @@ export declare class SessionsModel {
20
21
  nativeId: string;
21
22
  state: ISessionState;
22
23
  }[];
24
+ /**
25
+ * Reads running and waiting sessions, managed and observed, newest state change first.
26
+ * @returns At most `limit` records and whether more sessions are active.
27
+ */
28
+ active(limit: number): {
29
+ data: IActiveSessionRecord[];
30
+ isTruncated: boolean;
31
+ };
23
32
  /** Reads transitions after a sequence, in order, with one row of lookahead for continuation. */
24
33
  transitions(afterSequence: number, limit: number): {
25
34
  data: ISessionTransition[];