@staix/agent-hub 0.34.1 → 0.36.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 +73 -0
- package/README.md +53 -7
- package/docs/adding-an-ai-tool.md +2 -2
- package/docs/addons/claude-mem.md +4 -4
- package/docs/addons/open-code-review.md +1 -1
- package/docs/agent-notes/README.md +66 -0
- package/docs/agent-notes/adapters.md +14 -7
- package/docs/agent-notes/budget.md +1 -1
- package/docs/agent-notes/bus.md +2 -1
- package/docs/agent-notes/daemon.md +9 -7
- package/docs/agent-notes/local-worker.md +1 -1
- package/docs/agent-notes/models.md +5 -2
- package/docs/agent-notes/tasks.md +9 -2
- package/docs/agent-notes/tests.md +6 -0
- package/docs/design/adapters.md +182 -2
- package/docs/design/agent-hub-architecture.md +64 -2
- package/docs/design/agent-hub.md +6 -0
- package/docs/design/bus.md +26 -0
- package/docs/design/execution-reference.md +306 -0
- package/docs/design/guidance-experiments.md +438 -0
- package/docs/design/model-routes.md +628 -0
- package/docs/design/supervision.md +121 -0
- package/docs/design/task-board.md +121 -0
- package/docs/dogfood.md +45 -13
- package/docs/events.md +38 -20
- package/docs/memory.md +21 -7
- package/docs/operations.md +824 -40
- package/docs/profiles.md +2 -2
- package/docs/quickstart.md +117 -4
- package/docs/research.md +73 -13
- package/docs/roles.md +1 -1
- package/docs/sdlc.md +117 -11
- package/docs/security.md +153 -15
- package/docs/smoke.md +14 -0
- package/docs/specs/2026-09-19-agent-hub-design.md +13 -7
- package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
- package/docs/verification/2026-11-07-compat-python-startup-1248.md +51 -0
- package/docs/verification/2026-11-07-compat-receipt-harness-1248.md +105 -0
- package/docs/verification/2026-11-07-compat-receipt-producers-1248.md +96 -0
- package/docs/verification/2026-11-07-compat-workflow-1248.md +94 -0
- package/docs/verification/2026-11-07-daemon-startup-1232.md +169 -0
- package/docs/verification/2026-11-07-jcode-receipt-reconstruction-1248.md +118 -0
- package/docs/verification/2026-11-07-kimi-delayed-usage.md +34 -0
- package/docs/verification/2026-11-07-kimi-review-watch-1284.md +115 -0
- package/docs/verification/2026-11-08-agy-1.5.3.md +96 -0
- package/docs/verification/2026-11-08-agy-acp-t0.md +56 -0
- package/docs/verification/2026-11-08-hub-visual-1058.md +161 -0
- package/docs/verification/2026-11-08-jcode-0991-model-setter-1317.md +143 -0
- package/docs/verification/2026-11-08-kimi-252-model-setter-1317.md +137 -0
- package/docs/verification/2026-11-08-kimi-tui-completion-1282.md +45 -0
- package/docs/verification/2026-11-08-kimi-wire-yield-1283.md +31 -0
- package/docs/verification/2026-11-08-live-model-override-1317.md +250 -0
- package/docs/verification/2026-11-08-qwen-0269-acp.md +138 -0
- package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +91 -0
- package/docs/verification/2026-11-09-0.35.0.md +129 -0
- package/docs/verification/2026-11-09-headless-records-1320.md +157 -0
- package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
- package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
- package/docs/verification/2026-11-10-0.36.0.md +59 -0
- package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
- package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
- package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
- package/docs/verification/claude-permission-transport-native.py +10 -3
- package/docs/verification/claude-shell-wrapper-native.py +8 -8
- package/docs/verified.json +245 -15
- package/package.json +3 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +21230 -0
- package/plugins/agent-hub/kimi-review-policy-worker.js +217 -0
- package/plugins/agent-hub/server.js +4359 -1071
- package/scripts/check-docs.mjs +12 -1
- package/src/adapters/acp-model-policy.ts +56 -0
- package/src/adapters/acp.ts +175 -5
- package/src/adapters/agy/entry.ts +8 -5
- package/src/adapters/agy/hooks.ts +65 -15
- package/src/adapters/channel-peer.ts +33 -1
- package/src/adapters/claude-channel.ts +7 -4
- package/src/adapters/claude-implementer.ts +16 -3
- package/src/adapters/codex-appserver.ts +118 -8
- package/src/adapters/codex-review-isolation.ts +3 -1
- package/src/adapters/compat.ts +18 -13
- package/src/adapters/definitions/builtin-metadata.ts +8 -1
- package/src/adapters/definitions/native-cli-entry-kimi.ts +76 -7
- package/src/adapters/definitions/native-cli-preview-common.ts +2 -2
- package/src/adapters/definitions/native-cli-preview-kimi.ts +9 -2
- package/src/adapters/definitions/reviewer-variants.ts +3 -1
- package/src/adapters/kimi-review-policy-worker.js +2 -0
- package/src/adapters/kimi-review-policy-worker.ts +85 -0
- package/src/adapters/kimi-review-policy.ts +68 -0
- package/src/adapters/kimi-review.ts +41 -41
- package/src/adapters/kimi-tui-facts.ts +153 -0
- package/src/adapters/kimi-wire-usage.ts +33 -8
- package/src/adapters/local-worker.ts +60 -21
- package/src/adapters/model-token.ts +3 -0
- package/src/adapters/pi.ts +27 -5
- package/src/adapters/qwen-dual.ts +324 -44
- package/src/adapters/registry-types.ts +34 -3
- package/src/adapters/registry.ts +1 -0
- package/src/adapters/reviewer-policy-watch.ts +86 -0
- package/src/adapters/reviewer-print.ts +80 -18
- package/src/cli/agents.ts +1 -1
- package/src/cli/facts-hook.ts +4 -2
- package/src/cli/guidance.ts +67 -0
- package/src/cli/help.ts +13 -5
- package/src/cli/identity.ts +13 -3
- package/src/cli/init-prompt.ts +15 -2
- package/src/cli/init-required-checks.ts +122 -0
- package/src/cli/init-settings.ts +10 -4
- package/src/cli/init.ts +39 -3
- package/src/cli/kimi-facts-hook.ts +11 -0
- package/src/cli/kimi-plugin.ts +157 -0
- package/src/cli/lineage.ts +78 -0
- package/src/cli/main.ts +159 -19
- package/src/cli/model.ts +52 -0
- package/src/cli/output.ts +23 -1
- package/src/cli/reset.ts +1 -1
- package/src/cli/setup-research.ts +10 -0
- package/src/cli/status-lines.ts +8 -4
- package/src/hub/autonomy-defaults.ts +20 -9
- package/src/hub/board.ts +346 -4
- package/src/hub/budget.ts +1 -1
- package/src/hub/build-entry.ts +11 -0
- package/src/hub/bus.ts +52 -2
- package/src/hub/ci-watch.ts +4 -4
- package/src/hub/code-facts.ts +10 -3
- package/src/hub/completions.ts +3 -1
- package/src/hub/config-apply.ts +3 -1
- package/src/hub/config-trust.ts +1 -0
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +1387 -121
- package/src/hub/deliverable-files.ts +38 -5
- package/src/hub/delivery-hints.ts +4 -2
- package/src/hub/delivery-journal.ts +50 -2
- package/src/hub/delivery-public.ts +51 -0
- package/src/hub/dogfood-profile.ts +9 -5
- package/src/hub/envelope.ts +1 -1
- package/src/hub/events.ts +28 -18
- package/src/hub/execution-lineage-owner.ts +272 -0
- package/src/hub/execution-lineage.ts +164 -0
- package/src/hub/execution-links.ts +85 -0
- package/src/hub/execution-reference.ts +36 -0
- package/src/hub/guidance-variants.ts +398 -0
- package/src/hub/handoff.ts +1 -0
- package/src/hub/hub-tools.ts +62 -2
- package/src/hub/instances.ts +4 -3
- package/src/hub/kimi-events.ts +46 -0
- package/src/hub/kimi-usage.ts +132 -29
- package/src/hub/lifecycle.ts +31 -15
- package/src/hub/limits.ts +13 -4
- package/src/hub/manager.ts +58 -3
- package/src/hub/memory-policy.ts +4 -3
- package/src/hub/memory-sync-attestation.ts +54 -0
- package/src/hub/memory-sync-state.ts +20 -5
- package/src/hub/model-overrides.ts +115 -0
- package/src/hub/native-hook-launch.ts +12 -3
- package/src/hub/operational-view.ts +2 -2
- package/src/hub/peers.ts +28 -1
- package/src/hub/permission-mode.ts +1 -1
- package/src/hub/person-figures.ts +88 -0
- package/src/hub/planning.ts +1 -1
- package/src/hub/progress.ts +24 -7
- package/src/hub/report.ts +38 -4
- package/src/hub/research-dataset.ts +158 -0
- package/src/hub/research-memory.ts +68 -0
- package/src/hub/research-quality.ts +118 -0
- package/src/hub/research-record.ts +279 -0
- package/src/hub/research.ts +126 -27
- package/src/hub/restart.ts +27 -0
- package/src/hub/roles.ts +26 -0
- package/src/hub/routing.ts +4 -1
- package/src/hub/sdlc-merge.ts +39 -1
- package/src/hub/sdlc-release.ts +1 -1
- package/src/hub/sdlc.ts +62 -11
- package/src/hub/settings.ts +5 -0
- package/src/hub/startup-event-seeds.ts +51 -0
- package/src/hub/startup-readiness.ts +65 -0
- package/src/hub/startup-timing.ts +38 -0
- package/src/hub/supervision-proposals.ts +405 -0
- package/src/hub/supervision-rules.ts +388 -0
- package/src/hub/supervision.ts +2 -0
- package/src/hub/task-approval.ts +2 -2
- package/src/hub/task-repository.ts +5 -0
- package/src/hub/tasks.ts +632 -59
- package/src/hub/ui.ts +9 -5
- package/src/hub/visual-assets.ts +50 -0
- package/src/hub/visual.ts +257 -0
- package/src/memory/brief.ts +169 -14
- package/src/memory/capture.ts +4 -3
- package/src/memory/recall.ts +46 -5
- package/src/memory/record-provenance.ts +82 -0
- package/src/memory/records.ts +116 -0
- package/src/models/relay.ts +9 -2
- package/src/models/route/adec.ts +190 -0
- package/src/models/route/config.ts +64 -3
- package/src/models/route/decision-evidence.ts +83 -0
- package/src/models/route/decision.ts +215 -0
- package/src/models/route/relay-selector.ts +8 -7
- package/src/models/route/runtime.ts +35 -22
- package/src/models/route/stage-diagnostics.ts +22 -0
- package/src/models/route/stage-evidence.ts +55 -0
- package/src/models/route/stage-fallback.ts +58 -0
- package/src/models/route/stage-input.ts +155 -0
- package/src/models/route/stage.ts +5 -147
- package/src/ui/guidance-panel.ts +156 -0
- package/src/ui/guidance-view.ts +43 -0
- package/src/ui/index.html +134 -6
- package/src/ui/lineage-view.ts +34 -0
- package/src/ui/plugin.ts +136 -11
- package/templates/AGENTS.block.md +1 -1
- package/templates/config.json +1 -1
- package/templates/profiles/general.json +1 -1
- package/templates/profiles/research.json +1 -1
- package/templates/profiles/writing.json +1 -1
package/src/cli/init-prompt.ts
CHANGED
|
@@ -64,6 +64,7 @@ export function shownDefault(id: string): string {
|
|
|
64
64
|
: id === "coordination" ? DEFAULT_CONFIG.coordination
|
|
65
65
|
: id === "specs.enabled" ? DEFAULT_SPECS_CONFIG.enabled
|
|
66
66
|
: id === "specs.review" ? DEFAULT_SPECS_CONFIG.review
|
|
67
|
+
: id === "sdlc.required_checks" ? "none"
|
|
67
68
|
: id === "sdlc.mode" ? "off" // no file is written for it: the loader's own default (src/hub/sdlc.ts)
|
|
68
69
|
: row.id.endsWith(".enabled") ? false // a legacy `<kind>.enabled` switch that the template does not carry reads as off
|
|
69
70
|
: undefined;
|
|
@@ -84,8 +85,11 @@ const oneOf = (id: string, label: string, values: readonly string[], shown: stri
|
|
|
84
85
|
export interface InitQuestionContext {
|
|
85
86
|
/** The agent set `ahub setup` chose on this machine (the default shown for the agents question), or `undefined` for the shipped default. */
|
|
86
87
|
machineAgents?: readonly string[];
|
|
88
|
+
/** Effective research default for this new project, read from the trusted setup choice (else off). */
|
|
89
|
+
machineResearch?: boolean;
|
|
87
90
|
/** Project packs a profile answer may name besides the shipped profiles. */
|
|
88
91
|
packs?: readonly string[];
|
|
92
|
+
discoverChecks?: () => Promise<readonly string[]>;
|
|
89
93
|
/** Shadow history is offered only for a folder with no Git work tree. */
|
|
90
94
|
shadowAvailable?: boolean;
|
|
91
95
|
}
|
|
@@ -105,15 +109,17 @@ export function initQuestions(context: InitQuestionContext = {}): InitQuestion[]
|
|
|
105
109
|
id: "start.agents", label: "Agents ahub up starts", choices: `${START_AGENTS_ALLOWED.join(",")} as a comma list, or none`, shown: (context.machineAgents ?? START_AGENTS_DEFAULT).join(", ") || "none",
|
|
106
110
|
read: text => INIT_SETTINGS.find(row => row.id === "start.agents")!.parse(text.trim().toLowerCase()),
|
|
107
111
|
};
|
|
108
|
-
const switches = INIT_SETTINGS.filter(row => row.id.endsWith(".enabled") && !["specs.enabled", "memory.enabled", "snapshots.enabled"].includes(row.id));
|
|
112
|
+
const switches = INIT_SETTINGS.filter(row => row.id.endsWith(".enabled") && !["specs.enabled", "memory.enabled", "research.enabled", "snapshots.enabled"].includes(row.id));
|
|
109
113
|
const all: InitQuestion[] = [
|
|
110
114
|
profile,
|
|
111
115
|
agents,
|
|
112
116
|
onOff("specs.enabled", "Design specs and their freshness checks", shownDefault("specs.enabled") as "on" | "off"),
|
|
113
117
|
oneOf("specs.review", "Spec review mode", SPEC_REVIEW_MODES, shownDefault("specs.review")),
|
|
114
118
|
oneOf("sdlc.mode", "SDLC mode", SDLC_MODES, shownDefault("sdlc.mode")),
|
|
119
|
+
{ id: "sdlc.required_checks", label: "Required CI checks", choices: "comma-separated names", shown: "none", read: text => INIT_SETTINGS.find(row => row.id === "sdlc.required_checks")!.parse(text) },
|
|
115
120
|
oneOf("coordination", "Coordination", COORDINATION_MODES, shownDefault("coordination")),
|
|
116
121
|
onOff("memory.enabled", "Shared memory", shownDefault("memory.enabled") as "on" | "off"),
|
|
122
|
+
onOff("research.enabled", "Research records", context.machineResearch === true ? "on" : "off"),
|
|
117
123
|
onOff("snapshots.enabled", "Per-turn snapshots", shownDefault("snapshots.enabled") as "on" | "off"),
|
|
118
124
|
...switches.map(row => onOff(row.id, row.describe.charAt(0).toUpperCase() + row.describe.slice(1), shownDefault(row.id) as "on" | "off")),
|
|
119
125
|
oneOf("autonomy", "Machine autonomy preset", AUTONOMY_CHOICES, "inherit"),
|
|
@@ -133,7 +139,14 @@ export const questionLine = (question: InitQuestion): string => `${question.labe
|
|
|
133
139
|
export async function runInitPrompt(ports: InitPromptPorts, context: InitQuestionContext, preview: (answers: InitAnswers) => string[]): Promise<InitPromptResult> {
|
|
134
140
|
const answers: InitAnswers = { request: { values: {} }, shadow: false, releaseGuard: false };
|
|
135
141
|
ports.print("ahub init: press Enter to keep the default in brackets. N at the end, Ctrl-C or Ctrl-D writes nothing.");
|
|
136
|
-
for (const
|
|
142
|
+
for (const original of initQuestions(context)) {
|
|
143
|
+
let question = original;
|
|
144
|
+
if (question.id === "sdlc.required_checks") {
|
|
145
|
+
if (!["advise", "enforce"].includes(String(answers.request.values["sdlc.mode"]))) continue;
|
|
146
|
+
const names = await context.discoverChecks?.() ?? [];
|
|
147
|
+
answers.request.values["sdlc.required_checks"] = [...names];
|
|
148
|
+
question = { ...question, shown: names.join(", ") || "none; supply check names" };
|
|
149
|
+
}
|
|
137
150
|
let settled = false;
|
|
138
151
|
for (let attempt = 0; attempt < MAX_TRIES && !settled; attempt++) {
|
|
139
152
|
const answer = await ports.ask(questionLine(question));
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { constants, openSync, fstatSync, readSync, closeSync, readdirSync, lstatSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { githubOriginRepository } from "../hub/task-repository.ts";
|
|
4
|
+
import { requiredChecksFor } from "../hub/sdlc-merge.ts";
|
|
5
|
+
import { hubGitSync } from "../hub/git.ts";
|
|
6
|
+
import { loadSdlc, sdlcGh, type SdlcGh } from "../hub/sdlc.ts";
|
|
7
|
+
import type { InitSettingsRequest } from "./init-settings.ts";
|
|
8
|
+
|
|
9
|
+
const DISCOVERY_DEADLINE_MS = 20_000;
|
|
10
|
+
const DISCOVERY_READ_MS = 5_000;
|
|
11
|
+
const DISCOVERY_BYTES = 512 * 1024;
|
|
12
|
+
const DISCOVERY_JOBS = 100;
|
|
13
|
+
const WORKFLOW_FILES = 32;
|
|
14
|
+
const WORKFLOW_BYTES = 256 * 1024;
|
|
15
|
+
|
|
16
|
+
export interface InitCheckDiscovery { names: string[]; source: "CI" | "workflows" | "unknown"; reason?: string }
|
|
17
|
+
const validNames = (names: unknown[]): names is string[] => names.length > 0 && names.length <= 32 && names.every(name => typeof name === "string" && name.trim() === name && name.length > 0 && name.length <= 120 && !/[\p{Cc}]/u.test(name));
|
|
18
|
+
|
|
19
|
+
/** Literal block-style jobs only. ponytail: expressions, matrices and YAML aliases need an explicit override until a bounded YAML resolver is specified. */
|
|
20
|
+
export function workflowCheckNames(text: string): string[] | undefined {
|
|
21
|
+
const lines = text.split(/\r?\n/), start = lines.findIndex(line => /^jobs:\s*(?:#.*)?$/.test(line));
|
|
22
|
+
if (start < 0) return undefined;
|
|
23
|
+
const names: string[] = [];
|
|
24
|
+
let id: string | undefined, name: string | undefined, dynamic = false;
|
|
25
|
+
const finish = () => { if (id) names.push(name ?? id); };
|
|
26
|
+
for (const line of lines.slice(start + 1)) {
|
|
27
|
+
if (/^[^\s#]/.test(line)) break;
|
|
28
|
+
const job = /^ ([A-Za-z_][A-Za-z0-9_-]*):\s*(?:#.*)?$/.exec(line);
|
|
29
|
+
if (job) { finish(); id = job[1]!; name = undefined; continue; }
|
|
30
|
+
if (!line.trim() || /^\s*#/.test(line)) continue;
|
|
31
|
+
if (/^ \S/.test(line)) { dynamic = true; continue; }
|
|
32
|
+
if (!id) continue;
|
|
33
|
+
if (/^ (?:strategy|uses):/.test(line) || /^ <<:/.test(line)) dynamic = true;
|
|
34
|
+
const named = /^ name:\s*(.*?)\s*$/.exec(line);
|
|
35
|
+
if (named) {
|
|
36
|
+
const raw = named[1]!;
|
|
37
|
+
if (/\$\{|^[>|*&!{\[]/.test(raw)) { dynamic = true; continue; }
|
|
38
|
+
try {
|
|
39
|
+
if (raw.startsWith("'")) {
|
|
40
|
+
const quoted = /^'((?:[^']|'')*)'\s*(?:#.*)?$/.exec(raw);
|
|
41
|
+
if (!quoted) { dynamic = true; continue; }
|
|
42
|
+
name = quoted[1]!.replaceAll("''", "'");
|
|
43
|
+
} else if (raw.startsWith('"')) {
|
|
44
|
+
const quoted = /^("(?:[^"\\]|\\.)*")\s*(?:#.*)?$/.exec(raw);
|
|
45
|
+
if (!quoted) { dynamic = true; continue; }
|
|
46
|
+
name = JSON.parse(quoted[1]!);
|
|
47
|
+
} else name = raw.replace(/\s+#.*$/, "");
|
|
48
|
+
} catch { dynamic = true; }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
finish();
|
|
52
|
+
const unique = [...new Set(names)];
|
|
53
|
+
return !dynamic && validNames(unique) ? unique : undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function workflowChecks(cwd: string): InitCheckDiscovery {
|
|
57
|
+
const unknown: InitCheckDiscovery = { names: [], source: "unknown", reason: "CI unavailable or workflows have no complete literal job names; pass --required-checks <a,b,...>" };
|
|
58
|
+
const folder = join(cwd, ".github", "workflows");
|
|
59
|
+
try {
|
|
60
|
+
if (lstatSync(join(cwd, ".github")).isSymbolicLink() || lstatSync(folder).isSymbolicLink()) return unknown;
|
|
61
|
+
const files = readdirSync(folder).filter(file => file.endsWith(".yml")).sort();
|
|
62
|
+
if (!files.length || files.length > WORKFLOW_FILES) return unknown;
|
|
63
|
+
const names: string[] = [];
|
|
64
|
+
for (const file of files) {
|
|
65
|
+
const fd = openSync(join(folder, file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
66
|
+
try {
|
|
67
|
+
const stat = fstatSync(fd);
|
|
68
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > WORKFLOW_BYTES) return unknown;
|
|
69
|
+
const bytes = Buffer.alloc(WORKFLOW_BYTES + 1);
|
|
70
|
+
let length = 0, count = 0;
|
|
71
|
+
while ((count = readSync(fd, bytes, length, bytes.length - length, null)) > 0) { length += count; if (length > WORKFLOW_BYTES) return unknown; }
|
|
72
|
+
const after = fstatSync(fd);
|
|
73
|
+
if (stat.size !== after.size || stat.mtimeMs !== after.mtimeMs || length !== after.size) return unknown;
|
|
74
|
+
const text = bytes.subarray(0, length).toString("utf8");
|
|
75
|
+
const found = workflowCheckNames(text);
|
|
76
|
+
if (!found) return unknown;
|
|
77
|
+
names.push(...found);
|
|
78
|
+
} finally { closeSync(fd); }
|
|
79
|
+
}
|
|
80
|
+
const unique = [...new Set(names)];
|
|
81
|
+
return validNames(unique) ? { names: unique, source: "workflows" } : unknown;
|
|
82
|
+
} catch { return unknown; }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** At most three capped reads under one deadline; any incomplete evidence falls back to bounded local workflow data. No shell or YAML execution. */
|
|
86
|
+
export async function discoverInitChecks(cwd: string, run: SdlcGh = sdlcGh): Promise<InitCheckDiscovery> {
|
|
87
|
+
const deadline = performance.now() + DISCOVERY_DEADLINE_MS;
|
|
88
|
+
try {
|
|
89
|
+
const repo = githubOriginRepository(cwd);
|
|
90
|
+
if (!repo) return workflowChecks(cwd);
|
|
91
|
+
const read = async (args: string[]) => {
|
|
92
|
+
const remaining = deadline - performance.now();
|
|
93
|
+
if (remaining <= 0) throw new Error("discovery deadline");
|
|
94
|
+
const reply = await run(args, Math.min(DISCOVERY_READ_MS, remaining), cwd, DISCOVERY_BYTES);
|
|
95
|
+
if (reply.code !== 0 || Buffer.byteLength(reply.stdout) >= DISCOVERY_BYTES || performance.now() >= deadline) throw new Error("discovery unavailable");
|
|
96
|
+
return JSON.parse(reply.stdout);
|
|
97
|
+
};
|
|
98
|
+
const local = hubGitSync(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], { cwd, encoding: "utf8", timeout: DISCOVERY_READ_MS });
|
|
99
|
+
const remaining = deadline - performance.now();
|
|
100
|
+
const target = local.status === 0 && remaining > 0 ? hubGitSync(["rev-parse", "--verify", "refs/remotes/origin/HEAD^{commit}"], { cwd, encoding: "utf8", timeout: Math.min(DISCOVERY_READ_MS, remaining) }) : undefined;
|
|
101
|
+
let branch = local.status === 0 && target?.status === 0 ? local.stdout.trim().replace(/^refs\/remotes\/origin\//, "") : undefined;
|
|
102
|
+
if (!branch) branch = (await read(["api", `repos/${repo}`])).default_branch;
|
|
103
|
+
if (typeof branch !== "string" || !branch || /[\r\n]/.test(branch)) return workflowChecks(cwd);
|
|
104
|
+
const runs = await read(["api", "--method", "GET", `repos/${repo}/actions/runs`, "-f", `branch=${branch}`, "-f", "status=completed", "-f", "per_page=1"]);
|
|
105
|
+
const latest = runs.workflow_runs?.[0];
|
|
106
|
+
if (!Number.isSafeInteger(latest?.id) || latest.id <= 0 || latest.status !== "completed" || latest.head_branch !== branch) return workflowChecks(cwd);
|
|
107
|
+
const body = await read(["api", "--method", "GET", `repos/${repo}/actions/runs/${latest.id}/jobs`, "-f", `per_page=${DISCOVERY_JOBS}`]);
|
|
108
|
+
const jobs = body.jobs;
|
|
109
|
+
if (!Array.isArray(jobs) || body.total_count !== jobs.length || jobs.length >= DISCOVERY_JOBS) return workflowChecks(cwd);
|
|
110
|
+
const names: unknown[] = [...new Set(jobs.map(job => job?.name))];
|
|
111
|
+
return validNames(names) ? { names, source: "CI" } : workflowChecks(cwd);
|
|
112
|
+
} catch { return workflowChecks(cwd); }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The CLI resolves discovery before preview or write; an override never contacts GitHub. */
|
|
116
|
+
export async function withInitChecks(cwd: string, request: InitSettingsRequest, discover = discoverInitChecks): Promise<InitSettingsRequest> {
|
|
117
|
+
if (!["advise", "enforce"].includes(String(request.values["sdlc.mode"])) || Object.hasOwn(request.values, "sdlc.required_checks")) return request;
|
|
118
|
+
if (requiredChecksFor(loadSdlc(cwd), githubOriginRepository(cwd)).length) return request;
|
|
119
|
+
const result = await discover(cwd);
|
|
120
|
+
if (!result.names.length && request.values["sdlc.mode"] === "enforce") throw new Error(`enforce needs required CI checks: ${result.reason}; nothing was written`);
|
|
121
|
+
return { ...request, values: { ...request.values, "sdlc.required_checks": result.names } };
|
|
122
|
+
}
|
package/src/cli/init-settings.ts
CHANGED
|
@@ -48,8 +48,14 @@ export const INIT_SETTINGS: readonly InitSettingDef[] = [
|
|
|
48
48
|
catch (error) { throw new Error(`${(error as Error).message}; allowed: ${START_AGENTS_ALLOWED.join(", ")} or none; nothing was written`); }
|
|
49
49
|
} },
|
|
50
50
|
{ id: "sdlc.mode", flags: [{ flag: "--sdlc" }], file: "sdlc.toml", path: ["mode"], allowed: SDLC_MODES.join("|"), describe: "SDLC mode", parse: choice("sdlc.mode", "--sdlc", SDLC_MODES) },
|
|
51
|
+
{ id: "sdlc.required_checks", flags: [{ flag: "--required-checks" }], file: "sdlc.toml", path: ["required_checks"], allowed: "comma-separated check names", describe: "required CI checks", parse: text => {
|
|
52
|
+
const names = text.split(",").map(name => name.trim());
|
|
53
|
+
if (!names.length || names.some(name => !name || name.length > 120 || /[\p{Cc}]/u.test(name)) || new Set(names).size !== names.length || names.length > 32) throw new Error("--required-checks needs 1 to 32 distinct check names, each at most 120 characters; nothing was written");
|
|
54
|
+
return names;
|
|
55
|
+
} },
|
|
51
56
|
{ id: "coordination", flags: [{ flag: "--coordination" }], file: "config.json", path: ["coordination"], allowed: COORDINATION_MODES.join("|"), describe: "coordination mode", parse: choice("coordination", "--coordination", COORDINATION_MODES) },
|
|
52
57
|
{ id: "memory.enabled", flags: [{ flag: "--memory", value: true }, { flag: "--no-memory", value: false }], file: "config.json", path: ["memory", "enabled"], allowed: "on|off", describe: "shared memory", parse: () => { throw new Error("unreachable"); } },
|
|
58
|
+
{ id: "research.enabled", flags: [{ flag: "--research", value: true }, { flag: "--no-research", value: false }], file: "config.local.json", path: ["research", "enabled"], allowed: "on|off", describe: "research records", parse: () => { throw new Error("unreachable"); } },
|
|
53
59
|
{ id: "snapshots.enabled", flags: [{ flag: "--snapshots", value: true }, { flag: "--no-snapshots", value: false }], file: "config.json", path: ["snapshots", "enabled"], allowed: "on|off", describe: "per-turn snapshots", parse: () => { throw new Error("unreachable"); } },
|
|
54
60
|
// #1064 T3: the design-specs feature. `--no-specs` also removes the AGENT_HUB_SPECS block from AGENTS.md and `--specs` restores it (init.ts reads the planned `specs.enabled`); the key is shared, so a team commits the choice.
|
|
55
61
|
{ id: "specs.enabled", flags: [{ flag: "--specs", value: true }, { flag: "--no-specs", value: false }], file: "config.json", path: ["specs", "enabled"], allowed: "on|off", describe: "design specs and their freshness checks", parse: () => { throw new Error("unreachable"); } },
|
|
@@ -70,7 +76,7 @@ export interface InitSettingsRequest {
|
|
|
70
76
|
}
|
|
71
77
|
|
|
72
78
|
/** The usage line `ahub init` prints for a bad argument; help.ts shows the same flags. */
|
|
73
|
-
export const INIT_USAGE = "usage: ahub init [--profile dev|research|writing|general|<pack>] [--agents <a,b,...|none>] [--sdlc off|advise|enforce] [--coordination advisory|turn-free] [--memory|--no-memory] [--snapshots|--no-snapshots] [--pi|--no-pi] [--specs|--no-specs] [--spec-review off|report|require] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]";
|
|
79
|
+
export const INIT_USAGE = "usage: ahub init [--profile dev|research|writing|general|<pack>] [--agents <a,b,...|none>] [--sdlc off|advise|enforce] [--required-checks <a,b,...>] [--coordination advisory|turn-free] [--memory|--no-memory] [--research|--no-research] [--snapshots|--no-snapshots] [--pi|--no-pi] [--specs|--no-specs] [--spec-review off|report|require] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]";
|
|
74
80
|
|
|
75
81
|
/** Every flag the table and the two non-key choices own, for the caller's own argument loop and for help. */
|
|
76
82
|
export const INIT_SETTING_FLAGS: readonly string[] = [...INIT_SETTINGS.flatMap(row => row.flags.map(flag => flag.flag)), "--autonomy"];
|
|
@@ -207,13 +213,13 @@ export function planInitSettings(request: InitSettingsRequest, texts: InitSettin
|
|
|
207
213
|
if (!Object.hasOwn(request.values, row.id)) continue;
|
|
208
214
|
const to = request.values[row.id];
|
|
209
215
|
if (row.file === "sdlc.toml") {
|
|
210
|
-
let from: unknown = "off";
|
|
216
|
+
let from: unknown = row.id === "sdlc.mode" ? "off" : [];
|
|
211
217
|
if (texts["sdlc.toml"] !== null) {
|
|
212
|
-
try { const
|
|
218
|
+
try { const held = (Bun.TOML.parse(texts["sdlc.toml"]) as Record<string, unknown>)[row.path[0]!]; if (held !== undefined) from = held; }
|
|
213
219
|
catch { throw new Error(".agenthub/sdlc.toml is not valid TOML; fix it in your editor, then run ahub init again; nothing was written"); }
|
|
214
220
|
}
|
|
215
221
|
if (same(from, to)) continue; // off with no file is the shipped state: no file is written for it
|
|
216
|
-
const text = editSdlcText(next["sdlc.toml"] ?? texts["sdlc.toml"], [{ path: [
|
|
222
|
+
const text = editSdlcText(next["sdlc.toml"] ?? texts["sdlc.toml"], [{ path: [...row.path], value: to }]);
|
|
217
223
|
if (text !== null) next["sdlc.toml"] = text;
|
|
218
224
|
rows.push({ key: row.id, file: "sdlc.toml", from, to });
|
|
219
225
|
continue;
|
package/src/cli/init.ts
CHANGED
|
@@ -12,7 +12,9 @@ import { hubGitArgv, hubGitEnv, hubGitSync } from "../hub/git.ts";
|
|
|
12
12
|
import { KIMI_MCP_FILE } from "./kimi-mcp.ts";
|
|
13
13
|
import { AGY_PLUGIN_FILES } from "./agy-mcp.ts";
|
|
14
14
|
import { loadConfig } from "../hub/daemon.ts";
|
|
15
|
-
import {
|
|
15
|
+
import { requiredChecksFor } from "../hub/sdlc-merge.ts";
|
|
16
|
+
import { githubOriginRepository } from "../hub/task-repository.ts";
|
|
17
|
+
import { loadSdlc, sdlcConfig } from "../hub/sdlc.ts";
|
|
16
18
|
import { VERSION } from "../version.ts";
|
|
17
19
|
import { planInitSettings, type InitSettingFile, type InitSettingRow, type InitSettingsRequest } from "./init-settings.ts";
|
|
18
20
|
|
|
@@ -249,7 +251,7 @@ function changes(cwd: string, requestedName?: string, shadow = false, releaseGua
|
|
|
249
251
|
for (const name of Object.keys(result.next) as InitSettingFile[]) {
|
|
250
252
|
const path = files[name], text = result.next[name]!;
|
|
251
253
|
const row = changed.find(entry => entry.path === path);
|
|
252
|
-
const reason = `set ${result.rows.filter(entry => entry.file === name).map(entry => entry.key).join(", ")} from the init
|
|
254
|
+
const reason = `set ${result.rows.filter(entry => entry.file === name).map(entry => entry.key).join(", ")} from the init settings`;
|
|
253
255
|
if (row) { row.next = text; row.reason = `${row.reason}; ${reason}`; }
|
|
254
256
|
else changed.push({ action: existsSync(path) ? "modify" : "create", path, next: text, reason, ...(name === "config.local.json" ? { privateFile: true as const } : {}) });
|
|
255
257
|
}
|
|
@@ -273,7 +275,10 @@ function checkCandidate(cwd: string, plan: readonly PlannedWrite[]): void {
|
|
|
273
275
|
catch (error) { throw new Error(`the resulting .agenthub config does not pass the hub's config check: ${(error as Error).message}; fix that key in your editor, then run ahub init again; nothing was written`); }
|
|
274
276
|
}
|
|
275
277
|
if (sdlc !== undefined) {
|
|
276
|
-
try {
|
|
278
|
+
try {
|
|
279
|
+
const lifecycle = sdlcConfig(Bun.TOML.parse(sdlc), VERSION);
|
|
280
|
+
if (lifecycle.mode === "enforce" && !requiredChecksFor(lifecycle, githubOriginRepository(cwd)).length) throw new Error("enforce needs required CI checks; pass --required-checks <a,b,...>");
|
|
281
|
+
}
|
|
277
282
|
catch (error) { throw new Error(`the resulting .agenthub/sdlc.toml does not pass the hub's check: ${(error as Error).message}; fix it in your editor, then run ahub init again; nothing was written`); }
|
|
278
283
|
}
|
|
279
284
|
}
|
|
@@ -296,6 +301,37 @@ export function planInit(cwd: string, profile?: string, shadow = false, releaseG
|
|
|
296
301
|
export function initSettingRows(cwd: string, profile?: string, shadow = false, releaseGuard = false, settings?: InitSettingsRequest): InitSettingRow[] {
|
|
297
302
|
return changes(cwd, profile, shadow, releaseGuard, settings).settingRows;
|
|
298
303
|
}
|
|
304
|
+
/** A pre-existing local project choice wins; missing or unreadable machine defaults are off. Validation still runs before any write. */
|
|
305
|
+
export function initResearchDefault(cwd: string, machineValue: boolean | undefined): boolean {
|
|
306
|
+
const local = join(cwd, ".agenthub", "config.local.json");
|
|
307
|
+
try {
|
|
308
|
+
if (existsSync(local)) {
|
|
309
|
+
const value = JSON.parse(readFileSync(local, "utf8"))?.research?.enabled;
|
|
310
|
+
if (typeof value === "boolean") return value;
|
|
311
|
+
}
|
|
312
|
+
} catch { /* the init candidate validation reports malformed local files before writes */ }
|
|
313
|
+
return machineValue === true;
|
|
314
|
+
}
|
|
315
|
+
/** Add only a new project's effective on default to the normal plan. Off is the shipped default; explicit flags always win. Never writes machine defaults. */
|
|
316
|
+
export function withInitResearch(cwd: string, request: InitSettingsRequest, machineValue: boolean | undefined): InitSettingsRequest {
|
|
317
|
+
if (existsSync(join(cwd, ".agenthub", "config.json")) || Object.hasOwn(request.values, "research.enabled") || !initResearchDefault(cwd, machineValue)) return request;
|
|
318
|
+
return { ...request, values: { ...request.values, "research.enabled": true } };
|
|
319
|
+
}
|
|
320
|
+
/** Prepare person guidance before writes; the CLI prints it only after successful apply. Creates no lifecycle evidence or acceptance. */
|
|
321
|
+
export function initNextSteps(cwd: string, settings?: InitSettingsRequest): string[] {
|
|
322
|
+
const lines = [
|
|
323
|
+
"Next steps:",
|
|
324
|
+
"- Review and commit AGENTS.md, .agenthub/config.json and other shared init changes; keep config.local.json untracked.",
|
|
325
|
+
"- Start with ahub up or ahub claude; sessions started otherwise miss hub pushes.",
|
|
326
|
+
];
|
|
327
|
+
const mode = settings?.values["sdlc.mode"] ?? loadSdlc(cwd, VERSION).mode;
|
|
328
|
+
if (mode !== "off") lines.push(
|
|
329
|
+
`- SDLC ${mode}: accept the planner-recorded spec with ahub sdlc accept <task> --issue <n>.`,
|
|
330
|
+
"- When a plan departure needs your consent: ahub sdlc accept-departure <task> <head> <reason...>.",
|
|
331
|
+
"- After hub_task_done on the open PR, reviewer approval and green exact-head CI, use guarded merge: ahub sdlc merge <task>.",
|
|
332
|
+
);
|
|
333
|
+
return lines;
|
|
334
|
+
}
|
|
299
335
|
/** Returns the paths it changed, applying the same plan as the preview. */
|
|
300
336
|
export function init(cwd: string, profile?: string, shadow = false, releaseGuard = false, settings?: InitSettingsRequest): string[] {
|
|
301
337
|
const plan = changes(cwd, profile, shadow, releaseGuard, settings).writes;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { factsHook } from "./facts-hook.ts";
|
|
3
|
+
|
|
4
|
+
try {
|
|
5
|
+
const stateDir = process.env.AGENTHUB_STATE_DIR, event = process.argv[2], peer = process.env.AGENTHUB_PEER_ID;
|
|
6
|
+
const out = stateDir && event && peer ? await factsHook(await Bun.stdin.text(), stateDir, peer, 2000, event) : undefined;
|
|
7
|
+
if (out) console.log(out);
|
|
8
|
+
} catch {
|
|
9
|
+
// Native hooks fail open; a missing or refused observation never changes the turn.
|
|
10
|
+
}
|
|
11
|
+
process.exit(0);
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { closeSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmdirSync, unlinkSync, writeFileSync, type Stats } from "node:fs";
|
|
3
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
4
|
+
import { processLiveness, processSignature } from "../pi/process-signature.ts";
|
|
5
|
+
|
|
6
|
+
export interface KimiPluginOptions { home: string; hookScript: string; launchId: string; replaceStale?: boolean; now?: number; ownerPid?: number; ownerSignature?: string; liveness?: typeof processLiveness }
|
|
7
|
+
type JsonObject = Record<string, any>;
|
|
8
|
+
type Snapshot = { stat: Stats; bytes: Buffer };
|
|
9
|
+
type Target = { path: string; next: Buffer; before?: Snapshot };
|
|
10
|
+
type Plan = { root: string; managed: string; installed: string; record?: JsonObject; targets: Target[]; changed: boolean };
|
|
11
|
+
|
|
12
|
+
const EVENTS = ["TurnStarted", "Stop", "StopFailure", "Interrupt", "SessionEnd", "TaskStarted", "Notification"] as const;
|
|
13
|
+
const ID = "agent-hub";
|
|
14
|
+
const MAX_INSTALLED = 1024 * 1024;
|
|
15
|
+
const MAX_HOOK = 8 * 1024 * 1024;
|
|
16
|
+
const object = (value: unknown): value is JsonObject => !!value && typeof value === "object" && !Array.isArray(value);
|
|
17
|
+
const directory = (path: string, required = true) => {
|
|
18
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
19
|
+
if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error(`${path} must be a plain directory`);
|
|
20
|
+
if (!stat && required) throw new Error(`${path} must exist`);
|
|
21
|
+
return stat;
|
|
22
|
+
};
|
|
23
|
+
function file(path: string, cap: number): Snapshot | undefined {
|
|
24
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
25
|
+
if (!stat) return undefined;
|
|
26
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > cap) throw new Error(`${path} must be a bounded regular file`);
|
|
27
|
+
return { stat, bytes: readFileSync(path) };
|
|
28
|
+
}
|
|
29
|
+
function parse(value: Snapshot | undefined, name: string): JsonObject | undefined {
|
|
30
|
+
if (!value) return undefined;
|
|
31
|
+
try {
|
|
32
|
+
const row = JSON.parse(value.bytes.toString("utf8"));
|
|
33
|
+
if (!object(row)) throw new Error("not an object");
|
|
34
|
+
return row;
|
|
35
|
+
} catch { throw new Error(`${name} is not valid JSON`); }
|
|
36
|
+
}
|
|
37
|
+
function atomic(path: string, bytes: Buffer, before: Stats | undefined): void {
|
|
38
|
+
const current = lstatSync(path, { throwIfNoEntry: false });
|
|
39
|
+
if (before ? !current || current.dev !== before.dev || current.ino !== before.ino : current) throw new Error(`${path} changed before its managed write`);
|
|
40
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
41
|
+
let fd: number | undefined;
|
|
42
|
+
try {
|
|
43
|
+
fd = openSync(temporary, "wx", 0o600);
|
|
44
|
+
writeFileSync(fd, bytes);
|
|
45
|
+
closeSync(fd); fd = undefined;
|
|
46
|
+
renameSync(temporary, path);
|
|
47
|
+
} finally {
|
|
48
|
+
if (fd !== undefined) closeSync(fd);
|
|
49
|
+
try { unlinkSync(temporary); } catch { /* rename consumed it */ }
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function removeFile(path: string, expected: Buffer): void {
|
|
53
|
+
const current = lstatSync(path, { throwIfNoEntry: false });
|
|
54
|
+
if (!current || !current.isFile() || current.isSymbolicLink() || current.nlink !== 1 || !readFileSync(path).equals(expected)) return;
|
|
55
|
+
unlinkSync(path);
|
|
56
|
+
}
|
|
57
|
+
function manifest(): JsonObject {
|
|
58
|
+
return { name: ID, version: "1.0.0", description: "Managed by the ahub kimi launcher for this launch only.", hooks: EVENTS.map(event => ({ event, command: `bun ./kimi-hook.js ${event}`, timeout: 5 })) };
|
|
59
|
+
}
|
|
60
|
+
function ownerProof(options: KimiPluginOptions): { pid: number; signature: string } {
|
|
61
|
+
const pid = options.ownerPid ?? process.pid, signature = options.ownerSignature ?? processSignature(pid);
|
|
62
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || !signature) throw new Error("Kimi plugin ownership cannot be proven");
|
|
63
|
+
return { pid, signature };
|
|
64
|
+
}
|
|
65
|
+
function staleOwner(record: JsonObject, options: KimiPluginOptions): boolean {
|
|
66
|
+
const owner = record.agentHubOwner;
|
|
67
|
+
if (!object(owner) || !Number.isSafeInteger(owner.pid) || owner.pid <= 0 || typeof owner.signature !== "string" || !owner.signature) return false;
|
|
68
|
+
try { return (options.liveness ?? processLiveness)(owner.pid, owner.signature) === "gone"; } catch { return false; }
|
|
69
|
+
}
|
|
70
|
+
function plan(options: KimiPluginOptions): Plan {
|
|
71
|
+
if (!isAbsolute(options.home) || !isAbsolute(options.hookScript) || !/^[A-Za-z0-9._:-]{1,128}$/.test(options.launchId)) throw new Error("Kimi home, hook bundle and launch identity must be valid");
|
|
72
|
+
directory(options.home);
|
|
73
|
+
const hook = file(options.hookScript, MAX_HOOK);
|
|
74
|
+
if (!hook) throw new Error("Kimi hook bundle is missing");
|
|
75
|
+
const root = join(options.home, "plugins"), managed = join(root, "managed", ID), installed = join(root, "installed.json");
|
|
76
|
+
const installedBefore = file(installed, MAX_INSTALLED), document = parse(installedBefore, installed);
|
|
77
|
+
if (document && (document.version !== 1 || !Array.isArray(document.plugins))) throw new Error(`${installed} has an unsupported shape`);
|
|
78
|
+
const records = document?.plugins ?? [];
|
|
79
|
+
if (records.some((row: unknown) => !object(row))) throw new Error(`${installed} has an invalid plugin row`);
|
|
80
|
+
const record = records.find((row: JsonObject) => row.id === ID);
|
|
81
|
+
if (record && record.agentHubLaunch !== options.launchId && options.replaceStale === true && !staleOwner(record, options)) throw new Error("Kimi's agent-hub plugin owner is active or unknown; it was not changed");
|
|
82
|
+
if (record && (record.root !== managed || record.source !== "local-path" || record.origin !== "custom" || record.enabled !== true || typeof record.originalSource !== "string"
|
|
83
|
+
|| record.agentHubLaunch !== options.launchId && options.replaceStale !== true)) {
|
|
84
|
+
throw new Error("Kimi's agent-hub plugin belongs to another launch or is disabled; it was not changed");
|
|
85
|
+
}
|
|
86
|
+
const manifestBefore = file(join(managed, "kimi.plugin.json"), MAX_INSTALLED), hookBefore = file(join(managed, "kimi-hook.js"), MAX_HOOK);
|
|
87
|
+
const nextManifest = Buffer.from(`${JSON.stringify(manifest(), null, 2)}\n`);
|
|
88
|
+
const now = new Date(options.now ?? Date.now()).toISOString();
|
|
89
|
+
const changed = !record || record.agentHubLaunch !== options.launchId || !record.agentHubOwner || !manifestBefore?.bytes.equals(nextManifest) || !hookBefore?.bytes.equals(hook.bytes) || record.originalSource !== dirname(options.hookScript);
|
|
90
|
+
const nextRecord = {
|
|
91
|
+
id: ID, root: managed, source: "local-path", origin: "custom", enabled: true,
|
|
92
|
+
installedAt: typeof record?.installedAt === "string" ? record.installedAt : now,
|
|
93
|
+
updatedAt: changed ? now : typeof record?.updatedAt === "string" ? record.updatedAt : now,
|
|
94
|
+
originalSource: dirname(options.hookScript), agentHubLaunch: options.launchId,
|
|
95
|
+
agentHubOwner: record && record.agentHubLaunch === options.launchId && record.agentHubOwner ? record.agentHubOwner : ownerProof(options),
|
|
96
|
+
};
|
|
97
|
+
const nextDocument = { version: 1, plugins: [...records.filter((row: JsonObject) => row.id !== ID), nextRecord] };
|
|
98
|
+
return { root, managed, installed, ...(record ? { record } : {}), changed,
|
|
99
|
+
targets: [
|
|
100
|
+
{ path: join(managed, "kimi.plugin.json"), next: nextManifest, ...(manifestBefore ? { before: manifestBefore } : {}) },
|
|
101
|
+
{ path: join(managed, "kimi-hook.js"), next: hook.bytes, ...(hookBefore ? { before: hookBefore } : {}) },
|
|
102
|
+
{ path: installed, next: Buffer.from(`${JSON.stringify(nextDocument, null, 2)}\n`), ...(installedBefore ? { before: installedBefore } : {}) },
|
|
103
|
+
] };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function kimiPluginPreview(home: string, hookScript: string): { file: string; changed: true; action: string } {
|
|
107
|
+
if (!isAbsolute(home) || !isAbsolute(hookScript)) throw new Error("Kimi home and hook bundle must be absolute paths");
|
|
108
|
+
directory(home, false);
|
|
109
|
+
if (!file(hookScript, MAX_HOOK)) throw new Error("Kimi hook bundle is missing");
|
|
110
|
+
return { file: join(home, "plugins", "managed", ID), changed: true, action: "only after Kimi 2.5.2 is confirmed, install the launch-scoped completion plugin and remove it on exit; other versions keep the existing TUI with no plugin" };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function kimiPluginPlan(options: KimiPluginOptions): { file: string; changed: boolean; action: string } {
|
|
114
|
+
const current = plan(options);
|
|
115
|
+
return { file: current.managed, changed: current.changed, action: current.changed ? "create or update the launch-scoped Kimi plugin" : "keep the launch-scoped Kimi plugin" };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function locked<T>(options: KimiPluginOptions, run: () => T): T {
|
|
119
|
+
if (!isAbsolute(options.home)) throw new Error("Kimi home must be an absolute path");
|
|
120
|
+
directory(options.home);
|
|
121
|
+
const path = join(options.home, "agent-hub-plugin.lock");
|
|
122
|
+
let fd: number;
|
|
123
|
+
try { fd = openSync(path, "wx", 0o600); }
|
|
124
|
+
catch { throw new Error(`Another Kimi plugin replacement is active or left a stale lock; retry after it exits or inspect ${path}`); }
|
|
125
|
+
try { return run(); }
|
|
126
|
+
finally { closeSync(fd); unlinkSync(path); }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function ensureKimiPlugin(options: KimiPluginOptions): { changed: boolean } {
|
|
130
|
+
return locked(options, () => {
|
|
131
|
+
const current = plan(options);
|
|
132
|
+
if (!current.changed) return { changed: false };
|
|
133
|
+
for (const path of [join(options.home, "plugins"), join(options.home, "plugins", "managed"), current.managed]) {
|
|
134
|
+
if (!directory(path, false)) mkdirSync(path, { mode: 0o700 });
|
|
135
|
+
}
|
|
136
|
+
for (const target of current.targets) atomic(target.path, target.next, target.before?.stat);
|
|
137
|
+
return { changed: true };
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function cleanupKimiPlugin(options: KimiPluginOptions): void {
|
|
142
|
+
locked(options, () => {
|
|
143
|
+
const current = plan({ ...options, replaceStale: false });
|
|
144
|
+
const installedBefore = file(current.installed, MAX_INSTALLED), document = parse(installedBefore, current.installed);
|
|
145
|
+
const records = document?.plugins;
|
|
146
|
+
if (!document || !Array.isArray(records) || records.some((row: unknown) => !object(row))) throw new Error(`${current.installed} changed during the launch`);
|
|
147
|
+
const record = records.find((row: JsonObject) => row.id === ID);
|
|
148
|
+
if (!record) return;
|
|
149
|
+
if (record.root !== current.managed || record.enabled !== true) throw new Error("Kimi's agent-hub plugin changed during the launch; leaving it installed");
|
|
150
|
+
const next = { version: 1, plugins: records.filter((row: JsonObject) => row.id !== ID) };
|
|
151
|
+
atomic(current.installed, Buffer.from(`${JSON.stringify(next, null, 2)}\n`), installedBefore?.stat);
|
|
152
|
+
const [manifestTarget, hookTarget] = current.targets;
|
|
153
|
+
removeFile(join(current.managed, "kimi.plugin.json"), manifestTarget!.next);
|
|
154
|
+
removeFile(join(current.managed, "kimi-hook.js"), hookTarget!.next);
|
|
155
|
+
try { rmdirSync(current.managed); } catch { /* foreign or changed files stay */ }
|
|
156
|
+
});
|
|
157
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { executionReferenceKey, executionText, parseExecutionReference, type ExecutionReferenceV1 } from "../hub/execution-reference.ts";
|
|
2
|
+
import { LINEAGE_LIMITS, type LineageResult } from "../hub/execution-lineage.ts";
|
|
3
|
+
import { executionLineageLines } from "../ui/lineage-view.ts";
|
|
4
|
+
import { terminalText } from "./console-state.ts";
|
|
5
|
+
|
|
6
|
+
export const LINEAGE_USAGE = "usage: ahub lineage show (--task N | --attempt ra-id | --root JSON [--task-scope N --task-created MS]) [--cursor TOKEN] [--nodes N --edges N --bytes N] [--json] | link --task N --task-created MS --revision N --ref JSON [--from JSON] [--json]";
|
|
7
|
+
type Show = { op: "show"; json: boolean; taskId?: number; attemptId?: string; root?: ExecutionReferenceV1; task?: { id: number; created: number }; cursor?: string; nodes?: number; edges?: number; bytes?: number };
|
|
8
|
+
type Link = { op: "link"; json: boolean; taskId: number; taskCreated: number; flowRevision: number; reference: ExecutionReferenceV1; from?: ExecutionReferenceV1 };
|
|
9
|
+
const invalid = (): never => { throw new Error(`invalid lineage arguments; ${LINEAGE_USAGE}`); };
|
|
10
|
+
const integer = (raw: string | undefined, minimum: number, maximum = Number.MAX_SAFE_INTEGER): number => {
|
|
11
|
+
if (raw === undefined || !/^(0|[1-9][0-9]*)$/.test(raw)) return invalid();
|
|
12
|
+
const value = Number(raw);
|
|
13
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) return invalid();
|
|
14
|
+
return value;
|
|
15
|
+
};
|
|
16
|
+
function reference(raw: string | undefined): ExecutionReferenceV1 {
|
|
17
|
+
if (raw === undefined || Buffer.byteLength(raw) > 8192) return invalid();
|
|
18
|
+
try { return parseExecutionReference(JSON.parse(raw)); } catch { return invalid(); }
|
|
19
|
+
}
|
|
20
|
+
/** Shortcuts remain selectors: only the source host can supply their project identity. */
|
|
21
|
+
export function parseLineageCommand(args: readonly string[]): Show | Link {
|
|
22
|
+
const [op, ...rest] = args;
|
|
23
|
+
if (op !== "show" && op !== "link") return invalid();
|
|
24
|
+
const values = new Map<string, string>(); let json = false;
|
|
25
|
+
const allowed = op === "show"
|
|
26
|
+
? ["--task", "--attempt", "--root", "--task-scope", "--task-created", "--cursor", "--nodes", "--edges", "--bytes"]
|
|
27
|
+
: ["--task", "--task-created", "--revision", "--ref", "--from"];
|
|
28
|
+
for (let i = 0; i < rest.length; i++) {
|
|
29
|
+
const flag = rest[i]!;
|
|
30
|
+
if (flag === "--json") { if (json) return invalid(); json = true; continue; }
|
|
31
|
+
if (!allowed.includes(flag) || values.has(flag)) return invalid();
|
|
32
|
+
const value = rest[++i]; if (value === undefined || value.startsWith("--")) return invalid();
|
|
33
|
+
values.set(flag, value);
|
|
34
|
+
}
|
|
35
|
+
if (op === "link") return { op, json, taskId: integer(values.get("--task"), 1), taskCreated: integer(values.get("--task-created"), 0),
|
|
36
|
+
flowRevision: integer(values.get("--revision"), 0), reference: reference(values.get("--ref")),
|
|
37
|
+
...(values.has("--from") ? { from: reference(values.get("--from")) } : {}) };
|
|
38
|
+
if (["--task", "--attempt", "--root"].filter(key => values.has(key)).length !== 1) return invalid();
|
|
39
|
+
const result: Show = { op, json };
|
|
40
|
+
if (values.has("--task")) result.taskId = integer(values.get("--task"), 1);
|
|
41
|
+
if (values.has("--attempt")) {
|
|
42
|
+
const attemptId = values.get("--attempt")!;
|
|
43
|
+
if (!/^ra-[0-9a-f]{12}$/.test(attemptId)) return invalid();
|
|
44
|
+
result.attemptId = attemptId;
|
|
45
|
+
}
|
|
46
|
+
if (values.has("--root")) result.root = reference(values.get("--root"));
|
|
47
|
+
if (values.has("--task-scope") || values.has("--task-created")) {
|
|
48
|
+
if (!result.root) return invalid();
|
|
49
|
+
result.task = { id: integer(values.get("--task-scope"), 1), created: integer(values.get("--task-created"), 0) };
|
|
50
|
+
}
|
|
51
|
+
if (values.has("--cursor")) {
|
|
52
|
+
const cursor = values.get("--cursor")!;
|
|
53
|
+
if (cursor.length > LINEAGE_LIMITS.cursor || !/^[A-Za-z0-9_-]+$/.test(cursor)) return invalid();
|
|
54
|
+
result.cursor = cursor;
|
|
55
|
+
}
|
|
56
|
+
if (values.has("--nodes")) result.nodes = integer(values.get("--nodes"), 1, LINEAGE_LIMITS.nodes);
|
|
57
|
+
if (values.has("--edges")) result.edges = integer(values.get("--edges"), 1, LINEAGE_LIMITS.edges);
|
|
58
|
+
if (values.has("--bytes")) result.bytes = integer(values.get("--bytes"), LINEAGE_LIMITS.minimumBytes, LINEAGE_LIMITS.bytes);
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The closed shape check lives in the hub module, beside the reader that produces it, so the console reads it identically (#1220 T3). */
|
|
63
|
+
export { parseLineageResult as validateLineageReply } from "../hub/execution-lineage.ts";
|
|
64
|
+
export interface LineageLinkReceipt { id: string; taskId: number; reference: ExecutionReferenceV1; strength: "declared"; already: boolean }
|
|
65
|
+
export function validateLineageLink(value: unknown, command: { taskId: number; reference: ExecutionReferenceV1 }): LineageLinkReceipt {
|
|
66
|
+
const bad = (): never => { throw new Error("lineage link reply is unconfirmed; inspect ahub lineage show before retrying the link"); };
|
|
67
|
+
try {
|
|
68
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Buffer.byteLength(JSON.stringify(value)) > 8192) return bad();
|
|
69
|
+
const row = value as Record<string, unknown>, keys = ["id", "taskId", "reference", "strength", "already"];
|
|
70
|
+
if (Object.keys(row).length !== keys.length || !keys.every(key => Object.hasOwn(row, key)) || !executionText(row.id, 256) ||
|
|
71
|
+
row.taskId !== command.taskId || row.strength !== "declared" || typeof row.already !== "boolean" ||
|
|
72
|
+
executionReferenceKey(parseExecutionReference(row.reference)) !== executionReferenceKey(command.reference)) return bad();
|
|
73
|
+
return value as LineageLinkReceipt;
|
|
74
|
+
} catch { return bad(); }
|
|
75
|
+
}
|
|
76
|
+
/** The CLI is a terminal: the shared view crosses `terminalText` here, at this surface's own boundary. */
|
|
77
|
+
export const renderExecutionLineage = (result: LineageResult): string[] =>
|
|
78
|
+
executionLineageLines(result).map(line => terminalText(line).replace(/[\r\n]+/g, " "));
|