benignswarm 0.12.164 → 0.12.165
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/antigravity.js +10 -4
- package/dist/args.js +5 -3
- package/dist/build-caches.js +1 -1
- package/dist/client.js +83 -36
- package/dist/command-flags.js +2 -2
- package/dist/commands/codex-start.js +35 -10
- package/dist/commands/flow-agent.js +82 -0
- package/dist/commands/hook.js +23 -5
- package/dist/commands/lock-run.js +7 -15
- package/dist/commands/machine.js +176 -49
- package/dist/commands/mock.js +64 -0
- package/dist/commands/watch.js +5 -3
- package/dist/commands/wu.js +116 -8
- package/dist/config.js +5 -7
- package/dist/errors.js +3 -1
- package/dist/git-sandbox-paths.js +12 -1
- package/dist/git.js +19 -9
- package/dist/harnesses.js +5 -2
- package/dist/help.js +19 -5
- package/dist/index.js +7 -2
- package/dist/machine-network-health.js +50 -0
- package/dist/machine-processes.js +2 -2
- package/dist/machine-report.js +1 -1
- package/dist/merge-train.js +400 -42
- package/dist/model.js +42 -14
- package/dist/scratch-cleanup.js +468 -0
- package/dist/ux-jobs.js +329 -66
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/antigravity.js
CHANGED
|
@@ -6,7 +6,7 @@ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "no
|
|
|
6
6
|
import { configRoot } from "./config.js";
|
|
7
7
|
import { repoDirectory } from "./directories.js";
|
|
8
8
|
import { CliError } from "./errors.js";
|
|
9
|
-
import { gitSandboxDeniedPaths, gitSandboxReadablePaths, gitSandboxWritablePaths, sandboxProbeWorktreeAdminPath } from "./git-sandbox-paths.js";
|
|
9
|
+
import { gitSandboxDeniedPaths, gitSandboxReadablePaths, gitSandboxWorktreeMetadataPath, gitSandboxWritablePaths, sandboxProbeWorktreeAdminPath } from "./git-sandbox-paths.js";
|
|
10
10
|
export const ANTIGRAVITY_SETTINGS_PLACEHOLDER = "__B9S_ANTIGRAVITY_TURN_SETTINGS__";
|
|
11
11
|
export function isAntigravityWorkspaceWrite(env = process.env) {
|
|
12
12
|
return env.BSCHAT_HARNESS === "antigravity" && env.BSCHAT_ANTIGRAVITY_SANDBOX === "workspace-write";
|
|
@@ -87,6 +87,7 @@ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritabl
|
|
|
87
87
|
throw new CliError("sandbox_root_too_broad", "Antigravity workspace-write refuses a writable root that contains the checkout or home directory; configure the exact writable folder instead");
|
|
88
88
|
}
|
|
89
89
|
const additionalCheckouts = unitWorktree ? [{ label: `WU #${unitWorktree.number} worktree`, path: unitWorktree.path }] : [];
|
|
90
|
+
const unitWorktreeMetadata = unitWorktree ? gitSandboxWorktreeMetadataPath(unitWorktree.path) : null;
|
|
90
91
|
const gitPaths = gitSandboxWritablePaths(absoluteCwd, additionalCheckouts);
|
|
91
92
|
const gitReadPaths = gitSandboxReadablePaths(absoluteCwd, additionalCheckouts);
|
|
92
93
|
const exactGitFiles = new Set(["packed-refs", "packed-refs.lock", "FETCH_HEAD", "FETCH_HEAD.lock", "HEAD", "HEAD.lock", "index", "index.lock", "COMMIT_EDITMSG"]);
|
|
@@ -115,7 +116,11 @@ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritabl
|
|
|
115
116
|
return [
|
|
116
117
|
"--sandbox", "--settings",
|
|
117
118
|
JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow, deny } }),
|
|
118
|
-
...
|
|
119
|
+
...[...new Set([
|
|
120
|
+
...beside,
|
|
121
|
+
...(unitWorktree ? [resolve(unitWorktree.path)] : []),
|
|
122
|
+
...(unitWorktreeMetadata ? [unitWorktreeMetadata] : []),
|
|
123
|
+
])].flatMap((dir) => ["--add-dir", dir]),
|
|
119
124
|
];
|
|
120
125
|
}
|
|
121
126
|
export function antigravityTurnArgs(prompt, model, effort, timeoutSeconds, settings, conversation) {
|
|
@@ -214,6 +219,7 @@ export function runAntigravityTurn(bin, args, logPath, cwd, agent, expectedConve
|
|
|
214
219
|
exit_code: result.status,
|
|
215
220
|
...(expectedConversation ? { expected_conversation: expectedConversation } : {}),
|
|
216
221
|
...(model ? { model } : {}),
|
|
222
|
+
...(effort ? { effort } : {}),
|
|
217
223
|
...(parsed ? { result: parsed } : { raw: [output, result.stderr].filter(Boolean).join("\n").slice(-4000) }),
|
|
218
224
|
};
|
|
219
225
|
recordAntigravityTurn(logPath, record);
|
|
@@ -228,8 +234,8 @@ export function antigravityResumeCommand(bin, session, model, effort, timeoutSec
|
|
|
228
234
|
const tmp = `${logPath}.pending`;
|
|
229
235
|
const err = `${logPath}.stderr`;
|
|
230
236
|
const base = [bin, "-p", "{text}", "--output-format", "json", "--model", model, ...(effort ? ["--effort", effort] : []), "--print-timeout", `${timeoutSeconds}s`, "--conversation", session, ...settings].map((arg) => arg === "{text}" ? arg : shq(arg)).join(" ");
|
|
231
|
-
const script = `const fs=require('node:fs');const [tmp,err,log,status,started,expected,model]=process.argv.slice(1);const raw=fs.readFileSync(tmp,'utf8');const stderr=fs.readFileSync(err,'utf8');let result;try{result=JSON.parse(raw)}catch{}const record={started_at:started,finished_at:new Date().toISOString(),exit_code:Number(status),expected_conversation:expected,model,...(result?{result}:{raw:(raw+'\\n'+stderr).slice(-4000)})};fs.appendFileSync(log,JSON.stringify(record)+'\\n',{mode:0o600});fs.rmSync(tmp,{force:true});fs.rmSync(err,{force:true});`;
|
|
232
|
-
const node = `${shq(process.execPath)} -e ${shq(script)} ${shq(tmp)} ${shq(err)} ${shq(logPath)} "$agy_status" "$agy_started" ${shq(session)} ${shq(model)}`;
|
|
237
|
+
const script = `const fs=require('node:fs');const [tmp,err,log,status,started,expected,model,effort]=process.argv.slice(1);const raw=fs.readFileSync(tmp,'utf8');const stderr=fs.readFileSync(err,'utf8');let result;try{result=JSON.parse(raw)}catch{}const record={started_at:started,finished_at:new Date().toISOString(),exit_code:Number(status),expected_conversation:expected,model,...(effort?{effort}:{}),...(result?{result}:{raw:(raw+'\\n'+stderr).slice(-4000)})};fs.appendFileSync(log,JSON.stringify(record)+'\\n',{mode:0o600});fs.rmSync(tmp,{force:true});fs.rmSync(err,{force:true});`;
|
|
238
|
+
const node = `${shq(process.execPath)} -e ${shq(script)} ${shq(tmp)} ${shq(err)} ${shq(logPath)} "$agy_status" "$agy_started" ${shq(session)} ${shq(model)} ${shq(effort ?? "")}`;
|
|
233
239
|
return `agy_started=$(date -u +%Y-%m-%dT%H:%M:%SZ); ${base} > ${shq(tmp)} 2> ${shq(err)}; agy_status=$?; ${node}; exit "$agy_status"`;
|
|
234
240
|
}
|
|
235
241
|
function agyRecords(path) {
|
package/dist/args.js
CHANGED
|
@@ -8,7 +8,7 @@ export const LIST_FLAGS = [
|
|
|
8
8
|
"reworks", "confirm-causes", "processes", "cache", "caches", "root", "signing-key", "machines",
|
|
9
9
|
];
|
|
10
10
|
export const STRING_FLAGS = [
|
|
11
|
-
"as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task",
|
|
11
|
+
"as", "admin", "key", "url", "label", "level", "model", "since", "limit", "after", "topic", "goal", "task",
|
|
12
12
|
"state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions",
|
|
13
13
|
"cardinality", "assign-outside-qualifications", "judges", "machine", "idempotency-key", "dir", "confirm", "impact-revision", "type",
|
|
14
14
|
"name", "out", "token", "token-file", "job", "gate-command", "gate-override-note", "head", "baseline", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to",
|
|
@@ -23,7 +23,7 @@ export const STRING_FLAGS = [
|
|
|
23
23
|
"require-pushed", "require-gate-receipt", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email",
|
|
24
24
|
"repeat", "summary-minutes", "quota-share-threshold", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on",
|
|
25
25
|
"flow-summary", "flow-min-age", "flow-min-impact", "checkout", "unit-worktree", "sibling-checkout", "api", "nonce",
|
|
26
|
-
"sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
|
|
26
|
+
"sandbox", "subagents", "subagent-model", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
|
|
27
27
|
"plain", "if-yes", "if-no", "ssh", "variant", "count", "min", "max", "needs", "min-ram", "exclude", "carry", "from",
|
|
28
28
|
"to-ssh", "ssh-from", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires", "with",
|
|
29
29
|
"priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect",
|
|
@@ -37,7 +37,7 @@ export const STRING_FLAGS = [
|
|
|
37
37
|
"purpose", "storage-mode", "hosts", "arn", "version-id", "kms-key",
|
|
38
38
|
"mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class", "route",
|
|
39
39
|
"expires-at", "conflicts-with", "source-channel-id", "source-message-id", "plain-summary",
|
|
40
|
-
"metadata-file", "confirm-agent", "confirm-parked", "step", "compare", "merge-candidate", "outcome",
|
|
40
|
+
"choices", "choice", "metadata-file", "confirm-agent", "confirm-parked", "step", "compare", "merge-candidate", "outcome",
|
|
41
41
|
];
|
|
42
42
|
export const BOOL_FLAGS = [
|
|
43
43
|
"latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
|
|
@@ -63,6 +63,8 @@ export function parse(argv) {
|
|
|
63
63
|
// replacement command needs its value. Resolve that spelling by command.
|
|
64
64
|
if (argv[0] === "wu" && argv[1] === "reviewer")
|
|
65
65
|
options.replace = { type: "string" };
|
|
66
|
+
if ((argv[0] === "mock" || argv[0] === "design-study") && argv[1] === "gaps")
|
|
67
|
+
options.json = { type: "string" };
|
|
66
68
|
try {
|
|
67
69
|
const seen = new Set();
|
|
68
70
|
const negativeBooleans = new Set();
|
package/dist/build-caches.js
CHANGED
|
@@ -441,7 +441,7 @@ function processAlive(pid) {
|
|
|
441
441
|
}
|
|
442
442
|
}
|
|
443
443
|
/** Computes total logical size and most recent modification time under a directory without following symlinks. */
|
|
444
|
-
function measurePath(target) {
|
|
444
|
+
export function measurePath(target) {
|
|
445
445
|
let bytes = 0;
|
|
446
446
|
let mtimeMs = 0;
|
|
447
447
|
const stack = [target];
|
package/dist/client.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { CliError, WrittenReceiptMismatchError } from "./errors.js";
|
|
3
3
|
import { collectAuto, machineIdentityForAgent } from "./git.js";
|
|
4
4
|
import { resolveEffort } from "./model.js";
|
|
5
|
+
import { readState, updateState } from "./state.js";
|
|
5
6
|
import { cliUserAgent } from "./legacy-alias.js";
|
|
6
7
|
import { noteServerVersions } from "./update.js";
|
|
7
8
|
function expectedTextReceiptFields(method, path, body, response) {
|
|
@@ -364,8 +365,14 @@ export class Client {
|
|
|
364
365
|
* by the hook or the watcher, which say nothing about whether the agent is alive.
|
|
365
366
|
*/
|
|
366
367
|
static forAgent(c, model, opts = {}) {
|
|
367
|
-
const
|
|
368
|
-
|
|
368
|
+
const ref = `${c.project ?? "account"}/${c.agent}`;
|
|
369
|
+
const observedEffort = c.vendor === "antigravity" ? readState(ref).effort ?? null : null;
|
|
370
|
+
const effort = resolveEffort(opts.effort, process.env, c.vendor, process.cwd(), observedEffort);
|
|
371
|
+
if (c.vendor === "antigravity" && effort !== "unknown" && (opts.effort || process.env.BSCHAT_EFFORT) && effort !== observedEffort) {
|
|
372
|
+
updateState(ref, (state) => ({ ...state, effort, effort_observed_at: Date.now() }));
|
|
373
|
+
}
|
|
374
|
+
const auto = collectAuto({ model, machine: machineIdentityForAgent(c.machine), effort, provider: process.env.BSCHAT_PROVIDER, harness: c.vendor });
|
|
375
|
+
return new Client(c.url, c.key, opts.presence === false ? null : { ...auto }, c.agent, opts.machineIdentity ? auto.machine : null, { requestTimeoutMs: opts.requestTimeoutMs, retryForMs: opts.retryForMs, onRequest: opts.onRequest });
|
|
369
376
|
}
|
|
370
377
|
static forAdmin(c) {
|
|
371
378
|
return new Client(c.url, c.key, null);
|
|
@@ -377,14 +384,14 @@ export class Client {
|
|
|
377
384
|
const signals = [this.requestOptions.signal, external].filter((signal) => Boolean(signal));
|
|
378
385
|
return signals.length > 1 ? AbortSignal.any(signals) : signals[0];
|
|
379
386
|
}
|
|
380
|
-
requestSignal(external) {
|
|
387
|
+
requestSignal(external, timeoutMs = this.requestOptions.requestTimeoutMs) {
|
|
381
388
|
const callerSignal = this.callerSignal(external);
|
|
382
|
-
const timeout =
|
|
389
|
+
const timeout = timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined;
|
|
383
390
|
const signals = [callerSignal, timeout].filter((signal) => Boolean(signal));
|
|
384
391
|
return { signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0], timeout };
|
|
385
392
|
}
|
|
386
|
-
timeoutError(method, path) {
|
|
387
|
-
return new CliError("request_timeout", `${method} ${path} timed out after ${
|
|
393
|
+
timeoutError(method, path, timeoutMs = this.requestOptions.requestTimeoutMs) {
|
|
394
|
+
return new CliError("request_timeout", `${method} ${path} timed out after ${timeoutMs}ms`);
|
|
388
395
|
}
|
|
389
396
|
headers(autoOverride) {
|
|
390
397
|
const h = { authorization: `Bearer ${this.key}`, "user-agent": cliUserAgent() };
|
|
@@ -417,11 +424,10 @@ export class Client {
|
|
|
417
424
|
return response;
|
|
418
425
|
}
|
|
419
426
|
/**
|
|
420
|
-
* opts.retries
|
|
421
|
-
*
|
|
422
|
-
* GET/HEAD
|
|
423
|
-
*
|
|
424
|
-
* and non-idempotent POST 500 stays fail-fast even when marked retryable.
|
|
427
|
+
* opts.retries opts an idempotent request into a fixed number of retries. retryForMs (or the
|
|
428
|
+
* client-level equivalent) opts it into bounded-window retries, including per-attempt timeouts.
|
|
429
|
+
* Without either opt-in, GET/HEAD and transient overload/gateway responses retain the
|
|
430
|
+
* platform-wide bounded retry policy; non-idempotent POST 500 remains fail-fast.
|
|
425
431
|
*/
|
|
426
432
|
async call(method, path, body, opts = {}) {
|
|
427
433
|
const headers = this.headers(opts.auto);
|
|
@@ -433,30 +439,61 @@ export class Client {
|
|
|
433
439
|
const overloadRetries = Math.max(explicitRetries, DEFAULT_OVERLOAD_RETRIES);
|
|
434
440
|
const sleep = opts.sleepFn ?? sleepWithAbort;
|
|
435
441
|
const retrySignal = this.callerSignal(opts.signal);
|
|
442
|
+
const retryWindowMs = opts.retryForMs ?? this.requestOptions.retryForMs;
|
|
443
|
+
let retryWindowSpentMs = 0;
|
|
444
|
+
const remainingRetryWindowMs = () => retryWindowMs === undefined ? Number.POSITIVE_INFINITY : retryWindowMs - retryWindowSpentMs;
|
|
445
|
+
const canRetry = (attempt, maxAttempts) => retryWindowMs === undefined ? attempt < maxAttempts : remainingRetryWindowMs() > 0;
|
|
446
|
+
const waitBeforeRetry = async (attempt, retryAfterSeconds) => {
|
|
447
|
+
let delayMs = computeBackoffMs(attempt, retryAfterSeconds);
|
|
448
|
+
if (retryWindowMs !== undefined) {
|
|
449
|
+
const remainingMs = remainingRetryWindowMs();
|
|
450
|
+
if (remainingMs <= 1)
|
|
451
|
+
return false;
|
|
452
|
+
// Reserve at least one millisecond for the next attempt; if that attempt fails,
|
|
453
|
+
// the next wait sees the exhausted deadline and stops without another retry.
|
|
454
|
+
delayMs = Math.min(delayMs, Math.max(0, remainingMs - 1));
|
|
455
|
+
}
|
|
456
|
+
if (delayMs > 0)
|
|
457
|
+
await sleep(delayMs, retrySignal);
|
|
458
|
+
retryWindowSpentMs += delayMs;
|
|
459
|
+
return retryWindowMs === undefined || remainingRetryWindowMs() > 0;
|
|
460
|
+
};
|
|
436
461
|
for (let attempt = 0;; attempt++) {
|
|
437
462
|
let res;
|
|
438
463
|
let text;
|
|
439
464
|
const startedAt = Date.now();
|
|
440
|
-
const
|
|
441
|
-
|
|
465
|
+
const configuredTimeoutMs = opts.requestTimeoutMs ?? this.requestOptions.requestTimeoutMs;
|
|
466
|
+
const remainingRetryMs = remainingRetryWindowMs();
|
|
467
|
+
const requestTimeoutMs = retryWindowMs === undefined
|
|
468
|
+
? configuredTimeoutMs
|
|
469
|
+
: Math.max(1, Math.min(configuredTimeoutMs ?? 30_000, remainingRetryMs));
|
|
470
|
+
const { signal, timeout } = this.requestSignal(opts.signal, requestTimeoutMs);
|
|
471
|
+
const requestPath = path.split("?", 1)[0] ?? path;
|
|
472
|
+
this.requestOptions.onRequest?.({ phase: "start", method, path: requestPath, attempt: attempt + 1 });
|
|
442
473
|
try {
|
|
443
474
|
res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal });
|
|
444
475
|
text = await res.text();
|
|
445
476
|
}
|
|
446
477
|
catch (e) {
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
478
|
+
retryWindowSpentMs += Date.now() - startedAt;
|
|
479
|
+
const failure = timeout?.aborted ? "timeout" : e.message;
|
|
480
|
+
const networkRetries = retryWindowMs !== undefined ? Number.POSITIVE_INFINITY : isRead ? overloadRetries : explicitRetries;
|
|
481
|
+
const willRetry = canRetry(attempt, networkRetries);
|
|
482
|
+
process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (network error)${willRetry ? "; retrying" : "; retry window exhausted"}\n`);
|
|
483
|
+
this.requestOptions.onRequest?.({ phase: "end", method, path: requestPath, attempt: attempt + 1, durationMs: Date.now() - startedAt, error: failure });
|
|
450
484
|
if (this.requestOptions.signal?.aborted || opts.signal?.aborted)
|
|
451
485
|
throw new CliError("request_aborted", `${method} ${path} aborted before completion`);
|
|
452
|
-
|
|
453
|
-
if (attempt < networkRetries) {
|
|
454
|
-
await sleep(computeBackoffMs(attempt), retrySignal);
|
|
486
|
+
if (willRetry && await waitBeforeRetry(attempt))
|
|
455
487
|
continue;
|
|
456
|
-
|
|
488
|
+
if (timeout?.aborted)
|
|
489
|
+
throw this.timeoutError(method, path, requestTimeoutMs);
|
|
490
|
+
if (retrySignal?.aborted)
|
|
491
|
+
throw new CliError("request_aborted", `${method} ${path} aborted before completion`);
|
|
457
492
|
throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
|
|
458
493
|
}
|
|
459
|
-
|
|
494
|
+
retryWindowSpentMs += Date.now() - startedAt;
|
|
495
|
+
const requestFailure = !res.ok && res.status >= 500 ? `http_${res.status}` : undefined;
|
|
496
|
+
this.requestOptions.onRequest?.({ phase: "end", method, path: requestPath, attempt: attempt + 1, durationMs: Date.now() - startedAt, ...(requestFailure ? { error: requestFailure } : {}) });
|
|
460
497
|
noteServerVersions(res.headers, this.agentName);
|
|
461
498
|
let json;
|
|
462
499
|
try {
|
|
@@ -464,28 +501,35 @@ export class Client {
|
|
|
464
501
|
}
|
|
465
502
|
catch {
|
|
466
503
|
const transient = isTransientOverloadResponse(res.status, undefined, text, isRead, res.headers);
|
|
467
|
-
const maxAttempts = transient ? overloadRetries : explicitRetries;
|
|
468
|
-
if (res.status >= 500 && attempt
|
|
469
|
-
const
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
504
|
+
const maxAttempts = retryWindowMs !== undefined ? Number.POSITIVE_INFINITY : transient ? overloadRetries : explicitRetries;
|
|
505
|
+
if (res.status >= 500 && canRetry(attempt, maxAttempts)) {
|
|
506
|
+
const retryAfter = parseRetryAfterSeconds(res.headers.get("retry-after"));
|
|
507
|
+
const retrying = await waitBeforeRetry(attempt, retryAfter);
|
|
508
|
+
process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (${requestFailure})${retrying ? "; retrying" : "; retry window exhausted"}\n`);
|
|
509
|
+
if (retrying)
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
if (!res.ok && res.status >= 500) {
|
|
513
|
+
process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (${requestFailure}); retry window exhausted\n`);
|
|
514
|
+
throw new CliError(`http_${res.status}`, `${method} ${path} failed (${res.status}): ${text.slice(0, 200)}`, undefined, res.status);
|
|
473
515
|
}
|
|
474
516
|
throw new CliError("bad_response", `${method} ${path} returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
|
|
475
517
|
}
|
|
476
518
|
if (!res.ok) {
|
|
477
519
|
// Explicit opts.retries marks idempotent POST callers (e.g. client_id / lock job_token);
|
|
478
520
|
// default POST calls without opts.retries stay fail-fast on 500 even if marked retryable.
|
|
479
|
-
const nonIdempotentPost500 = upperMethod === "POST" && res.status === 500 && explicitRetries === 0;
|
|
521
|
+
const nonIdempotentPost500 = upperMethod === "POST" && res.status === 500 && explicitRetries === 0 && retryWindowMs === undefined;
|
|
480
522
|
const transient = isTransientOverloadResponse(res.status, json, text, isRead, res.headers);
|
|
481
|
-
const maxAttempts = transient ? overloadRetries : explicitRetries;
|
|
482
|
-
if (res.status >= 500 && !nonIdempotentPost500 && attempt
|
|
523
|
+
const maxAttempts = retryWindowMs !== undefined ? Number.POSITIVE_INFINITY : transient ? overloadRetries : explicitRetries;
|
|
524
|
+
if (res.status >= 500 && !nonIdempotentPost500 && canRetry(attempt, maxAttempts)) {
|
|
483
525
|
const retryAfter = parseRetryAfterSeconds(res.headers.get("retry-after")) ?? (typeof json?.retry_after === "number" ? json.retry_after : undefined);
|
|
484
|
-
const
|
|
485
|
-
process.stderr.write(`b9s: ${method} ${
|
|
486
|
-
|
|
487
|
-
|
|
526
|
+
const retrying = await waitBeforeRetry(attempt, retryAfter);
|
|
527
|
+
process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (${requestFailure})${retrying ? "; retrying" : "; retry window exhausted"}\n`);
|
|
528
|
+
if (retrying)
|
|
529
|
+
continue;
|
|
488
530
|
}
|
|
531
|
+
if (requestFailure)
|
|
532
|
+
process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (${requestFailure}); retry window exhausted\n`);
|
|
489
533
|
const err = json;
|
|
490
534
|
const hint = res.status >= 500
|
|
491
535
|
? `This is a platform failure, not something to fix on your side. Do not retry in a loop. Report it once: b9s feedback "<what you were doing>${err.reference ? ` ref ${err.reference}` : ""}" and carry on with other work.`
|
|
@@ -604,8 +648,11 @@ export function computeBackoffMs(attempt, retryAfterSeconds, random = Math.rando
|
|
|
604
648
|
function sleepWithAbort(ms, signal) {
|
|
605
649
|
if (signal?.aborted)
|
|
606
650
|
return Promise.reject(new CliError("request_aborted", "request aborted during retry backoff"));
|
|
607
|
-
const
|
|
608
|
-
const
|
|
651
|
+
const rawCap = process.env.B9S_TEST_RETRY_SLEEP_MS;
|
|
652
|
+
const testCap = rawCap !== undefined && rawCap !== "" ? Number(rawCap) : NaN;
|
|
653
|
+
const actualMs = Number.isFinite(testCap) && testCap >= 0 ? Math.min(ms, testCap) : ms;
|
|
654
|
+
if (actualMs <= 0)
|
|
655
|
+
return Promise.resolve();
|
|
609
656
|
return new Promise((resolve, reject) => {
|
|
610
657
|
const onAbort = () => {
|
|
611
658
|
clearTimeout(timer);
|
package/dist/command-flags.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { CliError } from "./errors.js";
|
|
2
2
|
const AGENT_GLOBAL_FLAGS = new Set(["as", "effort", "help", "json", "model", "version"]);
|
|
3
3
|
const ADMIN_GLOBAL_FLAGS = new Set(["admin", "as", "help", "json", "version"]);
|
|
4
|
-
const OPTION_CONTRACT_ALIASES = new Map([["ask", "ask-operator"]]);
|
|
4
|
+
const OPTION_CONTRACT_ALIASES = new Map([["ask", "ask-operator"], ["design-study", "mock"]]);
|
|
5
5
|
const INHERITED_OPTION_CONTRACTS = new Map([["codex start", ["start"]]]);
|
|
6
6
|
const PROJECT_COMMANDS = new Set([
|
|
7
|
-
"notice", "who", "send", "read", "channel", "agents", "activity", "feed", "evidence", "retire", "handoffs", "lists", "list", "item",
|
|
7
|
+
"mock", "design-study", "flow-agent", "notice", "who", "send", "read", "channel", "agents", "activity", "feed", "evidence", "retire", "handoffs", "lists", "list", "item",
|
|
8
8
|
"wu", "process", "record", "milestones", "milestone", "lock", "unlock", "locks", "ask", "ask-operator",
|
|
9
9
|
"explain", "worktrees", "measures", "measure", "environment", "test-results", "ux", "gate",
|
|
10
10
|
]);
|
|
@@ -14,7 +14,7 @@ import { readState, updateState } from "../state.js";
|
|
|
14
14
|
import { join } from "./join.js";
|
|
15
15
|
import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService, parseWorkUnitBindingResponse, prepareTurnWorktree, preparedWorktreePromptLines, resolveWatcherWorkUnitBinding, turnArgs, watch } from "./watch.js";
|
|
16
16
|
import { randomUUID } from "node:crypto";
|
|
17
|
-
import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, inspectCurrentClaudeEgressCapability, probeFor } from "../harnesses.js";
|
|
17
|
+
import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeSubagentModelEnv, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, inspectCurrentClaudeEgressCapability, probeFor } from "../harnesses.js";
|
|
18
18
|
import { allocateClaudeEgressPortPair, resolveTrustedControlPlaneOrigin, spawnClaudeEgressSupervised } from "../claude-egress-proxy.js";
|
|
19
19
|
import { claudeTurnEnv } from "../providers.js";
|
|
20
20
|
import { DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR } from "../turn-guard.js";
|
|
@@ -26,6 +26,22 @@ import { checkAndRecordHarnessBinary } from "../machine-binary.js";
|
|
|
26
26
|
import { clearSessionSecrets, normalizeAndValidateSecretHosts, parseSecretHostsJson, parseSecretKeyNamesJson, SECRET_DECLARED_HOSTS_VAR, SECRET_EGRESS_ENV_KEYS_VAR, wipeSecretMap, writeSessionSecrets, } from "../session-secrets.js";
|
|
27
27
|
const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
|
|
28
28
|
export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
|
|
29
|
+
const SUBAGENT_MODES = ["default", "encourage", "disabled"];
|
|
30
|
+
export function subagentStartupHint(harness, mode, model) {
|
|
31
|
+
const modeIsAdvisory = (mode === "encourage" && harness !== "codex")
|
|
32
|
+
|| (mode === "disabled" && harness !== "claude-code" && harness !== "codex");
|
|
33
|
+
const modelIsAdvisory = Boolean(model && harness !== "claude-code");
|
|
34
|
+
if (!modeIsAdvisory && !modelIsAdvisory)
|
|
35
|
+
return null;
|
|
36
|
+
const instructions = [];
|
|
37
|
+
if (modeIsAdvisory && mode === "disabled")
|
|
38
|
+
instructions.push("do not delegate to subagents");
|
|
39
|
+
if (modeIsAdvisory && mode === "encourage")
|
|
40
|
+
instructions.push("use native subagents for cleanly separable subtasks when useful, parallelize research or disjoint files, then integrate and verify the result yourself");
|
|
41
|
+
if (modelIsAdvisory)
|
|
42
|
+
instructions.push(`prefer subagent model ${model} when the harness supports it`);
|
|
43
|
+
return `Advisory only; this harness does not enforce this subagent preference: ${instructions.join("; ")}.`;
|
|
44
|
+
}
|
|
29
45
|
/** The guard states why it refuses. A refusal without a reason is still a refusal (no turn starts) and is reported as the defect it is. */
|
|
30
46
|
function refusalReason(diagnostic) {
|
|
31
47
|
return diagnostic.at(-1) ?? "the turn guard refused this turn without stating why; that is a CLI defect, report it with b9s feedback";
|
|
@@ -123,6 +139,13 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
|
|
|
123
139
|
const name = str(p.flags, "as");
|
|
124
140
|
if (!name)
|
|
125
141
|
throw new CliError("usage", `${cmd} needs --as <agent-name>`);
|
|
142
|
+
const subagentsValue = str(p.flags, "subagents") ?? "default";
|
|
143
|
+
if (!SUBAGENT_MODES.includes(subagentsValue))
|
|
144
|
+
throw new CliError("usage", "--subagents must be default, encourage, or disabled");
|
|
145
|
+
const subagents = subagentsValue;
|
|
146
|
+
const subagentModel = str(p.flags, "subagent-model");
|
|
147
|
+
if (subagentModel !== undefined && (!subagentModel.trim() || subagentModel.length > 100))
|
|
148
|
+
throw new CliError("usage", "--subagent-model must be a non-empty model identifier of at most 100 characters");
|
|
126
149
|
const machineSessionId = str(p.flags, "machine-session-id");
|
|
127
150
|
if (machineSessionId && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(machineSessionId))
|
|
128
151
|
throw new CliError("usage", "--machine-session-id must be a UUID");
|
|
@@ -242,12 +265,12 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
|
|
|
242
265
|
const writable = startWritableRoots(sandbox, machineWritable, explicitWritable);
|
|
243
266
|
// Refuses a sandbox the harness cannot honour before anything is enrolled.
|
|
244
267
|
const preflightSettings = harness === "codex"
|
|
245
|
-
? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
|
|
268
|
+
? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())], subagents)
|
|
246
269
|
: harness === "dsh"
|
|
247
270
|
? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
|
|
248
|
-
: harness === "claude-code" ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable) : [];
|
|
271
|
+
: harness === "claude-code" ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, undefined, undefined, subagents) : [];
|
|
249
272
|
let settings = preflightSettings;
|
|
250
|
-
const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) };
|
|
273
|
+
const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "claude-code" ? claudeSubagentModelEnv(subagentModel) : {}) };
|
|
251
274
|
// 1. Who: enroll with the invite token, or use credentials already on this machine.
|
|
252
275
|
const lines = [];
|
|
253
276
|
const token = str(p.flags, "token");
|
|
@@ -284,7 +307,7 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
|
|
|
284
307
|
httpProxyPort,
|
|
285
308
|
socksProxyPort,
|
|
286
309
|
};
|
|
287
|
-
settings = claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, undefined, claudeSecretEgress);
|
|
310
|
+
settings = claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, undefined, claudeSecretEgress, subagents);
|
|
288
311
|
}
|
|
289
312
|
if (harness === "antigravity") {
|
|
290
313
|
if (inContainer)
|
|
@@ -381,11 +404,11 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
|
|
|
381
404
|
const onboardingUnit = onboardingWorktree ? { number: onboardingWorktree.number, path: onboardingWorktree.path } : undefined;
|
|
382
405
|
const onboardingCwd = onboardingWorktree?.path ?? process.cwd();
|
|
383
406
|
const onboardingPreflightSettings = harness === "claude-code" && sandbox === "workspace-write" && onboardingUnit
|
|
384
|
-
? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, onboardingUnit)
|
|
407
|
+
? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, onboardingUnit, undefined, subagents)
|
|
385
408
|
: preflightSettings;
|
|
386
409
|
if (onboardingUnit) {
|
|
387
410
|
if (harness === "claude-code") {
|
|
388
|
-
settings = claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, onboardingUnit, claudeSecretEgress);
|
|
411
|
+
settings = claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, onboardingUnit, claudeSecretEgress, subagents);
|
|
389
412
|
}
|
|
390
413
|
else if (harness === "antigravity") {
|
|
391
414
|
settings = antigravitySettings(sandbox, process.cwd(), configRoot(), new URL(creds.url).host, [...writable, onboardingUnit.path], install.bin, process.execPath, ref, onboardingUnit);
|
|
@@ -405,6 +428,7 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
|
|
|
405
428
|
`Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
|
|
406
429
|
`Now: run \`b9s me\`, \`b9s process\` and \`b9s inbox --unread\`, then do what your role and inbox ask.`,
|
|
407
430
|
`If you ran on another machine before, read your latest note first: \`b9s handoffs --agent ${creds.agent}\` (your units, branches and chat are on the server as before).`,
|
|
431
|
+
...(subagentStartupHint(harness, subagents, subagentModel) ? [subagentStartupHint(harness, subagents, subagentModel)] : []),
|
|
408
432
|
...(onboardingWorktree ? preparedWorktreePromptLines(onboardingWorktree, "b9s start") : []),
|
|
409
433
|
].join("\n");
|
|
410
434
|
const diagnostic = [];
|
|
@@ -489,9 +513,9 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
|
|
|
489
513
|
mkdirSync(tmp, { recursive: true });
|
|
490
514
|
const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
|
|
491
515
|
const prune = bool(p.flags, "prune");
|
|
492
|
-
watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin, antigravityTmp), ...(antigravityTmpSessionKey ? { BSCHAT_ANTIGRAVITY_TMP_SESSION_KEY: antigravityTmpSessionKey } : {}), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
|
|
516
|
+
watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? { ...claudeSandboxEnv(sandbox), ...claudeSubagentModelEnv(subagentModel) } : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin, antigravityTmp), ...(antigravityTmpSessionKey ? { BSCHAT_ANTIGRAVITY_TMP_SESSION_KEY: antigravityTmpSessionKey } : {}), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
|
|
493
517
|
const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model,
|
|
494
|
-
...(harness === "claude-code" && sandbox === "workspace-write" ? { claudeRuntime: { sandbox, ...(effort ? { effort } : {}), writableRoots: writable, maxBudgetUsd, ...(claudeSecretEgress ? { secretEgress: { declaredHosts: claudeSecretEgress.declaredHosts, apiUrl: creds.url, envKeys: incomingSecretKeys, ...(!inContainer && secretSessionKey ? { sessionKey: secretSessionKey } : {}) } } : {}) } } : {}),
|
|
518
|
+
...(harness === "claude-code" && sandbox === "workspace-write" ? { claudeRuntime: { sandbox, ...(effort ? { effort } : {}), writableRoots: writable, maxBudgetUsd, subagents, ...(subagentModel ? { subagentModel } : {}), ...(claudeSecretEgress ? { secretEgress: { declaredHosts: claudeSecretEgress.declaredHosts, apiUrl: creds.url, envKeys: incomingSecretKeys, ...(!inContainer && secretSessionKey ? { sessionKey: secretSessionKey } : {}) } } : {}) } } : {}),
|
|
495
519
|
...(harness === "antigravity" && sandbox === "workspace-write" ? { antigravityRuntime: { sandbox, apiHost: new URL(creds.url).host, b9sBin: install.bin, nodeBin: process.execPath, writableRoots: writable, tmpSessionKey: antigravityTmpSessionKey, tmpDir: antigravityTmp } } : {}),
|
|
496
520
|
...(machineSessionId ? { machineSessionId } : {}) };
|
|
497
521
|
if (inContainer && claudeSecretEgress) {
|
|
@@ -865,10 +889,11 @@ export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, se
|
|
|
865
889
|
* the API and write its own b9s state (~/.b9s), and `wu start` puts unit worktrees beside the
|
|
866
890
|
* checkout, so those two places are writable and the network is on; nothing else is.
|
|
867
891
|
*/
|
|
868
|
-
export function codexSettings(sandbox, model, effort, cwd, bschatHome, extraWritable = []) {
|
|
892
|
+
export function codexSettings(sandbox, model, effort, cwd, bschatHome, extraWritable = [], subagents = "default") {
|
|
869
893
|
return [
|
|
870
894
|
...(model ? ["-m", model] : []),
|
|
871
895
|
...(effort ? ["-c", `model_reasoning_effort="${effort}"`] : []),
|
|
896
|
+
...(subagents === "disabled" ? ["-c", "features.multi_agent=false"] : subagents === "encourage" ? ["-c", "features.multi_agent=true", "-c", "agents.max_depth=1"] : []),
|
|
872
897
|
"-c", `sandbox_mode="${sandbox}"`,
|
|
873
898
|
"-c", `approval_policy="never"`,
|
|
874
899
|
...(sandbox === "workspace-write"
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { str } from "../args.js";
|
|
2
|
+
import { Client } from "../client.js";
|
|
3
|
+
import { loadAgent, resolveAgentName, loadAdmin, resolveAdminName } from "../config.js";
|
|
4
|
+
import { CliError } from "../errors.js";
|
|
5
|
+
import { projectOf } from "./agent.js";
|
|
6
|
+
export const FLOW_AGENT_LEVELS = ["advisory", "flow_ops", "autonomous_ops"];
|
|
7
|
+
const MAY = {
|
|
8
|
+
advisory: [
|
|
9
|
+
"Read the board, units, statuses and the merge train.",
|
|
10
|
+
"Post a structured diagnosis and a proposal in chat: what is stuck, why, and the one change that would move it.",
|
|
11
|
+
"Mutating unit, routing or pool endpoints are refused at this level; do not try them.",
|
|
12
|
+
],
|
|
13
|
+
flow_ops: [
|
|
14
|
+
"Everything advisory may do.",
|
|
15
|
+
"Reassign a stalled unit's owner, replace a quiet or non-approving reviewer.",
|
|
16
|
+
"Clear a wait that has resolved, unpark a ready unit, enqueue an approved unit on the merge train.",
|
|
17
|
+
"Remove one false --after edge, naming the edge and giving a reason; keep the others.",
|
|
18
|
+
],
|
|
19
|
+
autonomous_ops: [
|
|
20
|
+
"Everything flow_ops may do.",
|
|
21
|
+
"Set priority or expedite within the project's urgent_cap.",
|
|
22
|
+
"Split or rebalance a unit within the configured split bounds; a split child carries the registered split relationship.",
|
|
23
|
+
],
|
|
24
|
+
};
|
|
25
|
+
/** The parameterized system prompt for one autonomy level. Pure, so it is tested per level. */
|
|
26
|
+
export function flowAgentPrompt(level, limits) {
|
|
27
|
+
const may = MAY[level].map((line) => `- ${line}`).join("\n");
|
|
28
|
+
return `You are this project's Flow Agent, at autonomy level ${level}.
|
|
29
|
+
Your job is flow: keep work moving through the process without doing the work, the review or the merge yourself.
|
|
30
|
+
|
|
31
|
+
Hard invariants (every level; the server refuses these with 403):
|
|
32
|
+
- Never approve a unit, request changes, or close one as done.
|
|
33
|
+
- Never lift an operator hold.
|
|
34
|
+
- Never touch billing, authentication or production data.
|
|
35
|
+
|
|
36
|
+
At ${level} you may:
|
|
37
|
+
${may}
|
|
38
|
+
|
|
39
|
+
Limits: at most ${limits.max_turns_per_hour} turns per hour and $${limits.daily_budget_usd} per day. Check b9s flow-agent status before acting; when either is used up, stop and say so.
|
|
40
|
+
|
|
41
|
+
Operating loop, once per wake-up:
|
|
42
|
+
1. Read the triggers in the wake-up message, then b9s flow-agent status.
|
|
43
|
+
2. For each trigger, look at the unit or chain it names (b9s wu show <n>) and decide whether anything is actually stuck.
|
|
44
|
+
3. Take the smallest action your level allows that unblocks it, with a reason a person can follow; otherwise post the diagnosis and the proposal.
|
|
45
|
+
4. Do not repeat an action the status shows you already took for the same situation.
|
|
46
|
+
5. End the turn with one chat message listing what you did and what you left for others.`;
|
|
47
|
+
}
|
|
48
|
+
export async function flowAgent(p, out) {
|
|
49
|
+
const sub = p.positionals[1];
|
|
50
|
+
if (sub !== "status" && sub !== "prompt" && sub !== "run")
|
|
51
|
+
throw new CliError("usage", "flow-agent status | flow-agent prompt [--level advisory|flow_ops|autonomous_ops]");
|
|
52
|
+
if (sub === "run") {
|
|
53
|
+
const project = str(p.flags, "project") ?? process.env.BSCHAT_PROJECT ?? projectOf(p, loadAgent(resolveAgentName(str(p.flags, "as"))));
|
|
54
|
+
const client = Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
|
|
55
|
+
const result = await client.call("POST", `/projects/${encodeURIComponent(project)}/flow-agent/run`, { force: p.flags.force === true });
|
|
56
|
+
out.print("Flow Agent run requested.", result);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const creds = loadAgent(resolveAgentName(str(p.flags, "as")));
|
|
60
|
+
if (!creds.project)
|
|
61
|
+
throw new CliError("usage", "flow-agent needs a project agent; account agents pass --project <name>");
|
|
62
|
+
const project = creds.project;
|
|
63
|
+
const client = Client.forAgent(creds, str(p.flags, "model"));
|
|
64
|
+
const s = await client.call("GET", `/projects/${project}/flow-agent/status`);
|
|
65
|
+
if (sub === "status") {
|
|
66
|
+
const recent = (s.recent_actions ?? []);
|
|
67
|
+
const lines = [
|
|
68
|
+
`flow agent: ${s.enabled ? "enabled" : "disabled"} · ${s.autonomy_level}`,
|
|
69
|
+
`turns this hour: ${s.turns_this_hour}/${s.max_turns_per_hour} · spend today: $${Number(s.spend_today_usd).toFixed(2)}/$${s.daily_budget_usd}`,
|
|
70
|
+
`last run: ${s.last_run_at ?? "never"}`,
|
|
71
|
+
...recent.slice(0, 10).map((a) => ` ${a.at} ${a.kind}${a.unit_number === null ? "" : ` #${a.unit_number}`}${a.outcome ? ` (${a.outcome})` : ""}: ${a.summary}`),
|
|
72
|
+
];
|
|
73
|
+
out.print(lines.join("\n"), s);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const requested = str(p.flags, "level");
|
|
77
|
+
if (requested !== undefined && !FLOW_AGENT_LEVELS.includes(requested))
|
|
78
|
+
throw new CliError("usage", `--level must be one of ${FLOW_AGENT_LEVELS.join(", ")}`);
|
|
79
|
+
const level = (requested ?? s.autonomy_level);
|
|
80
|
+
const text = flowAgentPrompt(level, { daily_budget_usd: s.daily_budget_usd, max_turns_per_hour: s.max_turns_per_hour });
|
|
81
|
+
out.print(text, { autonomy_level: level, enabled: s.enabled, prompt: text });
|
|
82
|
+
}
|
package/dist/commands/hook.js
CHANGED
|
@@ -25,6 +25,28 @@ function readStdinJson() {
|
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
const THROTTLE_MS = 20_000;
|
|
28
|
+
/** Store only values the Antigravity runtime explicitly reports in its hook payload. */
|
|
29
|
+
export function rememberAntigravityRuntime(ref, input, env = process.env) {
|
|
30
|
+
const state = readState(ref, env);
|
|
31
|
+
const observation = (value) => {
|
|
32
|
+
if (typeof value !== "string")
|
|
33
|
+
return null;
|
|
34
|
+
const normalized = value.trim();
|
|
35
|
+
return normalized && normalized.toLowerCase() !== "unknown" ? normalized : null;
|
|
36
|
+
};
|
|
37
|
+
const model = observation(input.modelName);
|
|
38
|
+
const effort = [input.reasoningEffort, input.reasoning_effort, input.effort]
|
|
39
|
+
.map(observation)
|
|
40
|
+
.find((value) => value !== null) ?? null;
|
|
41
|
+
if ((!model || state.model === model) && (!effort || state.effort === effort))
|
|
42
|
+
return;
|
|
43
|
+
const observedAt = Date.now();
|
|
44
|
+
updateState(ref, (onDisk) => ({
|
|
45
|
+
...onDisk,
|
|
46
|
+
...(model ? { model, model_observed_at: observedAt } : {}),
|
|
47
|
+
...(effort ? { effort, effort_observed_at: observedAt } : {}),
|
|
48
|
+
}), env);
|
|
49
|
+
}
|
|
28
50
|
function omitMeasuresAlreadyIn(text, updates) {
|
|
29
51
|
if (!text || !updates)
|
|
30
52
|
return updates;
|
|
@@ -716,11 +738,7 @@ async function antigravityHook(p, payload) {
|
|
|
716
738
|
}
|
|
717
739
|
if (typeof input?.transcriptPath === "string" && input.transcriptPath)
|
|
718
740
|
noteSession(name, "antigravity", input.transcriptPath, conv, event === "SessionStart" && input?.source === "compact");
|
|
719
|
-
|
|
720
|
-
const observed = input.modelName;
|
|
721
|
-
if (readState(name).model !== observed)
|
|
722
|
-
updateState(name, (onDisk) => ({ ...onDisk, model: observed, model_observed_at: Date.now() }));
|
|
723
|
-
}
|
|
741
|
+
rememberAntigravityRuntime(name, input ?? {});
|
|
724
742
|
const st = readState(name);
|
|
725
743
|
if (Date.now() - (st.heartbeat_at ?? 0) > HEARTBEAT_MS) {
|
|
726
744
|
try {
|
|
@@ -22,18 +22,8 @@ function processIsRunning(pid) {
|
|
|
22
22
|
throw error;
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
|
-
/**
|
|
26
|
-
|
|
27
|
-
* the job's token, so a repeat is the same request. A release that failed once during a database
|
|
28
|
-
* overload left the lock held with no process behind it (two build hosts' suite locks sat held for
|
|
29
|
-
* 45 minutes), and a failed poll ended a job that was only waiting its turn. The release keeps
|
|
30
|
-
* trying for about two minutes, the others for about 40 seconds; after that the failure is
|
|
31
|
-
* reported as before, naming the job. If a release was applied and only its answer was lost, the
|
|
32
|
-
* repeat is refused (the job no longer holds the lock) and reported: the lock is free then.
|
|
33
|
-
*/
|
|
34
|
-
export function lockRunRetries(path) {
|
|
35
|
-
return path.endsWith("/release") ? 20 : 8;
|
|
36
|
-
}
|
|
25
|
+
/** All lock-run reports carry the stable job token and may safely retry for the lease grace. */
|
|
26
|
+
export const LOCK_RUN_RETRY_WINDOW_MS = 5 * 60_000;
|
|
37
27
|
export function createSupervisorRecordReader(onRecord, log) {
|
|
38
28
|
let pending = "";
|
|
39
29
|
const consume = (line) => {
|
|
@@ -111,7 +101,7 @@ export async function runUnderLock(o, deps) {
|
|
|
111
101
|
return result;
|
|
112
102
|
}
|
|
113
103
|
catch (error) {
|
|
114
|
-
throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: ${unlockCommand(o)}
|
|
104
|
+
throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: ${unlockCommand(o)}`, undefined, error);
|
|
115
105
|
}
|
|
116
106
|
};
|
|
117
107
|
let r = await deps.call("POST", `${base}/acquire`, { ...acquireBody });
|
|
@@ -150,9 +140,11 @@ export async function runUnderLock(o, deps) {
|
|
|
150
140
|
}
|
|
151
141
|
const startedMs = now();
|
|
152
142
|
const slot = Number.isInteger(r.slot) ? Number(r.slot) : undefined;
|
|
153
|
-
|
|
143
|
+
const countedLock = o.lock === "ux-browser" || o.lock === "complete-suite";
|
|
144
|
+
const capacity = Number.isSafeInteger(r.lock?.capacity) ? Number(r.lock.capacity) : undefined;
|
|
145
|
+
if (countedLock && (slot === undefined || slot < 1 || capacity === undefined || slot > capacity)) {
|
|
154
146
|
await release();
|
|
155
|
-
throw new CliError("lock_protocol_mismatch",
|
|
147
|
+
throw new CliError("lock_protocol_mismatch", `The server did not assign a valid ${o.lock} slot; the command was not started. Inspect the lock state: b9s locks`);
|
|
156
148
|
}
|
|
157
149
|
let code;
|
|
158
150
|
try {
|