@h-ai/tools 0.0.0-stage → 1.0.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +202 -0
  2. package/README.en.md +37 -0
  3. package/README.ja.md +37 -0
  4. package/README.md +36 -2
  5. package/dist/chunk-UA7MOYTT.js +413 -0
  6. package/dist/chunk-UA7MOYTT.js.map +1 -0
  7. package/dist/index.d.ts +16 -0
  8. package/dist/index.js +3 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/server/index.d.ts +306 -0
  11. package/dist/server/index.js +1051 -0
  12. package/dist/server/index.js.map +1 -0
  13. package/dist/tools-types-CM0lGuJr.d.ts +199 -0
  14. package/jobs/.dockerignore +4 -0
  15. package/jobs/README.md +223 -0
  16. package/jobs/archives.py +56 -0
  17. package/jobs/browser/Dockerfile +20 -0
  18. package/jobs/browser/operation.py +17 -0
  19. package/jobs/browser/render.mjs +90 -0
  20. package/jobs/browser_policy.py +36 -0
  21. package/jobs/documents/Dockerfile +23 -0
  22. package/jobs/documents/generate.py +165 -0
  23. package/jobs/documents/operation.py +84 -0
  24. package/jobs/documents/requirements.txt +3 -0
  25. package/jobs/hyperframes-runtime.mjs +73 -0
  26. package/jobs/media_files.py +78 -0
  27. package/jobs/ocr/Dockerfile +19 -0
  28. package/jobs/ocr/operation.py +18 -0
  29. package/jobs/office/Dockerfile +21 -0
  30. package/jobs/office/office_job.py +65 -0
  31. package/jobs/office/operation.py +43 -0
  32. package/jobs/preview_build/Dockerfile +19 -0
  33. package/jobs/preview_build/build.mjs +552 -0
  34. package/jobs/preview_build/operation.py +62 -0
  35. package/jobs/preview_build/package.json +11 -0
  36. package/jobs/tests/image-smoke.mjs +83 -0
  37. package/jobs/tests/requirements.txt +4 -0
  38. package/jobs/tests/test_documents_generate.py +107 -0
  39. package/jobs/tests/test_hai_tool.py +82 -0
  40. package/jobs/tests/test_media_jobs.py +449 -0
  41. package/jobs/tests/test_preview_build.py +213 -0
  42. package/jobs/tool.py +145 -0
  43. package/jobs/video_render/Dockerfile +20 -0
  44. package/jobs/video_render/operation.py +109 -0
  45. package/jobs/video_render/render.mjs +36 -0
  46. package/jobs/web_capture/Dockerfile +20 -0
  47. package/jobs/web_capture/capture.mjs +122 -0
  48. package/jobs/web_capture/operation.py +65 -0
  49. package/package.json +62 -3
