tryharness 0.7.72 → 0.7.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/assets/opencode-plugin.js +70 -3
  2. package/lib/asks.mjs +2 -0
  3. package/lib/boardCommands.mjs +9 -1
  4. package/lib/boardProtocol.json +23 -19
  5. package/lib/bridge.mjs +2 -0
  6. package/lib/capabilityCheck.mjs +86 -0
  7. package/lib/computerAddress.mjs +6 -14
  8. package/lib/coordinator.mjs +207 -26
  9. package/lib/daemon.mjs +150 -125
  10. package/lib/dispatchContract.json +1 -31
  11. package/lib/dispatchTools.js +8 -39
  12. package/lib/dispatches.mjs +27 -285
  13. package/lib/goalCommands.mjs +7 -3
  14. package/lib/herdr.mjs +159 -0
  15. package/lib/hookDialects.mjs +36 -2
  16. package/lib/jobAnswers.mjs +3 -0
  17. package/lib/kanban.mjs +256 -0
  18. package/lib/localAgentAsk.mjs +20 -29
  19. package/lib/machineRoutes.mjs +1 -5
  20. package/lib/manager.mjs +254 -0
  21. package/lib/mcp-stdio.mjs +58 -39
  22. package/lib/moves.mjs +365 -0
  23. package/lib/nudge.mjs +13 -3
  24. package/lib/ownMachines.mjs +43 -6
  25. package/lib/places.mjs +29 -2
  26. package/lib/runAuthority.mjs +2 -14
  27. package/lib/runBrief.mjs +14 -1
  28. package/lib/runWorker.mjs +4 -10
  29. package/lib/runner.mjs +1 -49
  30. package/lib/sessionControl.mjs +65 -1
  31. package/lib/steerHook.mjs +124 -0
  32. package/lib/steerQueue.mjs +176 -0
  33. package/lib/store.mjs +9 -23
  34. package/lib/subagentSteering.mjs +363 -0
  35. package/lib/subagents.mjs +138 -29
  36. package/lib/swarm.mjs +13 -3
  37. package/lib/taskCommands.mjs +0 -62
  38. package/lib/threadActions.mjs +4 -2
  39. package/lib/threadBriefs.mjs +9 -3
  40. package/lib/threadRuns.mjs +13 -0
  41. package/npm-shrinkwrap.json +14 -14
  42. package/package.json +4 -4
  43. package/release.json +44 -40
  44. package/lib/comfyExecution.mjs +0 -545
  45. package/lib/promptDecider.mjs +0 -471
  46. package/lib/promptFlow.mjs +0 -597
  47. package/lib/promptScopes.mjs +0 -670
