@pulsarinteractive/geniustasker 0.1.0-beta.1 → 0.1.0-beta.11

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/LICENSES/Apache-2.0.txt +202 -0
  5. package/README.md +47 -370
  6. package/SECURITY.md +14 -0
  7. package/THIRD_PARTY_NOTICES.md +15 -0
  8. package/docs/ARCHITECTURE.md +144 -0
  9. package/docs/CHATGPT.md +86 -0
  10. package/docs/CLI.md +444 -0
  11. package/docs/DOCUMENTATION_SYNC.md +144 -0
  12. package/docs/INTEGRATIONS.md +62 -0
  13. package/docs/LIMITS.md +62 -0
  14. package/docs/MEMORY.md +38 -0
  15. package/docs/OPENAI.md +21 -0
  16. package/docs/OPENAI_PUBLICATION.md +22 -0
  17. package/docs/PLANNING.md +79 -0
  18. package/docs/PROJECT_FILTERS.md +77 -0
  19. package/docs/RELEASING.md +23 -0
  20. package/docs/TESTING.md +52 -0
  21. package/docs/WORKFLOWS.md +37 -0
  22. package/examples/codex.toml +3 -0
  23. package/examples/mcp.json +8 -0
  24. package/mcp.json +10 -0
  25. package/package.json +45 -9
  26. package/plugin.json +24 -0
  27. package/remote/tool-catalog.json +1374 -0
  28. package/remote/workflows.json +67 -0
  29. package/skills/geniustasker/SKILL.md +49 -116
  30. package/skills/geniustasker/agents/openai.yaml +4 -0
  31. package/skills/geniustasker/references/collaboration.md +70 -0
  32. package/skills/geniustasker/references/incremental-reads.md +16 -0
  33. package/skills/geniustasker/references/profiles.md +22 -0
  34. package/skills/geniustasker/references/project-reads.md +43 -0
  35. package/skills/geniustasker-documentation/SKILL.md +39 -0
  36. package/skills/geniustasker-documentation/agents/openai.yaml +4 -0
  37. package/skills/geniustasker-documentation/references/structure.md +29 -0
  38. package/skills/geniustasker-graph/SKILL.md +31 -0
  39. package/skills/geniustasker-graph/agents/openai.yaml +4 -0
  40. package/skills/geniustasker-media/SKILL.md +33 -0
  41. package/skills/geniustasker-media/agents/openai.yaml +4 -0
  42. package/skills/geniustasker-memory/SKILL.md +120 -0
  43. package/skills/geniustasker-memory/agents/openai.yaml +4 -0
  44. package/skills/geniustasker-memory/references/knowledge-workflows.md +57 -0
  45. package/skills/geniustasker-planning/SKILL.md +28 -0
  46. package/skills/geniustasker-planning/agents/openai.yaml +4 -0
  47. package/src/changes.mjs +104 -28
  48. package/src/cli.mjs +453 -77
  49. package/src/client.mjs +210 -34
  50. package/src/command-catalog.mjs +545 -263
  51. package/src/commands.mjs +225 -53
  52. package/src/documentation-graph.mjs +251 -0
  53. package/src/documentation-store.mjs +589 -0
  54. package/src/documentation-sync.mjs +517 -0
  55. package/src/documentation.mjs +136 -0
  56. package/src/errors.mjs +55 -12
  57. package/src/knowledge.mjs +109 -0
  58. package/src/login.mjs +190 -47
  59. package/src/mcp.mjs +310 -43
  60. package/src/media.mjs +307 -0
  61. package/src/presentation.d.mts +1 -0
  62. package/src/presentation.mjs +12 -0
  63. package/src/profiles.mjs +123 -32
  64. package/src/read-cache.mjs +111 -0
  65. package/src/recovery.mjs +80 -0
  66. package/src/store.mjs +101 -26
  67. package/src/transport.mjs +182 -33
  68. package/src/workflows.mjs +9 -0