@@ -0,0 +1,1051 @@
1
+ import { tools, toolsM, HaiToolsError } from '../chunk-UA7MOYTT.js';
2
+ import { createHash } from 'crypto';
3
+ import { core, ok, err } from '@h-ai/core';
4
+ import { z } from 'zod';
5
+ import { Buffer } from 'buffer';
6
+ import { isIPv4 } from 'net';
7
+ import { extname } from 'path';
8
+ import { setTimeout } from 'timers/promises';
9
+
10
+ function createArtifactTools({ context, files }) {
11
+ const binding = (signal) => ({ ...context, signal });
12
+ const identifier = z.string().min(1).max(200).meta({
13
+ format: "artifact-id",
14
+ title: toolsM("tools_field_id")
15
+ });
16
+ const title = z.string().trim().min(1).max(160).meta({
17
+ title: toolsM("tools_field_title")
18
+ });
19
+ const content = z.string().max(1024 * 1024).meta({
20
+ title: toolsM("tools_field_content")
21
+ });
22
+ const editable = z.enum(["markdown", "html", "table", "chart"]).meta({
23
+ title: toolsM("tools_field_kind")
24
+ });
25
+ const mediaType = (kind) => kind === "markdown" ? "text/markdown" : kind === "html" ? "text/html" : "application/json";
26
+ const invalid2 = () => err(HaiToolsError.VALIDATION_FAILED, toolsM("tools_validationFailed"));
27
+ const publish = (signal, name, kind, text, output) => files.publish(binding(signal), {
28
+ ...context.execution ? {
29
+ id: identifierFor(context.execution.id, output)
30
+ } : {},
31
+ name,
32
+ kind,
33
+ mediaType: mediaType(kind),
34
+ data: new TextEncoder().encode(text)
35
+ });
36
+ const definitions = [
37
+ tools.define({
38
+ name: "artifact_create",
39
+ title: toolsM("tools_artifactCreate"),
40
+ description: toolsM("tools_artifactCreateDescription"),
41
+ examples: [
42
+ {
43
+ label: toolsM("tools_example_markdown"),
44
+ input: {
45
+ title: toolsM("tools_example_noteTitle"),
46
+ kind: "markdown",
47
+ content: toolsM("tools_example_noteContent")
48
+ }
49
+ }
50
+ ],
51
+ parameters: z.object({ title, kind: editable, content }),
52
+ resultHandler: async (input, { signal }) => {
53
+ if (input.kind === "table" || input.kind === "chart") {
54
+ try {
55
+ if (!z.record(z.string(), z.unknown()).safeParse(JSON.parse(input.content)).success)
56
+ return invalid2();
57
+ } catch {
58
+ return invalid2();
59
+ }
60
+ }
61
+ return publish(signal, input.title, input.kind, input.content, "artifact_create:artifact");
62
+ }
63
+ }),
64
+ tools.define({
65
+ name: "artifact_read",
66
+ title: toolsM("tools_artifactRead"),
67
+ description: toolsM("tools_artifactReadDescription"),
68
+ parameters: z.object({ id: identifier }),
69
+ resultHandler: async (input, { signal }) => {
70
+ const file = await files.read(binding(signal), input);
71
+ if (!file.success)
72
+ return file;
73
+ if (file.data.data.byteLength > 1024 * 1024 || !/^(?:text\/(?:markdown|html|plain)|application\/json)$/u.test(file.data.mediaType))
74
+ return invalid2();
75
+ try {
76
+ return ok({
77
+ id: file.data.id,
78
+ ...file.data.version === void 0 ? {} : { version: file.data.version },
79
+ content: new TextDecoder("utf-8", { fatal: true }).decode(file.data.data)
80
+ });
81
+ } catch {
82
+ return invalid2();
83
+ }
84
+ }
85
+ }),
86
+ tools.define({
87
+ name: "data_analyze",
88
+ title: toolsM("tools_dataAnalyze"),
89
+ description: toolsM("tools_dataAnalyzeDescription"),
90
+ examples: [
91
+ {
92
+ label: toolsM("tools_example_sales"),
93
+ input: {
94
+ title: toolsM("tools_example_sales"),
95
+ rows: [
96
+ { month: "Jan", sales: 10 },
97
+ { month: "Feb", sales: 20 }
98
+ ],
99
+ x: "month",
100
+ y: "sales",
101
+ chartType: "bar"
102
+ }
103
+ }
104
+ ],
105
+ parameters: z.object({
106
+ title,
107
+ rows: z.array(z.record(z.string().min(1).max(100), z.union([
108
+ z.string().max(4e3),
109
+ z.number().finite()
110
+ ]))).min(1).max(2e3).meta({
111
+ title: toolsM("tools_field_rows")
112
+ }),
113
+ x: z.string().min(1).max(100).meta({
114
+ title: toolsM("tools_field_x")
115
+ }),
116
+ y: z.string().min(1).max(100).meta({
117
+ title: toolsM("tools_field_y")
118
+ }),
119
+ chartType: z.enum([
120
+ "bar",
121
+ "line",
122
+ "area",
123
+ "pie",
124
+ "scatter"
125
+ ]).default("bar").meta({
126
+ title: toolsM("tools_field_chartType")
127
+ })
128
+ }),
129
+ resultHandler: async (input, { signal }) => {
130
+ const values = input.rows.map((row) => row[input.y]);
131
+ if (values.some((value) => typeof value !== "number") || input.rows.some((row) => !(input.x in row)))
132
+ return invalid2();
133
+ const numbers = z.array(z.number().finite()).parse(values);
134
+ const sum = numbers.reduce((sum2, value) => sum2 + value, 0);
135
+ if (!Number.isFinite(sum))
136
+ return invalid2();
137
+ const keys = [
138
+ ...new Set(input.rows.flatMap((row) => Object.keys(row)))
139
+ ];
140
+ if (keys.length > 50)
141
+ return invalid2();
142
+ let rowColumn = "source_row_id";
143
+ while (keys.includes(rowColumn))
144
+ rowColumn = `${rowColumn}_source`;
145
+ const keyFor = (key) => key === "row_id" ? rowColumn : key;
146
+ const table = await publish(signal, `${input.title.slice(0, 149)}.table.json`, "table", JSON.stringify({
147
+ table_columns: keys.map((key) => ({
148
+ key: keyFor(key),
149
+ label: key,
150
+ type: input.rows.every((row) => typeof row[key] === "number") ? "number" : "text"
151
+ })),
152
+ table_rows: input.rows.map((row, index) => ({
153
+ ...Object.fromEntries(Object.entries(row).map(([key, value]) => [
154
+ keyFor(key),
155
+ value
156
+ ])),
157
+ row_id: `row-${index + 1}`
158
+ }))
159
+ }), "data_analyze:table");
160
+ if (!table.success)
161
+ return table;
162
+ const chart = await publish(signal, `${input.title.slice(0, 149)}.chart.json`, "chart", JSON.stringify({
163
+ type: input.chartType,
164
+ data: input.rows,
165
+ x: input.x,
166
+ y: input.y
167
+ }), "data_analyze:chart");
168
+ if (!chart.success)
169
+ return chart;
170
+ return ok({
171
+ statistics: {
172
+ count: numbers.length,
173
+ sum,
174
+ mean: sum / numbers.length,
175
+ min: Math.min(...numbers),
176
+ max: Math.max(...numbers)
177
+ },
178
+ artifacts: [table.data, chart.data]
179
+ });
180
+ }
181
+ })
182
+ ];
183
+ if (files.save) {
184
+ const save = files.save;
185
+ definitions.push(tools.define({
186
+ name: "artifact_save",
187
+ title: toolsM("tools_artifactSave"),
188
+ description: toolsM("tools_artifactSaveDescription"),
189
+ parameters: z.object({
190
+ id: identifier,
191
+ baseVersion: z.number().int().positive().meta({
192
+ title: toolsM("tools_field_baseVersion")
193
+ }),
194
+ content
195
+ }),
196
+ resultHandler: (input, { signal }) => save(binding(signal), input)
197
+ }));
198
+ }
199
+ return {
200
+ tools: definitions,
201
+ groups: [
202
+ {
203
+ id: "documents",
204
+ title: toolsM("tools_documents"),
205
+ tools: ["artifact_create", "artifact_read", "artifact_save"]
206
+ },
207
+ {
208
+ id: "analysis",
209
+ title: toolsM("tools_dataAnalyze"),
210
+ tools: ["data_analyze"]
211
+ }
212
+ ]
213
+ };
214
+ }
215
+ function identifierFor(executionId, output) {
216
+ const digest = createHash("sha256").update(`${executionId}:${output}`).digest("hex");
217
+ return `${digest.slice(0, 8)}-${digest.slice(8, 12)}-4${digest.slice(13, 16)}-8${digest.slice(17, 20)}-${digest.slice(20, 32)}`;
218
+ }
219
+ var jobTitles = {
220
+ "documents.extract": "tools_job_documents_extract",
221
+ "documents.generate": "tools_job_documents_generate",
222
+ "office.convert": "tools_job_office_convert",
223
+ "office.recalculate": "tools_job_office_recalculate",
224
+ "ocr.recognize": "tools_job_ocr_recognize",
225
+ "browser.navigate": "tools_job_browser_navigate",
226
+ "web.capture": "tools_job_web_capture",
227
+ "preview.build": "tools_job_preview_build",
228
+ "video.render": "tools_job_video_render"
229
+ };
230
+ function createJobTools({ context, files, runner, environments, browserProxy }) {
231
+ const proxy = browserProxy === void 0 ? void 0 : browserProxyAddress(browserProxy);
232
+ const definitions = [];
233
+ const bindings = {};
234
+ const groups = /* @__PURE__ */ new Map();
235
+ const fileId = z.string().min(1).max(200).meta({
236
+ format: "artifact-id",
237
+ title: toolsM("tools_field_fileId")
238
+ });
239
+ const url = z.url().max(4096).refine((value) => {
240
+ const parsed = new URL(value);
241
+ return parsed.protocol === "https:" && !parsed.username && !parsed.password && !parsed.port && /^(?:[a-z0-9-]+\.)+[a-z][a-z0-9-]+$/iu.test(parsed.hostname) && !/(?:^|\.)(?:localhost|local|internal|test|invalid)$/iu.test(parsed.hostname);
242
+ }).meta({
243
+ title: toolsM("tools_field_url")
244
+ });
245
+ const safeName = /^[a-z0-9][\w.-]{0,127}$/iu;
246
+ const response = z.union([
247
+ z.object({
248
+ success: z.literal(true),
249
+ data: z.object({
250
+ text: z.string().max(256 * 1024).optional(),
251
+ artifact: z.object({
252
+ name: z.string().regex(safeName),
253
+ bytes: z.number().int().positive().max(50 * 1024 * 1024)
254
+ }).optional(),
255
+ summary: z.object({
256
+ sourceUrl: z.url(),
257
+ title: z.string().max(2048),
258
+ text: z.string().max(256 * 1024)
259
+ }).passthrough().optional()
260
+ })
261
+ }),
262
+ z.object({
263
+ success: z.literal(false),
264
+ error: z.object({
265
+ code: z.string().regex(/^[A-Z_]{1,64}$/u),
266
+ message: z.string().max(2048)
267
+ })
268
+ })
269
+ ]);
270
+ const command = 'import subprocess,sys\np=subprocess.run(["/usr/local/bin/hai-tool"],input=sys.argv[1].encode("utf-8"))\nif p.returncode: sys.exit(1)\nsys.stdin.buffer.read(1)';
271
+ const logger2 = core.logger.child({ module: "tools", scope: "jobs" });
272
+ function add(group, operation, parameters, prepare) {
273
+ const environmentId = environments[group];
274
+ const networked = group === "web" || group === "browser";
275
+ if (!environmentId || networked && !proxy)
276
+ return;
277
+ const name = operation.replaceAll(".", "_");
278
+ bindings[name] = environmentId;
279
+ const category = group === "office" || group === "ocr" ? "documents" : group === "browser" || group === "preview" ? "web" : group;
280
+ groups.set(category, [
281
+ ...groups.get(category) ?? [],
282
+ name
283
+ ]);
284
+ definitions.push(tools.define({
285
+ name,
286
+ title: toolsM(jobTitles[operation]),
287
+ description: toolsM(jobTitles[operation]),
288
+ ...operation === "documents.generate" ? {
289
+ examples: [
290
+ {
291
+ label: toolsM("tools_example_report"),
292
+ input: {
293
+ format: "docx",
294
+ title: toolsM("tools_example_report"),
295
+ paragraphs: [
296
+ toolsM("tools_example_reportContent")
297
+ ]
298
+ }
299
+ }
300
+ ]
301
+ } : {},
302
+ parameters,
303
+ timeoutMs: 3e5,
304
+ resultHandler: async (input, { signal }) => {
305
+ const fail = () => err(HaiToolsError.EXECUTION_FAILED, toolsM("tools_executionFailed"));
306
+ const environment = runner.environment(environmentId);
307
+ if (!context.execution || !environment.success || !environment.data.capabilities.includes(operation) || environment.data.networkPolicy !== (group === "web" || group === "browser" ? "internal" : "offline")) {
308
+ return err(HaiToolsError.FORBIDDEN, toolsM("tools_forbidden"));
309
+ }
310
+ const spec = prepare(input);
311
+ const inputs = {};
312
+ if (spec.source) {
313
+ const file = await files.read({ ...context, signal }, { id: spec.source });
314
+ if (!file.success)
315
+ return file;
316
+ const extension = extname(file.data.name).toLowerCase();
317
+ if (!/^\.[a-z0-9]{1,8}$/u.test(extension) || file.data.data.byteLength > 50 * 1024 * 1024)
318
+ return fail();
319
+ if (operation === "office.recalculate") {
320
+ if (extension !== ".xlsx" && extension !== ".ods")
321
+ return fail();
322
+ spec.output = `result${extension}`;
323
+ spec.mediaType = extension === ".ods" ? "application/vnd.oasis.opendocument.spreadsheet" : spec.mediaType;
324
+ }
325
+ spec.request.input = `source${extension}`;
326
+ inputs[`source${extension}`] = Buffer.from(file.data.data).toString("base64");
327
+ }
328
+ if (spec.inline !== void 0) {
329
+ inputs["source.json"] = Buffer.from(spec.inline).toString("base64");
330
+ spec.request.input = "source.json";
331
+ }
332
+ if (spec.output)
333
+ spec.request.output = spec.output;
334
+ const request = JSON.stringify({ operation, ...spec.request });
335
+ if (Buffer.byteLength(request) > 64 * 1024)
336
+ return fail();
337
+ signal.throwIfAborted();
338
+ const started = await context.execution.start({
339
+ command: "/usr/bin/python3",
340
+ args: ["-I", "-S", "-c", command, request],
341
+ inputs,
342
+ ...networked ? {
343
+ env: { HAI_TOOL_BROWSER_PROXY: proxy }
344
+ } : {}
345
+ });
346
+ if (!started.success)
347
+ return started;
348
+ const process = started.data;
349
+ process.stderr.resume();
350
+ const outcome = await (async () => {
351
+ const chunks = [];
352
+ let total = 0;
353
+ for await (const raw of process.stdout.iterator({ destroyOnReturn: false })) {
354
+ signal.throwIfAborted();
355
+ const chunk = Buffer.from(raw);
356
+ total += chunk.length;
357
+ if (total > 2 * 1024 * 1024)
358
+ return fail();
359
+ chunks.push(chunk);
360
+ if (chunk.includes(10))
361
+ break;
362
+ }
363
+ const parsed = response.safeParse(JSON.parse(Buffer.concat(chunks).toString("utf8").trim()));
364
+ if (!parsed.success)
365
+ return fail();
366
+ if (!parsed.data.success) {
367
+ const toolCode = parsed.data.error.code;
368
+ const diagnostic = { operation, toolCode, executionId: context.execution.id };
369
+ logger2.warn("Tool job operation rejected", diagnostic);
370
+ if (toolCode === "SANDBOX_UNAVAILABLE")
371
+ return err(HaiToolsError.EXECUTION_FAILED, toolsM("tools_sandboxUnavailable"), diagnostic);
372
+ if (toolCode === "UNSUPPORTED_PROJECT")
373
+ return err(HaiToolsError.VALIDATION_FAILED, toolsM("tools_previewUnsupported"), diagnostic);
374
+ if (toolCode === "OUTPUT_LIMIT")
375
+ return err(HaiToolsError.VALIDATION_FAILED, toolsM("tools_outputLimit"), diagnostic);
376
+ if (toolCode === "UNSAFE_DOCUMENT")
377
+ return err(HaiToolsError.VALIDATION_FAILED, toolsM("tools_unsafeDocument"), diagnostic);
378
+ if (toolCode === "TIMEOUT")
379
+ return err(HaiToolsError.TIMEOUT, toolsM("tools_timeout"), diagnostic);
380
+ const invalidInput = [
381
+ "INVALID_REQUEST",
382
+ "INVALID_INPUT",
383
+ "INVALID_PROJECT",
384
+ "UNSAFE_PROJECT"
385
+ ].includes(toolCode);
386
+ return err(invalidInput ? HaiToolsError.VALIDATION_FAILED : HaiToolsError.EXECUTION_FAILED, invalidInput ? toolsM("tools_validationFailed") : toolsM("tools_executionFailed"), diagnostic);
387
+ }
388
+ const result = parsed.data.data;
389
+ if (result.text !== void 0 && !spec.output)
390
+ return ok({ text: result.text });
391
+ if (!result.artifact || result.artifact.name !== spec.output)
392
+ return fail();
393
+ const bytes = await process.artifact(spec.output, result.artifact.bytes);
394
+ if (!bytes.success)
395
+ return bytes;
396
+ const data = Buffer.from(bytes.data, "base64");
397
+ if (data.byteLength !== result.artifact.bytes)
398
+ return fail();
399
+ signal.throwIfAborted();
400
+ const digest = createHash("sha256").update(`${context.execution.id}:${spec.output}`).digest("hex");
401
+ const id = `${digest.slice(0, 8)}-${digest.slice(8, 12)}-4${digest.slice(13, 16)}-8${digest.slice(17, 20)}-${digest.slice(20, 32)}`;
402
+ const published = await files.publish({ ...context, signal }, {
403
+ id,
404
+ name: spec.output,
405
+ kind: spec.kind ?? "file",
406
+ mediaType: spec.mediaType ?? "application/octet-stream",
407
+ data
408
+ });
409
+ if (!published.success)
410
+ return published;
411
+ return ok({
412
+ artifacts: [published.data],
413
+ ...result.summary ? { sourceUrl: result.summary.sourceUrl, title: result.summary.title, text: result.summary.text } : {}
414
+ });
415
+ })().catch((cause) => {
416
+ logger2.warn("Tool job response failed", { operation });
417
+ return err(HaiToolsError.EXECUTION_FAILED, toolsM("tools_executionFailed"), cause);
418
+ });
419
+ const closed = await process.close();
420
+ if (closed.success)
421
+ return outcome;
422
+ return outcome.success ? closed : err({
423
+ ...closed.error,
424
+ ext: {
425
+ ...closed.error.ext,
426
+ operationError: core.error.toPublic(outcome.error)
427
+ }
428
+ });
429
+ }
430
+ }));
431
+ }
432
+ add("documents", "documents.extract", z.object({ fileId }), (input) => ({ source: input.fileId, request: {} }));
433
+ const documentText = (maximum, required = false) => z.string().refine((value) => {
434
+ const characters = [...value];
435
+ return characters.length <= maximum && (!required || value.trim().length > 0) && characters.every((character) => {
436
+ const code = character.codePointAt(0) ?? 0;
437
+ return (code >= 32 || " \n\r".includes(character)) && !(code >= 55296 && code <= 57343) && (code & 65535) < 65534;
438
+ });
439
+ }).meta({
440
+ maxLength: maximum,
441
+ ...required ? { minLength: 1 } : {}
442
+ });
443
+ const documentTable = (slide2 = false) => z.strictObject({
444
+ headers: z.array(documentText(slide2 ? 32 : 2e3)).min(1).max(slide2 ? 6 : 20).meta({
445
+ title: toolsM("tools_field_headers")
446
+ }),
447
+ rows: z.array(z.array(documentText(slide2 ? 32 : 2e3)).max(slide2 ? 6 : 20)).max(slide2 ? 6 : 200).optional().meta({
448
+ title: toolsM("tools_field_rows")
449
+ })
450
+ }).superRefine((table, check) => {
451
+ if (table.rows?.some((row) => row.length !== table.headers.length)) {
452
+ check.addIssue({
453
+ code: "custom",
454
+ message: toolsM("tools_validationFailed"),
455
+ path: ["rows"]
456
+ });
457
+ }
458
+ }).meta({
459
+ title: toolsM("tools_field_table")
460
+ });
461
+ const slide = z.strictObject({
462
+ title: documentText(100, true).meta({
463
+ title: toolsM("tools_field_title")
464
+ }),
465
+ paragraphs: z.array(documentText(160)).max(6).optional().meta({
466
+ title: toolsM("tools_field_paragraphs")
467
+ }),
468
+ table: documentTable(true).optional()
469
+ }).superRefine((slide2, check) => {
470
+ const paragraphs = slide2.paragraphs ?? [];
471
+ const length = paragraphs.reduce((total, paragraph) => total + [...paragraph].length, 0);
472
+ if (length > 800 || slide2.table && (paragraphs.length > 1 || length > 120)) {
473
+ check.addIssue({
474
+ code: "custom",
475
+ message: toolsM("tools_validationFailed"),
476
+ path: ["paragraphs"]
477
+ });
478
+ }
479
+ }).meta({
480
+ allOf: [
481
+ {
482
+ if: {
483
+ required: ["table"]
484
+ },
485
+ then: {
486
+ properties: {
487
+ paragraphs: {
488
+ maxItems: 1,
489
+ items: { maxLength: 120 }
490
+ }
491
+ }
492
+ }
493
+ }
494
+ ]
495
+ });
496
+ const document = z.strictObject({
497
+ format: z.enum(["docx", "xlsx", "pptx"]).default("docx").meta({
498
+ title: toolsM("tools_field_format")
499
+ }),
500
+ title: documentText(200, true).meta({
501
+ title: toolsM("tools_field_title")
502
+ }),
503
+ paragraphs: z.array(documentText(2e3)).max(100).optional().meta({
504
+ title: toolsM("tools_field_paragraphs")
505
+ }),
506
+ table: documentTable().optional(),
507
+ slides: z.array(slide).min(1).max(20).optional().meta({
508
+ title: toolsM("tools_field_slides")
509
+ })
510
+ }).superRefine(({ format, ...content }, check) => {
511
+ const reject = (path) => check.addIssue({
512
+ code: "custom",
513
+ message: toolsM("tools_validationFailed"),
514
+ path: [path]
515
+ });
516
+ if (Buffer.byteLength(JSON.stringify(content)) > 256 * 1024)
517
+ reject("title");
518
+ if (content.slides !== void 0) {
519
+ if (format !== "pptx" || content.paragraphs !== void 0 || content.table !== void 0)
520
+ reject("slides");
521
+ } else if (format === "pptx" && !slide.safeParse(content).success) {
522
+ reject("paragraphs");
523
+ }
524
+ }).meta({
525
+ description: toolsM("tools_documentLimits"),
526
+ allOf: [
527
+ {
528
+ if: {
529
+ required: ["slides"]
530
+ },
531
+ then: {
532
+ required: ["format"],
533
+ properties: {
534
+ format: { const: "pptx" }
535
+ },
536
+ not: {
537
+ anyOf: [
538
+ {
539
+ required: ["paragraphs"]
540
+ },
541
+ {
542
+ required: ["table"]
543
+ }
544
+ ]
545
+ }
546
+ }
547
+ },
548
+ {
549
+ if: {
550
+ required: ["format"],
551
+ properties: {
552
+ format: { const: "pptx" }
553
+ },
554
+ not: {
555
+ required: ["slides"]
556
+ }
557
+ },
558
+ then: {
559
+ properties: {
560
+ title: { maxLength: 100 },
561
+ paragraphs: {
562
+ maxItems: 6,
563
+ items: { maxLength: 160 }
564
+ },
565
+ table: {
566
+ properties: {
567
+ headers: {
568
+ maxItems: 6,
569
+ items: { maxLength: 32 }
570
+ },
571
+ rows: {
572
+ maxItems: 6,
573
+ items: {
574
+ maxItems: 6,
575
+ items: { maxLength: 32 }
576
+ }
577
+ }
578
+ }
579
+ }
580
+ }
581
+ }
582
+ }
583
+ ]
584
+ });
585
+ add("documents", "documents.generate", document, ({ format, ...input }) => ({
586
+ inline: JSON.stringify(input),
587
+ request: {},
588
+ output: `result.${format}`,
589
+ mediaType: format === "docx" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : format === "xlsx" ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" : "application/vnd.openxmlformats-officedocument.presentationml.presentation"
590
+ }));
591
+ add("office", "office.convert", z.object({ fileId }), (input) => ({
592
+ source: input.fileId,
593
+ request: {},
594
+ output: "result.pdf",
595
+ mediaType: "application/pdf"
596
+ }));
597
+ add("office", "office.recalculate", z.object({ fileId }), (input) => ({
598
+ source: input.fileId,
599
+ request: {},
600
+ output: "result.xlsx",
601
+ mediaType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
602
+ }));
603
+ add("ocr", "ocr.recognize", z.object({
604
+ fileId,
605
+ language: z.enum([
606
+ "eng",
607
+ "chi_sim",
608
+ "jpn",
609
+ "eng+chi_sim",
610
+ "eng+jpn"
611
+ ]).default("eng").meta({
612
+ title: toolsM("tools_field_language")
613
+ })
614
+ }), (input) => ({
615
+ source: input.fileId,
616
+ request: { language: input.language }
617
+ }));
618
+ add("browser", "browser.navigate", z.object({ url }), (input) => ({
619
+ request: { url: input.url },
620
+ output: "screen.png",
621
+ kind: "image",
622
+ mediaType: "image/png"
623
+ }));
624
+ add("web", "web.capture", z.object({
625
+ url,
626
+ maxScreenshots: z.number().int().min(1).max(8).default(4).meta({
627
+ title: toolsM("tools_field_maxScreenshots")
628
+ })
629
+ }), (input) => ({ request: input, output: "capture.zip", mediaType: "application/zip" }));
630
+ add("preview", "preview.build", z.object({
631
+ fileId: fileId.meta({
632
+ ...fileId.meta(),
633
+ contentMediaType: "application/zip"
634
+ })
635
+ }), (input) => ({
636
+ source: input.fileId,
637
+ request: {},
638
+ output: "preview.html",
639
+ kind: "html",
640
+ mediaType: "text/html"
641
+ }));
642
+ add("video", "video.render", z.object({
643
+ fileId,
644
+ fps: z.union([
645
+ z.literal(24),
646
+ z.literal(25),
647
+ z.literal(30)
648
+ ]).default(30).meta({
649
+ title: toolsM("tools_field_fps")
650
+ })
651
+ }), (input) => ({
652
+ source: input.fileId,
653
+ request: { fps: input.fps },
654
+ output: "video.mp4",
655
+ kind: "video",
656
+ mediaType: "video/mp4"
657
+ }));
658
+ return {
659
+ tools: definitions,
660
+ environments: bindings,
661
+ groups: [...groups].map(([id, names]) => ({ id, title: id, tools: names }))
662
+ };
663
+ }
664
+ function browserProxyAddress(value) {
665
+ const parsed = /^http:\/\/((?:\d{1,3}\.){3}\d{1,3}):(\d{1,5})\/?$/iu.exec(value);
666
+ if (!parsed || !isIPv4(parsed[1]))
667
+ return void 0;
668
+ const host = parsed[1];
669
+ const port = Number(parsed[2]);
670
+ const octets = host.split(".").map(Number);
671
+ if (port < 1 || port > 65535 || host === "0.0.0.0" || octets[0] === 127 || octets[0] >= 224 && octets[0] <= 239 || octets[0] === 169 && octets[1] === 254) {
672
+ return void 0;
673
+ }
674
+ return `http://${host}:${port}`;
675
+ }
676
+ var logger = core.logger.child({ module: "tools", scope: "service" });
677
+ var scopeSchema = z.strictObject({
678
+ tenantId: z.string().min(1).max(200),
679
+ userId: z.string().min(1).max(200)
680
+ });
681
+ var keySchema = z.string().min(1).max(200);
682
+ var invocationSchema = z.strictObject({
683
+ name: z.string().regex(/^[a-z][\w-]{0,63}$/i),
684
+ input: z.json(),
685
+ sessionId: keySchema.optional(),
686
+ environmentId: z.string().min(1).max(100).optional()
687
+ });
688
+ var receiptSchema = z.strictObject({
689
+ id: z.string().regex(/^[a-f\d]{64}$/i),
690
+ key: keySchema
691
+ });
692
+ var timeoutSchema = z.number().int().min(1).max(864e5);
693
+ var live = /* @__PURE__ */ new Set(["queued", "running", "cancelling"]);
694
+ var errorEvent = z.object({
695
+ type: z.literal("tool-error"),
696
+ error: z.object({
697
+ code: z.string(),
698
+ message: z.string(),
699
+ httpStatus: z.number(),
700
+ traceId: z.string().optional()
701
+ })
702
+ });
703
+ function invalid(cause) {
704
+ return err(HaiToolsError.VALIDATION_FAILED, toolsM("tools_validationFailed"), cause);
705
+ }
706
+ function forbidden(cause) {
707
+ return err(HaiToolsError.FORBIDDEN, toolsM("tools_forbidden"), cause);
708
+ }
709
+ function failed(cause) {
710
+ return err(HaiToolsError.EXECUTION_FAILED, toolsM("tools_executionFailed"), cause);
711
+ }
712
+ function cancelled(cause) {
713
+ return err(HaiToolsError.CANCELLED, toolsM("tools_cancelled"), cause);
714
+ }
715
+ async function interrupted(run, signal) {
716
+ signal.throwIfAborted();
717
+ return new Promise((resolve, reject) => {
718
+ const abort = () => reject(signal.reason);
719
+ signal.addEventListener("abort", abort, { once: true });
720
+ Promise.resolve().then(() => {
721
+ signal.throwIfAborted();
722
+ return run();
723
+ }).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
724
+ });
725
+ }
726
+ function createToolService(options) {
727
+ const configuration = z.object({
728
+ id: z.string().min(1).max(60).regex(/^[\w.-]+$/),
729
+ runTimeoutMs: timeoutSchema.default(3e5),
730
+ queueTimeoutMs: timeoutSchema.default(3e5)
731
+ }).safeParse(options);
732
+ if (!configuration.success || typeof options.createTools !== "function" || typeof options.authorize !== "function")
733
+ return invalid(configuration.error);
734
+ const { id, runTimeoutMs, queueTimeoutMs } = configuration.data;
735
+ const kind = `hai.tools.${id}.v1`;
736
+ let closed = false;
737
+ function context(input, execution) {
738
+ return {
739
+ scope: scopeSchema.parse(input.scope),
740
+ ...input.sessionId === void 0 ? {} : {
741
+ sessionId: keySchema.parse(input.sessionId)
742
+ },
743
+ signal: execution?.signal ?? input.signal,
744
+ ...execution ? { execution } : {}
745
+ };
746
+ }
747
+ async function guarded(input, run) {
748
+ if (closed)
749
+ return failed();
750
+ if (input.signal?.aborted)
751
+ return cancelled(input.signal.reason);
752
+ try {
753
+ const current = context(input);
754
+ const signal = AbortSignal.any([
755
+ AbortSignal.timeout(runTimeoutMs),
756
+ ...current.signal ? [current.signal] : []
757
+ ]);
758
+ return await interrupted(() => run({ ...current, signal }), signal);
759
+ } catch (cause) {
760
+ if (input.signal?.aborted)
761
+ return cancelled(cause);
762
+ if (cause instanceof Error && cause.name === "TimeoutError")
763
+ return err(HaiToolsError.TIMEOUT, toolsM("tools_timeout"), cause);
764
+ if (cause instanceof z.ZodError)
765
+ return invalid(cause);
766
+ const failure = failed(cause);
767
+ if (!failure.success) {
768
+ const safe = core.error.toPublic(failure.error);
769
+ failure.error.traceId = safe.traceId;
770
+ logger.error("Tool service operation failed", {
771
+ service: id,
772
+ errorCode: String(safe.code),
773
+ traceId: safe.traceId
774
+ });
775
+ }
776
+ return failure;
777
+ }
778
+ }
779
+ async function resolve(current) {
780
+ const signal = current.signal ?? AbortSignal.timeout(runTimeoutMs);
781
+ const set = await interrupted(() => options.createTools(current), signal);
782
+ const select = options.enabled;
783
+ const selection = typeof select === "function" ? await interrupted(() => select(current), signal) : select;
784
+ const allowed = new Set(selection.tools ?? []);
785
+ const excluded = new Set(selection.exclude ?? []);
786
+ const groups = set.groups ?? [];
787
+ for (const group of groups) {
788
+ if (selection.groups?.includes(group.id)) {
789
+ for (const name of group.tools)
790
+ allowed.add(name);
791
+ }
792
+ }
793
+ const registry = tools.createRegistry();
794
+ const registered = registry.registerMany(set.tools.filter((tool) => allowed.has(tool.name) && !excluded.has(tool.name)));
795
+ if (!registered.success)
796
+ return registered;
797
+ const definitions = registry.getDefinitions();
798
+ const names = new Set(definitions.map((tool) => tool.name));
799
+ return ok({
800
+ registry,
801
+ environments: new Map(Object.entries(set.environments ?? {})),
802
+ catalog: {
803
+ tools: definitions,
804
+ groups: groups.map((group) => ({
805
+ ...group,
806
+ tools: group.tools.filter((name) => names.has(name))
807
+ })).filter((group) => group.tools.length > 0)
808
+ }
809
+ });
810
+ }
811
+ async function authorize(current, name, input, phase) {
812
+ try {
813
+ return await interrupted(() => options.authorize({ context: current, name, input, phase }), current.signal ?? AbortSignal.timeout(runTimeoutMs)) === true;
814
+ } catch (cause) {
815
+ if (current.signal?.aborted)
816
+ throw cause;
817
+ return false;
818
+ }
819
+ }
820
+ async function execute(input, execution) {
821
+ const parsed = invocationSchema.parse(input);
822
+ const current = context({ scope: execution.scope, sessionId: parsed.sessionId }, execution);
823
+ const resolved = await resolve(current);
824
+ let result;
825
+ if (!resolved.success) {
826
+ result = resolved;
827
+ } else if (!resolved.data.registry.has(parsed.name) || resolved.data.environments.get(parsed.name) !== parsed.environmentId) {
828
+ result = forbidden();
829
+ } else {
830
+ result = await resolved.data.registry.execute(parsed.name, parsed.input, {
831
+ signal: execution.signal,
832
+ objectId: JSON.stringify([execution.scope.tenantId, execution.scope.userId]),
833
+ sessionId: current.sessionId,
834
+ authorize: (request) => authorize(current, parsed.name, request.input, "execute")
835
+ });
836
+ }
837
+ if (!result.success) {
838
+ const safe = core.error.toPublic(result.error);
839
+ const diagnostic = {
840
+ service: id,
841
+ tool: parsed.name,
842
+ executionId: execution.id,
843
+ errorCode: String(safe.code),
844
+ traceId: safe.traceId
845
+ };
846
+ if ((safe.httpStatus ?? 500) >= 500)
847
+ logger.error("Tool execution failed", diagnostic);
848
+ else logger.debug("Tool execution rejected", diagnostic);
849
+ const emitted = await execution.emit({
850
+ type: "tool-error",
851
+ error: {
852
+ code: String(safe.code),
853
+ message: safe.message,
854
+ httpStatus: safe.httpStatus ?? 500,
855
+ ...safe.traceId ? { traceId: safe.traceId } : {}
856
+ }
857
+ });
858
+ if (!emitted.success)
859
+ logger.warn("Tool failure event could not be persisted", { executionId: execution.id, code: emitted.error.code });
860
+ throw new Error("Tool operation failed");
861
+ }
862
+ const output = z.json().safeParse(result.data === void 0 ? null : result.data);
863
+ if (!output.success)
864
+ throw new Error("Tool output is not a persistent JSON result");
865
+ return output.data;
866
+ }
867
+ const registration = options.runner.register(kind, execute);
868
+ if (!registration.success)
869
+ return registration;
870
+ async function find(receipt, current) {
871
+ const parsed = receiptSchema.safeParse(receipt);
872
+ if (!parsed.success)
873
+ return invalid(parsed.error);
874
+ const found = await options.runner.find(current.scope, kind, receipt.key);
875
+ if (!found.success)
876
+ return found;
877
+ return found.data?.id === receipt.id ? ok(found.data) : err(HaiToolsError.NOT_FOUND, toolsM("tools_notFound"));
878
+ }
879
+ async function project(execution, receipt, current, after = 0) {
880
+ const events = await options.runner.events(current.scope, execution.id, after, 100);
881
+ if (!events.success)
882
+ return events;
883
+ return ok({
884
+ receipt,
885
+ status: execution.status,
886
+ ...execution.output === void 0 ? {} : { output: execution.output },
887
+ ...execution.failure ? { failure: execution.failure } : {},
888
+ events: events.data,
889
+ next: events.data.at(-1)?.sequence ?? after
890
+ });
891
+ }
892
+ const service = {
893
+ find: (idempotencyKey, input) => guarded(input, async (current) => {
894
+ const key = keySchema.safeParse(idempotencyKey);
895
+ if (!key.success)
896
+ return invalid(key.error);
897
+ const found = await options.runner.find(current.scope, kind, key.data);
898
+ if (!found.success)
899
+ return found;
900
+ return found.data ? project(found.data, { id: found.data.id, key: key.data }, current) : ok(void 0);
901
+ }),
902
+ catalog: (input) => guarded(input, async (current) => {
903
+ const resolved = await resolve(current);
904
+ return resolved.success ? ok(resolved.data.catalog) : resolved;
905
+ }),
906
+ submit: (request, input) => guarded(input, async (current) => {
907
+ const parsed = invocationSchema.safeParse({
908
+ name: request.name,
909
+ input: request.input,
910
+ ...current.sessionId === void 0 ? {} : { sessionId: current.sessionId }
911
+ });
912
+ const key = keySchema.safeParse(request.idempotencyKey ?? core.id.uuid());
913
+ if (!parsed.success || !key.success)
914
+ return invalid();
915
+ const resolved = await resolve(current);
916
+ if (!resolved.success)
917
+ return resolved;
918
+ const tool = resolved.data.registry.get(parsed.data.name);
919
+ if (!tool)
920
+ return forbidden();
921
+ const signal = current.signal ?? AbortSignal.timeout(runTimeoutMs);
922
+ let validation;
923
+ try {
924
+ validation = await interrupted(() => tool.parameters.safeParseAsync(parsed.data.input), signal);
925
+ } catch (cause) {
926
+ if (signal.aborted)
927
+ throw cause;
928
+ return invalid(cause);
929
+ }
930
+ if (!validation.success)
931
+ return invalid(validation.error);
932
+ if (!await authorize(current, parsed.data.name, validation.data, "submit"))
933
+ return forbidden();
934
+ current.signal?.throwIfAborted();
935
+ const environmentId = resolved.data.environments.get(parsed.data.name);
936
+ const payload = {
937
+ ...parsed.data,
938
+ ...environmentId ? { environmentId } : {}
939
+ };
940
+ const accepted = await options.runner.submit({
941
+ kind,
942
+ scope: current.scope,
943
+ input: payload,
944
+ ...environmentId ? { environmentId } : {},
945
+ idempotencyKey: key.data,
946
+ capacityClass: environmentId ? "tool" : "default",
947
+ runTimeoutMs,
948
+ queueTimeoutMs
949
+ });
950
+ if (!accepted.success)
951
+ return accepted;
952
+ return ok({
953
+ receipt: { id: accepted.data.id, key: key.data },
954
+ status: accepted.data.status,
955
+ ...accepted.data.output === void 0 ? {} : { output: accepted.data.output },
956
+ events: [],
957
+ next: 0
958
+ });
959
+ }),
960
+ inspect: (receipt, input, cursor = {}) => guarded(input, async (current) => {
961
+ const after = z.number().int().min(0).max(1e5).safeParse(cursor.after ?? 0);
962
+ if (!after.success)
963
+ return invalid(after.error);
964
+ const found = await find(receipt, current);
965
+ return found.success ? project(found.data, receipt, current, after.data) : found;
966
+ }),
967
+ cancel: (receipt, input) => guarded(input, async (current) => {
968
+ const found = await find(receipt, current);
969
+ if (!found.success)
970
+ return found;
971
+ const cancelled2 = await options.runner.cancel(current.scope, found.data.id);
972
+ return cancelled2.success ? project(cancelled2.data, receipt, current) : cancelled2;
973
+ }),
974
+ async invoke(request, input) {
975
+ const submitted = await service.submit(request, input);
976
+ if (!submitted.success)
977
+ return submitted;
978
+ let current = submitted.data;
979
+ let lastError;
980
+ const signal = input.signal ? AbortSignal.any([
981
+ input.signal,
982
+ AbortSignal.timeout(runTimeoutMs + queueTimeoutMs + 1e3)
983
+ ]) : AbortSignal.timeout(runTimeoutMs + queueTimeoutMs + 1e3);
984
+ try {
985
+ while (live.has(current.status)) {
986
+ await setTimeout(40, void 0, { signal });
987
+ const inspected = await service.inspect(current.receipt, { ...input, signal }, { after: current.next });
988
+ if (!inspected.success)
989
+ return inspected;
990
+ current = inspected.data;
991
+ for (const event of current.events) {
992
+ const parsed = errorEvent.safeParse(event.data);
993
+ if (parsed.success)
994
+ lastError = parsed.data.error;
995
+ }
996
+ }
997
+ if (current.status === "succeeded")
998
+ return ok(current.output ?? null);
999
+ while (!lastError && (current.events.length === 100 || current.next === 0)) {
1000
+ const inspected = await service.inspect(current.receipt, { ...input, signal }, { after: current.next });
1001
+ if (!inspected.success)
1002
+ return inspected;
1003
+ current = inspected.data;
1004
+ for (const event of current.events) {
1005
+ const parsed = errorEvent.safeParse(event.data);
1006
+ if (parsed.success)
1007
+ lastError = parsed.data.error;
1008
+ }
1009
+ if (current.events.length < 100)
1010
+ break;
1011
+ }
1012
+ if (lastError)
1013
+ return err(lastError);
1014
+ if (current.status === "cancelled")
1015
+ return cancelled();
1016
+ if (current.failure === "run-timeout" || current.failure === "queue-timeout")
1017
+ return err(HaiToolsError.TIMEOUT, toolsM("tools_timeout"));
1018
+ return failed();
1019
+ } catch (cause) {
1020
+ if (input.signal?.aborted)
1021
+ return cancelled(cause);
1022
+ return err(HaiToolsError.TIMEOUT, toolsM("tools_timeout"), cause);
1023
+ } finally {
1024
+ if (signal.aborted && live.has(current.status)) {
1025
+ const stopped = await options.runner.cancel(input.scope, current.receipt.id);
1026
+ if (!stopped.success)
1027
+ logger.warn("Tool cancellation could not be requested", { executionId: current.receipt.id, code: stopped.error.code });
1028
+ }
1029
+ }
1030
+ },
1031
+ close() {
1032
+ if (closed)
1033
+ return;
1034
+ closed = true;
1035
+ registration.data();
1036
+ }
1037
+ };
1038
+ return ok(service);
1039
+ }
1040
+
1041
+ // src/server/index.ts
1042
+ var tools2 = {
1043
+ ...tools,
1044
+ createService: createToolService,
1045
+ createArtifactTools,
1046
+ createJobTools
1047
+ };
1048
+
1049
+ export { tools2 as tools };
1050
+ //# sourceMappingURL=index.js.map
1051
+ //# sourceMappingURL=index.js.map