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

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 (45) hide show
  1. package/README.en.md +567 -69
  2. package/README.ja.md +568 -70
  3. package/README.md +569 -71
  4. package/dist/{ai-audio-ws-protocol-1VhScfis.d.ts → ai-acp-types-DuPV5UGi.d.ts} +4922 -333
  5. package/dist/browser.d.ts +8 -5
  6. package/dist/browser.js +3 -3
  7. package/dist/{chunk-GMQFIWND.js → chunk-ILUCWONQ.js} +101 -13
  8. package/dist/chunk-ILUCWONQ.js.map +1 -0
  9. package/dist/{chunk-GAC5RLAG.js → chunk-LENTVEBE.js} +566 -45
  10. package/dist/chunk-LENTVEBE.js.map +1 -0
  11. package/dist/{chunk-HYMP57AC.js → chunk-NRDLMUSY.js} +25 -2
  12. package/dist/chunk-NRDLMUSY.js.map +1 -0
  13. package/dist/client/index.d.ts +28 -2
  14. package/dist/client/index.js +2 -2
  15. package/dist/index.d.ts +9 -13
  16. package/dist/index.js +10537 -1966
  17. package/dist/index.js.map +1 -1
  18. package/models/agents/README.md +119 -0
  19. package/models/agents/build.mjs +177 -0
  20. package/models/agents/codex-acp/Dockerfile +21 -0
  21. package/models/agents/codex-acp/agent.json +16 -0
  22. package/models/agents/deepseek-harness/Dockerfile +18 -0
  23. package/models/agents/deepseek-harness/agent.json +14 -0
  24. package/models/agents/goose/Dockerfile +29 -0
  25. package/models/agents/goose/agent.json +14 -0
  26. package/package.json +27 -31
  27. package/tools/.dockerignore +4 -0
  28. package/tools/README.md +111 -0
  29. package/tools/archives.py +56 -0
  30. package/tools/browser/Dockerfile +19 -0
  31. package/tools/browser/operation.py +50 -0
  32. package/tools/browser/render.mjs +40 -0
  33. package/tools/documents/Dockerfile +20 -0
  34. package/tools/documents/operation.py +80 -0
  35. package/tools/ocr/Dockerfile +19 -0
  36. package/tools/ocr/operation.py +18 -0
  37. package/tools/office/Dockerfile +21 -0
  38. package/tools/office/office_job.py +65 -0
  39. package/tools/office/operation.py +43 -0
  40. package/tools/tests/image-smoke.mjs +83 -0
  41. package/tools/tests/test_hai_tool.py +82 -0
  42. package/tools/tool.py +145 -0
  43. package/dist/chunk-GAC5RLAG.js.map +0 -1
  44. package/dist/chunk-GMQFIWND.js.map +0 -1
  45. package/dist/chunk-HYMP57AC.js.map +0 -1
