agent-gear 2.20.0 → 2.22.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/AGENTS.md +37 -9
- package/dist/cloud-host/supervisor.d.ts.map +1 -1
- package/dist/cloud-host/supervisor.js +6 -1
- package/dist/cloud-host/supervisor.js.map +1 -1
- package/dist/cloud-host/supervisor.test.js +35 -0
- package/dist/cloud-host/supervisor.test.js.map +1 -1
- package/dist/commands/github.d.ts +17 -0
- package/dist/commands/github.d.ts.map +1 -0
- package/dist/commands/github.js +24 -0
- package/dist/commands/github.js.map +1 -0
- package/dist/commands/github.test.d.ts +2 -0
- package/dist/commands/github.test.d.ts.map +1 -0
- package/dist/commands/github.test.js +31 -0
- package/dist/commands/github.test.js.map +1 -0
- package/dist/github/credential-manager.d.ts +11 -3
- package/dist/github/credential-manager.d.ts.map +1 -1
- package/dist/github/credential-manager.js +65 -19
- package/dist/github/credential-manager.js.map +1 -1
- package/dist/github/credential-manager.test.js +89 -0
- package/dist/github/credential-manager.test.js.map +1 -1
- package/dist/github/gh-config.d.ts +6 -0
- package/dist/github/gh-config.d.ts.map +1 -1
- package/dist/github/gh-config.js +16 -4
- package/dist/github/gh-config.js.map +1 -1
- package/dist/github/gh-config.test.js +25 -0
- package/dist/github/gh-config.test.js.map +1 -1
- package/dist/github/project-token.d.ts +81 -0
- package/dist/github/project-token.d.ts.map +1 -0
- package/dist/github/project-token.js +232 -0
- package/dist/github/project-token.js.map +1 -0
- package/dist/github/project-token.test.d.ts +2 -0
- package/dist/github/project-token.test.d.ts.map +1 -0
- package/dist/github/project-token.test.js +256 -0
- package/dist/github/project-token.test.js.map +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/knowledge-bases.d.ts +7 -15
- package/dist/knowledge-bases.d.ts.map +1 -1
- package/dist/knowledge-bases.js +40 -70
- package/dist/knowledge-bases.js.map +1 -1
- package/dist/knowledge-bases.test.js +79 -60
- package/dist/knowledge-bases.test.js.map +1 -1
- package/dist/workload-executor.d.ts +5 -0
- package/dist/workload-executor.d.ts.map +1 -1
- package/dist/workload-executor.js.map +1 -1
- package/dist/workload-executor.test.js +34 -0
- package/dist/workload-executor.test.js.map +1 -1
- package/package.json +1 -1
- package/src/cloud-host/supervisor.test.ts +43 -0
- package/src/cloud-host/supervisor.ts +5 -1
- package/src/commands/github.test.ts +38 -0
- package/src/commands/github.ts +36 -0
- package/src/github/credential-manager.test.ts +113 -0
- package/src/github/credential-manager.ts +68 -17
- package/src/github/gh-config.test.ts +25 -0
- package/src/github/gh-config.ts +17 -4
- package/src/github/project-token.test.ts +314 -0
- package/src/github/project-token.ts +292 -0
- package/src/index.ts +4 -0
- package/src/knowledge-bases.test.ts +93 -65
- package/src/knowledge-bases.ts +43 -78
- package/src/workload-executor.test.ts +48 -0
- package/src/workload-executor.ts +5 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import {
|
|
8
|
+
EXIT_FAILED,
|
|
9
|
+
EXIT_NOT_BOUND,
|
|
10
|
+
EXIT_NOT_PROJECT,
|
|
11
|
+
EXIT_OK,
|
|
12
|
+
EXIT_UNAUTHORIZED,
|
|
13
|
+
MAX_TOKEN_LENGTH,
|
|
14
|
+
normalizeGitHubRemote,
|
|
15
|
+
requestProjectToken,
|
|
16
|
+
resolveGitProject,
|
|
17
|
+
runGithubTokenCommand,
|
|
18
|
+
} from './project-token.js';
|
|
19
|
+
|
|
20
|
+
const exec = promisify(execFile);
|
|
21
|
+
|
|
22
|
+
const ENV: NodeJS.ProcessEnv = {
|
|
23
|
+
ZAG_AGENT_API_ENDPOINT: 'http://agent-api:8002/',
|
|
24
|
+
ZAG_CONTROLLER_ID: 'controller-123',
|
|
25
|
+
ZAG_HOST_KEY: 'zag_k_1_host_secret',
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
function jsonResponse(body: unknown, status = 200): Response {
|
|
29
|
+
return new Response(JSON.stringify(body), {
|
|
30
|
+
status,
|
|
31
|
+
headers: { 'content-type': 'application/json' },
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function fakeFetch(handler: (...args: Parameters<typeof fetch>) => Promise<Response>) {
|
|
36
|
+
return vi.fn(handler) as unknown as typeof fetch & ReturnType<typeof vi.fn>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe('normalizeGitHubRemote (T-GPT1)', () => {
|
|
40
|
+
it.each([
|
|
41
|
+
['https://github.com/Owner/Repo.git', 'Owner/Repo'],
|
|
42
|
+
['https://github.com/Owner/Repo', 'Owner/Repo'],
|
|
43
|
+
['http://github.com/Owner/Repo/', 'Owner/Repo'],
|
|
44
|
+
['git@github.com:Owner/Repo.git', 'Owner/Repo'],
|
|
45
|
+
['ssh://git@github.com/Owner/Repo.git', 'Owner/Repo'],
|
|
46
|
+
['git://github.com/Owner/Repo.git', 'Owner/Repo'],
|
|
47
|
+
['https://user:pass@github.com/owner/repo.git', 'owner/repo'],
|
|
48
|
+
[' https://GITHUB.com/owner/repo ', 'owner/repo'],
|
|
49
|
+
['github.com:owner/repo', 'owner/repo'],
|
|
50
|
+
['https://github.com/owner/re.po-1_x', 'owner/re.po-1_x'],
|
|
51
|
+
])('%s → %s', (remote, expected) => {
|
|
52
|
+
expect(normalizeGitHubRemote(remote)).toBe(expected);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it.each([
|
|
56
|
+
'',
|
|
57
|
+
' ',
|
|
58
|
+
'https://gitlab.com/owner/repo.git',
|
|
59
|
+
'https://github.com/owner',
|
|
60
|
+
'https://github.com/owner/repo/extra',
|
|
61
|
+
'https://github.com/own er/repo',
|
|
62
|
+
'not-a-url',
|
|
63
|
+
])('rejects %s', (remote) => {
|
|
64
|
+
expect(normalizeGitHubRemote(remote)).toBeNull();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe('resolveGitProject (T-GPT2)', () => {
|
|
69
|
+
let dir = '';
|
|
70
|
+
|
|
71
|
+
async function initRepo(remote?: string) {
|
|
72
|
+
dir = await mkdtemp(join(tmpdir(), 'zag-project-token-'));
|
|
73
|
+
await exec('git', ['init', '--quiet'], { cwd: dir });
|
|
74
|
+
if (remote) await exec('git', ['remote', 'add', 'origin', remote], { cwd: dir });
|
|
75
|
+
return dir;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
it('resolves owner/repo from the git origin', async () => {
|
|
79
|
+
const repo = await initRepo('git@github.com:owner/repo.git');
|
|
80
|
+
await expect(resolveGitProject(repo)).resolves.toEqual({
|
|
81
|
+
kind: 'project',
|
|
82
|
+
repoFullName: 'owner/repo',
|
|
83
|
+
});
|
|
84
|
+
await rm(repo, { recursive: true, force: true });
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('returns not-project outside a git repository', async () => {
|
|
88
|
+
const plain = await mkdtemp(join(tmpdir(), 'zag-plain-'));
|
|
89
|
+
await expect(resolveGitProject(plain)).resolves.toEqual({ kind: 'not-project' });
|
|
90
|
+
await rm(plain, { recursive: true, force: true });
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('returns not-project without an origin remote', async () => {
|
|
94
|
+
const repo = await initRepo();
|
|
95
|
+
await expect(resolveGitProject(repo)).resolves.toEqual({ kind: 'not-project' });
|
|
96
|
+
await rm(repo, { recursive: true, force: true });
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('returns not-project for a non-github origin', async () => {
|
|
100
|
+
const repo = await initRepo('https://gitlab.com/owner/repo.git');
|
|
101
|
+
await expect(resolveGitProject(repo)).resolves.toEqual({ kind: 'not-project' });
|
|
102
|
+
await rm(repo, { recursive: true, force: true });
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('returns not-project when git is unavailable', async () => {
|
|
106
|
+
const resolution = await resolveGitProject('/tmp', {
|
|
107
|
+
runGit: async () => null,
|
|
108
|
+
});
|
|
109
|
+
expect(resolution).toEqual({ kind: 'not-project' });
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
describe('requestProjectToken (T-GPT3)', () => {
|
|
114
|
+
it('posts the repo and returns the token', async () => {
|
|
115
|
+
const fetchFn = fakeFetch(async () =>
|
|
116
|
+
jsonResponse({ token: 'ghs_project', repoFullName: 'owner/repo', expiresAt: '2026-01-01T00:00:00Z' }),
|
|
117
|
+
);
|
|
118
|
+
const result = await requestProjectToken({
|
|
119
|
+
repoFullName: 'owner/repo',
|
|
120
|
+
env: ENV,
|
|
121
|
+
fetch: fetchFn,
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
expect(result).toEqual({ kind: 'token', token: 'ghs_project' });
|
|
125
|
+
const [url, init] = fetchFn.mock.calls[0] as unknown as [string, RequestInit];
|
|
126
|
+
expect(url).toBe(
|
|
127
|
+
'http://agent-api:8002/internal/cloud-hosts/controller-123/github-credential',
|
|
128
|
+
);
|
|
129
|
+
expect(init).toMatchObject({
|
|
130
|
+
method: 'POST',
|
|
131
|
+
body: JSON.stringify({ repoFullName: 'owner/repo' }),
|
|
132
|
+
});
|
|
133
|
+
expect((init.headers as Record<string, string>).Authorization).toBe(
|
|
134
|
+
'Bearer zag_k_1_host_secret',
|
|
135
|
+
);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('accepts a case-insensitive echo', async () => {
|
|
139
|
+
const fetchFn = fakeFetch(async () =>
|
|
140
|
+
jsonResponse({ token: 't', repoFullName: 'OWNER/REPO' }),
|
|
141
|
+
);
|
|
142
|
+
await expect(
|
|
143
|
+
requestProjectToken({ repoFullName: 'owner/repo', env: ENV, fetch: fetchFn }),
|
|
144
|
+
).resolves.toEqual({ kind: 'token', token: 't' });
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('rejects a mismatched echo', async () => {
|
|
148
|
+
const fetchFn = fakeFetch(async () =>
|
|
149
|
+
jsonResponse({ token: 't', repoFullName: 'other/repo' }),
|
|
150
|
+
);
|
|
151
|
+
const result = await requestProjectToken({
|
|
152
|
+
repoFullName: 'owner/repo',
|
|
153
|
+
env: ENV,
|
|
154
|
+
fetch: fetchFn,
|
|
155
|
+
});
|
|
156
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it('rejects a missing echo (old server ignoring the body)', async () => {
|
|
160
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ token: 't' }));
|
|
161
|
+
const result = await requestProjectToken({
|
|
162
|
+
repoFullName: 'owner/repo',
|
|
163
|
+
env: ENV,
|
|
164
|
+
fetch: fetchFn,
|
|
165
|
+
});
|
|
166
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it.each([['line1\nline2'], [''], ['has space'], ['x'.repeat(MAX_TOKEN_LENGTH + 1)]])(
|
|
170
|
+
'rejects an invalid token %#',
|
|
171
|
+
async (token) => {
|
|
172
|
+
const fetchFn = fakeFetch(async () =>
|
|
173
|
+
jsonResponse({ token, repoFullName: 'owner/repo' }),
|
|
174
|
+
);
|
|
175
|
+
const result = await requestProjectToken({
|
|
176
|
+
repoFullName: 'owner/repo',
|
|
177
|
+
env: ENV,
|
|
178
|
+
fetch: fetchFn,
|
|
179
|
+
});
|
|
180
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
181
|
+
},
|
|
182
|
+
);
|
|
183
|
+
|
|
184
|
+
it('maps 404 PROJECT_NOT_BOUND to exit 4', async () => {
|
|
185
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ error: 'PROJECT_NOT_BOUND' }, 404));
|
|
186
|
+
const result = await requestProjectToken({
|
|
187
|
+
repoFullName: 'owner/repo',
|
|
188
|
+
env: ENV,
|
|
189
|
+
fetch: fetchFn,
|
|
190
|
+
});
|
|
191
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_NOT_BOUND });
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('maps a plain 404 to exit 4', async () => {
|
|
195
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ error: 'NO_BINDING' }, 404));
|
|
196
|
+
const result = await requestProjectToken({
|
|
197
|
+
repoFullName: 'owner/repo',
|
|
198
|
+
env: ENV,
|
|
199
|
+
fetch: fetchFn,
|
|
200
|
+
});
|
|
201
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_NOT_BOUND });
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it('maps 403 REPO_NOT_AUTHORIZED to exit 5', async () => {
|
|
205
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ error: 'REPO_NOT_AUTHORIZED' }, 403));
|
|
206
|
+
const result = await requestProjectToken({
|
|
207
|
+
repoFullName: 'owner/repo',
|
|
208
|
+
env: ENV,
|
|
209
|
+
fetch: fetchFn,
|
|
210
|
+
});
|
|
211
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_UNAUTHORIZED });
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it('maps 500 to exit 6 and never leaks the body', async () => {
|
|
215
|
+
const fetchFn = fakeFetch(async () => jsonResponse({ error: 'boom-secret' }, 500));
|
|
216
|
+
const result = await requestProjectToken({
|
|
217
|
+
repoFullName: 'owner/repo',
|
|
218
|
+
env: ENV,
|
|
219
|
+
fetch: fetchFn,
|
|
220
|
+
});
|
|
221
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
222
|
+
expect(result.kind === 'error' ? result.message : '').not.toContain('boom-secret');
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
it('maps invalid JSON on 200 to exit 6', async () => {
|
|
226
|
+
const fetchFn = fakeFetch(async () => new Response('not-json', { status: 200 }));
|
|
227
|
+
const result = await requestProjectToken({
|
|
228
|
+
repoFullName: 'owner/repo',
|
|
229
|
+
env: ENV,
|
|
230
|
+
fetch: fetchFn,
|
|
231
|
+
});
|
|
232
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it('maps timeout to exit 6', async () => {
|
|
236
|
+
const fetchFn = fakeFetch(
|
|
237
|
+
async () =>
|
|
238
|
+
new Promise<Response>((_resolve, reject) => {
|
|
239
|
+
reject(Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }));
|
|
240
|
+
}),
|
|
241
|
+
);
|
|
242
|
+
const result = await requestProjectToken({
|
|
243
|
+
repoFullName: 'owner/repo',
|
|
244
|
+
env: ENV,
|
|
245
|
+
fetch: fetchFn,
|
|
246
|
+
});
|
|
247
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
248
|
+
expect(result.kind === 'error' ? result.message : '').toContain('超时');
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('fails on missing env without calling fetch', async () => {
|
|
252
|
+
const fetchFn = fakeFetch(async () => jsonResponse({}));
|
|
253
|
+
const result = await requestProjectToken({
|
|
254
|
+
repoFullName: 'owner/repo',
|
|
255
|
+
env: {},
|
|
256
|
+
fetch: fetchFn,
|
|
257
|
+
});
|
|
258
|
+
expect(result).toMatchObject({ kind: 'error', code: EXIT_FAILED });
|
|
259
|
+
expect(result.kind === 'error' ? result.message : '').toContain('ZAG_HOST_KEY');
|
|
260
|
+
expect(fetchFn).not.toHaveBeenCalled();
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
describe('runGithubTokenCommand (T-GPTC1)', () => {
|
|
265
|
+
it('writes only the token to stdout and exits 0', async () => {
|
|
266
|
+
const stdout: string[] = [];
|
|
267
|
+
const stderr: string[] = [];
|
|
268
|
+
const code = await runGithubTokenCommand({
|
|
269
|
+
resolveGitProject: async () => ({ kind: 'project', repoFullName: 'owner/repo' }),
|
|
270
|
+
requestProjectToken: async () => ({ kind: 'token', token: 'ghs_x' }),
|
|
271
|
+
stdout: (text) => stdout.push(text),
|
|
272
|
+
stderr: (text) => stderr.push(text),
|
|
273
|
+
});
|
|
274
|
+
expect(code).toBe(EXIT_OK);
|
|
275
|
+
expect(stdout.join('')).toBe('ghs_x\n');
|
|
276
|
+
expect(stderr).toEqual([]);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it('exits 3 silently for non-git directories', async () => {
|
|
280
|
+
const stdout: string[] = [];
|
|
281
|
+
const stderr: string[] = [];
|
|
282
|
+
const code = await runGithubTokenCommand({
|
|
283
|
+
resolveGitProject: async () => ({ kind: 'not-project' }),
|
|
284
|
+
requestProjectToken: async () => ({ kind: 'token', token: 'unused' }),
|
|
285
|
+
stdout: (text) => stdout.push(text),
|
|
286
|
+
stderr: (text) => stderr.push(text),
|
|
287
|
+
});
|
|
288
|
+
expect(code).toBe(EXIT_NOT_PROJECT);
|
|
289
|
+
expect(stdout).toEqual([]);
|
|
290
|
+
expect(stderr).toEqual([]);
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it.each([
|
|
294
|
+
[4 as const, EXIT_NOT_BOUND],
|
|
295
|
+
[5 as const, EXIT_UNAUTHORIZED],
|
|
296
|
+
[6 as const, EXIT_FAILED],
|
|
297
|
+
])('writes a single stderr line and returns %i', async (errorCode, expected) => {
|
|
298
|
+
const stdout: string[] = [];
|
|
299
|
+
const stderr: string[] = [];
|
|
300
|
+
const code = await runGithubTokenCommand({
|
|
301
|
+
resolveGitProject: async () => ({ kind: 'project', repoFullName: 'owner/repo' }),
|
|
302
|
+
requestProjectToken: async () => ({
|
|
303
|
+
kind: 'error',
|
|
304
|
+
code: errorCode,
|
|
305
|
+
message: '可读原因',
|
|
306
|
+
}),
|
|
307
|
+
stdout: (text) => stdout.push(text),
|
|
308
|
+
stderr: (text) => stderr.push(text),
|
|
309
|
+
});
|
|
310
|
+
expect(code).toBe(expected);
|
|
311
|
+
expect(stdout).toEqual([]);
|
|
312
|
+
expect(stderr).toEqual(['可读原因\n']);
|
|
313
|
+
});
|
|
314
|
+
});
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
/** 成功:已向 stdout 输出单行 token。 */
|
|
4
|
+
export const EXIT_OK = 0;
|
|
5
|
+
/** 当前目录不是 Github 项目(wrapper 需静默降级)。 */
|
|
6
|
+
export const EXIT_NOT_PROJECT = 3;
|
|
7
|
+
/** 项目未在平台初始化 / 云主机无绑定。 */
|
|
8
|
+
export const EXIT_NOT_BOUND = 4;
|
|
9
|
+
/** 当前账号无该项目权限。 */
|
|
10
|
+
export const EXIT_UNAUTHORIZED = 5;
|
|
11
|
+
/** 其它失败(env 缺失、平台不可达、超时、回显不匹配、非法响应)。 */
|
|
12
|
+
export const EXIT_FAILED = 6;
|
|
13
|
+
|
|
14
|
+
/** 申请接口超时(10 秒)。 */
|
|
15
|
+
export const REQUEST_TIMEOUT_MS = 10_000;
|
|
16
|
+
|
|
17
|
+
/** token 长度硬上限(防御异常响应污染 wrapper 的 env)。 */
|
|
18
|
+
export const MAX_TOKEN_LENGTH = 4096;
|
|
19
|
+
|
|
20
|
+
const GITHUB_HOST = 'github.com';
|
|
21
|
+
const REPO_SEGMENT = /^[\w.-]+$/;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 把 `git remote get-url origin` 的输出归一为 `owner/repo`(保留原大小写)。
|
|
25
|
+
*
|
|
26
|
+
* 支持 `https://`、`http://`、`ssh://`、`git://`、`git@github.com:owner/repo.git`、
|
|
27
|
+
* 带 userinfo 的 URL、尾部 `/` 与 `.git`;host 大小写不敏感。非 Github / 段数不为 2 /
|
|
28
|
+
* 含非法字符时返回 `null`。
|
|
29
|
+
*/
|
|
30
|
+
export function normalizeGitHubRemote(remote: string): string | null {
|
|
31
|
+
if (typeof remote !== 'string') return null;
|
|
32
|
+
let value = remote.trim();
|
|
33
|
+
if (!value) return null;
|
|
34
|
+
|
|
35
|
+
for (const prefix of ['https://', 'http://', 'ssh://', 'git://']) {
|
|
36
|
+
if (value.toLowerCase().startsWith(prefix)) {
|
|
37
|
+
value = value.slice(prefix.length);
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
// 剥 userinfo(`user:pass@host/...` 与 `git@host:...`)
|
|
42
|
+
const at = value.indexOf('@');
|
|
43
|
+
if (at >= 0) value = value.slice(at + 1);
|
|
44
|
+
|
|
45
|
+
// scp-like 形态 `github.com:owner/repo` → `github.com/owner/repo`
|
|
46
|
+
const colon = value.indexOf(':');
|
|
47
|
+
if (colon >= 0 && !value.slice(0, colon).includes('/')) {
|
|
48
|
+
value = `${value.slice(0, colon)}/${value.slice(colon + 1)}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
value = value.replace(/\/+$/, '');
|
|
52
|
+
if (value.toLowerCase().endsWith('.git')) value = value.slice(0, -4);
|
|
53
|
+
value = value.replace(/\/+$/, '');
|
|
54
|
+
if (!value) return null;
|
|
55
|
+
|
|
56
|
+
const segments = value.split('/');
|
|
57
|
+
if (segments.length !== 3) return null;
|
|
58
|
+
const [host, owner, repo] = segments as [string, string, string];
|
|
59
|
+
if (host.toLowerCase() !== GITHUB_HOST) return null;
|
|
60
|
+
if (!REPO_SEGMENT.test(owner) || !REPO_SEGMENT.test(repo)) return null;
|
|
61
|
+
return `${owner}/${repo}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface GitCommandResult {
|
|
65
|
+
code: number;
|
|
66
|
+
stdout: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** git 子命令执行器(测试注入;生产使用 `node:child_process.spawn`)。 */
|
|
70
|
+
export type GitRunner = (args: string[], cwd: string) => Promise<GitCommandResult | null>;
|
|
71
|
+
|
|
72
|
+
const defaultGitRunner: GitRunner = (args, cwd) =>
|
|
73
|
+
new Promise((resolve) => {
|
|
74
|
+
let settled = false;
|
|
75
|
+
const finish = (value: GitCommandResult | null): void => {
|
|
76
|
+
if (settled) return;
|
|
77
|
+
settled = true;
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
resolve(value);
|
|
80
|
+
};
|
|
81
|
+
const child = spawn('git', ['-C', cwd, ...args], { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
82
|
+
let stdout = '';
|
|
83
|
+
const timer = setTimeout(() => {
|
|
84
|
+
child.kill('SIGKILL');
|
|
85
|
+
finish(null);
|
|
86
|
+
}, REQUEST_TIMEOUT_MS);
|
|
87
|
+
timer.unref?.();
|
|
88
|
+
child.stdout?.on('data', (chunk: Buffer | string) => {
|
|
89
|
+
stdout += chunk.toString();
|
|
90
|
+
});
|
|
91
|
+
child.on('error', () => finish(null));
|
|
92
|
+
child.on('close', (code: number | null) => finish({ code: code ?? -1, stdout }));
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
export type GitProjectResolution =
|
|
96
|
+
| { kind: 'project'; repoFullName: string }
|
|
97
|
+
| { kind: 'not-project' };
|
|
98
|
+
|
|
99
|
+
export interface ResolveGitProjectDeps {
|
|
100
|
+
runGit?: GitRunner;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 解析 `cwd` 所属 Git 项目的 Github 仓库(`owner/repo`)。
|
|
105
|
+
* 不是 Git 仓库 / 无 origin / origin 非 Github 形态一律 `not-project`。
|
|
106
|
+
*/
|
|
107
|
+
export async function resolveGitProject(
|
|
108
|
+
cwd: string,
|
|
109
|
+
deps: ResolveGitProjectDeps = {},
|
|
110
|
+
): Promise<GitProjectResolution> {
|
|
111
|
+
const runGit = deps.runGit ?? defaultGitRunner;
|
|
112
|
+
try {
|
|
113
|
+
const topLevel = await runGit(['rev-parse', '--show-toplevel'], cwd);
|
|
114
|
+
if (!topLevel || topLevel.code !== 0) return { kind: 'not-project' };
|
|
115
|
+
const root = topLevel.stdout.trim();
|
|
116
|
+
if (!root) return { kind: 'not-project' };
|
|
117
|
+
|
|
118
|
+
const origin = await runGit(['remote', 'get-url', 'origin'], root);
|
|
119
|
+
if (!origin || origin.code !== 0) return { kind: 'not-project' };
|
|
120
|
+
|
|
121
|
+
const repoFullName = normalizeGitHubRemote(origin.stdout);
|
|
122
|
+
if (!repoFullName) return { kind: 'not-project' };
|
|
123
|
+
return { kind: 'project', repoFullName };
|
|
124
|
+
} catch {
|
|
125
|
+
return { kind: 'not-project' };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export type ProjectTokenResult =
|
|
130
|
+
| { kind: 'token'; token: string }
|
|
131
|
+
| { kind: 'error'; code: 4 | 5 | 6; message: string };
|
|
132
|
+
|
|
133
|
+
export interface RequestProjectTokenInput {
|
|
134
|
+
repoFullName: string;
|
|
135
|
+
env: NodeJS.ProcessEnv;
|
|
136
|
+
/** 注入 fetch(测试用);生产使用全局 fetch。 */
|
|
137
|
+
fetch?: typeof fetch;
|
|
138
|
+
/** 注入超时(测试或用例需要时)。 */
|
|
139
|
+
timeoutMs?: number;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const MISSING_ENV_KEYS = ['ZAG_AGENT_API_ENDPOINT', 'ZAG_CONTROLLER_ID', 'ZAG_HOST_KEY'] as const;
|
|
143
|
+
|
|
144
|
+
function missingEnvKeys(env: NodeJS.ProcessEnv): string[] {
|
|
145
|
+
return MISSING_ENV_KEYS.filter((key) => {
|
|
146
|
+
const value = env[key];
|
|
147
|
+
return typeof value !== 'string' || value.trim().length === 0;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function isValidToken(token: unknown): token is string {
|
|
152
|
+
return (
|
|
153
|
+
typeof token === 'string' &&
|
|
154
|
+
token.length > 0 &&
|
|
155
|
+
token.length <= MAX_TOKEN_LENGTH &&
|
|
156
|
+
!/\s/.test(token)
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function sameRepo(a: string, b: string): boolean {
|
|
161
|
+
return a.trim().toLowerCase() === b.trim().toLowerCase();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function parseJson(text: string): Record<string, unknown> | null {
|
|
165
|
+
try {
|
|
166
|
+
const value = JSON.parse(text) as unknown;
|
|
167
|
+
return value && typeof value === 'object' ? (value as Record<string, unknown>) : null;
|
|
168
|
+
} catch {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* 向 agent-api 申请项目级 Github token。
|
|
175
|
+
*
|
|
176
|
+
* 错误信息只含可读文案,不含 token / 响应体原文;退出码语义见 D6。
|
|
177
|
+
*/
|
|
178
|
+
export async function requestProjectToken(
|
|
179
|
+
input: RequestProjectTokenInput,
|
|
180
|
+
): Promise<ProjectTokenResult> {
|
|
181
|
+
const missing = missingEnvKeys(input.env);
|
|
182
|
+
if (missing.length > 0) {
|
|
183
|
+
return { kind: 'error', code: 6, message: `缺少环境变量:${missing.join('、')}` };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const endpoint = input.env.ZAG_AGENT_API_ENDPOINT!.trim().replace(/\/+$/, '');
|
|
187
|
+
const controllerId = input.env.ZAG_CONTROLLER_ID!.trim();
|
|
188
|
+
const hostKey = input.env.ZAG_HOST_KEY!.trim();
|
|
189
|
+
const url = `${endpoint}/internal/cloud-hosts/${encodeURIComponent(controllerId)}/github-credential`;
|
|
190
|
+
const fetchFn = input.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
|
|
191
|
+
|
|
192
|
+
const controller = new AbortController();
|
|
193
|
+
const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? REQUEST_TIMEOUT_MS);
|
|
194
|
+
timer.unref?.();
|
|
195
|
+
|
|
196
|
+
let status: number;
|
|
197
|
+
let text: string;
|
|
198
|
+
try {
|
|
199
|
+
const response = await fetchFn(url, {
|
|
200
|
+
method: 'POST',
|
|
201
|
+
headers: {
|
|
202
|
+
Authorization: `Bearer ${hostKey}`,
|
|
203
|
+
'Content-Type': 'application/json',
|
|
204
|
+
},
|
|
205
|
+
body: JSON.stringify({ repoFullName: input.repoFullName }),
|
|
206
|
+
signal: controller.signal,
|
|
207
|
+
});
|
|
208
|
+
status = response.status;
|
|
209
|
+
text = await response.text();
|
|
210
|
+
} catch (error) {
|
|
211
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
212
|
+
const message = /abort/i.test(reason)
|
|
213
|
+
? 'Github 凭据申请超时'
|
|
214
|
+
: 'Github 凭据申请失败(平台不可达)';
|
|
215
|
+
return { kind: 'error', code: 6, message };
|
|
216
|
+
} finally {
|
|
217
|
+
clearTimeout(timer);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const payload = text ? parseJson(text) : null;
|
|
221
|
+
const errorCode = typeof payload?.error === 'string' ? payload.error : '';
|
|
222
|
+
|
|
223
|
+
if (status === 200) {
|
|
224
|
+
const token = payload?.token;
|
|
225
|
+
const echoed = payload?.repoFullName;
|
|
226
|
+
if (typeof echoed !== 'string' || !sameRepo(echoed, input.repoFullName)) {
|
|
227
|
+
return { kind: 'error', code: 6, message: 'Github 凭据响应与请求项目不一致' };
|
|
228
|
+
}
|
|
229
|
+
if (!isValidToken(token)) {
|
|
230
|
+
return { kind: 'error', code: 6, message: 'Github 凭据响应缺少合法 token' };
|
|
231
|
+
}
|
|
232
|
+
return { kind: 'token', token };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (status === 404) {
|
|
236
|
+
return {
|
|
237
|
+
kind: 'error',
|
|
238
|
+
code: 4,
|
|
239
|
+
message:
|
|
240
|
+
errorCode === 'PROJECT_NOT_BOUND'
|
|
241
|
+
? '该项目尚未在平台初始化'
|
|
242
|
+
: '云主机未绑定 Github 项目',
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
if (status === 403) {
|
|
246
|
+
return {
|
|
247
|
+
kind: 'error',
|
|
248
|
+
code: 5,
|
|
249
|
+
message:
|
|
250
|
+
errorCode === 'REPO_NOT_AUTHORIZED' ? '当前账号无该项目权限' : 'Github 凭据申请被拒绝',
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
return { kind: 'error', code: 6, message: `Github 凭据申请失败(HTTP ${status})` };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export interface RunGithubTokenCommandOptions {
|
|
257
|
+
cwd?: string;
|
|
258
|
+
env?: NodeJS.ProcessEnv;
|
|
259
|
+
resolveGitProject?: typeof resolveGitProject;
|
|
260
|
+
requestProjectToken?: typeof requestProjectToken;
|
|
261
|
+
/** 输出通道(测试注入);生产为 `process.stdout.write`。 */
|
|
262
|
+
stdout?: (text: string) => void;
|
|
263
|
+
stderr?: (text: string) => void;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* `agent-gear github-token` 的完整编排。
|
|
268
|
+
*
|
|
269
|
+
* 纪律(D5):**零 logger**;成功时 stdout 只有一行 token,失败时 stdout 为空、stderr 一行。
|
|
270
|
+
* 返回退出码(不调用 `process.exit`,便于测试)。
|
|
271
|
+
*/
|
|
272
|
+
export async function runGithubTokenCommand(
|
|
273
|
+
options: RunGithubTokenCommandOptions = {},
|
|
274
|
+
): Promise<number> {
|
|
275
|
+
const cwd = options.cwd ?? process.cwd();
|
|
276
|
+
const env = options.env ?? process.env;
|
|
277
|
+
const writeStdout = options.stdout ?? ((text: string) => void process.stdout.write(text));
|
|
278
|
+
const writeStderr = options.stderr ?? ((text: string) => void process.stderr.write(text));
|
|
279
|
+
const resolve = options.resolveGitProject ?? resolveGitProject;
|
|
280
|
+
const request = options.requestProjectToken ?? requestProjectToken;
|
|
281
|
+
|
|
282
|
+
const project = await resolve(cwd);
|
|
283
|
+
if (project.kind !== 'project') return EXIT_NOT_PROJECT;
|
|
284
|
+
|
|
285
|
+
const result = await request({ repoFullName: project.repoFullName, env });
|
|
286
|
+
if (result.kind === 'token') {
|
|
287
|
+
writeStdout(`${result.token}\n`);
|
|
288
|
+
return EXIT_OK;
|
|
289
|
+
}
|
|
290
|
+
writeStderr(`${result.message}\n`);
|
|
291
|
+
return result.code;
|
|
292
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { writePid, removePid, isRunning } from './daemon.js';
|
|
|
9
9
|
import { startMcpRegistration } from './commands/mcp-proxy.js';
|
|
10
10
|
import { startMcpProxy } from './commands/mcp.js';
|
|
11
11
|
import { registerHarnessCommands } from './commands/harness.js';
|
|
12
|
+
import { registerGithubCommands } from './commands/github.js';
|
|
12
13
|
import { isCloudHostMode, startCloudHostSupervisor } from './cloud-host/supervisor.js';
|
|
13
14
|
import { processRegistry, isProcessAlive } from './acp/process-registry.js';
|
|
14
15
|
import { logger as rootLogger } from './observability/logger.js';
|
|
@@ -155,4 +156,7 @@ program
|
|
|
155
156
|
// 云电脑 harness 初始化子命令:`agent-gear harness prepare`(init 脚本调用)。
|
|
156
157
|
registerHarnessCommands(program);
|
|
157
158
|
|
|
159
|
+
// 云电脑 Github 项目级凭据:`agent-gear github-token`(gh wrapper 调用)。
|
|
160
|
+
registerGithubCommands(program);
|
|
161
|
+
|
|
158
162
|
program.parse();
|