jg-agent-hq 4.0.2 → 5.0.1

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 +13 -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 +44 -27
  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 +4 -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
@@ -9,6 +9,7 @@ const FrameSchema = z.object({ type: z.string(), session_id: z.string().optional
9
9
  const MessageSchema = z.object({
10
10
  uuid: z.string().min(1).max(4096),
11
11
  message: z.object({ role: z.string(), content: z.unknown() }),
12
+ tool_use_result: z.unknown().optional(),
12
13
  });
13
14
  const ResultSchema = z.object({
14
15
  subtype: z.string(),
@@ -38,7 +39,12 @@ const MessageStartSchema = z.object({
38
39
  const BlockStartSchema = z.object({
39
40
  event: z.object({
40
41
  index: z.number().int().min(0).max(127),
41
- content_block: z.object({ type: z.string(), text: z.string().optional() }),
42
+ content_block: z.object({
43
+ type: z.string(),
44
+ id: z.string().optional(),
45
+ name: z.string().optional(),
46
+ text: z.string().optional(),
47
+ }),
42
48
  }),
43
49
  });
44
50
  const BlockDeltaSchema = z.object({
@@ -98,7 +104,12 @@ export const receiveClaudeMessage = (session, raw, events) => {
98
104
  input.interruptRequested &&
99
105
  isClaudeInterruptionMarker(message.message.content))
100
106
  return;
101
- const item = toClaudeItem(RecordSchema.parse({ ...message, type: frame.type }), input.id);
107
+ const item = toClaudeItem(RecordSchema.parse({
108
+ type: frame.type,
109
+ uuid: message.uuid,
110
+ message: message.message,
111
+ toolUseResult: message.tool_use_result,
112
+ }), input.id);
102
113
  // final wrappers may share an API message ID while containing different content blocks
103
114
  const content = z
104
115
  .object({ message: z.object({ id: z.string().optional(), content: z.unknown() }) })
@@ -129,7 +140,8 @@ export const receiveClaudeMessage = (session, raw, events) => {
129
140
  replacedIds.push(preview[1].id);
130
141
  }
131
142
  }
132
- events?.item(session.id, item, true, replacedIds);
143
+ if (item)
144
+ events?.item(session.id, item, true, replacedIds);
133
145
  if (frame.type === 'user') {
134
146
  const results = ToolResultsSchema.safeParse(message.message.content);
135
147
  if (results.success)
@@ -164,12 +176,16 @@ export const receiveClaudeMessage = (session, raw, events) => {
164
176
  if (!session.apiMessageId)
165
177
  unavailable();
166
178
  const id = `live:${input.id}:${session.apiMessageId}:${block.index}`;
167
- session.previews.set(block.index, { id, type: block.content_block.type });
168
- events?.item(session.id, toClaudeItem({
179
+ const preview = toClaudeItem({
169
180
  type: 'assistant',
170
181
  uuid: id,
171
182
  message: { role: 'assistant', content: [block.content_block] },
172
- }, input.id), false);
183
+ }, input.id);
184
+ // a block the CLI leaves out, such as thinking, has no preview to show or replace
185
+ if (preview) {
186
+ session.previews.set(block.index, { id, type: block.content_block.type });
187
+ events?.item(session.id, preview, false);
188
+ }
173
189
  }
174
190
  else if (event.type === 'content_block_delta') {
175
191
  const block = BlockDeltaSchema.parse(raw).event;
@@ -43,6 +43,13 @@ export type IClaudeSession = {
43
43
  id: string;
44
44
  type: string;
45
45
  }>;
46
+ parked?: {
47
+ configuration: unknown;
48
+ agents: unknown;
49
+ permissionMode: unknown;
50
+ };
51
+ idleStop?: AbortController;
52
+ transition?: Promise<void>;
46
53
  requests: Map<string, {
47
54
  toolId: string | null;
48
55
  scopedId: string;
@@ -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 { isClaudeWorkspaceCwd, openTranscript, projectDirectory, toClaudeItem, } from './utilities.js';
10
10
  // identifies the path and record interpretation used by persisted projection entries
11
- const HISTORY_PROJECTION_VERSION = 4;
11
+ const HISTORY_PROJECTION_VERSION = 5;
12
12
  // one record, such as a tool result holding images, and an indexing read, which fits the largest
13
13
  const MAX_RECORD_BYTES = 8_388_608;
14
14
  const MAX_REFRESH_BYTES = 16_777_216;
@@ -162,13 +162,20 @@ export class ClaudeHistoryModel {
162
162
  },
163
163
  });
164
164
  }
165
- const entries = this.__database
166
- .prepare(`SELECT uuid, parent_uuid, turn_id, byte_offset, byte_length, created_at, is_visible FROM hq_claude_entry
167
- WHERE workspace_root = ? AND native_id = ? AND is_current = 1 AND is_visible = 1 AND byte_offset > ?
165
+ // items read newest first, the cursor holding the oldest offset read; one item is read by its UUID
166
+ const before = seek?.offset ?? Number.MAX_SAFE_INTEGER;
167
+ const entries = (command.nativeItemId === undefined
168
+ ? this.__database
169
+ .prepare(`SELECT uuid, parent_uuid, turn_id, byte_offset, byte_length, created_at, is_visible FROM hq_claude_entry
170
+ WHERE workspace_root = ? AND native_id = ? AND is_current = 1 AND is_visible = 1 AND byte_offset < ?
168
171
  ${command.turnId === undefined ? '' : 'AND turn_id = ?'}
169
- ORDER BY byte_offset LIMIT ?`)
170
- .all(root, command.nativeId, offset, ...(command.turnId === undefined ? [] : [command.turnId]), command.limit + 1)
171
- .map((entry) => EntryRowSchema.parse(entry));
172
+ ORDER BY byte_offset DESC LIMIT ?`)
173
+ .all(root, command.nativeId, before, ...(command.turnId === undefined ? [] : [command.turnId]), command.limit + 1)
174
+ : this.__database
175
+ .prepare(`SELECT uuid, parent_uuid, turn_id, byte_offset, byte_length, created_at, is_visible FROM hq_claude_entry
176
+ WHERE workspace_root = ? AND native_id = ? AND is_current = 1 AND is_visible = 1 AND uuid = ? AND turn_id = ?
177
+ LIMIT 1`)
178
+ .all(root, command.nativeId, command.nativeItemId, command.turnId ?? null)).map((entry) => EntryRowSchema.parse(entry));
172
179
  const page = entries.slice(0, command.limit);
173
180
  const fd = openTranscript(directory, command.nativeId);
174
181
  try {
@@ -177,7 +184,7 @@ export class ClaudeHistoryModel {
177
184
  const items = [];
178
185
  let size = 0;
179
186
  let readBytes = 0;
180
- let lastOffset = offset;
187
+ let lastOffset = before;
181
188
  for (const entry of page) {
182
189
  // a page always reads its first record, which can be larger than the page budget
183
190
  if (readBytes > 0 && readBytes + entry.byte_length > MAX_PAGE_BYTES)
@@ -189,7 +196,8 @@ export class ClaudeHistoryModel {
189
196
  const record = RecordSchema.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
190
197
  if (record.uuid !== entry.uuid || !isClaudeWorkspaceCwd(record.cwd, root))
191
198
  this.__unavailable();
192
- const item = toClaudeItem(record, entry.turn_id);
199
+ // the index stores only records the CLI shows, so a dropped one means it no longer matches
200
+ const item = toClaudeItem(record, entry.turn_id) ?? this.__unavailable();
193
201
  const itemSize = Buffer.byteLength(JSON.stringify(item));
194
202
  if (size + itemSize > MAX_PAGE_BYTES)
195
203
  break;
@@ -272,7 +280,7 @@ export class ClaudeHistoryModel {
272
280
  record.sessionId !== command.nativeId ||
273
281
  !isClaudeWorkspaceCwd(record.cwd, command.workspaceRoot))
274
282
  this.__unavailable();
275
- items.push(toClaudeItem(record, entry.turn_id, true));
283
+ items.push(toClaudeItem(record, entry.turn_id, true) ?? this.__unavailable());
276
284
  lastOffset = entry.byte_offset;
277
285
  readBytes += entry.byte_length;
278
286
  }
@@ -400,12 +408,19 @@ export class ClaudeHistoryModel {
400
408
  row.updated_at = Math.max(row.updated_at, Math.trunc(stat.mtimeMs));
401
409
  let position = row.byte_offset;
402
410
  let lineStart = position;
403
- let tail = Buffer.alloc(0);
404
411
  const chunk = Buffer.alloc(65_536);
405
412
  // hidden records whose parent comes later in the file, by location and awaited parent
406
413
  const heldBack = [];
414
+ /*
415
+ * A record read again, because it spans chunks or was held back, lands in one buffer that
416
+ * grows to the longest such record. Each read replaces the last one's bytes, which
417
+ * `__record` has decoded by then.
418
+ */
419
+ let spill = Buffer.alloc(0);
407
420
  const reread = (offset, length) => {
408
- const bytes = Buffer.alloc(length);
421
+ if (spill.length < length)
422
+ spill = Buffer.allocUnsafe(length);
423
+ const bytes = spill.subarray(0, length);
409
424
  if (readSync(fd, bytes, 0, length, offset) !== length)
410
425
  this.__unavailable();
411
426
  return bytes;
@@ -433,18 +448,22 @@ export class ClaudeHistoryModel {
433
448
  const count = readSync(fd, chunk, 0, Math.min(chunk.length, stat.size - position, remaining()), position);
434
449
  if (count === 0)
435
450
  break;
451
+ const chunkStart = position;
436
452
  position += count;
437
453
  consume(count);
438
- tail = Buffer.concat([tail, chunk.subarray(0, count)]);
439
- for (let end = tail.indexOf(10); end !== -1; end = tail.indexOf(10)) {
440
- if (end > MAX_RECORD_BYTES)
454
+ // a record that started in an earlier chunk is read again whole, not joined from chunks
455
+ const read = chunk.subarray(0, count);
456
+ for (let end = read.indexOf(10); end !== -1; end = read.indexOf(10, end + 1)) {
457
+ const length = chunkStart + end - lineStart;
458
+ if (length > MAX_RECORD_BYTES)
441
459
  this.__unavailable();
442
- if (end > 0)
443
- indexRecord(tail.subarray(0, end), lineStart);
444
- lineStart += end + 1;
445
- tail = tail.subarray(end + 1);
460
+ if (length > 0)
461
+ indexRecord(lineStart >= chunkStart
462
+ ? read.subarray(lineStart - chunkStart, end)
463
+ : reread(lineStart, length), lineStart);
464
+ lineStart = chunkStart + end + 1;
446
465
  }
447
- if (tail.length > MAX_RECORD_BYTES)
466
+ if (position - lineStart > MAX_RECORD_BYTES)
448
467
  this.__unavailable();
449
468
  }
450
469
  /*
@@ -531,7 +550,9 @@ export class ClaudeHistoryModel {
531
550
  WHERE workspace_root = ? AND native_id = ? AND uuid = ?`)
532
551
  .get(root, nativeId, record.parentUuid)
533
552
  : undefined;
534
- const visible = record.message !== undefined && !record.isMeta;
553
+ // the CLI's presentation decides what is shown, the kind evidence filters on and where turns start
554
+ const item = record.message !== undefined && !record.isMeta ? toClaudeItem(record, record.uuid) : null;
555
+ const visible = item !== null;
535
556
  if (record.parentUuid === record.uuid)
536
557
  this.__unavailable();
537
558
  if (record.parentUuid && !parent) {
@@ -540,11 +561,7 @@ export class ClaudeHistoryModel {
540
561
  if (!isOrphanAllowed)
541
562
  return record.parentUuid;
542
563
  }
543
- const textPrompt = record.type === 'user' &&
544
- !record.isMeta &&
545
- (typeof record.message?.content === 'string' ||
546
- (Array.isArray(record.message?.content) &&
547
- record.message.content.some((block) => z.object({ type: z.literal('text') }).safeParse(block).success)));
564
+ const textPrompt = item?.kind === 'user-message';
548
565
  const turnId = textPrompt
549
566
  ? record.uuid
550
567
  : typeof parent?.turn_id === 'string'
@@ -579,7 +596,7 @@ export class ClaudeHistoryModel {
579
596
  turn_id = excluded.turn_id, byte_offset = excluded.byte_offset, byte_length = excluded.byte_length,
580
597
  created_at = excluded.created_at, is_visible = excluded.is_visible, is_current = excluded.is_current,
581
598
  turn_start_offset = excluded.turn_start_offset, anchor_id = excluded.anchor_id, item_kind = excluded.item_kind`)
582
- .run(root, nativeId, record.uuid, record.parentUuid ?? null, turnId, offset, bytes.length, createdAt, visible ? 1 : 0, visible ? 1 : 0, turnStart, anchorId, visible ? toClaudeItem(record, turnId).kind : 'unsupported');
599
+ .run(root, nativeId, record.uuid, record.parentUuid ?? null, turnId, offset, bytes.length, createdAt, visible ? 1 : 0, visible ? 1 : 0, turnStart, anchorId, item?.kind ?? 'unsupported');
583
600
  if (visible) {
584
601
  if (!isAppend && !isSameLeaf)
585
602
  this.__database
@@ -26,6 +26,7 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
26
26
  tool: "tool";
27
27
  "agent-message": "agent-message";
28
28
  "file-change": "file-change";
29
+ notice: "notice";
29
30
  }>;
30
31
  nativeType: z.ZodString;
31
32
  provenance: z.ZodObject<{
@@ -3916,6 +3917,7 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
3916
3917
  tool: "tool";
3917
3918
  "agent-message": "agent-message";
3918
3919
  "file-change": "file-change";
3920
+ notice: "notice";
3919
3921
  }>;
3920
3922
  provenance: z.ZodObject<{
3921
3923
  origin: z.ZodEnum<{
@@ -3939,6 +3941,16 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
3939
3941
  }, z.core.$strip>;
3940
3942
  text: z.ZodString;
3941
3943
  isTruncated: z.ZodBoolean;
3944
+ callId: z.ZodNullable<z.ZodString>;
3945
+ outcome: z.ZodNullable<z.ZodEnum<{
3946
+ failed: "failed";
3947
+ succeeded: "succeeded";
3948
+ }>>;
3949
+ files: z.ZodArray<z.ZodObject<{
3950
+ path: z.ZodString;
3951
+ added: z.ZodNumber;
3952
+ removed: z.ZodNumber;
3953
+ }, z.core.$strip>>;
3942
3954
  }, z.core.$strip>>;
3943
3955
  }, z.core.$strip>;
3944
3956
  }, z.core.$strip>, z.ZodObject<{
@@ -4668,6 +4680,7 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
4668
4680
  tool: "tool";
4669
4681
  "agent-message": "agent-message";
4670
4682
  "file-change": "file-change";
4683
+ notice: "notice";
4671
4684
  }>;
4672
4685
  provenance: z.ZodObject<{
4673
4686
  origin: z.ZodEnum<{
@@ -4691,6 +4704,16 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
4691
4704
  }, z.core.$strip>;
4692
4705
  text: z.ZodString;
4693
4706
  isTruncated: z.ZodBoolean;
4707
+ callId: z.ZodNullable<z.ZodString>;
4708
+ outcome: z.ZodNullable<z.ZodEnum<{
4709
+ failed: "failed";
4710
+ succeeded: "succeeded";
4711
+ }>>;
4712
+ files: z.ZodArray<z.ZodObject<{
4713
+ path: z.ZodString;
4714
+ added: z.ZodNumber;
4715
+ removed: z.ZodNumber;
4716
+ }, z.core.$strip>>;
4694
4717
  state: z.ZodEnum<{
4695
4718
  active: "active";
4696
4719
  "awaiting-flush": "awaiting-flush";
@@ -4741,6 +4764,57 @@ export declare const ClaudeHistoryReadSchema: z.ZodUnion<readonly [z.ZodDiscrimi
4741
4764
  }, z.core.$strip>>;
4742
4765
  hasMore: z.ZodBoolean;
4743
4766
  }, z.core.$strip>;
4767
+ }, z.core.$strip>, z.ZodObject<{
4768
+ kind: z.ZodLiteral<"active-sessions">;
4769
+ result: z.ZodObject<{
4770
+ data: z.ZodArray<z.ZodObject<{
4771
+ provider: z.ZodString;
4772
+ nativeId: z.ZodString;
4773
+ nativeLineage: z.ZodNullable<z.ZodObject<{
4774
+ sessionId: z.ZodNullable<z.ZodString>;
4775
+ parentThreadId: z.ZodNullable<z.ZodString>;
4776
+ forkedFromId: z.ZodNullable<z.ZodString>;
4777
+ }, z.core.$strip>>;
4778
+ workspaceRoot: z.ZodString;
4779
+ name: z.ZodNullable<z.ZodString>;
4780
+ createdAt: z.ZodNumber;
4781
+ updatedAt: z.ZodNumber;
4782
+ nativeState: z.ZodEnum<{
4783
+ unknown: "unknown";
4784
+ idle: "idle";
4785
+ active: "active";
4786
+ notLoaded: "notLoaded";
4787
+ systemError: "systemError";
4788
+ }>;
4789
+ state: z.ZodEnum<{
4790
+ unknown: "unknown";
4791
+ idle: "idle";
4792
+ failed: "failed";
4793
+ running: "running";
4794
+ waiting: "waiting";
4795
+ closed: "closed";
4796
+ }>;
4797
+ ownership: z.ZodEnum<{
4798
+ external: "external";
4799
+ managed: "managed";
4800
+ uncertain: "uncertain";
4801
+ }>;
4802
+ managedId: z.ZodNullable<z.ZodUUID>;
4803
+ historyState: z.ZodEnum<{
4804
+ unavailable: "unavailable";
4805
+ available: "available";
4806
+ }>;
4807
+ }, z.core.$strip>>;
4808
+ isTruncated: z.ZodBoolean;
4809
+ }, z.core.$strip>;
4810
+ }, z.core.$strip>, z.ZodObject<{
4811
+ kind: z.ZodLiteral<"observation-pace">;
4812
+ result: z.ZodObject<{
4813
+ pace: z.ZodEnum<{
4814
+ live: "live";
4815
+ background: "background";
4816
+ }>;
4817
+ }, z.core.$strip>;
4744
4818
  }, z.core.$strip>], "kind">, z.ZodObject<{
4745
4819
  kind: z.ZodLiteral<"indexing">;
4746
4820
  }, z.core.$strict>]>;
@@ -4795,8 +4869,22 @@ export declare const RecordSchema: z.ZodObject<{
4795
4869
  role: z.ZodString;
4796
4870
  content: z.ZodUnknown;
4797
4871
  }, z.core.$strip>>;
4872
+ toolUseResult: z.ZodOptional<z.ZodUnknown>;
4798
4873
  }, z.core.$strip>;
4799
4874
  export type IRecord = z.infer<typeof RecordSchema>;
4875
+ export declare const FilePatchSchema: z.ZodObject<{
4876
+ filePath: z.ZodString;
4877
+ type: z.ZodOptional<z.ZodString>;
4878
+ content: z.ZodOptional<z.ZodString>;
4879
+ structuredPatch: z.ZodArray<z.ZodObject<{
4880
+ oldStart: z.ZodNumber;
4881
+ oldLines: z.ZodNumber;
4882
+ newStart: z.ZodNumber;
4883
+ newLines: z.ZodNumber;
4884
+ lines: z.ZodArray<z.ZodString>;
4885
+ }, z.core.$strip>>;
4886
+ }, z.core.$strip>;
4887
+ export type IFilePatch = z.infer<typeof FilePatchSchema>;
4800
4888
  export declare const SeekSchema: z.ZodObject<{
4801
4889
  createdAt: z.ZodNumber;
4802
4890
  nativeId: z.ZodUUID;
@@ -49,6 +49,21 @@ export const RecordSchema = z.object({
49
49
  isCompactSummary: z.boolean().optional(),
50
50
  customTitle: z.string().max(4096).optional(),
51
51
  message: z.object({ role: z.string(), content: z.unknown() }).optional(),
52
+ // the CLI's own result metadata, such as an edit's patch, which live frames call tool_use_result
53
+ toolUseResult: z.unknown().optional(),
54
+ });
55
+ // the file Claude Code records on an Edit or Write result; a created file's patch is empty
56
+ export const FilePatchSchema = z.object({
57
+ filePath: z.string().min(1).max(4096),
58
+ type: z.string().optional(),
59
+ content: z.string().optional(),
60
+ structuredPatch: z.array(z.object({
61
+ oldStart: z.number().int().nonnegative(),
62
+ oldLines: z.number().int().nonnegative(),
63
+ newStart: z.number().int().nonnegative(),
64
+ newLines: z.number().int().nonnegative(),
65
+ lines: z.array(z.string()),
66
+ })),
52
67
  });
53
68
  export const SeekSchema = z.strictObject({
54
69
  createdAt: z.number().int(),
@@ -1,5 +1,5 @@
1
- import type { IHistoryItem } from '../../../contracts/index.js';
2
- import type { IRecord } from './types.js';
1
+ import { type IHistoryItem } from '../../../contracts/index.js';
2
+ import { type IRecord } from './types.js';
3
3
  /**
4
4
  * Resolves only the verified native project layout, without following directory links.
5
5
  * @returns The exact native project directory; no recursive discovery is used.
@@ -20,8 +20,10 @@ export declare const isClaudeWorkspaceCwd: (cwd: string | undefined, workspaceRo
20
20
  */
21
21
  export declare const openTranscript: (directory: string, nativeId: string) => number;
22
22
  /**
23
- * Renders selected native content as bounded plain text, never as HTML.
23
+ * Presents one native record as the CLI shows it, shared by history pages, live items and
24
+ * evidence. Outcome and files come from the full record, before the text is cut.
25
+ * @returns The item, or null for a record the CLI leaves out, such as thinking or a task notification.
24
26
  * @throws
25
27
  * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
26
28
  */
27
- export declare const toClaudeItem: (record: IRecord, turnId: string, fullBody?: boolean) => IHistoryItem;
29
+ export declare const toClaudeItem: (record: IRecord, turnId: string, fullBody?: boolean) => IHistoryItem | null;
@@ -3,7 +3,10 @@ import { homedir } from 'node:os';
3
3
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
4
  import { Exception, hasErrorCode } from 'jg-exception';
5
5
  import { z } from 'zod';
6
+ import { MAX_ITEM_TEXT_LENGTH } from '../../../contracts/index.js';
7
+ import { countLines } from '../../../sessions/index.js';
6
8
  import { nativeProvenance } from '../../../sessions/evidence/index.js';
9
+ import { FilePatchSchema } from './types.js';
7
10
  const EXCLUDED = new Set(['_archive', '_archives', '_backup', '_backups']);
8
11
  /**
9
12
  * Resolves only the verified native project layout, without following directory links.
@@ -101,13 +104,148 @@ export const openTranscript = (directory, nativeId) => {
101
104
  };
102
105
  const BlockSchema = z.object({
103
106
  type: z.string(),
107
+ id: z.string().min(1).max(4096).optional(),
104
108
  text: z.string().optional(),
105
109
  content: z.unknown().optional(),
106
110
  name: z.string().optional(),
107
111
  input: z.unknown().optional(),
112
+ tool_use_id: z.string().min(1).max(4096).optional(),
113
+ is_error: z.boolean().optional(),
108
114
  });
115
+ const UNSUPPORTED = '[Unsupported native content]';
116
+ // the wrappers Claude Code writes around what it shows outside a model message
117
+ const LOCAL_OUTPUT = /^<local-command-stdout>([\s\S]*)<\/local-command-stdout>$/;
118
+ const SHELL_INPUT = /^<bash-input>([\s\S]*)<\/bash-input>$/;
119
+ const SHELL_OUTPUT = /^<bash-stdout>([\s\S]*)<\/bash-stdout><bash-stderr>([\s\S]*)<\/bash-stderr>$/;
120
+ const COMMAND = /^<command-(?:message|name)>/;
121
+ const COMMAND_NAME = /<command-name>\/?([^<]*)<\/command-name>/;
122
+ const COMMAND_ARGS = /<command-args>([\s\S]*?)<\/command-args>/;
123
+ const PERSISTED_OUTPUT = /^<persisted-output>\nOutput too large \(([^)\n]{1,64})\)\. Full output saved to: [^\n]*\n\nPreview \([^)\n]*\):\n([\s\S]*?)\n?<\/persisted-output>([\s\S]*)$/;
124
+ /** Shows a result saved to a file as its size and preview, without the file's path. */
125
+ const toResultText = (block) => {
126
+ if (typeof block.content !== 'string')
127
+ return `[Native ${block.type}]`;
128
+ const persisted = PERSISTED_OUTPUT.exec(block.content);
129
+ return persisted
130
+ ? `Output too large (${persisted[1]}), saved to a file\n${persisted[2]}${persisted[3]}`
131
+ : block.content;
132
+ };
133
+ /** Reads an Edit or Write result's file, counting every line of a created file as added. */
134
+ const toFileChange = (patch) => {
135
+ if (patch.type === 'create' && patch.content !== undefined)
136
+ return {
137
+ text: `${patch.filePath}\n${patch.content}`,
138
+ files: [{ path: patch.filePath, added: countLines(patch.content), removed: 0 }],
139
+ };
140
+ const lines = patch.structuredPatch.flatMap((hunk) => [
141
+ `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`,
142
+ ...hunk.lines,
143
+ ]);
144
+ return {
145
+ text: [patch.filePath, ...lines].join('\n'),
146
+ files: [
147
+ {
148
+ path: patch.filePath,
149
+ added: lines.filter((line) => line.startsWith('+')).length,
150
+ removed: lines.filter((line) => line.startsWith('-')).length,
151
+ },
152
+ ],
153
+ };
154
+ };
155
+ /**
156
+ * Presents an operator-side text record; a task notification, which the CLI doesn't show, is
157
+ * dropped, and a `!` shell output takes its input's UUID as its call.
158
+ */
159
+ const toUserPresentation = (record, text) => {
160
+ const base = { nativeType: record.type, callId: null, outcome: null, files: [] };
161
+ if (text.startsWith('<task-notification>'))
162
+ return null;
163
+ const local = LOCAL_OUTPUT.exec(text);
164
+ if (local)
165
+ return { ...base, kind: 'notice', text: local[1] };
166
+ if (text.startsWith('[Request interrupted by user'))
167
+ return { ...base, kind: 'notice', text };
168
+ const input = SHELL_INPUT.exec(text);
169
+ if (input)
170
+ return { ...base, kind: 'command', text: input[1].trim(), callId: record.uuid };
171
+ const output = SHELL_OUTPUT.exec(text);
172
+ if (output)
173
+ return {
174
+ ...base,
175
+ kind: 'command',
176
+ text: [output[1], output[2]].filter(Boolean).join('\n'),
177
+ callId: record.parentUuid ?? null,
178
+ };
179
+ const name = COMMAND.test(text) ? COMMAND_NAME.exec(text)?.[1] : undefined;
180
+ if (name) {
181
+ const args = COMMAND_ARGS.exec(text)?.[1]?.trim();
182
+ return { ...base, kind: 'user-message', text: args ? `/${name} ${args}` : `/${name}` };
183
+ }
184
+ return { ...base, kind: 'user-message', text };
185
+ };
186
+ /** Presents a native record as the CLI shows it, or null for one it leaves out. */
187
+ const toPresentation = (record) => {
188
+ const base = { nativeType: record.type, callId: null, outcome: null, files: [] };
189
+ if (record.type !== 'user' && record.type !== 'assistant')
190
+ return { ...base, kind: 'unsupported', text: UNSUPPORTED };
191
+ const message = record.type === 'user' ? 'user-message' : 'agent-message';
192
+ const content = record.message?.content;
193
+ if (typeof content !== 'string' && !Array.isArray(content))
194
+ return { ...base, kind: 'unsupported', text: UNSUPPORTED };
195
+ // the model's thinking stays collapsed in the CLI, so a record holding only thinking is dropped
196
+ const blocks = typeof content === 'string'
197
+ ? []
198
+ : content
199
+ .map((block) => BlockSchema.safeParse(block).data)
200
+ .filter((block) => block?.type !== 'thinking' && block?.type !== 'redacted_thinking');
201
+ if (Array.isArray(content) && blocks.length === 0)
202
+ return null;
203
+ const text = typeof content === 'string'
204
+ ? content
205
+ : blocks.every((block) => block?.type === 'text')
206
+ ? blocks.map((block) => block.text ?? '').join('\n')
207
+ : undefined;
208
+ if (record.isCompactSummary)
209
+ return { ...base, kind: 'notice', text: text ?? UNSUPPORTED };
210
+ if (text !== undefined)
211
+ return record.type === 'user'
212
+ ? toUserPresentation(record, text)
213
+ : { ...base, kind: 'agent-message', text };
214
+ if (blocks.every((block) => block?.type === 'tool_result')) {
215
+ const patch = FilePatchSchema.safeParse(record.toolUseResult);
216
+ return {
217
+ nativeType: 'tool-result',
218
+ kind: patch.success ? 'file-change' : 'tool',
219
+ ...(patch.success
220
+ ? toFileChange(patch.data)
221
+ : { text: blocks.map((block) => toResultText(block)).join('\n'), files: [] }),
222
+ callId: blocks.length === 1 ? (blocks[0].tool_use_id ?? null) : null,
223
+ outcome: blocks.some((block) => block.is_error) ? 'failed' : 'succeeded',
224
+ };
225
+ }
226
+ const calls = blocks.filter((block) => block?.type === 'tool_use' && block.name);
227
+ return {
228
+ ...base,
229
+ kind: calls.length > 0 ? 'tool' : message,
230
+ text: blocks
231
+ .map((block) => {
232
+ if (!block)
233
+ return UNSUPPORTED;
234
+ if (block.type === 'tool_use' && block.name)
235
+ return `${block.name}\n${JSON.stringify(block.input ?? {})}`;
236
+ if (block.type === 'text')
237
+ return block.text ?? '';
238
+ return `[Native ${block.type}]`;
239
+ })
240
+ .join('\n'),
241
+ // a record calling several tools can't pair each result with its call
242
+ callId: calls.length === 1 ? (calls[0].id ?? null) : null,
243
+ };
244
+ };
109
245
  /**
110
- * Renders selected native content as bounded plain text, never as HTML.
246
+ * Presents one native record as the CLI shows it, shared by history pages, live items and
247
+ * evidence. Outcome and files come from the full record, before the text is cut.
248
+ * @returns The item, or null for a record the CLI leaves out, such as thinking or a task notification.
111
249
  * @throws
112
250
  * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
113
251
  */
@@ -119,62 +257,18 @@ export const toClaudeItem = (record, turnId, fullBody = false) => {
119
257
  kind: 'agent-unavailable',
120
258
  },
121
259
  });
122
- if (record.type !== 'user' && record.type !== 'assistant')
123
- return {
124
- nativeId: record.uuid,
125
- turnId,
126
- nativeType: record.type,
127
- kind: 'unsupported',
128
- provenance: nativeProvenance('unsupported'),
129
- text: '[Unsupported native content]',
130
- isTruncated: false,
131
- };
132
- const content = record.message?.content;
133
- let text = '[Unsupported native content]';
134
- let isToolResult = false;
135
- let hasToolUse = false;
136
- if (typeof content === 'string')
137
- text = content;
138
- else if (Array.isArray(content)) {
139
- isToolResult =
140
- content.length > 0 &&
141
- content.every((block) => z.object({ type: z.literal('tool_result') }).safeParse(block).success);
142
- text = content
143
- .map((block) => {
144
- const parsed = BlockSchema.safeParse(block);
145
- if (!parsed.success)
146
- return '[Unsupported native content]';
147
- if (parsed.data.type === 'tool_use' && parsed.data.name) {
148
- hasToolUse = true;
149
- return `${parsed.data.name}\n${JSON.stringify(parsed.data.input ?? {})}`;
150
- }
151
- if (parsed.data.type === 'text')
152
- return parsed.data.text ?? '';
153
- if (parsed.data.type === 'tool_result' && typeof parsed.data.content === 'string')
154
- return parsed.data.content;
155
- return `[Native ${parsed.data.type}]`;
156
- })
157
- .join('\n');
158
- }
159
- let end = fullBody ? text.length : Math.min(text.length, 65_536);
260
+ const presentation = toPresentation(record);
261
+ if (!presentation)
262
+ return null;
263
+ const { text } = presentation;
264
+ let end = fullBody ? text.length : Math.min(text.length, MAX_ITEM_TEXT_LENGTH);
160
265
  if (end < text.length && /[\uD800-\uDBFF]/.test(text.charAt(end - 1)))
161
266
  end -= 1;
162
267
  return {
268
+ ...presentation,
163
269
  nativeId: record.uuid,
164
270
  turnId,
165
- nativeType: isToolResult ? 'tool-result' : record.type,
166
- provenance: record.isCompactSummary
167
- ? { ...nativeProvenance('unsupported'), origin: 'system', source: 'native-kind' }
168
- : nativeProvenance(isToolResult || hasToolUse
169
- ? 'tool'
170
- : record.type === 'user'
171
- ? 'user-message'
172
- : 'agent-message', record.type === 'user' && !isToolResult ? record.uuid : null),
173
- kind: isToolResult || hasToolUse
174
- ? 'tool'
175
- : record.type === 'user'
176
- ? 'user-message'
177
- : 'agent-message',
271
+ provenance: nativeProvenance(presentation.kind, presentation.kind === 'user-message' ? record.uuid : null),
178
272
  text: text.slice(0, end),
179
273
  isTruncated: end < text.length,
180
274
  };