@agent-native/actions 0.0.0-stage → 0.1.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/README.md +41 -2
- package/dist/chunk-4X4LYULO.js +108 -0
- package/dist/chunk-4X4LYULO.js.map +1 -0
- package/dist/chunk-D66CG6AI.js +265 -0
- package/dist/chunk-D66CG6AI.js.map +1 -0
- package/dist/chunk-KWA4U6DI.js +273 -0
- package/dist/chunk-KWA4U6DI.js.map +1 -0
- package/dist/chunk-SXOEFWAM.js +147 -0
- package/dist/chunk-SXOEFWAM.js.map +1 -0
- package/dist/cli.js +1765 -0
- package/dist/cli.js.map +1 -0
- package/dist/client-C87WZhlZ.d.ts +223 -0
- package/dist/client.d.ts +70 -0
- package/dist/client.js +110 -0
- package/dist/client.js.map +1 -0
- package/dist/contract.d.ts +251 -0
- package/dist/contract.js +372 -0
- package/dist/contract.js.map +1 -0
- package/dist/index.d.ts +251 -0
- package/dist/index.js +704 -0
- package/dist/index.js.map +1 -0
- package/dist/next-config.d.ts +16 -0
- package/dist/next-config.js +46 -0
- package/dist/next-config.js.map +1 -0
- package/dist/next-pages.d.ts +12 -0
- package/dist/next-pages.js +13 -0
- package/dist/next-pages.js.map +1 -0
- package/dist/next-server.d.ts +41 -0
- package/dist/next-server.js +96 -0
- package/dist/next-server.js.map +1 -0
- package/dist/next.d.ts +39 -0
- package/dist/next.js +68 -0
- package/dist/next.js.map +1 -0
- package/dist/nuxt.d.ts +17 -0
- package/dist/nuxt.js +22 -0
- package/dist/nuxt.js.map +1 -0
- package/dist/react.d.ts +50 -0
- package/dist/react.js +194 -0
- package/dist/react.js.map +1 -0
- package/dist/registry-CIe_aYoE.d.ts +263 -0
- package/dist/solid.d.ts +39 -0
- package/dist/solid.js +229 -0
- package/dist/solid.js.map +1 -0
- package/dist/svelte-server.d.ts +23 -0
- package/dist/svelte-server.js +33 -0
- package/dist/svelte-server.js.map +1 -0
- package/dist/svelte.d.ts +53 -0
- package/dist/svelte.js +244 -0
- package/dist/svelte.js.map +1 -0
- package/dist/vite.d.ts +30 -0
- package/dist/vite.js +131 -0
- package/dist/vite.js.map +1 -0
- package/dist/vue-server.d.ts +20 -0
- package/dist/vue-server.js +26 -0
- package/dist/vue-server.js.map +1 -0
- package/dist/vue.d.ts +64 -0
- package/dist/vue.js +250 -0
- package/dist/vue.js.map +1 -0
- package/dist/webmcp.d.ts +19 -0
- package/dist/webmcp.js +36 -0
- package/dist/webmcp.js.map +1 -0
- package/package.json +172 -4
- package/skills/agent-native-actions/SKILL.md +76 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1765 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import fs3 from "fs";
|
|
5
|
+
import path3 from "path";
|
|
6
|
+
import readline from "readline";
|
|
7
|
+
import { fileURLToPath } from "url";
|
|
8
|
+
import { createJiti } from "jiti";
|
|
9
|
+
|
|
10
|
+
// src/errors.ts
|
|
11
|
+
var ACTION_ERROR_BRAND = /* @__PURE__ */ Symbol.for("agent-native.actions.ActionError");
|
|
12
|
+
var POST_COMMIT_ERROR_BRAND = /* @__PURE__ */ Symbol.for(
|
|
13
|
+
"agent-native.actions.ActionPostCommitError"
|
|
14
|
+
);
|
|
15
|
+
var ActionError = class extends Error {
|
|
16
|
+
[ACTION_ERROR_BRAND] = true;
|
|
17
|
+
actionContractError = true;
|
|
18
|
+
statusCode;
|
|
19
|
+
errorCode;
|
|
20
|
+
details;
|
|
21
|
+
committed;
|
|
22
|
+
constructor(message, options = {}) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "ActionError";
|
|
25
|
+
this.statusCode = options.statusCode ?? options.status ?? 400;
|
|
26
|
+
this.errorCode = options.errorCode ?? "action_failed";
|
|
27
|
+
this.details = options.details;
|
|
28
|
+
this.committed = options.committed ?? false;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
var ActionPostCommitError = class extends ActionError {
|
|
32
|
+
[POST_COMMIT_ERROR_BRAND] = true;
|
|
33
|
+
cause;
|
|
34
|
+
constructor(message, cause, details) {
|
|
35
|
+
super(message, {
|
|
36
|
+
statusCode: 500,
|
|
37
|
+
errorCode: "post_commit_error",
|
|
38
|
+
committed: true,
|
|
39
|
+
...details ? { details } : {}
|
|
40
|
+
});
|
|
41
|
+
this.name = "ActionPostCommitError";
|
|
42
|
+
this.cause = cause;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
function isActionError(value) {
|
|
46
|
+
if (value instanceof ActionError) return true;
|
|
47
|
+
if (typeof value !== "object" || value === null) return false;
|
|
48
|
+
if (ACTION_ERROR_BRAND in value) return true;
|
|
49
|
+
return value.actionContractError === true && typeof value.errorCode === "string";
|
|
50
|
+
}
|
|
51
|
+
function isActionPostCommitError(value) {
|
|
52
|
+
return value instanceof ActionPostCommitError || typeof value === "object" && value !== null && POST_COMMIT_ERROR_BRAND in value;
|
|
53
|
+
}
|
|
54
|
+
function serializeActionErrorBody(error) {
|
|
55
|
+
if (isActionPostCommitError(error)) {
|
|
56
|
+
return {
|
|
57
|
+
statusCode: 500,
|
|
58
|
+
body: {
|
|
59
|
+
error: "Action completed but post-execution processing failed.",
|
|
60
|
+
errorCode: error.errorCode,
|
|
61
|
+
committed: true,
|
|
62
|
+
...error.details ? { details: error.details } : {}
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
if (isActionError(error)) {
|
|
67
|
+
const safeMessage = error.statusCode >= 500 ? "Internal action error." : error.message;
|
|
68
|
+
return {
|
|
69
|
+
statusCode: error.statusCode,
|
|
70
|
+
body: {
|
|
71
|
+
error: safeMessage,
|
|
72
|
+
errorCode: error.errorCode,
|
|
73
|
+
...error.committed ? { committed: true } : {},
|
|
74
|
+
...error.statusCode < 500 && error.details ? { details: error.details } : {}
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
statusCode: 500,
|
|
80
|
+
body: {
|
|
81
|
+
error: "Internal action error.",
|
|
82
|
+
errorCode: "internal_error"
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/schema.ts
|
|
88
|
+
function isPlainRecord(value) {
|
|
89
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
90
|
+
}
|
|
91
|
+
function formatIssuePath(path4) {
|
|
92
|
+
if (!path4 || path4.length === 0) return "";
|
|
93
|
+
return path4.map(
|
|
94
|
+
(segment) => typeof segment === "object" && "key" in segment ? String(segment.key) : String(segment)
|
|
95
|
+
).join(".");
|
|
96
|
+
}
|
|
97
|
+
async function validateInputSchema(schema, rawInput, actionName) {
|
|
98
|
+
const result = await schema["~standard"].validate(rawInput);
|
|
99
|
+
if (result.issues) {
|
|
100
|
+
const formatted = result.issues.map((issue) => {
|
|
101
|
+
const pathStr = formatIssuePath(issue.path);
|
|
102
|
+
return pathStr ? `${pathStr}: ${issue.message}` : issue.message;
|
|
103
|
+
});
|
|
104
|
+
throw new ActionError(
|
|
105
|
+
`Invalid input for "${actionName}": ${formatted.join("; ")}`,
|
|
106
|
+
{
|
|
107
|
+
statusCode: 400,
|
|
108
|
+
errorCode: "invalid_input",
|
|
109
|
+
details: {
|
|
110
|
+
issues: result.issues.map((issue) => ({
|
|
111
|
+
path: formatIssuePath(issue.path),
|
|
112
|
+
message: issue.message
|
|
113
|
+
}))
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
return result.value;
|
|
119
|
+
}
|
|
120
|
+
async function validateOutputSchema(schema, rawOutput, actionName) {
|
|
121
|
+
const result = await schema["~standard"].validate(rawOutput);
|
|
122
|
+
if (result.issues) {
|
|
123
|
+
const formatted = result.issues.map((issue) => {
|
|
124
|
+
const pathStr = formatIssuePath(issue.path);
|
|
125
|
+
return pathStr ? `${pathStr}: ${issue.message}` : issue.message;
|
|
126
|
+
});
|
|
127
|
+
throw new ActionPostCommitError(
|
|
128
|
+
`Action "${actionName}" returned output that violated outputSchema: ${formatted.join("; ")}`,
|
|
129
|
+
void 0,
|
|
130
|
+
{
|
|
131
|
+
issues: result.issues.map((issue) => ({
|
|
132
|
+
path: formatIssuePath(issue.path),
|
|
133
|
+
message: issue.message
|
|
134
|
+
}))
|
|
135
|
+
}
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
return result.value;
|
|
139
|
+
}
|
|
140
|
+
function schemaToJsonSchema(schema, mode, explicitOverride) {
|
|
141
|
+
if (mode === "input" && explicitOverride) {
|
|
142
|
+
return structuredClone(explicitOverride);
|
|
143
|
+
}
|
|
144
|
+
if (!schema) {
|
|
145
|
+
return mode === "input" ? { type: "object", properties: {}, additionalProperties: false } : null;
|
|
146
|
+
}
|
|
147
|
+
const standard = schema["~standard"];
|
|
148
|
+
const converter = mode === "input" ? standard.jsonSchema?.input : standard.jsonSchema?.output;
|
|
149
|
+
if (typeof converter !== "function") {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
const converted = converter({ target: "draft-2020-12" });
|
|
153
|
+
if (!isPlainRecord(converted)) {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
const copy = structuredClone(converted);
|
|
157
|
+
delete copy["$schema"];
|
|
158
|
+
return copy;
|
|
159
|
+
}
|
|
160
|
+
function normalizeLlmToolInput(rawInput, jsonSchema) {
|
|
161
|
+
if (!isPlainRecord(rawInput) || !jsonSchema) {
|
|
162
|
+
return rawInput;
|
|
163
|
+
}
|
|
164
|
+
const properties = isPlainRecord(jsonSchema["properties"]) ? jsonSchema["properties"] : null;
|
|
165
|
+
if (!properties) {
|
|
166
|
+
return rawInput;
|
|
167
|
+
}
|
|
168
|
+
const required = new Set(
|
|
169
|
+
Array.isArray(jsonSchema["required"]) ? jsonSchema["required"].filter(
|
|
170
|
+
(item) => typeof item === "string"
|
|
171
|
+
) : []
|
|
172
|
+
);
|
|
173
|
+
const out = {};
|
|
174
|
+
for (const [key, value] of Object.entries(rawInput)) {
|
|
175
|
+
const fieldSchema = isPlainRecord(properties[key]) ? properties[key] : null;
|
|
176
|
+
if (!fieldSchema) {
|
|
177
|
+
out[key] = value;
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
const fieldType = fieldSchema["type"];
|
|
181
|
+
const allowsNull = fieldType === "null" || Array.isArray(fieldType) && fieldType.includes("null") || Array.isArray(fieldSchema["anyOf"]) && fieldSchema["anyOf"].some(
|
|
182
|
+
(branch) => isPlainRecord(branch) && branch["type"] === "null"
|
|
183
|
+
);
|
|
184
|
+
if (value === null && !required.has(key) && !allowsNull) {
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (typeof value === "string" && (fieldType === "object" || fieldType === "array")) {
|
|
188
|
+
const trimmed = value.trim();
|
|
189
|
+
if (fieldType === "object" && trimmed.startsWith("{") && trimmed.endsWith("}") || fieldType === "array" && trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
190
|
+
try {
|
|
191
|
+
const parsed = JSON.parse(trimmed);
|
|
192
|
+
out[key] = fieldType === "object" ? normalizeLlmToolInput(parsed, fieldSchema) : parsed;
|
|
193
|
+
continue;
|
|
194
|
+
} catch {
|
|
195
|
+
out[key] = value;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (isPlainRecord(value) && fieldType === "object") {
|
|
201
|
+
out[key] = normalizeLlmToolInput(value, fieldSchema);
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
out[key] = value;
|
|
205
|
+
}
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// src/action.ts
|
|
210
|
+
function isDefinedAction(value) {
|
|
211
|
+
return typeof value === "object" && value !== null && "__agentNativeAction" in value && value.__agentNativeAction === true && typeof value.run === "function";
|
|
212
|
+
}
|
|
213
|
+
function resolveActionHttpMethod(action) {
|
|
214
|
+
if (action.http === false) return null;
|
|
215
|
+
if (action.http && action.http.method) return action.http.method;
|
|
216
|
+
return "POST";
|
|
217
|
+
}
|
|
218
|
+
function resolveActionHttpPath(name, action) {
|
|
219
|
+
if (action.http === false) return null;
|
|
220
|
+
if (action.http && action.http.path) {
|
|
221
|
+
return action.http.path.replace(/^\/+/, "");
|
|
222
|
+
}
|
|
223
|
+
return name;
|
|
224
|
+
}
|
|
225
|
+
function isActionReadOnly(action) {
|
|
226
|
+
if (typeof action.readOnly === "boolean") return action.readOnly;
|
|
227
|
+
return resolveActionHttpMethod(action) === "GET";
|
|
228
|
+
}
|
|
229
|
+
async function executeAction(options) {
|
|
230
|
+
const {
|
|
231
|
+
name,
|
|
232
|
+
action,
|
|
233
|
+
ctx,
|
|
234
|
+
caller,
|
|
235
|
+
approvalToken,
|
|
236
|
+
approved,
|
|
237
|
+
verifyApproval,
|
|
238
|
+
middleware = [],
|
|
239
|
+
onAfterMutate,
|
|
240
|
+
onError
|
|
241
|
+
} = options;
|
|
242
|
+
let committed = false;
|
|
243
|
+
try {
|
|
244
|
+
let candidateInput = options.rawInput;
|
|
245
|
+
if (caller === "mcp" || caller === "agent") {
|
|
246
|
+
const jsonSchema = schemaToJsonSchema(
|
|
247
|
+
action.schema,
|
|
248
|
+
"input",
|
|
249
|
+
action.toolSchema
|
|
250
|
+
);
|
|
251
|
+
candidateInput = normalizeLlmToolInput(candidateInput, jsonSchema);
|
|
252
|
+
}
|
|
253
|
+
const inputToValidate = candidateInput ?? {};
|
|
254
|
+
const validatedInput = action.schema ? await validateInputSchema(action.schema, inputToValidate, name) : inputToValidate;
|
|
255
|
+
if (action.authorize) {
|
|
256
|
+
const allowed = await action.authorize(validatedInput, ctx);
|
|
257
|
+
if (!allowed) {
|
|
258
|
+
throw new ActionError(`Not authorized to run action "${name}".`, {
|
|
259
|
+
statusCode: 403,
|
|
260
|
+
errorCode: "forbidden"
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (action.needsApproval !== void 0) {
|
|
265
|
+
const required = typeof action.needsApproval === "function" ? await action.needsApproval(validatedInput, ctx) : Boolean(action.needsApproval);
|
|
266
|
+
if (required) {
|
|
267
|
+
let isApproved = false;
|
|
268
|
+
if (verifyApproval) {
|
|
269
|
+
isApproved = Boolean(
|
|
270
|
+
await verifyApproval({
|
|
271
|
+
actionName: name,
|
|
272
|
+
input: validatedInput,
|
|
273
|
+
ctx,
|
|
274
|
+
caller,
|
|
275
|
+
...approvalToken !== void 0 ? { approvalToken } : {}
|
|
276
|
+
})
|
|
277
|
+
);
|
|
278
|
+
} else if (approved === true) {
|
|
279
|
+
isApproved = true;
|
|
280
|
+
}
|
|
281
|
+
if (!isApproved) {
|
|
282
|
+
throw new ActionError(
|
|
283
|
+
`Action "${name}" requires explicit human approval before executing.`,
|
|
284
|
+
{
|
|
285
|
+
statusCode: 403,
|
|
286
|
+
errorCode: "approval_required",
|
|
287
|
+
details: {
|
|
288
|
+
action: name,
|
|
289
|
+
input: validatedInput
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
const runCore = async () => action.run(validatedInput, ctx);
|
|
297
|
+
const dispatch = middleware.reduceRight(
|
|
298
|
+
(next, mw) => () => mw({ name, input: validatedInput, ctx, caller, next }),
|
|
299
|
+
runCore
|
|
300
|
+
);
|
|
301
|
+
const rawResult = await dispatch();
|
|
302
|
+
committed = true;
|
|
303
|
+
const validatedResult = action.outputSchema ? await validateOutputSchema(action.outputSchema, rawResult, name) : rawResult;
|
|
304
|
+
if (onAfterMutate && !isActionReadOnly(action)) {
|
|
305
|
+
try {
|
|
306
|
+
await onAfterMutate({
|
|
307
|
+
name,
|
|
308
|
+
input: validatedInput,
|
|
309
|
+
result: validatedResult,
|
|
310
|
+
ctx,
|
|
311
|
+
caller
|
|
312
|
+
});
|
|
313
|
+
} catch (hookError) {
|
|
314
|
+
throw new ActionPostCommitError(
|
|
315
|
+
`Action "${name}" succeeded, but post-mutation hook failed.`,
|
|
316
|
+
hookError
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return validatedResult;
|
|
321
|
+
} catch (error) {
|
|
322
|
+
onError?.(error, { name, caller, ctx, committed });
|
|
323
|
+
throw error;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// src/client.ts
|
|
328
|
+
var ActionClientError = class extends Error {
|
|
329
|
+
actionName;
|
|
330
|
+
statusCode;
|
|
331
|
+
errorCode;
|
|
332
|
+
committed;
|
|
333
|
+
details;
|
|
334
|
+
userMessage;
|
|
335
|
+
constructor(params) {
|
|
336
|
+
super(`Action ${params.actionName} failed: ${params.message}`);
|
|
337
|
+
this.name = "ActionClientError";
|
|
338
|
+
this.actionName = params.actionName;
|
|
339
|
+
this.statusCode = params.statusCode;
|
|
340
|
+
this.errorCode = params.errorCode ?? "action_failed";
|
|
341
|
+
this.committed = params.committed ?? false;
|
|
342
|
+
this.details = params.details;
|
|
343
|
+
this.userMessage = params.userMessage;
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
function buildActionQueryKey(actionName, input, scope) {
|
|
347
|
+
return scope ? ["agent-native-action", scope, actionName, input ?? {}] : ["agent-native-action", actionName, input ?? {}];
|
|
348
|
+
}
|
|
349
|
+
function createActionClient(options = {}) {
|
|
350
|
+
const baseUrl = (options.baseUrl ?? "/api/agent-native/actions").replace(
|
|
351
|
+
/\/+$/,
|
|
352
|
+
""
|
|
353
|
+
);
|
|
354
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
355
|
+
return {
|
|
356
|
+
baseUrl,
|
|
357
|
+
scope: options.scope,
|
|
358
|
+
queryKey: (name, input, extraScope) => buildActionQueryKey(name, input, extraScope ?? options.scope),
|
|
359
|
+
call: async (name, input, callOptions = {}) => {
|
|
360
|
+
const method = callOptions.method ?? options.methods?.[name] ?? "POST";
|
|
361
|
+
const resolvedBaseHeaders = typeof options.headers === "function" ? await options.headers() : options.headers;
|
|
362
|
+
const headers = new Headers(resolvedBaseHeaders);
|
|
363
|
+
if (callOptions.headers) {
|
|
364
|
+
new Headers(callOptions.headers).forEach((value, key) => {
|
|
365
|
+
headers.set(key, value);
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
if (callOptions.approvalToken) {
|
|
369
|
+
headers.set("X-Action-Approval", callOptions.approvalToken);
|
|
370
|
+
}
|
|
371
|
+
let url = `${baseUrl}/${encodeURIComponent(name)}`;
|
|
372
|
+
let body;
|
|
373
|
+
if (method === "GET") {
|
|
374
|
+
if (input !== void 0 && Object.keys(input).length > 0) {
|
|
375
|
+
const qs = new URLSearchParams({
|
|
376
|
+
input: JSON.stringify(input)
|
|
377
|
+
});
|
|
378
|
+
url = `${url}?${qs.toString()}`;
|
|
379
|
+
}
|
|
380
|
+
} else {
|
|
381
|
+
headers.set("Content-Type", "application/json");
|
|
382
|
+
body = JSON.stringify(input ?? {});
|
|
383
|
+
}
|
|
384
|
+
const response = await fetchImpl(url, {
|
|
385
|
+
method,
|
|
386
|
+
headers,
|
|
387
|
+
credentials: options.credentials ?? "same-origin",
|
|
388
|
+
...callOptions.signal ? { signal: callOptions.signal } : {},
|
|
389
|
+
...body !== void 0 ? { body } : {}
|
|
390
|
+
});
|
|
391
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
392
|
+
const isJson = contentType.includes("application/json");
|
|
393
|
+
if (!response.ok) {
|
|
394
|
+
let errorPayload = null;
|
|
395
|
+
try {
|
|
396
|
+
errorPayload = isJson ? await response.json() : await response.text();
|
|
397
|
+
} catch {
|
|
398
|
+
errorPayload = null;
|
|
399
|
+
}
|
|
400
|
+
const record = errorPayload && typeof errorPayload === "object" ? errorPayload : null;
|
|
401
|
+
const message = typeof record?.["error"] === "string" ? record["error"] : `HTTP ${response.status}`;
|
|
402
|
+
const errorCode = typeof record?.["errorCode"] === "string" ? record["errorCode"] : "action_failed";
|
|
403
|
+
const committed = record?.["committed"] === true;
|
|
404
|
+
const details = record?.["details"] && typeof record["details"] === "object" && !Array.isArray(record["details"]) ? record["details"] : void 0;
|
|
405
|
+
throw new ActionClientError({
|
|
406
|
+
actionName: name,
|
|
407
|
+
message,
|
|
408
|
+
statusCode: response.status,
|
|
409
|
+
errorCode,
|
|
410
|
+
committed,
|
|
411
|
+
...details ? { details } : {},
|
|
412
|
+
...response.status < 500 && typeof record?.["error"] === "string" ? { userMessage: record["error"] } : {}
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
if (response.status === 204) {
|
|
416
|
+
return void 0;
|
|
417
|
+
}
|
|
418
|
+
const payload = isJson ? await response.json() : await response.text();
|
|
419
|
+
return payload;
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// src/codegen.ts
|
|
425
|
+
import fs from "fs";
|
|
426
|
+
import path from "path";
|
|
427
|
+
var SKIP_FILES = /* @__PURE__ */ new Set([
|
|
428
|
+
"context",
|
|
429
|
+
"helpers",
|
|
430
|
+
"index",
|
|
431
|
+
"registry",
|
|
432
|
+
"run",
|
|
433
|
+
"types",
|
|
434
|
+
"utils"
|
|
435
|
+
]);
|
|
436
|
+
var ACTION_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".tsx", ".mts", ".js", ".mjs"]);
|
|
437
|
+
function toValidIdentifier(name, index) {
|
|
438
|
+
const cleaned = name.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
439
|
+
return `action_${index}_${cleaned}`;
|
|
440
|
+
}
|
|
441
|
+
function toPosixRelative(fromDir, targetFile) {
|
|
442
|
+
const withoutExt = targetFile.replace(/\.(?:tsx?|mts|mjs|js)$/, "");
|
|
443
|
+
const rel = path.relative(fromDir, withoutExt).split(path.sep).join("/");
|
|
444
|
+
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
445
|
+
}
|
|
446
|
+
function scanActionsDirectory(projectRoot, options = {}) {
|
|
447
|
+
const actionsDir = path.resolve(projectRoot, options.actionsDir ?? "actions");
|
|
448
|
+
const generatedDir = path.resolve(
|
|
449
|
+
projectRoot,
|
|
450
|
+
options.generatedDir ?? ".generated"
|
|
451
|
+
);
|
|
452
|
+
if (!fs.existsSync(actionsDir)) {
|
|
453
|
+
return { actions: [], contextFile: null };
|
|
454
|
+
}
|
|
455
|
+
let contextFile = null;
|
|
456
|
+
const entries = fs.readdirSync(actionsDir, { withFileTypes: true }).filter((entry) => entry.isFile()).sort((a, b) => a.name.localeCompare(b.name));
|
|
457
|
+
const seenNames = /* @__PURE__ */ new Map();
|
|
458
|
+
const actions = [];
|
|
459
|
+
for (const entry of entries) {
|
|
460
|
+
if (entry.name.endsWith(".d.ts") || entry.name.includes(".spec.") || entry.name.includes(".test.") || entry.name.startsWith("_") || entry.name.startsWith(".")) {
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
const ext = path.extname(entry.name);
|
|
464
|
+
if (!ACTION_EXTENSIONS.has(ext)) continue;
|
|
465
|
+
const baseName = entry.name.slice(0, -ext.length);
|
|
466
|
+
const fullPath = path.join(actionsDir, entry.name);
|
|
467
|
+
if (baseName === "context") {
|
|
468
|
+
contextFile = fullPath;
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
if (SKIP_FILES.has(baseName)) continue;
|
|
472
|
+
const existing = seenNames.get(baseName);
|
|
473
|
+
if (existing) {
|
|
474
|
+
throw new Error(
|
|
475
|
+
`Duplicate action name "${baseName}" found in ${existing} and ${fullPath}.`
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
seenNames.set(baseName, fullPath);
|
|
479
|
+
actions.push({
|
|
480
|
+
name: baseName,
|
|
481
|
+
filePath: fullPath,
|
|
482
|
+
relativeImport: toPosixRelative(generatedDir, fullPath),
|
|
483
|
+
identifier: toValidIdentifier(baseName, actions.length)
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
return { actions, contextFile };
|
|
487
|
+
}
|
|
488
|
+
function generateActionArtifacts(options) {
|
|
489
|
+
const generatedDir = path.resolve(
|
|
490
|
+
options.projectRoot,
|
|
491
|
+
options.generatedDir ?? ".generated"
|
|
492
|
+
);
|
|
493
|
+
const scan = scanActionsDirectory(options.projectRoot, {
|
|
494
|
+
...options.actionsDir ? { actionsDir: options.actionsDir } : {},
|
|
495
|
+
...options.generatedDir ? { generatedDir: options.generatedDir } : {}
|
|
496
|
+
});
|
|
497
|
+
fs.mkdirSync(generatedDir, { recursive: true });
|
|
498
|
+
const importLines = scan.actions.map(
|
|
499
|
+
(action) => `import ${action.identifier} from ${JSON.stringify(action.relativeImport)};`
|
|
500
|
+
);
|
|
501
|
+
const contextImport = scan.contextFile ? `import * as actionContextModule from ${JSON.stringify(toPosixRelative(generatedDir, scan.contextFile))};` : "";
|
|
502
|
+
const entriesLines = scan.actions.map(
|
|
503
|
+
(action) => ` ${JSON.stringify(action.name)}: ${action.identifier},`
|
|
504
|
+
);
|
|
505
|
+
const createContextLine = scan.contextFile ? ` ...(typeof actionContextModule.createContext === "function" ? { createContext: actionContextModule.createContext } : {}),` : "";
|
|
506
|
+
const manifestSource = [
|
|
507
|
+
"// Auto-generated by @agent-native/actions. Do not edit manually.",
|
|
508
|
+
'import { createActions } from "@agent-native/actions";',
|
|
509
|
+
...importLines,
|
|
510
|
+
...contextImport ? [contextImport] : [],
|
|
511
|
+
"",
|
|
512
|
+
"export const actions = createActions({",
|
|
513
|
+
" actions: {",
|
|
514
|
+
...entriesLines,
|
|
515
|
+
" },",
|
|
516
|
+
...createContextLine ? [createContextLine] : [],
|
|
517
|
+
"});",
|
|
518
|
+
"",
|
|
519
|
+
"export type AppActions = typeof actions;",
|
|
520
|
+
""
|
|
521
|
+
].join("\n");
|
|
522
|
+
const typeImportLines = scan.actions.map(
|
|
523
|
+
(action) => ` ${JSON.stringify(action.name)}: typeof import(${JSON.stringify(action.relativeImport)}).default;`
|
|
524
|
+
);
|
|
525
|
+
const typesSource = [
|
|
526
|
+
"// Auto-generated by @agent-native/actions. Do not edit manually.",
|
|
527
|
+
'import type { InferActionInputFromDef, InferActionReturn } from "@agent-native/actions";',
|
|
528
|
+
"",
|
|
529
|
+
"interface GeneratedActionDefinitions {",
|
|
530
|
+
...typeImportLines,
|
|
531
|
+
"}",
|
|
532
|
+
"",
|
|
533
|
+
'declare module "@agent-native/actions/client" {',
|
|
534
|
+
" interface ActionTypeRegistry {",
|
|
535
|
+
" actions: {",
|
|
536
|
+
" [K in keyof GeneratedActionDefinitions]: {",
|
|
537
|
+
" input: InferActionInputFromDef<GeneratedActionDefinitions[K]>;",
|
|
538
|
+
" output: InferActionReturn<GeneratedActionDefinitions[K]>;",
|
|
539
|
+
" };",
|
|
540
|
+
" };",
|
|
541
|
+
" }",
|
|
542
|
+
"}",
|
|
543
|
+
"",
|
|
544
|
+
"export {};",
|
|
545
|
+
""
|
|
546
|
+
].join("\n");
|
|
547
|
+
const manifestPath = path.join(generatedDir, "actions.ts");
|
|
548
|
+
const typesPath = path.join(generatedDir, "action-types.d.ts");
|
|
549
|
+
writeFileIfChanged(manifestPath, manifestSource);
|
|
550
|
+
writeFileIfChanged(typesPath, typesSource);
|
|
551
|
+
return {
|
|
552
|
+
manifestPath,
|
|
553
|
+
typesPath,
|
|
554
|
+
actionCount: scan.actions.length,
|
|
555
|
+
hasContextFile: Boolean(scan.contextFile)
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
function writeFileIfChanged(filePath, content) {
|
|
559
|
+
if (fs.existsSync(filePath)) {
|
|
560
|
+
const existing = fs.readFileSync(filePath, "utf8");
|
|
561
|
+
if (existing === content) return;
|
|
562
|
+
}
|
|
563
|
+
fs.writeFileSync(filePath, content, "utf8");
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// src/mcp.ts
|
|
567
|
+
import {
|
|
568
|
+
Server,
|
|
569
|
+
createMcpHandler
|
|
570
|
+
} from "@modelcontextprotocol/server";
|
|
571
|
+
function isPlainRecord2(value) {
|
|
572
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
573
|
+
}
|
|
574
|
+
function formatMcpErrorText(error) {
|
|
575
|
+
const { body } = serializeActionErrorBody(error);
|
|
576
|
+
const parts = [body.error];
|
|
577
|
+
if (body.errorCode && body.errorCode !== "action_failed") {
|
|
578
|
+
parts.push(`(errorCode: ${body.errorCode})`);
|
|
579
|
+
}
|
|
580
|
+
if (body.committed) {
|
|
581
|
+
parts.push("[committed: true \u2014 do not blindly retry]");
|
|
582
|
+
}
|
|
583
|
+
if (body.details) {
|
|
584
|
+
const serialized = JSON.stringify(body.details);
|
|
585
|
+
parts.push(
|
|
586
|
+
`Error details: ${serialized.length > 2e3 ? `${serialized.slice(0, 1997)}...` : serialized}`
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
return parts.join("\n");
|
|
590
|
+
}
|
|
591
|
+
function isExposedToMcp(name, action, options) {
|
|
592
|
+
if (action.agentTool === false || action.mcpTool === false) return false;
|
|
593
|
+
if (options.include && !options.include.includes(name)) return false;
|
|
594
|
+
if (options.exclude && options.exclude.includes(name)) return false;
|
|
595
|
+
return true;
|
|
596
|
+
}
|
|
597
|
+
function buildMcpServerForRequest(registry, options, invocation) {
|
|
598
|
+
const server = new Server(
|
|
599
|
+
{
|
|
600
|
+
name: options.name ?? "agent-native-actions",
|
|
601
|
+
version: options.version ?? "0.1.0"
|
|
602
|
+
},
|
|
603
|
+
{
|
|
604
|
+
capabilities: { tools: {} },
|
|
605
|
+
...options.instructions ? { instructions: options.instructions } : {}
|
|
606
|
+
}
|
|
607
|
+
);
|
|
608
|
+
server.setRequestHandler("tools/list", async () => {
|
|
609
|
+
const tools = [];
|
|
610
|
+
for (const [name, action] of Object.entries(registry.actions)) {
|
|
611
|
+
if (!isExposedToMcp(name, action, options)) continue;
|
|
612
|
+
const inputSchema = schemaToJsonSchema(
|
|
613
|
+
action.schema,
|
|
614
|
+
"input",
|
|
615
|
+
action.toolSchema
|
|
616
|
+
) ?? {
|
|
617
|
+
type: "object",
|
|
618
|
+
properties: {}
|
|
619
|
+
};
|
|
620
|
+
const outputSchema = action.mcpOutputSchema !== false && action.outputSchema ? schemaToJsonSchema(action.outputSchema, "output") : null;
|
|
621
|
+
const tool = {
|
|
622
|
+
name,
|
|
623
|
+
...action.title ? { title: action.title } : {},
|
|
624
|
+
description: action.description,
|
|
625
|
+
inputSchema,
|
|
626
|
+
...outputSchema && outputSchema["type"] === "object" ? { outputSchema } : {},
|
|
627
|
+
annotations: {
|
|
628
|
+
readOnlyHint: isActionReadOnly(action),
|
|
629
|
+
destructiveHint: Boolean(action.destructive),
|
|
630
|
+
idempotentHint: Boolean(action.retrySafe),
|
|
631
|
+
openWorldHint: false
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
tools.push(tool);
|
|
635
|
+
}
|
|
636
|
+
return { tools };
|
|
637
|
+
});
|
|
638
|
+
server.setRequestHandler("tools/call", async (request) => {
|
|
639
|
+
const toolName = request.params.name;
|
|
640
|
+
const args = request.params.arguments ?? {};
|
|
641
|
+
const action = registry.actions[toolName];
|
|
642
|
+
if (!action || !isExposedToMcp(toolName, action, options)) {
|
|
643
|
+
return {
|
|
644
|
+
isError: true,
|
|
645
|
+
content: [
|
|
646
|
+
{
|
|
647
|
+
type: "text",
|
|
648
|
+
text: `Action "${toolName}" is not exposed over MCP.
|
|
649
|
+
(errorCode: not_found)`
|
|
650
|
+
}
|
|
651
|
+
]
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
try {
|
|
655
|
+
const result = invocation.request ? await registry.invokeFromRequest(toolName, args, {
|
|
656
|
+
caller: "mcp",
|
|
657
|
+
request: invocation.request,
|
|
658
|
+
...invocation.platform !== void 0 ? { platform: invocation.platform } : {}
|
|
659
|
+
}) : await registry.invokeFromCliOrStdio(toolName, args, {
|
|
660
|
+
caller: "mcp"
|
|
661
|
+
});
|
|
662
|
+
const structuredContent = isPlainRecord2(result) ? result : Array.isArray(result) ? { items: result } : void 0;
|
|
663
|
+
const text = typeof result === "string" ? result : JSON.stringify(result ?? null, null, 2);
|
|
664
|
+
return {
|
|
665
|
+
content: [{ type: "text", text }],
|
|
666
|
+
...structuredContent ? { structuredContent } : {}
|
|
667
|
+
};
|
|
668
|
+
} catch (error) {
|
|
669
|
+
const { body } = serializeActionErrorBody(error);
|
|
670
|
+
return {
|
|
671
|
+
isError: true,
|
|
672
|
+
content: [{ type: "text", text: formatMcpErrorText(error) }],
|
|
673
|
+
structuredContent: {
|
|
674
|
+
error: {
|
|
675
|
+
message: body.error,
|
|
676
|
+
errorCode: body.errorCode,
|
|
677
|
+
...body.committed ? { committed: true } : {},
|
|
678
|
+
...body.details ? { details: body.details } : {}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
});
|
|
684
|
+
return server;
|
|
685
|
+
}
|
|
686
|
+
function createMcpFetchHandler(registry, options = {}) {
|
|
687
|
+
return async (request, override) => {
|
|
688
|
+
if (options.authenticate) {
|
|
689
|
+
const allowed = await options.authenticate(request);
|
|
690
|
+
if (!allowed) {
|
|
691
|
+
return new Response(
|
|
692
|
+
JSON.stringify({
|
|
693
|
+
error: "Unauthorized MCP request.",
|
|
694
|
+
errorCode: "unauthorized"
|
|
695
|
+
}),
|
|
696
|
+
{
|
|
697
|
+
status: 401,
|
|
698
|
+
headers: {
|
|
699
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
700
|
+
"Cache-Control": "no-store"
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
const handler = createMcpHandler(
|
|
707
|
+
() => buildMcpServerForRequest(registry, options, {
|
|
708
|
+
request,
|
|
709
|
+
...override?.platform !== void 0 ? { platform: override.platform } : {}
|
|
710
|
+
}),
|
|
711
|
+
{
|
|
712
|
+
legacy: "stateless",
|
|
713
|
+
responseMode: "auto"
|
|
714
|
+
}
|
|
715
|
+
);
|
|
716
|
+
try {
|
|
717
|
+
return await handler.fetch(request);
|
|
718
|
+
} catch (error) {
|
|
719
|
+
if (isActionError(error)) {
|
|
720
|
+
const { statusCode, body } = serializeActionErrorBody(error);
|
|
721
|
+
return new Response(JSON.stringify(body), {
|
|
722
|
+
status: statusCode,
|
|
723
|
+
headers: {
|
|
724
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
725
|
+
"Cache-Control": "no-store"
|
|
726
|
+
}
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
throw error;
|
|
730
|
+
}
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
async function runStdioMcpServer(registry, options = {}) {
|
|
734
|
+
const { serveStdio } = await import("@modelcontextprotocol/server/stdio");
|
|
735
|
+
const stdio = serveStdio(
|
|
736
|
+
() => buildMcpServerForRequest(registry, options, {}),
|
|
737
|
+
{ legacy: "serve" }
|
|
738
|
+
);
|
|
739
|
+
await new Promise((resolve) => {
|
|
740
|
+
process.stdin.once("end", resolve);
|
|
741
|
+
process.once("SIGINT", resolve);
|
|
742
|
+
process.once("SIGTERM", resolve);
|
|
743
|
+
});
|
|
744
|
+
await stdio.close();
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// src/http.ts
|
|
748
|
+
var DEFAULT_CORS_METHODS = "GET, POST, PUT, PATCH, DELETE, OPTIONS";
|
|
749
|
+
var DEFAULT_CORS_HEADERS = "Content-Type, Authorization, X-Action-Approval, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID";
|
|
750
|
+
function jsonResponse(body, status, extraHeaders) {
|
|
751
|
+
const headers = new Headers({
|
|
752
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
753
|
+
"Cache-Control": "no-store",
|
|
754
|
+
...extraHeaders
|
|
755
|
+
});
|
|
756
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
757
|
+
}
|
|
758
|
+
function buildCorsHeaders(request, cors) {
|
|
759
|
+
if (!cors) return {};
|
|
760
|
+
const origin = request.headers.get("origin");
|
|
761
|
+
if (!origin) return {};
|
|
762
|
+
let allowOrigin = null;
|
|
763
|
+
if (cors === true) {
|
|
764
|
+
allowOrigin = "*";
|
|
765
|
+
} else if (typeof cors.origin === "string") {
|
|
766
|
+
allowOrigin = cors.origin;
|
|
767
|
+
} else if (Array.isArray(cors.origin)) {
|
|
768
|
+
allowOrigin = cors.origin.includes(origin) ? origin : null;
|
|
769
|
+
} else if (typeof cors.origin === "function") {
|
|
770
|
+
allowOrigin = cors.origin(origin) ? origin : null;
|
|
771
|
+
}
|
|
772
|
+
if (!allowOrigin) return {};
|
|
773
|
+
const headers = {
|
|
774
|
+
"Access-Control-Allow-Origin": allowOrigin,
|
|
775
|
+
"Access-Control-Allow-Methods": DEFAULT_CORS_METHODS,
|
|
776
|
+
"Access-Control-Allow-Headers": DEFAULT_CORS_HEADERS,
|
|
777
|
+
Vary: "Origin"
|
|
778
|
+
};
|
|
779
|
+
if (typeof cors === "object" && cors.credentials && allowOrigin !== "*") {
|
|
780
|
+
headers["Access-Control-Allow-Credentials"] = "true";
|
|
781
|
+
}
|
|
782
|
+
return headers;
|
|
783
|
+
}
|
|
784
|
+
function checkCsrfOrigin(request, csrfProtection) {
|
|
785
|
+
if (!csrfProtection) return null;
|
|
786
|
+
const method = request.method.toUpperCase();
|
|
787
|
+
if (method === "GET" || method === "HEAD" || method === "OPTIONS") {
|
|
788
|
+
return null;
|
|
789
|
+
}
|
|
790
|
+
const hasCookie = Boolean(request.headers.get("cookie"));
|
|
791
|
+
const hasBearer = Boolean(request.headers.get("authorization"));
|
|
792
|
+
if (!hasCookie || hasBearer) return null;
|
|
793
|
+
const origin = request.headers.get("origin");
|
|
794
|
+
if (!origin) return null;
|
|
795
|
+
const requestOrigin = new URL(request.url).origin;
|
|
796
|
+
if (origin !== requestOrigin) {
|
|
797
|
+
return jsonResponse(
|
|
798
|
+
{
|
|
799
|
+
error: "Cross-origin cookie mutation rejected.",
|
|
800
|
+
errorCode: "csrf_origin_mismatch"
|
|
801
|
+
},
|
|
802
|
+
403
|
|
803
|
+
);
|
|
804
|
+
}
|
|
805
|
+
return null;
|
|
806
|
+
}
|
|
807
|
+
function parseQueryParams(url) {
|
|
808
|
+
const encodedInput = url.searchParams.get("input");
|
|
809
|
+
if (encodedInput !== null) {
|
|
810
|
+
try {
|
|
811
|
+
const parsed = JSON.parse(encodedInput);
|
|
812
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
813
|
+
return parsed;
|
|
814
|
+
}
|
|
815
|
+
throw new ActionError('Query parameter "input" must be a JSON object.', {
|
|
816
|
+
statusCode: 400,
|
|
817
|
+
errorCode: "invalid_input"
|
|
818
|
+
});
|
|
819
|
+
} catch (error) {
|
|
820
|
+
if (error instanceof ActionError) throw error;
|
|
821
|
+
throw new ActionError('Query parameter "input" is not valid JSON.', {
|
|
822
|
+
statusCode: 400,
|
|
823
|
+
errorCode: "invalid_input"
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
const params = {};
|
|
828
|
+
for (const [key, value] of url.searchParams.entries()) {
|
|
829
|
+
const existing = params[key];
|
|
830
|
+
if (existing !== void 0) {
|
|
831
|
+
params[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];
|
|
832
|
+
} else if (value === "true") {
|
|
833
|
+
params[key] = true;
|
|
834
|
+
} else if (value === "false") {
|
|
835
|
+
params[key] = false;
|
|
836
|
+
} else {
|
|
837
|
+
params[key] = value;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
return params;
|
|
841
|
+
}
|
|
842
|
+
async function readJsonBody(request) {
|
|
843
|
+
const contentLength = request.headers.get("content-length");
|
|
844
|
+
if (contentLength === "0") return {};
|
|
845
|
+
const text = await request.text();
|
|
846
|
+
if (!text.trim()) return {};
|
|
847
|
+
try {
|
|
848
|
+
return JSON.parse(text);
|
|
849
|
+
} catch {
|
|
850
|
+
throw new ActionError("Request body must be valid JSON.", {
|
|
851
|
+
statusCode: 400,
|
|
852
|
+
errorCode: "invalid_json"
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
function stripBasePath(pathname, basePath) {
|
|
857
|
+
const normalizedBase = basePath.replace(/\/+$/, "");
|
|
858
|
+
if (!normalizedBase || normalizedBase === "/") {
|
|
859
|
+
return pathname.replace(/^\/+/, "");
|
|
860
|
+
}
|
|
861
|
+
if (pathname === normalizedBase) return "";
|
|
862
|
+
if (pathname.startsWith(`${normalizedBase}/`)) {
|
|
863
|
+
return pathname.slice(normalizedBase.length + 1);
|
|
864
|
+
}
|
|
865
|
+
return pathname.replace(/^\/+/, "");
|
|
866
|
+
}
|
|
867
|
+
function createActionFetchHandler(registry, options = {}) {
|
|
868
|
+
const basePath = options.basePath ?? "/api/agent-native/actions";
|
|
869
|
+
const csrfProtection = options.csrfProtection ?? true;
|
|
870
|
+
return async (request, override) => {
|
|
871
|
+
const corsHeaders = buildCorsHeaders(request, options.cors);
|
|
872
|
+
const method = request.method.toUpperCase();
|
|
873
|
+
if (method === "OPTIONS") {
|
|
874
|
+
return new Response(null, {
|
|
875
|
+
status: 204,
|
|
876
|
+
headers: {
|
|
877
|
+
Allow: DEFAULT_CORS_METHODS,
|
|
878
|
+
...corsHeaders
|
|
879
|
+
}
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
const csrfBlock = checkCsrfOrigin(request, csrfProtection);
|
|
883
|
+
if (csrfBlock) return csrfBlock;
|
|
884
|
+
const url = new URL(request.url);
|
|
885
|
+
const relativePath = override?.actionPath !== void 0 ? override.actionPath.replace(/^\/+/, "") : stripBasePath(url.pathname, basePath);
|
|
886
|
+
if (!relativePath) {
|
|
887
|
+
if (method === "GET") {
|
|
888
|
+
return jsonResponse({ actions: registry.describe() }, 200, corsHeaders);
|
|
889
|
+
}
|
|
890
|
+
return jsonResponse(
|
|
891
|
+
{ error: "Action name is required.", errorCode: "not_found" },
|
|
892
|
+
404,
|
|
893
|
+
corsHeaders
|
|
894
|
+
);
|
|
895
|
+
}
|
|
896
|
+
const resolved = registry.resolveHttpAction(relativePath);
|
|
897
|
+
if (!resolved) {
|
|
898
|
+
return jsonResponse(
|
|
899
|
+
{
|
|
900
|
+
error: `Action "${relativePath}" not found.`,
|
|
901
|
+
errorCode: "not_found"
|
|
902
|
+
},
|
|
903
|
+
404,
|
|
904
|
+
corsHeaders
|
|
905
|
+
);
|
|
906
|
+
}
|
|
907
|
+
const expectedMethod = resolved.method;
|
|
908
|
+
if (method !== expectedMethod && !(expectedMethod === "GET" && method === "POST")) {
|
|
909
|
+
return jsonResponse(
|
|
910
|
+
{
|
|
911
|
+
error: `Action "${resolved.name}" expects ${expectedMethod}, received ${method}.`,
|
|
912
|
+
errorCode: "method_not_allowed"
|
|
913
|
+
},
|
|
914
|
+
405,
|
|
915
|
+
{ Allow: expectedMethod, ...corsHeaders }
|
|
916
|
+
);
|
|
917
|
+
}
|
|
918
|
+
try {
|
|
919
|
+
const rawInput = method === "GET" ? parseQueryParams(url) : await readJsonBody(request);
|
|
920
|
+
const approvalToken = request.headers.get("x-action-approval") ?? void 0;
|
|
921
|
+
const result = await registry.invokeFromRequest(resolved.name, rawInput, {
|
|
922
|
+
caller: "http",
|
|
923
|
+
request,
|
|
924
|
+
...approvalToken !== void 0 ? { approvalToken } : {},
|
|
925
|
+
...override?.platform !== void 0 ? { platform: override.platform } : {}
|
|
926
|
+
});
|
|
927
|
+
return jsonResponse(result ?? null, 200, corsHeaders);
|
|
928
|
+
} catch (error) {
|
|
929
|
+
const { statusCode, body } = serializeActionErrorBody(error);
|
|
930
|
+
return jsonResponse(body, statusCode, corsHeaders);
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// src/registry.ts
|
|
936
|
+
function readRuntimeEnv() {
|
|
937
|
+
return typeof process !== "undefined" ? process.env : {};
|
|
938
|
+
}
|
|
939
|
+
function defaultContext(input) {
|
|
940
|
+
return {
|
|
941
|
+
caller: input.caller,
|
|
942
|
+
source: input.source,
|
|
943
|
+
headers: input.headers,
|
|
944
|
+
...input.request ? { request: input.request } : {},
|
|
945
|
+
...input.signal ? { signal: input.signal } : {},
|
|
946
|
+
...input.actionName ? { actionName: input.actionName } : {}
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
function createActions(options) {
|
|
950
|
+
const { actions } = options;
|
|
951
|
+
const httpRouteIndex = /* @__PURE__ */ new Map();
|
|
952
|
+
for (const [name, action] of Object.entries(actions)) {
|
|
953
|
+
const method = resolveActionHttpMethod(action);
|
|
954
|
+
const routePath = resolveActionHttpPath(name, action);
|
|
955
|
+
if (method && routePath) {
|
|
956
|
+
if (httpRouteIndex.has(routePath)) {
|
|
957
|
+
throw new Error(
|
|
958
|
+
`Duplicate HTTP action route "${routePath}" in createActions().`
|
|
959
|
+
);
|
|
960
|
+
}
|
|
961
|
+
httpRouteIndex.set(routePath, {
|
|
962
|
+
name,
|
|
963
|
+
method
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
const resolveContext = async (input) => {
|
|
968
|
+
if (options.createContext) {
|
|
969
|
+
return options.createContext(input);
|
|
970
|
+
}
|
|
971
|
+
return defaultContext(input);
|
|
972
|
+
};
|
|
973
|
+
const invokeWithContext = async (name, rawInput, ctx, callOpts) => {
|
|
974
|
+
const action = actions[name];
|
|
975
|
+
if (!action) {
|
|
976
|
+
throw new ActionError(`Action "${name}" not found.`, {
|
|
977
|
+
statusCode: 404,
|
|
978
|
+
errorCode: "not_found"
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
return executeAction({
|
|
982
|
+
name,
|
|
983
|
+
action,
|
|
984
|
+
rawInput,
|
|
985
|
+
ctx,
|
|
986
|
+
caller: callOpts.caller,
|
|
987
|
+
...callOpts.approvalToken !== void 0 ? { approvalToken: callOpts.approvalToken } : {},
|
|
988
|
+
...callOpts.approved !== void 0 ? { approved: callOpts.approved } : {},
|
|
989
|
+
...options.verifyApproval ? { verifyApproval: options.verifyApproval } : {},
|
|
990
|
+
...options.middleware ? { middleware: options.middleware } : {},
|
|
991
|
+
...options.onAfterMutate ? { onAfterMutate: options.onAfterMutate } : {},
|
|
992
|
+
...options.onError ? { onError: options.onError } : {}
|
|
993
|
+
});
|
|
994
|
+
};
|
|
995
|
+
const invokeFromRequest = async (name, rawInput, reqOpts) => {
|
|
996
|
+
const ctx = await resolveContext({
|
|
997
|
+
caller: reqOpts.caller,
|
|
998
|
+
source: reqOpts.caller,
|
|
999
|
+
actionName: name,
|
|
1000
|
+
request: reqOpts.request,
|
|
1001
|
+
headers: reqOpts.request.headers,
|
|
1002
|
+
signal: reqOpts.request.signal,
|
|
1003
|
+
env: readRuntimeEnv(),
|
|
1004
|
+
...reqOpts.platform !== void 0 ? { platform: reqOpts.platform } : {}
|
|
1005
|
+
});
|
|
1006
|
+
return invokeWithContext(name, rawInput, ctx, {
|
|
1007
|
+
caller: reqOpts.caller,
|
|
1008
|
+
...reqOpts.approvalToken !== void 0 ? { approvalToken: reqOpts.approvalToken } : {}
|
|
1009
|
+
});
|
|
1010
|
+
};
|
|
1011
|
+
const invokeFromCliOrStdio = async (name, rawInput, cliOpts) => {
|
|
1012
|
+
const ctx = await resolveContext({
|
|
1013
|
+
caller: cliOpts.caller,
|
|
1014
|
+
source: cliOpts.caller,
|
|
1015
|
+
actionName: name,
|
|
1016
|
+
headers: new Headers(),
|
|
1017
|
+
env: readRuntimeEnv()
|
|
1018
|
+
});
|
|
1019
|
+
return invokeWithContext(name, rawInput, ctx, {
|
|
1020
|
+
caller: cliOpts.caller,
|
|
1021
|
+
...cliOpts.approved !== void 0 ? { approved: cliOpts.approved } : {},
|
|
1022
|
+
...cliOpts.approvalToken !== void 0 ? { approvalToken: cliOpts.approvalToken } : {}
|
|
1023
|
+
});
|
|
1024
|
+
};
|
|
1025
|
+
const registry = {
|
|
1026
|
+
actions,
|
|
1027
|
+
list: () => Object.keys(actions),
|
|
1028
|
+
describe: () => Object.entries(actions).map(([name, action]) => ({
|
|
1029
|
+
name,
|
|
1030
|
+
...action.title ? { title: action.title } : {},
|
|
1031
|
+
description: action.description,
|
|
1032
|
+
httpMethod: resolveActionHttpMethod(action),
|
|
1033
|
+
httpPath: resolveActionHttpPath(name, action),
|
|
1034
|
+
readOnly: isActionReadOnly(action),
|
|
1035
|
+
destructive: Boolean(action.destructive),
|
|
1036
|
+
retrySafe: Boolean(action.retrySafe),
|
|
1037
|
+
mcpExposed: action.agentTool !== false && action.mcpTool !== false,
|
|
1038
|
+
agentExposed: action.agentTool !== false,
|
|
1039
|
+
hasInputSchema: Boolean(action.schema),
|
|
1040
|
+
hasOutputSchema: Boolean(action.outputSchema)
|
|
1041
|
+
})),
|
|
1042
|
+
httpMethodMap: () => {
|
|
1043
|
+
const map = {};
|
|
1044
|
+
for (const [name, action] of Object.entries(actions)) {
|
|
1045
|
+
const method = resolveActionHttpMethod(action);
|
|
1046
|
+
if (method) map[name] = method;
|
|
1047
|
+
}
|
|
1048
|
+
return map;
|
|
1049
|
+
},
|
|
1050
|
+
resolveHttpAction: (relativePath) => httpRouteIndex.get(relativePath) ?? null,
|
|
1051
|
+
call: async (name, input, callOpts = {}) => {
|
|
1052
|
+
const caller = callOpts.caller ?? "server";
|
|
1053
|
+
const ctx = callOpts.ctx !== void 0 ? callOpts.ctx : await resolveContext({
|
|
1054
|
+
caller,
|
|
1055
|
+
source: caller,
|
|
1056
|
+
actionName: name,
|
|
1057
|
+
...callOpts.request ? { request: callOpts.request } : {},
|
|
1058
|
+
headers: new Headers(
|
|
1059
|
+
callOpts.headers ?? callOpts.request?.headers
|
|
1060
|
+
),
|
|
1061
|
+
...callOpts.signal ? { signal: callOpts.signal } : callOpts.request ? { signal: callOpts.request.signal } : {},
|
|
1062
|
+
env: readRuntimeEnv(),
|
|
1063
|
+
...callOpts.platform !== void 0 ? { platform: callOpts.platform } : {}
|
|
1064
|
+
});
|
|
1065
|
+
return await invokeWithContext(name, input, ctx, {
|
|
1066
|
+
caller,
|
|
1067
|
+
...callOpts.approvalToken !== void 0 ? { approvalToken: callOpts.approvalToken } : {},
|
|
1068
|
+
...callOpts.approved !== void 0 ? { approved: callOpts.approved } : {}
|
|
1069
|
+
});
|
|
1070
|
+
},
|
|
1071
|
+
invokeFromRequest,
|
|
1072
|
+
invokeFromCliOrStdio,
|
|
1073
|
+
invokeWithContext,
|
|
1074
|
+
fetchHandler: async () => new Response("Not initialized", { status: 500 }),
|
|
1075
|
+
mcpHandler: async () => new Response("Not initialized", { status: 500 }),
|
|
1076
|
+
handler: async () => new Response("Not initialized", { status: 500 }),
|
|
1077
|
+
createHandler: (combinedOptions = {}) => {
|
|
1078
|
+
const basePath = combinedOptions.basePath ?? "/api/agent-native";
|
|
1079
|
+
const actionBasePath = `${basePath.replace(/\/+$/, "")}/actions`;
|
|
1080
|
+
const actionFetch = createActionFetchHandler(registry, {
|
|
1081
|
+
...options.http,
|
|
1082
|
+
...combinedOptions.http,
|
|
1083
|
+
basePath: actionBasePath
|
|
1084
|
+
});
|
|
1085
|
+
const mcpEnabled = combinedOptions.mcp !== false;
|
|
1086
|
+
const mcpOpts = typeof combinedOptions.mcp === "object" ? { ...options.mcp, ...combinedOptions.mcp } : { ...options.mcp };
|
|
1087
|
+
const mcpFetch = mcpEnabled ? createMcpFetchHandler(registry, mcpOpts) : null;
|
|
1088
|
+
return async (request, override) => {
|
|
1089
|
+
const url = new URL(request.url);
|
|
1090
|
+
const rel = override?.pathSegments !== void 0 ? override.pathSegments.join("/") : stripBasePath(url.pathname, basePath);
|
|
1091
|
+
if (rel === "mcp" || rel.startsWith("mcp/")) {
|
|
1092
|
+
if (!mcpFetch) {
|
|
1093
|
+
return new Response(
|
|
1094
|
+
JSON.stringify({
|
|
1095
|
+
error: "MCP endpoint is disabled.",
|
|
1096
|
+
errorCode: "not_found"
|
|
1097
|
+
}),
|
|
1098
|
+
{
|
|
1099
|
+
status: 404,
|
|
1100
|
+
headers: { "Content-Type": "application/json; charset=utf-8" }
|
|
1101
|
+
}
|
|
1102
|
+
);
|
|
1103
|
+
}
|
|
1104
|
+
return mcpFetch(
|
|
1105
|
+
request,
|
|
1106
|
+
override?.platform !== void 0 ? { platform: override.platform } : void 0
|
|
1107
|
+
);
|
|
1108
|
+
}
|
|
1109
|
+
if (rel === "actions" || rel.startsWith("actions/")) {
|
|
1110
|
+
const actionPath = rel === "actions" ? "" : rel.slice("actions/".length);
|
|
1111
|
+
return actionFetch(request, {
|
|
1112
|
+
actionPath,
|
|
1113
|
+
...override?.platform !== void 0 ? { platform: override.platform } : {}
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
return new Response(
|
|
1117
|
+
JSON.stringify({
|
|
1118
|
+
error: `Unknown route "${rel}". Expected /actions/<name> or /mcp.`,
|
|
1119
|
+
errorCode: "not_found"
|
|
1120
|
+
}),
|
|
1121
|
+
{
|
|
1122
|
+
status: 404,
|
|
1123
|
+
headers: { "Content-Type": "application/json; charset=utf-8" }
|
|
1124
|
+
}
|
|
1125
|
+
);
|
|
1126
|
+
};
|
|
1127
|
+
}
|
|
1128
|
+
};
|
|
1129
|
+
registry.fetchHandler = createActionFetchHandler(registry, options.http);
|
|
1130
|
+
registry.mcpHandler = createMcpFetchHandler(registry, options.mcp);
|
|
1131
|
+
registry.handler = registry.createHandler();
|
|
1132
|
+
return registry;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
// src/skill.ts
|
|
1136
|
+
import fs2 from "fs";
|
|
1137
|
+
import path2 from "path";
|
|
1138
|
+
var AGENT_NATIVE_ACTIONS_SKILL_NAME = "agent-native-actions";
|
|
1139
|
+
var AGENT_NATIVE_ACTIONS_SKILL_RELATIVE_PATH = path2.join(
|
|
1140
|
+
".agents",
|
|
1141
|
+
"skills",
|
|
1142
|
+
AGENT_NATIVE_ACTIONS_SKILL_NAME,
|
|
1143
|
+
"SKILL.md"
|
|
1144
|
+
);
|
|
1145
|
+
var AGENT_NATIVE_ACTIONS_SKILL_MD = `---
|
|
1146
|
+
name: agent-native-actions
|
|
1147
|
+
description: Build and maintain backend operations with @agent-native/actions. Use whenever adding a new feature, endpoint, mutation, data fetch, CLI command, or AI tool in this app so UI, HTTP, CLI, MCP, and AI SDKs always share one typed action.
|
|
1148
|
+
---
|
|
1149
|
+
|
|
1150
|
+
# Agent-Native Actions
|
|
1151
|
+
|
|
1152
|
+
This repository uses \`@agent-native/actions\` as the single source of truth for application operations.
|
|
1153
|
+
|
|
1154
|
+
## Core Rule: Always Build New Capabilities as Actions
|
|
1155
|
+
|
|
1156
|
+
When adding any new backend feature, query, mutation, or integration:
|
|
1157
|
+
|
|
1158
|
+
1. **Create one file per operation in \`actions/<verb-noun>.ts\`** (for example \`actions/list-deals.ts\`, \`actions/create-invoice.ts\`, \`actions/refund-charge.ts\`).
|
|
1159
|
+
2. **Do not create parallel ad-hoc \`/api/*\` REST routes, Next.js Server Actions, tRPC procedures, or standalone database scripts** for normal app operations. Put the operation in \`actions/\` so your UI hooks, HTTP API, CLI, MCP server, and AI SDK tools automatically stay in parity.
|
|
1160
|
+
3. Reserve custom routes only for streaming responses, binary/file uploads, inbound third-party webhooks, OAuth callbacks, or non-JSON endpoints.
|
|
1161
|
+
|
|
1162
|
+
## Defining an Action
|
|
1163
|
+
|
|
1164
|
+
Use the app's typed \`defineAction\` helper from \`actions/context.ts\` if present (otherwise import \`defineAction\` from \`@agent-native/actions\`):
|
|
1165
|
+
|
|
1166
|
+
\`\`\`ts
|
|
1167
|
+
// actions/list-todos.ts
|
|
1168
|
+
import { z } from "zod";
|
|
1169
|
+
import { defineAction } from "./context"; // or "@agent-native/actions"
|
|
1170
|
+
|
|
1171
|
+
export default defineAction({
|
|
1172
|
+
description: "List todos for the current user",
|
|
1173
|
+
schema: z.object({
|
|
1174
|
+
done: z.boolean().optional().describe("Filter by completion status"),
|
|
1175
|
+
}),
|
|
1176
|
+
http: { method: "GET" },
|
|
1177
|
+
readOnly: true,
|
|
1178
|
+
authorize: (_input, ctx) => Boolean(ctx.user),
|
|
1179
|
+
run: async ({ done }, ctx) => {
|
|
1180
|
+
return db.todos.findMany({ where: { userId: ctx.user.id, done } });
|
|
1181
|
+
},
|
|
1182
|
+
});
|
|
1183
|
+
\`\`\`
|
|
1184
|
+
|
|
1185
|
+
### Action Authoring Checklist
|
|
1186
|
+
|
|
1187
|
+
- **Filename = action name:** \`actions/create-todo.ts\` becomes \`create-todo\`. Subfolders join with hyphens (\`actions/billing/refund.ts\` -> \`billing-refund\`). Prefix shared helpers with \`_\` (\`actions/_shared/db.ts\`) so they are not registered as actions.
|
|
1188
|
+
- **Describe every field:** Always provide a concise one-line \`description\` and \`.describe(...)\` on schema fields so the CLI \`--help\`, MCP clients, and AI agents know how to call the action.
|
|
1189
|
+
- **Mark reads explicitly:** Set \`http: { method: "GET" }\` and \`readOnly: true\` on read-only queries. Leave mutations on default \`POST\` (or \`PUT\` / \`DELETE\`).
|
|
1190
|
+
- **Enforce auth in \`authorize(input, ctx)\`:** Never trust UI hiding. Check \`ctx\` (resolved once in \`actions/context.ts\`) inside \`authorize(input, ctx)\` so HTTP, CLI, MCP, and AI callers all go through the same check.
|
|
1191
|
+
- **Gate sensitive writes with \`needsApproval\`:** For destructive, irreversible, or high-value mutations (deleting data, issuing refunds, sending external emails), set \`needsApproval: true\` or \`needsApproval: (input, ctx) => ...\` and \`destructive: true\`.
|
|
1192
|
+
- **Throw structured errors with \`fail()\` or \`defineActionErrors()\`:** Never throw bare strings or swallow errors into fake empty results. Use \`fail("Invoice not found", { statusCode: 404, errorCode: "not_found" })\`.
|
|
1193
|
+
- **Hide internal-only actions from external agents when needed:** Set \`mcpTool: false\` (or \`agentTool: false\`) on UI-only or internal admin operations.
|
|
1194
|
+
|
|
1195
|
+
## Calling Actions from UI Code
|
|
1196
|
+
|
|
1197
|
+
Use the typed client hooks for this repo's framework \u2014 never hand-write \`fetch("/api/...")\` calls for actions:
|
|
1198
|
+
|
|
1199
|
+
- **React / Next.js:** \`useActionQuery("list-todos", { done: false })\` and \`useActionMutation("create-todo")\` from \`@agent-native/actions/react\` (or \`@agent-native/actions/next\`)
|
|
1200
|
+
- **SolidJS:** \`createActionQuery\` / \`createActionMutation\` from \`@agent-native/actions/solid\`
|
|
1201
|
+
- **Vue / Nuxt:** \`useActionQuery\` / \`useActionMutation\` from \`@agent-native/actions/vue\`
|
|
1202
|
+
- **Svelte 5 / SvelteKit:** \`createActionQuery\` / \`createActionMutation\` from \`@agent-native/actions/svelte\`
|
|
1203
|
+
- **Plain TypeScript:** \`createActionClient()\` from \`@agent-native/actions/client\`
|
|
1204
|
+
|
|
1205
|
+
Mutations automatically invalidate related queries so views stay fresh without manual query-key plumbing.
|
|
1206
|
+
|
|
1207
|
+
## Regenerating Types & Verifying via CLI
|
|
1208
|
+
|
|
1209
|
+
After adding or changing actions:
|
|
1210
|
+
|
|
1211
|
+
1. Regenerate \`.generated/actions.ts\` and \`.generated/action-types.d.ts\` if the dev server is not running:
|
|
1212
|
+
\`\`\`bash
|
|
1213
|
+
npx @agent-native/actions generate
|
|
1214
|
+
\`\`\`
|
|
1215
|
+
2. Verify discovery and execution through the CLI:
|
|
1216
|
+
\`\`\`bash
|
|
1217
|
+
pnpm action --list
|
|
1218
|
+
pnpm action <action-name> --help
|
|
1219
|
+
pnpm action <action-name> '{"key":"value"}'
|
|
1220
|
+
\`\`\`
|
|
1221
|
+
`;
|
|
1222
|
+
function installActionsSkill(options) {
|
|
1223
|
+
const filePath = path2.join(
|
|
1224
|
+
options.projectRoot,
|
|
1225
|
+
AGENT_NATIVE_ACTIONS_SKILL_RELATIVE_PATH
|
|
1226
|
+
);
|
|
1227
|
+
const exists = fs2.existsSync(filePath);
|
|
1228
|
+
if (exists && !options.overwrite) {
|
|
1229
|
+
return {
|
|
1230
|
+
filePath,
|
|
1231
|
+
relativePath: AGENT_NATIVE_ACTIONS_SKILL_RELATIVE_PATH,
|
|
1232
|
+
status: "skipped"
|
|
1233
|
+
};
|
|
1234
|
+
}
|
|
1235
|
+
if (options.dryRun) {
|
|
1236
|
+
return {
|
|
1237
|
+
filePath,
|
|
1238
|
+
relativePath: AGENT_NATIVE_ACTIONS_SKILL_RELATIVE_PATH,
|
|
1239
|
+
status: exists ? "would-update" : "would-create"
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
fs2.mkdirSync(path2.dirname(filePath), { recursive: true });
|
|
1243
|
+
fs2.writeFileSync(filePath, AGENT_NATIVE_ACTIONS_SKILL_MD, "utf8");
|
|
1244
|
+
return {
|
|
1245
|
+
filePath,
|
|
1246
|
+
relativePath: AGENT_NATIVE_ACTIONS_SKILL_RELATIVE_PATH,
|
|
1247
|
+
status: exists ? "updated" : "created"
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
// src/cli.ts
|
|
1252
|
+
function parseCliArgs(argv) {
|
|
1253
|
+
const positionals = [];
|
|
1254
|
+
const flags = {};
|
|
1255
|
+
for (let i = 0; i < argv.length; i++) {
|
|
1256
|
+
const token = argv[i];
|
|
1257
|
+
if (token === void 0) continue;
|
|
1258
|
+
if (!token.startsWith("--")) {
|
|
1259
|
+
positionals.push(token);
|
|
1260
|
+
continue;
|
|
1261
|
+
}
|
|
1262
|
+
const stripped = token.slice(2);
|
|
1263
|
+
const eqIndex = stripped.indexOf("=");
|
|
1264
|
+
if (eqIndex !== -1) {
|
|
1265
|
+
const key = stripped.slice(0, eqIndex);
|
|
1266
|
+
const val = stripped.slice(eqIndex + 1);
|
|
1267
|
+
appendFlag(flags, key, val);
|
|
1268
|
+
continue;
|
|
1269
|
+
}
|
|
1270
|
+
const next = argv[i + 1];
|
|
1271
|
+
if (next !== void 0 && !next.startsWith("--")) {
|
|
1272
|
+
appendFlag(flags, stripped, next);
|
|
1273
|
+
i++;
|
|
1274
|
+
} else {
|
|
1275
|
+
flags[stripped] = true;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
return { positionals, flags };
|
|
1279
|
+
}
|
|
1280
|
+
function appendFlag(flags, key, value) {
|
|
1281
|
+
const existing = flags[key];
|
|
1282
|
+
if (existing === void 0 || typeof existing === "boolean") {
|
|
1283
|
+
flags[key] = value;
|
|
1284
|
+
} else if (Array.isArray(existing)) {
|
|
1285
|
+
existing.push(value);
|
|
1286
|
+
} else {
|
|
1287
|
+
flags[key] = [existing, value];
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
function loadEnvFiles(projectRoot) {
|
|
1291
|
+
const candidates = [".env", ".env.local"];
|
|
1292
|
+
for (const filename of candidates) {
|
|
1293
|
+
const filePath = path3.join(projectRoot, filename);
|
|
1294
|
+
if (!fs3.existsSync(filePath)) continue;
|
|
1295
|
+
const raw = fs3.readFileSync(filePath, "utf8");
|
|
1296
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
1297
|
+
const trimmed = line.trim();
|
|
1298
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
1299
|
+
const eq = trimmed.indexOf("=");
|
|
1300
|
+
if (eq === -1) continue;
|
|
1301
|
+
const key = trimmed.slice(0, eq).trim();
|
|
1302
|
+
let val = trimmed.slice(eq + 1).trim();
|
|
1303
|
+
if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
|
|
1304
|
+
val = val.slice(1, -1);
|
|
1305
|
+
}
|
|
1306
|
+
if (process.env[key] === void 0) {
|
|
1307
|
+
process.env[key] = val;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
function readTsconfigAliases(projectRoot) {
|
|
1313
|
+
const tsconfigPath = path3.join(projectRoot, "tsconfig.json");
|
|
1314
|
+
if (!fs3.existsSync(tsconfigPath)) return {};
|
|
1315
|
+
try {
|
|
1316
|
+
const raw = fs3.readFileSync(tsconfigPath, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");
|
|
1317
|
+
const parsed = JSON.parse(raw);
|
|
1318
|
+
const paths = parsed.compilerOptions?.paths;
|
|
1319
|
+
if (!paths) return {};
|
|
1320
|
+
const baseDir = path3.resolve(
|
|
1321
|
+
projectRoot,
|
|
1322
|
+
parsed.compilerOptions?.baseUrl ?? "."
|
|
1323
|
+
);
|
|
1324
|
+
const aliases = {};
|
|
1325
|
+
for (const [pattern, targets] of Object.entries(paths)) {
|
|
1326
|
+
const target = targets[0];
|
|
1327
|
+
if (!target) continue;
|
|
1328
|
+
const cleanPattern = pattern.endsWith("/*") ? pattern.slice(0, -1) : pattern;
|
|
1329
|
+
const cleanTarget = target.endsWith("/*") ? target.slice(0, -1) : target;
|
|
1330
|
+
aliases[cleanPattern] = path3.resolve(baseDir, cleanTarget);
|
|
1331
|
+
}
|
|
1332
|
+
return aliases;
|
|
1333
|
+
} catch {
|
|
1334
|
+
return {};
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
async function loadRegistry(projectRoot, options) {
|
|
1338
|
+
const jiti = createJiti(path3.join(projectRoot, "package.json"), {
|
|
1339
|
+
interopDefault: true,
|
|
1340
|
+
alias: readTsconfigAliases(projectRoot)
|
|
1341
|
+
});
|
|
1342
|
+
if (options.registryPath) {
|
|
1343
|
+
const absPath = path3.resolve(projectRoot, options.registryPath);
|
|
1344
|
+
const mod = await jiti.import(absPath);
|
|
1345
|
+
const registry = mod.actions ?? mod.default;
|
|
1346
|
+
if (!registry || typeof registry.call !== "function") {
|
|
1347
|
+
throw new Error(
|
|
1348
|
+
`Registry file ${absPath} must export \`actions\` (or default export) created with createActions().`
|
|
1349
|
+
);
|
|
1350
|
+
}
|
|
1351
|
+
return registry;
|
|
1352
|
+
}
|
|
1353
|
+
const scan = scanActionsDirectory(projectRoot, {
|
|
1354
|
+
...options.actionsDir ? { actionsDir: options.actionsDir } : {}
|
|
1355
|
+
});
|
|
1356
|
+
const loadedActions = {};
|
|
1357
|
+
for (const item of scan.actions) {
|
|
1358
|
+
const mod = await jiti.import(item.filePath);
|
|
1359
|
+
const candidate = mod.default ?? mod;
|
|
1360
|
+
if (!isDefinedAction(candidate)) {
|
|
1361
|
+
throw new Error(
|
|
1362
|
+
`Action file ${item.filePath} must default-export a defineAction() definition.`
|
|
1363
|
+
);
|
|
1364
|
+
}
|
|
1365
|
+
loadedActions[item.name] = candidate;
|
|
1366
|
+
}
|
|
1367
|
+
let createContext;
|
|
1368
|
+
if (scan.contextFile) {
|
|
1369
|
+
const ctxMod = await jiti.import(scan.contextFile);
|
|
1370
|
+
if (typeof ctxMod.createContext === "function") {
|
|
1371
|
+
createContext = ctxMod.createContext;
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
if (createContext) {
|
|
1375
|
+
return createActions({
|
|
1376
|
+
actions: loadedActions,
|
|
1377
|
+
createContext
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
return createActions({
|
|
1381
|
+
actions: loadedActions,
|
|
1382
|
+
createContext: (input) => input
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
function detectFramework(projectRoot) {
|
|
1386
|
+
const pkgPath = path3.join(projectRoot, "package.json");
|
|
1387
|
+
if (!fs3.existsSync(pkgPath)) return "node";
|
|
1388
|
+
try {
|
|
1389
|
+
const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf8"));
|
|
1390
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
1391
|
+
if ("next" in deps) return "next";
|
|
1392
|
+
if ("nuxt" in deps) return "nuxt";
|
|
1393
|
+
if ("@sveltejs/kit" in deps) return "sveltekit";
|
|
1394
|
+
if ("vite" in deps) return "vite";
|
|
1395
|
+
} catch {
|
|
1396
|
+
return "node";
|
|
1397
|
+
}
|
|
1398
|
+
return "node";
|
|
1399
|
+
}
|
|
1400
|
+
function runInit(projectRoot, options) {
|
|
1401
|
+
const framework = options.framework ?? detectFramework(projectRoot);
|
|
1402
|
+
const actionsDir = path3.join(projectRoot, "actions");
|
|
1403
|
+
const sampleActionPath = path3.join(actionsDir, "hello.ts");
|
|
1404
|
+
const plannedWrites = [];
|
|
1405
|
+
if (!fs3.existsSync(sampleActionPath)) {
|
|
1406
|
+
plannedWrites.push({
|
|
1407
|
+
filePath: sampleActionPath,
|
|
1408
|
+
note: "Sample action (callable via UI, HTTP, CLI, and MCP)",
|
|
1409
|
+
content: [
|
|
1410
|
+
'import { defineAction } from "@agent-native/actions";',
|
|
1411
|
+
'import { z } from "zod";',
|
|
1412
|
+
"",
|
|
1413
|
+
"export default defineAction({",
|
|
1414
|
+
' description: "Say hello from @agent-native/actions",',
|
|
1415
|
+
" schema: z.object({",
|
|
1416
|
+
' name: z.string().default("world").describe("Name to greet"),',
|
|
1417
|
+
" }),",
|
|
1418
|
+
' http: { method: "GET" },',
|
|
1419
|
+
" readOnly: true,",
|
|
1420
|
+
" run: async ({ name }) => ({ message: `Hello, ${name}!` }),",
|
|
1421
|
+
"});",
|
|
1422
|
+
""
|
|
1423
|
+
].join("\n")
|
|
1424
|
+
});
|
|
1425
|
+
}
|
|
1426
|
+
if (framework === "next") {
|
|
1427
|
+
const hasSrcApp = fs3.existsSync(path3.join(projectRoot, "src", "app"));
|
|
1428
|
+
const routePath = path3.join(
|
|
1429
|
+
projectRoot,
|
|
1430
|
+
hasSrcApp ? "src/app" : "app",
|
|
1431
|
+
"api/agent-native/[...path]/route.ts"
|
|
1432
|
+
);
|
|
1433
|
+
const manifestRel = hasSrcApp ? "../../../../../.generated/actions" : "../../../../.generated/actions";
|
|
1434
|
+
if (!fs3.existsSync(routePath)) {
|
|
1435
|
+
plannedWrites.push({
|
|
1436
|
+
filePath: routePath,
|
|
1437
|
+
note: "Single Next.js App Router catch-all serving /actions/* and /mcp",
|
|
1438
|
+
content: [
|
|
1439
|
+
'import { createNextHandler } from "@agent-native/actions/next";',
|
|
1440
|
+
`import { actions } from "${manifestRel}";`,
|
|
1441
|
+
"",
|
|
1442
|
+
"export const { GET, POST, PUT, PATCH, DELETE, OPTIONS } =",
|
|
1443
|
+
" createNextHandler(actions);",
|
|
1444
|
+
""
|
|
1445
|
+
].join("\n")
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
} else if (framework === "sveltekit") {
|
|
1449
|
+
const routePath = path3.join(
|
|
1450
|
+
projectRoot,
|
|
1451
|
+
"src/routes/api/agent-native/[...path]/+server.ts"
|
|
1452
|
+
);
|
|
1453
|
+
if (!fs3.existsSync(routePath)) {
|
|
1454
|
+
plannedWrites.push({
|
|
1455
|
+
filePath: routePath,
|
|
1456
|
+
note: "Single SvelteKit catch-all serving /actions/* and /mcp",
|
|
1457
|
+
content: [
|
|
1458
|
+
'import { createSvelteKitHandler } from "@agent-native/actions/svelte/server";',
|
|
1459
|
+
'import { actions } from "../../../../../.generated/actions";',
|
|
1460
|
+
"",
|
|
1461
|
+
"export const { GET, POST, PUT, PATCH, DELETE, OPTIONS } =",
|
|
1462
|
+
" createSvelteKitHandler(actions);",
|
|
1463
|
+
""
|
|
1464
|
+
].join("\n")
|
|
1465
|
+
});
|
|
1466
|
+
}
|
|
1467
|
+
} else if (framework === "nuxt") {
|
|
1468
|
+
const routePath = path3.join(
|
|
1469
|
+
projectRoot,
|
|
1470
|
+
"server/api/agent-native/[...path].ts"
|
|
1471
|
+
);
|
|
1472
|
+
if (!fs3.existsSync(routePath)) {
|
|
1473
|
+
plannedWrites.push({
|
|
1474
|
+
filePath: routePath,
|
|
1475
|
+
note: "Single Nuxt/Nitro catch-all serving /actions/* and /mcp",
|
|
1476
|
+
content: [
|
|
1477
|
+
'import { createNitroHandler } from "@agent-native/actions/vue/server";',
|
|
1478
|
+
'import { actions } from "../../../.generated/actions";',
|
|
1479
|
+
"",
|
|
1480
|
+
"export default createNitroHandler(actions);",
|
|
1481
|
+
""
|
|
1482
|
+
].join("\n")
|
|
1483
|
+
});
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
console.error(
|
|
1487
|
+
`[@agent-native/actions] Detected framework: ${framework}${options.dryRun ? " (dry-run)" : ""}`
|
|
1488
|
+
);
|
|
1489
|
+
for (const write of plannedWrites) {
|
|
1490
|
+
const rel = path3.relative(projectRoot, write.filePath);
|
|
1491
|
+
if (options.dryRun) {
|
|
1492
|
+
console.error(` [would create] ${rel} \u2014 ${write.note}`);
|
|
1493
|
+
} else {
|
|
1494
|
+
fs3.mkdirSync(path3.dirname(write.filePath), { recursive: true });
|
|
1495
|
+
fs3.writeFileSync(write.filePath, write.content, "utf8");
|
|
1496
|
+
console.error(` [created] ${rel} \u2014 ${write.note}`);
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
const pkgPath = path3.join(projectRoot, "package.json");
|
|
1500
|
+
if (fs3.existsSync(pkgPath)) {
|
|
1501
|
+
const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf8"));
|
|
1502
|
+
pkg.scripts ??= {};
|
|
1503
|
+
if (!pkg.scripts["action"]) {
|
|
1504
|
+
if (options.dryRun) {
|
|
1505
|
+
console.error(
|
|
1506
|
+
' [would update] package.json \u2014 add `"action": "actions"` script'
|
|
1507
|
+
);
|
|
1508
|
+
} else {
|
|
1509
|
+
pkg.scripts["action"] = "actions";
|
|
1510
|
+
fs3.writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}
|
|
1511
|
+
`, "utf8");
|
|
1512
|
+
console.error(
|
|
1513
|
+
' [updated] package.json \u2014 added `"action": "actions"` script'
|
|
1514
|
+
);
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
if (!options.dryRun) {
|
|
1519
|
+
const generated = generateActionArtifacts({ projectRoot });
|
|
1520
|
+
console.error(
|
|
1521
|
+
` [generated] ${path3.relative(projectRoot, generated.manifestPath)} & ${path3.relative(projectRoot, generated.typesPath)} (${generated.actionCount} action(s))`
|
|
1522
|
+
);
|
|
1523
|
+
}
|
|
1524
|
+
const skillResult = installActionsSkill({
|
|
1525
|
+
projectRoot,
|
|
1526
|
+
dryRun: options.dryRun === true
|
|
1527
|
+
});
|
|
1528
|
+
if (skillResult.status === "created") {
|
|
1529
|
+
console.error(
|
|
1530
|
+
` [created] ${skillResult.relativePath} \u2014 agent skill teaching coding agents to build new features as actions`
|
|
1531
|
+
);
|
|
1532
|
+
} else if (skillResult.status === "would-create") {
|
|
1533
|
+
console.error(
|
|
1534
|
+
` [would create] ${skillResult.relativePath} \u2014 agent skill teaching coding agents to build new features as actions`
|
|
1535
|
+
);
|
|
1536
|
+
}
|
|
1537
|
+
if (framework === "next") {
|
|
1538
|
+
console.error(
|
|
1539
|
+
"\nNext step: wrap next.config.ts with `withAgentNativeActions()` from `@agent-native/actions/next/config`."
|
|
1540
|
+
);
|
|
1541
|
+
} else if (framework === "vite" || framework === "sveltekit") {
|
|
1542
|
+
console.error(
|
|
1543
|
+
"\nNext step: add `agentNativeActionsPlugin()` from `@agent-native/actions/vite` to vite.config.ts."
|
|
1544
|
+
);
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
function coerceCliInput(flags, jsonArg) {
|
|
1548
|
+
if (jsonArg !== void 0) {
|
|
1549
|
+
const parsed = JSON.parse(jsonArg);
|
|
1550
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1551
|
+
throw new Error(
|
|
1552
|
+
`JSON argument must be an object, e.g. '{"title":"Ship"}'.`
|
|
1553
|
+
);
|
|
1554
|
+
}
|
|
1555
|
+
return parsed;
|
|
1556
|
+
}
|
|
1557
|
+
const input = {};
|
|
1558
|
+
const reserved = /* @__PURE__ */ new Set([
|
|
1559
|
+
"registry",
|
|
1560
|
+
"dir",
|
|
1561
|
+
"cwd",
|
|
1562
|
+
"help",
|
|
1563
|
+
"list",
|
|
1564
|
+
"approved",
|
|
1565
|
+
"remote",
|
|
1566
|
+
"token",
|
|
1567
|
+
"dry-run",
|
|
1568
|
+
"framework"
|
|
1569
|
+
]);
|
|
1570
|
+
for (const [key, value] of Object.entries(flags)) {
|
|
1571
|
+
if (reserved.has(key)) continue;
|
|
1572
|
+
if (value === "true") {
|
|
1573
|
+
input[key] = true;
|
|
1574
|
+
} else if (value === "false") {
|
|
1575
|
+
input[key] = false;
|
|
1576
|
+
} else if (typeof value === "string" && /^-?\d+(?:\.\d+)?$/.test(value)) {
|
|
1577
|
+
input[key] = Number(value);
|
|
1578
|
+
} else {
|
|
1579
|
+
input[key] = value;
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
return input;
|
|
1583
|
+
}
|
|
1584
|
+
async function promptInteractiveApproval(actionName, input) {
|
|
1585
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
1586
|
+
return false;
|
|
1587
|
+
}
|
|
1588
|
+
const rl = readline.createInterface({
|
|
1589
|
+
input: process.stdin,
|
|
1590
|
+
output: process.stderr
|
|
1591
|
+
});
|
|
1592
|
+
return new Promise((resolve) => {
|
|
1593
|
+
rl.question(
|
|
1594
|
+
`Action "${actionName}" requires approval.
|
|
1595
|
+
Input: ${JSON.stringify(input)}
|
|
1596
|
+
Approve and run? [y/N] `,
|
|
1597
|
+
(answer) => {
|
|
1598
|
+
rl.close();
|
|
1599
|
+
const normalized = answer.trim().toLowerCase();
|
|
1600
|
+
resolve(normalized === "y" || normalized === "yes");
|
|
1601
|
+
}
|
|
1602
|
+
);
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
async function runActionCli(argv) {
|
|
1606
|
+
const { positionals, flags } = parseCliArgs(argv);
|
|
1607
|
+
const projectRoot = typeof flags["cwd"] === "string" ? path3.resolve(flags["cwd"]) : process.cwd();
|
|
1608
|
+
const registryPath = typeof flags["registry"] === "string" ? flags["registry"] : void 0;
|
|
1609
|
+
const actionsDir = typeof flags["dir"] === "string" ? flags["dir"] : void 0;
|
|
1610
|
+
const command = positionals[0];
|
|
1611
|
+
if (command === "init") {
|
|
1612
|
+
const fw = typeof flags["framework"] === "string" ? flags["framework"] : void 0;
|
|
1613
|
+
runInit(projectRoot, {
|
|
1614
|
+
dryRun: flags["dry-run"] === true,
|
|
1615
|
+
...fw ? { framework: fw } : {}
|
|
1616
|
+
});
|
|
1617
|
+
return 0;
|
|
1618
|
+
}
|
|
1619
|
+
if (command === "skill") {
|
|
1620
|
+
if (flags["print"] === true) {
|
|
1621
|
+
process.stdout.write(AGENT_NATIVE_ACTIONS_SKILL_MD);
|
|
1622
|
+
return 0;
|
|
1623
|
+
}
|
|
1624
|
+
const result = installActionsSkill({
|
|
1625
|
+
projectRoot,
|
|
1626
|
+
dryRun: flags["dry-run"] === true,
|
|
1627
|
+
overwrite: flags["force"] === true
|
|
1628
|
+
});
|
|
1629
|
+
console.error(` [${result.status}] ${result.relativePath}`);
|
|
1630
|
+
return 0;
|
|
1631
|
+
}
|
|
1632
|
+
if (command === "generate") {
|
|
1633
|
+
const res = generateActionArtifacts({
|
|
1634
|
+
projectRoot,
|
|
1635
|
+
...actionsDir ? { actionsDir } : {}
|
|
1636
|
+
});
|
|
1637
|
+
console.log(
|
|
1638
|
+
JSON.stringify(
|
|
1639
|
+
{
|
|
1640
|
+
manifestPath: path3.relative(projectRoot, res.manifestPath),
|
|
1641
|
+
typesPath: path3.relative(projectRoot, res.typesPath),
|
|
1642
|
+
actionCount: res.actionCount,
|
|
1643
|
+
hasContextFile: res.hasContextFile
|
|
1644
|
+
},
|
|
1645
|
+
null,
|
|
1646
|
+
2
|
|
1647
|
+
)
|
|
1648
|
+
);
|
|
1649
|
+
return 0;
|
|
1650
|
+
}
|
|
1651
|
+
loadEnvFiles(projectRoot);
|
|
1652
|
+
if (command === "mcp") {
|
|
1653
|
+
const registry2 = await loadRegistry(projectRoot, {
|
|
1654
|
+
...registryPath ? { registryPath } : {},
|
|
1655
|
+
...actionsDir ? { actionsDir } : {}
|
|
1656
|
+
});
|
|
1657
|
+
await runStdioMcpServer(registry2);
|
|
1658
|
+
return 0;
|
|
1659
|
+
}
|
|
1660
|
+
if (typeof flags["remote"] === "string" && command) {
|
|
1661
|
+
const input2 = coerceCliInput(flags, positionals[1]);
|
|
1662
|
+
const token = typeof flags["token"] === "string" ? flags["token"] : void 0;
|
|
1663
|
+
const client = createActionClient({
|
|
1664
|
+
baseUrl: flags["remote"],
|
|
1665
|
+
...token ? { headers: { Authorization: `Bearer ${token}` } } : {}
|
|
1666
|
+
});
|
|
1667
|
+
const result = await client.call(command, input2);
|
|
1668
|
+
console.log(JSON.stringify(result ?? null, null, 2));
|
|
1669
|
+
return 0;
|
|
1670
|
+
}
|
|
1671
|
+
const registry = await loadRegistry(projectRoot, {
|
|
1672
|
+
...registryPath ? { registryPath } : {},
|
|
1673
|
+
...actionsDir ? { actionsDir } : {}
|
|
1674
|
+
});
|
|
1675
|
+
if (command === "inspect") {
|
|
1676
|
+
console.log(
|
|
1677
|
+
JSON.stringify(
|
|
1678
|
+
{
|
|
1679
|
+
projectRoot,
|
|
1680
|
+
actions: registry.describe()
|
|
1681
|
+
},
|
|
1682
|
+
null,
|
|
1683
|
+
2
|
|
1684
|
+
)
|
|
1685
|
+
);
|
|
1686
|
+
return 0;
|
|
1687
|
+
}
|
|
1688
|
+
if (!command || flags["list"] === true || command === "list") {
|
|
1689
|
+
const list = registry.describe();
|
|
1690
|
+
if (list.length === 0) {
|
|
1691
|
+
console.log(
|
|
1692
|
+
"No actions found. Run `npx @agent-native/actions init` to create one."
|
|
1693
|
+
);
|
|
1694
|
+
return 0;
|
|
1695
|
+
}
|
|
1696
|
+
for (const item of list) {
|
|
1697
|
+
const verb = item.httpMethod ?? "NO-HTTP";
|
|
1698
|
+
console.log(`${item.name.padEnd(28)} [${verb}] ${item.description}`);
|
|
1699
|
+
}
|
|
1700
|
+
return 0;
|
|
1701
|
+
}
|
|
1702
|
+
const action = registry.actions[command];
|
|
1703
|
+
if (!action) {
|
|
1704
|
+
console.error(
|
|
1705
|
+
`Action "${command}" not found. Available: ${registry.list().join(", ") || "(none)"}`
|
|
1706
|
+
);
|
|
1707
|
+
return 1;
|
|
1708
|
+
}
|
|
1709
|
+
if (flags["help"] === true) {
|
|
1710
|
+
console.log(`${command} \u2014 ${action.description}`);
|
|
1711
|
+
const jsonSchema = schemaToJsonSchema(
|
|
1712
|
+
action.schema,
|
|
1713
|
+
"input",
|
|
1714
|
+
action.toolSchema
|
|
1715
|
+
);
|
|
1716
|
+
if (jsonSchema) {
|
|
1717
|
+
console.log("\nInput JSON Schema:");
|
|
1718
|
+
console.log(JSON.stringify(jsonSchema, null, 2));
|
|
1719
|
+
}
|
|
1720
|
+
return 0;
|
|
1721
|
+
}
|
|
1722
|
+
const input = coerceCliInput(flags, positionals[1]);
|
|
1723
|
+
const approvalFlag = flags["approved"] === true;
|
|
1724
|
+
try {
|
|
1725
|
+
const result = await registry.invokeFromCliOrStdio(command, input, {
|
|
1726
|
+
caller: "cli",
|
|
1727
|
+
approved: approvalFlag
|
|
1728
|
+
});
|
|
1729
|
+
console.log(JSON.stringify(result ?? null, null, 2));
|
|
1730
|
+
return 0;
|
|
1731
|
+
} catch (error) {
|
|
1732
|
+
if (isActionError(error) && error.errorCode === "approval_required") {
|
|
1733
|
+
const confirmed = await promptInteractiveApproval(command, input);
|
|
1734
|
+
if (confirmed) {
|
|
1735
|
+
const result = await registry.invokeFromCliOrStdio(command, input, {
|
|
1736
|
+
caller: "cli",
|
|
1737
|
+
approved: true
|
|
1738
|
+
});
|
|
1739
|
+
console.log(JSON.stringify(result ?? null, null, 2));
|
|
1740
|
+
return 0;
|
|
1741
|
+
}
|
|
1742
|
+
console.error(
|
|
1743
|
+
`Approval required for "${command}". Confirm with a human and re-run with --approved.`
|
|
1744
|
+
);
|
|
1745
|
+
return 2;
|
|
1746
|
+
}
|
|
1747
|
+
const { body } = serializeActionErrorBody(error);
|
|
1748
|
+
console.error(JSON.stringify(body, null, 2));
|
|
1749
|
+
return 1;
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
var isDirectExecution = typeof process !== "undefined" && process.argv[1] !== void 0 && path3.resolve(process.argv[1]) === path3.resolve(fileURLToPath(import.meta.url));
|
|
1753
|
+
if (isDirectExecution) {
|
|
1754
|
+
runActionCli(process.argv.slice(2)).then((code) => {
|
|
1755
|
+
if (code !== 0) process.exit(code);
|
|
1756
|
+
}).catch((err) => {
|
|
1757
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
1758
|
+
process.exit(1);
|
|
1759
|
+
});
|
|
1760
|
+
}
|
|
1761
|
+
export {
|
|
1762
|
+
parseCliArgs,
|
|
1763
|
+
runActionCli
|
|
1764
|
+
};
|
|
1765
|
+
//# sourceMappingURL=cli.js.map
|