@indigoai-us/hq-cli 5.345.268 → 5.345.270
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/CHANGELOG.md +38 -0
- package/README.md +12 -0
- package/contracts/host-canary-release.json +7 -7
- package/dist/lib/daemon/run.js +12 -0
- package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
- package/dist/lib/hook-engine/reconcile.js +8 -0
- package/dist/lib/hook-engine/stable-heal.d.ts +17 -1
- package/dist/lib/hook-engine/stable-heal.js +42 -5
- package/dist/lib/hook-engine/stable-link.d.ts +70 -0
- package/dist/lib/hook-engine/stable-link.js +300 -0
- package/dist/lib/install/hook-target.js +4 -1
- package/dist/lib/signals/steps/extract.d.ts +27 -7
- package/dist/lib/signals/steps/extract.js +88 -87
- package/dist/utils/hook-engine-crash.d.ts +86 -0
- package/dist/utils/hook-engine-crash.js +325 -0
- package/dist/utils/hook-engine-rollup.d.ts +8 -3
- package/dist/utils/hook-trust.js +7 -1
- package/dist/utils/host-registration.d.ts +12 -35
- package/dist/utils/host-registration.js +47 -177
- package/dist/utils/version-gate.d.ts +42 -4
- package/dist/utils/version-gate.js +84 -25
- package/package.json +7 -7
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The release-stable link `<home>/.hq/bin/hq-hook/stable`, which every
|
|
3
|
+
* core.next registration runs the engine through.
|
|
4
|
+
*
|
|
5
|
+
* Kept apart from host-registration.ts so the start-up heal
|
|
6
|
+
* (stable-heal.ts) can move the link without loading the registration switch,
|
|
7
|
+
* the canary gate and their imports. host-registration.ts re-exports what it
|
|
8
|
+
* always exported from here.
|
|
9
|
+
*
|
|
10
|
+
* The link never moves to a lower engine version than the one it names unless
|
|
11
|
+
* the caller is a repair or downgrade the person asked for and passes
|
|
12
|
+
* `allowDowngrade: true` (no command does yet). There is deliberately no
|
|
13
|
+
* environment switch: a lane or an old install script could set one. The
|
|
14
|
+
* refusal applies only while the newer engine the link names is still there
|
|
15
|
+
* and runnable. An older hq-cli run with the real home once moved it from
|
|
16
|
+
* 5.345.268 back to 5.345.238; the older engine did not know the installed gate
|
|
17
|
+
* and refused every PreToolUse call until a heal finished. This guard only
|
|
18
|
+
* binds CLIs that carry it; stable-heal.ts undoes a roll-back made by an older
|
|
19
|
+
* CLI when the pinned engine was canary-accepted on this machine.
|
|
20
|
+
*/
|
|
21
|
+
import * as fs from 'node:fs';
|
|
22
|
+
import * as path from 'node:path';
|
|
23
|
+
/** Name of the release-stable link next to the pinned engine versions. */
|
|
24
|
+
export const STABLE_LINK_NAME = 'stable';
|
|
25
|
+
/** Record of canary-accepted hook engines committed to `stable`, under the home folder. */
|
|
26
|
+
export const ACCEPTED_HOOK_ENGINE_RECORD = path.join('.hq', 'bin', 'hq-hook', 'accepted-engine.json');
|
|
27
|
+
/** Schema of [`ACCEPTED_HOOK_ENGINE_RECORD`]. */
|
|
28
|
+
export const ACCEPTED_HOOK_ENGINE_SCHEMA = 'hq.accepted-hook-engine.v1';
|
|
29
|
+
/**
|
|
30
|
+
* Read `<home>/.hq/bin/hq-hook/accepted-engine.json`; null when absent,
|
|
31
|
+
* unreadable, invalid, or writable by another user.
|
|
32
|
+
*/
|
|
33
|
+
export function readAcceptedHookEngineRecord(home, platform = process.platform) {
|
|
34
|
+
const file = path.join(home, ACCEPTED_HOOK_ENGINE_RECORD);
|
|
35
|
+
let text;
|
|
36
|
+
try {
|
|
37
|
+
checkOwnedEntry(file, 'file', platform);
|
|
38
|
+
text = fs.readFileSync(file, 'utf8');
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
let doc;
|
|
44
|
+
try {
|
|
45
|
+
doc = JSON.parse(text);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
const rec = doc;
|
|
51
|
+
if (!rec || rec.schema !== ACCEPTED_HOOK_ENGINE_SCHEMA || !rec.engines || typeof rec.engines !== 'object' || Array.isArray(rec.engines)) {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
const engines = {};
|
|
55
|
+
for (const [key, raw] of Object.entries(rec.engines)) {
|
|
56
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
57
|
+
continue;
|
|
58
|
+
const entry = raw;
|
|
59
|
+
if (typeof entry.engineVersion !== 'string' || !entry.engineVersion)
|
|
60
|
+
continue;
|
|
61
|
+
if (typeof entry.pinnedEngine !== 'string' || !entry.pinnedEngine)
|
|
62
|
+
continue;
|
|
63
|
+
if (!Array.isArray(entry.hosts))
|
|
64
|
+
continue;
|
|
65
|
+
const hosts = entry.hosts.filter((h) => typeof h === 'string');
|
|
66
|
+
if (hosts.length === 0)
|
|
67
|
+
continue;
|
|
68
|
+
engines[key] = {
|
|
69
|
+
engineVersion: entry.engineVersion,
|
|
70
|
+
pinnedEngine: entry.pinnedEngine,
|
|
71
|
+
acceptedAt: typeof entry.acceptedAt === 'string' ? entry.acceptedAt : '',
|
|
72
|
+
hosts,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
return { schema: ACCEPTED_HOOK_ENGINE_SCHEMA, engines };
|
|
76
|
+
}
|
|
77
|
+
/** True when `pinned` resolves to an engine recorded in the accepted-engine record (it passed the host canary gate here). */
|
|
78
|
+
export function isAcceptedHookEngine(home, pinned, platform = process.platform) {
|
|
79
|
+
let resolved;
|
|
80
|
+
try {
|
|
81
|
+
resolved = fs.realpathSync(pinned);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
const entry = readAcceptedHookEngineRecord(home, platform)?.engines[resolved];
|
|
87
|
+
return !!entry && entry.hosts.length > 0;
|
|
88
|
+
}
|
|
89
|
+
/** Thrown when `stable` names a newer, runnable engine and the caller did not ask for a downgrade. */
|
|
90
|
+
export class StableDowngradeRefused extends Error {
|
|
91
|
+
constructor(message) {
|
|
92
|
+
super(message);
|
|
93
|
+
this.name = 'StableDowngradeRefused';
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
export function hookEngineDir(home) {
|
|
97
|
+
return path.join(home, '.hq', 'bin', 'hq-hook');
|
|
98
|
+
}
|
|
99
|
+
/** The stable path that stands for a pinned engine path. */
|
|
100
|
+
export function stableEnginePath(pinned, home) {
|
|
101
|
+
const relative = path.relative(hookEngineDir(home), pinned);
|
|
102
|
+
const [, ...rest] = relative.split(/[\\/]/);
|
|
103
|
+
if (relative.startsWith('..') || path.isAbsolute(relative) || rest.length === 0) {
|
|
104
|
+
throw new Error(`hook engine ${pinned} is not under ${hookEngineDir(home)}`);
|
|
105
|
+
}
|
|
106
|
+
return path.join(hookEngineDir(home), STABLE_LINK_NAME, ...rest);
|
|
107
|
+
}
|
|
108
|
+
function parseVersion(version) {
|
|
109
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(version);
|
|
110
|
+
if (!match)
|
|
111
|
+
return null;
|
|
112
|
+
return { core: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] ? match[4].split('.') : [] };
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Semver precedence of two engine version folder names: negative when `a` is
|
|
116
|
+
* older, positive when newer, 0 when equal. Null when either is not a version
|
|
117
|
+
* folder name, so the caller cannot tell which is older.
|
|
118
|
+
*/
|
|
119
|
+
export function compareEngineVersions(a, b) {
|
|
120
|
+
const left = parseVersion(a);
|
|
121
|
+
const right = parseVersion(b);
|
|
122
|
+
if (!left || !right)
|
|
123
|
+
return null;
|
|
124
|
+
for (let i = 0; i < 3; i += 1) {
|
|
125
|
+
if (left.core[i] !== right.core[i])
|
|
126
|
+
return left.core[i] - right.core[i];
|
|
127
|
+
}
|
|
128
|
+
if (!left.pre.length || !right.pre.length)
|
|
129
|
+
return right.pre.length - left.pre.length;
|
|
130
|
+
for (let i = 0; i < Math.max(left.pre.length, right.pre.length); i += 1) {
|
|
131
|
+
const x = left.pre[i];
|
|
132
|
+
const y = right.pre[i];
|
|
133
|
+
if (x === undefined)
|
|
134
|
+
return -1;
|
|
135
|
+
if (y === undefined)
|
|
136
|
+
return 1;
|
|
137
|
+
if (x === y)
|
|
138
|
+
continue;
|
|
139
|
+
const xn = /^\d+$/.test(x);
|
|
140
|
+
const yn = /^\d+$/.test(y);
|
|
141
|
+
if (xn && yn)
|
|
142
|
+
return Number(x) - Number(y);
|
|
143
|
+
if (xn !== yn)
|
|
144
|
+
return xn ? -1 : 1;
|
|
145
|
+
return x < y ? -1 : 1;
|
|
146
|
+
}
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
/** The version folder an engine path under `<home>/.hq/bin/hq-hook` sits in; null when it is not under it. */
|
|
150
|
+
export function engineVersionOf(pinned, home) {
|
|
151
|
+
const relative = path.relative(hookEngineDir(home), pinned);
|
|
152
|
+
if (relative.startsWith('..') || path.isAbsolute(relative))
|
|
153
|
+
return null;
|
|
154
|
+
const version = relative.split(/[\\/]/)[0];
|
|
155
|
+
return version && version !== STABLE_LINK_NAME ? version : null;
|
|
156
|
+
}
|
|
157
|
+
/** The version folder name `stable` names (even when that folder is gone); null when it is not a link. */
|
|
158
|
+
export function stableLinkVersion(home) {
|
|
159
|
+
try {
|
|
160
|
+
const target = fs.readlinkSync(path.join(hookEngineDir(home), STABLE_LINK_NAME));
|
|
161
|
+
return target.split(/[\\/]/).filter(Boolean).pop() ?? null;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** True when `file` resolves to a regular file that this platform can run. */
|
|
168
|
+
function isRunnableFile(file, platform) {
|
|
169
|
+
try {
|
|
170
|
+
const stat = fs.statSync(fs.realpathSync(file));
|
|
171
|
+
return stat.isFile() && (platform === 'win32' || (stat.mode & 0o111) !== 0);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/** Append one line to `<home>/.hq/logs/stable-heal.log`; best effort. */
|
|
178
|
+
export function appendStableHealLog(home, line, now = Date.now()) {
|
|
179
|
+
try {
|
|
180
|
+
const logDir = path.join(home, '.hq', 'logs');
|
|
181
|
+
fs.mkdirSync(logDir, { recursive: true });
|
|
182
|
+
fs.appendFileSync(path.join(logDir, 'stable-heal.log'), `${new Date(now).toISOString()} ${line}\n`);
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
// Nowhere left to record it; the caller still gets the error.
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Point `<home>/.hq/bin/hq-hook/stable` at the pinned engine's version folder
|
|
190
|
+
* and return the stable engine path. The link is replaced by rename, so a
|
|
191
|
+
* planted file at the temporary name or the link itself is never followed. A
|
|
192
|
+
* `stable` that is a real folder (not a link) is someone else's and is left
|
|
193
|
+
* alone: the call fails and the caller keeps the current registrations.
|
|
194
|
+
*
|
|
195
|
+
* A link that names a newer engine than `pinned`, which is still there and
|
|
196
|
+
* runnable, stays where it is: the call records the refusal in stable-heal.log
|
|
197
|
+
* and throws [`StableDowngradeRefused`], unless the person asked for the
|
|
198
|
+
* downgrade ([`LinkStableEngineOptions.allowDowngrade`]).
|
|
199
|
+
*/
|
|
200
|
+
export function linkStableEngine(pinned, home, platform = process.platform, options = {}) {
|
|
201
|
+
const root = hookEngineDir(home);
|
|
202
|
+
const relative = path.relative(root, pinned).split(/[\\/]/);
|
|
203
|
+
const version = relative[0];
|
|
204
|
+
if (!version || version === '..' || version === STABLE_LINK_NAME || path.isAbsolute(path.relative(root, pinned))) {
|
|
205
|
+
throw new Error(`hook engine ${pinned} is not under ${root}`);
|
|
206
|
+
}
|
|
207
|
+
const stable = path.join(root, STABLE_LINK_NAME);
|
|
208
|
+
// Store rule v2: every path component this follows or creates under the home
|
|
209
|
+
// folder is a real folder of this user that group and others cannot write:
|
|
210
|
+
// .hq, .hq/bin, .hq/bin/hq-hook, the version folder and any folder below it
|
|
211
|
+
// up to the engine, and the engine file itself.
|
|
212
|
+
const components = [path.join(home, '.hq'), path.join(home, '.hq', 'bin'), root];
|
|
213
|
+
for (let i = 0; i < relative.length - 1; i += 1)
|
|
214
|
+
components.push(path.join(root, ...relative.slice(0, i + 1)));
|
|
215
|
+
for (const component of components)
|
|
216
|
+
checkOwnedEntry(component, 'folder', platform);
|
|
217
|
+
checkOwnedEntry(pinned, 'file', platform);
|
|
218
|
+
// Windows creates a junction, which needs an absolute target; elsewhere the
|
|
219
|
+
// link is relative so it names the version folder beside it.
|
|
220
|
+
const target = platform === 'win32' ? path.join(root, version) : version;
|
|
221
|
+
let current;
|
|
222
|
+
try {
|
|
223
|
+
current = fs.lstatSync(stable);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
if (error.code !== 'ENOENT')
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
if (current && !current.isSymbolicLink())
|
|
230
|
+
throw new Error(`${stable} exists and is not a link; leaving it in place`);
|
|
231
|
+
if (current && pointsAt(stable, path.join(root, version)))
|
|
232
|
+
return stableEnginePath(pinned, home);
|
|
233
|
+
if (current && options.allowDowngrade !== true) {
|
|
234
|
+
const linked = stableLinkVersion(home);
|
|
235
|
+
const order = linked ? compareEngineVersions(version, linked) : null;
|
|
236
|
+
// Only a newer engine that still runs holds the link: a dangling or broken
|
|
237
|
+
// target is relinked to the engine installed now.
|
|
238
|
+
const linkedEngine = path.join(stable, ...relative.slice(1));
|
|
239
|
+
if (order !== null && order < 0 && pointsAt(stable, path.join(root, linked)) && isRunnableFile(linkedEngine, platform)) {
|
|
240
|
+
const message = `refused to move ${stable} from ${linked} back to the older engine ${version} (${pinned}); only an explicit repair or downgrade may move it back`;
|
|
241
|
+
appendStableHealLog(home, message, (options.now ?? Date.now)());
|
|
242
|
+
throw new StableDowngradeRefused(message);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
if (platform === 'win32') {
|
|
246
|
+
// A junction cannot be renamed over another. A running engine keeps its
|
|
247
|
+
// own image open, which the junction does not hold.
|
|
248
|
+
if (current) {
|
|
249
|
+
try {
|
|
250
|
+
fs.unlinkSync(stable);
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
fs.rmdirSync(stable);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
fs.symlinkSync(target, stable, 'junction');
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
const staged = path.join(root, `.${STABLE_LINK_NAME}.${process.pid}.tmp`);
|
|
260
|
+
try {
|
|
261
|
+
fs.unlinkSync(staged);
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
if (error.code !== 'ENOENT')
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
fs.symlinkSync(target, staged);
|
|
268
|
+
try {
|
|
269
|
+
fs.renameSync(staged, stable);
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
try {
|
|
273
|
+
fs.unlinkSync(staged);
|
|
274
|
+
}
|
|
275
|
+
catch { /* already gone */ }
|
|
276
|
+
throw error;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return stableEnginePath(pinned, home);
|
|
280
|
+
}
|
|
281
|
+
/** A real folder or file (not a link) of this user that group and others cannot write. */
|
|
282
|
+
export function checkOwnedEntry(entry, kind, platform) {
|
|
283
|
+
const stat = fs.lstatSync(entry);
|
|
284
|
+
if (stat.isSymbolicLink() || (kind === 'folder' ? !stat.isDirectory() : !stat.isFile()))
|
|
285
|
+
throw new Error(`${entry} is not a ${kind}`);
|
|
286
|
+
if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
|
|
287
|
+
throw new Error(`${entry} is not owned by this user`);
|
|
288
|
+
if (platform !== 'win32' && (stat.mode & 0o022) !== 0)
|
|
289
|
+
throw new Error(`${entry} is writable by group or others`);
|
|
290
|
+
}
|
|
291
|
+
/** True when the link resolves to `folder` (Windows reports junction targets in its own spelling). */
|
|
292
|
+
export function pointsAt(link, folder) {
|
|
293
|
+
try {
|
|
294
|
+
return fs.realpathSync(link) === fs.realpathSync(folder);
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
return false;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
//# sourceMappingURL=stable-link.js.map
|
|
@@ -83,7 +83,10 @@ export function resolveInstallHookTarget(hqRoot, home, daemonInstalled, env = pr
|
|
|
83
83
|
}
|
|
84
84
|
const coreNext = forHost(rawCoreNext, hqRoot, host, env);
|
|
85
85
|
if (coreNext) {
|
|
86
|
-
candidate?.commitStable
|
|
86
|
+
if (candidate?.commitStable)
|
|
87
|
+
candidate.commitStable([host]);
|
|
88
|
+
else
|
|
89
|
+
candidate?.recordAccepted?.([host]);
|
|
87
90
|
return { target: { ...coreNext, fallback } };
|
|
88
91
|
}
|
|
89
92
|
const existingHosts = nativeOnly ? detectMachineHookHosts(hqRoot, home, env) : [];
|
|
@@ -281,15 +281,35 @@ export declare function codexFilesystemProfile(installDir: string, workDir: stri
|
|
|
281
281
|
export declare function grokSandboxProfile(scope: TurnScope, envPath: string | undefined): string;
|
|
282
282
|
/** Grok can read the source; candidate writing belongs to the host. */
|
|
283
283
|
export declare function grokAllowRules(channelDir: string): string[];
|
|
284
|
-
|
|
285
|
-
|
|
284
|
+
export interface DroppedCandidate {
|
|
285
|
+
index: number;
|
|
286
|
+
reason: string;
|
|
287
|
+
}
|
|
288
|
+
export type CandidateParseResult = {
|
|
289
|
+
ok: true;
|
|
290
|
+
argv: string[];
|
|
291
|
+
} | {
|
|
292
|
+
ok: false;
|
|
293
|
+
reason: string;
|
|
294
|
+
};
|
|
295
|
+
export interface ExecuteCandidatesResult {
|
|
296
|
+
error?: string;
|
|
297
|
+
dropped: DroppedCandidate[];
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Validate one structured candidate object and build the fixed 7-element argv
|
|
301
|
+
* for the pinned candidate wrapper. No shell ever interprets model output, and
|
|
302
|
+
* the model can never change the executable, wrapper path, or flag shape.
|
|
303
|
+
*/
|
|
304
|
+
export declare function structuredCandidateArgv(candidate: unknown, wrapperPath: string): CandidateParseResult;
|
|
286
305
|
/**
|
|
287
|
-
* Validate
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
*
|
|
306
|
+
* Validate structured candidates and execute each valid one through the pinned
|
|
307
|
+
* wrapper using a fixed argv array (never a shell command string). A malformed
|
|
308
|
+
* or invalid candidate drops only itself, records why, and keeps the rest of
|
|
309
|
+
* the item's valid candidates. When `expectedWrapper` is set, the file on disk
|
|
310
|
+
* is compared to that text immediately before each exec.
|
|
291
311
|
*/
|
|
292
|
-
export declare function executeGrokCandidates(text: string, wrapperPath: string, spawn: SpawnSyncFn, opts: Parameters<SpawnSyncFn>[2], expectedWrapper?: string, runtime?: "grok" | "codex" | "claude"):
|
|
312
|
+
export declare function executeGrokCandidates(text: string, wrapperPath: string, spawn: SpawnSyncFn, opts: Parameters<SpawnSyncFn>[2], expectedWrapper?: string, runtime?: "grok" | "codex" | "claude"): ExecuteCandidatesResult;
|
|
293
313
|
/**
|
|
294
314
|
* Read denies for the grok login. Grok matches a `~` tool path literally and
|
|
295
315
|
* expands `~` only after that check, so the absolute temp home is not enough.
|
|
@@ -411,8 +411,8 @@ export function buildExtractPrompt(input) {
|
|
|
411
411
|
// A fleet turn (hq-fleet-local complete) has no tools, like codex: the host
|
|
412
412
|
// puts the item in the prompt.
|
|
413
413
|
const hostRead = input.runtime === "codex" || input.runtime === "fleet";
|
|
414
|
-
// The no-shell runtimes return
|
|
415
|
-
const
|
|
414
|
+
// The no-shell runtimes return structured candidates as JSON data for the host to write.
|
|
415
|
+
const jsonCandidates = input.runtime === "grok" || hostRead;
|
|
416
416
|
const tool = hostRead ? "terminal or any other tool" : "terminal tool";
|
|
417
417
|
return [
|
|
418
418
|
"You are running the ontology worker's process-source skill unattended for ONE source item.",
|
|
@@ -431,23 +431,29 @@ export function buildExtractPrompt(input) {
|
|
|
431
431
|
: input.runtime === "grok"
|
|
432
432
|
? "- Read the item with the read_file tool. Only files in the item's channel folder are readable."
|
|
433
433
|
: "- Read the item with the Read tool. Only files in the item's channel folder are readable.",
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
434
|
+
...(jsonCandidates
|
|
435
|
+
? [
|
|
436
|
+
`- You have no ${tool}. Return JSON only: {"candidates":[{"kind":"signal"|"entity","type":"<type>","body":"<text>"}]}. HQ writes validated candidates after your turn. At most ${MAX_CANDIDATES_PER_ITEM} candidates; use an empty array for no candidates.`,
|
|
437
|
+
"- Do not return shell commands or flags; put the literal candidate text in \"body\". Company, audience and source ref are fixed by HQ.",
|
|
438
|
+
]
|
|
439
|
+
: [
|
|
440
|
+
`- Write candidates ONLY with: bash ${input.wrapperPath} --kind signal|entity --type <type> --body "<text>"`,
|
|
441
|
+
"- That command already fixes the company, audience and source ref for this item. Do not pass --company, --audience, --source-ref or --body-file; it refuses them.",
|
|
442
|
+
]),
|
|
439
443
|
`- Signal types (exactly these): ${EXTRACT_SIGNAL_TYPES.join(", ")}.`,
|
|
440
444
|
`- Entity types: ${ENTITY_TYPES.join(", ")}.`,
|
|
441
445
|
"- Every signal body must end with a citation: a one-sentence quote from the item or its timestamp, for example: (cite: \"we ship Friday\") or (cite: 00:12:31).",
|
|
442
446
|
"- No other command can run, and no other file can be written.",
|
|
443
|
-
|
|
444
|
-
? '- Return only the JSON
|
|
447
|
+
jsonCandidates
|
|
448
|
+
? '- Return only the JSON candidates object, without markdown fences. This overrides the skill instructions about executing commands.'
|
|
445
449
|
: "- When finished, reply with one line: the number of candidates written.",
|
|
446
450
|
"",
|
|
447
451
|
...(input.priorSignals?.length ? [
|
|
448
452
|
"Already extracted for this source; do not repeat; return `update: <id>` to amend one",
|
|
449
453
|
JSON.stringify(input.priorSignals),
|
|
450
|
-
|
|
454
|
+
jsonCandidates
|
|
455
|
+
? 'For signals only, pass "body" as a JSON string {"title":"short title","body":"text with citation","update":"prior id (omit for new)"}. Entity bodies stay plain text.'
|
|
456
|
+
: 'For signals only, pass --body a JSON object {"title":"short title","body":"text with citation","update":"prior id (omit for new)"}. Entity bodies stay plain text.',
|
|
451
457
|
] : []),
|
|
452
458
|
"--- process-source skill ---",
|
|
453
459
|
input.skillText.trim(),
|
|
@@ -897,57 +903,33 @@ export function grokSandboxProfile(scope, envPath) {
|
|
|
897
903
|
export function grokAllowRules(channelDir) {
|
|
898
904
|
return [`Read(${channelDir}/**)`];
|
|
899
905
|
}
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
const ch = command[i++];
|
|
912
|
-
if (ch === "'" || ch === '"') {
|
|
913
|
-
const quote = ch;
|
|
914
|
-
let closed = false;
|
|
915
|
-
while (i < command.length) {
|
|
916
|
-
const c = command[i++];
|
|
917
|
-
if (c === quote) {
|
|
918
|
-
closed = true;
|
|
919
|
-
break;
|
|
920
|
-
}
|
|
921
|
-
if (quote === '"' && (c === "$" || c === "`"))
|
|
922
|
-
return null;
|
|
923
|
-
if (quote === '"' && c === "\\") {
|
|
924
|
-
const next = command[i++];
|
|
925
|
-
if (next !== '"' && next !== "\\")
|
|
926
|
-
return null;
|
|
927
|
-
word += next;
|
|
928
|
-
}
|
|
929
|
-
else
|
|
930
|
-
word += c;
|
|
931
|
-
}
|
|
932
|
-
if (!closed)
|
|
933
|
-
return null;
|
|
934
|
-
}
|
|
935
|
-
else if (ch === "\\" && command[i] === "'") {
|
|
936
|
-
word += command[i++];
|
|
937
|
-
}
|
|
938
|
-
else if (/^[a-zA-Z0-9_./:-]$/.test(ch))
|
|
939
|
-
word += ch;
|
|
940
|
-
else
|
|
941
|
-
return null;
|
|
942
|
-
}
|
|
943
|
-
words.push(word);
|
|
906
|
+
const SIGNAL_TYPE_SET = new Set(EXTRACT_SIGNAL_TYPES);
|
|
907
|
+
const ENTITY_TYPE_SET = new Set(ENTITY_TYPES);
|
|
908
|
+
const MAX_CANDIDATES_PER_ITEM = 8;
|
|
909
|
+
/**
|
|
910
|
+
* Validate one structured candidate object and build the fixed 7-element argv
|
|
911
|
+
* for the pinned candidate wrapper. No shell ever interprets model output, and
|
|
912
|
+
* the model can never change the executable, wrapper path, or flag shape.
|
|
913
|
+
*/
|
|
914
|
+
export function structuredCandidateArgv(candidate, wrapperPath) {
|
|
915
|
+
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) {
|
|
916
|
+
return { ok: false, reason: "candidate must be a JSON object" };
|
|
944
917
|
}
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
918
|
+
const obj = candidate;
|
|
919
|
+
const kind = obj.kind;
|
|
920
|
+
if (kind !== "signal" && kind !== "entity") {
|
|
921
|
+
return { ok: false, reason: 'invalid kind: must be "signal" or "entity"' };
|
|
922
|
+
}
|
|
923
|
+
const type = obj.type;
|
|
924
|
+
const allowedTypes = kind === "signal" ? SIGNAL_TYPE_SET : ENTITY_TYPE_SET;
|
|
925
|
+
if (typeof type !== "string" || !allowedTypes.has(type)) {
|
|
926
|
+
return { ok: false, reason: `invalid ${kind} type` };
|
|
927
|
+
}
|
|
928
|
+
const body = obj.body;
|
|
929
|
+
if (typeof body !== "string" || body.length === 0 || body.includes("\0")) {
|
|
930
|
+
return { ok: false, reason: "body must be a non-empty string without NUL bytes" };
|
|
931
|
+
}
|
|
932
|
+
return { ok: true, argv: [wrapperPath, "--kind", kind, "--type", type, "--body", body] };
|
|
951
933
|
}
|
|
952
934
|
/** True when the writer on disk is still the script this turn generated. */
|
|
953
935
|
function wrapperMatchesGenerated(wrapperPath, expected) {
|
|
@@ -959,10 +941,11 @@ function wrapperMatchesGenerated(wrapperPath, expected) {
|
|
|
959
941
|
}
|
|
960
942
|
}
|
|
961
943
|
/**
|
|
962
|
-
* Validate
|
|
963
|
-
*
|
|
964
|
-
*
|
|
965
|
-
*
|
|
944
|
+
* Validate structured candidates and execute each valid one through the pinned
|
|
945
|
+
* wrapper using a fixed argv array (never a shell command string). A malformed
|
|
946
|
+
* or invalid candidate drops only itself, records why, and keeps the rest of
|
|
947
|
+
* the item's valid candidates. When `expectedWrapper` is set, the file on disk
|
|
948
|
+
* is compared to that text immediately before each exec.
|
|
966
949
|
*/
|
|
967
950
|
export function executeGrokCandidates(text, wrapperPath, spawn, opts, expectedWrapper, runtime = "grok") {
|
|
968
951
|
let data;
|
|
@@ -970,27 +953,33 @@ export function executeGrokCandidates(text, wrapperPath, spawn, opts, expectedWr
|
|
|
970
953
|
data = JSON.parse(text);
|
|
971
954
|
}
|
|
972
955
|
catch {
|
|
973
|
-
return `${runtime} must return a JSON
|
|
956
|
+
return { error: `${runtime} must return a JSON candidates object`, dropped: [] };
|
|
957
|
+
}
|
|
958
|
+
if (!data || typeof data !== "object" || Array.isArray(data) || !("candidates" in data) || !Array.isArray(data.candidates)) {
|
|
959
|
+
return { error: `${runtime} must return a JSON candidates array`, dropped: [] };
|
|
974
960
|
}
|
|
975
|
-
if (
|
|
976
|
-
return `${runtime} must return at most
|
|
961
|
+
if (data.candidates.length > MAX_CANDIDATES_PER_ITEM) {
|
|
962
|
+
return { error: `${runtime} must return at most ${MAX_CANDIDATES_PER_ITEM} candidates`, dropped: [] };
|
|
977
963
|
}
|
|
978
964
|
const batch = [];
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
965
|
+
const dropped = [];
|
|
966
|
+
for (let index = 0; index < data.candidates.length; index++) {
|
|
967
|
+
const parsed = structuredCandidateArgv(data.candidates[index], wrapperPath);
|
|
968
|
+
if (!parsed.ok) {
|
|
969
|
+
dropped.push({ index, reason: parsed.reason });
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
batch.push(parsed.argv);
|
|
984
973
|
}
|
|
985
974
|
for (const argv of batch) {
|
|
986
975
|
if (expectedWrapper !== undefined && !wrapperMatchesGenerated(wrapperPath, expectedWrapper)) {
|
|
987
|
-
return "pinned candidate writer does not match the generated script";
|
|
976
|
+
return { error: "pinned candidate writer does not match the generated script", dropped };
|
|
988
977
|
}
|
|
989
978
|
const result = spawn("/bin/bash", argv, opts);
|
|
990
979
|
if (result.error || result.status !== 0)
|
|
991
|
-
return "pinned candidate writer failed";
|
|
980
|
+
return { error: "pinned candidate writer failed", dropped };
|
|
992
981
|
}
|
|
993
|
-
return
|
|
982
|
+
return { dropped };
|
|
994
983
|
}
|
|
995
984
|
/**
|
|
996
985
|
* Read denies for the grok login. Grok matches a `~` tool path literally and
|
|
@@ -1395,15 +1384,18 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
|
|
|
1395
1384
|
const c = classifyFailure(detail, `${runtime} turn failed: ${detail.slice(0, 300) || "error result"}`);
|
|
1396
1385
|
return { ok: false, ...c, turns: parsed.turns, ...failCost };
|
|
1397
1386
|
}
|
|
1387
|
+
let droppedCandidates;
|
|
1398
1388
|
if (runtime === "grok") {
|
|
1399
1389
|
if (scope.wrapperBody === undefined) {
|
|
1400
1390
|
return { ok: false, error: "pinned candidate writer is missing", errorKind: "other", turns: parsed.turns, ...failCost };
|
|
1401
1391
|
}
|
|
1402
|
-
const
|
|
1392
|
+
const exec = executeGrokCandidates(stripFence(String(parsed.result.result ?? "")), scope.wrapperPath, ctx.spawn, {
|
|
1403
1393
|
cwd, env: grokTurnEnv({ ...process.env, HQ_ROOT: ctx.hqRoot }), timeoutMs: SCRIPT_TIMEOUT_MS,
|
|
1404
1394
|
}, scope.wrapperBody);
|
|
1405
|
-
if (
|
|
1406
|
-
|
|
1395
|
+
if (exec.dropped.length)
|
|
1396
|
+
droppedCandidates = exec.dropped;
|
|
1397
|
+
if (exec.error)
|
|
1398
|
+
return { ok: false, error: exec.error, errorKind: "other", turns: parsed.turns, ...(droppedCandidates ? { droppedCandidates } : {}), ...failCost };
|
|
1407
1399
|
}
|
|
1408
1400
|
if (runtime === "codex") {
|
|
1409
1401
|
const used = codexToolItem(res.stdout);
|
|
@@ -1414,13 +1406,15 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
|
|
|
1414
1406
|
}
|
|
1415
1407
|
if (codexReplyText === null)
|
|
1416
1408
|
return { ok: false, error: "codex printed no reply", errorKind: "other", turns: parsed.turns, ...failCost };
|
|
1417
|
-
const
|
|
1409
|
+
const exec = executeGrokCandidates(stripFence(codexReplyText), scope.wrapperPath, ctx.spawn, {
|
|
1418
1410
|
cwd: scope.turnDir, env: grokTurnEnv({ ...process.env, HQ_ROOT: ctx.hqRoot }), timeoutMs: SCRIPT_TIMEOUT_MS,
|
|
1419
1411
|
}, scope.wrapperBody, "codex");
|
|
1420
|
-
if (
|
|
1421
|
-
|
|
1412
|
+
if (exec.dropped.length)
|
|
1413
|
+
droppedCandidates = exec.dropped;
|
|
1414
|
+
if (exec.error)
|
|
1415
|
+
return { ok: false, error: exec.error, errorKind: "other", turns: parsed.turns, ...(droppedCandidates ? { droppedCandidates } : {}), ...failCost };
|
|
1422
1416
|
}
|
|
1423
|
-
return { ok: true, turns: parsed.turns, ...cost };
|
|
1417
|
+
return { ok: true, turns: parsed.turns, ...(droppedCandidates ? { droppedCandidates } : {}), ...cost };
|
|
1424
1418
|
}
|
|
1425
1419
|
/** Spawn error codes that mean the hq-fleet-local helper never started. */
|
|
1426
1420
|
const FLEET_HELPER_NOT_STARTED = new Set(["ENOENT", "EACCES", "ENOTDIR", "EPERM", "ENOEXEC"]);
|
|
@@ -1492,12 +1486,13 @@ async function runFleetTurn(ctx, target, prompt, scope, opts) {
|
|
|
1492
1486
|
if (scope.wrapperBody === undefined) {
|
|
1493
1487
|
return { ok: false, error: "pinned candidate writer is missing", errorKind: "other", turns: 1, ...charged };
|
|
1494
1488
|
}
|
|
1495
|
-
const
|
|
1489
|
+
const exec = executeGrokCandidates(stripFence(result.text), scope.wrapperPath, ctx.spawn, {
|
|
1496
1490
|
cwd: scope.turnDir, env: grokTurnEnv({ ...process.env, HQ_ROOT: ctx.hqRoot }), timeoutMs: SCRIPT_TIMEOUT_MS,
|
|
1497
1491
|
}, scope.wrapperBody, "claude");
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1492
|
+
const dropped = exec.dropped.length ? { droppedCandidates: exec.dropped } : {};
|
|
1493
|
+
if (exec.error)
|
|
1494
|
+
return { ok: false, error: exec.error, errorKind: "other", turns: 1, ...dropped, ...charged };
|
|
1495
|
+
return { ok: true, turns: 1, ...dropped, ...charged };
|
|
1501
1496
|
}
|
|
1502
1497
|
/**
|
|
1503
1498
|
* The Executive bot's HQ Fleet target (fleetCompleteTarget, the resolution
|
|
@@ -1728,6 +1723,7 @@ export function createExtractStep(options = {}) {
|
|
|
1728
1723
|
/** Signal candidates with no citation marker, and the sources they came from. Counted, not rejected. */
|
|
1729
1724
|
let uncitedCandidates = 0;
|
|
1730
1725
|
const uncitedSources = [];
|
|
1726
|
+
const droppedCandidates = [];
|
|
1731
1727
|
let errorKind;
|
|
1732
1728
|
const failures = [
|
|
1733
1729
|
...unreadable,
|
|
@@ -1903,6 +1899,11 @@ export function createExtractStep(options = {}) {
|
|
|
1903
1899
|
lastCost = turn.costUsd;
|
|
1904
1900
|
if (turn.costEstimated)
|
|
1905
1901
|
unpricedSources += 1;
|
|
1902
|
+
if (turn.droppedCandidates?.length) {
|
|
1903
|
+
for (const d of turn.droppedCandidates) {
|
|
1904
|
+
droppedCandidates.push({ file: item.file, index: d.index, reason: d.reason });
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1906
1907
|
sourcesRun += 1;
|
|
1907
1908
|
const created = [...allCandidateFiles(ctx.hqRoot)].filter((f) => !before.has(f));
|
|
1908
1909
|
if (!turn.ok && (priorSignals.length || turn.budgetExceeded)) {
|
|
@@ -1987,7 +1988,7 @@ export function createExtractStep(options = {}) {
|
|
|
1987
1988
|
...(failures.length ? { failures } : {}),
|
|
1988
1989
|
...(skippedItems.length ? { skippedItems } : {}),
|
|
1989
1990
|
...(rejected ? { rejectedCandidates: rejected } : {}),
|
|
1990
|
-
detail: { new: itemsOut, updated, skipped, runtime, ...(runtime === "claude" ? { login: fleet ? "fleet" : "claude-cli", ...(fleet ? { bot: fleet.botName } : {}) } : {}), ...(fleetFallback ? { loginFallback: fleetFallback } : {}), ...(fleetTooLarge.length ? { fleetTooLarge } : {}), ...(choice.fallback ? { fallback: choice.fallback } : {}), ...(budgetStoppedAt ? { budgetStoppedAt } : {}), ...(unpricedSources ? { spendEstimated: true, unpricedSources, unpricedSourceEstimateUsd: turnOpts.unpricedSourceEstimateUsd } : {}), ...(uncitedCandidates ? { uncitedCandidates, uncitedSources } : {}), ...listingDetail },
|
|
1991
|
+
detail: { new: itemsOut, updated, skipped, runtime, ...(runtime === "claude" ? { login: fleet ? "fleet" : "claude-cli", ...(fleet ? { bot: fleet.botName } : {}) } : {}), ...(fleetFallback ? { loginFallback: fleetFallback } : {}), ...(fleetTooLarge.length ? { fleetTooLarge } : {}), ...(choice.fallback ? { fallback: choice.fallback } : {}), ...(budgetStoppedAt ? { budgetStoppedAt } : {}), ...(unpricedSources ? { spendEstimated: true, unpricedSources, unpricedSourceEstimateUsd: turnOpts.unpricedSourceEstimateUsd } : {}), ...(uncitedCandidates ? { uncitedCandidates, uncitedSources } : {}), ...(droppedCandidates.length ? { droppedCandidates } : {}), ...listingDetail },
|
|
1991
1992
|
};
|
|
1992
1993
|
// Between-sources stop. An in-source stop sets budgetStoppedAt and leaves sourcesLeft at 0.
|
|
1993
1994
|
// Main names that next source in budgetStoppedAt; the estimate reason is recorded too.
|