gcf-board 0.5.1 → 0.6.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/README.md +8 -8
- package/dist/server/app.js +161 -20
- package/dist/server/chat.js +13 -0
- package/dist/server/files.js +5 -2
- package/dist/server/mcp.js +28 -0
- package/dist/server/moves.js +11 -0
- package/dist/server/propose.js +96 -0
- package/dist/server/runs.js +23 -115
- package/dist/server/talks.js +498 -0
- package/dist/web/assets/index-D_F7OEyk.js +36 -0
- package/dist/web/index.html +1 -1
- package/node_modules/gcf-session/lib/activity.js +371 -0
- package/node_modules/gcf-session/lib/adapter/claude.js +226 -0
- package/node_modules/gcf-session/lib/adapter/index.js +33 -0
- package/node_modules/gcf-session/lib/chat-input.js +260 -0
- package/node_modules/gcf-session/lib/chat.js +832 -0
- package/node_modules/gcf-session/lib/cli.js +52 -0
- package/node_modules/gcf-session/lib/cost.js +29 -0
- package/node_modules/gcf-session/lib/index.js +58 -0
- package/node_modules/gcf-session/lib/job.js +417 -0
- package/node_modules/gcf-session/lib/limit.js +132 -0
- package/node_modules/gcf-session/lib/lock.js +81 -0
- package/node_modules/gcf-session/lib/proc.js +93 -0
- package/node_modules/gcf-session/lib/session.js +320 -0
- package/node_modules/gcf-session/lib/store.js +28 -0
- package/node_modules/gcf-session/lib/thread.js +423 -0
- package/node_modules/gcf-session/lib/windows.js +46 -0
- package/node_modules/gcf-session/package.json +23 -0
- package/node_modules/gcf-session/types/index.d.ts +152 -0
- package/package.json +10 -3
- package/dist/web/assets/index-DpzFCrLV.js +0 -36
package/dist/web/index.html
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>GCF board</title>
|
|
7
|
-
<script type="module" crossorigin src="/assets/index-
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-D_F7OEyk.js"></script>
|
|
8
8
|
<link rel="stylesheet" crossorigin href="/assets/index-BYAEKw51.css">
|
|
9
9
|
</head>
|
|
10
10
|
<body>
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// The live log of an agent session: `claude -p --output-format stream-json` prints one JSON event
|
|
2
|
+
// per line, and the run log gets one readable line per event worth seeing, so an operator can tell
|
|
3
|
+
// a working session from a stuck one. A line that is not JSON is another agent's own output.
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {object} Cost What a session spent, from its `result` event.
|
|
7
|
+
* @property {number} cost_usd
|
|
8
|
+
* @property {{input: number, output: number, cache_read: number, cache_creation: number}} tokens
|
|
9
|
+
* @property {number} turns
|
|
10
|
+
* @property {number} duration_ms
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** `12:03:10`, the local time of day. */
|
|
14
|
+
export const clock = (now = new Date()) => now.toTimeString().slice(0, 8);
|
|
15
|
+
|
|
16
|
+
const cut = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
|
|
17
|
+
|
|
18
|
+
/** The first `n` non-empty lines of a text, trimmed, on one line. */
|
|
19
|
+
const firstLines = (text, n) =>
|
|
20
|
+
String(text)
|
|
21
|
+
.split('\n')
|
|
22
|
+
.map((l) => l.trim())
|
|
23
|
+
.filter(Boolean)
|
|
24
|
+
.slice(0, n)
|
|
25
|
+
.join(' ');
|
|
26
|
+
|
|
27
|
+
// The input field that tells most about a tool call, in this order; with none, the name alone.
|
|
28
|
+
const TELLING = ['file_path', 'command', 'pattern', 'url', 'description'];
|
|
29
|
+
|
|
30
|
+
function toolLine(use) {
|
|
31
|
+
const key = TELLING.find((k) => typeof use.input?.[k] === 'string');
|
|
32
|
+
|
|
33
|
+
return key ? `tool: ${use.name} ${cut(firstLines(use.input[key], 1), 120)}` : `tool: ${use.name}`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A tool result's text: a string, or a list of text blocks. */
|
|
37
|
+
const resultText = (content) =>
|
|
38
|
+
Array.isArray(content) ? content.map((c) => c?.text ?? '').join('\n') : String(content ?? '');
|
|
39
|
+
|
|
40
|
+
/** `1.2M`, `85k`, `950`: one decimal below ten of its unit. */
|
|
41
|
+
export const count = (n) =>
|
|
42
|
+
n >= 1e6 ? scaled(n / 1e6, 'M') : n >= 1e3 ? scaled(n / 1e3, 'k') : `${n}`;
|
|
43
|
+
const scaled = (v, unit) => `${v < 10 ? v.toFixed(1) : Math.round(v)}${unit}`;
|
|
44
|
+
|
|
45
|
+
/** `8s`, `34m`, `1h 12m`. */
|
|
46
|
+
function span(ms) {
|
|
47
|
+
const s = Math.round(ms / 1000);
|
|
48
|
+
if (s < 60) return `${s}s`;
|
|
49
|
+
const m = Math.round(s / 60);
|
|
50
|
+
|
|
51
|
+
return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @returns {Cost} */
|
|
55
|
+
function costOf(e) {
|
|
56
|
+
const u = e.usage ?? {};
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
cost_usd: Number(e.total_cost_usd ?? 0),
|
|
60
|
+
tokens: {
|
|
61
|
+
input: Number(u.input_tokens ?? 0),
|
|
62
|
+
output: Number(u.output_tokens ?? 0),
|
|
63
|
+
cache_read: Number(u.cache_read_input_tokens ?? 0),
|
|
64
|
+
cache_creation: Number(u.cache_creation_input_tokens ?? 0),
|
|
65
|
+
},
|
|
66
|
+
turns: Number(e.num_turns ?? 0),
|
|
67
|
+
duration_ms: Number(e.duration_ms ?? 0),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function summary(e, c, limited) {
|
|
72
|
+
// A limit ends with subtype `success`: name the limit, not that.
|
|
73
|
+
const end = limited
|
|
74
|
+
? 'ended (usage limit)'
|
|
75
|
+
: e.is_error
|
|
76
|
+
? `ended (${e.subtype ?? 'error'})`
|
|
77
|
+
: 'done';
|
|
78
|
+
const t = c.tokens;
|
|
79
|
+
|
|
80
|
+
return (
|
|
81
|
+
`${end} in ${span(c.duration_ms)}, ${c.turns} turns, $${c.cost_usd.toFixed(2)} ` +
|
|
82
|
+
`(in ${count(t.input)} / out ${count(t.output)} tokens, cache read ${count(t.cache_read)}, ` +
|
|
83
|
+
`cache write ${count(t.cache_creation)})`
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Claude's usage-limit ending, `You've hit your session limit · resets 3am (Europe/Berlin)`:
|
|
89
|
+
* `{limit: {resets}}`, the time it names (null without one), or nothing for any other text. An
|
|
90
|
+
* error result is the session's end, so the message anywhere in it counts; an agent's text or a
|
|
91
|
+
* plain line counts only when it is that message whole: prose about some other limit is not.
|
|
92
|
+
* @returns {{limit?: {resets: string | null}}}
|
|
93
|
+
*/
|
|
94
|
+
function limitIn(text, whole = true) {
|
|
95
|
+
const s = String(text ?? '').trim();
|
|
96
|
+
// shortcut: any "You've hit your … limit" counts, so an agent's whole-line "You've hit your WIP
|
|
97
|
+
// limit" would pause its item; narrow it once Claude's wordings (Opus, weekly…) are all known.
|
|
98
|
+
const hit = whole ? /^You['’]ve hit your [^\n]*limit[^\n]*$/i : /hit your .*limit/i;
|
|
99
|
+
if (!hit.test(s)) return {};
|
|
100
|
+
|
|
101
|
+
return { limit: { resets: s.match(/resets (.+)$/im)?.[1].trim() || null } };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* One stdout line of a session as log lines: an event worth seeing becomes one stamped line, the
|
|
106
|
+
* rest of the stream (hooks, init, thinking, rate limits) none; the `result` event gives the
|
|
107
|
+
* final text, a summary line and the cost. `session_id` comes with the init event, `limit` with
|
|
108
|
+
* the usage-limit message, in whatever form it arrives: the session can be resumed after either.
|
|
109
|
+
* @param {string} line
|
|
110
|
+
* The main agent's turns also carry `context`, the tokens its window holds (a subagent's turns,
|
|
111
|
+
* `parent_tool_use_id` set, fill a window of their own); the init names the `model`, the result
|
|
112
|
+
* the `windows` of its models, and a compaction says `compacted`. A tool result gives `failed`,
|
|
113
|
+
* the calls that came to nothing.
|
|
114
|
+
* `events` are the line's neutral events (`Neutral`).
|
|
115
|
+
* @returns {{lines: string[], events: Neutral[], cost?: Cost, session_id?: string,
|
|
116
|
+
* limit?: {resets: string | null},
|
|
117
|
+
* context?: number, turn?: string, model?: string, windows?: Record<string, number>,
|
|
118
|
+
* compacted?: boolean, failed?: string[], quota?: Record<string, unknown>}}
|
|
119
|
+
*/
|
|
120
|
+
export function activity(line, now = new Date()) {
|
|
121
|
+
let e;
|
|
122
|
+
try {
|
|
123
|
+
e = JSON.parse(line);
|
|
124
|
+
} catch {
|
|
125
|
+
return { lines: [line], events: [], ...limitIn(line) };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (typeof e?.type !== 'string') return { lines: [line], events: [] };
|
|
129
|
+
|
|
130
|
+
return { events: eventsOf(e), ...logged(e, now) };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** What one parsed event of the stream tells, but its neutral events (`eventsOf`). */
|
|
134
|
+
function logged(e, now) {
|
|
135
|
+
const at = `[${clock(now)}]`;
|
|
136
|
+
const content = Array.isArray(e.message?.content) ? e.message.content : [];
|
|
137
|
+
if (e.type === 'system') return system(e, at);
|
|
138
|
+
if (e.type === 'assistant') return { ...said(content, at), ...contextOf(e) };
|
|
139
|
+
if (e.type === 'user') {
|
|
140
|
+
const errors = content.filter((b) => b.type === 'tool_result' && b.is_error);
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
lines: errors.map(
|
|
144
|
+
(b) => `${at} tool error: ${cut(firstLines(resultText(b.content), 1), 300)}`,
|
|
145
|
+
),
|
|
146
|
+
// A refused or failed call wrote nothing: its write does not count.
|
|
147
|
+
...(errors.length ? { failed: errors.map((b) => String(b.tool_use_id)) } : {}),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (e.type === 'result') return ended(e, at);
|
|
152
|
+
|
|
153
|
+
return quotaOf(e);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// The neutral kind of each claude tool (docs/Session-Engine.md AD-4); any other is `other`.
|
|
157
|
+
const KINDS = {
|
|
158
|
+
Read: 'read',
|
|
159
|
+
Grep: 'search',
|
|
160
|
+
Glob: 'search',
|
|
161
|
+
LS: 'search',
|
|
162
|
+
Edit: 'edit',
|
|
163
|
+
Write: 'edit',
|
|
164
|
+
MultiEdit: 'edit',
|
|
165
|
+
NotebookEdit: 'edit',
|
|
166
|
+
Bash: 'shell',
|
|
167
|
+
PowerShell: 'shell',
|
|
168
|
+
WebFetch: 'web',
|
|
169
|
+
WebSearch: 'web',
|
|
170
|
+
Task: 'subagent',
|
|
171
|
+
Agent: 'subagent',
|
|
172
|
+
Skill: 'skill',
|
|
173
|
+
AskUserQuestion: 'question',
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
/** The neutral kind of a claude tool: an MCP tool is `mcp__<server>__<tool>`. */
|
|
177
|
+
export const kindOf = (tool) => KINDS[tool] ?? (/^mcp__/.test(tool) ? 'mcp' : 'other');
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* @typedef {{type: 'said', sub: boolean, text: string}
|
|
181
|
+
* | {type: 'tool_call', sub: boolean, id: string, kind: string, tool: string, input: any}
|
|
182
|
+
* | {type: 'tool_result', sub: boolean, id: string, error: boolean, text: string}
|
|
183
|
+
* | {type: 'read'}
|
|
184
|
+
* | {type: 'question', request_id: string, input: any}
|
|
185
|
+
* | {type: 'permission', request_id: string, tool: string, kind: string, input: any,
|
|
186
|
+
* title: string, reason: string | null, always: string | null}
|
|
187
|
+
* | {type: 'refused', tool: string, reason: string}
|
|
188
|
+
* | {type: 'cancel', request_id: string}
|
|
189
|
+
* | {type: 'result', subtype?: string, total_cost_usd: number | null}
|
|
190
|
+
* | {type: 'background', tasks: {id: string, description: string}[]}
|
|
191
|
+
* | {type: 'compacted'}} Neutral
|
|
192
|
+
* The events a session's work is read by, the same from any agent: what the main agent (or a
|
|
193
|
+
* subagent, `sub`) said and called, the results, the operator's messages it took in, the
|
|
194
|
+
* question and permission requests, a turn's end, the background tasks, a compaction.
|
|
195
|
+
*/
|
|
196
|
+
|
|
197
|
+
/** @returns {Neutral[]} */
|
|
198
|
+
function eventsOf(e) {
|
|
199
|
+
const sub = e.parent_tool_use_id != null;
|
|
200
|
+
const content = Array.isArray(e.message?.content) ? e.message.content : [];
|
|
201
|
+
if (e.type === 'assistant') {
|
|
202
|
+
const text = content.filter((b) => b.type === 'text').map((b) => b.text);
|
|
203
|
+
const calls = content.filter((b) => b.type === 'tool_use');
|
|
204
|
+
|
|
205
|
+
// The calls first: a step a call ends reads before the words that come with it.
|
|
206
|
+
return [
|
|
207
|
+
...calls.map((b) => ({
|
|
208
|
+
type: /** @type {const} */ ('tool_call'),
|
|
209
|
+
sub,
|
|
210
|
+
id: String(b.id),
|
|
211
|
+
kind: kindOf(b.name),
|
|
212
|
+
tool: String(b.name),
|
|
213
|
+
input: b.input ?? {},
|
|
214
|
+
})),
|
|
215
|
+
{ type: 'said', sub, text: text.join('\n') },
|
|
216
|
+
];
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (e.type === 'user') return userEvents(e, sub, content);
|
|
220
|
+
if (e.type === 'control_request') return requested(e);
|
|
221
|
+
if (e.type === 'control_cancel_request') return [{ type: 'cancel', request_id: e.request_id }];
|
|
222
|
+
if (e.type === 'result')
|
|
223
|
+
return [{ type: 'result', subtype: e.subtype, total_cost_usd: e.total_cost_usd ?? null }];
|
|
224
|
+
|
|
225
|
+
return e.type === 'system' ? systemEvents(e) : [];
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** A user event: a message echoed as read (`--replay-user-messages`), or tool results. */
|
|
229
|
+
function userEvents(e, sub, content) {
|
|
230
|
+
if (e.isReplay) return [{ type: /** @type {const} */ ('read') }];
|
|
231
|
+
|
|
232
|
+
return content
|
|
233
|
+
.filter((b) => b.type === 'tool_result')
|
|
234
|
+
.map((b) => ({
|
|
235
|
+
type: /** @type {const} */ ('tool_result'),
|
|
236
|
+
sub,
|
|
237
|
+
id: String(b.tool_use_id),
|
|
238
|
+
error: Boolean(b.is_error),
|
|
239
|
+
text: resultText(b.content),
|
|
240
|
+
}));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* A tool the agent asks to use: a question card, or a permission.
|
|
245
|
+
* @returns {Neutral[]}
|
|
246
|
+
*/
|
|
247
|
+
function requested(e) {
|
|
248
|
+
if (e.request?.subtype !== 'can_use_tool') return [];
|
|
249
|
+
const { tool_name: tool, input = {} } = e.request;
|
|
250
|
+
if (tool === 'AskUserQuestion') return [{ type: 'question', request_id: e.request_id, input }];
|
|
251
|
+
const title =
|
|
252
|
+
input.file_path ?? input.notebook_path ?? input.command ?? input.url ?? input.pattern ?? tool;
|
|
253
|
+
|
|
254
|
+
return [
|
|
255
|
+
{
|
|
256
|
+
type: 'permission',
|
|
257
|
+
request_id: e.request_id,
|
|
258
|
+
tool,
|
|
259
|
+
kind: kindOf(tool),
|
|
260
|
+
input,
|
|
261
|
+
title: String(title),
|
|
262
|
+
reason: typeof e.request.description === 'string' ? e.request.description : null,
|
|
263
|
+
always: alwaysOf(e.request.permission_suggestions),
|
|
264
|
+
},
|
|
265
|
+
];
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* The rule "always" would save (AD-2): claude's suggestion of an allow rule for the local
|
|
270
|
+
* settings, as `Tool(content)`; null for none, for a bare tool or a bare `*`: too wide.
|
|
271
|
+
*/
|
|
272
|
+
function alwaysOf(suggestions) {
|
|
273
|
+
const add = (Array.isArray(suggestions) ? suggestions : []).find(
|
|
274
|
+
(s) => s?.type === 'addRules' && s.behavior === 'allow' && s.destination === 'localSettings',
|
|
275
|
+
);
|
|
276
|
+
const r = add?.rules?.[0];
|
|
277
|
+
const content = typeof r?.ruleContent === 'string' ? r.ruleContent.trim() : '';
|
|
278
|
+
if (typeof r?.toolName !== 'string' || !content || /^\**$/.test(content)) return null;
|
|
279
|
+
|
|
280
|
+
return `${r.toolName}(${content})`;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** @returns {Neutral[]} */
|
|
284
|
+
function systemEvents(e) {
|
|
285
|
+
if (e.subtype === 'compact_boundary') return [{ type: 'compacted' }];
|
|
286
|
+
// A deny rule of the settings refused a call (spike 8).
|
|
287
|
+
if (e.subtype === 'permission_denied')
|
|
288
|
+
return [{ type: 'refused', tool: String(e.tool_name ?? ''), reason: String(e.message ?? '') }];
|
|
289
|
+
if (e.subtype !== 'background_tasks_changed') return [];
|
|
290
|
+
const tasks = (Array.isArray(e.tasks) ? e.tasks : []).map((t) => ({
|
|
291
|
+
id: String(t.task_id ?? t.id ?? ''),
|
|
292
|
+
description: String(t.description ?? ''),
|
|
293
|
+
}));
|
|
294
|
+
|
|
295
|
+
return [{ type: 'background', tasks }];
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* The account's usage-limit state as the stream gives it, raw: kept to learn its fields before
|
|
300
|
+
* the board shows the quota (Board-PRD decision 17). Any other event gives nothing.
|
|
301
|
+
*/
|
|
302
|
+
const quotaOf = (e) =>
|
|
303
|
+
e.type === 'rate_limit_event' && e.rate_limit_info
|
|
304
|
+
? { lines: [], quota: e.rate_limit_info }
|
|
305
|
+
: { lines: [] };
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* A system event: the init names the session and its model; a compaction is a line, the
|
|
309
|
+
* agent's context summarized; the rest (hooks, thinking) give nothing.
|
|
310
|
+
*/
|
|
311
|
+
function system(e, at) {
|
|
312
|
+
if (e.subtype === 'compact_boundary')
|
|
313
|
+
return { lines: [`${at} compacted: the agent's context was summarized`], compacted: true };
|
|
314
|
+
if (e.subtype !== 'init' || typeof e.session_id !== 'string') return { lines: [] };
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
lines: [],
|
|
318
|
+
session_id: e.session_id,
|
|
319
|
+
...(typeof e.model === 'string' ? { model: e.model } : {}),
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** The tokens a main-agent turn holds in its window: its input, read from cache or written. */
|
|
324
|
+
function contextOf(e) {
|
|
325
|
+
const u = e.message?.usage;
|
|
326
|
+
if (e.parent_tool_use_id != null || !u) return {};
|
|
327
|
+
const tokens =
|
|
328
|
+
Number(u.input_tokens ?? 0) +
|
|
329
|
+
Number(u.cache_read_input_tokens ?? 0) +
|
|
330
|
+
Number(u.cache_creation_input_tokens ?? 0);
|
|
331
|
+
|
|
332
|
+
return { context: tokens, ...(e.message.id ? { turn: String(e.message.id) } : {}) };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** An assistant turn: its tool calls and its text, which may be the usage-limit message. */
|
|
336
|
+
function said(content, at) {
|
|
337
|
+
const texts = content.filter((b) => b.type === 'text').map((b) => b.text);
|
|
338
|
+
|
|
339
|
+
return {
|
|
340
|
+
...(texts.map((t) => limitIn(t)).find((l) => l.limit) ?? {}),
|
|
341
|
+
lines: content.flatMap((b) => {
|
|
342
|
+
if (b.type === 'tool_use') return [`${at} ${toolLine(b)}`];
|
|
343
|
+
const text = b.type === 'text' ? cut(firstLines(b.text, 2), 300) : '';
|
|
344
|
+
|
|
345
|
+
return text ? [`${at} agent: ${text}`] : [];
|
|
346
|
+
}),
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** The `result` event: the final text, a summary line, the cost, and a limit that ended it. */
|
|
351
|
+
function ended(e, at) {
|
|
352
|
+
const cost = costOf(e);
|
|
353
|
+
const text =
|
|
354
|
+
typeof e.result === 'string' && e.result.trim() ? [`${at} result:\n${e.result}`] : [];
|
|
355
|
+
// An error result counts the message anywhere in it; any other only as the whole text.
|
|
356
|
+
const limit = limitIn(e.result, !e.is_error);
|
|
357
|
+
|
|
358
|
+
// The window of each model the session used: its subagents may run on another.
|
|
359
|
+
const windows = Object.entries(e.modelUsage ?? {})
|
|
360
|
+
.map(([m, u]) => /** @type {[string, number]} */ ([m, Number(u?.contextWindow)]))
|
|
361
|
+
.filter(([, n]) => n > 0);
|
|
362
|
+
|
|
363
|
+
return {
|
|
364
|
+
lines: [...text, `${at} ${summary(e, cost, Boolean(limit.limit))}`],
|
|
365
|
+
// The reply itself: a lessons turn answers with its JSON here.
|
|
366
|
+
...(typeof e.result === 'string' ? { result: e.result } : {}),
|
|
367
|
+
cost,
|
|
368
|
+
...limit,
|
|
369
|
+
...(windows.length ? { windows: Object.fromEntries(windows) } : {}),
|
|
370
|
+
};
|
|
371
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// The claude-cli adapter (docs/Session-Engine.md AD-20): all the engine knows of `claude -p`.
|
|
2
|
+
// Its command line and env, its stream read into neutral events (activity.js), its stdin
|
|
3
|
+
// input, its resume and the sign of a session it does not have, its capabilities.
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { activity, kindOf } from '../activity.js';
|
|
7
|
+
import { claim } from '../lock.js';
|
|
8
|
+
import { writeAtomic } from '../store.js';
|
|
9
|
+
|
|
10
|
+
/** What a chat session adds to the agent's command. */
|
|
11
|
+
export const CHAT_FLAGS =
|
|
12
|
+
'--input-format stream-json --permission-prompt-tool stdio --replay-user-messages';
|
|
13
|
+
|
|
14
|
+
// What `claude --resume` prints on stderr for a session it does not have.
|
|
15
|
+
export const NO_SESSION = /No conversation found with session ID/;
|
|
16
|
+
|
|
17
|
+
/** One line of stream-json input. */
|
|
18
|
+
const line = (e) => `${JSON.stringify(e)}\n`;
|
|
19
|
+
|
|
20
|
+
const respond = (requestId, response) =>
|
|
21
|
+
line({
|
|
22
|
+
type: 'control_response',
|
|
23
|
+
response: { subtype: 'success', request_id: requestId, response },
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/** The input a session takes on stdin, each as the line to write. */
|
|
27
|
+
export const encode = {
|
|
28
|
+
/** A message: its text, or its content blocks (text and images). */
|
|
29
|
+
message: (content) => line({ type: 'user', message: { role: 'user', content } }),
|
|
30
|
+
/** A question card's answers. */
|
|
31
|
+
answer: (requestId, input, answers) =>
|
|
32
|
+
respond(requestId, { behavior: 'allow', updatedInput: { ...input, answers } }),
|
|
33
|
+
/** A tool call allowed. */
|
|
34
|
+
allow: (requestId, input) => respond(requestId, { behavior: 'allow', updatedInput: input }),
|
|
35
|
+
/** A tool call refused, with why. */
|
|
36
|
+
deny: (requestId, message) => respond(requestId, { behavior: 'deny', message }),
|
|
37
|
+
/** Stop the turn's step. */
|
|
38
|
+
interrupt: () =>
|
|
39
|
+
line({
|
|
40
|
+
type: 'control_request',
|
|
41
|
+
request_id: `interrupt-${Date.now()}`,
|
|
42
|
+
request: { subtype: 'interrupt' },
|
|
43
|
+
}),
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The flags of a trusted session (Harness-PRD §7): everything allowed but the deny rules of
|
|
48
|
+
* `settingsFile`, which hold in every mode; the project's settings and MCP servers only, so the
|
|
49
|
+
* operator's plugins, hooks and connectors stay out.
|
|
50
|
+
*/
|
|
51
|
+
export function trustedFlags(dir, settingsFile) {
|
|
52
|
+
const mcp = existsSync(path.join(dir, '.mcp.json')) ? ' --mcp-config .mcp.json' : '';
|
|
53
|
+
|
|
54
|
+
return (
|
|
55
|
+
'--permission-mode bypassPermissions --setting-sources project,local ' +
|
|
56
|
+
`--strict-mcp-config${mcp} --settings "${settingsFile}"`
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// The claude tools of each neutral kind (AD-4). The core keeps the same table to give a harness
|
|
61
|
+
// before 0.12 claude strings (gcf-aif-ext lib/agent-permissions.js): change both.
|
|
62
|
+
const TOOLS = {
|
|
63
|
+
read: ['Read'],
|
|
64
|
+
search: ['Grep', 'Glob'],
|
|
65
|
+
edit: ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'],
|
|
66
|
+
shell: ['Bash', 'PowerShell'],
|
|
67
|
+
web: ['WebFetch'],
|
|
68
|
+
subagent: ['Task', 'Agent'],
|
|
69
|
+
skill: ['Skill'],
|
|
70
|
+
question: ['AskUserQuestion'],
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
// The kinds whose pattern is a path glob: the project's, or an absolute one.
|
|
74
|
+
const FILES = new Set(['read', 'search', 'edit']);
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* A path glob as claude reads it: a project path as it is; an absolute one from the root of the
|
|
78
|
+
* filesystem, `//<path>`, a Windows drive as claude names it, `//c/<path>`.
|
|
79
|
+
*/
|
|
80
|
+
function pathRule(pattern) {
|
|
81
|
+
const drive = /^([A-Za-z]):[\\/](.*)$/.exec(pattern);
|
|
82
|
+
if (drive) return `//${drive[1].toLowerCase()}/${drive[2].replaceAll('\\', '/')}`;
|
|
83
|
+
|
|
84
|
+
return pattern.startsWith('/') && !pattern.startsWith('//') ? `/${pattern}` : pattern;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The claude rules of a neutral one `{kind, pattern}`: one per tool of its kind,
|
|
89
|
+
* `WebFetch(domain:…)` for `web`, `mcp__…` for `mcp`, an `other` as it is; none for a kind it
|
|
90
|
+
* does not know.
|
|
91
|
+
*/
|
|
92
|
+
function rulesOf({ kind, pattern }) {
|
|
93
|
+
if (kind === 'other') return [pattern];
|
|
94
|
+
if (kind === 'mcp') return [`mcp__${pattern}`];
|
|
95
|
+
const web = kind === 'web' && pattern ? `domain:${pattern}` : pattern;
|
|
96
|
+
const spec = FILES.has(kind) ? pathRule(pattern) : web;
|
|
97
|
+
|
|
98
|
+
return (TOOLS[kind] ?? []).map((t) => (spec ? `${t}(${spec})` : t));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The `permissions` of a claude settings file from neutral lists `{deny, ask, allow}`: claude
|
|
103
|
+
* itself holds deny over ask over allow.
|
|
104
|
+
*/
|
|
105
|
+
export function permissions(rules = {}) {
|
|
106
|
+
const list = (key) => [...new Set((rules[key] ?? []).flatMap(rulesOf))];
|
|
107
|
+
|
|
108
|
+
return { deny: list('deny'), ask: list('ask'), allow: list('allow') };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Keep an "always" rule (AD-2): added to the allow list of `.claude/settings.local.json` in
|
|
113
|
+
* `dir`, the file read and merged under the engine's lock (AD-34), its other keys kept.
|
|
114
|
+
* shortcut: an interactive claude writing the same file meanwhile is not held off by the lock.
|
|
115
|
+
*/
|
|
116
|
+
// One save at a time in this process: the lock file holds off the others, not this one.
|
|
117
|
+
let saving = Promise.resolve();
|
|
118
|
+
|
|
119
|
+
export function saveAlways(dir, rule) {
|
|
120
|
+
const next = saving.then(() => saveLocked(dir, rule));
|
|
121
|
+
saving = next.catch(() => {});
|
|
122
|
+
|
|
123
|
+
return next;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function saveLocked(dir, rule) {
|
|
127
|
+
const lock = path.join(dir, '.gcf-session', 'settings.lock');
|
|
128
|
+
mkdirSync(path.dirname(lock), { recursive: true });
|
|
129
|
+
let release = await claim(lock);
|
|
130
|
+
for (let i = 0; !release && i < 50; i++) {
|
|
131
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
132
|
+
release = await claim(lock);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (!release) throw new Error('the settings lock stays held');
|
|
136
|
+
try {
|
|
137
|
+
const file = path.join(dir, '.claude', 'settings.local.json');
|
|
138
|
+
let settings = {};
|
|
139
|
+
try {
|
|
140
|
+
settings = JSON.parse(readFileSync(file, 'utf8')) ?? {};
|
|
141
|
+
} catch (e) {
|
|
142
|
+
if (/** @type {any} */ (e).code !== 'ENOENT') throw e;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const allow = settings.permissions?.allow ?? [];
|
|
146
|
+
if (allow.includes(rule)) return;
|
|
147
|
+
settings.permissions = { ...settings.permissions, allow: [...allow, rule] };
|
|
148
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
149
|
+
writeAtomic(file, `${JSON.stringify(settings, null, 2)}\n`);
|
|
150
|
+
} finally {
|
|
151
|
+
await release();
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The text a write replaces and its new text, `[{old, new}]`; `old` null: the whole file. */
|
|
156
|
+
function editsOf(tool, t) {
|
|
157
|
+
if (tool === 'Write') return [{ old: null, new: String(t.content ?? '') }];
|
|
158
|
+
if (tool === 'Edit') return [{ old: t.old_string ?? '', new: t.new_string ?? '' }];
|
|
159
|
+
if (tool === 'MultiEdit')
|
|
160
|
+
return (Array.isArray(t.edits) ? t.edits : []).map((e) => ({
|
|
161
|
+
old: e?.old_string ?? '',
|
|
162
|
+
new: e?.new_string ?? '',
|
|
163
|
+
}));
|
|
164
|
+
|
|
165
|
+
return [];
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* A claude hook's input as a neutral call (AD-21), what a guard decides on: `event` (`tool`,
|
|
170
|
+
* `prompt`), `kind`, `tool`, `paths`, `command`, `glob`, `skill`, `prompt`, `session`,
|
|
171
|
+
* `subagent` (a subagent's call); `content`, a search that reads the files (Grep), not only
|
|
172
|
+
* their names; `edits`, what a write replaces. Null for no input.
|
|
173
|
+
* @param {any} input
|
|
174
|
+
*/
|
|
175
|
+
export function hookCall(input) {
|
|
176
|
+
if (!input || typeof input !== 'object') return null;
|
|
177
|
+
const t = input.tool_input ?? {};
|
|
178
|
+
const tool = String(input.tool_name ?? '');
|
|
179
|
+
const file = t.file_path ?? t.notebook_path ?? t.path;
|
|
180
|
+
const str = (v) => (typeof v === 'string' ? v : null);
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
event: input.hook_event_name === 'UserPromptSubmit' ? 'prompt' : 'tool',
|
|
184
|
+
kind: tool ? kindOf(tool) : null,
|
|
185
|
+
tool,
|
|
186
|
+
paths: typeof file === 'string' && file ? [file] : [],
|
|
187
|
+
command: str(t.command),
|
|
188
|
+
glob: str(t.glob),
|
|
189
|
+
skill: str(t.skill),
|
|
190
|
+
prompt: str(input.prompt),
|
|
191
|
+
session: str(input.session_id),
|
|
192
|
+
subagent: Boolean(input.agent_id),
|
|
193
|
+
content: tool === 'Grep',
|
|
194
|
+
edits: editsOf(tool, t),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export const claude = {
|
|
199
|
+
name: 'claude',
|
|
200
|
+
caps: {
|
|
201
|
+
hooks: true,
|
|
202
|
+
questions: true,
|
|
203
|
+
approvals: true,
|
|
204
|
+
midTurnInput: true,
|
|
205
|
+
resume: true,
|
|
206
|
+
interrupt: true,
|
|
207
|
+
systemPrompt: true,
|
|
208
|
+
},
|
|
209
|
+
/**
|
|
210
|
+
* A session's command line: the agent, the session it resumes, its flags, then the prompt in
|
|
211
|
+
* double quotes, or the chat flags (the prompt goes on stdin).
|
|
212
|
+
*/
|
|
213
|
+
command: ({ agent, resume = null, flags = '', chat = false, prompt }) =>
|
|
214
|
+
[agent, resume && `--resume ${resume}`, flags, chat ? CHAT_FLAGS : `"${prompt}"`]
|
|
215
|
+
.filter(Boolean)
|
|
216
|
+
.join(' '),
|
|
217
|
+
/** The env a session adds: the guards read the session's own checkout. */
|
|
218
|
+
env: (dir) => ({ CLAUDE_PROJECT_DIR: dir }),
|
|
219
|
+
parse: activity,
|
|
220
|
+
gone: (stderrLine) => NO_SESSION.test(stderrLine),
|
|
221
|
+
encode,
|
|
222
|
+
trustedFlags,
|
|
223
|
+
permissions,
|
|
224
|
+
hookCall,
|
|
225
|
+
saveAlways,
|
|
226
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The provider adapter of an agent command (docs/Session-Engine.md AD-20): `claude…` is
|
|
2
|
+
// claude-cli; any other command is raw, with every capability off. No registry, no key.
|
|
3
|
+
import { claude } from './claude.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A raw agent: the command and its prompt, nothing resumed or asked of it. Its output is read
|
|
7
|
+
* as claude's stream where it is one (a stand-in in the tests), as plain lines where it is not.
|
|
8
|
+
*/
|
|
9
|
+
export const raw = {
|
|
10
|
+
...claude,
|
|
11
|
+
name: 'raw',
|
|
12
|
+
caps: {
|
|
13
|
+
hooks: false,
|
|
14
|
+
questions: false,
|
|
15
|
+
approvals: false,
|
|
16
|
+
midTurnInput: false,
|
|
17
|
+
resume: false,
|
|
18
|
+
interrupt: false,
|
|
19
|
+
systemPrompt: false,
|
|
20
|
+
},
|
|
21
|
+
command: ({ agent, flags = '', chat = false, prompt }) =>
|
|
22
|
+
claude.command({ agent, flags, chat, prompt }),
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The adapter of an agent command: claude's for `claude…`, and for the stand-in a test names in
|
|
27
|
+
* `GCF_SESSION_AGENT` (AD-20, AD-25); raw for any other.
|
|
28
|
+
*/
|
|
29
|
+
export const adapterFor = (command) =>
|
|
30
|
+
/^claude(\s|$)/.test(command) ||
|
|
31
|
+
(process.env.GCF_SESSION_AGENT && command === process.env.GCF_SESSION_AGENT)
|
|
32
|
+
? claude
|
|
33
|
+
: raw;
|