@pulsarinteractive/geniustasker 0.1.0-beta.1 → 0.1.0-beta.3
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 +23 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +21 -0
- package/LICENSES/Apache-2.0.txt +202 -0
- package/README.md +52 -371
- package/SECURITY.md +14 -0
- package/THIRD_PARTY_NOTICES.md +15 -0
- package/docs/ARCHITECTURE.md +104 -0
- package/docs/CLI.md +395 -0
- package/docs/INTEGRATIONS.md +62 -0
- package/docs/OPENAI.md +37 -0
- package/docs/RELEASING.md +16 -0
- package/docs/TESTING.md +52 -0
- package/examples/codex.toml +3 -0
- package/examples/mcp.json +8 -0
- package/mcp.json +10 -0
- package/package.json +42 -7
- package/plugin.json +24 -0
- package/skills/geniustasker/SKILL.md +6 -115
- package/skills/geniustasker/agents/openai.yaml +4 -0
- package/skills/geniustasker/references/collaboration.md +70 -0
- package/skills/geniustasker/references/incremental-reads.md +16 -0
- package/skills/geniustasker/references/profiles.md +22 -0
- package/skills/geniustasker-memory/SKILL.md +52 -0
- package/skills/geniustasker-memory/agents/openai.yaml +4 -0
- package/src/changes.mjs +104 -28
- package/src/cli.mjs +298 -77
- package/src/client.mjs +149 -32
- package/src/commands.mjs +202 -52
- package/src/errors.mjs +55 -12
- package/src/login.mjs +190 -47
- package/src/mcp.mjs +183 -43
- package/src/profiles.mjs +123 -32
- package/src/store.mjs +101 -26
- package/src/transport.mjs +141 -31
package/src/profiles.mjs
CHANGED
|
@@ -2,62 +2,153 @@ import * as z from 'zod/v4';
|
|
|
2
2
|
import { AgentError, fail } from './errors.mjs';
|
|
3
3
|
import catalog from './command-catalog.mjs';
|
|
4
4
|
|
|
5
|
-
const name = z
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
5
|
+
const name = z
|
|
6
|
+
.string()
|
|
7
|
+
.trim()
|
|
8
|
+
.min(1)
|
|
9
|
+
.max(80)
|
|
10
|
+
// eslint-disable-next-line no-control-regex -- Reject control characters in untrusted input.
|
|
11
|
+
.regex(/^[^\u0000-\u001f\u007f]+$/u);
|
|
12
|
+
const unique = (values) => new Set(values).size === values.length;
|
|
13
|
+
export const grantSchema = z
|
|
14
|
+
.object({
|
|
15
|
+
allResources: z.boolean(),
|
|
16
|
+
resourceIds: z
|
|
17
|
+
.array(z.string().min(1).max(256))
|
|
18
|
+
.max(catalog.grants.maxResources)
|
|
19
|
+
.refine(unique),
|
|
20
|
+
permissions: z
|
|
21
|
+
.array(z.enum(catalog.grants.permissions))
|
|
22
|
+
.max(catalog.grants.permissions.length)
|
|
23
|
+
.refine(unique),
|
|
24
|
+
})
|
|
25
|
+
.strict()
|
|
26
|
+
.refine((grant) => !grant.allResources || grant.resourceIds.length === 0);
|
|
12
27
|
export const profileCreateSchema = z.object({ id: z.uuid(), name, grant: grantSchema }).strict();
|
|
13
|
-
export const profileRestrictSchema = z
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
28
|
+
export const profileRestrictSchema = z
|
|
29
|
+
.object({
|
|
30
|
+
profileId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
|
|
31
|
+
name,
|
|
32
|
+
expectedRevision: z.number().int().min(1),
|
|
33
|
+
grant: grantSchema,
|
|
34
|
+
})
|
|
35
|
+
.strict();
|
|
36
|
+
export const profileSelectSchema = z
|
|
37
|
+
.object({ profileId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/) })
|
|
38
|
+
.strict();
|
|
39
|
+
const choiceSchema = z
|
|
40
|
+
.object({
|
|
41
|
+
id: z.string(),
|
|
42
|
+
name,
|
|
43
|
+
revision: z.number().int().min(1),
|
|
44
|
+
current: z.boolean(),
|
|
45
|
+
permissions: z.array(z.string()),
|
|
46
|
+
allResources: z.boolean(),
|
|
47
|
+
resourceCount: z.number().int().min(0),
|
|
48
|
+
})
|
|
49
|
+
.strict();
|
|
50
|
+
const choicesSchema = z
|
|
51
|
+
.object({
|
|
52
|
+
connectionId: z.string(),
|
|
53
|
+
currentProfileId: z.string(),
|
|
54
|
+
items: z.array(choiceSchema).max(catalog.grants.maxProfilesPerConnection),
|
|
55
|
+
})
|
|
56
|
+
.strict();
|
|
57
|
+
const profileSchema = z
|
|
58
|
+
.object({
|
|
59
|
+
id: z.string(),
|
|
60
|
+
connectionId: z.string(),
|
|
61
|
+
name,
|
|
62
|
+
revision: z.number().int().min(1),
|
|
63
|
+
grant: grantSchema,
|
|
64
|
+
disabledAt: z.number().nullable(),
|
|
65
|
+
})
|
|
66
|
+
.strict();
|
|
67
|
+
const input = (schema, value) => {
|
|
68
|
+
const result = schema.safeParse(value);
|
|
69
|
+
if (!result.success) {
|
|
70
|
+
fail('invalid_arguments', 'Use the declared profile fields, a valid name and a bounded grant.');
|
|
71
|
+
}
|
|
72
|
+
return result.data;
|
|
73
|
+
};
|
|
20
74
|
|
|
21
75
|
/** Profile management is separate from domain-operation journals: creation has
|
|
22
76
|
* an explicit UUID retained in the caller's file, restriction a live revision,
|
|
23
77
|
* and selection rotates the credential family under the credential-store lock. */
|
|
24
78
|
export class AgentProfiles {
|
|
25
|
-
constructor(client) {
|
|
79
|
+
constructor(client) {
|
|
80
|
+
this.client = client;
|
|
81
|
+
}
|
|
26
82
|
async list() {
|
|
27
83
|
const result = choicesSchema.safeParse(await this.client.get('profiles'));
|
|
28
|
-
if (!result.success)
|
|
84
|
+
if (!result.success) {
|
|
85
|
+
fail('invalid_response', 'The profile list was invalid.');
|
|
86
|
+
}
|
|
29
87
|
return result.data;
|
|
30
88
|
}
|
|
31
|
-
async create(value) {
|
|
32
|
-
|
|
89
|
+
async create(value) {
|
|
90
|
+
return this.write('profiles', 'POST', input(profileCreateSchema, value));
|
|
91
|
+
}
|
|
92
|
+
async restrict(value) {
|
|
93
|
+
return this.write('profile', 'PUT', input(profileRestrictSchema, value));
|
|
94
|
+
}
|
|
33
95
|
async write(resource, method, value) {
|
|
34
96
|
const session = await this.client.authorizedSession();
|
|
35
|
-
if (method === 'PUT' && value.profileId !== session.profile_id)
|
|
36
|
-
fail('profile_selection_conflict', 'This draft belongs to another profile.', {
|
|
97
|
+
if (method === 'PUT' && value.profileId !== session.profile_id) {
|
|
98
|
+
fail('profile_selection_conflict', 'This draft belongs to another profile.', {
|
|
99
|
+
status: 409,
|
|
100
|
+
remediation: 'Read whoami and prepare a fresh restriction for the intended profile.',
|
|
101
|
+
});
|
|
102
|
+
}
|
|
37
103
|
try {
|
|
38
|
-
const result = await this.client.transport.request(`/api/agents/v1/${resource}`, {
|
|
104
|
+
const result = await this.client.transport.request(`/api/agents/v1/${resource}`, {
|
|
105
|
+
method,
|
|
106
|
+
token: session.access_token,
|
|
107
|
+
json: value,
|
|
108
|
+
});
|
|
39
109
|
const parsed = profileSchema.safeParse(result);
|
|
40
|
-
if (
|
|
41
|
-
|
|
110
|
+
if (
|
|
111
|
+
!parsed.success ||
|
|
112
|
+
parsed.data.connectionId !== session.connection_id ||
|
|
113
|
+
parsed.data.id !== (method === 'POST' ? value.id : session.profile_id)
|
|
114
|
+
) {
|
|
42
115
|
fail('invalid_response', 'The profile change could not be confirmed.');
|
|
116
|
+
}
|
|
43
117
|
return parsed.data;
|
|
44
118
|
} catch (error) {
|
|
45
|
-
if (!(error instanceof AgentError))
|
|
119
|
+
if (!(error instanceof AgentError)) {
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
46
122
|
error.details.profileId = method === 'POST' ? value.id : session.profile_id;
|
|
47
123
|
error.details.execution ??= 'unknown';
|
|
48
|
-
error.remediation =
|
|
49
|
-
|
|
50
|
-
|
|
124
|
+
error.remediation =
|
|
125
|
+
method === 'POST'
|
|
126
|
+
? 'List profiles and reconcile this profileId. Keep the same UUID on retry; do not create a replacement after an uncertain reply.'
|
|
127
|
+
: 'Read whoami to see the current profile and revision before preparing another restriction.';
|
|
51
128
|
throw error;
|
|
52
129
|
}
|
|
53
130
|
}
|
|
54
131
|
async select(value) {
|
|
55
132
|
const { profileId } = input(profileSelectSchema, value);
|
|
56
133
|
const choices = await this.list();
|
|
57
|
-
const source = choices.items.find(p => p.id === choices.currentProfileId && p.current);
|
|
58
|
-
const target = choices.items.find(p => p.id === profileId);
|
|
59
|
-
if (!source || !target)
|
|
60
|
-
|
|
61
|
-
|
|
134
|
+
const source = choices.items.find((p) => p.id === choices.currentProfileId && p.current);
|
|
135
|
+
const target = choices.items.find((p) => p.id === profileId);
|
|
136
|
+
if (!source || !target) {
|
|
137
|
+
fail(
|
|
138
|
+
'profile_selection_denied',
|
|
139
|
+
'This profile is not available within the current connection and permissions.',
|
|
140
|
+
{
|
|
141
|
+
status: 403,
|
|
142
|
+
remediation: 'Run profiles list. An agent cannot switch back to broader permissions.',
|
|
143
|
+
},
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
return this.client.selectProfile({
|
|
147
|
+
profileId,
|
|
148
|
+
expectedRevision: target.revision,
|
|
149
|
+
expectedSourceRevision: source.revision,
|
|
150
|
+
sourceProfileId: source.id,
|
|
151
|
+
connectionId: choices.connectionId,
|
|
152
|
+
});
|
|
62
153
|
}
|
|
63
154
|
}
|
package/src/store.mjs
CHANGED
|
@@ -11,56 +11,131 @@ import { fail } from './errors.mjs';
|
|
|
11
11
|
* A hard crash deliberately leaves a lock/refresh marker rather than risking a
|
|
12
12
|
* second use of a rotated refresh token. Doctor explains recovery. */
|
|
13
13
|
export class CredentialStore {
|
|
14
|
-
constructor({
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
constructor({
|
|
15
|
+
directory = join(homedir(), '.geniustasker'),
|
|
16
|
+
context = 'default',
|
|
17
|
+
lockTimeoutMs = 20000,
|
|
18
|
+
maxBytes = 16384,
|
|
19
|
+
} = {}) {
|
|
20
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(context)) {
|
|
21
|
+
fail('invalid_arguments', 'Context names use 1–48 letters, numbers, underscores or hyphens.');
|
|
22
|
+
}
|
|
23
|
+
this.context = context;
|
|
24
|
+
this.maxBytes = maxBytes;
|
|
25
|
+
this.directory = resolve(directory);
|
|
26
|
+
this.path = join(this.directory, `${context}.json`);
|
|
27
|
+
this.lockPath = `${this.path}.lock`;
|
|
28
|
+
this.lockTimeoutMs = lockTimeoutMs;
|
|
18
29
|
}
|
|
19
30
|
async prepare() {
|
|
20
31
|
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
21
32
|
const stat = await lstat(this.directory);
|
|
22
|
-
if (
|
|
23
|
-
|
|
33
|
+
if (
|
|
34
|
+
!stat.isDirectory() ||
|
|
35
|
+
stat.isSymbolicLink() ||
|
|
36
|
+
(process.getuid && stat.uid !== process.getuid()) ||
|
|
37
|
+
(process.platform !== 'win32' && stat.mode & 0o077)
|
|
38
|
+
) {
|
|
39
|
+
fail(
|
|
40
|
+
'unsafe_credential_store',
|
|
41
|
+
'The credential directory must be private and owned by you.',
|
|
42
|
+
{ remediation: 'Use a dedicated directory with permissions 0700.' },
|
|
43
|
+
);
|
|
44
|
+
}
|
|
24
45
|
}
|
|
25
46
|
async read() {
|
|
26
|
-
await this.prepare();
|
|
27
|
-
|
|
28
|
-
|
|
47
|
+
await this.prepare();
|
|
48
|
+
let handle;
|
|
49
|
+
try {
|
|
50
|
+
handle = await open(this.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (error.code === 'ENOENT') {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
fail('unsafe_credential_store', 'The credential file could not be opened safely.');
|
|
56
|
+
}
|
|
29
57
|
try {
|
|
30
58
|
const stat = await handle.stat();
|
|
31
|
-
if (
|
|
59
|
+
if (
|
|
60
|
+
!stat.isFile() ||
|
|
61
|
+
stat.nlink !== 1 ||
|
|
62
|
+
stat.size > this.maxBytes ||
|
|
63
|
+
(process.platform !== 'win32' && stat.mode & 0o077) ||
|
|
64
|
+
(process.getuid && stat.uid !== process.getuid())
|
|
65
|
+
) {
|
|
32
66
|
fail('unsafe_credential_store', 'The credential file must be private and owned by you.');
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
return JSON.parse(await handle.readFile('utf8'));
|
|
70
|
+
} catch {
|
|
71
|
+
fail('invalid_credential_store', 'The credential file is damaged.', {
|
|
72
|
+
remediation:
|
|
73
|
+
'Revoke the session in Account → Agents, then remove this context and log in again.',
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
} finally {
|
|
77
|
+
await handle.close();
|
|
78
|
+
}
|
|
36
79
|
}
|
|
37
80
|
async write(data) {
|
|
38
81
|
const temporary = `${this.path}.${randomUUID()}.tmp`;
|
|
39
82
|
const handle = await open(temporary, 'wx', 0o600);
|
|
40
|
-
try {
|
|
41
|
-
|
|
83
|
+
try {
|
|
84
|
+
await handle.writeFile(JSON.stringify(data));
|
|
85
|
+
await handle.sync();
|
|
86
|
+
} finally {
|
|
87
|
+
await handle.close();
|
|
88
|
+
}
|
|
42
89
|
try {
|
|
43
90
|
await rename(temporary, this.path);
|
|
44
91
|
if (process.platform !== 'win32') {
|
|
45
92
|
const directory = await open(this.directory, constants.O_RDONLY);
|
|
46
|
-
try {
|
|
93
|
+
try {
|
|
94
|
+
await directory.sync();
|
|
95
|
+
} finally {
|
|
96
|
+
await directory.close();
|
|
97
|
+
}
|
|
47
98
|
}
|
|
99
|
+
} finally {
|
|
100
|
+
await unlink(temporary).catch((error) => {
|
|
101
|
+
if (error.code !== 'ENOENT') {
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
});
|
|
48
105
|
}
|
|
49
|
-
finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
|
|
50
106
|
}
|
|
51
|
-
async remove() {
|
|
107
|
+
async remove() {
|
|
108
|
+
await unlink(this.path).catch((error) => {
|
|
109
|
+
if (error.code !== 'ENOENT') {
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
}
|
|
52
114
|
async locked(callback, signal) {
|
|
53
|
-
await this.prepare();
|
|
115
|
+
await this.prepare();
|
|
116
|
+
const deadline = Date.now() + this.lockTimeoutMs;
|
|
54
117
|
while (true) {
|
|
55
|
-
try {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
118
|
+
try {
|
|
119
|
+
await mkdir(this.lockPath, { mode: 0o700 });
|
|
120
|
+
break;
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (error.code !== 'EEXIST') {
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
if (Date.now() >= deadline) {
|
|
126
|
+
fail('credential_store_busy', 'Another command owns this credential context.', {
|
|
127
|
+
retryable: true,
|
|
128
|
+
remediation:
|
|
129
|
+
'Wait for that command. After a crash, stop all clients using this context, then remove its empty .lock directory.',
|
|
130
|
+
});
|
|
131
|
+
}
|
|
60
132
|
await delay(50, undefined, { signal });
|
|
61
133
|
}
|
|
62
134
|
}
|
|
63
|
-
try {
|
|
64
|
-
|
|
135
|
+
try {
|
|
136
|
+
return await callback();
|
|
137
|
+
} finally {
|
|
138
|
+
await rmdir(this.lockPath);
|
|
139
|
+
}
|
|
65
140
|
}
|
|
66
141
|
}
|
package/src/transport.mjs
CHANGED
|
@@ -1,68 +1,178 @@
|
|
|
1
1
|
import { AgentError, fail } from './errors.mjs';
|
|
2
2
|
|
|
3
|
-
export const ORIGINS = Object.freeze({
|
|
3
|
+
export const ORIGINS = Object.freeze({
|
|
4
|
+
production: 'https://api-geniustasker.pulsarinteractive.cloud',
|
|
5
|
+
development: 'https://dev-api-geniustasker.pulsarinteractive.cloud',
|
|
6
|
+
});
|
|
4
7
|
export const CLIENT_ID = 'geniustasker-cli';
|
|
8
|
+
/** Resolve an approved API origin; loopback is available only by explicit opt-in. */
|
|
5
9
|
export function originOf(value = ORIGINS.production, allowLocal = false) {
|
|
6
|
-
let url;
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
+
let url;
|
|
11
|
+
try {
|
|
12
|
+
url = new URL(value);
|
|
13
|
+
} catch {
|
|
14
|
+
fail('invalid_origin', 'An absolute API origin is required.');
|
|
15
|
+
}
|
|
16
|
+
if (
|
|
17
|
+
url.username ||
|
|
18
|
+
url.password ||
|
|
19
|
+
url.pathname !== '/' ||
|
|
20
|
+
url.search ||
|
|
21
|
+
url.hash ||
|
|
22
|
+
!(
|
|
23
|
+
Object.values(ORIGINS).includes(url.origin) ||
|
|
24
|
+
(allowLocal && url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname))
|
|
25
|
+
)
|
|
26
|
+
) {
|
|
27
|
+
fail(
|
|
28
|
+
'invalid_origin',
|
|
29
|
+
'Use a GeniusTasker API origin or an explicit loopback origin with --allow-local.',
|
|
30
|
+
);
|
|
31
|
+
}
|
|
10
32
|
return url.origin;
|
|
11
33
|
}
|
|
12
34
|
|
|
13
|
-
const identifier =
|
|
14
|
-
|
|
35
|
+
const identifier = (value) =>
|
|
36
|
+
typeof value === 'string' && /^[a-zA-Z0-9_.:-]{1,100}$/.test(value) ? value : undefined;
|
|
37
|
+
const boundedText = (value) =>
|
|
38
|
+
typeof value === 'string' &&
|
|
39
|
+
value.length <= 500 &&
|
|
40
|
+
// eslint-disable-next-line no-control-regex -- Reject control characters in untrusted input.
|
|
41
|
+
!/[\u0000-\u001f\u007f]/u.test(value) &&
|
|
42
|
+
!/gta1\.|wd[ar]_|sk-proj-/u.test(value)
|
|
43
|
+
? value
|
|
44
|
+
: undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Bounded HTTP transport for delegated endpoints, with no implicit retries.
|
|
47
|
+
* Call originOf before construction; inject fetch/signal for controlled tests
|
|
48
|
+
* and operation-level cancellation. Error serialization excludes raw responses.
|
|
49
|
+
*/
|
|
15
50
|
export class Transport {
|
|
16
|
-
constructor(origin, { fetchImpl = fetch, timeoutMs = 15000, signal } = {}) {
|
|
51
|
+
constructor(origin, { fetchImpl = fetch, timeoutMs = 15000, signal } = {}) {
|
|
52
|
+
this.origin = origin;
|
|
53
|
+
this.fetch = fetchImpl;
|
|
54
|
+
this.timeoutMs = timeoutMs;
|
|
55
|
+
this.signal = signal;
|
|
56
|
+
}
|
|
17
57
|
async request(path, { method = 'GET', form, json, token, query } = {}) {
|
|
18
|
-
if (
|
|
58
|
+
if (
|
|
59
|
+
!(path.startsWith('/api/agents/') || path === '/.well-known/oauth-authorization-server') ||
|
|
60
|
+
path.startsWith('//')
|
|
61
|
+
) {
|
|
19
62
|
fail('invalid_arguments', 'Only delegated endpoints are available.');
|
|
63
|
+
}
|
|
20
64
|
const url = new URL(path, this.origin);
|
|
21
|
-
if (
|
|
65
|
+
if (
|
|
66
|
+
url.origin !== this.origin ||
|
|
67
|
+
!(
|
|
68
|
+
url.pathname.startsWith('/api/agents/') ||
|
|
69
|
+
url.pathname === '/.well-known/oauth-authorization-server'
|
|
70
|
+
)
|
|
71
|
+
) {
|
|
22
72
|
fail('invalid_origin', 'Cross-origin or non-delegated requests are refused.');
|
|
23
|
-
|
|
24
|
-
if (
|
|
73
|
+
}
|
|
74
|
+
if (query) {
|
|
75
|
+
for (const [key, value] of Object.entries(query)) {
|
|
76
|
+
if (value !== undefined) {
|
|
77
|
+
url.searchParams.set(key, String(value));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (form && json !== undefined) {
|
|
82
|
+
fail('invalid_arguments', 'Choose one request body format.');
|
|
83
|
+
}
|
|
25
84
|
const jsonBody = json === undefined ? undefined : JSON.stringify(json);
|
|
26
|
-
if (jsonBody && Buffer.byteLength(jsonBody) > 32768)
|
|
85
|
+
if (jsonBody && Buffer.byteLength(jsonBody) > 32768) {
|
|
86
|
+
fail('invalid_arguments', 'Command exceeds the 32 KiB request limit.');
|
|
87
|
+
}
|
|
27
88
|
let response;
|
|
28
89
|
const timeout = AbortSignal.timeout(this.timeoutMs);
|
|
29
90
|
const signal = this.signal ? AbortSignal.any([timeout, this.signal]) : timeout;
|
|
30
91
|
try {
|
|
31
|
-
response = await this.fetch(url, {
|
|
32
|
-
|
|
33
|
-
|
|
92
|
+
response = await this.fetch(url, {
|
|
93
|
+
method,
|
|
94
|
+
redirect: 'error',
|
|
95
|
+
signal,
|
|
96
|
+
headers: {
|
|
97
|
+
Accept: 'application/json',
|
|
98
|
+
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
99
|
+
...(form
|
|
100
|
+
? { 'Content-Type': 'application/x-www-form-urlencoded' }
|
|
101
|
+
: jsonBody
|
|
102
|
+
? { 'Content-Type': 'application/json' }
|
|
103
|
+
: {}),
|
|
104
|
+
},
|
|
105
|
+
...(form ? { body: new URLSearchParams(form) } : jsonBody ? { body: jsonBody } : {}),
|
|
106
|
+
});
|
|
34
107
|
} catch {
|
|
35
|
-
throw new AgentError('network_unavailable', 'The API did not return a usable response.', {
|
|
108
|
+
throw new AgentError('network_unavailable', 'The API did not return a usable response.', {
|
|
109
|
+
retryable: true,
|
|
110
|
+
remediation:
|
|
111
|
+
'Check connectivity. Authentication exchanges are never retried automatically.',
|
|
112
|
+
execution: method === 'GET' ? 'not_applicable' : 'unknown',
|
|
113
|
+
});
|
|
36
114
|
}
|
|
37
|
-
const chunks = [];
|
|
115
|
+
const chunks = [];
|
|
116
|
+
let size = 0;
|
|
38
117
|
try {
|
|
39
|
-
if (response.body)
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
118
|
+
if (response.body) {
|
|
119
|
+
for await (const chunk of response.body) {
|
|
120
|
+
size += chunk.length;
|
|
121
|
+
if (size > 262144) {
|
|
122
|
+
fail('invalid_response', 'The API response exceeded the size limit.');
|
|
123
|
+
}
|
|
124
|
+
chunks.push(chunk);
|
|
125
|
+
}
|
|
43
126
|
}
|
|
44
127
|
} catch (error) {
|
|
45
|
-
if (error instanceof AgentError)
|
|
46
|
-
|
|
128
|
+
if (error instanceof AgentError) {
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
fail('network_unavailable', 'The API response was interrupted.', {
|
|
132
|
+
retryable: true,
|
|
133
|
+
execution: method === 'GET' ? 'not_applicable' : 'unknown',
|
|
134
|
+
});
|
|
47
135
|
}
|
|
48
136
|
let data;
|
|
49
|
-
try {
|
|
50
|
-
|
|
137
|
+
try {
|
|
138
|
+
data = size ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : null;
|
|
139
|
+
} catch {
|
|
140
|
+
fail('invalid_response', 'The API returned an unexpected format.', {
|
|
141
|
+
status: response.status,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
51
144
|
if (!response.ok) {
|
|
52
145
|
const e = data?.error;
|
|
53
146
|
const code = identifier(typeof e === 'string' ? e : e?.code) ?? 'api_error';
|
|
54
147
|
const retry = Number(response.headers.get('Retry-After') ?? e?.retryAfterSeconds);
|
|
55
148
|
throw new AgentError(code, boundedText(e?.message) ?? 'The API refused the request.', {
|
|
56
|
-
status: response.status,
|
|
57
|
-
|
|
149
|
+
status: response.status,
|
|
150
|
+
retryable:
|
|
151
|
+
typeof e?.retryable === 'boolean'
|
|
152
|
+
? e.retryable
|
|
153
|
+
: response.status === 429 || response.status === 503,
|
|
154
|
+
remediation:
|
|
155
|
+
boundedText(e?.remediation) ??
|
|
156
|
+
(response.status === 401
|
|
157
|
+
? 'Run auth login again; check the connection in Account → Agents.'
|
|
158
|
+
: 'Check permissions, availability and command help.'),
|
|
58
159
|
...(identifier(e?.requestId) ? { requestId: e.requestId } : {}),
|
|
59
|
-
...(Number.isFinite(retry) && retry >= 0 && retry <= 86400
|
|
60
|
-
|
|
160
|
+
...(Number.isFinite(retry) && retry >= 0 && retry <= 86400
|
|
161
|
+
? { retryAfterSeconds: retry }
|
|
162
|
+
: {}),
|
|
163
|
+
...(Number.isSafeInteger(data?.interval) && data.interval > 0
|
|
164
|
+
? { interval: data.interval }
|
|
165
|
+
: {}),
|
|
61
166
|
...(identifier(e?.execution) ? { execution: e.execution } : {}),
|
|
62
167
|
...(Number.isSafeInteger(e?.resetAt) && e.resetAt > 0 ? { resetAt: e.resetAt } : {}),
|
|
63
168
|
});
|
|
64
169
|
}
|
|
65
170
|
return data;
|
|
66
171
|
}
|
|
67
|
-
oauth(endpoint, form) {
|
|
172
|
+
oauth(endpoint, form) {
|
|
173
|
+
return this.request(`/api/agents/oauth/${endpoint}`, {
|
|
174
|
+
method: 'POST',
|
|
175
|
+
form: { client_id: CLIENT_ID, ...form },
|
|
176
|
+
});
|
|
177
|
+
}
|
|
68
178
|
}
|