@tienne/gestalt 0.153.0 → 0.155.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.
- package/dist/package.json +1 -1
- package/dist/plugin/.codex-plugin/plugin.json +1 -1
- package/dist/plugin/skills/conductor/SKILL.md +9 -2
- package/dist/src/cli/commands/conductor-results.d.ts.map +1 -1
- package/dist/src/cli/commands/conductor-results.js +2 -0
- package/dist/src/cli/commands/conductor-results.js.map +1 -1
- package/dist/src/cli/commands/conductor.d.ts +11 -0
- package/dist/src/cli/commands/conductor.d.ts.map +1 -1
- package/dist/src/cli/commands/conductor.js +46 -0
- package/dist/src/cli/commands/conductor.js.map +1 -1
- package/dist/src/cli/index.d.ts.map +1 -1
- package/dist/src/cli/index.js +13 -1
- package/dist/src/cli/index.js.map +1 -1
- package/dist/src/conductor/activity-tick.d.ts +47 -0
- package/dist/src/conductor/activity-tick.d.ts.map +1 -0
- package/dist/src/conductor/activity-tick.js +132 -0
- package/dist/src/conductor/activity-tick.js.map +1 -0
- package/dist/src/conductor/activity.d.ts +94 -0
- package/dist/src/conductor/activity.d.ts.map +1 -0
- package/dist/src/conductor/activity.js +151 -0
- package/dist/src/conductor/activity.js.map +1 -0
- package/dist/src/conductor/archive.d.ts +62 -0
- package/dist/src/conductor/archive.d.ts.map +1 -0
- package/dist/src/conductor/archive.js +286 -0
- package/dist/src/conductor/archive.js.map +1 -0
- package/dist/src/conductor/engine.d.ts +7 -1
- package/dist/src/conductor/engine.d.ts.map +1 -1
- package/dist/src/conductor/engine.js +105 -7
- package/dist/src/conductor/engine.js.map +1 -1
- package/dist/src/conductor/fold.d.ts +16 -0
- package/dist/src/conductor/fold.d.ts.map +1 -1
- package/dist/src/conductor/fold.js +46 -5
- package/dist/src/conductor/fold.js.map +1 -1
- package/dist/src/conductor/intake.d.ts +5 -0
- package/dist/src/conductor/intake.d.ts.map +1 -1
- package/dist/src/conductor/intake.js +3 -0
- package/dist/src/conductor/intake.js.map +1 -1
- package/dist/src/conductor/jira.d.ts +4 -0
- package/dist/src/conductor/jira.d.ts.map +1 -1
- package/dist/src/conductor/jira.js +8 -0
- package/dist/src/conductor/jira.js.map +1 -1
- package/dist/src/conductor/launcher.d.ts +18 -0
- package/dist/src/conductor/launcher.d.ts.map +1 -1
- package/dist/src/conductor/launcher.js +47 -3
- package/dist/src/conductor/launcher.js.map +1 -1
- package/dist/src/conductor/pr-watch.d.ts +1 -1
- package/dist/src/conductor/pr-watch.d.ts.map +1 -1
- package/dist/src/conductor/pr-watch.js +8 -5
- package/dist/src/conductor/pr-watch.js.map +1 -1
- package/dist/src/conductor/recent-events.js +2 -1
- package/dist/src/conductor/recent-events.js.map +1 -1
- package/dist/src/conductor/results.d.ts +5 -0
- package/dist/src/conductor/results.d.ts.map +1 -1
- package/dist/src/conductor/results.js +3 -1
- package/dist/src/conductor/results.js.map +1 -1
- package/dist/src/conductor/resume.d.ts +5 -0
- package/dist/src/conductor/resume.d.ts.map +1 -1
- package/dist/src/conductor/resume.js +12 -0
- package/dist/src/conductor/resume.js.map +1 -1
- package/dist/src/conductor/store.d.ts +35 -2
- package/dist/src/conductor/store.d.ts.map +1 -1
- package/dist/src/conductor/store.js +122 -22
- package/dist/src/conductor/store.js.map +1 -1
- package/dist/src/conductor/transcript-tools.d.ts +19 -0
- package/dist/src/conductor/transcript-tools.d.ts.map +1 -0
- package/dist/src/conductor/transcript-tools.js +32 -0
- package/dist/src/conductor/transcript-tools.js.map +1 -0
- package/dist/src/conductor/transcript.d.ts +137 -0
- package/dist/src/conductor/transcript.d.ts.map +1 -0
- package/dist/src/conductor/transcript.js +654 -0
- package/dist/src/conductor/transcript.js.map +1 -0
- package/dist/src/conductor/types.d.ts +19 -2
- package/dist/src/conductor/types.d.ts.map +1 -1
- package/dist/src/conductor/types.js +1 -0
- package/dist/src/conductor/types.js.map +1 -1
- package/dist/src/conductor/work-log.d.ts +82 -0
- package/dist/src/conductor/work-log.d.ts.map +1 -0
- package/dist/src/conductor/work-log.js +223 -0
- package/dist/src/conductor/work-log.js.map +1 -0
- package/dist/src/conductor-web/html.js +141 -1
- package/dist/src/conductor-web/html.js.map +1 -1
- package/dist/src/conductor-web/server.d.ts +8 -1
- package/dist/src/conductor-web/server.d.ts.map +1 -1
- package/dist/src/conductor-web/server.js +16 -0
- package/dist/src/conductor-web/server.js.map +1 -1
- package/dist/src/core/config.d.ts +18 -0
- package/dist/src/core/config.d.ts.map +1 -1
- package/dist/src/core/config.js +10 -0
- package/dist/src/core/config.js.map +1 -1
- package/package.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.mcp.json +1 -1
- package/plugin/mcp.json +1 -1
- package/plugin/skills/conductor/SKILL.md +9 -2
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
import { closeSync, existsSync, fstatSync, openSync, readdirSync, readSync, realpathSync, statSync, } from 'node:fs';
|
|
2
|
+
import { maskSecrets } from '../architecture/secret-mask.js';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { basename, dirname, isAbsolute, join, relative } from 'node:path';
|
|
5
|
+
import { cwdSlug, isSessionId } from '../peer/locate.js';
|
|
6
|
+
import { LAUNCHED_STATUSES, SHELL_TOOLS, SUBAGENT_TOOLS, TASK_TOOLS, TODO_TOOLS, WRITE_TOOLS, } from './transcript-tools.js';
|
|
7
|
+
/**
|
|
8
|
+
* 컨덕터 워커의 Claude Code 트랜스크립트 리더.
|
|
9
|
+
*
|
|
10
|
+
* `~/.claude/projects/<워크트리 경로를 인코딩한 디렉토리>/<세션 id>.jsonl` 끝에서 정해진 크기까지만 읽고
|
|
11
|
+
* 읽은 위치를 커서에 남겨 다음엔 새 줄만 읽는다. 처음 읽을 때 앞부분을 건너뛰면 `history: 'partial'`이다.
|
|
12
|
+
* 트랜스크립트는 문서화되지 않은 형식이라 모르는 줄은 건너뛰고 읽다 실패하면 부르는 쪽이 필드를 비운다.
|
|
13
|
+
* 보조 신호라서 이 모듈이 실패해도 컨덕터 동작은 바뀌지 않아야 한다.
|
|
14
|
+
*
|
|
15
|
+
* 읽는 방식은 agenttrail(github.com/sodiumsun/agenttrail)의 `bin/lib/claude.mjs`, `logtail.mjs`, `tasks.mjs`를
|
|
16
|
+
* 따랐다. 서브에이전트가 쓴 자기 트랜스크립트(`<세션 id>/subagents/`)는 읽지 않는다.
|
|
17
|
+
*/
|
|
18
|
+
/** 한 번에 읽는 상한. agenttrail과 같다 */
|
|
19
|
+
export const READ_LIMIT = 2 * 1024 * 1024;
|
|
20
|
+
const HEAD_BYTES = 256 * 1024;
|
|
21
|
+
const DETAIL_MAX = 90;
|
|
22
|
+
const MAX_PENDING = 64;
|
|
23
|
+
const MAX_TIMELINE = 300;
|
|
24
|
+
const MAX_SUBAGENTS = 50;
|
|
25
|
+
const MAX_TASKS = 100;
|
|
26
|
+
const MAX_TEXTS = 200;
|
|
27
|
+
const TEXT_MAX = 400;
|
|
28
|
+
/** 세션 시작 시각이 워커 시작보다 이만큼 앞서도 그 워커 세션으로 본다. 시계 차이와 띄우는 순서 몫이다 */
|
|
29
|
+
const START_SLACK_MS = 5 * 60_000;
|
|
30
|
+
const LIVE_TASK = new Set(['pending', 'in_progress', 'completed']);
|
|
31
|
+
export function emptyDigest(keepText = false) {
|
|
32
|
+
return {
|
|
33
|
+
activity: null,
|
|
34
|
+
tasks: null,
|
|
35
|
+
subagents: [],
|
|
36
|
+
timeline: [],
|
|
37
|
+
...(keepText ? { texts: [] } : {}),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* 트랜스크립트를 찾을 설정 디렉토리들. `CLAUDE_CONFIG_DIR`이 있으면 먼저 보고 `~/.claude`도 본다.
|
|
42
|
+
* 오르카 프로필은 `projects`를 `~/.claude/projects`로 심링크해 두는 경우가 많아 실제 경로로 겹침을 걷는다
|
|
43
|
+
*/
|
|
44
|
+
export function projectRoots(env = process.env, home = homedir()) {
|
|
45
|
+
const dirs = [env['CLAUDE_CONFIG_DIR'], join(home, '.claude')]
|
|
46
|
+
.filter((d) => typeof d === 'string' && isAbsolute(d))
|
|
47
|
+
.map((d) => join(d, 'projects'));
|
|
48
|
+
const seen = new Set();
|
|
49
|
+
const out = [];
|
|
50
|
+
for (const d of dirs) {
|
|
51
|
+
let key;
|
|
52
|
+
try {
|
|
53
|
+
key = realpathSync(d);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (seen.has(key))
|
|
59
|
+
continue;
|
|
60
|
+
seen.add(key);
|
|
61
|
+
out.push(d);
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
/** 저장해 둔 커서 경로를 다시 쓸 때 본다. 워크트리의 projects 디렉토리 바로 아래 세션 파일만 받는다 */
|
|
66
|
+
export function isWorkerTranscriptPath(file, cwd, roots = projectRoots()) {
|
|
67
|
+
const name = basename(file);
|
|
68
|
+
if (!name.endsWith('.jsonl') || !isSessionId(name.slice(0, -'.jsonl'.length)))
|
|
69
|
+
return false;
|
|
70
|
+
const dir = dirname(file);
|
|
71
|
+
return roots.some((r) => join(r, cwdSlug(cwd)) === dir);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* 워커 세션 트랜스크립트를 고른다. 세션 id가 있으면 그 파일을, 없으면 워크트리 디렉토리에서 세션이
|
|
75
|
+
* 워커 시작 뒤(5분 여유)와 종료 앞에 시작한 파일 중 가장 최근에 바뀐 것을 고른다. 못 찾으면 undefined
|
|
76
|
+
*/
|
|
77
|
+
export function locateWorkerTranscript(opts) {
|
|
78
|
+
const roots = opts.roots ?? projectRoots();
|
|
79
|
+
const dirs = roots.map((r) => join(r, cwdSlug(opts.cwd)));
|
|
80
|
+
if (opts.sessionId && isSessionId(opts.sessionId)) {
|
|
81
|
+
for (const d of dirs) {
|
|
82
|
+
const f = join(d, `${opts.sessionId}.jsonl`);
|
|
83
|
+
if (isFile(f))
|
|
84
|
+
return f;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const startMs = Date.parse(opts.startedAt);
|
|
88
|
+
if (Number.isNaN(startMs))
|
|
89
|
+
return undefined;
|
|
90
|
+
const endMs = opts.endedAt ? Date.parse(opts.endedAt) : Number.POSITIVE_INFINITY;
|
|
91
|
+
let best;
|
|
92
|
+
for (const d of dirs) {
|
|
93
|
+
let names;
|
|
94
|
+
try {
|
|
95
|
+
names = readdirSync(d);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
for (const name of names) {
|
|
101
|
+
if (!name.endsWith('.jsonl'))
|
|
102
|
+
continue;
|
|
103
|
+
const file = join(d, name);
|
|
104
|
+
let st;
|
|
105
|
+
try {
|
|
106
|
+
st = statSync(file);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (!st.isFile())
|
|
112
|
+
continue;
|
|
113
|
+
const mtime = st.mtimeMs;
|
|
114
|
+
if (mtime < startMs - START_SLACK_MS)
|
|
115
|
+
continue;
|
|
116
|
+
const began = sessionStartMs(file, st.size);
|
|
117
|
+
if (began === undefined || began < startMs - START_SLACK_MS || began >= endMs)
|
|
118
|
+
continue;
|
|
119
|
+
// 끝이 정해진 회차는 다음 회차 세션이 일찍 떠 후보에 섞일 수 있어 시작 기록에 가장 가까운 세션을 고른다
|
|
120
|
+
const gap = Math.abs(began - startMs);
|
|
121
|
+
const better = opts.endedAt ? !best || gap < best.gap : !best || mtime > best.mtime;
|
|
122
|
+
if (better)
|
|
123
|
+
best = { file, mtime, gap };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return best?.file;
|
|
127
|
+
}
|
|
128
|
+
/** 세션 첫 줄은 안 바뀌어서 한 번 읽은 시작 시각을 경로로 기억한다. tick과 browse가 후보마다 앞부분을 다시 읽지 않게 한다 */
|
|
129
|
+
const startCache = new Map();
|
|
130
|
+
const START_CACHE_MAX = 512;
|
|
131
|
+
function sessionStartMs(file, size) {
|
|
132
|
+
const hit = startCache.get(file);
|
|
133
|
+
if (hit !== undefined)
|
|
134
|
+
return Number.isNaN(hit) ? undefined : hit;
|
|
135
|
+
const v = readSessionStartMs(file);
|
|
136
|
+
if (v === null)
|
|
137
|
+
return undefined;
|
|
138
|
+
// 앞부분을 다 채운 파일은 뒤에 더 써도 시각이 안 생기니 없다는 것도 기억한다. NaN이 그 표시다
|
|
139
|
+
if (v !== undefined || size >= HEAD_BYTES) {
|
|
140
|
+
startCache.set(file, v ?? Number.NaN);
|
|
141
|
+
evictOldest(startCache, START_CACHE_MAX);
|
|
142
|
+
}
|
|
143
|
+
return v;
|
|
144
|
+
}
|
|
145
|
+
/** 크기 상한을 넘으면 먼저 넣은 것부터 지운다 */
|
|
146
|
+
export function evictOldest(items, max) {
|
|
147
|
+
while (items.size > max)
|
|
148
|
+
items.delete(items.keys().next().value);
|
|
149
|
+
}
|
|
150
|
+
/** 파일 앞부분에서 시각이 있는 첫 줄의 시각. 못 읽었으면 null */
|
|
151
|
+
function readSessionStartMs(file) {
|
|
152
|
+
let head;
|
|
153
|
+
try {
|
|
154
|
+
head = readRange(file, 0, HEAD_BYTES);
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
const lines = head.split('\n');
|
|
160
|
+
// 끝 줄은 잘렸을 수 있다
|
|
161
|
+
for (const line of lines.slice(0, -1)) {
|
|
162
|
+
if (!line.includes('"timestamp"'))
|
|
163
|
+
continue;
|
|
164
|
+
const row = parse(line);
|
|
165
|
+
const t = typeof row?.['timestamp'] === 'string' ? Date.parse(row['timestamp']) : Number.NaN;
|
|
166
|
+
if (!Number.isNaN(t))
|
|
167
|
+
return t;
|
|
168
|
+
}
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* 새로 붙은 줄을 읽어 상태를 갱신한다. 앞 상태가 다른 파일이거나 파일이 줄었으면 처음부터 다시 쌓는다.
|
|
173
|
+
* 쓰다 만 마지막 줄은 다음에 통째로 읽는다. 파일을 못 읽으면 던진다
|
|
174
|
+
*/
|
|
175
|
+
export function readTranscript(file, prev, opts = {}) {
|
|
176
|
+
const limit = opts.readLimit ?? READ_LIMIT;
|
|
177
|
+
let state = prev && prev.cursor.file === file
|
|
178
|
+
? prev
|
|
179
|
+
: {
|
|
180
|
+
cursor: { file, offset: 0, partial: false, pending: {} },
|
|
181
|
+
digest: emptyDigest(opts.keepText),
|
|
182
|
+
};
|
|
183
|
+
const fd = openSync(file, 'r');
|
|
184
|
+
try {
|
|
185
|
+
const size = fstatSync(fd).size;
|
|
186
|
+
if (size < state.cursor.offset)
|
|
187
|
+
state = {
|
|
188
|
+
cursor: { file, offset: 0, partial: false, pending: {} },
|
|
189
|
+
digest: emptyDigest(opts.keepText),
|
|
190
|
+
};
|
|
191
|
+
if (size === state.cursor.offset)
|
|
192
|
+
return state;
|
|
193
|
+
let start = state.cursor.offset;
|
|
194
|
+
let dropFirst = false;
|
|
195
|
+
const cursor = { ...state.cursor, pending: { ...state.cursor.pending } };
|
|
196
|
+
if (size - start > limit) {
|
|
197
|
+
start = size - limit;
|
|
198
|
+
dropFirst = true;
|
|
199
|
+
cursor.partial = true;
|
|
200
|
+
}
|
|
201
|
+
const buf = Buffer.alloc(size - start);
|
|
202
|
+
readSync(fd, buf, 0, buf.length, start);
|
|
203
|
+
const last = buf.lastIndexOf(10);
|
|
204
|
+
if (last < 0)
|
|
205
|
+
return state;
|
|
206
|
+
const first = dropFirst ? buf.indexOf(10) + 1 : 0;
|
|
207
|
+
cursor.offset = start + last + 1;
|
|
208
|
+
const digest = cloneDigest(state.digest);
|
|
209
|
+
const ctx = { cursor, digest, cwd: opts.cwd, keepText: opts.keepText === true };
|
|
210
|
+
for (const line of buf.toString('utf-8', first, last + 1).split('\n')) {
|
|
211
|
+
if (!line)
|
|
212
|
+
continue;
|
|
213
|
+
const row = parse(line);
|
|
214
|
+
if (row)
|
|
215
|
+
applyRow(row, ctx);
|
|
216
|
+
}
|
|
217
|
+
return { cursor, digest };
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
closeSync(fd);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function cloneDigest(d) {
|
|
224
|
+
return {
|
|
225
|
+
activity: d.activity,
|
|
226
|
+
tasks: d.tasks ? [...d.tasks] : null,
|
|
227
|
+
subagents: d.subagents.map((s) => ({ ...s })),
|
|
228
|
+
timeline: d.timeline.map((t) => ({ ...t })),
|
|
229
|
+
...(d.lastEventAt ? { lastEventAt: d.lastEventAt } : {}),
|
|
230
|
+
...(d.backgroundGate ? { backgroundGate: { ...d.backgroundGate } } : {}),
|
|
231
|
+
...(d.texts ? { texts: [...d.texts] } : {}),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
const INTERRUPTED = /^\[Request interrupted by user/;
|
|
235
|
+
const NOT_A_TURN = /^<(local-command-[a-z]+|command-name|command-message)>/;
|
|
236
|
+
const NOTIFICATION = '<task-notification>';
|
|
237
|
+
const FINISHED = /<status>(?:completed|failed|killed)<\/status>/;
|
|
238
|
+
const NOTIFIED_CALL = /<tool-use-id>([^<]+)<\/tool-use-id>/;
|
|
239
|
+
const LAUNCH_TEXT = /async agent launched|teammate|^\s*spawned/i;
|
|
240
|
+
const GATE_COMMAND = /\bgate\b/;
|
|
241
|
+
function parse(line) {
|
|
242
|
+
try {
|
|
243
|
+
const v = JSON.parse(line);
|
|
244
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
return undefined;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const record = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
|
|
251
|
+
export function clean(v, max = DETAIL_MAX) {
|
|
252
|
+
return typeof v === 'string'
|
|
253
|
+
? v
|
|
254
|
+
// eslint-disable-next-line no-control-regex -- 화면에 그릴 값에서 제어 문자를 지우는 게 이 정규식의 일이다
|
|
255
|
+
.replace(/[\x00-\x1f\x7f]+/g, ' ')
|
|
256
|
+
.replace(/\s+/g, ' ')
|
|
257
|
+
.trim()
|
|
258
|
+
.slice(0, max)
|
|
259
|
+
: '';
|
|
260
|
+
}
|
|
261
|
+
function applyRow(row, ctx) {
|
|
262
|
+
if (row['isSidechain'] === true)
|
|
263
|
+
return;
|
|
264
|
+
const at = typeof row['timestamp'] === 'string' ? row['timestamp'] : undefined;
|
|
265
|
+
if (!at || Number.isNaN(Date.parse(at)))
|
|
266
|
+
return;
|
|
267
|
+
const type = row['type'];
|
|
268
|
+
if (type === 'system') {
|
|
269
|
+
if (row['subtype'] === 'turn_duration')
|
|
270
|
+
endTurn(at, ctx);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
const message = record(row['message']);
|
|
274
|
+
const content = message?.['content'];
|
|
275
|
+
if (type === 'assistant') {
|
|
276
|
+
ctx.digest.lastEventAt = at;
|
|
277
|
+
const blocks = Array.isArray(content) ? content.map(record).filter(Boolean) : [];
|
|
278
|
+
for (const b of blocks) {
|
|
279
|
+
if (b['type'] === 'tool_use' && typeof b['id'] === 'string')
|
|
280
|
+
startCall(b, at, ctx);
|
|
281
|
+
else if (ctx.keepText && b['type'] === 'text')
|
|
282
|
+
pushText(ctx.digest, at, b['text']);
|
|
283
|
+
}
|
|
284
|
+
if (message?.['stop_reason'] === 'end_turn')
|
|
285
|
+
endTurn(at, ctx);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (type !== 'user' || row['isMeta'] === true || row['isCompactSummary'] === true)
|
|
289
|
+
return;
|
|
290
|
+
ctx.digest.lastEventAt = at;
|
|
291
|
+
const blocks = Array.isArray(content) ? content.map(record).filter(Boolean) : [];
|
|
292
|
+
const results = blocks.filter((b) => b['type'] === 'tool_result');
|
|
293
|
+
if (results.length > 0) {
|
|
294
|
+
const structured = results.length === 1 ? record(row['toolUseResult']) : undefined;
|
|
295
|
+
for (const b of results)
|
|
296
|
+
finishCall(b, structured, at, ctx);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
const text = (typeof content === 'string'
|
|
300
|
+
? content
|
|
301
|
+
: blocks.map((b) => (typeof b['text'] === 'string' ? b['text'] : '')).join('\n')).trimStart();
|
|
302
|
+
if (!text)
|
|
303
|
+
return;
|
|
304
|
+
if (INTERRUPTED.test(text))
|
|
305
|
+
return endTurn(at, ctx);
|
|
306
|
+
if (NOT_A_TURN.test(text))
|
|
307
|
+
return;
|
|
308
|
+
turnStart(ctx);
|
|
309
|
+
if (text.includes(NOTIFICATION) && FINISHED.test(text)) {
|
|
310
|
+
const id = NOTIFIED_CALL.exec(text)?.[1];
|
|
311
|
+
if (id)
|
|
312
|
+
finishSubagent(ctx.digest, id, at);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
function turnStart(ctx) {
|
|
316
|
+
// 턴이 끝난 뒤 새 턴이 왔으면 백그라운드 gate 뒤에 멈춘 게 아니다
|
|
317
|
+
if (ctx.digest.backgroundGate?.turnEndedAt)
|
|
318
|
+
delete ctx.digest.backgroundGate;
|
|
319
|
+
}
|
|
320
|
+
function endTurn(at, ctx) {
|
|
321
|
+
ctx.cursor.pending = {};
|
|
322
|
+
const bg = ctx.digest.backgroundGate;
|
|
323
|
+
if (bg && !bg.turnEndedAt)
|
|
324
|
+
bg.turnEndedAt = at;
|
|
325
|
+
}
|
|
326
|
+
function toolDetail(input, cwd) {
|
|
327
|
+
const p = input['file_path'] ?? input['notebook_path'];
|
|
328
|
+
const path = typeof p === 'string' ? shortPath(p, cwd) : '';
|
|
329
|
+
// 명령 원문보다 사람이 붙인 설명이 짧고 덜 새어 나가서 먼저 쓴다
|
|
330
|
+
const d = (path || undefined) ??
|
|
331
|
+
input['description'] ??
|
|
332
|
+
input['command'] ??
|
|
333
|
+
input['pattern'] ??
|
|
334
|
+
input['url'] ??
|
|
335
|
+
input['query'] ??
|
|
336
|
+
input['skill'] ??
|
|
337
|
+
'';
|
|
338
|
+
// 자른 뒤에 가리면 잘린 토큰이 패턴에 안 걸려 그대로 남는다
|
|
339
|
+
return clean(typeof d === 'string' ? maskSecrets(d).text : d);
|
|
340
|
+
}
|
|
341
|
+
function shortPath(p, cwd) {
|
|
342
|
+
if (!cwd || !isAbsolute(p))
|
|
343
|
+
return p;
|
|
344
|
+
const rel = relative(cwd, p);
|
|
345
|
+
return rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel : p;
|
|
346
|
+
}
|
|
347
|
+
function startCall(block, at, ctx) {
|
|
348
|
+
const id = block['id'];
|
|
349
|
+
if (ctx.cursor.pending[id] || ctx.digest.timeline.some((t) => t.id === id))
|
|
350
|
+
return;
|
|
351
|
+
const input = record(block['input']) ?? {};
|
|
352
|
+
// 바깥에서 온 이름이라 표 이름과 견줄 때만 그대로 쓰고 저장은 줄여서 한다
|
|
353
|
+
const rawName = typeof block['name'] === 'string' ? block['name'] : '';
|
|
354
|
+
const tool = clean(rawName, 60) || 'tool';
|
|
355
|
+
const detail = toolDetail(input, ctx.cwd);
|
|
356
|
+
const call = { tool, at, detail };
|
|
357
|
+
const filePath = input['file_path'] ?? input['notebook_path'];
|
|
358
|
+
if (WRITE_TOOLS.has(rawName) && typeof filePath === 'string')
|
|
359
|
+
call.file = shortPath(filePath, ctx.cwd);
|
|
360
|
+
if (TASK_TOOLS.has(rawName) || TODO_TOOLS.has(rawName))
|
|
361
|
+
call.task = taskInput(input);
|
|
362
|
+
if (SUBAGENT_TOOLS.has(rawName)) {
|
|
363
|
+
call.subagent = true;
|
|
364
|
+
pushBounded(ctx.digest.subagents, {
|
|
365
|
+
id,
|
|
366
|
+
name: clean(input['description'] ?? input['name'] ?? input['subagent_type'], 60) || 'sub-agent',
|
|
367
|
+
startedAt: at,
|
|
368
|
+
state: 'running',
|
|
369
|
+
}, MAX_SUBAGENTS);
|
|
370
|
+
}
|
|
371
|
+
if (SHELL_TOOLS.has(rawName) &&
|
|
372
|
+
input['run_in_background'] === true &&
|
|
373
|
+
typeof input['command'] === 'string' &&
|
|
374
|
+
GATE_COMMAND.test(input['command']))
|
|
375
|
+
ctx.digest.backgroundGate = { at };
|
|
376
|
+
else if (ctx.digest.backgroundGate?.turnEndedAt)
|
|
377
|
+
delete ctx.digest.backgroundGate;
|
|
378
|
+
hold(ctx.cursor, id, call);
|
|
379
|
+
pushBounded(ctx.digest.timeline, { id, at, tool, detail }, MAX_TIMELINE);
|
|
380
|
+
ctx.digest.activity = { tool, ...(call.file ? { file: call.file } : {}), at };
|
|
381
|
+
}
|
|
382
|
+
function hold(cursor, id, call) {
|
|
383
|
+
cursor.pending[id] = call;
|
|
384
|
+
const ids = Object.keys(cursor.pending);
|
|
385
|
+
if (ids.length > MAX_PENDING)
|
|
386
|
+
delete cursor.pending[ids[0]];
|
|
387
|
+
}
|
|
388
|
+
function pushBounded(list, item, max) {
|
|
389
|
+
list.push(item);
|
|
390
|
+
if (list.length > max)
|
|
391
|
+
list.splice(0, list.length - max);
|
|
392
|
+
}
|
|
393
|
+
function pushText(digest, at, text) {
|
|
394
|
+
// 본문에 붙여 넣은 토큰도 작업 내용 탭으로 나가서 도구 인자처럼 자르기 전에 가린다
|
|
395
|
+
const t = clean(typeof text === 'string' ? maskSecrets(text).text : text, TEXT_MAX);
|
|
396
|
+
if (!t)
|
|
397
|
+
return;
|
|
398
|
+
pushBounded((digest.texts ??= []), { at, text: t }, MAX_TEXTS);
|
|
399
|
+
}
|
|
400
|
+
function blockText(content) {
|
|
401
|
+
if (typeof content === 'string')
|
|
402
|
+
return content;
|
|
403
|
+
if (!Array.isArray(content))
|
|
404
|
+
return '';
|
|
405
|
+
return content
|
|
406
|
+
.map((b) => {
|
|
407
|
+
const r = record(b);
|
|
408
|
+
return typeof r?.['text'] === 'string' ? r['text'] : '';
|
|
409
|
+
})
|
|
410
|
+
.join('\n');
|
|
411
|
+
}
|
|
412
|
+
function finishCall(block, structured, at, ctx) {
|
|
413
|
+
const id = block['tool_use_id'];
|
|
414
|
+
if (typeof id !== 'string')
|
|
415
|
+
return;
|
|
416
|
+
const call = ctx.cursor.pending[id];
|
|
417
|
+
// 시작이 읽은 범위 밖이면 아무것도 모른다
|
|
418
|
+
if (!call)
|
|
419
|
+
return;
|
|
420
|
+
delete ctx.cursor.pending[id];
|
|
421
|
+
const error = block['is_error'] === true;
|
|
422
|
+
const event = ctx.digest.timeline.find((t) => t.id === id);
|
|
423
|
+
if (event) {
|
|
424
|
+
event.ok = !error;
|
|
425
|
+
const ms = Date.parse(at) - Date.parse(call.at);
|
|
426
|
+
if (Number.isFinite(ms))
|
|
427
|
+
event.ms = Math.max(0, ms);
|
|
428
|
+
}
|
|
429
|
+
if (call.subagent) {
|
|
430
|
+
const s = ctx.digest.subagents.find((x) => x.id === id);
|
|
431
|
+
if (s && s.state === 'running') {
|
|
432
|
+
if (!error && wasLaunched(structured, block))
|
|
433
|
+
s.state = 'detached';
|
|
434
|
+
else {
|
|
435
|
+
s.state = 'done';
|
|
436
|
+
s.endedAt = at;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
if (call.task && !error) {
|
|
441
|
+
const effect = taskEffect(call.tool, call.task, structured ?? block['content']);
|
|
442
|
+
if (effect) {
|
|
443
|
+
const next = applyTaskEffect(ctx.digest.tasks ?? [], effect);
|
|
444
|
+
if (next)
|
|
445
|
+
ctx.digest.tasks = next;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
function wasLaunched(structured, block) {
|
|
450
|
+
const status = structured?.['status'];
|
|
451
|
+
if (typeof status === 'string')
|
|
452
|
+
return LAUNCHED_STATUSES.has(status);
|
|
453
|
+
return LAUNCH_TEXT.test(blockText(block['content']).slice(0, 200));
|
|
454
|
+
}
|
|
455
|
+
function finishSubagent(digest, id, at) {
|
|
456
|
+
const s = digest.subagents.find((x) => x.id === id);
|
|
457
|
+
if (s && s.state !== 'done') {
|
|
458
|
+
s.state = 'done';
|
|
459
|
+
s.endedAt = at;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
const CREATED = /^Task #(\d+) created successfully: ([^\r\n]+)$/;
|
|
463
|
+
const UPDATED = /^Updated task #(\d+) ((?:owner|status|subject|description|activeForm|metadata|blocks|blockedBy|deleted)(?:, (?:owner|status|subject|description|activeForm|metadata|blocks|blockedBy|deleted))*)$/;
|
|
464
|
+
function taskId(v) {
|
|
465
|
+
return typeof v === 'string' || typeof v === 'number' ? clean(String(v), 100) : '';
|
|
466
|
+
}
|
|
467
|
+
/** Claude의 {content|subject}와 Codex의 {step}을 받는다. 상태를 모르는 항목은 뺀다 */
|
|
468
|
+
export function taskList(items) {
|
|
469
|
+
if (!Array.isArray(items))
|
|
470
|
+
return null;
|
|
471
|
+
const out = [];
|
|
472
|
+
for (const raw of items.slice(0, MAX_TASKS)) {
|
|
473
|
+
const t = record(raw);
|
|
474
|
+
if (!t)
|
|
475
|
+
continue;
|
|
476
|
+
const title = clean(t['content'] ?? t['step'] ?? t['subject'] ?? t['title'], 180);
|
|
477
|
+
const status = t['status'];
|
|
478
|
+
if (!title || typeof status !== 'string' || !LIVE_TASK.has(status))
|
|
479
|
+
continue;
|
|
480
|
+
const id = taskId(t['id']);
|
|
481
|
+
out.push({ ...(id ? { id } : {}), title, status: status });
|
|
482
|
+
}
|
|
483
|
+
return out;
|
|
484
|
+
}
|
|
485
|
+
function taskInput(input) {
|
|
486
|
+
const todos = taskList(input['todos']);
|
|
487
|
+
return {
|
|
488
|
+
...(taskId(input['taskId']) ? { taskId: taskId(input['taskId']) } : {}),
|
|
489
|
+
...(clean(input['subject'], 180) ? { subject: clean(input['subject'], 180) } : {}),
|
|
490
|
+
...(typeof input['status'] === 'string' ? { status: input['status'] } : {}),
|
|
491
|
+
...(input['merge'] === true ? { merge: true } : {}),
|
|
492
|
+
...(todos ? { todos } : {}),
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
const reportsFailure = (r) => {
|
|
496
|
+
const o = record(r);
|
|
497
|
+
return (!!o &&
|
|
498
|
+
(o['is_error'] === true || o['isError'] === true || !!o['error'] || o['success'] === false));
|
|
499
|
+
};
|
|
500
|
+
/** 결과 꼴을 { failed } / { value } / { text } / {} 중 하나로 줄인다 */
|
|
501
|
+
function readResponse(response) {
|
|
502
|
+
if (response === undefined || response === null)
|
|
503
|
+
return {};
|
|
504
|
+
if (reportsFailure(response))
|
|
505
|
+
return { failed: true };
|
|
506
|
+
let r = response;
|
|
507
|
+
if (Array.isArray(r)) {
|
|
508
|
+
const only = r.length === 1 ? record(r[0]) : undefined;
|
|
509
|
+
r = only?.['type'] === 'text' ? only['text'] : null;
|
|
510
|
+
}
|
|
511
|
+
else if (record(r) && 'content' in r) {
|
|
512
|
+
const c = r['content'];
|
|
513
|
+
if (Array.isArray(c)) {
|
|
514
|
+
const only = c.length === 1 ? record(c[0]) : undefined;
|
|
515
|
+
r = only?.['type'] === 'text' ? only['text'] : null;
|
|
516
|
+
}
|
|
517
|
+
else
|
|
518
|
+
r = c;
|
|
519
|
+
}
|
|
520
|
+
if (typeof r === 'string') {
|
|
521
|
+
const text = r.trim();
|
|
522
|
+
const parsed = parse(text);
|
|
523
|
+
if (parsed)
|
|
524
|
+
return reportsFailure(parsed) ? { failed: true } : { value: parsed };
|
|
525
|
+
return { text };
|
|
526
|
+
}
|
|
527
|
+
const obj = record(r);
|
|
528
|
+
return obj ? { value: obj } : {};
|
|
529
|
+
}
|
|
530
|
+
function knownChange(id, title, status) {
|
|
531
|
+
const statusKnown = typeof status === 'string' && (LIVE_TASK.has(status) || status === 'deleted');
|
|
532
|
+
if (!statusKnown && !title)
|
|
533
|
+
return null;
|
|
534
|
+
return {
|
|
535
|
+
change: {
|
|
536
|
+
id,
|
|
537
|
+
...(title ? { title } : {}),
|
|
538
|
+
...(statusKnown ? { status: status } : {}),
|
|
539
|
+
},
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
function taskEffect(tool, input, response) {
|
|
543
|
+
const result = readResponse(response);
|
|
544
|
+
if (result.failed)
|
|
545
|
+
return null;
|
|
546
|
+
if (TODO_TOOLS.has(tool)) {
|
|
547
|
+
const newTodos = result.value?.['newTodos'];
|
|
548
|
+
const ok = Array.isArray(newTodos) || /modified successfully/i.test(result.text ?? '');
|
|
549
|
+
const list = ok ? (Array.isArray(newTodos) ? taskList(newTodos) : (input.todos ?? null)) : null;
|
|
550
|
+
return list ? { replace: list, ...(input.merge ? { partial: true } : {}) } : null;
|
|
551
|
+
}
|
|
552
|
+
if (result.text === undefined && result.value === undefined)
|
|
553
|
+
return null;
|
|
554
|
+
const task = record(result.value?.['task']);
|
|
555
|
+
if (tool === 'TaskList') {
|
|
556
|
+
const list = taskList(result.value?.['tasks']);
|
|
557
|
+
return list ? { replace: list } : null;
|
|
558
|
+
}
|
|
559
|
+
if (tool === 'TaskCreate') {
|
|
560
|
+
if (result.text !== undefined) {
|
|
561
|
+
const m = CREATED.exec(result.text);
|
|
562
|
+
const title = input.subject || clean(m?.[2], 180);
|
|
563
|
+
return m && title ? { change: { id: m[1], title, status: 'pending' } } : null;
|
|
564
|
+
}
|
|
565
|
+
const id = taskId(task?.['id']);
|
|
566
|
+
const title = clean(task?.['subject'], 180) || input.subject || '';
|
|
567
|
+
if (!id || !title)
|
|
568
|
+
return null;
|
|
569
|
+
const st = task?.['status'];
|
|
570
|
+
return {
|
|
571
|
+
change: {
|
|
572
|
+
id,
|
|
573
|
+
title,
|
|
574
|
+
status: typeof st === 'string' && LIVE_TASK.has(st) ? st : 'pending',
|
|
575
|
+
},
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
if (tool === 'TaskUpdate') {
|
|
579
|
+
const wanted = input.taskId ?? '';
|
|
580
|
+
if (result.text !== undefined) {
|
|
581
|
+
const m = UPDATED.exec(result.text);
|
|
582
|
+
if (!m || (wanted && m[1] !== wanted))
|
|
583
|
+
return null;
|
|
584
|
+
const fields = m[2].split(', ');
|
|
585
|
+
const status = fields.includes('status') || fields.includes('deleted') ? input.status : undefined;
|
|
586
|
+
return knownChange(m[1], fields.includes('subject') ? (input.subject ?? '') : '', status);
|
|
587
|
+
}
|
|
588
|
+
if (task) {
|
|
589
|
+
const id = taskId(task['id']) || wanted;
|
|
590
|
+
if (!id || (wanted && id !== wanted))
|
|
591
|
+
return null;
|
|
592
|
+
return knownChange(id, clean(task['subject'], 180), task['status']);
|
|
593
|
+
}
|
|
594
|
+
if (result.value?.['success'] === true) {
|
|
595
|
+
const id = taskId(result.value['taskId']) || wanted;
|
|
596
|
+
if (!id || (wanted && id !== wanted))
|
|
597
|
+
return null;
|
|
598
|
+
const fields = Array.isArray(result.value['updatedFields'])
|
|
599
|
+
? result.value['updatedFields']
|
|
600
|
+
: [];
|
|
601
|
+
const change = record(result.value['statusChange']);
|
|
602
|
+
const status = change?.['to'] ??
|
|
603
|
+
(fields.includes('status') || fields.includes('deleted') ? input.status : undefined);
|
|
604
|
+
return knownChange(id, fields.includes('subject') ? (input.subject ?? '') : '', status);
|
|
605
|
+
}
|
|
606
|
+
return null;
|
|
607
|
+
}
|
|
608
|
+
// TaskGet
|
|
609
|
+
if (task)
|
|
610
|
+
return knownChange(taskId(task['id']), clean(task['subject'], 180), task['status']);
|
|
611
|
+
return null;
|
|
612
|
+
}
|
|
613
|
+
/** 효과를 반영한 다음 목록. 바뀐 게 없으면 null. 제목을 본 적 없는 항목의 상태는 버린다 */
|
|
614
|
+
function applyTaskEffect(todos, effect) {
|
|
615
|
+
if ('replace' in effect) {
|
|
616
|
+
if (!effect.partial)
|
|
617
|
+
return effect.replace;
|
|
618
|
+
const incoming = effect.replace.filter((t) => t.id);
|
|
619
|
+
const ids = new Set(incoming.map((t) => t.id));
|
|
620
|
+
return [...todos.filter((t) => !ids.has(t.id)), ...incoming];
|
|
621
|
+
}
|
|
622
|
+
const { id, title, status } = effect.change;
|
|
623
|
+
if (!id)
|
|
624
|
+
return null;
|
|
625
|
+
const prior = todos.find((t) => t.id === id);
|
|
626
|
+
if (status === 'deleted')
|
|
627
|
+
return prior ? todos.filter((t) => t !== prior) : null;
|
|
628
|
+
if (prior)
|
|
629
|
+
return todos.map((t) => t === prior ? { ...t, ...(title ? { title } : {}), ...(status ? { status } : {}) } : t);
|
|
630
|
+
return title && status && todos.length < MAX_TASKS ? [...todos, { id, title, status }] : null;
|
|
631
|
+
}
|
|
632
|
+
function isFile(p) {
|
|
633
|
+
try {
|
|
634
|
+
return statSync(p).isFile();
|
|
635
|
+
}
|
|
636
|
+
catch {
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
function readRange(file, start, length) {
|
|
641
|
+
const fd = openSync(file, 'r');
|
|
642
|
+
try {
|
|
643
|
+
const buf = Buffer.alloc(length);
|
|
644
|
+
const n = readSync(fd, buf, 0, length, start);
|
|
645
|
+
return buf.toString('utf-8', 0, n);
|
|
646
|
+
}
|
|
647
|
+
finally {
|
|
648
|
+
closeSync(fd);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
export function transcriptExists(file) {
|
|
652
|
+
return !!file && existsSync(file);
|
|
653
|
+
}
|
|
654
|
+
//# sourceMappingURL=transcript.js.map
|