@kirkchinese/harness-forge 0.4.0 → 0.5.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 (125) hide show
  1. package/README.md +4 -0
  2. package/docs/DETAIL.zh.md +47 -0
  3. package/lib/agents/presets.d.ts +7 -0
  4. package/lib/agents/presets.js +11 -1
  5. package/lib/agents/profiles.js +3 -2
  6. package/lib/agents/row.js +3 -1
  7. package/lib/client/paths.d.ts +12 -0
  8. package/lib/client/paths.js +68 -0
  9. package/lib/client/typert.d.ts +12 -1
  10. package/lib/client/typert.js +54 -6
  11. package/lib/client.js +1593 -270
  12. package/lib/commands/row.js +1 -1
  13. package/lib/context/instructions.js +5 -5
  14. package/lib/dsh/host.d.ts +3 -0
  15. package/lib/dsh/host.js +3 -0
  16. package/lib/forge/contract.d.ts +42 -2
  17. package/lib/forge/contract.js +3 -1
  18. package/lib/forge/follow.d.ts +30 -0
  19. package/lib/forge/follow.js +73 -0
  20. package/lib/forge/ledger.d.ts +70 -7
  21. package/lib/forge/ledger.js +314 -42
  22. package/lib/forge/projects.d.ts +5 -2
  23. package/lib/forge/projects.js +23 -16
  24. package/lib/forge/remote/archive.d.ts +65 -0
  25. package/lib/forge/remote/archive.js +565 -0
  26. package/lib/forge/remote/code-parts.d.ts +18 -0
  27. package/lib/forge/remote/code-parts.js +76 -0
  28. package/lib/forge/remote/fetch.d.ts +265 -0
  29. package/lib/forge/remote/fetch.js +1133 -0
  30. package/lib/forge/remote/service.d.ts +256 -0
  31. package/lib/forge/remote/service.js +868 -0
  32. package/lib/forge/service.d.ts +19 -9
  33. package/lib/forge/service.js +47 -31
  34. package/lib/forge/settings.d.ts +5 -3
  35. package/lib/forge/settings.js +11 -4
  36. package/lib/forge/state.d.ts +60 -0
  37. package/lib/forge/state.js +174 -58
  38. package/lib/hooks/broker/engine.js +2 -8
  39. package/lib/hooks/broker/session-events.d.ts +5 -0
  40. package/lib/hooks/broker/session-events.js +12 -3
  41. package/lib/hooks/broker/types.d.ts +7 -5
  42. package/lib/hooks/condition.d.ts +78 -2
  43. package/lib/hooks/condition.js +494 -73
  44. package/lib/hooks/config.d.ts +1 -1
  45. package/lib/hooks/config.js +4 -0
  46. package/lib/hooks/glob.d.ts +41 -0
  47. package/lib/hooks/glob.js +114 -0
  48. package/lib/hooks/permissions.d.ts +8 -3
  49. package/lib/hooks/permissions.js +119 -26
  50. package/lib/hooks/powershell-aliases.d.ts +19 -0
  51. package/lib/hooks/powershell-aliases.js +58 -0
  52. package/lib/hooks/process.d.ts +17 -0
  53. package/lib/hooks/process.js +156 -1
  54. package/lib/hooks/row.js +2 -0
  55. package/lib/hooks/runner.d.ts +17 -4
  56. package/lib/hooks/runner.js +42 -13
  57. package/lib/hooks/shell-commands.d.ts +10 -1
  58. package/lib/hooks/shell-commands.js +74 -10
  59. package/lib/hooks/shell.d.ts +3 -2
  60. package/lib/hooks/shell.js +5 -2
  61. package/lib/hooks/vocabulary.js +3 -1
  62. package/lib/mcp/catalog.d.ts +5 -2
  63. package/lib/mcp/catalog.js +18 -10
  64. package/lib/mcp/mount.d.ts +40 -2
  65. package/lib/mcp/mount.js +131 -31
  66. package/lib/mcp/policy.d.ts +42 -0
  67. package/lib/mcp/policy.js +43 -0
  68. package/lib/mcp/remote.js +5 -15
  69. package/lib/mcp/row.js +111 -17
  70. package/lib/mods/loader.js +4 -0
  71. package/lib/mods/service/turns.d.ts +8 -7
  72. package/lib/mods/service/turns.js +10 -35
  73. package/lib/opencode/bun.js +14 -2
  74. package/lib/opencode/row.d.ts +14 -1
  75. package/lib/opencode/row.js +38 -20
  76. package/lib/opencode/runtime/server.js +2 -1
  77. package/lib/porting/adapter-paths.d.ts +13 -0
  78. package/lib/porting/adapter-paths.js +120 -0
  79. package/lib/porting/port-gap.d.ts +10 -4
  80. package/lib/porting/port-gap.js +43 -7
  81. package/lib/porting/prompt.js +9 -7
  82. package/lib/porting/row.js +7 -5
  83. package/lib/porting/verify-port.d.ts +3 -10
  84. package/lib/porting/verify-port.js +12 -34
  85. package/lib/sessions/chat-import.d.ts +48 -0
  86. package/lib/sessions/chat-import.js +44 -0
  87. package/lib/sessions/claude.d.ts +16 -10
  88. package/lib/sessions/claude.js +76 -55
  89. package/lib/sessions/codex-discover.d.ts +34 -0
  90. package/lib/sessions/codex-discover.js +205 -0
  91. package/lib/sessions/codex-meta.d.ts +63 -0
  92. package/lib/sessions/codex-meta.js +148 -0
  93. package/lib/sessions/codex-text.d.ts +9 -0
  94. package/lib/sessions/codex-text.js +44 -0
  95. package/lib/sessions/codex.d.ts +34 -22
  96. package/lib/sessions/codex.js +150 -183
  97. package/lib/sessions/opencode.d.ts +15 -9
  98. package/lib/sessions/opencode.js +77 -58
  99. package/lib/sessions/persist.d.ts +162 -0
  100. package/lib/sessions/persist.js +377 -0
  101. package/lib/sessions/row.d.ts +2 -1
  102. package/lib/sessions/row.js +75 -9
  103. package/lib/sessions/turns.d.ts +31 -0
  104. package/lib/sessions/turns.js +63 -0
  105. package/lib/sessions/zstd.d.ts +15 -0
  106. package/lib/sessions/zstd.js +152 -0
  107. package/lib/shared/render.d.ts +30 -1
  108. package/lib/shared/render.js +813 -48
  109. package/lib/skills/provider.d.ts +2 -0
  110. package/lib/skills/provider.js +8 -2
  111. package/lib/skills/row.js +1 -1
  112. package/lib/workbench/adapter-coverage.d.ts +20 -2
  113. package/lib/workbench/adapter-coverage.js +46 -7
  114. package/lib/workbench/overview.d.ts +77 -27
  115. package/lib/workbench/overview.js +99 -12
  116. package/lib/workbench/remote.d.ts +64 -21
  117. package/lib/workbench/remote.js +181 -42
  118. package/lib/workbench/settings.d.ts +5 -1
  119. package/lib/workbench/settings.js +6 -2
  120. package/lib/workbench/workbench.d.ts +34 -4
  121. package/lib/workbench/workbench.js +147 -46
  122. package/locale/zh.json +2 -1
  123. package/package.json +3 -2
  124. package/lib/forge/marketplace-install.d.ts +0 -3
  125. package/lib/forge/marketplace-install.js +0 -64
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Listing Codex sessions for import. Codex keeps one rollout file per thread (some a gigabyte), in
3
+ * `sessions/YYYY/MM/DD`, plus the threads it archived in `archived_sessions`; the thread names the person gave
4
+ * are in `session_index.jsonl`. The list is built from file names and modification times alone, newest first; only
5
+ * the files of the page asked for are opened, and only their first bytes.
6
+ * @module @kirkchinese/harness-forge
7
+ */
8
+ import { open, readdir, stat } from 'node:fs/promises';
9
+ import { basename, dirname, join } from 'node:path';
10
+ import { SESSION_PAGE_SIZE } from '../forge/contract.js';
11
+ import { stringField } from './codex-text.js';
12
+ import { CodexTitle, rolloutCreatedAt, rolloutThread, threadNames } from './codex-meta.js';
13
+ import { decodeZstdHead, zstdAvailable } from './zstd.js';
14
+ /** Most files opened for one page: skipped ones (subagent threads) still cost a read. */
15
+ const PROBE_LIMIT = 400;
16
+ /** The `session_meta` line is a few tens of KB (it carries the base instructions). */
17
+ const META_BYTES = 64 * 1024;
18
+ const HEAD_BYTES = 256 * 1024;
19
+ /** How far into a rollout the first thing the person said is looked for, when it is not in the first bytes. */
20
+ const DEEP_HEAD_BYTES = 4 * 1024 * 1024;
21
+ const COMPRESSED_HEAD_BYTES = 4 * 1024 * 1024;
22
+ const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
23
+ /** `rollout-<time>-<thread>.jsonl`; a thread Codex continued in a new file is `…-<thread>_<segment>.jsonl`. */
24
+ const ROLLOUT_NAME = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_${UUID})?\\.jsonl(?:\\.zst)?$`, 'iu');
25
+ const ROLLOUT_FILE = /^rollout-.*\.jsonl(?:\.zst)?$/u;
26
+ /**
27
+ * One page of the Codex sessions under `root` (`~/.codex/sessions`; the archive and the thread names are read from
28
+ * its siblings), newest first: every `rollout-*.jsonl` and `.jsonl.zst`, a thread once. A subagent's thread is part
29
+ * of the session that spawned it and left out, unless `isImported` says an import of it is stored: an earlier
30
+ * version imported those, and the copy has to stay reachable.
31
+ */
32
+ export async function discoverCodexSessions(root, page = {}, isImported = async () => false) {
33
+ const limit = Math.max(1, page.limit ?? SESSION_PAGE_SIZE);
34
+ const files = await listRollouts(root);
35
+ const names = await threadNames(basename(root) === 'sessions' ? dirname(root) : undefined);
36
+ const sessions = [];
37
+ let at = Math.max(0, page.cursor ?? 0);
38
+ const stop = Math.min(files.length, at + PROBE_LIMIT);
39
+ for (; at < stop && sessions.length < limit; at++) {
40
+ const candidate = await probe(files[at], names).catch(() => undefined);
41
+ if (candidate !== undefined && (candidate.subagent !== true || await isImported(candidate)))
42
+ sessions.push(candidate);
43
+ }
44
+ return { sessions, ...(at < files.length ? { next: at } : {}) };
45
+ }
46
+ /** The thread each rollout file held when it was last read, by path: a rollout's `session_meta` never changes. */
47
+ const threadCache = new Map();
48
+ /**
49
+ * Every thread the rollouts under `root` hold, subagent threads included (an earlier version imported those too):
50
+ * what tells whether an id an earlier version gave a thread was given to others. Each file's `session_meta` is read
51
+ * once, until the file changes.
52
+ */
53
+ export async function codexThreads(root) {
54
+ const threads = new Map();
55
+ for (const file of await listRollouts(root)) {
56
+ let cached = threadCache.get(file.path);
57
+ if (cached === undefined || cached.updatedAt !== file.updatedAt || cached.bytes !== file.bytes) {
58
+ const meta = await readMeta(file.path).catch(() => undefined);
59
+ const thread = meta === undefined ? undefined : rolloutThread(meta.payload);
60
+ cached = { updatedAt: file.updatedAt, bytes: file.bytes, thread: meta === undefined || thread === undefined ? undefined : { thread, createdAt: rolloutCreatedAt(meta.payload, meta.firstTime), path: file.path } };
61
+ threadCache.set(file.path, cached);
62
+ }
63
+ if (cached.thread !== undefined)
64
+ threads.set(cached.thread.thread.id, cached.thread);
65
+ }
66
+ return [...threads.values()];
67
+ }
68
+ /**
69
+ * Every rollout file, a thread once (the file written last), newest first. A thread is told by its file name; an
70
+ * older file whose name does not carry it, by the `session_meta` at its start. Done for the whole list before it is
71
+ * cut into pages, so a thread is on one page only.
72
+ */
73
+ async function listRollouts(root) {
74
+ const found = [];
75
+ const walk = async (dir, archived) => {
76
+ let entries;
77
+ try {
78
+ entries = await readdir(dir, { withFileTypes: true });
79
+ }
80
+ catch {
81
+ return;
82
+ }
83
+ for (const entry of entries) {
84
+ const path = join(dir, entry.name);
85
+ if (entry.isDirectory())
86
+ await walk(path, archived);
87
+ else if (entry.isFile() && ROLLOUT_FILE.test(entry.name)) {
88
+ const info = await stat(path).catch(() => undefined);
89
+ const thread = ROLLOUT_NAME.exec(entry.name)?.[1]?.toLowerCase();
90
+ if (info !== undefined)
91
+ found.push({ path, ...(thread !== undefined ? { thread } : {}), updatedAt: info.mtimeMs, bytes: info.size, archived });
92
+ }
93
+ }
94
+ };
95
+ await walk(root, false);
96
+ if (basename(root) === 'sessions')
97
+ await walk(join(dirname(root), 'archived_sessions'), true);
98
+ // The compressed twin of a rollout still on disk as plain text is the same session.
99
+ const plain = new Set(found.filter(file => !file.path.endsWith('.zst')).map(file => file.path));
100
+ const readable = found.filter(file => !file.path.endsWith('.zst') || (zstdAvailable() && !plain.has(file.path.slice(0, -'.zst'.length))));
101
+ readable.sort((a, b) => b.updatedAt - a.updatedAt || b.path.localeCompare(a.path));
102
+ const kept = new Set();
103
+ const out = [];
104
+ for (const file of readable) {
105
+ const key = file.thread ?? await metaThread(file.path) ?? file.path;
106
+ if (kept.has(key))
107
+ continue;
108
+ kept.add(key);
109
+ out.push(file);
110
+ }
111
+ return out;
112
+ }
113
+ /** The thread an older rollout holds, from its `session_meta`; `undefined` when its first bytes do not say. */
114
+ async function metaThread(path) {
115
+ try {
116
+ const meta = await readMeta(path);
117
+ return meta === undefined ? undefined : rolloutThread(meta.payload)?.id.toLowerCase();
118
+ }
119
+ catch {
120
+ return undefined;
121
+ }
122
+ }
123
+ /** A rollout's `session_meta` record (its payload, and the time of the first record), from its first bytes. */
124
+ async function readMeta(path) {
125
+ for (const bytes of [META_BYTES, HEAD_BYTES]) {
126
+ const head = records(await readHead(path, bytes));
127
+ const payload = head.find(record => record['type'] === 'session_meta')?.['payload'];
128
+ if (typeof payload === 'object' && payload !== null)
129
+ return { payload: payload, firstTime: head[0]?.['timestamp'] };
130
+ }
131
+ return undefined;
132
+ }
133
+ async function probe(file, names) {
134
+ const meta = await readMeta(file.path);
135
+ if (meta === undefined)
136
+ return undefined;
137
+ const thread = rolloutThread(meta.payload);
138
+ if (thread === undefined)
139
+ return undefined;
140
+ const source = meta.payload['source'];
141
+ const subagent = typeof source === 'object' && source !== null && 'subagent' in source;
142
+ const title = await titleOf(file.path, new CodexTitle(names.get(thread.id)));
143
+ const cwd = stringField(meta.payload['cwd']);
144
+ const createdAt = rolloutCreatedAt(meta.payload, meta.firstTime);
145
+ return {
146
+ path: file.path,
147
+ sourceId: thread.id,
148
+ ...(thread.sessionId !== thread.id ? { parentId: thread.sessionId } : {}),
149
+ ...(title !== undefined ? { title } : {}),
150
+ ...(cwd !== undefined ? { cwd } : {}),
151
+ ...(createdAt > 0 ? { createdAt } : {}),
152
+ updatedAt: file.updatedAt,
153
+ bytes: file.bytes,
154
+ ...(file.archived ? { archived: true } : {}),
155
+ ...(subagent ? { subagent: true } : {}),
156
+ };
157
+ }
158
+ /** The thread's title: its name, else what the person first said, from the start of the rollout. */
159
+ async function titleOf(path, title) {
160
+ if (title.title !== undefined)
161
+ return title.title;
162
+ for (const bytes of [HEAD_BYTES, DEEP_HEAD_BYTES]) {
163
+ const text = await readHead(path, bytes);
164
+ for (const record of records(text)) {
165
+ title.observe(record);
166
+ if (title.title !== undefined)
167
+ return title.title;
168
+ }
169
+ // The whole file was read, or the whole of what can be decoded: nothing more to find.
170
+ if (Buffer.byteLength(text) < bytes * 0.9)
171
+ break;
172
+ }
173
+ return undefined;
174
+ }
175
+ /** The complete lines among the first `bytes` of a rollout's text (a line cut at the end is dropped). */
176
+ function records(text) {
177
+ const out = [];
178
+ for (const line of text.split('\n')) {
179
+ if (line.length === 0)
180
+ continue;
181
+ try {
182
+ const value = JSON.parse(line);
183
+ if (typeof value === 'object' && value !== null)
184
+ out.push(value);
185
+ }
186
+ catch {
187
+ // The line the read stopped in, or a damaged one.
188
+ }
189
+ }
190
+ return out;
191
+ }
192
+ /** The first `bytes` of a rollout (decoded, when compressed). */
193
+ async function readHead(path, bytes) {
194
+ const handle = await open(path, 'r');
195
+ try {
196
+ const compressed = path.endsWith('.zst');
197
+ const length = compressed ? COMPRESSED_HEAD_BYTES : bytes;
198
+ const buffer = Buffer.alloc(length);
199
+ const { bytesRead } = await handle.read(buffer, 0, length, 0);
200
+ return compressed ? await decodeZstdHead(buffer.subarray(0, bytesRead), bytes) : buffer.toString('utf8', 0, bytesRead);
201
+ }
202
+ finally {
203
+ await handle.close();
204
+ }
205
+ }
@@ -0,0 +1,63 @@
1
+ import type { ImportIdentity } from './persist.js';
2
+ import type { TurnReader } from './turns.js';
3
+ /** Which thread a rollout holds, from its `session_meta` payload. */
4
+ export interface RolloutThread {
5
+ /** The thread (`id`). */
6
+ readonly id: string;
7
+ /** The session the thread belongs to (`session_id`): a forked thread's parent, else the thread itself. */
8
+ readonly sessionId: string;
9
+ }
10
+ /** The thread of a `session_meta` payload. `id` is the thread; `session_id` of a forked thread is its parent's. */
11
+ export declare function rolloutThread(meta: Readonly<Record<string, unknown>>): RolloutThread | undefined;
12
+ /**
13
+ * When a rollout's thread was created: its `session_meta` time, else the time of its first record; 0 when it has
14
+ * none. Every Harness Forge version stored this as the DSH session's `createdAt`, which is what tells which thread a
15
+ * stored session holds.
16
+ */
17
+ export declare function rolloutCreatedAt(meta: Readonly<Record<string, unknown>>, firstRecordTime: unknown): number;
18
+ /**
19
+ * The DSH id of an imported Codex session. Prefixed, so it never equals the Codex id: a session under the source's
20
+ * own id reads as native to other importers (dsh-chat-import hides those sources).
21
+ */
22
+ export declare function codexSessionId(sourceId: string): string;
23
+ /** A thread a rollout holds, when it was created, and the rollout. */
24
+ export interface IndexedThread {
25
+ readonly thread: RolloutThread;
26
+ readonly createdAt: number;
27
+ readonly path: string;
28
+ }
29
+ /** What tells which thread a stored session holds, beyond its creation time; each read only when it is needed. */
30
+ export interface CodexEvidence {
31
+ /** Every thread the rollouts beside this one hold (this one may be among them). */
32
+ threads(): Promise<readonly IndexedThread[]>;
33
+ /** A reader of this thread's turns, as the import reads them. */
34
+ turns(): TurnReader;
35
+ /** A reader of another rollout's turns. */
36
+ turnsOf(path: string): TurnReader;
37
+ }
38
+ /**
39
+ * How an import finds the DSH session holding a thread: under its own id, or an id an earlier version gave it if
40
+ * the stored session's creation time is the thread's, and, when that id was given to other threads too, its turns
41
+ * are this thread's ({@link matchStored}).
42
+ */
43
+ export declare function codexIdentity(thread: RolloutThread, createdAt: number, evidence: CodexEvidence): ImportIdentity;
44
+ /** Text on one line, whitespace collapsed and cut at {@link TITLE_CHARS}; `undefined` when nothing is left. */
45
+ export declare function oneLine(text: string): string | undefined;
46
+ /** The text a person typed in one record: a message, whichever of Codex's ways of writing it. */
47
+ export declare function typedPrompt(record: Readonly<Record<string, unknown>>): string | undefined;
48
+ /**
49
+ * A Codex thread's title, chosen the way Codex shows it: the name the person gave the thread (in
50
+ * `session_index.jsonl`), else what they first said. The list and the import both take it from here.
51
+ */
52
+ export declare class CodexTitle {
53
+ private readonly name?;
54
+ private prompt;
55
+ constructor(name?: string | undefined);
56
+ /** Look at one record of the rollout, in file order. */
57
+ observe(record: Readonly<Record<string, unknown>>): void;
58
+ get title(): string | undefined;
59
+ }
60
+ /** The Codex home a rollout is in (`~/.codex` for `~/.codex/sessions/…` or `~/.codex/archived_sessions/…`). */
61
+ export declare function codexHomeOf(rolloutPath: string): string | undefined;
62
+ /** Thread names from `session_index.jsonl` in a Codex home, by thread id; a later line for a thread (a rename) wins. */
63
+ export declare function threadNames(codexHome: string | undefined): Promise<Map<string, string>>;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * What listing and importing a Codex rollout must agree on: which thread it is, when it was created, what it is
3
+ * called, and which DSH session holds it. One definition each, so the row a person picks is the session they get.
4
+ * @module @kirkchinese/harness-forge
5
+ */
6
+ import { readFile, stat } from 'node:fs/promises';
7
+ import { basename, dirname, join } from 'node:path';
8
+ import { stringField, textOf, timestamp, usablePrompt } from './codex-text.js';
9
+ /** Longest title, in characters: a long first message is no title past a line or so. */
10
+ const TITLE_CHARS = 120;
11
+ /** The thread names file stays small (one line per rename); a larger one is not Codex's and is not read. */
12
+ const INDEX_MAX_BYTES = 16 * 1024 * 1024;
13
+ /** The thread of a `session_meta` payload. `id` is the thread; `session_id` of a forked thread is its parent's. */
14
+ export function rolloutThread(meta) {
15
+ const id = stringField(meta['id']) ?? stringField(meta['session_id']);
16
+ if (id === undefined)
17
+ return undefined;
18
+ return { id, sessionId: stringField(meta['session_id']) ?? id };
19
+ }
20
+ /**
21
+ * When a rollout's thread was created: its `session_meta` time, else the time of its first record; 0 when it has
22
+ * none. Every Harness Forge version stored this as the DSH session's `createdAt`, which is what tells which thread a
23
+ * stored session holds.
24
+ */
25
+ export function rolloutCreatedAt(meta, firstRecordTime) {
26
+ return timestamp(meta['timestamp']) ?? timestamp(firstRecordTime) ?? 0;
27
+ }
28
+ /**
29
+ * The DSH id of an imported Codex session. Prefixed, so it never equals the Codex id: a session under the source's
30
+ * own id reads as native to other importers (dsh-chat-import hides those sources).
31
+ */
32
+ export function codexSessionId(sourceId) {
33
+ return `codex-${sourceId}`;
34
+ }
35
+ /**
36
+ * The ids earlier versions gave a thread. Harness Forge 0.4.0 used the bare `session_meta.session_id ?? id`, and
37
+ * builds after it, before this one, the same prefixed (`codex-<session_id>`); a fork carries its parent's
38
+ * `session_id`, so the parent and its forks got one id. Older ones used the bare thread id.
39
+ */
40
+ function codexLegacyIds(thread) {
41
+ const id = codexSessionId(thread.id);
42
+ return [...new Set([codexSessionId(thread.sessionId), thread.sessionId, thread.id])].filter(legacy => legacy !== id);
43
+ }
44
+ /**
45
+ * How an import finds the DSH session holding a thread: under its own id, or an id an earlier version gave it if
46
+ * the stored session's creation time is the thread's, and, when that id was given to other threads too, its turns
47
+ * are this thread's ({@link matchStored}).
48
+ */
49
+ export function codexIdentity(thread, createdAt, evidence) {
50
+ const id = codexSessionId(thread.id);
51
+ return {
52
+ id,
53
+ legacyIds: codexLegacyIds(thread),
54
+ provenance: {
55
+ createdAt,
56
+ alternateId: `${id}-${createdAt}`,
57
+ // The other threads created at this one's time that may be stored under the id, as their own (this
58
+ // version's) or as an earlier version's: a thread created at another time is not the one stored there.
59
+ rivals: async (legacyId) => (await evidence.threads())
60
+ .filter(other => other.thread.id !== thread.id && other.createdAt === createdAt
61
+ && (codexSessionId(other.thread.id) === legacyId || codexLegacyIds(other.thread).includes(legacyId)))
62
+ .map(other => () => evidence.turnsOf(other.path)),
63
+ turns: () => evidence.turns(),
64
+ },
65
+ };
66
+ }
67
+ /** Text on one line, whitespace collapsed and cut at {@link TITLE_CHARS}; `undefined` when nothing is left. */
68
+ export function oneLine(text) {
69
+ const line = text.trim().replace(/\s+/gu, ' ');
70
+ if (line.length === 0)
71
+ return undefined;
72
+ return line.length <= TITLE_CHARS ? line : `${line.slice(0, TITLE_CHARS - 1).trimEnd()}…`;
73
+ }
74
+ /** The text a person typed in one record: a message, whichever of Codex's ways of writing it. */
75
+ export function typedPrompt(record) {
76
+ const payload = record['payload'];
77
+ if (payload === undefined)
78
+ return undefined;
79
+ let text;
80
+ if (record['type'] === 'event_msg' && payload['type'] === 'user_message')
81
+ text = stringField(payload['message']);
82
+ else if (record['type'] === 'event_msg' && payload['type'] === 'item_completed') {
83
+ const item = payload['item'];
84
+ if (item?.['type'] === 'UserMessage')
85
+ text = textOf(item['content']);
86
+ }
87
+ else if (record['type'] === 'response_item' && payload['type'] === 'message' && payload['role'] === 'user')
88
+ text = textOf(payload['content']);
89
+ return text !== undefined && usablePrompt(text) ? text : undefined;
90
+ }
91
+ /**
92
+ * A Codex thread's title, chosen the way Codex shows it: the name the person gave the thread (in
93
+ * `session_index.jsonl`), else what they first said. The list and the import both take it from here.
94
+ */
95
+ export class CodexTitle {
96
+ name;
97
+ prompt;
98
+ constructor(name) {
99
+ this.name = name;
100
+ }
101
+ /** Look at one record of the rollout, in file order. */
102
+ observe(record) {
103
+ if (this.name !== undefined || this.prompt !== undefined)
104
+ return;
105
+ const typed = typedPrompt(record);
106
+ if (typed !== undefined)
107
+ this.prompt = oneLine(typed);
108
+ }
109
+ get title() {
110
+ return this.name ?? this.prompt;
111
+ }
112
+ }
113
+ /** The Codex home a rollout is in (`~/.codex` for `~/.codex/sessions/…` or `~/.codex/archived_sessions/…`). */
114
+ export function codexHomeOf(rolloutPath) {
115
+ for (let dir = dirname(rolloutPath); dirname(dir) !== dir; dir = dirname(dir)) {
116
+ if (basename(dir) === 'sessions' || basename(dir) === 'archived_sessions')
117
+ return dirname(dir);
118
+ }
119
+ return undefined;
120
+ }
121
+ /** Thread names from `session_index.jsonl` in a Codex home, by thread id; a later line for a thread (a rename) wins. */
122
+ export async function threadNames(codexHome) {
123
+ const names = new Map();
124
+ if (codexHome === undefined)
125
+ return names;
126
+ const path = join(codexHome, 'session_index.jsonl');
127
+ try {
128
+ if ((await stat(path)).size > INDEX_MAX_BYTES)
129
+ return names;
130
+ for (const line of (await readFile(path, 'utf8')).split(/\r?\n/u)) {
131
+ if (line.trim().length === 0)
132
+ continue;
133
+ try {
134
+ const entry = JSON.parse(line);
135
+ const name = typeof entry.thread_name === 'string' ? oneLine(entry.thread_name) : undefined;
136
+ if (typeof entry.id === 'string' && name !== undefined)
137
+ names.set(entry.id, name);
138
+ }
139
+ catch {
140
+ // A line cut by a crash; the rest of the index is intact.
141
+ }
142
+ }
143
+ }
144
+ catch {
145
+ // No index: titles come from the first message.
146
+ }
147
+ return names;
148
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * What the Codex rollout readers share: the text of a message's content, the prompts a person typed (not the
3
+ * instructions Codex puts first), and the typed fields of a record.
4
+ * @module @kirkchinese/harness-forge
5
+ */
6
+ export declare function usablePrompt(text: string): boolean;
7
+ export declare function textOf(value: unknown): string;
8
+ export declare function stringField(value: unknown): string | undefined;
9
+ export declare function timestamp(value: unknown): number | undefined;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * What the Codex rollout readers share: the text of a message's content, the prompts a person typed (not the
3
+ * instructions Codex puts first), and the typed fields of a record.
4
+ * @module @kirkchinese/harness-forge
5
+ */
6
+ export function usablePrompt(text) {
7
+ const value = text.trim();
8
+ if (value.length === 0)
9
+ return false;
10
+ if (value.startsWith('<') || value.startsWith('# AGENTS.md'))
11
+ return false;
12
+ return !(value.includes('<environment_context>')
13
+ || value.includes('<skills_instructions>')
14
+ || value.includes('<permissions instructions>')
15
+ || value.includes('<user_instructions>'));
16
+ }
17
+ export function textOf(value) {
18
+ if (typeof value === 'string')
19
+ return value;
20
+ if (!Array.isArray(value))
21
+ return '';
22
+ return value
23
+ .map((item) => {
24
+ if (typeof item === 'string')
25
+ return item;
26
+ if (typeof item !== 'object' || item === null)
27
+ return '';
28
+ const record = item;
29
+ return typeof record['text'] === 'string' ? record['text'] : '';
30
+ })
31
+ .filter(Boolean)
32
+ .join('\n');
33
+ }
34
+ export function stringField(value) {
35
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
36
+ }
37
+ export function timestamp(value) {
38
+ if (typeof value === 'string') {
39
+ const parsed = Date.parse(value);
40
+ if (Number.isFinite(parsed))
41
+ return parsed;
42
+ }
43
+ return undefined;
44
+ }
@@ -1,30 +1,42 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
2
  import type { NormalizedSession } from '@kirkchinese/harness-forge-core';
3
- export interface CodexSessionCandidate {
4
- readonly path: string;
5
- readonly sourceId: string;
6
- readonly title?: string;
7
- readonly cwd?: string;
8
- readonly createdAt?: number;
9
- }
10
- export interface CodexImportReport {
11
- readonly id: string;
12
- readonly sourcePath: string;
13
- readonly title?: string;
14
- readonly turns: number;
15
- readonly events: number;
16
- readonly stats: Record<string, number>;
17
- }
3
+ import { type LineObserver, type TranscriptLine } from '@kirkchinese/harness-forge-core';
4
+ import { type IndexedThread, type RolloutThread } from './codex-meta.js';
5
+ import { type ImportIdentity, type ImportReport } from './persist.js';
6
+ export type CodexImportReport = ImportReport;
7
+ export { discoverCodexSessions, type CodexSessionCandidate } from './codex-discover.js';
8
+ export { codexSessionId } from './codex-meta.js';
18
9
  /** Default Codex rollout directory. */
19
10
  export declare function defaultCodexSessionsRoot(home?: string): string;
20
- /** Discover `rollout-*.jsonl` files newest first. */
21
- export declare function discoverCodexSessions(root?: string, limit?: number): Promise<CodexSessionCandidate[]>;
11
+ /** One Codex rollout in the shared normalized model, with the thread it holds. */
12
+ export interface CodexRollout {
13
+ /** The session, under the id this version gives the thread (or `targetId`). */
14
+ readonly session: NormalizedSession;
15
+ readonly title?: string;
16
+ readonly thread: RolloutThread;
17
+ }
22
18
  /** Parse one Codex rollout into the shared normalized model. */
23
- export declare function readCodexSession(path: string, targetId?: string): Promise<{
24
- session: NormalizedSession;
25
- title?: string;
26
- }>;
27
- /** Import one Codex rollout into DSH session persistence. */
19
+ export declare function readCodexSession(path: string, targetId?: string): Promise<CodexRollout>;
20
+ /**
21
+ * Import one Codex rollout into DSH session persistence: into the session that already holds its thread, else a new
22
+ * one. A stored session that may or may not hold it (nothing tells) is not guessed at: the import is refused, and
23
+ * the list offers both. `targetId` imports into that session, the way "Import as new" does.
24
+ */
28
25
  export declare function importCodexSession(ctx: Context, sourcePath: string, options?: {
29
26
  readonly targetId?: string;
30
27
  }): Promise<CodexImportReport>;
28
+ /** What the list and the import know already, so neither reads it again. */
29
+ export interface KnownRollout {
30
+ /** The threads under a sessions folder ({@link codexThreads}), shared by the rows of one list. */
31
+ readonly threads?: (root: string) => Promise<readonly IndexedThread[]>;
32
+ /** The rollout, read. */
33
+ readonly session?: NormalizedSession;
34
+ }
35
+ /** The identity of the thread a rollout holds: the one the list shows and the import uses. */
36
+ export declare function rolloutIdentity(path: string, thread: RolloutThread, createdAt: number, known?: KnownRollout): ImportIdentity;
37
+ /**
38
+ * The lines of a rollout, plain or compressed, streamed: what the import reads. The size is checked before the file
39
+ * is read (a compressed one, as its decoded bytes stream by), so a rollout that is too large costs nothing.
40
+ * `observer` sees how much the line splitter holds at once.
41
+ */
42
+ export declare function rolloutLines(path: string, observer?: LineObserver): AsyncGenerator<TranscriptLine>;