@@ -0,0 +1,56 @@
1
+ """对 Office ZIP 容器执行解包配额和主动内容筛查。"""
2
+ import pathlib
3
+ import xml.etree.ElementTree as ET
4
+ import zipfile
5
+ from tool import ToolError
6
+
7
+
8
+ class OfficeArchive:
9
+ def __init__(self, path):
10
+ self.archive = zipfile.ZipFile(path)
11
+ try:
12
+ files = self.archive.infolist()
13
+ names = [item.filename for item in files]
14
+ if len(files) > 2048 or len(names) != len(set(names)) or sum(item.file_size for item in files) > 100 * 1024 * 1024:
15
+ raise ToolError('UNSAFE_DOCUMENT', 'Document exceeds the archive limits')
16
+ for item in files:
17
+ name = item.filename.lower()
18
+ parts = pathlib.PurePosixPath(name).parts
19
+ if (name.startswith('/') or '\\' in name or '..' in parts or item.flag_bits & 1
20
+ or 'vbaproject' in name or '/embeddings/' in name or '/activex/' in name
21
+ or '/externallinks/' in name or name.startswith(('basic/', 'scripts/'))):
22
+ raise ToolError('UNSAFE_DOCUMENT', 'Document contains unsupported active content')
23
+ except BaseException:
24
+ self.archive.close()
25
+ raise
26
+
27
+ def __enter__(self):
28
+ return self
29
+
30
+ def __exit__(self, *_):
31
+ self.archive.close()
32
+
33
+ def xml(self, name):
34
+ info = self.archive.getinfo(name)
35
+ if info.file_size > 16 * 1024 * 1024:
36
+ raise ToolError('UNSAFE_DOCUMENT', 'Document XML exceeds the size limit')
37
+ source = self.archive.read(info).decode('utf-8-sig')
38
+ if '<!DOCTYPE' in source or '<!ENTITY' in source or '\x00' in source:
39
+ raise ToolError('UNSAFE_DOCUMENT', 'Document XML must not define entities')
40
+ return ET.fromstring(source)
41
+
42
+ def reject_external_links(self):
43
+ for name in self.archive.namelist():
44
+ if name.endswith('.rels'):
45
+ for link in self.xml(name):
46
+ if link.get('TargetMode', '').lower() == 'external':
47
+ raise ToolError('UNSAFE_DOCUMENT', 'Document references an external resource')
48
+ if name in ('content.xml', 'styles.xml', 'settings.xml'):
49
+ for element in self.xml(name).iter():
50
+ link = element.get('{http://www.w3.org/1999/xlink}href', '')
51
+ if link.startswith(('.', '/', '\\')) or ':' in link:
52
+ raise ToolError('UNSAFE_DOCUMENT', 'Document references an external resource')
53
+
54
+
55
+ def office_archive_error():
56
+ return ToolError('INVALID_INPUT', 'Invalid office document')
@@ -0,0 +1,19 @@
1
+ FROM docker.io/library/node:24.22.1-bookworm-slim@sha256:be8204d4bd327363357f532187b752ff62759c31bedf98e9e18fc08c9cbd605c
2
+ RUN mkdir -p /etc/ssl/certs && node -e "require('node:fs').writeFileSync('/etc/ssl/certs/ca-certificates.crt', require('node:tls').rootCertificates.join('\\n'))"
3
+ ARG DEBIAN_MIRROR=https://deb.debian.org/debian
4
+ ARG DEBIAN_SECURITY_MIRROR=https://deb.debian.org/debian-security
5
+ RUN set -eu; \
6
+ sed -i -e "s|http://deb.debian.org/debian-security|${DEBIAN_SECURITY_MIRROR}|g" -e "s|http://deb.debian.org/debian|${DEBIAN_MIRROR}|g" /etc/apt/sources.list.d/debian.sources; \
7
+ apt-get -o Acquire::Retries=2 -o Acquire::https::Timeout=20 update; \
8
+ apt-get install -y --no-install-recommends python3 chromium fonts-liberation fonts-noto-cjk; \
9
+ rm -rf /var/lib/apt/lists/*
10
+ RUN mkdir -p /opt/hai-tools /input /output && chown 1000:1000 /output
11
+ COPY tool.py /usr/local/bin/hai-tool
12
+ COPY browser/operation.py /opt/hai-tools/operation.py
13
+ COPY browser/render.mjs /opt/hai-tools/render.mjs
14
+ RUN npm install --prefix /opt/hai-tools --no-audit --no-fund --ignore-scripts playwright-core@1.65.0
15
+ RUN chmod 0555 /usr/local/bin/hai-tool
16
+ USER 1000:1000
17
+ ENV HOME=/tmp PYTHONDONTWRITEBYTECODE=1
18
+ WORKDIR /tmp
19
+ ENTRYPOINT ["/usr/local/bin/hai-tool"]
@@ -0,0 +1,50 @@
1
+ import ipaddress
2
+ import os
3
+ import pathlib
4
+ import re
5
+ from urllib.parse import urlsplit
6
+ from tool import ToolError, publish, run_command
7
+
8
+ HOST = re.compile(r'(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z][A-Za-z0-9-]{1,62}\Z', re.ASCII)
9
+
10
+
11
+ def parse_url(url):
12
+ if not isinstance(url, str) or len(url) > 2048 or any(ord(c) <= 32 or c == '\\' for c in url):
13
+ raise ToolError('INVALID_REQUEST', 'Expected an HTTPS URL')
14
+ try:
15
+ parsed = urlsplit(url)
16
+ if (parsed.scheme == 'https' and parsed.username is None and parsed.password is None
17
+ and parsed.hostname and HOST.fullmatch(parsed.hostname) and parsed.port in (None, 443)):
18
+ return url
19
+ except ValueError:
20
+ pass
21
+ raise ToolError('INVALID_REQUEST', 'Expected HTTPS with a DNS hostname and default port')
22
+
23
+
24
+ def deployment_proxy():
25
+ # 代理身份来自部署环境;作业参数不能替换它。
26
+ try:
27
+ proxy = urlsplit(os.environ.get('HAI_TOOL_BROWSER_PROXY', ''))
28
+ if (proxy.scheme != 'http' or proxy.username is not None or proxy.password is not None
29
+ or proxy.path not in ('', '/') or proxy.query or proxy.fragment or not proxy.port):
30
+ raise ValueError
31
+ host = ipaddress.IPv4Address(proxy.hostname)
32
+ if host.is_loopback or host.is_unspecified or host.is_multicast or host.is_link_local:
33
+ raise ValueError
34
+ return f'http://{host}:{proxy.port}'
35
+ except (TypeError, ValueError):
36
+ raise ToolError('NETWORK_POLICY_REQUIRED', 'A deployment-controlled egress proxy is required') from None
37
+
38
+
39
+ def navigate(request, _source, artifact, workspace):
40
+ url = parse_url(request['url'])
41
+ if artifact.suffix.lower() != '.png':
42
+ raise ToolError('INVALID_REQUEST', 'Browser screenshot must be PNG')
43
+ proxy = deployment_proxy()
44
+ result = workspace / 'screen.png'
45
+ worker = pathlib.Path(__file__).with_name('render.mjs')
46
+ run_command(['node', str(worker), proxy, url, str(result)], 45, workspace)
47
+ return publish(result, artifact, b'\x89PNG\r\n\x1a\n')
48
+
49
+
50
+ commands = {'browser.navigate': ({'url', 'output'}, set(), navigate)}
@@ -0,0 +1,40 @@
1
+ import process from 'node:process'
2
+ import { chromium } from 'playwright-core'
3
+
4
+ async function render() {
5
+ const [proxy, url, output] = process.argv.slice(2)
6
+ const browser = await chromium.launch({
7
+ executablePath: '/usr/bin/chromium',
8
+ chromiumSandbox: true,
9
+ proxy: { server: proxy, bypass: '<-loopback>' },
10
+ args: ['--disable-quic'],
11
+ })
12
+ try {
13
+ const context = await browser.newContext({
14
+ javaScriptEnabled: false,
15
+ acceptDownloads: false,
16
+ serviceWorkers: 'block',
17
+ viewport: { width: 1280, height: 720 },
18
+ })
19
+ await context.route('**/*', async (route) => {
20
+ const target = new URL(route.request().url())
21
+ if (target.protocol !== 'https:' || target.port || target.username || target.password) {
22
+ await route.abort()
23
+ return
24
+ }
25
+ await route.continue()
26
+ })
27
+ const page = await context.newPage()
28
+ const response = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 20_000 })
29
+ if (!response?.ok() || new URL(page.url()).protocol !== 'https:')
30
+ throw new Error('Navigation failed')
31
+ await page.screenshot({ path: output, timeout: 10_000 })
32
+ }
33
+ finally {
34
+ await browser.close()
35
+ }
36
+ }
37
+
38
+ render().catch(() => {
39
+ process.exitCode = 1
40
+ })
@@ -0,0 +1,20 @@
1
+ FROM docker.io/library/node:24.22.1-bookworm-slim@sha256:be8204d4bd327363357f532187b752ff62759c31bedf98e9e18fc08c9cbd605c AS trust
2
+ RUN mkdir -p /etc/ssl/certs && node -e "require('node:fs').writeFileSync('/etc/ssl/certs/ca-certificates.crt', require('node:tls').rootCertificates.join('\\n'))"
3
+ FROM mcr.microsoft.com/mirror/docker/library/debian:bookworm-slim@sha256:b4aa902587c2e61ce789849cb54c332b0400fe27b1ee33af4669e1f7e7c3e22f
4
+ COPY --from=trust /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
5
+ ARG DEBIAN_MIRROR=https://deb.debian.org/debian
6
+ ARG DEBIAN_SECURITY_MIRROR=https://deb.debian.org/debian-security
7
+ RUN set -eu; \
8
+ sed -i -e "s|http://deb.debian.org/debian-security|${DEBIAN_SECURITY_MIRROR}|g" -e "s|http://deb.debian.org/debian|${DEBIAN_MIRROR}|g" /etc/apt/sources.list.d/debian.sources; \
9
+ apt-get -o Acquire::Retries=2 -o Acquire::https::Timeout=20 update; \
10
+ apt-get install -y --no-install-recommends python3 poppler-utils; \
11
+ rm -rf /var/lib/apt/lists/*
12
+ RUN mkdir -p /opt/hai-tools /input /output && chown 1000:1000 /output
13
+ COPY tool.py /usr/local/bin/hai-tool
14
+ COPY documents/operation.py /opt/hai-tools/operation.py
15
+ COPY archives.py /opt/hai-tools/archives.py
16
+ RUN chmod 0555 /usr/local/bin/hai-tool
17
+ USER 1000:1000
18
+ ENV HOME=/tmp PYTHONDONTWRITEBYTECODE=1
19
+ WORKDIR /tmp
20
+ ENTRYPOINT ["/usr/local/bin/hai-tool"]
@@ -0,0 +1,80 @@
1
+ import xml.etree.ElementTree as ET
2
+ import zipfile
3
+ from archives import OfficeArchive, office_archive_error
4
+ from tool import TEXT_LIMIT, ToolError, read_text, run_command, text_result
5
+
6
+ WORD = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
7
+ SHEET = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
8
+
9
+
10
+ def collect_lines(lines):
11
+ result = []
12
+ size = 0
13
+ for line in lines:
14
+ size += len(line.encode('utf-8')) + 1
15
+ if size > TEXT_LIMIT:
16
+ raise ToolError('OUTPUT_LIMIT', 'Extracted text exceeds the size limit')
17
+ result.append(line)
18
+ return text_result('\n'.join(result))
19
+
20
+
21
+ def word_lines(document):
22
+ for paragraph in document.xml('word/document.xml').iter(WORD + 'p'):
23
+ yield ''.join(value.text or '' for value in paragraph.iter(WORD + 't'))
24
+
25
+
26
+ def sheet_lines(document):
27
+ names = document.archive.namelist()
28
+ strings = []
29
+ if 'xl/sharedStrings.xml' in names:
30
+ for item in document.xml('xl/sharedStrings.xml').iter(SHEET + 'si'):
31
+ strings.append(''.join(value.text or '' for value in item.iter(SHEET + 't')))
32
+ worksheets = sorted(name for name in names if name.startswith('xl/worksheets/') and name.rsplit('/', 1)[1].startswith('sheet') and name.endswith('.xml'))
33
+ if not worksheets:
34
+ raise office_archive_error()
35
+ for name in worksheets:
36
+ yield name.rsplit('/', 1)[1]
37
+ for row in document.xml(name).iter(SHEET + 'row'):
38
+ values = []
39
+ for cell in row.findall(SHEET + 'c'):
40
+ value = cell.findtext(SHEET + 'v') or ''
41
+ cell_type = cell.get('t')
42
+ if cell_type == 's':
43
+ index = int(value)
44
+ if index < 0 or index >= len(strings):
45
+ raise office_archive_error()
46
+ value = strings[index]
47
+ elif cell_type == 'inlineStr':
48
+ value = ''.join(item.text or '' for item in cell.iter(SHEET + 't'))
49
+ values.append(value)
50
+ yield '\t'.join(values)
51
+
52
+
53
+ def extract(_request, source, _artifact, workspace):
54
+ suffix = source.suffix.lower()
55
+ if suffix in ('.txt', '.md', '.csv', '.tsv'):
56
+ try:
57
+ return read_text(source)
58
+ except UnicodeDecodeError:
59
+ raise ToolError('INVALID_INPUT', 'Expected UTF-8 document text') from None
60
+ if suffix == '.pdf':
61
+ with source.open('rb') as stream:
62
+ if not stream.read(5) == b'%PDF-':
63
+ raise ToolError('INVALID_INPUT', 'Invalid PDF document')
64
+ result = workspace / 'extracted.txt'
65
+ # 额外读取一页检测超限,避免把较长文档报告为完整输出。
66
+ run_command(['pdftotext', '-l', '101', '-enc', 'UTF-8', str(source), str(result)], 30, workspace)
67
+ extracted = read_text(result)
68
+ if extracted['text'].count('\f') > 100:
69
+ raise ToolError('OUTPUT_LIMIT', 'PDF exceeds the page limit')
70
+ return extracted
71
+ if suffix in ('.docx', '.xlsx'):
72
+ try:
73
+ with OfficeArchive(source) as document:
74
+ return collect_lines(word_lines(document) if suffix == '.docx' else sheet_lines(document))
75
+ except (zipfile.BadZipFile, KeyError, ValueError, ET.ParseError):
76
+ raise office_archive_error() from None
77
+ raise ToolError('INVALID_INPUT', 'Unsupported document format')
78
+
79
+
80
+ commands = {'documents.extract': ({'input'}, set(), extract)}
@@ -0,0 +1,19 @@
1
+ FROM docker.io/library/node:24.22.1-bookworm-slim@sha256:be8204d4bd327363357f532187b752ff62759c31bedf98e9e18fc08c9cbd605c AS trust
2
+ RUN mkdir -p /etc/ssl/certs && node -e "require('node:fs').writeFileSync('/etc/ssl/certs/ca-certificates.crt', require('node:tls').rootCertificates.join('\\n'))"
3
+ FROM mcr.microsoft.com/mirror/docker/library/debian:bookworm-slim@sha256:b4aa902587c2e61ce789849cb54c332b0400fe27b1ee33af4669e1f7e7c3e22f
4
+ COPY --from=trust /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
5
+ ARG DEBIAN_MIRROR=https://deb.debian.org/debian
6
+ ARG DEBIAN_SECURITY_MIRROR=https://deb.debian.org/debian-security
7
+ RUN set -eu; \
8
+ sed -i -e "s|http://deb.debian.org/debian-security|${DEBIAN_SECURITY_MIRROR}|g" -e "s|http://deb.debian.org/debian|${DEBIAN_MIRROR}|g" /etc/apt/sources.list.d/debian.sources; \
9
+ apt-get -o Acquire::Retries=2 -o Acquire::https::Timeout=20 update; \
10
+ apt-get install -y --no-install-recommends python3 tesseract-ocr tesseract-ocr-eng tesseract-ocr-chi-sim tesseract-ocr-jpn; \
11
+ rm -rf /var/lib/apt/lists/*
12
+ RUN mkdir -p /opt/hai-tools /input /output && chown 1000:1000 /output
13
+ COPY tool.py /usr/local/bin/hai-tool
14
+ COPY ocr/operation.py /opt/hai-tools/operation.py
15
+ RUN chmod 0555 /usr/local/bin/hai-tool
16
+ USER 1000:1000
17
+ ENV HOME=/tmp PYTHONDONTWRITEBYTECODE=1
18
+ WORKDIR /tmp
19
+ ENTRYPOINT ["/usr/local/bin/hai-tool"]
@@ -0,0 +1,18 @@
1
+ from tool import ToolError, read_text, run_command
2
+
3
+ LANGUAGES = {'eng', 'chi_sim', 'jpn', 'eng+chi_sim', 'eng+jpn'}
4
+
5
+
6
+ def recognize(request, source, _artifact, workspace):
7
+ language = request.get('language', 'eng')
8
+ if not isinstance(language, str) or language not in LANGUAGES:
9
+ raise ToolError('INVALID_REQUEST', 'Unsupported OCR language')
10
+ with source.open('rb') as stream:
11
+ header = stream.read(8)
12
+ if not (header.startswith(b'\x89PNG\r\n\x1a\n') or header.startswith(b'\xff\xd8\xff') or header.startswith((b'II*\0', b'MM\0*'))):
13
+ raise ToolError('INVALID_INPUT', 'Expected a PNG, JPEG or TIFF image')
14
+ run_command(['/usr/bin/tesseract', str(source), str(workspace / 'result'), '-l', language], 60, workspace)
15
+ return read_text(workspace / 'result.txt')
16
+
17
+
18
+ commands = {'ocr.recognize': ({'input'}, {'language'}, recognize)}
@@ -0,0 +1,21 @@
1
+ FROM docker.io/library/node:24.22.1-bookworm-slim@sha256:be8204d4bd327363357f532187b752ff62759c31bedf98e9e18fc08c9cbd605c AS trust
2
+ RUN mkdir -p /etc/ssl/certs && node -e "require('node:fs').writeFileSync('/etc/ssl/certs/ca-certificates.crt', require('node:tls').rootCertificates.join('\\n'))"
3
+ FROM mcr.microsoft.com/mirror/docker/library/debian:bookworm-slim@sha256:b4aa902587c2e61ce789849cb54c332b0400fe27b1ee33af4669e1f7e7c3e22f
4
+ COPY --from=trust /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
5
+ ARG DEBIAN_MIRROR=https://deb.debian.org/debian
6
+ ARG DEBIAN_SECURITY_MIRROR=https://deb.debian.org/debian-security
7
+ RUN set -eu; \
8
+ sed -i -e "s|http://deb.debian.org/debian-security|${DEBIAN_SECURITY_MIRROR}|g" -e "s|http://deb.debian.org/debian|${DEBIAN_MIRROR}|g" /etc/apt/sources.list.d/debian.sources; \
9
+ apt-get -o Acquire::Retries=2 -o Acquire::https::Timeout=20 update; \
10
+ apt-get install -y --no-install-recommends python3 python3-uno libreoffice-writer libreoffice-calc libreoffice-impress fonts-liberation fonts-noto-cjk; \
11
+ rm -rf /var/lib/apt/lists/*
12
+ RUN mkdir -p /opt/hai-tools /input /output && chown 1000:1000 /output
13
+ COPY tool.py /usr/local/bin/hai-tool
14
+ COPY office/operation.py /opt/hai-tools/operation.py
15
+ COPY archives.py /opt/hai-tools/archives.py
16
+ COPY office/office_job.py /opt/hai-tools/office_job.py
17
+ RUN chmod 0555 /usr/local/bin/hai-tool
18
+ USER 1000:1000
19
+ ENV HOME=/tmp PYTHONDONTWRITEBYTECODE=1
20
+ WORKDIR /tmp
21
+ ENTRYPOINT ["/usr/local/bin/hai-tool"]
@@ -0,0 +1,65 @@
1
+ """通过独立 LibreOffice profile 和本地 UNO 管道运行单个作业。"""
2
+ import pathlib
3
+ import subprocess
4
+ import sys
5
+ import time
6
+ import uuid
7
+ import uno
8
+ from com.sun.star.beans import PropertyValue
9
+ from com.sun.star.connection import NoConnectException
10
+ from com.sun.star.document.MacroExecMode import NEVER_EXECUTE
11
+ from com.sun.star.document.UpdateDocMode import NO_UPDATE
12
+
13
+
14
+ def property_value(name, value):
15
+ item = PropertyValue()
16
+ item.Name = name
17
+ item.Value = value
18
+ return item
19
+
20
+
21
+ def main():
22
+ source, result, output_filter, operation = sys.argv[1:]
23
+ context = uno.getComponentContext()
24
+ resolver = context.ServiceManager.createInstanceWithContext('com.sun.star.bridge.UnoUrlResolver', context)
25
+ pipe = 'hai_' + uuid.uuid4().hex
26
+ address = 'pipe,name=' + pipe + ';urp;StarOffice.ComponentContext'
27
+ profile = (pathlib.Path.cwd() / 'profile').as_uri()
28
+ with subprocess.Popen([
29
+ '/usr/bin/libreoffice', '-env:UserInstallation=' + profile,
30
+ '--headless', '--nologo', '--norestore', '--nodefault', '--nofirststartwizard', '--accept=' + address,
31
+ ]) as process:
32
+ try:
33
+ deadline = time.monotonic() + 10
34
+ while True:
35
+ try:
36
+ remote = resolver.resolve('uno:' + address)
37
+ break
38
+ except NoConnectException:
39
+ if time.monotonic() >= deadline or process.poll() is not None:
40
+ raise
41
+ time.sleep(0.05)
42
+ desktop = remote.ServiceManager.createInstanceWithContext('com.sun.star.frame.Desktop', remote)
43
+ document = desktop.loadComponentFromURL(pathlib.Path(source).as_uri(), '_blank', 0, (
44
+ property_value('Hidden', True),
45
+ property_value('ReadOnly', True),
46
+ property_value('MacroExecutionMode', NEVER_EXECUTE),
47
+ property_value('UpdateDocMode', NO_UPDATE),
48
+ ))
49
+ if document is None:
50
+ raise RuntimeError('Unable to load office document')
51
+ try:
52
+ if operation == 'recalculate':
53
+ document.calculateAll()
54
+ document.storeToURL(pathlib.Path(result).as_uri(), (property_value('FilterName', output_filter),))
55
+ finally:
56
+ document.dispose()
57
+ desktop.terminate()
58
+ process.wait(timeout=3)
59
+ finally:
60
+ if process.poll() is None:
61
+ process.kill()
62
+
63
+
64
+ if __name__ == '__main__':
65
+ main()
@@ -0,0 +1,43 @@
1
+ import pathlib
2
+ import xml.etree.ElementTree as ET
3
+ import zipfile
4
+ from archives import OfficeArchive, office_archive_error
5
+ from tool import ToolError, publish, run_command
6
+
7
+
8
+ PDF_FILTERS = {
9
+ '.docx': 'writer_pdf_Export', '.odt': 'writer_pdf_Export',
10
+ '.xlsx': 'calc_pdf_Export', '.ods': 'calc_pdf_Export',
11
+ '.pptx': 'impress_pdf_Export', '.odp': 'impress_pdf_Export',
12
+ }
13
+ SHEET_FILTERS = {'.xlsx': 'Calc MS Excel 2007 XML', '.ods': 'calc8'}
14
+
15
+
16
+ def process(request, source, artifact, workspace):
17
+ suffix = source.suffix.lower()
18
+ convert = request['operation'] == 'office.convert'
19
+ if convert:
20
+ if suffix not in PDF_FILTERS or artifact.suffix.lower() != '.pdf':
21
+ raise ToolError('INVALID_REQUEST', 'Conversion requires a supported office document and PDF output')
22
+ output_filter = PDF_FILTERS[suffix]
23
+ signature = b'%PDF-'
24
+ else:
25
+ if suffix not in SHEET_FILTERS or artifact.suffix.lower() != suffix:
26
+ raise ToolError('INVALID_REQUEST', 'Recalculation requires matching XLSX or ODS input and output')
27
+ output_filter = SHEET_FILTERS[suffix]
28
+ signature = b'PK\x03\x04'
29
+ try:
30
+ with OfficeArchive(source) as document:
31
+ document.reject_external_links()
32
+ except (zipfile.BadZipFile, KeyError, ValueError, ET.ParseError):
33
+ raise office_archive_error() from None
34
+ result = workspace / artifact.name
35
+ worker = pathlib.Path(__file__).with_name('office_job.py')
36
+ run_command(['/usr/bin/python3', str(worker), str(source), str(result), output_filter, 'convert' if convert else 'recalculate'], 90, workspace)
37
+ return publish(result, artifact, signature)
38
+
39
+
40
+ commands = {
41
+ 'office.convert': ({'input', 'output'}, set(), process),
42
+ 'office.recalculate': ({'input', 'output'}, set(), process),
43
+ }
@@ -0,0 +1,83 @@
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
+ })
@@ -0,0 +1,82 @@
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()