@akai-workflow-builder/cli-sdk 0.2.1 → 0.3.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/CHANGELOG.md +7 -0
- package/dist/runtime/execute-request.d.ts +25 -0
- package/dist/runtime/execute-request.d.ts.map +1 -0
- package/dist/runtime/execute-request.js +36 -0
- package/dist/runtime/executor/classify-error.d.ts +11 -0
- package/dist/runtime/executor/classify-error.d.ts.map +1 -0
- package/dist/runtime/executor/classify-error.js +162 -0
- package/dist/runtime/executor/image-compress.d.ts +26 -0
- package/dist/runtime/executor/image-compress.d.ts.map +1 -0
- package/dist/runtime/executor/image-compress.js +202 -0
- package/dist/runtime/executor/index.d.ts +44 -0
- package/dist/runtime/executor/index.d.ts.map +1 -0
- package/dist/runtime/executor/index.js +393 -0
- package/dist/runtime/executor/redact.d.ts +9 -0
- package/dist/runtime/executor/redact.d.ts.map +1 -0
- package/dist/runtime/executor/redact.js +23 -0
- package/dist/runtime/index.d.ts +15 -0
- package/dist/runtime/index.d.ts.map +1 -0
- package/dist/runtime/index.js +13 -0
- package/dist/runtime/registry/index.d.ts +5 -0
- package/dist/runtime/registry/index.d.ts.map +1 -0
- package/dist/runtime/registry/index.js +1 -0
- package/dist/runtime/registry/loader.d.ts +42 -0
- package/dist/runtime/registry/loader.d.ts.map +1 -0
- package/dist/runtime/registry/loader.js +621 -0
- package/dist/runtime/registry/types.d.ts +252 -0
- package/dist/runtime/registry/types.d.ts.map +1 -0
- package/dist/runtime/registry/types.js +1 -0
- package/dist/runtime/registry/wire.d.ts +152 -0
- package/dist/runtime/registry/wire.d.ts.map +1 -0
- package/dist/runtime/registry/wire.js +299 -0
- package/package.json +22 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,13 @@ All notable changes to `@akai-workflow-builder/cli-sdk` are documented here.
|
|
|
4
4
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
6
6
|
|
|
7
|
+
## [0.3.0](https://github.com/akai-workflow-builder/akai-cli-sdk/compare/cli-sdk-v0.2.1...cli-sdk-v0.3.0) (2026-07-28)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
### Features
|
|
11
|
+
|
|
12
|
+
* add /runtime subpath export (executeTool + registry loader) [AKAI-2112] ([396711d](https://github.com/akai-workflow-builder/akai-cli-sdk/commit/396711dd67e4743c99be05dd30b382dbe07a7a0a))
|
|
13
|
+
|
|
7
14
|
## [0.2.1](https://github.com/akai-workflow-builder/akai-cli-sdk/compare/cli-sdk-v0.2.0...cli-sdk-v0.2.1) (2026-07-23)
|
|
8
15
|
|
|
9
16
|
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/**
|
|
3
|
+
* Wire shape of `POST /tools/execute` request bodies. Validated by the
|
|
4
|
+
* route handler before any registry / SDK code runs — a parse failure
|
|
5
|
+
* here yields 400 `invalid_envelope`; per-tool input validation comes
|
|
6
|
+
* later (422 `invalid_input`).
|
|
7
|
+
*
|
|
8
|
+
* Secrets are typed as a `Record<string, string>` — undefined values
|
|
9
|
+
* mean "not provided" and should be omitted by the caller. Required-
|
|
10
|
+
* but-missing is caught downstream by the SDK's `buildScopedSecrets`.
|
|
11
|
+
*/
|
|
12
|
+
export declare const ExecuteRequestBody: z.ZodObject<{
|
|
13
|
+
cli: z.ZodString;
|
|
14
|
+
tool: z.ZodString;
|
|
15
|
+
input: z.ZodUnknown;
|
|
16
|
+
isJson: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
17
|
+
secrets: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
|
|
18
|
+
properties: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
|
|
19
|
+
confirmedWrite: z.ZodOptional<z.ZodBoolean>;
|
|
20
|
+
outputPutUrl: z.ZodOptional<z.ZodString>;
|
|
21
|
+
oauthAccessToken: z.ZodOptional<z.ZodString>;
|
|
22
|
+
appTokenAccessToken: z.ZodOptional<z.ZodString>;
|
|
23
|
+
}, z.core.$strip>;
|
|
24
|
+
export type ExecuteRequestBody = z.infer<typeof ExecuteRequestBody>;
|
|
25
|
+
//# sourceMappingURL=execute-request.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execute-request.d.ts","sourceRoot":"","sources":["../../src/runtime/execute-request.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;GASG;AACH,eAAO,MAAM,kBAAkB;;;;;;;;;;;iBAwB7B,CAAC;AAEH,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/**
|
|
3
|
+
* Wire shape of `POST /tools/execute` request bodies. Validated by the
|
|
4
|
+
* route handler before any registry / SDK code runs — a parse failure
|
|
5
|
+
* here yields 400 `invalid_envelope`; per-tool input validation comes
|
|
6
|
+
* later (422 `invalid_input`).
|
|
7
|
+
*
|
|
8
|
+
* Secrets are typed as a `Record<string, string>` — undefined values
|
|
9
|
+
* mean "not provided" and should be omitted by the caller. Required-
|
|
10
|
+
* but-missing is caught downstream by the SDK's `buildScopedSecrets`.
|
|
11
|
+
*/
|
|
12
|
+
export const ExecuteRequestBody = z.object({
|
|
13
|
+
cli: z.string().min(1, 'cli is required'),
|
|
14
|
+
tool: z.string().min(1, 'tool is required'),
|
|
15
|
+
input: z.unknown(),
|
|
16
|
+
isJson: z.boolean().optional().default(true),
|
|
17
|
+
secrets: z.record(z.string(), z.string()).optional().default({}),
|
|
18
|
+
// Non-sensitive tenant property values (base URL, region, environment),
|
|
19
|
+
// resolved by akai-app and forwarded by the worker. Scoped to the tool's
|
|
20
|
+
// declared propertyKeys and surfaced as `ctx.properties` by the executor.
|
|
21
|
+
properties: z.record(z.string(), z.string()).optional().default({}),
|
|
22
|
+
confirmedWrite: z.boolean().optional(),
|
|
23
|
+
// Presigned PUT URL the worker pre-mints for file-output tools
|
|
24
|
+
// (`tool.options.producesFiles === true`). The executor uploads a gzip-tar
|
|
25
|
+
// of whatever the handler wrote via `ctx.writeFile` to this URL; the worker
|
|
26
|
+
// extracts it into AGENT_WORKDIR. Required for producesFiles tools — its
|
|
27
|
+
// absence on such a call yields `output_channel_missing`.
|
|
28
|
+
outputPutUrl: z.string().url().optional(),
|
|
29
|
+
// OAuth access token the host injects per session. The executor forwards it
|
|
30
|
+
// into the SDK ctx as `ctx.oauth.accessToken`; google clients dual-read it
|
|
31
|
+
// (preferred) or fall back to the legacy GMAIL_ACCESS_TOKEN secret.
|
|
32
|
+
oauthAccessToken: z.string().min(1).optional(),
|
|
33
|
+
// App (client-credentials) token the host mints via the connection's appToken
|
|
34
|
+
// spec. Forwarded into `ctx.appToken.accessToken` by the executor.
|
|
35
|
+
appTokenAccessToken: z.string().min(1).optional(),
|
|
36
|
+
});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type ToolErrorKind = 'not_found' | 'forbidden' | 'auth_expired' | 'invalid_input' | 'conflict' | 'rate_limited' | 'unavailable';
|
|
2
|
+
export interface ClassifiedError {
|
|
3
|
+
readonly kind: ToolErrorKind;
|
|
4
|
+
readonly message: string;
|
|
5
|
+
readonly meta?: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
export declare function classifyTypedThrow(err: unknown): ClassifiedError | null;
|
|
8
|
+
export declare function classifyError(err: unknown): ClassifiedError | null;
|
|
9
|
+
export declare function describeUpstreamError(err: unknown): string | undefined;
|
|
10
|
+
export declare function classifyConventionError(err: unknown, source: 'baseline' | 'customer'): ClassifiedError | null;
|
|
11
|
+
//# sourceMappingURL=classify-error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"classify-error.d.ts","sourceRoot":"","sources":["../../../src/runtime/executor/classify-error.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,aAAa,GACrB,WAAW,GACX,WAAW,GACX,cAAc,GACd,eAAe,GACf,UAAU,GACV,cAAc,GACd,aAAa,CAAC;AAYlB,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACzC;AAKD,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,eAAe,GAAG,IAAI,CAYvE;AAmBD,wBAAgB,aAAa,CAAC,GAAG,EAAE,OAAO,GAAG,eAAe,GAAG,IAAI,CAwClE;AAQD,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAkBtE;AAyDD,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,OAAO,EACZ,MAAM,EAAE,UAAU,GAAG,UAAU,GAC9B,eAAe,GAAG,IAAI,CAKxB"}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
const KINDS = new Set([
|
|
2
|
+
'not_found',
|
|
3
|
+
'forbidden',
|
|
4
|
+
'auth_expired',
|
|
5
|
+
'invalid_input',
|
|
6
|
+
'conflict',
|
|
7
|
+
'rate_limited',
|
|
8
|
+
'unavailable',
|
|
9
|
+
]);
|
|
10
|
+
// Brand-duck-typed on `name === 'AkaiToolError'` + a known `kind` (no SDK class
|
|
11
|
+
// import). An untrusted throw that merely has a `kind` but no brand is not vetted
|
|
12
|
+
// and falls through to the generic classifier.
|
|
13
|
+
export function classifyTypedThrow(err) {
|
|
14
|
+
if (err === null || typeof err !== 'object')
|
|
15
|
+
return null;
|
|
16
|
+
const e = err;
|
|
17
|
+
if (e.name !== 'AkaiToolError')
|
|
18
|
+
return null;
|
|
19
|
+
if (typeof e.kind !== 'string' || !KINDS.has(e.kind))
|
|
20
|
+
return null;
|
|
21
|
+
if (typeof e.message !== 'string')
|
|
22
|
+
return null;
|
|
23
|
+
const meta = e.meta;
|
|
24
|
+
return {
|
|
25
|
+
kind: e.kind,
|
|
26
|
+
message: e.message,
|
|
27
|
+
...(meta && typeof meta === 'object' ? { meta: meta } : {}),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
// Explicit allowlist, not a `/^E.../` regex — that would also match Node `ERR_*`
|
|
31
|
+
// codes (caller errors, not network outages) and wrongly mark them retryable.
|
|
32
|
+
const NETWORK_CODES = new Set([
|
|
33
|
+
'ENOTFOUND',
|
|
34
|
+
'ECONNRESET',
|
|
35
|
+
'ECONNREFUSED',
|
|
36
|
+
'ECONNABORTED',
|
|
37
|
+
'ETIMEDOUT',
|
|
38
|
+
'ESOCKETTIMEDOUT',
|
|
39
|
+
'EAI_AGAIN',
|
|
40
|
+
'EPIPE',
|
|
41
|
+
'EHOSTUNREACH',
|
|
42
|
+
'EHOSTDOWN',
|
|
43
|
+
'ENETUNREACH',
|
|
44
|
+
'ENETDOWN',
|
|
45
|
+
]);
|
|
46
|
+
export function classifyError(err) {
|
|
47
|
+
if (err === null || typeof err !== 'object')
|
|
48
|
+
return null;
|
|
49
|
+
const e = err;
|
|
50
|
+
const code = e.code;
|
|
51
|
+
if (typeof code === 'string' && NETWORK_CODES.has(code)) {
|
|
52
|
+
return { kind: 'unavailable', message: 'Upstream service unreachable — retry shortly.', meta: { retryable: true } };
|
|
53
|
+
}
|
|
54
|
+
if (e.name === 'AbortError') {
|
|
55
|
+
return { kind: 'unavailable', message: 'Request aborted — retry.', meta: { retryable: true } };
|
|
56
|
+
}
|
|
57
|
+
const status = pickHttpStatus(e);
|
|
58
|
+
if (status === undefined)
|
|
59
|
+
return null; // unknown shape → generic 500
|
|
60
|
+
if (status >= 500)
|
|
61
|
+
return null; // upstream 5xx is a real failure → generic 500
|
|
62
|
+
// The provider's own error description (sanitized) turns an opaque "HTTP 400"
|
|
63
|
+
// into a diagnosable one (e.g. Sheets "Unable to parse range: <tab>"). Only
|
|
64
|
+
// appended to the resource/state 4xx — 401 (sensitive) and 429 (transient)
|
|
65
|
+
// keep their fixed, action-oriented guidance.
|
|
66
|
+
const detail = describeUpstreamError(e);
|
|
67
|
+
const withDetail = (kind, base) => ({
|
|
68
|
+
kind,
|
|
69
|
+
message: detail ? `${base}: ${detail}.` : `${base}.`,
|
|
70
|
+
});
|
|
71
|
+
switch (status) {
|
|
72
|
+
case 401:
|
|
73
|
+
return { kind: 'auth_expired', message: 'Authentication expired or invalid — reconnect the integration.' };
|
|
74
|
+
case 403:
|
|
75
|
+
return withDetail('forbidden', 'Permission denied for this resource');
|
|
76
|
+
case 404:
|
|
77
|
+
return withDetail('not_found', 'Resource not found — check the id/URL and that you have access');
|
|
78
|
+
case 409:
|
|
79
|
+
return withDetail('conflict', 'Conflict with the current state of the resource');
|
|
80
|
+
case 429:
|
|
81
|
+
return { kind: 'rate_limited', message: 'Rate limit hit — retry shortly.', meta: { retryable: true } };
|
|
82
|
+
default:
|
|
83
|
+
return withDetail('invalid_input', `Request rejected by the upstream service (HTTP ${status})`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const MAX_DETAIL_LENGTH = 200;
|
|
87
|
+
// Pull the provider's STRUCTURED error description out of known error shapes, in
|
|
88
|
+
// priority order, and sanitize it. We read only well-known message fields —
|
|
89
|
+
// never the raw error/response object — so nothing but the provider's own
|
|
90
|
+
// wording can be surfaced. Returns undefined when no known shape has a message.
|
|
91
|
+
export function describeUpstreamError(err) {
|
|
92
|
+
if (err === null || typeof err !== 'object')
|
|
93
|
+
return undefined;
|
|
94
|
+
const e = err;
|
|
95
|
+
const response = asRecord(e.response);
|
|
96
|
+
const data = asRecord(response?.data);
|
|
97
|
+
const dataError = data?.error;
|
|
98
|
+
const raw = asString(asRecord(dataError)?.message) ?? // googleapis: response.data.error.message
|
|
99
|
+
asString(asRecord(asArray(e.errors)?.[0])?.message) ?? // { errors: [{ message }] }
|
|
100
|
+
asString(data?.message) ?? // generic: response.data.message
|
|
101
|
+
asString(dataError) ?? // response.data.error is itself a string
|
|
102
|
+
asString(asRecord(e.body)?.message) ?? // { body: { message } }
|
|
103
|
+
asString(e.body); // body is itself a string
|
|
104
|
+
if (raw === undefined)
|
|
105
|
+
return undefined;
|
|
106
|
+
const cleaned = sanitizeDetail(raw);
|
|
107
|
+
return cleaned.length > 0 ? cleaned : undefined;
|
|
108
|
+
}
|
|
109
|
+
// Surface only the provider's wording, scrubbed of anything credential-shaped:
|
|
110
|
+
// collapse whitespace, strip `Bearer <...>` and `key=/token=/secret=` values,
|
|
111
|
+
// drop JWT and long opaque base64/hex runs, then length-cap. Over-scrubs by
|
|
112
|
+
// design — never leak.
|
|
113
|
+
function sanitizeDetail(input) {
|
|
114
|
+
let s = input.replace(/\s+/g, ' ').trim();
|
|
115
|
+
s = s.replace(/\bBearer\s+[A-Za-z0-9._~+/\-]+=*/gi, 'Bearer ***');
|
|
116
|
+
s = s.replace(/\b(client[_-]?secret|api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|passwd|authorization|auth|key|sig|signature)(\s*[=:]\s*)"?[^\s"'&,;]+"?/gi, '$1$2***');
|
|
117
|
+
s = s.replace(/\b[A-Za-z0-9._\-]+\.[A-Za-z0-9._\-]{16,}\.[A-Za-z0-9._\-]+/g, '***'); // JWT-ish
|
|
118
|
+
s = s.replace(/[A-Za-z0-9+/_\-]{20,}={0,2}/g, '***'); // long opaque base64/hex run
|
|
119
|
+
s = s.replace(/\s+/g, ' ').trim().replace(/[.!?;:]+$/, '');
|
|
120
|
+
if (s.length > MAX_DETAIL_LENGTH) {
|
|
121
|
+
s = `${s.slice(0, MAX_DETAIL_LENGTH).trimEnd()}…`;
|
|
122
|
+
}
|
|
123
|
+
return s;
|
|
124
|
+
}
|
|
125
|
+
function asRecord(x) {
|
|
126
|
+
return x !== null && typeof x === 'object' ? x : undefined;
|
|
127
|
+
}
|
|
128
|
+
function asArray(x) {
|
|
129
|
+
return Array.isArray(x) ? x : undefined;
|
|
130
|
+
}
|
|
131
|
+
function asString(x) {
|
|
132
|
+
return typeof x === 'string' && x.trim().length > 0 ? x : undefined;
|
|
133
|
+
}
|
|
134
|
+
// Status from the common error shapes, numeric fields only — a string syscall
|
|
135
|
+
// code in `err.code` is never read as a status.
|
|
136
|
+
function pickHttpStatus(e) {
|
|
137
|
+
const response = e.response;
|
|
138
|
+
const candidate = asNumber(e.status) ??
|
|
139
|
+
asNumber(response?.status) ??
|
|
140
|
+
asNumber(e.statusCode) ??
|
|
141
|
+
asNumber(e.code);
|
|
142
|
+
if (candidate === undefined)
|
|
143
|
+
return undefined;
|
|
144
|
+
return Number.isInteger(candidate) && candidate >= 100 && candidate <= 599 ? candidate : undefined;
|
|
145
|
+
}
|
|
146
|
+
function asNumber(x) {
|
|
147
|
+
return typeof x === 'number' ? x : undefined;
|
|
148
|
+
}
|
|
149
|
+
// Baseline tools throw `Error: ...` / `Error <verb>ing ...:` for user-facing
|
|
150
|
+
// failures (the legacy console.error convention legacy surfaced on stderr). Only
|
|
151
|
+
// trust BASELINE source — its text is audited and secret-free; customer tools
|
|
152
|
+
// stay generic, as do non-convention messages (bugs) so they keep logging.
|
|
153
|
+
const CONVENTION_PREFIX = /^Error[:\s]/;
|
|
154
|
+
export function classifyConventionError(err, source) {
|
|
155
|
+
if (source !== 'baseline')
|
|
156
|
+
return null;
|
|
157
|
+
if (!(err instanceof Error))
|
|
158
|
+
return null;
|
|
159
|
+
if (!CONVENTION_PREFIX.test(err.message))
|
|
160
|
+
return null;
|
|
161
|
+
return { kind: 'invalid_input', message: err.message };
|
|
162
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** SDK Read tool hard limit — images above this are compression candidates. */
|
|
2
|
+
export declare const READ_LIMIT: number;
|
|
3
|
+
/** Extensions the size-gate treats as images. Single source of truth. */
|
|
4
|
+
export declare const IMAGE_EXTENSIONS: ReadonlySet<string>;
|
|
5
|
+
/** A file converted in place — `from`/`to` are paths relative to the output dir. */
|
|
6
|
+
export interface ConvertedFile {
|
|
7
|
+
readonly from: string;
|
|
8
|
+
readonly to: string;
|
|
9
|
+
}
|
|
10
|
+
/** Minimal logger surface — the executor's ToolLogger satisfies this. */
|
|
11
|
+
interface WarnLogger {
|
|
12
|
+
warn(...args: unknown[]): void;
|
|
13
|
+
}
|
|
14
|
+
/** Detect HEIC/HEIF by ISO-BMFF magic bytes (`ftyp` box at offset 4). */
|
|
15
|
+
export declare function isHeicBuffer(buf: Buffer): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* For each staged file matching the image gate, write a sibling
|
|
18
|
+
* `<base>.converted.jpg` compressed under READ_LIMIT and keep the original.
|
|
19
|
+
*
|
|
20
|
+
* @param outputDir absolute staging dir the relative `files` are rooted at
|
|
21
|
+
* @param files relative POSIX paths already staged (from `listRelativeFiles`)
|
|
22
|
+
* @returns the `{ from, to }` pairs that were converted (empty when none / no codec)
|
|
23
|
+
*/
|
|
24
|
+
export declare function compressLargeImages(outputDir: string, files: readonly string[], logger?: WarnLogger): Promise<ConvertedFile[]>;
|
|
25
|
+
export {};
|
|
26
|
+
//# sourceMappingURL=image-compress.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-compress.d.ts","sourceRoot":"","sources":["../../../src/runtime/executor/image-compress.ts"],"names":[],"mappings":"AAwBA,+EAA+E;AAC/E,eAAO,MAAM,UAAU,QAAa,CAAC;AAErC,yEAAyE;AACzE,eAAO,MAAM,gBAAgB,EAAE,WAAW,CAAC,MAAM,CAW/C,CAAC;AAqBH,oFAAoF;AACpF,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;CACrB;AAED,yEAAyE;AACzE,UAAU,UAAU;IAClB,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;CAChC;AA0CD,yEAAyE;AACzE,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAIjD;AAqDD;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CACvC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,MAAM,CAAC,EAAE,UAAU,GAClB,OAAO,CAAC,aAAa,EAAE,CAAC,CA6D1B"}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Executor-side image auto-conversion. Runs at the file-output choke point
|
|
3
|
+
* (see `executor/index.ts`): after a `producesFiles` handler has staged its
|
|
4
|
+
* files, but before they are tarred and PUT to the presigned URL.
|
|
5
|
+
*
|
|
6
|
+
* Only files with an image extension (see `IMAGE_EXTENSIONS`) are inspected.
|
|
7
|
+
* Among those, a conversion candidate is a large image (> 256KB) or any
|
|
8
|
+
* HEIC/HEIF — detected by extension OR ISO-BMFF `ftyp` magic bytes, so a HEIC
|
|
9
|
+
* mis-extensioned as another image type (e.g. `.png`) is still caught. For each
|
|
10
|
+
* candidate we write a sibling `<base>.converted.jpg` compressed to fit under
|
|
11
|
+
* the SDK Read tool's 256KB limit. The original is always kept; the sibling is
|
|
12
|
+
* additive.
|
|
13
|
+
*
|
|
14
|
+
* `sharp` + `heic-convert` are soft dependencies: the require is guarded and
|
|
15
|
+
* each per-file conversion is guarded, so a missing/incompatible codec or a
|
|
16
|
+
* single bad file logs a warning and falls through, delivering the original
|
|
17
|
+
* unchanged. Conversion never fails a tool call.
|
|
18
|
+
*
|
|
19
|
+
* Algorithm is byte-for-byte the legacy worker behavior
|
|
20
|
+
* (`worker/src/cli/lib/image-convert.js` + the gdrive/files download gate).
|
|
21
|
+
*/
|
|
22
|
+
import fs from 'node:fs/promises';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
/** SDK Read tool hard limit — images above this are compression candidates. */
|
|
25
|
+
export const READ_LIMIT = 256 * 1024;
|
|
26
|
+
/** Extensions the size-gate treats as images. Single source of truth. */
|
|
27
|
+
export const IMAGE_EXTENSIONS = new Set([
|
|
28
|
+
'.heic',
|
|
29
|
+
'.heif',
|
|
30
|
+
'.png',
|
|
31
|
+
'.tiff',
|
|
32
|
+
'.tif',
|
|
33
|
+
'.webp',
|
|
34
|
+
'.bmp',
|
|
35
|
+
'.avif',
|
|
36
|
+
'.jpg',
|
|
37
|
+
'.jpeg',
|
|
38
|
+
]);
|
|
39
|
+
const HEIC_EXTENSIONS = new Set(['.heic', '.heif']);
|
|
40
|
+
const HEIC_BRANDS = new Set([
|
|
41
|
+
'heic',
|
|
42
|
+
'heix',
|
|
43
|
+
'heim',
|
|
44
|
+
'heis',
|
|
45
|
+
'mif1',
|
|
46
|
+
'msf1',
|
|
47
|
+
'hevc',
|
|
48
|
+
'hevx',
|
|
49
|
+
]);
|
|
50
|
+
/** Progressive cascade — stop at the first result that fits under READ_LIMIT. */
|
|
51
|
+
const CASCADE = [
|
|
52
|
+
{ width: 1200, quality: 60 },
|
|
53
|
+
{ width: 800, quality: 40 },
|
|
54
|
+
{ width: 600, quality: 20 },
|
|
55
|
+
];
|
|
56
|
+
let codecsCache;
|
|
57
|
+
/**
|
|
58
|
+
* Resolve sharp (required) and heic-convert (optional) once, guarded.
|
|
59
|
+
* Returns null only when sharp is unavailable — all compression disabled.
|
|
60
|
+
* When heic-convert is missing, heicConvert is null: PNG/JPEG/etc still
|
|
61
|
+
* compress; HEIC files fall through to the per-file catch and deliver originals.
|
|
62
|
+
*/
|
|
63
|
+
async function loadCodecs() {
|
|
64
|
+
if (codecsCache !== undefined)
|
|
65
|
+
return codecsCache;
|
|
66
|
+
try {
|
|
67
|
+
const sharpMod = (await import('sharp'));
|
|
68
|
+
let heicConvert = null;
|
|
69
|
+
try {
|
|
70
|
+
const heicMod = (await import('heic-convert'));
|
|
71
|
+
heicConvert = heicMod.default;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// heic-convert unavailable; HEIC files skip conversion, everything else proceeds
|
|
75
|
+
}
|
|
76
|
+
codecsCache = { sharp: sharpMod.default, heicConvert };
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
codecsCache = null;
|
|
80
|
+
}
|
|
81
|
+
return codecsCache;
|
|
82
|
+
}
|
|
83
|
+
/** Detect HEIC/HEIF by ISO-BMFF magic bytes (`ftyp` box at offset 4). */
|
|
84
|
+
export function isHeicBuffer(buf) {
|
|
85
|
+
if (buf.length < 12)
|
|
86
|
+
return false;
|
|
87
|
+
if (buf.toString('ascii', 4, 8) !== 'ftyp')
|
|
88
|
+
return false;
|
|
89
|
+
return HEIC_BRANDS.has(buf.toString('ascii', 8, 12));
|
|
90
|
+
}
|
|
91
|
+
function isHeic(ext, buf) {
|
|
92
|
+
return HEIC_EXTENSIONS.has(ext) || isHeicBuffer(buf);
|
|
93
|
+
}
|
|
94
|
+
/** True when the file is a conversion candidate per the legacy gate. `header`
|
|
95
|
+
* is the first 12 bytes (enough for the HEIC magic); `size` is the full size. */
|
|
96
|
+
function isCandidate(ext, header, size) {
|
|
97
|
+
if (isHeic(ext, header))
|
|
98
|
+
return true;
|
|
99
|
+
return IMAGE_EXTENSIONS.has(ext) && size > READ_LIMIT;
|
|
100
|
+
}
|
|
101
|
+
/** Read the first `n` bytes of a file without loading the whole thing. */
|
|
102
|
+
async function readHeader(abs, n) {
|
|
103
|
+
const fh = await fs.open(abs, 'r');
|
|
104
|
+
try {
|
|
105
|
+
const out = Buffer.alloc(n);
|
|
106
|
+
const { bytesRead } = await fh.read(out, 0, n, 0);
|
|
107
|
+
return out.subarray(0, bytesRead);
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
await fh.close();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Decode source bytes into a sharp-compatible JPEG/raw buffer. HEIC/HEIF are
|
|
115
|
+
* pre-decoded via heic-convert; everything else is passed through as-is.
|
|
116
|
+
*/
|
|
117
|
+
async function loadSource(codecs, ext, raw) {
|
|
118
|
+
if (isHeic(ext, raw)) {
|
|
119
|
+
if (!codecs.heicConvert)
|
|
120
|
+
throw new Error('heic-convert unavailable');
|
|
121
|
+
return Buffer.from(await codecs.heicConvert({ buffer: raw, format: 'JPEG', quality: 1 }));
|
|
122
|
+
}
|
|
123
|
+
return raw;
|
|
124
|
+
}
|
|
125
|
+
/** Run the progressive cascade, returning the first JPEG buffer ≤ READ_LIMIT (or the smallest tried). */
|
|
126
|
+
async function compressToLimit(codecs, srcBuf) {
|
|
127
|
+
let last;
|
|
128
|
+
for (const step of CASCADE) {
|
|
129
|
+
last = await codecs
|
|
130
|
+
.sharp(srcBuf)
|
|
131
|
+
.rotate()
|
|
132
|
+
.resize({ width: step.width, withoutEnlargement: true })
|
|
133
|
+
.jpeg({ quality: step.quality })
|
|
134
|
+
.toBuffer();
|
|
135
|
+
if (last.length <= READ_LIMIT)
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
// CASCADE is non-empty, so `last` is always assigned.
|
|
139
|
+
return last;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* For each staged file matching the image gate, write a sibling
|
|
143
|
+
* `<base>.converted.jpg` compressed under READ_LIMIT and keep the original.
|
|
144
|
+
*
|
|
145
|
+
* @param outputDir absolute staging dir the relative `files` are rooted at
|
|
146
|
+
* @param files relative POSIX paths already staged (from `listRelativeFiles`)
|
|
147
|
+
* @returns the `{ from, to }` pairs that were converted (empty when none / no codec)
|
|
148
|
+
*/
|
|
149
|
+
export async function compressLargeImages(outputDir, files, logger) {
|
|
150
|
+
const converted = [];
|
|
151
|
+
// Cheap ext pre-filter so a codec-less runtime doesn't pay the import on
|
|
152
|
+
// every file-output call that ships no images.
|
|
153
|
+
const maybeImages = files.filter((rel) => IMAGE_EXTENSIONS.has(path.extname(rel).toLowerCase()));
|
|
154
|
+
if (maybeImages.length === 0)
|
|
155
|
+
return converted;
|
|
156
|
+
const codecs = await loadCodecs();
|
|
157
|
+
if (!codecs) {
|
|
158
|
+
logger?.warn('image-compress: sharp unavailable, delivering originals unchanged');
|
|
159
|
+
return converted;
|
|
160
|
+
}
|
|
161
|
+
for (const rel of maybeImages) {
|
|
162
|
+
try {
|
|
163
|
+
const abs = path.join(outputDir, rel);
|
|
164
|
+
const ext = path.extname(rel).toLowerCase();
|
|
165
|
+
// Cheap candidacy: stat for size + a 12-byte header for the HEIC magic, so
|
|
166
|
+
// small non-HEIC images are ruled out without reading the whole file.
|
|
167
|
+
const { size } = await fs.stat(abs);
|
|
168
|
+
const header = await readHeader(abs, 12);
|
|
169
|
+
if (!isCandidate(ext, header, size))
|
|
170
|
+
continue;
|
|
171
|
+
const dir = path.posix.dirname(rel);
|
|
172
|
+
const base = path.posix.basename(rel, path.posix.extname(rel));
|
|
173
|
+
const toRel = (dir === '.' ? '' : `${dir}/`) + `${base}.converted.jpg`;
|
|
174
|
+
const toAbs = path.join(outputDir, toRel);
|
|
175
|
+
// The handler may already have produced a `.converted.jpg` sibling.
|
|
176
|
+
// Don't clobber it (data loss) or add a duplicate path to the upload.
|
|
177
|
+
try {
|
|
178
|
+
await fs.access(toAbs);
|
|
179
|
+
logger?.warn('image-compress: sibling already exists, skipping', toRel);
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
// No sibling yet — proceed.
|
|
184
|
+
}
|
|
185
|
+
// Candidate confirmed — read the full bytes for decode/compress.
|
|
186
|
+
const raw = await fs.readFile(abs);
|
|
187
|
+
const srcBuf = await loadSource(codecs, ext, raw);
|
|
188
|
+
const outBuf = await compressToLimit(codecs, srcBuf);
|
|
189
|
+
if (outBuf.length > READ_LIMIT) {
|
|
190
|
+
logger?.warn('image-compress: cascade could not reach limit, delivering original unchanged', rel);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
// `wx` fails if a sibling was created between the access check and now.
|
|
194
|
+
await fs.writeFile(toAbs, outBuf, { flag: 'wx' });
|
|
195
|
+
converted.push({ from: rel, to: toRel });
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
logger?.warn('image-compress: conversion failed, delivering original unchanged', rel, err instanceof Error ? err.message : String(err));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return converted;
|
|
202
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { ToolLogger } from '../../types.js';
|
|
2
|
+
import { type ConvertedFile } from './image-compress.js';
|
|
3
|
+
import type { Registry } from '../registry/index.js';
|
|
4
|
+
import type { ExecuteRequestBody } from '../execute-request.js';
|
|
5
|
+
export type ExecuteErrorCode = 'unknown_tool' | 'invalid_input' | 'secret_unknown_key' | 'secret_missing' | 'property_unknown_key' | 'property_missing' | 'write_not_confirmed' | 'output_channel_missing' | 'egress_blocked' | 'spec_error' | 'handler_error' | 'upstream_not_found' | 'upstream_forbidden' | 'upstream_auth_expired' | 'upstream_invalid_input' | 'upstream_conflict' | 'upstream_rate_limited' | 'upstream_unavailable';
|
|
6
|
+
export interface ExecuteSuccess {
|
|
7
|
+
readonly ok: true;
|
|
8
|
+
readonly result: unknown;
|
|
9
|
+
/**
|
|
10
|
+
* Relative paths of files the handler staged via `ctx.writeFile`. Present on
|
|
11
|
+
* every `producesFiles` tool result — an array of the written paths, or `[]`
|
|
12
|
+
* when it wrote nothing; omitted entirely for non-file tools. The bytes are
|
|
13
|
+
* delivered out-of-band: a gzip-tar of the staging dir is PUT to
|
|
14
|
+
* `body.outputPutUrl` and the worker extracts it into AGENT_WORKDIR.
|
|
15
|
+
*/
|
|
16
|
+
readonly outputFiles?: readonly string[];
|
|
17
|
+
/**
|
|
18
|
+
* Image siblings the executor added at the file-output boundary: each
|
|
19
|
+
* `{ from, to }` maps a large/HEIC original to a readable `<base>.converted.jpg`
|
|
20
|
+
* (≤256KB) that was written next to it. Both the original and the sibling are
|
|
21
|
+
* listed in `outputFiles`; this field just points the agent at the readable
|
|
22
|
+
* copy. Omitted when nothing was converted.
|
|
23
|
+
*/
|
|
24
|
+
readonly converted?: readonly ConvertedFile[];
|
|
25
|
+
}
|
|
26
|
+
export interface ExecuteFailure {
|
|
27
|
+
readonly ok: false;
|
|
28
|
+
readonly error: {
|
|
29
|
+
readonly code: ExecuteErrorCode;
|
|
30
|
+
readonly message: string;
|
|
31
|
+
readonly meta?: Record<string, unknown>;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export type ExecuteResult = ExecuteSuccess | ExecuteFailure;
|
|
35
|
+
export interface ExecuteParams {
|
|
36
|
+
readonly registry: Registry;
|
|
37
|
+
readonly body: ExecuteRequestBody;
|
|
38
|
+
readonly logger: ToolLogger;
|
|
39
|
+
readonly signal: AbortSignal;
|
|
40
|
+
readonly workdir: string;
|
|
41
|
+
readonly tenantId?: string;
|
|
42
|
+
}
|
|
43
|
+
export declare function executeTool(params: ExecuteParams): Promise<ExecuteResult>;
|
|
44
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/runtime/executor/index.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAqC,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAKpF,OAAO,EAAuB,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAE9E,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAUhE,MAAM,MAAM,gBAAgB,GACxB,cAAc,GACd,eAAe,GACf,oBAAoB,GACpB,gBAAgB,GAChB,sBAAsB,GACtB,kBAAkB,GAClB,qBAAqB,GACrB,wBAAwB,GACxB,gBAAgB,GAChB,YAAY,GACZ,eAAe,GAEf,oBAAoB,GACpB,oBAAoB,GACpB,uBAAuB,GACvB,wBAAwB,GACxB,mBAAmB,GACnB,uBAAuB,GACvB,sBAAsB,CAAC;AAE3B,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAClB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB;;;;;;OAMG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC;;;;;;OAMG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,aAAa,EAAE,CAAC;CAC/C;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IACnB,QAAQ,CAAC,KAAK,EAAE;QACd,QAAQ,CAAC,IAAI,EAAE,gBAAgB,CAAC;QAChC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACzC,CAAC;CACH;AAED,MAAM,MAAM,aAAa,GAAG,cAAc,GAAG,cAAc,CAAC;AAE5D,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAClC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,wBAAsB,WAAW,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CA+P/E"}
|