@h-ai/ai 1.0.0-beta.30 → 1.0.0-beta.32

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 (48) hide show
  1. package/README.en.md +11 -1114
  2. package/README.ja.md +10 -1113
  3. package/README.md +11 -1137
  4. package/dist/{ai-acp-types-DuPV5UGi.d.ts → ai-acp-types-cue1ZWUk.d.ts} +4970 -5227
  5. package/dist/ai-file-types-BN7l67hR.d.ts +167 -0
  6. package/dist/ai-file-worker.d.ts +38 -0
  7. package/dist/ai-file-worker.js +85 -0
  8. package/dist/ai-file-worker.js.map +1 -0
  9. package/dist/ai-video-archive-worker.d.ts +32 -0
  10. package/dist/ai-video-archive-worker.js +102 -0
  11. package/dist/ai-video-archive-worker.js.map +1 -0
  12. package/dist/browser.d.ts +5 -2
  13. package/dist/browser.js +4 -3
  14. package/dist/{chunk-NRDLMUSY.js → chunk-C6T3ONVG.js} +4 -8
  15. package/dist/chunk-C6T3ONVG.js.map +1 -0
  16. package/dist/{chunk-LENTVEBE.js → chunk-HZDINADT.js} +254 -973
  17. package/dist/chunk-HZDINADT.js.map +1 -0
  18. package/dist/chunk-IVEOIRBO.js +971 -0
  19. package/dist/chunk-IVEOIRBO.js.map +1 -0
  20. package/dist/chunk-OWR55FRO.js +140 -0
  21. package/dist/chunk-OWR55FRO.js.map +1 -0
  22. package/dist/{chunk-ILUCWONQ.js → chunk-UVBQCI7A.js} +3 -3
  23. package/dist/{chunk-ILUCWONQ.js.map → chunk-UVBQCI7A.js.map} +1 -1
  24. package/dist/client/index.js +2 -2
  25. package/dist/index.d.ts +6 -3
  26. package/dist/index.js +1492 -743
  27. package/dist/index.js.map +1 -1
  28. package/models/agents/README.md +3 -1
  29. package/models/agents/deepseek-harness/Dockerfile +2 -0
  30. package/package.json +10 -10
  31. package/dist/chunk-LENTVEBE.js.map +0 -1
  32. package/dist/chunk-NRDLMUSY.js.map +0 -1
  33. package/tools/.dockerignore +0 -4
  34. package/tools/README.md +0 -111
  35. package/tools/archives.py +0 -56
  36. package/tools/browser/Dockerfile +0 -19
  37. package/tools/browser/operation.py +0 -50
  38. package/tools/browser/render.mjs +0 -40
  39. package/tools/documents/Dockerfile +0 -20
  40. package/tools/documents/operation.py +0 -80
  41. package/tools/ocr/Dockerfile +0 -19
  42. package/tools/ocr/operation.py +0 -18
  43. package/tools/office/Dockerfile +0 -21
  44. package/tools/office/office_job.py +0 -65
  45. package/tools/office/operation.py +0 -43
  46. package/tools/tests/image-smoke.mjs +0 -83
  47. package/tools/tests/test_hai_tool.py +0 -82
  48. package/tools/tool.py +0 -145
