@chenkai114/dsh-superagent-dingtalk 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +103 -2
- package/cordis.patch.yml +197 -0
- package/lib/client.js +6883 -0
- package/lib/deployment-DWOTbxsX.js +483 -0
- package/lib/dingtalk-watch.d.ts +221 -0
- package/lib/dingtalk-watch.js +1164 -0
- package/lib/feishu-CQ3D3dWE.js +1325 -0
- package/lib/feishu-watch.d.ts +125 -0
- package/lib/feishu-watch.js +2 -0
- package/lib/github-pull-D87HmHAP.js +596 -0
- package/lib/github-watch.d.ts +2 -0
- package/lib/github-watch.js +833 -0
- package/lib/index.d.ts +369 -0
- package/lib/index.js +10631 -0
- package/lib/intake-Ba9xBNyb.d.ts +734 -0
- package/lib/kind-BlPO15JX.d.ts +959 -0
- package/lib/poll-BWa7O9Kk.js +395 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +147 -4
- package/prompts/admission.md +68 -0
- package/prompts/cli.md +17 -0
- package/prompts/dispatch.md +59 -0
- package/prompts/handoff-orchestrator.md +4 -0
- package/prompts/handoff-worker.md +7 -0
- package/prompts/handoff.md +6 -0
- package/prompts/orchestrator.md +16 -0
- package/prompts/replies.md +35 -0
- package/prompts/shared.md +7 -0
- package/prompts/subscriptions.md +13 -0
- package/prompts/team/communication.md +97 -0
- package/prompts/team/delivery.md +28 -0
- package/prompts/team/scope.md +22 -0
- package/prompts/work.md +49 -0
- package/prompts/worker.md +10 -0
- package/skills/dsh-superagent-feishu/SKILL.md +12 -0
- package/skills/dsh-superagent-github/SKILL.md +14 -0
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
import { l as CliError, m as fill } from "./poll-BWa7O9Kk.js";
|
|
2
|
+
import { accessSync, constants, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { delimiter, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { lstat, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import s from "@deepseek-ai/schemastery";
|
|
7
|
+
//#region src/limits.ts
|
|
8
|
+
/** Validation bounds shared between host schemas and management panel forms. */
|
|
9
|
+
const LIMITS = {
|
|
10
|
+
ruleName: 100,
|
|
11
|
+
ruleInstruction: 2e3,
|
|
12
|
+
evalTimeoutSeconds: {
|
|
13
|
+
min: 30,
|
|
14
|
+
max: 600
|
|
15
|
+
},
|
|
16
|
+
maxWorkers: {
|
|
17
|
+
min: 1,
|
|
18
|
+
max: 16
|
|
19
|
+
},
|
|
20
|
+
prepareCommand: 4e3,
|
|
21
|
+
promptMaxChars: {
|
|
22
|
+
min: 1e3,
|
|
23
|
+
max: 1e6
|
|
24
|
+
},
|
|
25
|
+
admissionContextMaxPages: {
|
|
26
|
+
min: 1,
|
|
27
|
+
max: 100
|
|
28
|
+
},
|
|
29
|
+
admissionContextTimeoutMs: {
|
|
30
|
+
min: 1,
|
|
31
|
+
max: 9e4
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/setup.ts
|
|
36
|
+
/** Structured startup and configuration errors with the settings location where the operator can fix them. */
|
|
37
|
+
const SETUP_PROBLEMS = {
|
|
38
|
+
foreignFile: ["deployment", "{file} was not written by dsh-superagent; move it, or choose another state directory."],
|
|
39
|
+
gitTooOld: ["deployment", "git does not read the github.com credential configuration dsh-superagent writes; dsh-superagent needs git 2.32 or later."],
|
|
40
|
+
environmentFailed: ["deployment", "Preparing the agent environment failed."],
|
|
41
|
+
repositoryUnset: ["github", "The GitHub Source names no repository."],
|
|
42
|
+
agentCliUnset: ["github", "The agent GitHub CLI is not set."],
|
|
43
|
+
agentCliMissing: ["github", "The agent GitHub CLI was not found."],
|
|
44
|
+
agentCliSignedOut: ["github", "The agent GitHub CLI cannot read its account."],
|
|
45
|
+
agentCliNoAccount: ["github", "The agent GitHub CLI did not report a GitHub account."],
|
|
46
|
+
repositoryUnreadable: ["github", "@{account} cannot read {repository}."],
|
|
47
|
+
repositoryUnreported: ["github", "The agent GitHub CLI did not return {repository}."],
|
|
48
|
+
repositoryReadOnly: ["github", "@{account} cannot push to {repository}."],
|
|
49
|
+
feishuCliFailed: ["feishu", "The bot lark-cli does not work."],
|
|
50
|
+
feishuNoApp: ["feishu", "auth status of the bot lark-cli did not report the app."],
|
|
51
|
+
feishuBotNotReady: ["feishu", "The bot identity of app {app} is {status}; configure the app secret with lark-cli."],
|
|
52
|
+
feishuUserIdentity: ["feishu", "The bot lark-cli allows user identities (strict mode {mode}); give the bot its own lark-cli configuration in strict mode bot, as docs/006-deployment.md describes."],
|
|
53
|
+
feishuNoBot: ["feishu", "The Feishu bot API did not return the bot's open_id."]
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Thrown by deployment and account verification checks when a required CLI, account, or repository check fails.
|
|
57
|
+
* `Setup` records it for the management overview, and the HTTP layer returns `problem` so the panel can localize it.
|
|
58
|
+
*/
|
|
59
|
+
var SetupError = class extends Error {
|
|
60
|
+
code;
|
|
61
|
+
values;
|
|
62
|
+
place;
|
|
63
|
+
constructor(code, values = {}) {
|
|
64
|
+
const [place, text] = SETUP_PROBLEMS[code];
|
|
65
|
+
const sentence = fill(text, values);
|
|
66
|
+
super(values.output ? `${sentence}\n${values.output}` : sentence);
|
|
67
|
+
this.code = code;
|
|
68
|
+
this.values = values;
|
|
69
|
+
this.place = place;
|
|
70
|
+
}
|
|
71
|
+
get problem() {
|
|
72
|
+
return {
|
|
73
|
+
place: this.place,
|
|
74
|
+
code: this.code,
|
|
75
|
+
values: this.values,
|
|
76
|
+
detail: this.message
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/infra/environment.ts
|
|
82
|
+
/**
|
|
83
|
+
* Process environment and CLI shims that bind git, gh, and lark-cli to the deployment's accounts and block disallowed commands.
|
|
84
|
+
* Variables read by workers avoid `KEY|PASSWORD|SECRET|TOKEN` in their names because DSH strips credential-shaped variables from child environments.
|
|
85
|
+
* Provides default-path guardrails rather than an OS-level security boundary, as workers run under the operator's OS user.
|
|
86
|
+
*/
|
|
87
|
+
const MARKER = "# Written by dsh-superagent on every start; edits are lost.";
|
|
88
|
+
/** Markers of files written under the project's earlier names (`dsh-tag`, `dsh-go`, `dsh-freelancer`), which `dsh-superagent` owns and replaces too. */
|
|
89
|
+
const LEGACY_MARKERS = [
|
|
90
|
+
"dsh-tag",
|
|
91
|
+
"dsh-go",
|
|
92
|
+
"dsh-freelancer"
|
|
93
|
+
].map((name) => `# Written by ${name} on every start; edits are lost.`);
|
|
94
|
+
/** Commands workers need, which `blockedCommands` cannot block: the shims and git. */
|
|
95
|
+
const WORKER_COMMANDS = [
|
|
96
|
+
"gh",
|
|
97
|
+
"git",
|
|
98
|
+
"lark-cli"
|
|
99
|
+
];
|
|
100
|
+
const workerBin = (stateDir) => join(stateDir, "worker-bin");
|
|
101
|
+
const workerGitConfig = (stateDir) => join(stateDir, "worker-gitconfig");
|
|
102
|
+
const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
103
|
+
const gitQuote = (value) => `"${value.replace(/[\\"]/g, (char) => `\\${char}`)}"`;
|
|
104
|
+
const credentialHelper = (cli) => `!${shellQuote(cli)} auth git-credential`;
|
|
105
|
+
function sameDirectory(a, b) {
|
|
106
|
+
const real = (path) => {
|
|
107
|
+
try {
|
|
108
|
+
return realpathSync(path);
|
|
109
|
+
} catch {
|
|
110
|
+
return resolve(path);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
return real(a) === real(b);
|
|
114
|
+
}
|
|
115
|
+
function withoutDirectory(path, dir) {
|
|
116
|
+
return path.split(delimiter).filter((entry) => !sameDirectory(entry, dir)).join(delimiter);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The variables that tell git which repository, work tree and index to act on. A host started inside git, such as by
|
|
120
|
+
* `git rebase --exec`, passes them on, and a git started below it would act on that repository. GIT_CEILING_DIRECTORIES is
|
|
121
|
+
* kept: it names no repository, and it stops git's search for one where the operator chose.
|
|
122
|
+
*/
|
|
123
|
+
const GIT_LOCATION = [
|
|
124
|
+
"GIT_DIR",
|
|
125
|
+
"GIT_WORK_TREE",
|
|
126
|
+
"GIT_INDEX_FILE",
|
|
127
|
+
"GIT_PREFIX",
|
|
128
|
+
"GIT_COMMON_DIR",
|
|
129
|
+
"GIT_OBJECT_DIRECTORY",
|
|
130
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
131
|
+
"GIT_NAMESPACE"
|
|
132
|
+
];
|
|
133
|
+
/**
|
|
134
|
+
* Returns environment variable overrides that strip ambient GitHub tokens, interactive prompts, the repository the host's own
|
|
135
|
+
* environment may name, and operator git identity/config overrides.
|
|
136
|
+
*/
|
|
137
|
+
function agentVariables(stateDir) {
|
|
138
|
+
return {
|
|
139
|
+
GH_TOKEN: void 0,
|
|
140
|
+
GITHUB_TOKEN: void 0,
|
|
141
|
+
...Object.fromEntries(GIT_LOCATION.map((name) => [name, void 0])),
|
|
142
|
+
GIT_CONFIG_GLOBAL: workerGitConfig(stateDir),
|
|
143
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
144
|
+
GIT_CONFIG_COUNT: void 0,
|
|
145
|
+
GIT_CONFIG_PARAMETERS: void 0,
|
|
146
|
+
GIT_ASKPASS: "",
|
|
147
|
+
SSH_ASKPASS: void 0,
|
|
148
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
149
|
+
GIT_AUTHOR_NAME: void 0,
|
|
150
|
+
GIT_COMMITTER_NAME: void 0,
|
|
151
|
+
GIT_AUTHOR_EMAIL: void 0,
|
|
152
|
+
GIT_COMMITTER_EMAIL: void 0
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
/** True when a regular file starts with the dsh-superagent marker in its first two lines; a symbolic link, directory, or other non-regular file never counts as written by dsh-superagent. */
|
|
156
|
+
async function written(file) {
|
|
157
|
+
if (!(await lstat(file)).isFile()) return false;
|
|
158
|
+
const head = (await readFile(file, "utf8")).split("\n", 2);
|
|
159
|
+
return [MARKER, ...LEGACY_MARKERS].some((marker) => head.includes(marker));
|
|
160
|
+
}
|
|
161
|
+
async function own(file, text, mode = 420) {
|
|
162
|
+
let foreign = false;
|
|
163
|
+
try {
|
|
164
|
+
foreign = !await written(file);
|
|
165
|
+
} catch {}
|
|
166
|
+
if (foreign) throw new SetupError("foreignFile", { file });
|
|
167
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
168
|
+
await writeFile(temporary, text, { mode });
|
|
169
|
+
await rename(temporary, file);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Atomically writes worker CLI shims and the isolated git configuration file into the state directory, refusing to overwrite foreign files.
|
|
173
|
+
* Each shim strips the shim directory from PATH before exec so wrapper scripts resolving `gh` or `lark-cli` by name reach the real binary.
|
|
174
|
+
*/
|
|
175
|
+
async function writeEnvironment(deployment, blockedCommands) {
|
|
176
|
+
const { stateDir, repository, github, feishu } = deployment;
|
|
177
|
+
const dir = workerBin(stateDir);
|
|
178
|
+
await mkdir(dir, { recursive: true });
|
|
179
|
+
const before = await readdir(dir);
|
|
180
|
+
for (const name of before) {
|
|
181
|
+
const file = join(dir, name);
|
|
182
|
+
if (!await written(file)) throw new SetupError("foreignFile", { file });
|
|
183
|
+
}
|
|
184
|
+
const kept = /* @__PURE__ */ new Set();
|
|
185
|
+
const shim = async (name, body) => {
|
|
186
|
+
const temporary = join(dir, `.${name}.${process.pid}.tmp`);
|
|
187
|
+
await writeFile(temporary, `#!/bin/sh\n${MARKER}\n${body}\n`, { mode: 493 });
|
|
188
|
+
await rename(temporary, join(dir, name));
|
|
189
|
+
kept.add(name);
|
|
190
|
+
};
|
|
191
|
+
const withoutShims = [
|
|
192
|
+
`self=${shellQuote(dir)}`,
|
|
193
|
+
"rest=",
|
|
194
|
+
"IFS=:",
|
|
195
|
+
"set -f",
|
|
196
|
+
"for entry in $PATH; do [ \"$entry\" = \"$self\" ] || rest=\"${rest:+$rest:}$entry\"; done",
|
|
197
|
+
"set +f",
|
|
198
|
+
"unset IFS",
|
|
199
|
+
"PATH=$rest",
|
|
200
|
+
"export PATH"
|
|
201
|
+
].join("\n");
|
|
202
|
+
const run = (program) => `${withoutShims}\nexec ${shellQuote(program)} "$@"`;
|
|
203
|
+
const fail = (message) => `echo ${shellQuote(message)} >&2\nexit 1`;
|
|
204
|
+
await shim("gh", run(github.cli));
|
|
205
|
+
await shim("lark-cli", feishu ? run(feishu.cli) : fail("lark-cli is unavailable: this installation has no Feishu bot."));
|
|
206
|
+
for (const name of new Set(blockedCommands.filter((name) => !WORKER_COMMANDS.includes(name)))) await shim(name, fail(`${name} is blocked in this installation; use gh, which acts as ${github.login}.`));
|
|
207
|
+
for (const name of before) if (!kept.has(name)) await unlink(join(dir, name));
|
|
208
|
+
await own(workerGitConfig(stateDir), [
|
|
209
|
+
MARKER,
|
|
210
|
+
"[user]",
|
|
211
|
+
" useConfigOnly = true",
|
|
212
|
+
"[credential]",
|
|
213
|
+
" helper =",
|
|
214
|
+
"[credential \"https://github.com\"]",
|
|
215
|
+
`\thelper = ${gitQuote(credentialHelper(github.cli))}`,
|
|
216
|
+
"[url \"https://github.com/\"]",
|
|
217
|
+
" insteadOf = git@github.com:",
|
|
218
|
+
" insteadOf = ssh://git@github.com/",
|
|
219
|
+
"[filter \"lfs\"]",
|
|
220
|
+
" clean = git-lfs clean -- %f",
|
|
221
|
+
" smudge = git-lfs smudge -- %f",
|
|
222
|
+
" process = git-lfs filter-process",
|
|
223
|
+
" required = true"
|
|
224
|
+
].join("\n") + "\n");
|
|
225
|
+
}
|
|
226
|
+
/** Applies environment overrides and prepends worker shims to `process.env.PATH`, returning a restore callback. */
|
|
227
|
+
function applyEnvironment(variables, stateDir, path) {
|
|
228
|
+
const values = {
|
|
229
|
+
...variables,
|
|
230
|
+
PATH: [workerBin(stateDir), path].join(delimiter)
|
|
231
|
+
};
|
|
232
|
+
const previous = Object.fromEntries(Object.keys(values).map((name) => [name, process.env[name]]));
|
|
233
|
+
const apply = (env) => {
|
|
234
|
+
for (const [name, value] of Object.entries(env)) if (value === void 0) delete process.env[name];
|
|
235
|
+
else process.env[name] = value;
|
|
236
|
+
};
|
|
237
|
+
apply(values);
|
|
238
|
+
return () => {
|
|
239
|
+
apply(previous);
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/** Spawns a command through the DSH subprocess runtime, which strips credential-shaped environment variables. */
|
|
243
|
+
async function runAsWorker(subprocess, argv, cwd, signal, env) {
|
|
244
|
+
const handle = subprocess.spawn({
|
|
245
|
+
argv,
|
|
246
|
+
cwd,
|
|
247
|
+
graceMs: 2e3,
|
|
248
|
+
signal,
|
|
249
|
+
...env ? { env } : {},
|
|
250
|
+
stdio: {
|
|
251
|
+
stdin: "ignore",
|
|
252
|
+
stdout: { maxBytes: 1 << 20 },
|
|
253
|
+
stderr: { maxBytes: 65536 }
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
const { exitCode } = await handle.done;
|
|
257
|
+
const read = (reader) => reader?.readFrom(0).text ?? "";
|
|
258
|
+
if (exitCode === 0) return read(handle.collected.stdout);
|
|
259
|
+
const ended = exitCode === null ? "was stopped before it finished" : `exited with ${exitCode}`;
|
|
260
|
+
throw new CliError(read(handle.collected.stderr).trim() || `${argv.join(" ")} ${ended}`, void 0, exitCode ?? void 0);
|
|
261
|
+
}
|
|
262
|
+
/** Verifies that worker git invocations resolve the deployment's GitHub credential helper. */
|
|
263
|
+
async function verifyEnvironment(deployment, subprocess, signal) {
|
|
264
|
+
const { github, stateDir } = deployment;
|
|
265
|
+
if ((await runAsWorker(subprocess, [
|
|
266
|
+
"git",
|
|
267
|
+
"config",
|
|
268
|
+
"-z",
|
|
269
|
+
"--show-origin",
|
|
270
|
+
"--get-all",
|
|
271
|
+
"credential.https://github.com.helper"
|
|
272
|
+
], stateDir, AbortSignal.any([signal, AbortSignal.timeout(6e4)])).catch(() => "")).split("\0").join("\0") !== [
|
|
273
|
+
`file:${workerGitConfig(stateDir)}`,
|
|
274
|
+
credentialHelper(github.cli),
|
|
275
|
+
""
|
|
276
|
+
].join("\0")) throw new SetupError("gitTooOld");
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Verifies that a ticket directory's local or worktree git config defines no custom `credential.*` or `http.*extraheader`
|
|
280
|
+
* keys, which the agent's git would read from the repository's own config and act on.
|
|
281
|
+
*/
|
|
282
|
+
async function verifyDirectory(directory, subprocess, signal) {
|
|
283
|
+
const scoped = (await runAsWorker(subprocess, [
|
|
284
|
+
"git",
|
|
285
|
+
"config",
|
|
286
|
+
"-z",
|
|
287
|
+
"--show-scope",
|
|
288
|
+
"--get-regexp",
|
|
289
|
+
"^(credential\\..*|http\\..*extraheader)$"
|
|
290
|
+
], directory, AbortSignal.any([signal, AbortSignal.timeout(6e4)])).catch((error) => {
|
|
291
|
+
if (error instanceof CliError && error.exitCode === 1) return "";
|
|
292
|
+
throw error;
|
|
293
|
+
})).split("\0");
|
|
294
|
+
const local = scoped.flatMap((scope, index) => index % 2 === 0 && (scope === "local" || scope === "worktree") ? [scoped[index + 1].split("\n")[0]] : []);
|
|
295
|
+
if (local.length) throw new Error(`The git configuration of the repository in ${directory} sets ${local.join(", ")}, which the agent's git would also read; remove them.`);
|
|
296
|
+
}
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region src/deployment.ts
|
|
299
|
+
/** Plugin configuration and startup verification for repository access and agent CLI identities. */
|
|
300
|
+
const reason = (error) => error instanceof Error ? error.message : String(error);
|
|
301
|
+
const absolute = (description) => s.string().pattern(/^\//).description(`${description} Absolute path.`);
|
|
302
|
+
/** Plugin configuration of the dsh-superagent entry. Volatile fields apply without a restart because dsh-superagent reads them on each use; changing `stateDir` remounts the plugin. */
|
|
303
|
+
const Config = s.object({
|
|
304
|
+
stateDir: absolute("Directory for the database, locks, worker shims, the agent's git configuration and, by default, the ticket directories.").required(),
|
|
305
|
+
promptMaxChars: s.number().min(LIMITS.promptMaxChars.min).max(LIMITS.promptMaxChars.max).step(1).default(1e5).description("Largest saved prompt configuration, in characters.").volatile(),
|
|
306
|
+
admissionContextMaxPages: s.number().min(LIMITS.admissionContextMaxPages.min).max(LIMITS.admissionContextMaxPages.max).step(1).default(10).description("Pages of thread context one assessment may read.").volatile(),
|
|
307
|
+
admissionContextTimeoutMs: s.number().min(LIMITS.admissionContextTimeoutMs.min).max(LIMITS.admissionContextTimeoutMs.max).step(1).default(15e3).description("Time limit of one context read during an assessment, in milliseconds.").volatile()
|
|
308
|
+
});
|
|
309
|
+
const MOVED = {
|
|
310
|
+
repository: "on the GitHub Source",
|
|
311
|
+
branchPrefix: "in the prepare command of the Execution settings",
|
|
312
|
+
github: "on the GitHub Source",
|
|
313
|
+
feishu: "on the Feishu Source",
|
|
314
|
+
author: "prompt text",
|
|
315
|
+
repositoryPath: "in the prepare command of the Execution settings",
|
|
316
|
+
worktreeRoot: "the ticket directory of the Execution settings",
|
|
317
|
+
blockedCommands: "in the Execution settings"
|
|
318
|
+
};
|
|
319
|
+
/** Read machine settings and reject unknown configuration keys (naming where deprecated keys moved). */
|
|
320
|
+
function machineOf(config) {
|
|
321
|
+
const unknown = Object.keys(config).filter((key) => !(key in (Config.dict ?? {})));
|
|
322
|
+
if (unknown.length) throw new Error(`dsh-superagent configuration has keys it does not use: ${unknown.map((key) => MOVED[key] ? `${key} (now ${MOVED[key]})` : key).join(", ")}; docs/006-deployment.md lists the keys`);
|
|
323
|
+
const { stateDir, promptMaxChars, admissionContextMaxPages, admissionContextTimeoutMs } = config;
|
|
324
|
+
return {
|
|
325
|
+
stateDir,
|
|
326
|
+
promptMaxChars,
|
|
327
|
+
admissionContextMaxPages,
|
|
328
|
+
admissionContextTimeoutMs
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
const GithubAccountsSchema = z.object({
|
|
332
|
+
repository: z.string().trim().regex(/^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)?$/, "owner/name").default(""),
|
|
333
|
+
cli: z.string().trim().default("")
|
|
334
|
+
});
|
|
335
|
+
const FeishuBotSchema = z.object({ cli: z.string().trim().default("") });
|
|
336
|
+
/** Source configuration keys that affect deployment setup and trigger a restart when changed. */
|
|
337
|
+
const SETUP_FIELDS = {
|
|
338
|
+
github: Object.keys(GithubAccountsSchema.shape),
|
|
339
|
+
feishu: Object.keys(FeishuBotSchema.shape)
|
|
340
|
+
};
|
|
341
|
+
/** Resolve a command name or absolute path to an executable file, ignoring the worker shim directory. */
|
|
342
|
+
function executable(name, path, exclude) {
|
|
343
|
+
if (name.includes("/") && !isAbsolute(name)) throw new Error(`${name} must be a command name or an absolute path`);
|
|
344
|
+
const candidates = isAbsolute(name) ? [name] : path.split(delimiter).filter((dir) => isAbsolute(dir) && !(exclude && sameDirectory(dir, exclude))).map((dir) => join(dir, name));
|
|
345
|
+
for (const candidate of candidates) try {
|
|
346
|
+
if (statSync(candidate).isFile()) {
|
|
347
|
+
accessSync(candidate, constants.X_OK);
|
|
348
|
+
return candidate;
|
|
349
|
+
}
|
|
350
|
+
} catch {}
|
|
351
|
+
throw new Error(`${name} is not an executable file${isAbsolute(name) ? "" : " on PATH"}`);
|
|
352
|
+
}
|
|
353
|
+
/** Run startup checks through DSH's worker subprocess service with worker shims removed from PATH so a `gh` wrapper script reaches the real binary. */
|
|
354
|
+
function workerProbe(subprocess, stateDir, cwd, signal) {
|
|
355
|
+
const path = withoutDirectory(process.env.PATH ?? "", workerBin(stateDir));
|
|
356
|
+
return (argv) => runAsWorker(subprocess, [
|
|
357
|
+
"env",
|
|
358
|
+
`PATH=${path}`,
|
|
359
|
+
...argv
|
|
360
|
+
], cwd, AbortSignal.any([signal, AbortSignal.timeout(6e4)]));
|
|
361
|
+
}
|
|
362
|
+
const GithubUser = z.object({
|
|
363
|
+
login: z.string().regex(/^[A-Za-z0-9-]+$/),
|
|
364
|
+
id: z.number().int().positive()
|
|
365
|
+
});
|
|
366
|
+
const RepositoryAccess = z.object({
|
|
367
|
+
name: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/),
|
|
368
|
+
push: z.boolean().nullable()
|
|
369
|
+
});
|
|
370
|
+
function parsed(schema, text) {
|
|
371
|
+
let value;
|
|
372
|
+
try {
|
|
373
|
+
value = JSON.parse(text);
|
|
374
|
+
} catch {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const result = schema.safeParse(value);
|
|
378
|
+
return result.success ? result.data : void 0;
|
|
379
|
+
}
|
|
380
|
+
/** Verify the agent's GitHub CLI identity and push access to the configured repository. */
|
|
381
|
+
async function resolveDeployment(machine, github, probe, path = process.env.PATH ?? "") {
|
|
382
|
+
const { stateDir } = machine;
|
|
383
|
+
const accounts = GithubAccountsSchema.parse(github ?? {});
|
|
384
|
+
const remote = accounts.repository;
|
|
385
|
+
if (!remote) throw new SetupError("repositoryUnset");
|
|
386
|
+
if (!accounts.cli) throw new SetupError("agentCliUnset");
|
|
387
|
+
let cli;
|
|
388
|
+
try {
|
|
389
|
+
cli = executable(accounts.cli, path, workerBin(stateDir));
|
|
390
|
+
} catch (error) {
|
|
391
|
+
throw new SetupError("agentCliMissing", { output: reason(error) });
|
|
392
|
+
}
|
|
393
|
+
const text = await probe([
|
|
394
|
+
cli,
|
|
395
|
+
"api",
|
|
396
|
+
"user"
|
|
397
|
+
]).catch((error) => {
|
|
398
|
+
throw new SetupError("agentCliSignedOut", { output: reason(error) });
|
|
399
|
+
});
|
|
400
|
+
const agent = parsed(GithubUser, text);
|
|
401
|
+
if (!agent) throw new SetupError("agentCliNoAccount");
|
|
402
|
+
const access = parsed(RepositoryAccess, await probe([
|
|
403
|
+
cli,
|
|
404
|
+
"api",
|
|
405
|
+
`repos/${remote}`,
|
|
406
|
+
"--jq",
|
|
407
|
+
"{name: .full_name, push: .permissions.push}"
|
|
408
|
+
]).catch((error) => {
|
|
409
|
+
throw new SetupError("repositoryUnreadable", {
|
|
410
|
+
account: agent.login,
|
|
411
|
+
repository: remote,
|
|
412
|
+
output: reason(error)
|
|
413
|
+
});
|
|
414
|
+
}));
|
|
415
|
+
if (!access) throw new SetupError("repositoryUnreported", { repository: remote });
|
|
416
|
+
const repository = access.name;
|
|
417
|
+
if (access.push !== true) throw new SetupError("repositoryReadOnly", {
|
|
418
|
+
account: agent.login,
|
|
419
|
+
repository
|
|
420
|
+
});
|
|
421
|
+
return {
|
|
422
|
+
...machine,
|
|
423
|
+
repository,
|
|
424
|
+
github: {
|
|
425
|
+
cli,
|
|
426
|
+
login: agent.login,
|
|
427
|
+
noreply: `${agent.id}+${agent.login}@users.noreply.github.com`
|
|
428
|
+
}
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
const AuthStatus = z.object({
|
|
432
|
+
appId: z.string().regex(/^cli_[A-Za-z0-9]+$/),
|
|
433
|
+
brand: z.enum(["feishu", "lark"]).default("feishu"),
|
|
434
|
+
identities: z.object({ bot: z.object({ status: z.string() }) })
|
|
435
|
+
});
|
|
436
|
+
const BotInfo = z.object({ bot: z.object({
|
|
437
|
+
open_id: z.string().regex(/^ou_[A-Za-z0-9]+$/),
|
|
438
|
+
app_name: z.string().default("")
|
|
439
|
+
}) });
|
|
440
|
+
/**
|
|
441
|
+
* Verify that the configured Feishu CLI is authenticated as a bot and restricted to strict mode `bot`.
|
|
442
|
+
* Workers invoke this CLI as `lark-cli`, so a CLI that also permits a user identity would let workers act as that user.
|
|
443
|
+
*/
|
|
444
|
+
async function resolveFeishuBot(machine, feishu, probe, path = process.env.PATH ?? "") {
|
|
445
|
+
const { cli: name } = FeishuBotSchema.parse(feishu ?? {});
|
|
446
|
+
if (!name) return void 0;
|
|
447
|
+
const fail = (error) => {
|
|
448
|
+
throw error instanceof SetupError ? error : new SetupError("feishuCliFailed", { output: reason(error) });
|
|
449
|
+
};
|
|
450
|
+
let cli = "";
|
|
451
|
+
try {
|
|
452
|
+
cli = executable(name, path, workerBin(machine.stateDir));
|
|
453
|
+
} catch (error) {
|
|
454
|
+
fail(error);
|
|
455
|
+
}
|
|
456
|
+
const run = (...args) => probe([
|
|
457
|
+
"env",
|
|
458
|
+
"LARKSUITE_CLI_NO_UPDATE_NOTIFIER=1",
|
|
459
|
+
"LARKSUITE_CLI_NO_SKILLS_NOTIFIER=1",
|
|
460
|
+
cli,
|
|
461
|
+
...args
|
|
462
|
+
]).catch(fail);
|
|
463
|
+
const text = await run("auth", "status");
|
|
464
|
+
const status = parsed(AuthStatus, text.slice(text.indexOf("{")));
|
|
465
|
+
if (!status) return fail(new SetupError("feishuNoApp"));
|
|
466
|
+
if (status.identities.bot.status !== "ready") fail(new SetupError("feishuBotNotReady", {
|
|
467
|
+
app: status.appId,
|
|
468
|
+
status: status.identities.bot.status
|
|
469
|
+
}));
|
|
470
|
+
const mode = /strict-mode:\s*(\w+)/.exec(await run("config", "strict-mode"))?.[1];
|
|
471
|
+
if (mode !== "bot") fail(new SetupError("feishuUserIdentity", { mode: mode ?? "unknown" }));
|
|
472
|
+
const info = parsed(BotInfo, (await run("api", "GET", "/open-apis/bot/v3/info", "--as", "bot", "--format", "ndjson")).split("\n")[0] ?? "");
|
|
473
|
+
if (!info) return fail(new SetupError("feishuNoBot"));
|
|
474
|
+
return {
|
|
475
|
+
cli,
|
|
476
|
+
appId: status.appId,
|
|
477
|
+
brand: status.brand,
|
|
478
|
+
botId: info.bot.open_id,
|
|
479
|
+
name: info.bot.app_name
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
//#endregion
|
|
483
|
+
export { writeEnvironment as _, machineOf as a, workerProbe as c, applyEnvironment as d, runAsWorker as f, workerBin as g, withoutDirectory as h, SETUP_FIELDS as i, WORKER_COMMANDS as l, verifyEnvironment as m, FeishuBotSchema as n, resolveDeployment as o, verifyDirectory as p, GithubAccountsSchema as r, resolveFeishuBot as s, Config as t, agentVariables as u, SetupError as v, LIMITS as y };
|