@akagilnc/pi-workflow-roles 0.1.3758 → 0.1.3783
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/README.md +3 -2
- package/README.zh-CN.md +3 -2
- package/dist/acp-host/production-host.js +1735 -948
- package/dist/collector-config.js +0 -1
- package/dist/collector-github.js +199 -2
- package/dist/collector-identity.js +128 -41
- package/dist/collector-ledger.js +38 -9
- package/dist/collector-receipt.js +19 -7
- package/dist/collector-role.js +330 -369
- package/dist/collector-target.js +169 -0
- package/dist/collector-tool-schemas.js +51 -14
- package/dist/headless-host/description.js +77 -0
- package/dist/headless-host/mcp-relay.mjs +119 -0
- package/dist/headless-host/production-host.js +26590 -0
- package/dist/host-descriptions.js +44 -3
- package/dist/package-contracts/collector-output.js +32 -0
- package/dist/package-contracts/terminating-infrastructure.js +13 -12
- package/dist/pi/role-turn-host.js +1 -2
- package/dist/public-cli/github-remote.js +45 -0
- package/dist/public-cli/invocation.js +53 -54
- package/dist/public-cli/load-production-external-host.js +19 -0
- package/dist/public-cli/load-production-headless-host.js +36 -0
- package/dist/public-cli/main.js +857 -310
- package/dist/public-cli/option-definitions.js +6 -4
- package/dist/public-cli/run-lifecycle.js +3 -3
- package/dist/public-cli/settlement.js +83 -6
- package/dist/public-role-summons.js +40 -5
- package/dist/role-runtime.js +137 -7
- package/dist/submission-correctable-error.js +24 -0
- package/extensions/role-runtime.ts +0 -1
- package/package.json +1 -1
- package/scripts/build-package.mjs +28 -0
- package/src/acp-host/role-envelope.ts +146 -103
- package/src/acp-host/role-turn-host.ts +12 -0
- package/src/collector-config.ts +0 -1
- package/src/collector-github.ts +236 -2
- package/src/collector-identity.ts +148 -40
- package/src/collector-ledger.ts +48 -10
- package/src/collector-receipt.ts +33 -14
- package/src/collector-role.ts +376 -450
- package/src/collector-target.ts +207 -0
- package/src/collector-tool-schemas.ts +62 -15
- package/src/headless-host/description.ts +123 -0
- package/src/headless-host/production-host.ts +75 -0
- package/src/headless-host/role-turn-host.ts +424 -0
- package/src/host-contracts.ts +2 -1
- package/src/host-descriptions.ts +53 -6
- package/src/package-contracts/collector-output.ts +72 -0
- package/src/package-contracts/terminating-infrastructure.ts +24 -13
- package/src/pi/role-turn-host.ts +1 -2
- package/src/public-cli/cli.ts +12 -3
- package/src/public-cli/collector-run.ts +3 -2
- package/src/public-cli/github-remote.ts +45 -0
- package/src/public-cli/invocation.ts +60 -59
- package/src/public-cli/load-production-external-host.ts +29 -0
- package/src/public-cli/load-production-headless-host.ts +48 -0
- package/src/public-cli/main.ts +5 -0
- package/src/public-cli/option-definitions.ts +6 -4
- package/src/public-cli/run-lifecycle.ts +2 -2
- package/src/public-cli/settlement.ts +82 -6
- package/src/public-role-summons.ts +62 -9
- package/src/role-runtime.ts +166 -13
- package/src/submission-correctable-error.ts +38 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #676 D1: Collector admission target recognition on structured git context.
|
|
3
|
+
* Explicit PR wins (no association queries). Otherwise gather online candidates
|
|
4
|
+
* from structured upstream head and HEAD commit association only. Deduped unique
|
|
5
|
+
* → bind; many → require explicit --pr; zero → unbound so the role can decide
|
|
6
|
+
* from task materials via the bind-target business tool. No task-text scrape,
|
|
7
|
+
* no second state machine. Git/config/transport failures keep true cause.
|
|
8
|
+
*/
|
|
9
|
+
import { execFileSync } from "node:child_process";
|
|
10
|
+
import { createGhApiRunner, listPullRequestNumbersByCommit, listPullRequestNumbersByHead, } from "./collector-github.js";
|
|
11
|
+
import { CliUsageError } from "./public-cli/cli-errors.js";
|
|
12
|
+
import { ownerFromGitHubRemoteUrl, ownerRepoFromGitHubRemoteUrl, } from "./public-cli/github-remote.js";
|
|
13
|
+
function ambiguousTarget(detail, cause) {
|
|
14
|
+
throw new CliUsageError(`collector target is ambiguous: ${detail}; pass an explicit --pr`, cause === undefined ? undefined : { cause });
|
|
15
|
+
}
|
|
16
|
+
/** Real git failure — not target ambiguity. Propagates with true cause on exit 1. */
|
|
17
|
+
function gitFailure(detail, cause) {
|
|
18
|
+
throw new Error(`collector git failed: ${detail}`, {
|
|
19
|
+
cause: cause instanceof Error ? cause : new Error(String(cause)),
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
function gitText(projectRoot, args) {
|
|
23
|
+
return execFileSync("git", [...args], {
|
|
24
|
+
cwd: projectRoot,
|
|
25
|
+
encoding: "utf8",
|
|
26
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
27
|
+
}).trim();
|
|
28
|
+
}
|
|
29
|
+
/** git config --get exit 1 = key absent; other failures keep true cause. */
|
|
30
|
+
function isGitConfigMissing(error) {
|
|
31
|
+
if (typeof error !== "object" || error === null)
|
|
32
|
+
return false;
|
|
33
|
+
const status = error.status;
|
|
34
|
+
return status === 1;
|
|
35
|
+
}
|
|
36
|
+
function readCurrentBranch(projectRoot) {
|
|
37
|
+
try {
|
|
38
|
+
return gitText(projectRoot, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
gitFailure("cannot read current git branch", error);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function readHeadSha(projectRoot) {
|
|
45
|
+
try {
|
|
46
|
+
return gitText(projectRoot, ["rev-parse", "HEAD"]);
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
gitFailure("cannot read current HEAD", error);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Head ref short name from branch.<name>.merge (refs/heads/<ref> or bare ref).
|
|
54
|
+
* Non-heads merge forms are not a structured head binding.
|
|
55
|
+
*/
|
|
56
|
+
function headRefFromMerge(merge) {
|
|
57
|
+
const trimmed = merge.trim();
|
|
58
|
+
if (trimmed.length === 0)
|
|
59
|
+
return undefined;
|
|
60
|
+
if (trimmed.startsWith("refs/heads/")) {
|
|
61
|
+
const ref = trimmed.slice("refs/heads/".length);
|
|
62
|
+
return ref.length > 0 ? ref : undefined;
|
|
63
|
+
}
|
|
64
|
+
// Reject other refs/* (e.g. refs/remotes/…) — not a PR head ref binding.
|
|
65
|
+
if (trimmed.startsWith("refs/"))
|
|
66
|
+
return undefined;
|
|
67
|
+
return trimmed;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Real upstream head owner + head ref from branch.<name>.remote/merge when configured.
|
|
71
|
+
* Missing config keys = not configured (undefined). Config/remote execution failures
|
|
72
|
+
* throw with true cause — never swallowed as "no upstream, keep fallback".
|
|
73
|
+
*/
|
|
74
|
+
function readUpstreamHeadBinding(projectRoot, branch) {
|
|
75
|
+
let remote;
|
|
76
|
+
try {
|
|
77
|
+
remote = gitText(projectRoot, ["config", "--get", `branch.${branch}.remote`]);
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (isGitConfigMissing(error))
|
|
81
|
+
remote = undefined;
|
|
82
|
+
else
|
|
83
|
+
gitFailure(`cannot read branch.${branch}.remote`, error);
|
|
84
|
+
}
|
|
85
|
+
if (remote === undefined || remote.length === 0)
|
|
86
|
+
return undefined;
|
|
87
|
+
let merge;
|
|
88
|
+
try {
|
|
89
|
+
merge = gitText(projectRoot, ["config", "--get", `branch.${branch}.merge`]);
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (isGitConfigMissing(error))
|
|
93
|
+
merge = undefined;
|
|
94
|
+
else
|
|
95
|
+
gitFailure(`cannot read branch.${branch}.merge`, error);
|
|
96
|
+
}
|
|
97
|
+
if (merge === undefined || merge.length === 0)
|
|
98
|
+
return undefined;
|
|
99
|
+
const headRef = headRefFromMerge(merge);
|
|
100
|
+
if (headRef === undefined)
|
|
101
|
+
return undefined;
|
|
102
|
+
let remoteUrl;
|
|
103
|
+
try {
|
|
104
|
+
remoteUrl = gitText(projectRoot, ["remote", "get-url", remote]);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
gitFailure(`cannot read remote URL for ${remote}`, error);
|
|
108
|
+
}
|
|
109
|
+
const headOwner = ownerFromGitHubRemoteUrl(remoteUrl);
|
|
110
|
+
if (headOwner === undefined)
|
|
111
|
+
return undefined;
|
|
112
|
+
return { headOwner, headRef };
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Resolve the Collector PR target without guessing from task text.
|
|
116
|
+
* - Explicit `--pr` → that number (no association queries).
|
|
117
|
+
* - Otherwise: full online candidates (upstream head + HEAD commit), deduped.
|
|
118
|
+
* - Exactly 1 → bound. >1 → require explicit `--pr`. 0 → unbound (role bind tool).
|
|
119
|
+
* - Git/config/transport/HTTP/JSON failures propagate with true cause.
|
|
120
|
+
*/
|
|
121
|
+
export async function resolveCollectorTarget(input) {
|
|
122
|
+
if (input.explicitPrNumber !== undefined) {
|
|
123
|
+
return { kind: "bound", prNumber: input.explicitPrNumber };
|
|
124
|
+
}
|
|
125
|
+
const branch = readCurrentBranch(input.projectRoot);
|
|
126
|
+
const detached = branch.length === 0 || branch === "HEAD";
|
|
127
|
+
// Detached HEAD cannot associate via branch head; commit association still runs.
|
|
128
|
+
const runner = createGhApiRunner();
|
|
129
|
+
const { owner, repo } = input.repository;
|
|
130
|
+
const numbers = [];
|
|
131
|
+
if (!detached) {
|
|
132
|
+
const headSha = readHeadSha(input.projectRoot);
|
|
133
|
+
const upstream = readUpstreamHeadBinding(input.projectRoot, branch);
|
|
134
|
+
// Prefer structured head owner:ref from real upstream merge binding (fork-safe).
|
|
135
|
+
if (upstream !== undefined) {
|
|
136
|
+
numbers.push(...(await listPullRequestNumbersByHead(runner, {
|
|
137
|
+
owner,
|
|
138
|
+
repo,
|
|
139
|
+
headOwner: upstream.headOwner,
|
|
140
|
+
headRef: upstream.headRef,
|
|
141
|
+
})));
|
|
142
|
+
}
|
|
143
|
+
// Always also take commit association — never let a sole upstream hit hide a conflict.
|
|
144
|
+
numbers.push(...(await listPullRequestNumbersByCommit(runner, {
|
|
145
|
+
owner,
|
|
146
|
+
repo,
|
|
147
|
+
commitSha: headSha,
|
|
148
|
+
})));
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
// Detached: commit association only (no branch head).
|
|
152
|
+
const headSha = readHeadSha(input.projectRoot);
|
|
153
|
+
numbers.push(...(await listPullRequestNumbersByCommit(runner, {
|
|
154
|
+
owner,
|
|
155
|
+
repo,
|
|
156
|
+
commitSha: headSha,
|
|
157
|
+
})));
|
|
158
|
+
}
|
|
159
|
+
const unique = [...new Set(numbers)];
|
|
160
|
+
if (unique.length === 1) {
|
|
161
|
+
return { kind: "bound", prNumber: unique[0] };
|
|
162
|
+
}
|
|
163
|
+
if (unique.length > 1) {
|
|
164
|
+
ambiguousTarget(`multiple PRs associated with context: ${unique.join(", ")}`);
|
|
165
|
+
}
|
|
166
|
+
// Zero structured git hits — leave unbound so the role can decide from materials.
|
|
167
|
+
return { kind: "unbound" };
|
|
168
|
+
}
|
|
169
|
+
export { ownerRepoFromGitHubRemoteUrl, ownerFromGitHubRemoteUrl };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
2
|
import { COLLECTOR_ELIGIBILITY_MS } from "./collector-evidence.js";
|
|
3
|
+
import { openToolObject } from "./open-tool-schema.js";
|
|
3
4
|
import { withInfrastructureFailureDeclaration } from "./package-contracts/terminating-infrastructure.js";
|
|
4
5
|
export const collectorObserveArgsSchema = Type.Object({}, { additionalProperties: false });
|
|
5
6
|
export const collectorRequestArgsSchema = Type.Object({
|
|
@@ -13,21 +14,57 @@ export const collectorWaitArgsSchema = Type.Object({
|
|
|
13
14
|
durationMs: Type.Integer({ minimum: 1, maximum: COLLECTOR_ELIGIBILITY_MS, description: "等待毫秒;单次上限五分钟且不超剩余资格" }),
|
|
14
15
|
}, { additionalProperties: false });
|
|
15
16
|
/**
|
|
16
|
-
* #
|
|
17
|
-
*
|
|
18
|
-
* the
|
|
19
|
-
* (repo/PR/comment id/url/author/kind/时间) and validates resolvability.
|
|
20
|
-
* Category is a short LLM classification label, never a body transcription.
|
|
17
|
+
* #676 A: role-decided target bind. The model judges task materials and submits
|
|
18
|
+
* the chosen PR and/or issue identity; runtime only performs online association
|
|
19
|
+
* for the role-chosen ticket — never scrapes task text to lock a target.
|
|
21
20
|
*/
|
|
22
|
-
export const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}, { additionalProperties: false });
|
|
26
|
-
export const collectorOutputBaseSchema = Type.Object({
|
|
27
|
-
findings: Type.Optional(Type.Array(collectorFindingArgsSchema, {
|
|
28
|
-
description: "本次收集到的逐条 findings;零 finding 的模板通知不得进入。正常完工无 finding 时省略。",
|
|
21
|
+
export const collectorBindTargetArgsSchema = Type.Object({
|
|
22
|
+
prNumber: Type.Optional(Type.Unknown({
|
|
23
|
+
description: "角色判定的本仓 PR 号(正整数)。与 issueNumber 二选一或同指唯一目标。形状指引,非 schema 闸。",
|
|
29
24
|
})),
|
|
30
|
-
|
|
25
|
+
issueNumber: Type.Optional(Type.Unknown({
|
|
26
|
+
description: "角色判定的本仓 issue 号(正整数);runtime 经线上关联解析唯一 PR。形状指引,非 schema 闸。",
|
|
27
|
+
})),
|
|
28
|
+
}, { additionalProperties: true });
|
|
29
|
+
/**
|
|
30
|
+
* #641 chain① / #676 C / ADR 0057: nested finding item declarations for model
|
|
31
|
+
* guidance. Host must not pure-shape-reject the envelope (第 0 条). Runtime binds
|
|
32
|
+
* resolvable evidence pointers only; unprojected content stays distinguishable.
|
|
33
|
+
*/
|
|
34
|
+
const collectorFindingItemDeclaration = (() => {
|
|
35
|
+
// Nested declarations for model guidance only — open required so host cannot
|
|
36
|
+
// pure-shape-reject missing optional fields (第 0 条 / ADR 0057 / #676 C).
|
|
37
|
+
const item = Type.Object({
|
|
38
|
+
evidenceId: Type.Unknown({
|
|
39
|
+
description: "observe 返回的材料指针(必填语义)",
|
|
40
|
+
}),
|
|
41
|
+
category: Type.Unknown({
|
|
42
|
+
description: "简短归类标签,不是摘要",
|
|
43
|
+
}),
|
|
44
|
+
summary: Type.Unknown({
|
|
45
|
+
description: "哪个 bot、什么问题的摘要;不誊抄正文",
|
|
46
|
+
}),
|
|
47
|
+
}, {
|
|
48
|
+
additionalProperties: true,
|
|
49
|
+
description: "单条 finding 指针:evidenceId + 可选 category/summary。形状指引,非 schema 闸。",
|
|
50
|
+
});
|
|
51
|
+
item.required = [];
|
|
52
|
+
return item;
|
|
53
|
+
})();
|
|
54
|
+
/**
|
|
55
|
+
* Field declarations + descriptions are guidance for the model — host must not
|
|
56
|
+
* pure-shape-reject the envelope (第 0 条 / ADR 0057).
|
|
57
|
+
*/
|
|
58
|
+
export const collectorOutputBaseSchema = openToolObject(Type.Object({
|
|
59
|
+
// No root type:array — host must not shape-reject non-array findings (#676 C).
|
|
60
|
+
// Nested item declarations ride `items` for registration preservation (ADR 0057).
|
|
61
|
+
findings: Type.Unsafe({
|
|
62
|
+
description: "本次收集到的逐条 findings(指针数组为规范形)。零 finding 的模板通知不得进入;正常完工无 finding 时省略。形状指引,非 schema 闸。",
|
|
63
|
+
items: collectorFindingItemDeclaration,
|
|
64
|
+
}),
|
|
65
|
+
unfinishedReasons: Type.Unknown({
|
|
66
|
+
description: "未完成原因字符串数组(额度/故障/等待届满等现场依据);不得把未完成表述为无问题。无可报告时省略。形状指引,非 schema 闸。",
|
|
67
|
+
}),
|
|
68
|
+
}));
|
|
31
69
|
/** Runtime owns the observed evidence; the model submits findings and signals sole-final submission. */
|
|
32
70
|
export const collectorOutputArgsSchema = withInfrastructureFailureDeclaration(collectorOutputBaseSchema);
|
|
33
|
-
collectorOutputArgsSchema.required = [];
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One headless CLI host description (#645 / #752).
|
|
3
|
+
* Every host-specific value the generic headless adapter needs — binary, argv
|
|
4
|
+
* shape, session binding — is data here; lifecycle stays one copy so #646 codex
|
|
5
|
+
* is another row, not a fork.
|
|
6
|
+
*/
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
/** Absolute agent binary for one operator home. */
|
|
9
|
+
export function resolveHeadlessBinary(description, operatorHome) {
|
|
10
|
+
return join(operatorHome, ...description.binaryFromHome);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Build one headless CLI argv for a single process turn.
|
|
14
|
+
* Shape: `<promptFlag> <prompt> <fixedArgs…> <system/schema/mcp/model/effort/session…>`.
|
|
15
|
+
*/
|
|
16
|
+
export function headlessTurnArgs(options) {
|
|
17
|
+
const { description } = options;
|
|
18
|
+
const args = [
|
|
19
|
+
description.promptFlag,
|
|
20
|
+
options.prompt,
|
|
21
|
+
...description.fixedArgs,
|
|
22
|
+
description.systemPromptFlag,
|
|
23
|
+
options.systemPromptPath,
|
|
24
|
+
description.jsonSchemaFlag,
|
|
25
|
+
JSON.stringify(options.jsonSchema),
|
|
26
|
+
];
|
|
27
|
+
if (options.mcpConfigPath !== undefined && options.mcpConfigPath !== "") {
|
|
28
|
+
args.push(description.mcpConfigFlag, options.mcpConfigPath);
|
|
29
|
+
}
|
|
30
|
+
if (options.model !== undefined && options.model !== "") {
|
|
31
|
+
args.push(description.modelFlag, options.model);
|
|
32
|
+
}
|
|
33
|
+
if (options.effort !== undefined && options.effort !== "") {
|
|
34
|
+
args.push(description.effortFlag, options.effort);
|
|
35
|
+
}
|
|
36
|
+
if (options.session.kind === "new") {
|
|
37
|
+
args.push(description.sessionIdFlag, options.session.id);
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
args.push(description.resumeFlag, options.session.id);
|
|
41
|
+
}
|
|
42
|
+
return args;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Project shared-envelope MCP server rows into Claude `--mcp-config` JSON.
|
|
46
|
+
* Env stays a plain object (Claude CLI shape); ACP rows use `{name,value}[]`.
|
|
47
|
+
*/
|
|
48
|
+
export function headlessMcpConfigDocument(mcpServers) {
|
|
49
|
+
const servers = {};
|
|
50
|
+
for (const row of mcpServers) {
|
|
51
|
+
const name = typeof row.name === "string" ? row.name : undefined;
|
|
52
|
+
const command = typeof row.command === "string" ? row.command : undefined;
|
|
53
|
+
if (name === undefined || name === "" || command === undefined || command === "")
|
|
54
|
+
continue;
|
|
55
|
+
const entry = { command };
|
|
56
|
+
if (Array.isArray(row.args))
|
|
57
|
+
entry.args = row.args;
|
|
58
|
+
if (Array.isArray(row.env)) {
|
|
59
|
+
const env = {};
|
|
60
|
+
for (const item of row.env) {
|
|
61
|
+
if (typeof item !== "object" || item === null)
|
|
62
|
+
continue;
|
|
63
|
+
const record = item;
|
|
64
|
+
if (typeof record.name === "string" && typeof record.value === "string") {
|
|
65
|
+
env[record.name] = record.value;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (Object.keys(env).length > 0)
|
|
69
|
+
entry.env = env;
|
|
70
|
+
}
|
|
71
|
+
else if (typeof row.env === "object" && row.env !== null && !Array.isArray(row.env)) {
|
|
72
|
+
entry.env = row.env;
|
|
73
|
+
}
|
|
74
|
+
servers[name] = entry;
|
|
75
|
+
}
|
|
76
|
+
return Object.freeze({ mcpServers: Object.freeze(servers) });
|
|
77
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { connect } from "node:net";
|
|
3
|
+
import { createInterface } from "node:readline";
|
|
4
|
+
|
|
5
|
+
const socketPath = process.env.AK_ACP_MCP_SOCKET;
|
|
6
|
+
const token = process.env.AK_ACP_MCP_TOKEN;
|
|
7
|
+
if (!socketPath || !token) throw new Error("AK ACP MCP relay identity is missing");
|
|
8
|
+
|
|
9
|
+
const upstream = connect(socketPath);
|
|
10
|
+
const waiters = new Map();
|
|
11
|
+
let nextId = 0;
|
|
12
|
+
let terminalError;
|
|
13
|
+
let shutdownRequested = false;
|
|
14
|
+
let exiting = false;
|
|
15
|
+
let inFlight = 0;
|
|
16
|
+
let pendingStdout = 0;
|
|
17
|
+
|
|
18
|
+
function exitStatus() {
|
|
19
|
+
return terminalError === undefined ? 0 : 1;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function maybeExit() {
|
|
23
|
+
if (!shutdownRequested || exiting) return;
|
|
24
|
+
if (inFlight > 0 || waiters.size > 0 || pendingStdout > 0) return;
|
|
25
|
+
exiting = true;
|
|
26
|
+
stdinLines.close();
|
|
27
|
+
if (!upstream.destroyed) upstream.end();
|
|
28
|
+
process.exit(exitStatus());
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function requestShutdown() {
|
|
32
|
+
shutdownRequested = true;
|
|
33
|
+
maybeExit();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function settle(error) {
|
|
37
|
+
if (terminalError !== undefined) return;
|
|
38
|
+
terminalError = error;
|
|
39
|
+
for (const waiter of waiters.values()) waiter.reject(error);
|
|
40
|
+
waiters.clear();
|
|
41
|
+
maybeExit();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
upstream.on("error", (error) => settle(error));
|
|
45
|
+
upstream.on("close", () => {
|
|
46
|
+
// Shutdown may already be requested (stdin EOF) while an RPC is still
|
|
47
|
+
// in flight. Outstanding waiters must still settle, or drain never ends.
|
|
48
|
+
if (!exiting) settle(new Error("AK ACP MCP upstream closed"));
|
|
49
|
+
maybeExit();
|
|
50
|
+
});
|
|
51
|
+
createInterface({ input: upstream }).on("line", (line) => {
|
|
52
|
+
let message;
|
|
53
|
+
try { message = JSON.parse(line); }
|
|
54
|
+
catch (error) { settle(error); upstream.destroy(); return; }
|
|
55
|
+
const waiter = waiters.get(message.id);
|
|
56
|
+
if (waiter === undefined) return;
|
|
57
|
+
waiters.delete(message.id);
|
|
58
|
+
if (message.error !== undefined) {
|
|
59
|
+
const error = new Error(typeof message.error.message === "string" ? message.error.message : "AK ACP MCP relay failure");
|
|
60
|
+
error.code = message.error.code;
|
|
61
|
+
error.cause = message.error;
|
|
62
|
+
waiter.reject(error);
|
|
63
|
+
} else waiter.resolve(message.result);
|
|
64
|
+
maybeExit();
|
|
65
|
+
});
|
|
66
|
+
function request(method, params = {}) {
|
|
67
|
+
if (terminalError !== undefined) return Promise.reject(terminalError);
|
|
68
|
+
const id = ++nextId;
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
waiters.set(id, { resolve, reject });
|
|
71
|
+
upstream.write(`${JSON.stringify({ id, token, method, params })}\n`, (error) => {
|
|
72
|
+
if (error === null || error === undefined) return;
|
|
73
|
+
const waiter = waiters.get(id);
|
|
74
|
+
if (waiter === undefined) return;
|
|
75
|
+
waiters.delete(id);
|
|
76
|
+
waiter.reject(error);
|
|
77
|
+
maybeExit();
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
function send(message) {
|
|
82
|
+
const payload = `${JSON.stringify(message)}\n`;
|
|
83
|
+
pendingStdout += 1;
|
|
84
|
+
process.stdout.write(payload, (error) => {
|
|
85
|
+
pendingStdout -= 1;
|
|
86
|
+
if (error) settle(error);
|
|
87
|
+
maybeExit();
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function ok(id, result) { if (id !== undefined) send({ jsonrpc: "2.0", id, result }); }
|
|
91
|
+
function fail(id, error) { if (id !== undefined) send({ jsonrpc: "2.0", id, error: { code: -32000, message: error instanceof Error ? error.message : String(error) } }); }
|
|
92
|
+
|
|
93
|
+
const stdinLines = createInterface({ input: process.stdin });
|
|
94
|
+
stdinLines.on("line", async (line) => {
|
|
95
|
+
inFlight += 1;
|
|
96
|
+
try {
|
|
97
|
+
let message;
|
|
98
|
+
try { message = JSON.parse(line); }
|
|
99
|
+
catch (error) { fail(null, error); return; }
|
|
100
|
+
try {
|
|
101
|
+
if (message.method === "initialize") {
|
|
102
|
+
ok(message.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "ak-role-envelope", version: "1" } });
|
|
103
|
+
} else if (message.method === "ping") {
|
|
104
|
+
ok(message.id, {});
|
|
105
|
+
} else if (message.method === "tools/list") {
|
|
106
|
+
ok(message.id, await request("tools/list"));
|
|
107
|
+
} else if (message.method === "tools/call") {
|
|
108
|
+
ok(message.id, await request("tools/call", message.params));
|
|
109
|
+
} else if (message.method !== "notifications/initialized" && message.method !== "initialized") {
|
|
110
|
+
fail(message.id, new Error(`Unsupported MCP method: ${String(message.method)}`));
|
|
111
|
+
}
|
|
112
|
+
} catch (error) { fail(message.id, error); }
|
|
113
|
+
} finally {
|
|
114
|
+
inFlight -= 1;
|
|
115
|
+
maybeExit();
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
stdinLines.on("close", requestShutdown);
|
|
119
|
+
process.on("SIGTERM", requestShutdown);
|