@@ -1,83 +0,0 @@
1
- import { spawnSync } from 'node:child_process'
2
- import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
3
- import { tmpdir } from 'node:os'
4
- import { join } from 'node:path'
5
- import process from 'node:process'
6
-
7
- async function smoke() {
8
- const engine = process.env.HAI_TOOL_IMAGE_ENGINE ?? 'podman'
9
- if (!['podman', 'docker'].includes(engine))
10
- throw new Error('HAI_TOOL_IMAGE_ENGINE must be podman or docker')
11
- const directory = await mkdtemp(join(tmpdir(), 'hai-tool-images-'))
12
- const input = join(directory, 'input')
13
- const output = join(directory, 'output')
14
- try {
15
- await mkdir(input, { mode: 0o755 })
16
- await mkdir(output)
17
- await chmod(output, 0o777)
18
- await writeFile(join(input, 'input.txt'), 'HAI tool image fixture')
19
- for (const [name, request, check] of [
20
- [
21
- 'documents',
22
- { operation: 'documents.extract', input: 'input.txt' },
23
- result => result.data?.text === 'HAI tool image fixture',
24
- ],
25
- [
26
- 'office',
27
- { operation: 'office.convert', input: 'input.txt', output: 'office.pdf' },
28
- result => result.error?.code === 'INVALID_REQUEST',
29
- ],
30
- [
31
- 'ocr',
32
- { operation: 'ocr.recognize', input: 'input.txt' },
33
- result => result.error?.code === 'INVALID_INPUT',
34
- ],
35
- [
36
- 'browser',
37
- { operation: 'browser.navigate', url: 'https://example.com/', output: 'page.png' },
38
- result => result.error?.code === 'NETWORK_POLICY_REQUIRED',
39
- ],
40
- ]) {
41
- const image = process.env[`HAI_TOOL_IMAGE_${name.toUpperCase()}`]
42
- if (!image)
43
- throw new Error(`Missing image for ${name}`)
44
- const task = spawnSync(engine, [
45
- 'run',
46
- '--rm',
47
- '--pull=never',
48
- '-i',
49
- '--network=none',
50
- '--read-only',
51
- '--tmpfs=/tmp:rw,nosuid,nodev,size=128m',
52
- ...(engine === 'podman'
53
- ? ['--userns=keep-id:uid=1000,gid=1000']
54
- : []),
55
- '--mount',
56
- `type=bind,src=${input},dst=/input,ro=true`,
57
- '--mount',
58
- `type=bind,src=${output},dst=/output`,
59
- image,
60
- ], {
61
- input: JSON.stringify(request),
62
- encoding: 'utf8',
63
- timeout: 30_000,
64
- })
65
- if (task.status !== 0)
66
- throw new Error(`${name} failed to start: ${task.stderr ?? task.error}`)
67
- const result = JSON.parse(task.stdout)
68
- if (!check(result))
69
- throw new Error(`${name} returned unexpected result: ${JSON.stringify(result)}`)
70
- process.stdout.write(`${name} image smoke passed\n`)
71
- }
72
- if (await readFile(join(input, 'input.txt'), 'utf8') !== 'HAI tool image fixture')
73
- throw new Error('Tool modified read-only input')
74
- }
75
- finally {
76
- await rm(directory, { recursive: true, force: true })
77
- }
78
- }
79
-
80
- smoke().catch((error) => {
81
- process.stderr.write(`${error.message}\n`)
82
- process.exitCode = 1
83
- })
@@ -1,82 +0,0 @@
1
- import importlib.util
2
- import io
3
- import json
4
- import pathlib
5
- import sys
6
- import tempfile
7
- import unittest
8
- import zipfile
9
-
10
- ROOT = pathlib.Path(__file__).resolve().parents[1]
11
- sys.path.insert(0, str(ROOT))
12
- from tool import serve
13
-
14
-
15
- def load(kind):
16
- spec = importlib.util.spec_from_file_location(kind, ROOT / kind / 'operation.py')
17
- module = importlib.util.module_from_spec(spec)
18
- spec.loader.exec_module(module)
19
- return module.commands
20
-
21
-
22
- class ToolTests(unittest.TestCase):
23
- def setUp(self):
24
- self.temp = tempfile.TemporaryDirectory()
25
- self.addCleanup(self.temp.cleanup)
26
- self.root = pathlib.Path(self.temp.name)
27
- self.inputs = self.root / 'input'
28
- self.outputs = self.root / 'output'
29
- self.inputs.mkdir()
30
- self.outputs.mkdir()
31
-
32
- def run_tool(self, kind, request):
33
- result = io.StringIO()
34
- serve(io.BytesIO(json.dumps(request).encode()), result, load(kind), self.inputs, self.outputs)
35
- return json.loads(result.getvalue())
36
-
37
- def test_extract_text_and_reject_link_escape(self):
38
- (self.inputs / 'plain.txt').write_text('Hello, 文件。', encoding='utf-8')
39
- args = {'operation': 'documents.extract', 'input': 'plain.txt'}
40
- self.assertEqual(self.run_tool('documents', args), {'success': True, 'data': {'text': 'Hello, 文件。'}})
41
- (self.inputs / 'link.txt').symlink_to(self.inputs / 'plain.txt')
42
- for name in ['../plain.txt', '/etc/passwd', 'link.txt']:
43
- self.assertFalse(self.run_tool('documents', {**args, 'input': name})['success'])
44
-
45
- def test_reject_unknown_fields_and_oversized_json(self):
46
- bad = self.run_tool('documents', {'operation': 'documents.extract', 'input': 'plain.txt', 'command': 'wrong'})
47
- self.assertEqual(bad['error']['code'], 'INVALID_REQUEST')
48
- result = io.StringIO()
49
- serve(io.BytesIO(b' ' * 70_000), result, load('documents'), self.inputs, self.outputs)
50
- self.assertEqual(json.loads(result.getvalue())['error']['code'], 'INVALID_REQUEST')
51
-
52
- def test_office_rejects_external_document_relationships(self):
53
- with zipfile.ZipFile(self.inputs / 'linked.docx', 'w') as archive:
54
- archive.writestr('[Content_Types].xml', '<Types/>')
55
- archive.writestr('word/document.xml', '<document/>')
56
- archive.writestr('word/_rels/document.xml.rels', '<Relationships><Relationship TargetMode="External" Target="https://example.test/file"/></Relationships>')
57
- result = self.run_tool('office', {'operation': 'office.convert', 'input': 'linked.docx', 'output': 'result.pdf'})
58
- self.assertEqual(result['error']['code'], 'UNSAFE_DOCUMENT')
59
- self.assertEqual(list(self.outputs.iterdir()), [])
60
-
61
- def test_ocr_rejects_unsupported_input_and_language(self):
62
- (self.inputs / 'sample.png').write_bytes(b'invalid image data')
63
- args = {'operation': 'ocr.recognize', 'input': 'sample.png'}
64
- self.assertEqual(self.run_tool('ocr', {**args, 'language': '-bad'})['error']['code'], 'INVALID_REQUEST')
65
- self.assertEqual(self.run_tool('ocr', {**args, 'language': 'eng'})['error']['code'], 'INVALID_INPUT')
66
-
67
- def test_browser_rejects_invalid_url_and_missing_deployment_proxy(self):
68
- args = {'operation': 'browser.navigate', 'output': 'screen.png'}
69
- for url in ['file:///etc/passwd', 'http://example.test', 'https://person:token@example.test', 'https://127.0.0.1/']:
70
- self.assertEqual(self.run_tool('browser', {**args, 'url': url})['error']['code'], 'INVALID_REQUEST')
71
- self.assertEqual(self.run_tool('browser', {**args, 'url': 'https://example.test'})['error']['code'], 'NETWORK_POLICY_REQUIRED')
72
-
73
- def test_tool_cannot_overwrite_existing_outputs(self):
74
- artifact = self.outputs / 'screen.png'
75
- artifact.write_text('existing')
76
- args = {'operation': 'browser.navigate', 'output': artifact.name, 'url': 'https://example.test'}
77
- self.assertEqual(self.run_tool('browser', args)['error']['code'], 'INVALID_OUTPUT')
78
- self.assertEqual(artifact.read_text(), 'existing')
79
-
80
-
81
- if __name__ == '__main__':
82
- unittest.main()
package/tools/tool.py DELETED
@@ -1,145 +0,0 @@
1
- #!/usr/bin/python3
2
- """固定工具镜像的单请求入口。"""
3
- import json
4
- import os
5
- import pathlib
6
- import re
7
- import shutil
8
- import signal
9
- import stat
10
- import subprocess
11
- import sys
12
- import tempfile
13
-
14
- REQUEST_LIMIT = 64 * 1024
15
- FILE_LIMIT = 50 * 1024 * 1024
16
- TEXT_LIMIT = 256 * 1024
17
- NAME = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,127}\Z', re.ASCII)
18
-
19
-
20
- class ToolError(Exception):
21
- def __init__(self, code, message):
22
- super().__init__(message)
23
- self.code = code
24
-
25
-
26
- def require_name(name, code):
27
- if not isinstance(name, str) or not NAME.fullmatch(name):
28
- raise ToolError(code, 'A simple file name is required')
29
- return name
30
-
31
-
32
- def input_file(root, name):
33
- path = root / require_name(name, 'INVALID_INPUT')
34
- try:
35
- info = path.lstat()
36
- except OSError:
37
- raise ToolError('INVALID_INPUT', 'Input file is unavailable') from None
38
- if not stat.S_ISREG(info.st_mode) or not 0 < info.st_size <= FILE_LIMIT:
39
- raise ToolError('INVALID_INPUT', 'Input is not a regular file or exceeds the size limit')
40
- return path
41
-
42
-
43
- def output_file(root, name):
44
- path = root / require_name(name, 'INVALID_OUTPUT')
45
- if os.path.lexists(path):
46
- raise ToolError('INVALID_OUTPUT', 'Output already exists')
47
- return path
48
-
49
-
50
- def text_result(text):
51
- if len(text.encode('utf-8')) > TEXT_LIMIT:
52
- raise ToolError('OUTPUT_LIMIT', 'Extracted text exceeds the size limit')
53
- return {'text': text}
54
-
55
-
56
- def read_text(path):
57
- with path.open('rb') as source:
58
- data = source.read(TEXT_LIMIT + 1)
59
- if len(data) > TEXT_LIMIT:
60
- raise ToolError('OUTPUT_LIMIT', 'Extracted text exceeds the size limit')
61
- return text_result(data.decode('utf-8'))
62
-
63
-
64
- def publish(source, output, signature):
65
- info = source.lstat()
66
- if not stat.S_ISREG(info.st_mode) or not 0 < info.st_size <= FILE_LIMIT:
67
- raise ToolError('INVALID_OUTPUT', 'Produced artifact is not a bounded regular file')
68
- with source.open('rb') as stream:
69
- if not stream.read(len(signature)).startswith(signature):
70
- raise ToolError('INVALID_OUTPUT', 'Produced artifact has an unexpected format')
71
- stream.seek(0)
72
- try:
73
- with output.open('xb') as destination:
74
- try:
75
- shutil.copyfileobj(stream, destination)
76
- except OSError:
77
- output.unlink(missing_ok=True)
78
- raise
79
- except FileExistsError:
80
- raise ToolError('INVALID_OUTPUT', 'Output already exists') from None
81
- return {'artifact': {'name': output.name, 'bytes': info.st_size}}
82
-
83
-
84
- def run_command(args, timeout, workdir):
85
- # 不继承代理、工具凭据或外部程序配置。诊断输出不能混入协议。
86
- env = {'PATH': '/usr/local/bin:/usr/bin:/bin', 'HOME': str(workdir), 'TMPDIR': str(workdir), 'LANG': 'C.UTF-8'}
87
- with subprocess.Popen(args, cwd=workdir, env=env, stdin=subprocess.DEVNULL,
88
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) as child:
89
- try:
90
- code = child.wait(timeout=timeout)
91
- except BaseException:
92
- try:
93
- os.killpg(child.pid, signal.SIGKILL)
94
- except ProcessLookupError:
95
- pass
96
- child.wait()
97
- raise
98
- if code != 0:
99
- raise ToolError('TOOL_FAILED', 'The selected operation failed')
100
-
101
-
102
- def no_duplicates(pairs):
103
- values = {}
104
- for key, value in pairs:
105
- if key in values:
106
- raise ToolError('INVALID_REQUEST', 'Duplicate request field')
107
- values[key] = value
108
- return values
109
-
110
-
111
- def serve(source, response, commands, inputs, outputs):
112
- try:
113
- raw = source.read(REQUEST_LIMIT + 1)
114
- if len(raw) > REQUEST_LIMIT:
115
- raise ToolError('INVALID_REQUEST', 'Request exceeds the size limit')
116
- request = json.loads(raw.decode('utf-8'), object_pairs_hook=no_duplicates)
117
- operation = request.get('operation') if isinstance(request, dict) else None
118
- if not isinstance(operation, str) or operation not in commands:
119
- raise ToolError('INVALID_REQUEST', 'Unknown operation')
120
- required, optional, handler = commands[operation]
121
- keys = set(request) - {'operation'}
122
- if not required <= keys <= required | optional:
123
- raise ToolError('INVALID_REQUEST', 'Missing or unsupported request fields')
124
- item = input_file(inputs, request['input']) if 'input' in request else None
125
- artifact = output_file(outputs, request['output']) if 'output' in request else None
126
- with tempfile.TemporaryDirectory(prefix='hai-tool-') as workspace:
127
- data = handler(request, item, artifact, pathlib.Path(workspace))
128
- result = {'success': True, 'data': data}
129
- except ToolError as error:
130
- result = {'success': False, 'error': {'code': error.code, 'message': str(error)}}
131
- except (json.JSONDecodeError, UnicodeDecodeError, RecursionError):
132
- result = {'success': False, 'error': {'code': 'INVALID_REQUEST', 'message': 'Malformed JSON request'}}
133
- except subprocess.TimeoutExpired:
134
- result = {'success': False, 'error': {'code': 'TIMEOUT', 'message': 'The selected operation timed out'}}
135
- except (OSError, ValueError):
136
- result = {'success': False, 'error': {'code': 'TOOL_FAILED', 'message': 'The selected operation failed'}}
137
- response.write(json.dumps(result, ensure_ascii=True, allow_nan=False) + '\n')
138
-
139
-
140
- if __name__ == '__main__':
141
- # 可执行文件只加载构建时随镜像复制的固定操作。
142
- sys.path.insert(0, '/opt/hai-tools')
143
- sys.modules['tool'] = sys.modules[__name__]
144
- from operation import commands
145
- serve(sys.stdin.buffer, sys.stdout, commands, pathlib.Path('/input'), pathlib.Path('/output'))