@@ -0,0 +1,80 @@
1
+ import { AgentError } from './errors.mjs';
2
+
3
+ /** Seconds and IMF-fixdate, using the response clock when supplied. No early cap. */
4
+ export function retryAfterSeconds(response, error, now = Date.now()) {
5
+ const value = response.headers.get('Retry-After');
6
+ if (value !== null && /^\d+(?:\.\d+)?$/.test(value.trim())) {
7
+ const seconds = Number(value);
8
+ if (seconds >= 0) {
9
+ return Math.min(Number.MAX_SAFE_INTEGER, seconds);
10
+ }
11
+ }
12
+ const date =
13
+ value && /^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value)
14
+ ? Date.parse(value)
15
+ : NaN;
16
+ if (Number.isFinite(date)) {
17
+ const serverDate = Date.parse(response.headers.get('Date') ?? '');
18
+ return Math.max(0, (date - (Number.isFinite(serverDate) ? serverDate : now)) / 1000);
19
+ }
20
+ if (Number.isFinite(error?.retryAfterMs) && error.retryAfterMs >= 0) {
21
+ return error.retryAfterMs / 1000;
22
+ }
23
+ if (Number.isFinite(error?.retryAfterSeconds) && error.retryAfterSeconds >= 0) {
24
+ return error.retryAfterSeconds;
25
+ }
26
+ if (Number.isSafeInteger(error?.resetAt) && error.resetAt > now) {
27
+ return (error.resetAt - now) / 1000;
28
+ }
29
+ return undefined;
30
+ }
31
+
32
+ /** An explicit edge challenge never reached the origin. An opaque refusal may have. */
33
+ export function edgeRefusal(response, data) {
34
+ const challenge = response.headers.get('cf-mitigated')?.toLowerCase() === 'challenge';
35
+ const error = data?.error;
36
+ const code = typeof error === 'string' ? error : error?.code;
37
+ const recognized =
38
+ typeof code === 'string' &&
39
+ /^[a-zA-Z0-9_.:-]{1,100}$/.test(code) &&
40
+ !response.headers.get('content-type')?.toLowerCase().includes('text/html');
41
+ if (!challenge && (![401, 403].includes(response.status) || recognized)) {
42
+ return null;
43
+ }
44
+ return new AgentError(
45
+ challenge ? 'edge_challenge' : 'edge_refusal_unknown',
46
+ 'A temporary protection refused the request. The saved session and operation are retained.',
47
+ {
48
+ status: 503,
49
+ retryable: true,
50
+ remediation:
51
+ 'Wait for retryAfterSeconds, then retry the same saved operation. Do not discard its journal.',
52
+ retryAfterSeconds: retryAfterSeconds(response, error) ?? 60,
53
+ execution: challenge ? 'not_started' : 'unknown',
54
+ },
55
+ );
56
+ }
57
+
58
+ /** Persist a positive jitter once; extreme waits suspend rather than overflow a timer. */
59
+ export function retryAt(error, now = Date.now(), random = Math.random) {
60
+ const seconds = error?.details?.retryAfterSeconds;
61
+ if (!error?.retryable || !Number.isFinite(seconds) || seconds < 0) {
62
+ return undefined;
63
+ }
64
+ const jitter = 1000 + Math.floor(Math.max(0, Math.min(1, random())) * 29000);
65
+ return Math.min(Number.MAX_SAFE_INTEGER, now + Math.ceil(seconds * 1000) + jitter);
66
+ }
67
+
68
+ export function requireRetryReady(deadline, now = Date.now()) {
69
+ if (Number.isSafeInteger(deadline) && deadline > now) {
70
+ throw new AgentError('retry_pending', 'The saved request is waiting for the server cooldown.', {
71
+ status: 429,
72
+ retryable: true,
73
+ execution: 'not_started',
74
+ retryAfterSeconds: Math.ceil((deadline - now) / 1000),
75
+ retryAt: deadline,
76
+ remediation:
77
+ 'Wait for the saved deadline, then retry the same operation. No request was sent.',
78
+ });
79
+ }
80
+ }
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({ directory = join(homedir(), '.geniustasker'), context = 'default', lockTimeoutMs = 20000, maxBytes = 16384 } = {}) {
15
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(context)) fail('invalid_arguments', 'Context names use 1–48 letters, numbers, underscores or hyphens.');
16
- this.context = context; this.maxBytes = maxBytes;
17
- this.directory = resolve(directory); this.path = join(this.directory, `${context}.json`); this.lockPath = `${this.path}.lock`; this.lockTimeoutMs = lockTimeoutMs;
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 (!stat.isDirectory() || stat.isSymbolicLink() || (process.getuid && stat.uid !== process.getuid()) || process.platform !== 'win32' && (stat.mode & 0o077))
23
- fail('unsafe_credential_store', 'The credential directory must be private and owned by you.', { remediation: 'Use a dedicated directory with permissions 0700.' });
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(); let handle;
27
- try { handle = await open(this.path, constants.O_RDONLY | constants.O_NOFOLLOW); }
28
- catch (error) { if (error.code === 'ENOENT') return null; fail('unsafe_credential_store', 'The credential file could not be opened safely.'); }
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 (!stat.isFile() || stat.nlink !== 1 || stat.size > this.maxBytes || process.platform !== 'win32' && (stat.mode & 0o077) || process.getuid && stat.uid !== process.getuid())
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
- try { return JSON.parse(await handle.readFile('utf8')); }
34
- catch { fail('invalid_credential_store', 'The credential file is damaged.', { remediation: 'Revoke the session in Account → Agents, then remove this context and log in again.' }); }
35
- } finally { await handle.close(); }
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 { await handle.writeFile(JSON.stringify(data)); await handle.sync(); }
41
- finally { await handle.close(); }
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 { await directory.sync(); } finally { await directory.close(); }
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() { await unlink(this.path).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
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(); const deadline = Date.now() + this.lockTimeoutMs;
115
+ await this.prepare();
116
+ const deadline = Date.now() + this.lockTimeoutMs;
54
117
  while (true) {
55
- try { await mkdir(this.lockPath, { mode: 0o700 }); break; }
56
- catch (error) {
57
- if (error.code !== 'EEXIST') throw error;
58
- if (Date.now() >= deadline) fail('credential_store_busy', 'Another command owns this credential context.', { retryable: true,
59
- remediation: 'Wait for that command. After a crash, stop all clients using this context, then remove its empty .lock directory.' });
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 { return await callback(); }
64
- finally { await rmdir(this.lockPath); }
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,217 @@
1
1
  import { AgentError, fail } from './errors.mjs';
2
+ import catalog from './command-catalog.mjs';
3
+ import { edgeRefusal, retryAfterSeconds } from './recovery.mjs';
2
4
 
3
- export const ORIGINS = Object.freeze({ production: 'https://api-geniustasker.pulsarinteractive.cloud', development: 'https://dev-api-geniustasker.pulsarinteractive.cloud' });
5
+ export const ORIGINS = Object.freeze({
6
+ production: 'https://api-geniustasker.pulsarinteractive.cloud',
7
+ development: 'https://dev-api-geniustasker.pulsarinteractive.cloud',
8
+ });
4
9
  export const CLIENT_ID = 'geniustasker-cli';
10
+ /** Resolve an approved API origin; loopback is available only by explicit opt-in. */
5
11
  export function originOf(value = ORIGINS.production, allowLocal = false) {
6
- let url; try { url = new URL(value); } catch { fail('invalid_origin', 'An absolute API origin is required.'); }
7
- if (url.username || url.password || url.pathname !== '/' || url.search || url.hash ||
8
- !(Object.values(ORIGINS).includes(url.origin) || allowLocal && url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname)))
9
- fail('invalid_origin', 'Use a GeniusTasker API origin or an explicit loopback origin with --allow-local.');
12
+ let url;
13
+ try {
14
+ url = new URL(value);
15
+ } catch {
16
+ fail('invalid_origin', 'An absolute API origin is required.');
17
+ }
18
+ if (
19
+ url.username ||
20
+ url.password ||
21
+ url.pathname !== '/' ||
22
+ url.search ||
23
+ url.hash ||
24
+ !(
25
+ Object.values(ORIGINS).includes(url.origin) ||
26
+ (allowLocal && url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname))
27
+ )
28
+ ) {
29
+ fail(
30
+ 'invalid_origin',
31
+ 'Use a GeniusTasker API origin or an explicit loopback origin with --allow-local.',
32
+ );
33
+ }
10
34
  return url.origin;
11
35
  }
12
36
 
13
- const identifier = value => typeof value === 'string' && /^[a-zA-Z0-9_.:-]{1,100}$/.test(value) ? value : undefined;
14
- const boundedText = value => typeof value === 'string' && value.length <= 500 && !/[\u0000-\u001f\u007f]/u.test(value) && !/gta1\.|wd[ar]_|sk-proj-/u.test(value) ? value : undefined;
37
+ const identifier = (value) =>
38
+ typeof value === 'string' && /^[a-zA-Z0-9_.:-]{1,100}$/.test(value) ? value : undefined;
39
+ const boundedText = (value) =>
40
+ typeof value === 'string' &&
41
+ value.length <= 500 &&
42
+ // eslint-disable-next-line no-control-regex -- Reject control characters in untrusted input.
43
+ !/[\u0000-\u001f\u007f]/u.test(value) &&
44
+ !/gta1\.|wd[ar]_|sk-proj-/u.test(value)
45
+ ? value
46
+ : undefined;
47
+ /**
48
+ * Bounded HTTP transport for delegated endpoints, with no implicit retries.
49
+ * Call originOf before construction; inject fetch/signal for controlled tests
50
+ * and operation-level cancellation. Error serialization excludes raw responses.
51
+ */
15
52
  export class Transport {
16
- constructor(origin, { fetchImpl = fetch, timeoutMs = 15000, signal } = {}) { this.origin = origin; this.fetch = fetchImpl; this.timeoutMs = timeoutMs; this.signal = signal; }
17
- async request(path, { method = 'GET', form, json, token, query } = {}) {
18
- if (!(path.startsWith('/api/agents/') || path === '/.well-known/oauth-authorization-server') || path.startsWith('//'))
53
+ constructor(origin, { fetchImpl = fetch, timeoutMs = 15000, signal } = {}) {
54
+ this.origin = origin;
55
+ this.fetch = fetchImpl;
56
+ this.timeoutMs = timeoutMs;
57
+ this.signal = signal;
58
+ }
59
+ async request(path, { method = 'GET', form, json, token, query, bytes, binary = false } = {}) {
60
+ if (
61
+ !(path.startsWith('/api/agents/') || path === '/.well-known/oauth-authorization-server') ||
62
+ path.startsWith('//')
63
+ ) {
19
64
  fail('invalid_arguments', 'Only delegated endpoints are available.');
65
+ }
20
66
  const url = new URL(path, this.origin);
21
- if (url.origin !== this.origin || !(url.pathname.startsWith('/api/agents/') || url.pathname === '/.well-known/oauth-authorization-server'))
67
+ if (
68
+ url.origin !== this.origin ||
69
+ !(
70
+ url.pathname.startsWith('/api/agents/') ||
71
+ url.pathname === '/.well-known/oauth-authorization-server'
72
+ )
73
+ ) {
22
74
  fail('invalid_origin', 'Cross-origin or non-delegated requests are refused.');
23
- if (query) for (const [key, value] of Object.entries(query)) if (value !== undefined) url.searchParams.set(key, String(value));
24
- if (form && json !== undefined) fail('invalid_arguments', 'Choose one request body format.');
75
+ }
76
+ if (query) {
77
+ for (const [key, value] of Object.entries(query)) {
78
+ if (value !== undefined) {
79
+ url.searchParams.set(key, String(value));
80
+ }
81
+ }
82
+ }
83
+ if (
84
+ (bytes !== undefined || binary) &&
85
+ (url.pathname !== '/api/agents/v1/media/content' ||
86
+ (bytes !== undefined && (!Buffer.isBuffer(bytes) || bytes.length > 15000000)) ||
87
+ (bytes !== undefined && (json !== undefined || form)))
88
+ ) {
89
+ fail('invalid_arguments', 'Binary transfer requires the bounded delegated media endpoint.');
90
+ }
91
+ if (form && json !== undefined) {
92
+ fail('invalid_arguments', 'Choose one request body format.');
93
+ }
25
94
  const jsonBody = json === undefined ? undefined : JSON.stringify(json);
26
- if (jsonBody && Buffer.byteLength(jsonBody) > 32768) fail('invalid_arguments', 'Command exceeds the 32 KiB request limit.');
95
+ if (jsonBody && Buffer.byteLength(jsonBody) > catalog.maxCommandBytes) {
96
+ fail(
97
+ 'invalid_arguments',
98
+ `Command exceeds the ${catalog.maxCommandBytes} byte request limit.`,
99
+ );
100
+ }
27
101
  let response;
28
102
  const timeout = AbortSignal.timeout(this.timeoutMs);
29
103
  const signal = this.signal ? AbortSignal.any([timeout, this.signal]) : timeout;
30
104
  try {
31
- response = await this.fetch(url, { method, redirect: 'error', signal,
32
- headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(form ? { 'Content-Type': 'application/x-www-form-urlencoded' } : jsonBody ? { 'Content-Type': 'application/json' } : {}) },
33
- ...(form ? { body: new URLSearchParams(form) } : jsonBody ? { body: jsonBody } : {}) });
105
+ response = await this.fetch(url, {
106
+ method,
107
+ redirect: 'error',
108
+ signal,
109
+ headers: {
110
+ Accept: binary ? 'application/octet-stream' : 'application/json',
111
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
112
+ ...(bytes !== undefined
113
+ ? { 'Content-Type': 'application/octet-stream', 'Content-Length': String(bytes.length) }
114
+ : form
115
+ ? { 'Content-Type': 'application/x-www-form-urlencoded' }
116
+ : jsonBody
117
+ ? { 'Content-Type': 'application/json' }
118
+ : {}),
119
+ },
120
+ ...(bytes !== undefined
121
+ ? { body: bytes }
122
+ : form
123
+ ? { body: new URLSearchParams(form) }
124
+ : jsonBody
125
+ ? { body: jsonBody }
126
+ : {}),
127
+ });
34
128
  } catch {
35
- throw new AgentError('network_unavailable', 'The API did not return a usable response.', { retryable: true, remediation: 'Check connectivity. Authentication exchanges are never retried automatically.', execution: method === 'GET' ? 'not_applicable' : 'unknown' });
129
+ throw new AgentError('network_unavailable', 'The API did not return a usable response.', {
130
+ retryable: true,
131
+ remediation:
132
+ 'Check connectivity. Authentication exchanges are never retried automatically.',
133
+ execution: method === 'GET' ? 'not_applicable' : 'unknown',
134
+ });
36
135
  }
37
- const chunks = []; let size = 0;
136
+ const challenge = edgeRefusal(response, null);
137
+ if (response.headers.get('cf-mitigated')?.toLowerCase() === 'challenge') {
138
+ await response.body?.cancel().catch(() => {});
139
+ throw challenge;
140
+ }
141
+ const chunks = [];
142
+ let size = 0;
38
143
  try {
39
- if (response.body) for await (const chunk of response.body) {
40
- size += chunk.length;
41
- if (size > 262144) fail('invalid_response', 'The API response exceeded the size limit.');
42
- chunks.push(chunk);
144
+ if (response.body) {
145
+ for await (const chunk of response.body) {
146
+ size += chunk.length;
147
+ if (size > (binary && response.ok ? 15000000 : 262144)) {
148
+ fail('invalid_response', 'The API response exceeded the size limit.');
149
+ }
150
+ chunks.push(chunk);
151
+ }
43
152
  }
44
153
  } catch (error) {
45
- if (error instanceof AgentError) throw error;
46
- fail('network_unavailable', 'The API response was interrupted.', { retryable: true, execution: method === 'GET' ? 'not_applicable' : 'unknown' });
154
+ if (error instanceof AgentError) {
155
+ throw error;
156
+ }
157
+ fail('network_unavailable', 'The API response was interrupted.', {
158
+ retryable: true,
159
+ execution: method === 'GET' ? 'not_applicable' : 'unknown',
160
+ });
161
+ }
162
+ if (binary && response.ok) {
163
+ return Buffer.concat(chunks);
47
164
  }
48
165
  let data;
49
- try { data = size ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : null; }
50
- catch { fail('invalid_response', 'The API returned an unexpected format.', { status: response.status }); }
166
+ try {
167
+ data = size ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : null;
168
+ } catch {
169
+ const refusal = edgeRefusal(response, null);
170
+ if (refusal) {
171
+ throw refusal;
172
+ }
173
+ fail('invalid_response', 'The API returned an unexpected format.', {
174
+ status: response.status,
175
+ retryable: response.status === 429 || response.status >= 500,
176
+ retryAfterSeconds: retryAfterSeconds(response) ?? 60,
177
+ execution: method === 'GET' ? 'not_applicable' : 'unknown',
178
+ });
179
+ }
180
+ const refusal = edgeRefusal(response, data);
181
+ if (refusal) {
182
+ throw refusal;
183
+ }
51
184
  if (!response.ok) {
52
185
  const e = data?.error;
53
186
  const code = identifier(typeof e === 'string' ? e : e?.code) ?? 'api_error';
54
- const retry = Number(response.headers.get('Retry-After') ?? e?.retryAfterSeconds);
187
+ const retry =
188
+ retryAfterSeconds(response, e) ?? ([429, 503].includes(response.status) ? 60 : undefined);
55
189
  throw new AgentError(code, boundedText(e?.message) ?? 'The API refused the request.', {
56
- status: response.status, retryable: typeof e?.retryable === 'boolean' ? e.retryable : response.status === 429 || response.status === 503,
57
- remediation: boundedText(e?.remediation) ?? (response.status === 401 ? 'Run auth login again; check the connection in Account → Agents.' : 'Check permissions, availability and command help.'),
190
+ status: response.status,
191
+ retryable:
192
+ typeof e?.retryable === 'boolean'
193
+ ? e.retryable
194
+ : response.status === 429 || response.status === 503,
195
+ remediation:
196
+ boundedText(e?.remediation) ??
197
+ (response.status === 401
198
+ ? 'Run auth login again; check the connection in Account → Agents.'
199
+ : 'Check permissions, availability and command help.'),
58
200
  ...(identifier(e?.requestId) ? { requestId: e.requestId } : {}),
59
- ...(Number.isFinite(retry) && retry >= 0 && retry <= 86400 ? { retryAfterSeconds: retry } : {}),
60
- ...(Number.isSafeInteger(data?.interval) && data.interval > 0 ? { interval: data.interval } : {}),
201
+ ...(Number.isFinite(retry) && retry >= 0 ? { retryAfterSeconds: retry } : {}),
202
+ ...(Number.isSafeInteger(data?.interval) && data.interval > 0
203
+ ? { interval: data.interval }
204
+ : {}),
61
205
  ...(identifier(e?.execution) ? { execution: e.execution } : {}),
62
206
  ...(Number.isSafeInteger(e?.resetAt) && e.resetAt > 0 ? { resetAt: e.resetAt } : {}),
63
207
  });
64
208
  }
65
209
  return data;
66
210
  }
67
- oauth(endpoint, form) { return this.request(`/api/agents/oauth/${endpoint}`, { method: 'POST', form: { client_id: CLIENT_ID, ...form } }); }
211
+ oauth(endpoint, form) {
212
+ return this.request(`/api/agents/oauth/${endpoint}`, {
213
+ method: 'POST',
214
+ form: { client_id: CLIENT_ID, ...form },
215
+ });
216
+ }
68
217
  }
@@ -0,0 +1,9 @@
1
+ import * as z from 'zod/v4';
2
+ import guides from '../remote/workflows.json' with { type: 'json' };
3
+
4
+ /** Reviewed static guidance, shared with the hosted connector. No account data. */
5
+ export const workflowSchema = z.object({ topic: z.enum(Object.keys(guides.topics)) }).strict();
6
+ export function workflow(input) {
7
+ const { topic } = workflowSchema.parse(input);
8
+ return { version: guides.version, topic, ...guides.topics[topic] };
9
+ }