@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
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool execution path: given a validated request envelope and the
|
|
3
|
+
* in-memory registry, look up the tool, validate input + secrets
|
|
4
|
+
* against the tool's declared shape, build a sandboxed `ToolCtx` via
|
|
5
|
+
* the SDK, invoke the handler, and return either a result or a
|
|
6
|
+
* structured error envelope.
|
|
7
|
+
*
|
|
8
|
+
* Error mapping is keyed on what the agent needs to know (was my call
|
|
9
|
+
* malformed? was my secret missing? was a write blocked by approval?)
|
|
10
|
+
* rather than which line of code threw. The route layer maps each
|
|
11
|
+
* `ExecuteResult.error.code` to an HTTP status.
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs/promises';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { createRequire } from 'node:module';
|
|
17
|
+
import { buildCtx } from '../../ctx/build-ctx.js';
|
|
18
|
+
import { AkaiError, AkaiEgressError, AkaiPropertyError, AkaiSecretError, AkaiSpecError } from '../../errors.js';
|
|
19
|
+
import { DYNAMIC_EGRESS_PREFIXES } from '../../tool.js';
|
|
20
|
+
import { create as tarCreate } from 'tar';
|
|
21
|
+
import { z } from 'zod';
|
|
22
|
+
import { classifyConventionError, classifyError, classifyTypedThrow } from './classify-error.js';
|
|
23
|
+
import { compressLargeImages } from './image-compress.js';
|
|
24
|
+
import { redactSecrets } from './redact.js';
|
|
25
|
+
// Surfaces in the safe-fetch user-agent. Sourced from the SDK's own
|
|
26
|
+
// package.json (resolved relative to this module) so it can't drift from the
|
|
27
|
+
// published version. `../../../package.json` resolves the same from both
|
|
28
|
+
// src/runtime/executor/ (tests) and dist/runtime/executor/ (runtime).
|
|
29
|
+
const { version: SDK_VERSION } = createRequire(import.meta.url)('../../../package.json');
|
|
30
|
+
export async function executeTool(params) {
|
|
31
|
+
const { registry, body, logger, signal, workdir, tenantId } = params;
|
|
32
|
+
const lookup = registry.lookupTool(body.cli, body.tool);
|
|
33
|
+
if (!lookup) {
|
|
34
|
+
return failure('unknown_tool', `no tool '${body.cli}.${body.tool}' in registry`, {
|
|
35
|
+
cli: body.cli,
|
|
36
|
+
tool: body.tool,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
// The registry's BrandedCLI is structurally compatible with the SDK's
|
|
40
|
+
// CLIDef — same fields, same `__akaiCLI` brand. We only cast at the
|
|
41
|
+
// boundary to the SDK call. `tool.input` is treated as a ZodType here
|
|
42
|
+
// because `defineCLI`'s spec validator guarantees it.
|
|
43
|
+
const cli = lookup.cli;
|
|
44
|
+
const tool = lookup.tool;
|
|
45
|
+
// Step 1: parse input against the tool's declared schema. A failure
|
|
46
|
+
// here is the agent's fault — bad call — and surfaces with full zod
|
|
47
|
+
// issues so the agent can retry with the right shape.
|
|
48
|
+
let parsedInput;
|
|
49
|
+
try {
|
|
50
|
+
const inputSchema = tool.input;
|
|
51
|
+
if (isZodSchema(inputSchema)) {
|
|
52
|
+
parsedInput = inputSchema.parse(body.input);
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
// The registry's brand check doesn't introspect `tool.input` —
|
|
56
|
+
// treat a non-zod input as "no schema declared" and pass through.
|
|
57
|
+
// In practice every SDK-authored tool has a zod input; this branch
|
|
58
|
+
// is for resilience against hand-rolled fixtures.
|
|
59
|
+
parsedInput = body.input;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
catch (err) {
|
|
63
|
+
if (err instanceof z.ZodError) {
|
|
64
|
+
return failure('invalid_input', summariseZodError(err), { issues: err.issues });
|
|
65
|
+
}
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
// Step 2: per-request secret-shape check. Extras (keys NOT declared by
|
|
69
|
+
// the tool) are rejected here — they signal stale schema or a typo.
|
|
70
|
+
// Missing-required is enforced downstream by buildScopedSecrets.
|
|
71
|
+
const declared = new Set(tool.options.secretKeys);
|
|
72
|
+
for (const key of Object.keys(body.secrets)) {
|
|
73
|
+
if (!declared.has(key)) {
|
|
74
|
+
return failure('secret_unknown_key', `secret '${key}' is not declared by tool '${body.cli}.${body.tool}'`, {
|
|
75
|
+
key,
|
|
76
|
+
declared: Array.from(declared),
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
// Same shape check for properties: a key the tool doesn't declare signals a
|
|
81
|
+
// stale schema or typo. buildScopedProperties enforces missing-required.
|
|
82
|
+
const declaredProperties = new Set(tool.options.propertyKeys ?? []);
|
|
83
|
+
for (const key of Object.keys(body.properties)) {
|
|
84
|
+
if (!declaredProperties.has(key)) {
|
|
85
|
+
return failure('property_unknown_key', `property '${key}' is not declared by tool '${body.cli}.${body.tool}'`, {
|
|
86
|
+
key,
|
|
87
|
+
declared: Array.from(declaredProperties),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
// Step 3: readonly gate. Non-readonly tools require explicit
|
|
92
|
+
// confirmedWrite — the worker sets it only after akai-app's
|
|
93
|
+
// pre-approval flow returns approved.
|
|
94
|
+
if (!tool.options.isReadonly && body.confirmedWrite !== true) {
|
|
95
|
+
return failure('write_not_confirmed', `tool '${body.cli}.${body.tool}' is a write but the request lacks confirmedWrite: true`, { cli: body.cli, tool: body.tool, isReadonly: false });
|
|
96
|
+
}
|
|
97
|
+
// Step 4: a producesFiles tool needs an outputPutUrl — reject early so
|
|
98
|
+
// written files are never silently dropped.
|
|
99
|
+
const producesFiles = tool.options.producesFiles === true;
|
|
100
|
+
if (producesFiles && body.outputPutUrl === undefined) {
|
|
101
|
+
return failure('output_channel_missing', `tool '${body.cli}.${body.tool}' produces files but the request lacks outputPutUrl`, { cli: body.cli, tool: body.tool, producesFiles: true });
|
|
102
|
+
}
|
|
103
|
+
// Step 4b: resolve dynamic egress (`property:KEY` | `secret:KEY`) to a static
|
|
104
|
+
// host list before ctx is built — the SDK's buildCtx hard-throws on the
|
|
105
|
+
// dynamic object form (it delegates resolution to the host runtime). A
|
|
106
|
+
// static/native tool is left untouched; only `{ from: '<prefix>:KEY' }` is
|
|
107
|
+
// resolved.
|
|
108
|
+
const resolved = resolveEgress(cli, body.tool, body);
|
|
109
|
+
if (!resolved.ok) {
|
|
110
|
+
return resolved;
|
|
111
|
+
}
|
|
112
|
+
const resolvedCli = resolved.cli;
|
|
113
|
+
// Created inside the try so a mkdtemp failure returns a structured error.
|
|
114
|
+
let outputDir;
|
|
115
|
+
try {
|
|
116
|
+
if (producesFiles) {
|
|
117
|
+
outputDir = await fs.mkdtemp(path.join(os.tmpdir(), 'akai-out-'));
|
|
118
|
+
}
|
|
119
|
+
// Step 5: build the SDK ctx. `buildScopedSecrets` (inside buildCtx)
|
|
120
|
+
// throws `AkaiSecretError` on required-but-empty — translate to
|
|
121
|
+
// `secret_missing`.
|
|
122
|
+
let ctx;
|
|
123
|
+
try {
|
|
124
|
+
ctx = buildCtx({
|
|
125
|
+
cli: resolvedCli,
|
|
126
|
+
toolName: body.tool,
|
|
127
|
+
secretValues: body.secrets,
|
|
128
|
+
propertyValues: body.properties,
|
|
129
|
+
logger,
|
|
130
|
+
signal,
|
|
131
|
+
workdir,
|
|
132
|
+
sdkVersion: SDK_VERSION,
|
|
133
|
+
...(tenantId !== undefined ? { tenantId } : {}),
|
|
134
|
+
...(outputDir !== undefined ? { outputDir } : {}),
|
|
135
|
+
...(body.oauthAccessToken !== undefined ? { oauthAccessToken: body.oauthAccessToken } : {}),
|
|
136
|
+
...(body.appTokenAccessToken !== undefined ? { appTokenAccessToken: body.appTokenAccessToken } : {}),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
catch (err) {
|
|
140
|
+
if (err instanceof AkaiSecretError) {
|
|
141
|
+
return failure('secret_missing', err.message, err.meta);
|
|
142
|
+
}
|
|
143
|
+
// Required-but-unset connection property (e.g. SAP_BASE_URL) — surface the
|
|
144
|
+
// clear message instead of letting it fall through to a generic 500.
|
|
145
|
+
if (err instanceof AkaiPropertyError) {
|
|
146
|
+
return failure('property_missing', err.message, err.meta);
|
|
147
|
+
}
|
|
148
|
+
if (err instanceof AkaiSpecError) {
|
|
149
|
+
return failure('spec_error', err.message, err.meta);
|
|
150
|
+
}
|
|
151
|
+
throw err;
|
|
152
|
+
}
|
|
153
|
+
// Step 6: invoke the handler. SDK-typed errors map cleanly; anything
|
|
154
|
+
// else becomes `handler_error` so the response is always structured.
|
|
155
|
+
let result;
|
|
156
|
+
try {
|
|
157
|
+
result = await tool.handler({ input: parsedInput, ctx, isJson: body.isJson });
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
if (err instanceof AkaiEgressError) {
|
|
161
|
+
return failure('egress_blocked', err.message, err.meta);
|
|
162
|
+
}
|
|
163
|
+
if (err instanceof AkaiSecretError) {
|
|
164
|
+
return failure('secret_missing', err.message, err.meta);
|
|
165
|
+
}
|
|
166
|
+
// Branded typed throw → vetted wording verbatim; else a status-derived
|
|
167
|
+
// classification. Neither echoes raw untrusted text.
|
|
168
|
+
const classified = classifyTypedThrow(err) ?? classifyError(err);
|
|
169
|
+
if (classified) {
|
|
170
|
+
return failure(`upstream_${classified.kind}`, classified.message, classified.meta);
|
|
171
|
+
}
|
|
172
|
+
// Baseline tool's `Error ...` message → surface verbatim as 422, matching
|
|
173
|
+
// what legacy printed on stderr (customer tools stay generic).
|
|
174
|
+
const convention = classifyConventionError(err, lookup.source);
|
|
175
|
+
if (convention) {
|
|
176
|
+
return failure('invalid_input', convention.message);
|
|
177
|
+
}
|
|
178
|
+
// A baseline tool's `AkaiError` is a deliberate, audited, secret-free
|
|
179
|
+
// failure message (the secret-bearing subclasses — AkaiSecretError /
|
|
180
|
+
// AkaiEgressError — are caught above, and AkaiToolError was handled by
|
|
181
|
+
// classifyTypedThrow). Surface it verbatim so the agent sees the real
|
|
182
|
+
// reason (e.g. NetSuite's SuiteQL parse error) instead of an opaque
|
|
183
|
+
// generic message.
|
|
184
|
+
//
|
|
185
|
+
// `instanceof` alone is brittle: a baseline package dynamic-imported with
|
|
186
|
+
// its own copy of the SDK throws an AkaiError that fails `instanceof`
|
|
187
|
+
// against our copy (the same package-boundary gap classifyTypedThrow
|
|
188
|
+
// sidesteps). Fall back to an EXACT name match — base `AkaiError` only, so
|
|
189
|
+
// the secret-bearing subclasses (distinct names, already handled above)
|
|
190
|
+
// can't slip through even across SDK copies.
|
|
191
|
+
const isBaselineAkaiError = err instanceof AkaiError ||
|
|
192
|
+
(err != null && typeof err === 'object' && err.name === 'AkaiError');
|
|
193
|
+
if (lookup.source === 'baseline' && isBaselineAkaiError) {
|
|
194
|
+
// The name-match fallback can hit an arbitrary object, so don't trust
|
|
195
|
+
// its shape: only surface when message is actually a string, and only
|
|
196
|
+
// forward meta when it's an object. Otherwise fall through to generic.
|
|
197
|
+
const e = err;
|
|
198
|
+
if (typeof e.message === 'string') {
|
|
199
|
+
const meta = e.meta != null && typeof e.meta === 'object' ? e.meta : undefined;
|
|
200
|
+
return failure('invalid_input', e.message, meta);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
logger.error('tool handler threw', body.cli, body.tool, err instanceof Error ? err.stack ?? err.message : String(err));
|
|
204
|
+
const handlerMessage = err instanceof Error ? err.message : '';
|
|
205
|
+
if (handlerMessage) {
|
|
206
|
+
const injectedCredentials = [
|
|
207
|
+
...Object.values(body.secrets),
|
|
208
|
+
body.oauthAccessToken,
|
|
209
|
+
body.appTokenAccessToken,
|
|
210
|
+
].filter((value) => typeof value === 'string');
|
|
211
|
+
const messageWithoutSecrets = redactSecrets(handlerMessage, injectedCredentials);
|
|
212
|
+
if (messageWithoutSecrets) {
|
|
213
|
+
return failure('handler_error', messageWithoutSecrets);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return failure('handler_error', 'tool handler failed');
|
|
217
|
+
}
|
|
218
|
+
// Step 7: deliver staged output files (non-file tools fall through).
|
|
219
|
+
if (!producesFiles || outputDir === undefined) {
|
|
220
|
+
return { ok: true, result };
|
|
221
|
+
}
|
|
222
|
+
const files = await listRelativeFiles(outputDir);
|
|
223
|
+
if (files.length === 0) {
|
|
224
|
+
return { ok: true, result, outputFiles: [] };
|
|
225
|
+
}
|
|
226
|
+
// Add-sibling image pass: large/HEIC images get a readable `.converted.jpg`
|
|
227
|
+
// next to them. Soft-guarded inside compressLargeImages — a missing codec or
|
|
228
|
+
// a per-file failure logs and falls through, so this never fails the call.
|
|
229
|
+
const converted = await compressLargeImages(outputDir, files, logger);
|
|
230
|
+
const all = converted.length > 0 ? [...files, ...converted.map((c) => c.to)].sort() : files;
|
|
231
|
+
// gzip-tar the staging dir and PUT to the presigned URL.
|
|
232
|
+
const tarBuffer = await tarToBuffer(outputDir, all);
|
|
233
|
+
const putRes = await fetch(body.outputPutUrl, { method: 'PUT', body: tarBuffer, signal });
|
|
234
|
+
if (!putRes.ok) {
|
|
235
|
+
return failure('handler_error', `failed to upload output files (PUT ${putRes.status})`, { status: putRes.status });
|
|
236
|
+
}
|
|
237
|
+
return converted.length > 0
|
|
238
|
+
? { ok: true, result, outputFiles: all, converted }
|
|
239
|
+
: { ok: true, result, outputFiles: all };
|
|
240
|
+
}
|
|
241
|
+
catch (err) {
|
|
242
|
+
// Structured error for mkdtemp/tar/PUT throws instead of an unhandled 500.
|
|
243
|
+
logger.error('output channel failed', body.cli, body.tool, err instanceof Error ? err.stack ?? err.message : String(err));
|
|
244
|
+
return failure('handler_error', 'failed to deliver output files');
|
|
245
|
+
}
|
|
246
|
+
finally {
|
|
247
|
+
if (outputDir !== undefined) {
|
|
248
|
+
await fs.rm(outputDir, { recursive: true, force: true }).catch(() => { });
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Resolve a tool's dynamic `{ from: 'property:KEY' }` | `{ from: 'secret:KEY' }`
|
|
254
|
+
* egress to a static host list before `buildCtx` runs — the SDK's
|
|
255
|
+
* `staticEgress` hard-throws on the dynamic object form and delegates
|
|
256
|
+
* resolution to the host runtime (us).
|
|
257
|
+
*
|
|
258
|
+
* - Static (`Array.isArray`) or native (`network === undefined`) egress is a
|
|
259
|
+
* no-op: the original `cli` is returned untouched.
|
|
260
|
+
* - For the dynamic form we read the bound value from the matching source —
|
|
261
|
+
* `property:KEY` from `body.properties`, `secret:KEY` from `body.secrets` —
|
|
262
|
+
* extract its URL hostname (no port — `createSafeFetch` matches on hostname
|
|
263
|
+
* only), and return a shallow clone of the CLI/tool/options with the egress
|
|
264
|
+
* narrowed to exactly that one host. The registry def is shared across
|
|
265
|
+
* requests, so we clone rather than mutate — concurrent calls with different
|
|
266
|
+
* tenant URLs each resolve their own host.
|
|
267
|
+
* - Egress is never widened: an unset/empty value fails closed
|
|
268
|
+
* (`property_missing` / `secret_missing`), a malformed prefix `spec_error`,
|
|
269
|
+
* never open-all.
|
|
270
|
+
*/
|
|
271
|
+
function resolveEgress(cli, toolName, body) {
|
|
272
|
+
const tool = cli.tools[toolName];
|
|
273
|
+
const egress = tool?.options.network?.egress;
|
|
274
|
+
// Static list or native (no network) — leave the CLI untouched. A missing
|
|
275
|
+
// tool also lands here (egress undefined) and is handled by the caller's
|
|
276
|
+
// own lookup; resolution is a strict no-op in that case.
|
|
277
|
+
if (tool === undefined || egress === undefined || Array.isArray(egress)) {
|
|
278
|
+
return { ok: true, cli };
|
|
279
|
+
}
|
|
280
|
+
// `Array.isArray` does not narrow a `readonly string[]` union member, so the
|
|
281
|
+
// remaining shape is asserted here — the guard above already excluded the
|
|
282
|
+
// array and undefined cases.
|
|
283
|
+
const dynamic = egress;
|
|
284
|
+
const from = dynamic.from;
|
|
285
|
+
// Match against the SDK's prefix set and dispatch to the right value source.
|
|
286
|
+
// Strip the matched prefix by LENGTH — do NOT split on ':' — the value is a
|
|
287
|
+
// URL whose host:port also contains colons.
|
|
288
|
+
const prefix = DYNAMIC_EGRESS_PREFIXES.find((p) => from.startsWith(p) && from.length > p.length);
|
|
289
|
+
if (prefix === undefined) {
|
|
290
|
+
return failure('spec_error', `tool '${body.cli}.${toolName}' has unsupported dynamic egress '${from}'`);
|
|
291
|
+
}
|
|
292
|
+
const key = from.slice(prefix.length);
|
|
293
|
+
const isSecret = prefix === 'secret:';
|
|
294
|
+
const raw = (isSecret ? body.secrets[key] : body.properties[key])?.trim();
|
|
295
|
+
if (raw === undefined || raw === '') {
|
|
296
|
+
return isSecret
|
|
297
|
+
? failure('secret_missing', `tool '${body.cli}.${toolName}' egress is bound to secret '${key}' but it is unset; set the '${key}' secret on the connection`, { key })
|
|
298
|
+
: failure('property_missing', `tool '${body.cli}.${toolName}' egress is bound to property '${key}' but it is unset; set the connection's base URL`, { key });
|
|
299
|
+
}
|
|
300
|
+
// Bare host[:port] fallback for secrets like sunfish's SUNFISH_HOST; "host:port" alone parses as a bogus scheme with empty hostname, not a throw.
|
|
301
|
+
let host;
|
|
302
|
+
try {
|
|
303
|
+
host = new URL(raw).hostname;
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
host = '';
|
|
307
|
+
}
|
|
308
|
+
if (host === '') {
|
|
309
|
+
let fallback;
|
|
310
|
+
try {
|
|
311
|
+
fallback = new URL(`https://${raw}`);
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
return notAbsoluteUrl(isSecret, key);
|
|
315
|
+
}
|
|
316
|
+
const isBareHost = fallback.username === '' && fallback.password === '' &&
|
|
317
|
+
fallback.pathname === '/' && fallback.search === '' && fallback.hash === '';
|
|
318
|
+
if (!isBareHost || fallback.hostname === '') {
|
|
319
|
+
return notAbsoluteUrl(isSecret, key);
|
|
320
|
+
}
|
|
321
|
+
host = fallback.hostname;
|
|
322
|
+
}
|
|
323
|
+
// Shallow-clone the shared registry def down to the egress array, narrowing
|
|
324
|
+
// it to exactly the one resolved host. Preserve any other `network` settings
|
|
325
|
+
// and override only `egress` so future SDK network fields are not dropped.
|
|
326
|
+
const resolvedTool = {
|
|
327
|
+
...tool,
|
|
328
|
+
options: {
|
|
329
|
+
...tool.options,
|
|
330
|
+
network: { ...tool.options.network, egress: [host] },
|
|
331
|
+
},
|
|
332
|
+
};
|
|
333
|
+
const resolvedCli = {
|
|
334
|
+
...cli,
|
|
335
|
+
tools: { ...cli.tools, [toolName]: resolvedTool },
|
|
336
|
+
};
|
|
337
|
+
return { ok: true, cli: resolvedCli };
|
|
338
|
+
}
|
|
339
|
+
/** A dynamic-egress value that's neither an absolute URL nor a bare hostname
|
|
340
|
+
* — fail closed with the source-accurate code/message (secret vs property). */
|
|
341
|
+
function notAbsoluteUrl(isSecret, key) {
|
|
342
|
+
return isSecret
|
|
343
|
+
? failure('secret_missing', `secret '${key}' must be a hostname or absolute URL`, { key })
|
|
344
|
+
: failure('property_missing', `property '${key}' must be a hostname or absolute URL`, { key });
|
|
345
|
+
}
|
|
346
|
+
/** Recursively list files under `dir` as POSIX paths relative to it. */
|
|
347
|
+
async function listRelativeFiles(dir) {
|
|
348
|
+
const out = [];
|
|
349
|
+
async function walk(current) {
|
|
350
|
+
const dirents = await fs.readdir(current, { withFileTypes: true });
|
|
351
|
+
for (const d of dirents) {
|
|
352
|
+
const abs = path.join(current, d.name);
|
|
353
|
+
if (d.isDirectory()) {
|
|
354
|
+
await walk(abs);
|
|
355
|
+
}
|
|
356
|
+
else if (d.isFile()) {
|
|
357
|
+
out.push(path.relative(dir, abs).split(path.sep).join('/'));
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
await walk(dir);
|
|
362
|
+
out.sort();
|
|
363
|
+
return out;
|
|
364
|
+
}
|
|
365
|
+
/** gzip-tar the given relative files rooted at `cwd` into one Buffer. */
|
|
366
|
+
async function tarToBuffer(cwd, files) {
|
|
367
|
+
const chunks = [];
|
|
368
|
+
const stream = tarCreate({ gzip: true, cwd, portable: true }, [...files]);
|
|
369
|
+
for await (const chunk of stream) {
|
|
370
|
+
// tar yields Buffers already — only convert when it isn't one, to avoid
|
|
371
|
+
// doubling memory bandwidth on large outputs (Buffer.concat copies at the end).
|
|
372
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
373
|
+
}
|
|
374
|
+
return Buffer.concat(chunks);
|
|
375
|
+
}
|
|
376
|
+
function failure(code, message, meta) {
|
|
377
|
+
return { ok: false, error: meta !== undefined ? { code, message, meta } : { code, message } };
|
|
378
|
+
}
|
|
379
|
+
function isZodSchema(x) {
|
|
380
|
+
if (x === null || typeof x !== 'object')
|
|
381
|
+
return false;
|
|
382
|
+
// zod v4 schemas: `parse` is the canonical runtime entry; `_def` is
|
|
383
|
+
// their structural marker.
|
|
384
|
+
const o = x;
|
|
385
|
+
return typeof o.parse === 'function' && '_def' in o;
|
|
386
|
+
}
|
|
387
|
+
function summariseZodError(err) {
|
|
388
|
+
const first = err.issues[0];
|
|
389
|
+
if (!first)
|
|
390
|
+
return 'input validation failed';
|
|
391
|
+
const path = first.path.length > 0 ? first.path.join('.') : '(root)';
|
|
392
|
+
return `input.${path}: ${first.message}`;
|
|
393
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Return a handler error message safe to forward to the agent: every injected
|
|
3
|
+
* credential value replaced with `***`, stack lines dropped (first line only),
|
|
4
|
+
* and length-capped. Values shorter than four characters are left alone to
|
|
5
|
+
* avoid replacing common substrings. Returns an empty string for a blank
|
|
6
|
+
* message so the caller can fall back to a generic error.
|
|
7
|
+
*/
|
|
8
|
+
export declare function redactSecrets(message: string, injectedCredentials: readonly string[]): string;
|
|
9
|
+
//# sourceMappingURL=redact.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redact.d.ts","sourceRoot":"","sources":["../../../src/runtime/executor/redact.ts"],"names":[],"mappings":"AAIA;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,mBAAmB,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAgB7F"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const MAX_MESSAGE_LENGTH = 500;
|
|
2
|
+
const MIN_REDACTABLE_LENGTH = 4;
|
|
3
|
+
const REDACTION_MARKER = '***';
|
|
4
|
+
/**
|
|
5
|
+
* Return a handler error message safe to forward to the agent: every injected
|
|
6
|
+
* credential value replaced with `***`, stack lines dropped (first line only),
|
|
7
|
+
* and length-capped. Values shorter than four characters are left alone to
|
|
8
|
+
* avoid replacing common substrings. Returns an empty string for a blank
|
|
9
|
+
* message so the caller can fall back to a generic error.
|
|
10
|
+
*/
|
|
11
|
+
export function redactSecrets(message, injectedCredentials) {
|
|
12
|
+
let redacted = (message.split('\n')[0] ?? '').trim();
|
|
13
|
+
const orderedCredentials = [...new Set(injectedCredentials)]
|
|
14
|
+
.filter((credential) => credential.length >= MIN_REDACTABLE_LENGTH)
|
|
15
|
+
.sort((a, b) => b.length - a.length);
|
|
16
|
+
for (const credential of orderedCredentials) {
|
|
17
|
+
redacted = redacted.split(credential).join(REDACTION_MARKER);
|
|
18
|
+
}
|
|
19
|
+
if (redacted.length > MAX_MESSAGE_LENGTH) {
|
|
20
|
+
redacted = `${redacted.slice(0, MAX_MESSAGE_LENGTH)}…`;
|
|
21
|
+
}
|
|
22
|
+
return redacted;
|
|
23
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-runtime surface: execute an sdk tool (`executeTool`) and load a package
|
|
3
|
+
* registry (`Registry`). Consumed by the two hosts — akai-cli-service (`remote`)
|
|
4
|
+
* and the worker (`in-process`). Kept as a SEPARATE entry point from the
|
|
5
|
+
* authoring root (`.`, `defineCLI`/`defineConnection`) so tool authors' import
|
|
6
|
+
* and dependency surface is unchanged by the runtime living here.
|
|
7
|
+
*
|
|
8
|
+
* Import as: `import { executeTool, Registry } from '@akai-workflow-builder/cli-sdk/runtime'`.
|
|
9
|
+
*/
|
|
10
|
+
export * from './executor/index.js';
|
|
11
|
+
export type { ConvertedFile } from './executor/image-compress.js';
|
|
12
|
+
export * from './registry/index.js';
|
|
13
|
+
export { toWireListPayload } from './registry/wire.js';
|
|
14
|
+
export * from './execute-request.js';
|
|
15
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,cAAc,qBAAqB,CAAC;AACpC,YAAY,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAClE,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,cAAc,sBAAsB,CAAC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-runtime surface: execute an sdk tool (`executeTool`) and load a package
|
|
3
|
+
* registry (`Registry`). Consumed by the two hosts — akai-cli-service (`remote`)
|
|
4
|
+
* and the worker (`in-process`). Kept as a SEPARATE entry point from the
|
|
5
|
+
* authoring root (`.`, `defineCLI`/`defineConnection`) so tool authors' import
|
|
6
|
+
* and dependency surface is unchanged by the runtime living here.
|
|
7
|
+
*
|
|
8
|
+
* Import as: `import { executeTool, Registry } from '@akai-workflow-builder/cli-sdk/runtime'`.
|
|
9
|
+
*/
|
|
10
|
+
export * from './executor/index.js';
|
|
11
|
+
export * from './registry/index.js';
|
|
12
|
+
export { toWireListPayload } from './registry/wire.js';
|
|
13
|
+
export * from './execute-request.js';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { Registry } from './loader.js';
|
|
2
|
+
export type { LoadRegistryOptions } from './loader.js';
|
|
3
|
+
export type { BrandedCLI, BrandedConnection, BrandedConnectionOAuth, BrandedOAuthAdminField, BrandedTool, BrandedToolOptions, BrandedSecretDecl, ConnectionAuthKind, ConnectionEntry, ConnectionRefreshStrategy, ConnectionTokenEndpointAuthMethod, RegistryEntry, RegistrySource, RegistryStats, ToolLookup, } from './types.js';
|
|
4
|
+
export type { WireConnectionEntry, WireConnectionOAuth, WireTenant, } from './wire.js';
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/runtime/registry/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,YAAY,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AACvD,YAAY,EACV,UAAU,EACV,iBAAiB,EACjB,sBAAsB,EACtB,sBAAsB,EACtB,WAAW,EACX,kBAAkB,EAClB,iBAAiB,EACjB,kBAAkB,EAClB,eAAe,EACf,yBAAyB,EACzB,iCAAiC,EACjC,aAAa,EACb,cAAc,EACd,aAAa,EACb,UAAU,GACX,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,mBAAmB,EACnB,mBAAmB,EACnB,UAAU,GACX,MAAM,WAAW,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Registry } from './loader.js';
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { ConnectionEntry, LoadFailure, RegistryEntry, RegistryStats, ToolLookup } from './types.js';
|
|
2
|
+
import type { ToolLogger } from '../../types.js';
|
|
3
|
+
export interface LoadRegistryOptions {
|
|
4
|
+
/** Absolute path to the baseline packages root (e.g. `/app/tools/packages`). */
|
|
5
|
+
readonly baselinePath?: string;
|
|
6
|
+
/** Optional absolute path to the customer packages root. */
|
|
7
|
+
readonly customerPath?: string;
|
|
8
|
+
readonly logger?: ToolLogger;
|
|
9
|
+
/**
|
|
10
|
+
* How to treat a duplicate CLI id / connection slug.
|
|
11
|
+
*
|
|
12
|
+
* `false` (default, PRODUCTION): resilient. The first definition wins (baseline
|
|
13
|
+
* is scanned before customer, so baseline always wins), and the colliding
|
|
14
|
+
* later definition is skipped, logged loudly, and recorded as a `LoadFailure`.
|
|
15
|
+
* A duplicate is a bad *connection*, never a reason to fail-closed and take
|
|
16
|
+
* every tenant's tools down — the lesson from the employee-navigator/kota
|
|
17
|
+
* cross-repo outages.
|
|
18
|
+
*
|
|
19
|
+
* `true` (CI / authoring): strict. An ACCIDENTAL duplicate throws, so a
|
|
20
|
+
* collision fails a PR pre-merge where it's cheap to fix, instead of only
|
|
21
|
+
* being logged at runtime. An explicit customer override (see
|
|
22
|
+
* `resolveCollision`) is intentional, not accidental — it is honored and
|
|
23
|
+
* recorded, never thrown, even in strict mode. Used by the bundle-import gate
|
|
24
|
+
* and the baseline self-check.
|
|
25
|
+
*/
|
|
26
|
+
readonly strict?: boolean;
|
|
27
|
+
}
|
|
28
|
+
export declare class Registry {
|
|
29
|
+
private readonly byCliId;
|
|
30
|
+
private readonly byConnectionSlug;
|
|
31
|
+
private readonly loadFailures;
|
|
32
|
+
private constructor();
|
|
33
|
+
static load(opts: LoadRegistryOptions): Promise<Registry>;
|
|
34
|
+
lookupTool(cliId: string, toolKey: string): ToolLookup | undefined;
|
|
35
|
+
entries(): ReadonlyArray<RegistryEntry>;
|
|
36
|
+
connections(): ReadonlyArray<ConnectionEntry>;
|
|
37
|
+
/** Packages skipped at load: failed brand/shape check, or the dropped side of
|
|
38
|
+
* a duplicate id/slug collision. */
|
|
39
|
+
failures(): ReadonlyArray<LoadFailure>;
|
|
40
|
+
stats(): RegistryStats;
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=loader.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../../src/runtime/registry/loader.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAMV,eAAe,EACf,WAAW,EACX,aAAa,EAEb,aAAa,EACb,UAAU,EACX,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAcjD,MAAM,WAAW,mBAAmB;IAClC,gFAAgF;IAChF,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,4DAA4D;IAC5D,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC;IAC7B;;;;;;;;;;;;;;;;OAgBG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,qBAAa,QAAQ;IAGnB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA6B;IAGrD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAA+B;IAKhE,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA6B;IAE1D,OAAO;WAYM,IAAI,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAyH/D,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS;IAQlE,OAAO,IAAI,aAAa,CAAC,aAAa,CAAC;IAIvC,WAAW,IAAI,aAAa,CAAC,eAAe,CAAC;IAI7C;wCACoC;IACpC,QAAQ,IAAI,aAAa,CAAC,WAAW,CAAC;IAItC,KAAK,IAAI,aAAa;CA2BvB"}
|