@@ -1,471 +0,0 @@
1
- // The prompt decider: reads an owner's natural-language prompt and picks one of the assignments code already
2
- // offered, or none. It only selects. Grants, budgets, request identity, source-span binding and every executor check
3
- // stay with the caller; a decision here is not permission to run anything.
4
- //
5
- // Two transports sit behind one interface so a fine-tuned Relay model can replace today's stand-in by owner
6
- // configuration alone (config.promptDecider):
7
- // { "transport": "native-claude", "model"?: "<Claude Code model name>" } the default stand-in
8
- // { "transport": "local-openai", "origin": "http://127.0.0.1:<port>", "model": "<name>" }
9
- // Nothing else is loadable: no module paths, no credentials, no hosted fallback.
10
- import fs from "node:fs";
11
- import http from "node:http";
12
- import net from "node:net";
13
- import { createHash } from "node:crypto";
14
- import { spawnSync } from "node:child_process";
15
- import { agentBinary, agentCommand } from "./agentBinaries.mjs";
16
- import { askLocalAgent } from "./localAgentAsk.mjs";
17
-
18
- export const PROMPT_DECISION_CONTRACT = "prompt-decision@1";
19
- // --restricted, which keeps the stand-in tool-free, first shipped in this Claude Code release.
20
- const MIN_CLAUDE_VERSION = [2, 1, 248];
21
- const CHAT_COMPLETIONS_PATH = "/v1/chat/completions";
22
- // A decision is three small fields; a reply larger than this is not one.
23
- const MAX_REPLY_BYTES = 1 << 20;
24
- const REF = /^[A-Za-z0-9][A-Za-z0-9_.:@-]*$/;
25
- // Model names become one argv value or one JSON string; a leading "-" would read as a flag.
26
- const MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:\/@+-]{0,127}$/;
27
-
28
- const INSTRUCTIONS = `You select which offered assignment should carry out the owner's prompt. You only choose; code checks and runs everything.
29
- Return only one JSON object with exactly these keys: assignment_ref, computer_source, signoff.
30
- - assignment_ref: one candidate's assignment_ref copied exactly, or the literal "none".
31
- - Each candidate is one agent on one computer with one capability_ref. Choose a candidate whose capability covers all the requested work: a workspace-read capability for reading files only, a workspace-files capability for reading or writing ordinary files, an image capability for creating or editing images. If no single candidate covers the work, or it needs anything not offered (shell commands, network access, money, secrets, other computers), answer "none".
32
- - If the prompt names a computer, choose only a candidate whose computer is that one, and set computer_source to {"start":S,"end":E}, the character offsets in prompt where that computer's name appears. Never substitute another computer; if none of its candidates fits, answer "none". If no computer is named, computer_source is null.
33
- - signoff: true when the owner asks to review, approve or sign off before the work starts; otherwise false.
34
- Do not invent candidates, refs, computers, limits or permissions.`;
35
-
36
- const refusal = (code, message) =>
37
- Object.assign(new Error(message), { code, refused: true });
38
-
39
- const exactKeys = (value, keys) =>
40
- value !== null &&
41
- typeof value === "object" &&
42
- !Array.isArray(value) &&
43
- Object.keys(value).length === keys.length &&
44
- keys.every((key) => Object.hasOwn(value, key));
45
-
46
- const allowedKeys = (value, required, optional) =>
47
- value !== null &&
48
- typeof value === "object" &&
49
- !Array.isArray(value) &&
50
- required.every((key) => Object.hasOwn(value, key)) &&
51
- Object.keys(value).every(
52
- (key) => required.includes(key) || optional.includes(key)
53
- );
54
-
55
- const atLeastVersion = (version, minimum) => {
56
- for (let i = 0; i < minimum.length; i++)
57
- if (version[i] !== minimum[i]) return version[i] > minimum[i];
58
- return true;
59
- };
60
-
61
- /** Only numeric loopback hosts: a name could resolve elsewhere, and anything else leaves the computer. */
62
- const isNumericLoopback = (hostname) => {
63
- const host = hostname.replace(/^\[|\]$/g, "");
64
- if (net.isIPv4(host)) return host.split(".")[0] === "127";
65
- return net.isIPv6(host) && (host === "::1" || host === "0:0:0:0:0:0:0:1");
66
- };
67
-
68
- function readSettings(config) {
69
- const settings = config?.promptDecider ?? { transport: "native-claude" };
70
- if (settings?.transport === "native-claude") {
71
- if (!allowedKeys(settings, ["transport"], ["model"]))
72
- throw refusal("decider_config", "native-claude takes only model");
73
- const model = settings.model ?? null;
74
- if (model !== null && !MODEL_NAME.test(model))
75
- throw refusal("decider_config", "the model name is not a plain name");
76
- return { transport: "native-claude", model };
77
- }
78
- if (settings?.transport === "local-openai") {
79
- if (!exactKeys(settings, ["transport", "origin", "model"]))
80
- throw refusal(
81
- "decider_config",
82
- "local-openai takes exactly origin and model"
83
- );
84
- if (typeof settings.model !== "string" || !MODEL_NAME.test(settings.model))
85
- throw refusal("decider_config", "the model name is not a plain name");
86
- let url;
87
- try {
88
- url = new URL(settings.origin);
89
- } catch {
90
- throw refusal("decider_config", "the origin is not a URL");
91
- }
92
- if (
93
- url.protocol !== "http:" ||
94
- url.origin !== settings.origin ||
95
- !isNumericLoopback(url.hostname)
96
- )
97
- throw refusal(
98
- "decider_config",
99
- "the origin must be http://<numeric loopback address>:<port>, with no path or credentials"
100
- );
101
- return {
102
- transport: "local-openai",
103
- model: settings.model,
104
- origin: url.origin,
105
- endpoint: url.origin + CHAT_COMPLETIONS_PATH,
106
- };
107
- }
108
- throw refusal("decider_config", "unknown prompt decider transport");
109
- }
110
-
111
- function nativeExecutable() {
112
- const found = agentBinary("claude-code", agentCommand("claude-code"));
113
- if (!found)
114
- throw refusal("decider_unavailable", "Claude Code is not installed");
115
- const executable = fs.realpathSync(found);
116
- const reported = spawnSync(executable, ["--version"], { encoding: "utf8" });
117
- const version = /(\d+)\.(\d+)\.(\d+)/
118
- .exec(reported.stdout ?? "")
119
- ?.slice(1)
120
- .map(Number);
121
- if (
122
- reported.status !== 0 ||
123
- !version ||
124
- !atLeastVersion(version, MIN_CLAUDE_VERSION)
125
- )
126
- throw refusal(
127
- "decider_unavailable",
128
- `Claude Code ${MIN_CLAUDE_VERSION.join(".")} or newer is required for the tool-free decider`
129
- );
130
- return { executable, version: version.join(".") };
131
- }
132
-
133
- function describe(settings) {
134
- const base =
135
- settings.transport === "native-claude"
136
- ? {
137
- transport: "native-claude",
138
- model: settings.model,
139
- // The prompt and candidates go to Anthropic through Claude Code.
140
- privacy: "hosted",
141
- ...nativeExecutable(),
142
- tools: "none",
143
- }
144
- : {
145
- transport: "local-openai",
146
- model: settings.model,
147
- // Harness can only promise the bytes stay on this computer's loopback; what the server listening there
148
- // does with them is the owner's own model setup.
149
- privacy: "loopback",
150
- origin: settings.origin,
151
- endpoint: settings.endpoint,
152
- executable: null,
153
- tools: "none",
154
- credentials: false,
155
- hosted_fallback: false,
156
- };
157
- const decider_ref = `decider:${createHash("sha256")
158
- .update(JSON.stringify({ contract: PROMPT_DECISION_CONTRACT, ...base }))
159
- .digest("hex")
160
- .slice(0, 16)}`;
161
- return { contract: PROMPT_DECISION_CONTRACT, decider_ref, ...base };
162
- }
163
-
164
- function checkRequest({ prompt, candidates, requestRef }) {
165
- if (typeof prompt !== "string" || !prompt.trim())
166
- throw refusal("decider_input", "the prompt is empty");
167
- if (typeof requestRef !== "string" || !REF.test(requestRef))
168
- throw refusal("decider_input", "the request needs a ref");
169
- if (!Array.isArray(candidates) || !candidates.length)
170
- throw refusal("decider_input", "no candidates were offered");
171
- const seen = new Set();
172
- for (const candidate of candidates) {
173
- const wellFormed =
174
- allowedKeys(
175
- candidate,
176
- ["assignment_ref", "computer", "label", "capability_ref"],
177
- ["workspace"]
178
- ) &&
179
- REF.test(candidate.assignment_ref) &&
180
- candidate.assignment_ref !== "none" &&
181
- REF.test(candidate.capability_ref) &&
182
- typeof candidate.computer === "string" &&
183
- candidate.computer.trim() !== "" &&
184
- typeof candidate.label === "string" &&
185
- (candidate.workspace === undefined ||
186
- typeof candidate.workspace === "string");
187
- if (!wellFormed || seen.has(candidate.assignment_ref))
188
- throw refusal("decider_input", "a candidate is malformed or repeated");
189
- seen.add(candidate.assignment_ref);
190
- }
191
- }
192
-
193
- function outputSchema(candidates) {
194
- return {
195
- type: "object",
196
- additionalProperties: false,
197
- required: ["assignment_ref", "computer_source", "signoff"],
198
- properties: {
199
- assignment_ref: {
200
- type: "string",
201
- enum: [...candidates.map((c) => c.assignment_ref), "none"],
202
- },
203
- computer_source: {
204
- anyOf: [
205
- { type: "null" },
206
- {
207
- type: "object",
208
- additionalProperties: false,
209
- required: ["start", "end"],
210
- properties: {
211
- start: { type: "integer", minimum: 0 },
212
- end: { type: "integer", minimum: 1 },
213
- },
214
- },
215
- ],
216
- },
217
- signoff: { type: "boolean" },
218
- },
219
- };
220
- }
221
-
222
- /** The decision exactly as the model must have given it, or a refusal: never repaired, never defaulted. */
223
- function checkDecision(decision, { prompt, candidates }) {
224
- if (!exactKeys(decision, ["assignment_ref", "computer_source", "signoff"]))
225
- throw refusal("decider_output", "the decision does not have its shape");
226
- if (typeof decision.signoff !== "boolean")
227
- throw refusal("decider_output", "signoff is not a boolean");
228
- const chosen =
229
- decision.assignment_ref === "none"
230
- ? null
231
- : candidates.find((c) => c.assignment_ref === decision.assignment_ref);
232
- if (decision.assignment_ref !== "none" && !chosen)
233
- throw refusal("decider_output", "the decision chose an unoffered ref");
234
- const span = decision.computer_source;
235
- if (span !== null) {
236
- const valid =
237
- exactKeys(span, ["start", "end"]) &&
238
- Number.isInteger(span.start) &&
239
- Number.isInteger(span.end) &&
240
- span.start >= 0 &&
241
- span.end > span.start &&
242
- span.end <= prompt.length;
243
- if (!valid)
244
- throw refusal("decider_output", "computer_source is not a prompt span");
245
- if (
246
- chosen &&
247
- prompt.slice(span.start, span.end).toLowerCase() !==
248
- chosen.computer.toLowerCase()
249
- )
250
- throw refusal(
251
- "decider_output",
252
- "computer_source does not name the chosen computer"
253
- );
254
- }
255
- // A named computer is never silently swapped for another one.
256
- const lowered = prompt.toLowerCase();
257
- const named = candidates.some((c) =>
258
- lowered.includes(c.computer.toLowerCase())
259
- );
260
- if (chosen && named && span === null)
261
- throw refusal(
262
- "decider_output",
263
- "a computer was named but the decision did not cite it"
264
- );
265
- return {
266
- assignment_ref: decision.assignment_ref,
267
- computer_source:
268
- span === null ? null : { start: span.start, end: span.end },
269
- signoff: decision.signoff,
270
- };
271
- }
272
-
273
- const parseObject = (text) => {
274
- const trimmed = text
275
- .trim()
276
- .replace(/^```(?:json)?\s*\n([\s\S]*)\n```$/, "$1")
277
- .trim();
278
- try {
279
- return JSON.parse(trimmed);
280
- } catch {
281
- throw refusal("decider_output", "the reply is not one JSON object");
282
- }
283
- };
284
-
285
- const statePrompt = ({ prompt, candidates }) =>
286
- `STATE_JSON\n${JSON.stringify({ prompt, candidates })}`;
287
-
288
- async function askNative(settings, info, request, trace) {
289
- const text = `${INSTRUCTIONS}\n${statePrompt(request)}`;
290
- trace.sent = { prompt: text, model: settings.model };
291
- await askLocalAgent("claude-code", text, {
292
- executable: info.executable,
293
- isolated: true,
294
- model: settings.model,
295
- onResponse: (response) => {
296
- trace.response = response;
297
- },
298
- }).catch(() => {});
299
- const response = trace.response;
300
- if (!response)
301
- throw refusal("decider_transport", "Claude Code did not start");
302
- if (response.code !== 0)
303
- throw refusal(
304
- "decider_transport",
305
- `Claude Code exited with code ${response.code}`
306
- );
307
- let envelope;
308
- try {
309
- envelope = JSON.parse(response.stdout.trim());
310
- } catch {
311
- throw refusal("decider_output", "Claude Code did not answer in JSON");
312
- }
313
- if (envelope?.is_error === true || typeof envelope?.result !== "string")
314
- throw refusal("decider_output", "Claude Code reported no result");
315
- return parseObject(envelope.result);
316
- }
317
-
318
- function postLoopback(endpoint, body) {
319
- return new Promise((resolve, reject) => {
320
- const payload = Buffer.from(JSON.stringify(body));
321
- // node:http, not fetch: it never consults proxy settings or follows redirects, so the request stays on loopback.
322
- const request = http.request(
323
- endpoint,
324
- {
325
- method: "POST",
326
- agent: false,
327
- headers: {
328
- "content-type": "application/json",
329
- "content-length": payload.length,
330
- },
331
- },
332
- (response) => {
333
- const chunks = [];
334
- let size = 0;
335
- response.on("data", (chunk) => {
336
- size += chunk.length;
337
- if (size > MAX_REPLY_BYTES) {
338
- request.destroy(new Error("the reply is too large"));
339
- return;
340
- }
341
- chunks.push(chunk);
342
- });
343
- response.on("end", () =>
344
- resolve({
345
- status: response.statusCode,
346
- body: Buffer.concat(chunks).toString("utf8"),
347
- })
348
- );
349
- response.on("error", reject);
350
- }
351
- );
352
- request.on("error", reject);
353
- request.end(payload);
354
- });
355
- }
356
-
357
- async function askLoopback(settings, request, trace) {
358
- const body = {
359
- model: settings.model,
360
- messages: [
361
- { role: "system", content: INSTRUCTIONS },
362
- { role: "user", content: statePrompt(request) },
363
- ],
364
- response_format: {
365
- type: "json_schema",
366
- json_schema: {
367
- name: "prompt_decision",
368
- strict: true,
369
- schema: outputSchema(request.candidates),
370
- },
371
- },
372
- stream: false,
373
- };
374
- trace.sent = { endpoint: settings.endpoint, body };
375
- try {
376
- trace.response = await postLoopback(settings.endpoint, body);
377
- } catch (error) {
378
- trace.response = { error: error.message };
379
- throw refusal(
380
- "decider_transport",
381
- `the local model failed: ${error.message}`
382
- );
383
- }
384
- if (trace.response.status !== 200)
385
- throw refusal(
386
- "decider_transport",
387
- `the local model answered HTTP ${trace.response.status}`
388
- );
389
- let completion;
390
- try {
391
- completion = JSON.parse(trace.response.body);
392
- } catch {
393
- throw refusal("decider_output", "the local model did not answer in JSON");
394
- }
395
- const choice = completion?.choices?.[0];
396
- if (
397
- completion?.choices?.length !== 1 ||
398
- choice?.finish_reason !== "stop" ||
399
- choice?.message?.tool_calls?.length ||
400
- typeof choice?.message?.content !== "string"
401
- )
402
- throw refusal(
403
- "decider_output",
404
- "the local model did not finish with one plain answer"
405
- );
406
- return parseObject(choice.message.content);
407
- }
408
-
409
- /**
410
- * The prompt decider. `configuration()` returns the owner-local config, read at every call so a model swap needs
411
- * no restart; `record(raw)` receives, for every select, the original prompt and candidates, what was sent, the raw
412
- * reply and the outcome, including failures, before select settles. A select makes at most one model call and never
413
- * retries: a lost reply may still have been charged.
414
- */
415
- export function createPromptDecider({ configuration, record }) {
416
- return {
417
- /** Which decider would answer, with no inference: { ok: true, ... } or { ok: false, code, error }. */
418
- info() {
419
- try {
420
- return { ok: true, ...describe(readSettings(configuration())) };
421
- } catch (error) {
422
- if (!error.refused) throw error;
423
- return { ok: false, code: error.code, error: error.message };
424
- }
425
- },
426
- /**
427
- * Resolves exactly { assignment_ref, computer_source, signoff }, assignment_ref being an offered ref or "none".
428
- * Rejects with an Error carrying `code` and `refused: true` when the decider is unavailable, the input is
429
- * malformed, or the reply is not a safe decision.
430
- */
431
- async select({ prompt, candidates, requestRef }) {
432
- const trace = {
433
- contract: PROMPT_DECISION_CONTRACT,
434
- requestRef,
435
- prompt,
436
- candidates,
437
- decider: null,
438
- sent: null,
439
- response: null,
440
- decision: null,
441
- refusal: null,
442
- at: new Date().toISOString(),
443
- };
444
- try {
445
- checkRequest({ prompt, candidates, requestRef });
446
- const settings = readSettings(configuration());
447
- const info = describe(settings);
448
- trace.decider = info;
449
- const request = { prompt, candidates };
450
- const answer =
451
- settings.transport === "native-claude"
452
- ? await askNative(settings, info, request, trace)
453
- : await askLoopback(settings, request, trace);
454
- trace.decision = checkDecision(answer, request);
455
- return trace.decision;
456
- } catch (error) {
457
- trace.refusal = {
458
- code: error.code ?? "decider_error",
459
- message: error.message,
460
- };
461
- throw error.refused
462
- ? error
463
- : Object.assign(refusal("decider_error", error.message), {
464
- cause: error,
465
- });
466
- } finally {
467
- record(trace);
468
- }
469
- },
470
- };
471
- }