@staix/agent-hub 0.39.0 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/README.md +12 -6
- package/docs/adding-an-ai-tool.md +1 -1
- package/docs/agent-notes/README.md +7 -0
- package/docs/agent-notes/adapters.md +5 -3
- package/docs/agent-notes/benchmarks.md +2 -0
- package/docs/agent-notes/budget.md +1 -0
- package/docs/agent-notes/bus.md +1 -0
- package/docs/agent-notes/daemon.md +8 -3
- package/docs/agent-notes/local-worker.md +3 -1
- package/docs/agent-notes/security-review.md +1 -0
- package/docs/agent-notes/tasks.md +7 -2
- package/docs/agent-notes/tests.md +7 -7
- package/docs/contracts/companion-cli-v1.json +4 -0
- package/docs/design/adapters.md +91 -0
- package/docs/design/agent-hub-architecture.md +17 -0
- package/docs/design/agent-hub.md +10 -0
- package/docs/design/bus.md +7 -0
- package/docs/design/cli-output.md +183 -0
- package/docs/design/execution-reference.md +6 -1
- package/docs/design/roadmap.md +191 -0
- package/docs/design/task-board.md +34 -0
- package/docs/dogfood.md +11 -4
- package/docs/events.md +4 -4
- package/docs/memory.md +3 -3
- package/docs/operations.md +153 -41
- package/docs/profiles.md +1 -0
- package/docs/quickstart.md +17 -4
- package/docs/sdlc.md +3 -1
- package/docs/security.md +40 -4
- package/docs/verification/2026-11-14-codex-0169-reviewer-isolation.md +70 -0
- package/docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md +48 -0
- package/docs/verification/2026-11-14-pi-152-compat.md +45 -0
- package/docs/verification/2026-11-15-0.40.0.md +39 -0
- package/docs/verification/2026-11-16-pi-loopback-1447.md +39 -0
- package/docs/verification/pi-152-model-free.ts +57 -0
- package/docs/verification/pi-152-native.mjs +21 -0
- package/docs/verified.json +22 -22
- package/package.json +3 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +332 -89
- package/plugins/agent-hub/kimi-review-policy-worker.js +16 -11
- package/plugins/agent-hub/server.js +417 -160
- package/src/adapters/agy/definition.ts +1 -1
- package/src/adapters/claude-channel.ts +1 -1
- package/src/adapters/codex-review-isolation.ts +61 -17
- package/src/adapters/compat.ts +7 -7
- package/src/adapters/definitions/builtin-metadata.ts +6 -6
- package/src/adapters/definitions/native-config-defaults.ts +1 -1
- package/src/adapters/definitions/native-config-policy.ts +1 -1
- package/src/adapters/definitions/qwen.ts +1 -1
- package/src/adapters/local-worker.ts +5 -3
- package/src/adapters/pi.ts +54 -11
- package/src/adapters/registry-types.ts +2 -1
- package/src/adapters/reviewer-print.ts +2 -1
- package/src/cli/answer-args.ts +11 -3
- package/src/cli/console-question.ts +1 -1
- package/src/cli/console-state.ts +95 -10
- package/src/cli/console.ts +6 -2
- package/src/cli/error-format.ts +19 -0
- package/src/cli/help.ts +290 -25
- package/src/cli/identity-audit.ts +8 -7
- package/src/cli/identity.ts +17 -0
- package/src/cli/init.ts +102 -9
- package/src/cli/main.js +2 -2
- package/src/cli/main.ts +57 -21
- package/src/cli/output-standard.ts +56 -0
- package/src/cli/output.ts +143 -8
- package/src/cli/roadmap.ts +215 -0
- package/src/cli/smoke-pty-bridge.ts +7 -24
- package/src/cli/task-output.ts +3 -1
- package/src/cli/upgrade-presentation-flags.ts +2 -2
- package/src/hub/board.ts +200 -3
- package/src/hub/bus.ts +9 -0
- package/src/hub/check-runner.ts +3 -4
- package/src/hub/ci-watch.ts +19 -4
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +245 -43
- package/src/hub/events.ts +2 -2
- package/src/hub/execution-reference.ts +1 -1
- package/src/hub/github-import.ts +81 -0
- package/src/hub/hub-tools.ts +34 -9
- package/src/hub/install-policy.ts +23 -0
- package/src/hub/lifecycle-schema.ts +2 -2
- package/src/hub/no-writes.ts +3 -0
- package/src/hub/operational-authority.ts +3 -1
- package/src/hub/operational-view.ts +1 -1
- package/src/hub/pi-failure.ts +7 -0
- package/src/hub/question-desk.ts +26 -7
- package/src/hub/questions.ts +33 -5
- package/src/hub/restart.ts +7 -0
- package/src/hub/roadmap-triage.ts +86 -0
- package/src/hub/roadmap-unplaced.ts +169 -0
- package/src/hub/roadmap-view.ts +83 -0
- package/src/hub/roadmap.ts +127 -0
- package/src/hub/sdlc-merge.ts +5 -4
- package/src/hub/sdlc-queue.ts +3 -3
- package/src/hub/sdlc.ts +37 -2
- package/src/hub/specs-task.ts +7 -0
- package/src/hub/task-sweep.ts +29 -2
- package/src/hub/task-worktree.ts +37 -0
- package/src/hub/tasks.ts +381 -7
- package/src/pi/dependency-publish.ts +50 -0
- package/src/pi/extension.ts +1 -1
- package/src/pi/launch.ts +1 -1
- package/src/pi/task-dependencies.ts +249 -0
- package/src/ui/index.html +53 -13
- package/src/ui/plugin-questions.ts +5 -0
- package/src/ui/plugin.ts +6 -1
- package/templates/config.json +1 -1
package/src/cli/init.ts
CHANGED
|
@@ -3,7 +3,8 @@ import { initShadow, repoOf } from "../hub/snapshots.ts";
|
|
|
3
3
|
import { PROFILE_NAMES, profileName, projectProfile, resolveProfile, mergeProfileOverrides, type ProfileName } from "../hub/profiles.ts";
|
|
4
4
|
import { canonicalJson, loadPacks, packOverrides, type DomainPack } from "../hub/packs.ts";
|
|
5
5
|
import { JCODE_MCP_FILE } from "./jcode-mcp.ts";
|
|
6
|
-
import { closeSync, constants, fstatSync, openSync, readSync, existsSync, lstatSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync, renameSync } from "node:fs";
|
|
6
|
+
import { closeSync, constants, fstatSync, openSync, readSync, existsSync, lstatSync, mkdirSync, mkdtempSync, rmSync, readFileSync, statSync, unlinkSync, writeFileSync, renameSync } from "node:fs";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
7
8
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
8
9
|
import { spawnSync } from "node:child_process";
|
|
9
10
|
import type { Stats } from "node:fs";
|
|
@@ -60,6 +61,68 @@ export function ignoreRule(cwd: string, path: string): string | null | undefined
|
|
|
60
61
|
const [source, line, pattern] = r.stdout.split("\0");
|
|
61
62
|
return pattern === undefined || pattern.startsWith("!") ? null : `${source}:${line}:${pattern}`;
|
|
62
63
|
}
|
|
64
|
+
const SHARED_IGNORE_BEGIN = "# agent-hub shared config (managed by ahub init)";
|
|
65
|
+
const SHARED_IGNORE_END = "# end agent-hub shared config";
|
|
66
|
+
/** One exact-line parser for replacement and removal; malformed ownership is never guessed. */
|
|
67
|
+
function sharedIgnoreBlock(text: string): { start: number; end: number; eol: string; newline: boolean } | undefined {
|
|
68
|
+
let start: number | undefined, end: number | undefined, offset = 0;
|
|
69
|
+
let eol = "\n", newline = false;
|
|
70
|
+
const malformed = () => new Error("--track-config: incomplete or duplicate managed shared-config ignore markers; repair the marker pair in the project .gitignore and retry ahub init; nothing was written");
|
|
71
|
+
for (const line of text.match(/[^\n]*(?:\n|$)/g) ?? []) {
|
|
72
|
+
const value = line.replace(/\r?\n$/, "");
|
|
73
|
+
if (value === SHARED_IGNORE_BEGIN) {
|
|
74
|
+
if (start !== undefined) throw malformed();
|
|
75
|
+
start = offset; eol = line.endsWith("\r\n") ? "\r\n" : "\n";
|
|
76
|
+
} else if (value === SHARED_IGNORE_END) {
|
|
77
|
+
if (start === undefined || end !== undefined) throw malformed();
|
|
78
|
+
end = offset + line.length; newline = line.endsWith("\n");
|
|
79
|
+
}
|
|
80
|
+
offset += line.length;
|
|
81
|
+
}
|
|
82
|
+
if ((start === undefined) !== (end === undefined)) throw malformed();
|
|
83
|
+
return start === undefined || end === undefined ? undefined : { start, end, eol, newline };
|
|
84
|
+
}
|
|
85
|
+
function sharedIgnoreRepository(cwd: string, unknown = false): { gitDir: string; root: string } | undefined {
|
|
86
|
+
const git = hubGitSync(["rev-parse", "--absolute-git-dir", "--show-toplevel"], { cwd, env: { ...process.env, LC_ALL: "C" }, encoding: "utf8", timeout: 3000 });
|
|
87
|
+
if (git.status !== 0 && git.stderr?.startsWith("fatal: not a git repository")) return;
|
|
88
|
+
if (git.status !== 0 || unknown) throw new Error("--track-config: git could not determine repository ignore rules; run git status and retry ahub init; nothing was written");
|
|
89
|
+
const [gitDir, root] = git.stdout.trim().split("\n");
|
|
90
|
+
if (!gitDir || !root) throw new Error("--track-config: git did not identify the repository paths; run git status and retry ahub init; nothing was written");
|
|
91
|
+
return { gitDir, root: realPath(root) };
|
|
92
|
+
}
|
|
93
|
+
/** Git evaluates planned project rules in a disposable worktree; the real index/config are never written. */
|
|
94
|
+
function verifySharedIgnores(cwd: string, text: string, tracked: readonly string[], repository: ReturnType<typeof sharedIgnoreRepository>): void {
|
|
95
|
+
if (!repository || repository.root !== realPath(cwd)) return;
|
|
96
|
+
const { gitDir } = repository;
|
|
97
|
+
const excludes = hubGitSync(["config", "--path", "--get", "core.excludesFile"], { cwd, encoding: "utf8", timeout: 3000 });
|
|
98
|
+
if (excludes.status !== 0 && excludes.status !== 1) throw new Error("--track-config: git could not read the excludes-file setting; run git config --get core.excludesFile and retry ahub init; nothing was written");
|
|
99
|
+
const excludeArgs = excludes.status === 0 ? ["-c", `core.excludesFile=${resolve(cwd, excludes.stdout.trim())}`] : [];
|
|
100
|
+
let scratch: string | undefined;
|
|
101
|
+
try {
|
|
102
|
+
scratch = mkdtempSync(join(tmpdir(), "ahub-init-ignore-"));
|
|
103
|
+
scratch = realPath(scratch);
|
|
104
|
+
writeFileSync(join(scratch, ".gitignore"), text);
|
|
105
|
+
mkdirSync(join(scratch, ".agenthub"));
|
|
106
|
+
const nested = join(cwd, ".agenthub", ".gitignore");
|
|
107
|
+
if (existsSync(nested)) writeFileSync(join(scratch, ".agenthub", ".gitignore"), readFileSync(nested, "utf8"));
|
|
108
|
+
const protectedPaths = [".agenthub/state/", ".agenthub/config.local.json", ".agenthub/routing.local.toml", ...SHARED_CONFIG.filter(name => !tracked.includes(name)).map(name => `.agenthub/${name}`)];
|
|
109
|
+
for (const path of [...tracked.map(name => `.agenthub/${name}`), ...protectedPaths]) {
|
|
110
|
+
const verdict = hubGitSync([...excludeArgs, `--git-dir=${gitDir}`, `--work-tree=${scratch}`, "check-ignore", "-v", "-z", "--no-index", "--stdin"], { cwd: scratch, encoding: "utf8", timeout: 3000, input: `${path}\0` });
|
|
111
|
+
if (verdict.status !== 0 && verdict.status !== 1) throw new Error("git could not evaluate the planned ignore rules; run git status and retry ahub init");
|
|
112
|
+
const [source, line, pattern] = verdict.stdout.split("\0");
|
|
113
|
+
const ignored = verdict.status === 0 && pattern !== undefined && !pattern.startsWith("!");
|
|
114
|
+
if (tracked.includes(path.slice(".agenthub/".length)) ? ignored : !ignored)
|
|
115
|
+
throw new Error(`${path} ${ignored ? `is ignored by ${source}:${line}:${pattern}` : "would be exposed by the planned rules"}; change the project ignore rule and retry ahub init`);
|
|
116
|
+
}
|
|
117
|
+
} catch (error) {
|
|
118
|
+
// File/read errors may contain private paths; only git verdicts above expose the existing rule location.
|
|
119
|
+
if (error instanceof Error && (error.message.startsWith(".agenthub/") || error.message.startsWith("git could not"))) throw new Error(`--track-config: ${error.message}; nothing was written`);
|
|
120
|
+
throw new Error("--track-config: could not prepare the disposable ignore preview; check temporary-directory and project ignore-file permissions, then retry ahub init; nothing was written");
|
|
121
|
+
} finally {
|
|
122
|
+
if (scratch) try { rmSync(scratch, { recursive: true, force: true }); }
|
|
123
|
+
catch { throw new Error("--track-config: could not remove the disposable ignore preview; check temporary-directory permissions before retrying ahub init; nothing was written"); }
|
|
124
|
+
}
|
|
125
|
+
}
|
|
63
126
|
/** #1411 (owner comment): `hub_routes` keys that name this machine's endpoints; routing.local.toml cannot hold them yet, so a routing.toml that sets one stays untracked. */
|
|
64
127
|
function routingMachineKeys(cwd: string): string[] {
|
|
65
128
|
const path = join(cwd, ".agenthub", "routing.toml");
|
|
@@ -316,18 +379,46 @@ function changes(cwd: string, requestedName?: string, shadow = false, releaseGua
|
|
|
316
379
|
for (const entry of tracked.size ? AGY_PLUGIN_FILES.filter(file => !tracked.has(file)) : [agyPlugin]) add(entry);
|
|
317
380
|
}
|
|
318
381
|
if (existsSync(join(cwd, JCODE_MCP_FILE)) && hubGitSync(["ls-files", "--error-unmatch", "--", JCODE_MCP_FILE], { cwd, encoding: "utf8", timeout: 3000 }).status !== 0) add(JCODE_MCP_FILE);
|
|
319
|
-
// #
|
|
320
|
-
// which stays ignored until the local overlay can hold it. Untracked: each file is ignored unless git already ignores it.
|
|
382
|
+
// #1496: append owned re-inclusions instead of changing project or outside ignore rules.
|
|
321
383
|
const track = settings?.values[TRACK_CONFIG];
|
|
384
|
+
let ignoreReason = track === false ? "ignore runtime state, machine-local configuration and the per-checkout hub config" : "ignore runtime state and machine-local configuration";
|
|
322
385
|
if (track === true) {
|
|
386
|
+
const tracked = SHARED_CONFIG.filter(name => !(name === "routing.toml" && routingMachineKeys(cwd).length));
|
|
387
|
+
const rules = tracked.map(name => ignoreRule(cwd, `.agenthub/${name}`));
|
|
388
|
+
const repository = sharedIgnoreRepository(cwd, rules.some(rule => rule === undefined));
|
|
389
|
+
if (repository && repository.root !== realPath(cwd)) {
|
|
390
|
+
for (const [index, rule] of rules.entries()) if (rule) {
|
|
391
|
+
const path = `.agenthub/${tracked[index]}`;
|
|
392
|
+
throw new Error(`--track-config: ${path} is ignored by ${rule}; change that line so git sees the file (after a directory rule such as .agenthub/, add !/.agenthub/, /.agenthub/* and !/${path}), then run ahub init again; nothing was written`);
|
|
393
|
+
}
|
|
394
|
+
if (routingMachineKeys(cwd).length) add(".agenthub/routing.toml");
|
|
395
|
+
} else {
|
|
396
|
+
const owned = sharedIgnoreBlock(lines);
|
|
397
|
+
if (rules.some(Boolean) || owned) {
|
|
398
|
+
const entries = ["!/.agenthub/", "/.agenthub/*", ...tracked.map(name => `!/.agenthub/${name}`)];
|
|
399
|
+
const eol = owned?.eol ?? (lines.includes("\r\n") ? "\r\n" : "\n");
|
|
400
|
+
const block = [SHARED_IGNORE_BEGIN, ...entries, SHARED_IGNORE_END].join(eol);
|
|
401
|
+
lines = owned
|
|
402
|
+
? lines.slice(0, owned.start) + block + (owned.newline ? eol : "") + lines.slice(owned.end)
|
|
403
|
+
: `${lines}${lines && !lines.endsWith("\n") ? eol : ""}${block}${eol}`;
|
|
404
|
+
const ruleClass = rules.some(rule => rule?.includes("/info/exclude:")) ? "repository info/exclude"
|
|
405
|
+
: rules.some(rule => rule && !rule.startsWith(".gitignore:") && !rule.startsWith(".agenthub/")) ? "global excludes" : "project ignore";
|
|
406
|
+
ignoreReason = `re-include shared config over ${ruleClass} rules in project .gitignore: ${entries.join(", ")}`;
|
|
407
|
+
} else if (routingMachineKeys(cwd).length) add(".agenthub/routing.toml");
|
|
408
|
+
verifySharedIgnores(cwd, lines, tracked, repository);
|
|
409
|
+
}
|
|
410
|
+
} else if (track === false) {
|
|
411
|
+
const owned = sharedIgnoreBlock(lines);
|
|
412
|
+
if (owned) lines = lines.slice(0, owned.start) + lines.slice(owned.end);
|
|
323
413
|
for (const name of SHARED_CONFIG) {
|
|
324
|
-
const
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
414
|
+
const entry = `.agenthub/${name}`;
|
|
415
|
+
// Existing owned negations must not suppress a new ignore line before the block is removed.
|
|
416
|
+
if (owned && !lines.split("\n").includes(entry)) lines += `${lines && !lines.endsWith("\n") ? "\n" : ""}${entry}\n`;
|
|
417
|
+
else add(entry);
|
|
328
418
|
}
|
|
329
|
-
|
|
330
|
-
|
|
419
|
+
if (owned) verifySharedIgnores(cwd, lines, [], sharedIgnoreRepository(cwd));
|
|
420
|
+
}
|
|
421
|
+
if (lines || existsSync(ignore)) write(ignore, lines, ignoreReason);
|
|
331
422
|
// #1065 T1: the settings table. config.json is the text it will have after the template and pack writes above; the rest is what is on disk.
|
|
332
423
|
let settingRows: InitSettingRow[] = [];
|
|
333
424
|
if (settings && (Object.keys(settings.values).length)) {
|
|
@@ -434,6 +525,8 @@ export function initNextSteps(cwd: string, settings?: InitSettingsRequest): stri
|
|
|
434
525
|
untrack(committed(SHARED_CONFIG));
|
|
435
526
|
} else if (track === true) {
|
|
436
527
|
// #1411: the files to commit, and what must not go in with them.
|
|
528
|
+
const ignorePlan = planInit(cwd, undefined, false, false, settings).find(change => change.path === join(cwd, ".gitignore") && change.reason.startsWith("re-include"));
|
|
529
|
+
if (ignorePlan) lines.push(`- ${ignorePlan.reason}.`);
|
|
437
530
|
const endpoints = routingMachineKeys(cwd);
|
|
438
531
|
const files = SHARED_CONFIG.filter(name => !(name === "routing.toml" && endpoints.length) && (name !== "sdlc.toml" || existsSync(join(cwd, ".agenthub", name)) || mode !== "off"));
|
|
439
532
|
lines.push(`- Review and commit AGENTS.md and ${files.map(name => `.agenthub/${name}`).join(", ")}; keep config.local.json untracked.`);
|
package/src/cli/main.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// Keep this entrypoint plain JavaScript: Node must fail before loading TypeScript or bun:sqlite.
|
|
3
3
|
const version = /^(\d+)\.(\d+)\.(\d+)$/.exec(process.versions.bun ?? "");
|
|
4
|
-
if (!version || !(Number(version[1]) > 1 || (Number(version[1]) === 1 && (Number(version[2]) > 4 || (Number(version[2]) === 4 && Number(version[3]) >=
|
|
5
|
-
console.error("ahub: Bun >=1.4.
|
|
4
|
+
if (!version || !(Number(version[1]) > 1 || (Number(version[1]) === 1 && (Number(version[2]) > 4 || (Number(version[2]) === 4 && Number(version[3]) >= 4))))) {
|
|
5
|
+
console.error("ahub: Bun >=1.4.4 is required. Install Bun: https://bun.sh");
|
|
6
6
|
process.exit(1);
|
|
7
7
|
}
|
|
8
8
|
|
package/src/cli/main.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { runtimePruneHealth } from "../hub/runtime-prune-health.ts";
|
|
|
4
4
|
import { conductorLocalOperation, conductorOperation, OPERATIONAL_PERSON_GUIDANCE } from "../hub/operational-authority.ts";
|
|
5
5
|
import { sayRecipients } from "./say-input.ts";
|
|
6
6
|
import { parseAnswerArgs } from "./answer-args.ts";
|
|
7
|
+
import { parseRoadmapArgs, renderRoadmap } from "./roadmap.ts";
|
|
7
8
|
import type { DeliverableRow } from "../hub/tasks.ts";
|
|
8
9
|
import { kimiSourceRow } from "../hub/budget-notes.ts";
|
|
9
10
|
import { hubGitSync, hubGitEnv } from "../hub/git.ts";
|
|
@@ -133,9 +134,10 @@ import { agentShellCause, classifyPeerCommand, cliCommandLabel, detectCliIdentit
|
|
|
133
134
|
import { recordCliAudit, recordDelegatedCliAudit } from "./identity-audit.ts";
|
|
134
135
|
import { runConsole } from "./console.ts";
|
|
135
136
|
import { installedVersions } from "./console-versions.ts";
|
|
136
|
-
import {
|
|
137
|
+
import { errorLines, failureExitCode } from "./error-format.ts";
|
|
138
|
+
import { asciiMarkers, paint, permissionBoundary, resolveColor, streamEnv, wrap, type Span } from "./console-state.ts";
|
|
137
139
|
import { queueResolveArgsValid } from "../hub/person-command.ts";
|
|
138
|
-
import { outputWidth, renderRuntimeModels, renderRoster, renderRoles, rolesView,renderStatus, renderBoard, renderBacklog, renderBoardColumns, boardColumnModel, renderBudget, renderDoctor, renderProjects, renderQueue, renderTurns, renderOrphans, renderOrphanCleanup, renderQueueShow, renderModelsStatus, renderExecutionBudgetStatus, renderReport, renderUsage, renderLimits, renderTotal, type DoctorCheck } from "./output.ts";
|
|
140
|
+
import { outputWidth, renderRuntimeModels, renderRoster, renderRoles, rolesView,renderStatus, renderStatusDefault, renderBoard, renderBacklog, renderBoardColumns, boardColumnModel, renderBudget, renderDoctor, renderProjects, renderQueue, renderTurns, renderOrphans, renderOrphanCleanup, renderQueueShow, renderModelsStatus, renderExecutionBudgetStatus, renderReport, renderUsage, renderLimits, renderTotal, type DoctorCheck } from "./output.ts";
|
|
139
141
|
import { renderHelp, configuredAcpHelp, guidanceProbeUsage, listsSubcommand, subcommandUsage } from "./help.ts";
|
|
140
142
|
import { renderBacklogResult, renderGroom, renderReleaseChange, renderReleaseList, renderReleaseNew, renderReleaseShow, renderTaskCancel, renderTaskShow } from "./task-output.ts";
|
|
141
143
|
import { SURVEY_FOCUS } from "../hub/advisor-survey.ts";
|
|
@@ -294,13 +296,14 @@ operationalAuditReady=identity.role==="tools" && commandAccess==="conductor" &&
|
|
|
294
296
|
function audit(outcome: "run" | "refused" | "invalid"): void {
|
|
295
297
|
if (caller.role === "console") return;
|
|
296
298
|
if(outcome==="refused" && operationalAuditReady){if(operationalRefusalRecorded)return;operationalRefusalRecorded=true;}
|
|
297
|
-
try { recordCliAudit(stateDir, caller.role === "tools" ? caller.peer : "unknown", commandLabel, outcome); }
|
|
299
|
+
try { recordCliAudit(stateDir, caller.role === "tools" ? caller.peer : "unknown", commandLabel, outcome, cmd === "answer" && args.includes("--instructed")); }
|
|
298
300
|
catch {
|
|
299
301
|
if (delegatedPeer) fail("live-test delegation audit unavailable; nothing was executed");
|
|
300
302
|
console.error("ahub: CLI audit could not be recorded (outbox unavailable or full)");
|
|
301
303
|
}
|
|
302
304
|
}
|
|
303
305
|
if (identity.role === "invalid") { audit("invalid"); fail(`${identity.reason}; use ahub console or a terminal with no agent markers`); }
|
|
306
|
+
if (delegationRefused && cmd === "answer" && args.includes("--instructed")) { audit("refused"); fail(`${LIVE_TEST_PERSON_REFUSAL}; the person can answer with ahub console`); }
|
|
304
307
|
if (delegationRefused) { audit("refused"); fail(LIVE_TEST_PERSON_REFUSAL); }
|
|
305
308
|
if (identity.role === "tools" && commandAccess === "console") { audit("refused"); fail(peerCommandRefusal(identity.peer, commandLabel)); }
|
|
306
309
|
// Recovery keeps its authoritative delegation audit in the operation receipt, independent of an old source drain.
|
|
@@ -347,9 +350,9 @@ try { process.chdir(cwd); } catch { fail(`project directory is unavailable: ${cw
|
|
|
347
350
|
function outputOptions(source: readonly string[] = args) {
|
|
348
351
|
const flags = source.filter(arg => arg.startsWith("--color="));
|
|
349
352
|
if (flags.length > 1 || source.includes("--color")) fail(`usage: ahub ${cmd} [--color=auto|always|never] [--json] [--full]`);
|
|
350
|
-
const color = resolveColor(flags[0]?.slice("--color=".length),
|
|
353
|
+
const color = resolveColor(flags[0]?.slice("--color=".length), streamEnv(!!process.stdout.isTTY));
|
|
351
354
|
if (color instanceof Error) fail(`usage: ahub ${cmd} [--color=auto|always|never] [--json] [--full]`);
|
|
352
|
-
return { color: color === true, json: source.includes("--json"), full: source.includes("--full"),
|
|
355
|
+
return { color: color === true, json: source.includes("--json"), full: source.includes("--full"), verbose: source.includes("--verbose"),
|
|
353
356
|
columns: outputWidth({ isTTY: !!process.stdout.isTTY, columns: process.stdout.columns, COLUMNS: process.env.COLUMNS }) };
|
|
354
357
|
}
|
|
355
358
|
/**
|
|
@@ -381,6 +384,10 @@ function outputArguments(): string[] {
|
|
|
381
384
|
return args.filter(arg => arg !== "--json" && arg !== "--full" && !arg.startsWith("--color="));
|
|
382
385
|
}
|
|
383
386
|
/** `sdlc` operands: the read subcommands that print for a person (#814) drop `--json`, `--full` and `--color=`; every other subcommand keeps its argv exactly. */
|
|
387
|
+
/** The daemon answers a missing task id with a JSON string (`"no task #N"`), a found task with an object: the sentence for a missing one, otherwise undefined. */
|
|
388
|
+
function missingTaskText(text: string): string | undefined {
|
|
389
|
+
try { const value: unknown = JSON.parse(text); return typeof value === "string" && /^no task #\d+$/.test(value) ? value : undefined; } catch { return undefined; }
|
|
390
|
+
}
|
|
384
391
|
/** A hub tool answers JSON text. Text that does not parse is printed as it came: a renderer never sees it, so it cannot read as an empty report. */
|
|
385
392
|
function showToolText(render: (data: any, columns?: number, now?: number) => Span[][], text: string, present: ReturnType<typeof outputOptions>): void {
|
|
386
393
|
let data: unknown;
|
|
@@ -565,12 +572,17 @@ function startupDiagnostic(error: unknown): string {
|
|
|
565
572
|
return message.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim().slice(0, 512) || "invalid startup configuration";
|
|
566
573
|
}
|
|
567
574
|
|
|
568
|
-
|
|
575
|
+
/**
|
|
576
|
+
* CLI output standard v1, Messages: `ahub: <what failed>: <why>` on stderr; with a terminal on stderr it leads with the fail marker, and a piped line
|
|
577
|
+
* keeps the plain `ahub: ` form so a script or agent matching it still works. `next` is a complete, copyable command printed on a second line (ASCII
|
|
578
|
+
* `->` when the locale is not UTF-8); a caller passes it only where the fix is known, and a daemon refusal is passed through without one.
|
|
579
|
+
* A usage error exits 2, any other failure 1; a usage error is one whose text starts with `usage:` (the form every call site already uses) or names an unknown command.
|
|
580
|
+
*/
|
|
581
|
+
function fail(message: string, refusalAudited=false, authorityRefused?:boolean, next?: string): never {
|
|
569
582
|
if(operationalAuditReady && authorityRefused!==false){if(refusalAudited)operationalRefusalRecorded=true;if(!operationalRefusalRecorded)audit("refused");}
|
|
570
|
-
console.error(
|
|
571
|
-
process.exit(
|
|
583
|
+
console.error(errorLines(message, next, !!process.stderr.isTTY, asciiMarkers(process.env, process.argv.includes("--ascii"))).join("\n"));
|
|
584
|
+
process.exit(failureExitCode(message));
|
|
572
585
|
}
|
|
573
|
-
|
|
574
586
|
function operationalIncomplete(result: {complete?:boolean;incompleteReason?:unknown;truncated?:boolean}, history: "log"|"event"): void {
|
|
575
587
|
if(result.complete===false)console.error(`ahub: operational output is incomplete: ${typeof result.incompleteReason==="string"?terminalText(result.incompleteReason).replace(/[\r\n]+/g," ").slice(0,200):"public privacy or history coverage unavailable"}`);
|
|
576
588
|
else if(result.truncated)console.error(`ahub: operational ${history} history is truncated`);
|
|
@@ -638,7 +650,7 @@ async function hold(t: "pause" | "resume"): Promise<void> {
|
|
|
638
650
|
function recoveryDisplay() {
|
|
639
651
|
// A terminal gives its own width; a pipe gives COLUMNS when set, else 80 (#814: a person reads a pipe too).
|
|
640
652
|
const width = process.stdout.columns ?? outputWidth({ isTTY: false, COLUMNS: process.env.COLUMNS }) ?? 80;
|
|
641
|
-
return readRecoveryPresentationFlags(args, {
|
|
653
|
+
return readRecoveryPresentationFlags(args, { ...streamEnv(!!process.stdout.isTTY), columns: width });
|
|
642
654
|
}
|
|
643
655
|
const humanRecovery = (json: boolean) => !json && !!process.stdin.isTTY && !!process.stdout.isTTY;
|
|
644
656
|
const printRecovery = (lines: readonly string[]) => { for (const line of lines) console.log(line); };
|
|
@@ -909,6 +921,8 @@ const contract = (file: string, kind: "contract" | "manifest" = "contract"): unk
|
|
|
909
921
|
const consoleInstalled = () => installedVersions(join(import.meta.dir, "..", ".."));
|
|
910
922
|
/** `ahub goal new` options: those that take a value, and all it knows. The words they leave are the title. */
|
|
911
923
|
const GOAL_NEW_VALUE_FLAGS = ["--milestone", "--depends"], GOAL_NEW_FLAGS = [...GOAL_NEW_VALUE_FLAGS, "--shared", "--json"];
|
|
924
|
+
/** `ahub doctor` exits 1 on a failed row; `ahub setup` runs the same function and keeps its own exit behavior. */
|
|
925
|
+
let doctorSetsExit = true;
|
|
912
926
|
const commands: Record<string, () => Promise<void> | void> = {
|
|
913
927
|
upgrade: () => upgrade("upgrade"),
|
|
914
928
|
restart: () => upgrade("restart"),
|
|
@@ -1031,10 +1045,10 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
1031
1045
|
else if (conductorPeer) retireConductorOperation(result, conductorPeer);
|
|
1032
1046
|
},
|
|
1033
1047
|
help: () => {
|
|
1034
|
-
const color = resolveColor(undefined,
|
|
1048
|
+
const color = resolveColor(undefined, streamEnv(!!process.stdout.isTTY)) === true;
|
|
1035
1049
|
const topic = asksHelp(args[0]) ? undefined : args[0];
|
|
1036
1050
|
const text = topic && !definitionOf(topic) && projectCatalog.definitionOf(topic)?.permission.genericAcp !== undefined
|
|
1037
|
-
? configuredAcpHelp(topic) : renderHelp(process.stdout.columns ?? 80, color, topic);
|
|
1051
|
+
? configuredAcpHelp(topic) : renderHelp(process.stdout.columns ?? 80, color, topic, undefined, asciiMarkers(process.env, args.includes("--ascii")));
|
|
1038
1052
|
if (!text) fail(`unknown command "${topic}"; run ahub help`);
|
|
1039
1053
|
console.log(text);
|
|
1040
1054
|
},
|
|
@@ -1140,7 +1154,7 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
1140
1154
|
const acon = registerAconPlugin(hubHome(), join(root, "src", "ui", "plugin.ts"));
|
|
1141
1155
|
console.log("error" in acon ? `acon plugin not registered: ${acon.error}` : acon.changed ? `acon plugin registered: ${acon.path}` : `acon plugin up to date: ${acon.path}`);
|
|
1142
1156
|
if (recoveryLauncherCurrent) recoveryLauncherCurrent();
|
|
1143
|
-
else await commands.doctor!();
|
|
1157
|
+
else { doctorSetsExit = false; await commands.doctor!(); }
|
|
1144
1158
|
},
|
|
1145
1159
|
|
|
1146
1160
|
init: async () => {
|
|
@@ -1227,7 +1241,7 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
1227
1241
|
|
|
1228
1242
|
console: async () => {
|
|
1229
1243
|
if (args.some(arg => arg !== "--panels" && arg !== "--no-pet" && !arg.startsWith("--color=")) || args.filter(arg => arg.startsWith("--color=")).length > 1) fail("usage: ahub console [--panels] [--no-pet] [--color=auto|always|never]");
|
|
1230
|
-
const color = resolveColor(args.find(arg => arg.startsWith("--color="))?.slice("--color=".length),
|
|
1244
|
+
const color = resolveColor(args.find(arg => arg.startsWith("--color="))?.slice("--color=".length), streamEnv(!!process.stdin.isTTY && !!process.stdout.isTTY));
|
|
1231
1245
|
if (color instanceof Error) return fail("usage: ahub console [--panels] [--no-pet] [--color=auto|always|never]");
|
|
1232
1246
|
await runConsole({ client: await connect(), cwd, stateDir, liveTest, panels: args.includes("--panels"), noPet: args.includes("--no-pet"), color, installed: consoleInstalled() });
|
|
1233
1247
|
},
|
|
@@ -1530,7 +1544,7 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
1530
1544
|
const peer = args[0];
|
|
1531
1545
|
if (typeof peer !== "string" || !peerDefinition(peer)?.capabilities?.watch) fail("usage: ahub watch kimi|qwen [--no-thoughts] [--color=auto|always|never]");
|
|
1532
1546
|
if (args.slice(1).some(arg => arg !== "--no-thoughts" && !/^--color=(auto|always|never)$/.test(arg))) fail("unsupported watch option");
|
|
1533
|
-
const color = resolveColor(args.find(arg => arg.startsWith("--color="))?.slice(8),
|
|
1547
|
+
const color = resolveColor(args.find(arg => arg.startsWith("--color="))?.slice(8), streamEnv(!!process.stdout.isTTY));
|
|
1534
1548
|
if (color instanceof Error) fail(color.message);
|
|
1535
1549
|
const hub = await connect();
|
|
1536
1550
|
const input = process.stdin;
|
|
@@ -1647,6 +1661,14 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
1647
1661
|
return shown((data, columns, now) => renderBacklogResult(sub === "person" ? "plan" : sub as "plan" | "pin", data, columns, now))(taskOp("hub_backlog_plan", { id: Number(id), revision: Number(revision), fields, reason: reason.join(" ") }));
|
|
1648
1662
|
},
|
|
1649
1663
|
|
|
1664
|
+
roadmap: async () => {
|
|
1665
|
+
let options;
|
|
1666
|
+
try { options = parseRoadmapArgs(args); } catch (error) { return fail(`${error instanceof Error ? error.message : "invalid roadmap arguments"}; see ahub help roadmap`); }
|
|
1667
|
+
// R3 (#1481): the GitHub reads and the model call each carry their own deadline, so these ops wait longer than the 30 s default.
|
|
1668
|
+
const text = await taskOp(options.op, options.args, false, undefined, ["hub_roadmap_unplaced", "hub_roadmap_triage", "roadmap_import_github"].includes(options.op) ? 60_000 : undefined);
|
|
1669
|
+
if (options.json) console.log(text);
|
|
1670
|
+
else console.log(renderRoadmap(text, outputOptions().columns));
|
|
1671
|
+
},
|
|
1650
1672
|
release: async () => {
|
|
1651
1673
|
const split = splitPresentation(args, { edges: true }), operands = split.operands;
|
|
1652
1674
|
const [sub, name, revision, value] = operands;
|
|
@@ -2183,7 +2205,15 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
2183
2205
|
if (sub === "show") {
|
|
2184
2206
|
// a stray operand (for example the value of a `--color always` that is not the `--color=` form) is a usage error, never silently ignored
|
|
2185
2207
|
if (rest.length !== 1) fail("usage: ahub task show <id> [--json] [--full] [--color=auto|always|never]");
|
|
2186
|
-
|
|
2208
|
+
// CLI output standard v1: a lookup that finds nothing is a failure (stderr, exit 1), not a successful print. The daemon answers a missing id with a JSON string
|
|
2209
|
+
// (`"no task #N"`) while a found task is an object. The exit code is the standard's and is set apart from the format: `--json` keeps printing the hub's own document
|
|
2210
|
+
// byte for byte on stdout, and exits 1 like the human path, which prints the error and a next step on stderr instead.
|
|
2211
|
+
const shown = taskOp("task_show", { id: rest[0] });
|
|
2212
|
+
const missing = missingTaskText(await shown);
|
|
2213
|
+
if (missing !== undefined && !outputOptions(presentation.flags).json) return fail(missing, false, undefined, "ahub board");
|
|
2214
|
+
await shownTask(renderTaskShow)(shown);
|
|
2215
|
+
if (missing !== undefined) process.exitCode = 1; // --json printed the hub's document above; a lookup that found nothing still fails
|
|
2216
|
+
return;
|
|
2187
2217
|
}
|
|
2188
2218
|
if (sub === "claim") {
|
|
2189
2219
|
// #901: a person's verdict on one declared plan claim. The claim is named by its 1-based slot and its text is never typed, stored or printed here.
|
|
@@ -2645,10 +2675,10 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
2645
2675
|
}
|
|
2646
2676
|
const parsed = parseAnswerArgs(operands);
|
|
2647
2677
|
if (!parsed.ok) return fail(parsed.error);
|
|
2648
|
-
const reply = await hub.request({ t: "answer", surface: "terminal", questionSet: parsed.value.set, answers: parsed.value.answers });
|
|
2678
|
+
const reply = await hub.request({ t: "answer", surface: "terminal", questionSet: parsed.value.set, answers: parsed.value.answers, ...(parsed.value.instruction === undefined ? {} : { instructed: parsed.value.instruction }) });
|
|
2649
2679
|
if (reply.ok === false) return fail(String(reply.error ?? "the answer was refused"));
|
|
2650
|
-
if (options.json) return console.log(JSON.stringify({ ok: true, questionSet: reply.questionSet, state: reply.state }));
|
|
2651
|
-
console.log(`answered ${reply.questionSet ?? parsed.value.set}`);
|
|
2680
|
+
if (options.json) return console.log(JSON.stringify({ ok: true, questionSet: reply.questionSet, state: reply.state, ...(reply.instructed ? { actor: reply.actor, instructed: true } : {}) }));
|
|
2681
|
+
console.log(`answered ${reply.questionSet ?? parsed.value.set}${reply.instructed && typeof reply.actor === "string" ? `; answered by ${terminalText(reply.actor)} on the person's instruction` : ""}`);
|
|
2652
2682
|
} finally { hub.close(); }
|
|
2653
2683
|
},
|
|
2654
2684
|
|
|
@@ -2729,7 +2759,9 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
2729
2759
|
const { status } = await hub.request({ t: "status", specs: true });
|
|
2730
2760
|
if (options.json) return console.log(JSON.stringify(status, null, 2));
|
|
2731
2761
|
const quota = await hub.request({ t: "budget" });
|
|
2732
|
-
|
|
2762
|
+
// CLI output standard v1: the default view answers "is it OK, and what do I do next"; every detail the older view printed stays behind --verbose (and --full, which adds the long ids).
|
|
2763
|
+
const data = { ...status, budget: quota.budget ?? {} };
|
|
2764
|
+
printOutput(options.verbose || options.full ? renderStatus(data, options.columns, Date.now(), options.full) : renderStatusDefault(data, options.columns, Date.now(), asciiMarkers(process.env, args.includes("--ascii"))), options.color);
|
|
2733
2765
|
if (status.needs) { const pet = loadPetConfig(cwd); if (pet.enabled) console.log(renderPet(petView(status), false, pet.character)); }
|
|
2734
2766
|
// #258: open long-term tasks and who holds them, as of this machine's last memory sync.
|
|
2735
2767
|
if (status.memoryProfile ? status.memoryProfile.state === "ready" : memoryIndexExists(join(hubHome(), "memory"))) {
|
|
@@ -3364,7 +3396,10 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
3364
3396
|
} finally {
|
|
3365
3397
|
// Preserve findings already collected if a later probe (for example config parsing) throws.
|
|
3366
3398
|
if (options.json) console.log(JSON.stringify(checks, null, 2));
|
|
3367
|
-
else printOutput(renderDoctor(checks, options.columns, Date.now(), options.full), options.color);
|
|
3399
|
+
else printOutput(renderDoctor(checks, options.columns, Date.now(), options.full, asciiMarkers(process.env, args.includes("--ascii"))), options.color);
|
|
3400
|
+
// CLI output standard v1: a check command exits 1 when any row is a failure (warnings and unknowns change nothing), `--json` included; the document is unchanged.
|
|
3401
|
+
// `ahub setup` prints the same report but keeps its own exit code (`doctorSetsExit` is cleared there).
|
|
3402
|
+
if (doctorSetsExit && checks.some(check => check.level === "fail")) process.exitCode = 1;
|
|
3368
3403
|
}
|
|
3369
3404
|
},
|
|
3370
3405
|
};
|
|
@@ -3463,6 +3498,7 @@ async function runConductorCommand(): Promise<void> {
|
|
|
3463
3498
|
}
|
|
3464
3499
|
let op: string;
|
|
3465
3500
|
let input: Record<string, unknown>;
|
|
3501
|
+
if (cmd === "answer") return commands.answer!(); // The daemon checks instructed answer authority.
|
|
3466
3502
|
if (cmd === "sdlc") return commands.sdlc!(); // SDLC operational subcommands are role-checked by the daemon.
|
|
3467
3503
|
if (cmd === "task") {
|
|
3468
3504
|
op = args[0] === "assign" ? "hub_task_assign" : "hub_task_escalate";
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// CLI output standard v1 (docs/design/cli-output.md): the portable core. This file imports nothing, so a CLI outside the hub can reuse it as is. It holds the nine roles, the marker table and color resolution.
|
|
2
|
+
// Human-output code names a role or a marker, never an SGR code or a glyph literal.
|
|
3
|
+
/**
|
|
4
|
+
* The nine semantic roles of CLI output standard v1 on the 16 ANSI colors, so a terminal theme decides the shades. Code names a role,
|
|
5
|
+
* never an SGR code (`test/cli-output-conformance.test.ts` fails on a raw SGR literal in `src/cli/` and `src/hub/`). `value` is the
|
|
6
|
+
* default foreground and carries no SGR. Bold is only for `header`, `section` and the three status roles; no backgrounds.
|
|
7
|
+
*/
|
|
8
|
+
/** End of every painted span. */
|
|
9
|
+
export const SGR_RESET = "\x1b[0m";
|
|
10
|
+
/** SGR of the console tones that are not an identity palette entry; the role table above is the standard, these are the TUI's own. */
|
|
11
|
+
export const TONE_SGR = Object.freeze({ strong: "\x1b[1;36m", failure: "\x1b[31m", number: "\x1b[1m", issueRef: "\x1b[4m", taskRef: "\x1b[4;35m" } as const);
|
|
12
|
+
export type Role = "header" | "section" | "key" | "value" | "success" | "warning" | "error" | "hint" | "accent";
|
|
13
|
+
export const ROLE_SGR: Readonly<Record<Role, string>> = Object.freeze({
|
|
14
|
+
header: "\x1b[1;34m", section: "\x1b[1;35m", key: "\x1b[34m", value: "", success: "\x1b[1;32m", warning: "\x1b[1;33m", error: "\x1b[1;31m", hint: "\x1b[90m", accent: "\x1b[36m",
|
|
15
|
+
});
|
|
16
|
+
export const MARKER_NAMES = ["ok", "fail", "warn", "absent", "unknown", "pending", "active", "next"] as const;
|
|
17
|
+
export type MarkerName = (typeof MARKER_NAMES)[number];
|
|
18
|
+
/** Semantic glyphs, each with its ASCII form and the one role that colors it. Code names a marker, never a glyph literal. */
|
|
19
|
+
export const MARKERS: Readonly<Record<MarkerName, { glyph: string; ascii: string; role: Role }>> = Object.freeze({
|
|
20
|
+
ok: { glyph: "\u2713", ascii: "ok", role: "success" }, fail: { glyph: "\u2717", ascii: "x", role: "error" }, warn: { glyph: "\u26a0", ascii: "!", role: "warning" },
|
|
21
|
+
absent: { glyph: "-", ascii: "-", role: "hint" }, unknown: { glyph: "?", ascii: "?", role: "hint" }, pending: { glyph: "~", ascii: "~", role: "hint" },
|
|
22
|
+
active: { glyph: "*", ascii: "*", role: "success" }, next: { glyph: "\u2192", ascii: "->", role: "accent" },
|
|
23
|
+
});
|
|
24
|
+
export const SECTION_MARKER = { glyph: "\u25b8", ascii: ">" } as const;
|
|
25
|
+
export const MARKER_COLUMN = 2;
|
|
26
|
+
/** Cells a string occupies: East Asian Ambiguous characters count as 1, so a Korean or CJK terminal keeps the same alignment. */
|
|
27
|
+
export const cellWidth = (text: string): number => Bun.stringWidth(text, { ambiguousIsNarrow: true });
|
|
28
|
+
/** A marker padded to the 2-cell marker column (ASCII `ok` and `->` fill it). */
|
|
29
|
+
export function markerCell(name: MarkerName, ascii: boolean): string {
|
|
30
|
+
const text = ascii ? MARKERS[name].ascii : MARKERS[name].glyph;
|
|
31
|
+
return text + " ".repeat(Math.max(0, MARKER_COLUMN - cellWidth(text)));
|
|
32
|
+
}
|
|
33
|
+
/** The environment one output stream's color decision reads (`streamEnv` builds it). */
|
|
34
|
+
export interface ColorEnv { isTTY: boolean; TERM?: string; NO_COLOR?: string; FORCE_COLOR?: string; CLICOLOR?: string; CLICOLOR_FORCE?: string }
|
|
35
|
+
/** `isTTY` of the stream that is decided (stdout and stderr are decided separately) plus the color variables of `env`. */
|
|
36
|
+
export function streamEnv(isTTY: boolean, env: Readonly<Record<string, string | undefined>> = process.env): ColorEnv {
|
|
37
|
+
return { isTTY, TERM: env.TERM, NO_COLOR: env.NO_COLOR, FORCE_COLOR: env.FORCE_COLOR, CLICOLOR: env.CLICOLOR, CLICOLOR_FORCE: env.CLICOLOR_FORCE };
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Color for one stream, first rule wins (standard v1): `--color=never|always`; non-empty NO_COLOR off; FORCE_COLOR or CLICOLOR_FORCE
|
|
41
|
+
* non-empty and not `0` on; FORCE_COLOR=0 or CLICOLOR=0 off; a TTY whose TERM is not `dumb` on; otherwise off. `auto` and no flag
|
|
42
|
+
* apply rules 2 to 6. An unknown flag value is a usage error. `--json` is never colored: the caller does not ask.
|
|
43
|
+
*/
|
|
44
|
+
export function resolveColor(flag: string | undefined, env: ColorEnv): boolean | Error {
|
|
45
|
+
if (flag === "always") return true;
|
|
46
|
+
if (flag === "never") return false;
|
|
47
|
+
if (flag !== undefined && flag !== "auto") return new Error("usage: ahub <command> [--color=auto|always|never]");
|
|
48
|
+
if (env.NO_COLOR) return false;
|
|
49
|
+
if ((env.FORCE_COLOR && env.FORCE_COLOR !== "0") || (env.CLICOLOR_FORCE && env.CLICOLOR_FORCE !== "0")) return true;
|
|
50
|
+
if (env.FORCE_COLOR === "0" || env.CLICOLOR === "0") return false;
|
|
51
|
+
return env.isTTY && env.TERM !== "dumb";
|
|
52
|
+
}
|
|
53
|
+
/** ASCII markers when `--ascii` is given or the locale (`LC_ALL`, then `LC_CTYPE`, then `LANG`) is not UTF-8. */
|
|
54
|
+
export function asciiMarkers(env: Readonly<Record<string, string | undefined>> = process.env, flag = false): boolean {
|
|
55
|
+
return flag || !/utf-?8/i.test(env.LC_ALL || env.LC_CTYPE || env.LANG || "");
|
|
56
|
+
}
|