@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.
- package/README.en.md +11 -1114
- package/README.ja.md +10 -1113
- package/README.md +11 -1137
- package/dist/{ai-acp-types-DuPV5UGi.d.ts → ai-acp-types-cue1ZWUk.d.ts} +4970 -5227
- package/dist/ai-file-types-BN7l67hR.d.ts +167 -0
- package/dist/ai-file-worker.d.ts +38 -0
- package/dist/ai-file-worker.js +85 -0
- package/dist/ai-file-worker.js.map +1 -0
- package/dist/ai-video-archive-worker.d.ts +32 -0
- package/dist/ai-video-archive-worker.js +102 -0
- package/dist/ai-video-archive-worker.js.map +1 -0
- package/dist/browser.d.ts +5 -2
- package/dist/browser.js +4 -3
- package/dist/{chunk-NRDLMUSY.js → chunk-C6T3ONVG.js} +4 -8
- package/dist/chunk-C6T3ONVG.js.map +1 -0
- package/dist/{chunk-LENTVEBE.js → chunk-HZDINADT.js} +254 -973
- package/dist/chunk-HZDINADT.js.map +1 -0
- package/dist/chunk-IVEOIRBO.js +971 -0
- package/dist/chunk-IVEOIRBO.js.map +1 -0
- package/dist/chunk-OWR55FRO.js +140 -0
- package/dist/chunk-OWR55FRO.js.map +1 -0
- package/dist/{chunk-ILUCWONQ.js → chunk-UVBQCI7A.js} +3 -3
- package/dist/{chunk-ILUCWONQ.js.map → chunk-UVBQCI7A.js.map} +1 -1
- package/dist/client/index.js +2 -2
- package/dist/index.d.ts +6 -3
- package/dist/index.js +1492 -743
- package/dist/index.js.map +1 -1
- package/models/agents/README.md +3 -1
- package/models/agents/deepseek-harness/Dockerfile +2 -0
- package/package.json +10 -10
- package/dist/chunk-LENTVEBE.js.map +0 -1
- package/dist/chunk-NRDLMUSY.js.map +0 -1
- package/tools/.dockerignore +0 -4
- package/tools/README.md +0 -111
- package/tools/archives.py +0 -56
- package/tools/browser/Dockerfile +0 -19
- package/tools/browser/operation.py +0 -50
- package/tools/browser/render.mjs +0 -40
- package/tools/documents/Dockerfile +0 -20
- package/tools/documents/operation.py +0 -80
- package/tools/ocr/Dockerfile +0 -19
- package/tools/ocr/operation.py +0 -18
- package/tools/office/Dockerfile +0 -21
- package/tools/office/office_job.py +0 -65
- package/tools/office/operation.py +0 -43
- package/tools/tests/image-smoke.mjs +0 -83
- package/tools/tests/test_hai_tool.py +0 -82
- package/tools/tool.py +0 -145
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ai-types.ts"],"names":[],"mappings":"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","file":"chunk-NRDLMUSY.js","sourcesContent":["import type { ErrorInfo, HaiResult } from '@h-ai/core'\nimport type { RunnerFunctions } from '@h-ai/runner'\nimport type { A2AOperations } from './a2a/ai-a2a-types.js'\nimport type { ACPPlatformPolicy } from './acp/ai-acp-platform.js'\nimport type { ACPAgentAdapter, ACPOperations } from './acp/ai-acp-types.js'\n/**\n * @h-ai/ai — 公共类型定义\n *\n * 聚合导出模块根类型和子功能类型,供外部通过 `@h-ai/ai` 一站式引入。\n * @module ai-types\n */\n\nimport type { AIConfig, AIConfigInput } from './ai-config.js'\n\nimport type { CompressOperations } from './compress/ai-compress-types.js'\nimport type { ContextOperations } from './context/ai-context-types.js'\nimport type { EmbeddingOperations } from './embedding/ai-embedding-types.js'\nimport type { FileOperations } from './file/ai-file-types.js'\nimport type { KnowledgeOperations } from './knowledge/ai-knowledge-types.js'\nimport type { StreamOperations, ToolsOperations } from './llm/ai-llm-types.js'\nimport type { MCPJobFiles } from './mcp/ai-mcp-types.js'\nimport type { MemoryOperations } from './memory/ai-memory-types.js'\nimport type { PersonaOperations } from './persona/ai-persona-types.js'\nimport type { RagOperations } from './rag/ai-rag-types.js'\nimport type { ReasoningOperations } from './reasoning/ai-reasoning-types.js'\nimport type { ManagedAudioOperations, ManagedImageOperations, ManagedLLMOperations, ManagedMCPOperations, ManagedRetrievalOperations } from './registry/ai-registry-types.js'\nimport type { RerankOperations } from './rerank/ai-rerank-types.js'\nimport type { AIStoreProvider } from './store/ai-store-types.js'\nimport type { SummaryOperations } from './summary/ai-summary-types.js'\nimport type { TokenOperations } from './token/ai-token-types.js'\nimport { core } from '@h-ai/core'\n\n// ─── 错误定义(照 @h-ai/core 范式) ───\n\n/**\n * AI 错误信息映射(错误码:HTTP状态码)。\n *\n * 错误码采用 3 位数字格式(000-999),HTTP 状态码遵循标准 HTTP 规范。\n * 完整错误码将自动生成为:`hai:ai:NNN`\n */\nconst AIErrorInfo = {\n // 通用 (000-009)\n INTERNAL_ERROR: '000:500',\n ACP_GIT_NOT_FOUND: '070:500',\n ACP_OPERATION_FAILED: '071:500',\n ACP_INVALID_REQUEST: '072:400',\n ACP_NOT_FOUND: '073:404',\n ACP_BUSY: '074:409',\n ACP_UNSUPPORTED: '075:422',\n ACP_CANCELLED: '076:499',\n ACP_TIMEOUT: '077:504',\n ACP_OUTPUT_INVALID: '078:422',\n ACP_CONFLICT: '079:409',\n ACP_PARTIAL_FAILURE: '080:409',\n ACP_CLOSED: '081:409',\n ACP_RUNTIME_UNAVAILABLE: '082:503',\n ACP_MODEL_INCOMPATIBLE: '083:422',\n ACP_CLEANUP_FAILED: '084:500',\n\n // 初始化 (010-019)\n NOT_INITIALIZED: '010:500',\n CONFIGURATION_ERROR: '011:500',\n INIT_IN_PROGRESS: '012:500',\n RERANK_API_ERROR: '020:502',\n RERANK_INVALID_REQUEST: '021:400',\n\n // LLM (100-199)\n API_ERROR: '100:502',\n INVALID_REQUEST: '101:400',\n RATE_LIMITED: '102:429',\n TIMEOUT: '103:504',\n MODEL_NOT_FOUND: '104:404',\n CONTEXT_LENGTH_EXCEEDED: '105:400',\n LLM_RECORD_FAILED: '106:500',\n LLM_HISTORY_FAILED: '107:500',\n\n // MCP (200-299)\n MCP_CONNECTION_ERROR: '200:502',\n MCP_PROTOCOL_ERROR: '201:502',\n MCP_TOOL_ERROR: '202:500',\n MCP_RESOURCE_ERROR: '203:500',\n MCP_SERVER_ERROR: '204:502',\n MCP_TOOL_FORBIDDEN: '205:403',\n MCP_TOOL_CANCELLED: '206:499',\n\n // Embedding (300-399)\n EMBEDDING_API_ERROR: '300:502',\n EMBEDDING_MODEL_NOT_FOUND: '301:404',\n EMBEDDING_INPUT_TOO_LONG: '302:400',\n\n // 工具 (400-499)\n TOOL_NOT_FOUND: '400:404',\n TOOL_VALIDATION_FAILED: '401:400',\n TOOL_EXECUTION_FAILED: '402:500',\n TOOL_TIMEOUT: '403:504',\n TOOL_ALREADY_REGISTERED: '404:409',\n TOOL_FORBIDDEN: '405:403',\n\n // Reasoning (500-599)\n REASONING_FAILED: '500:500',\n REASONING_MAX_ROUNDS: '501:400',\n REASONING_STRATEGY_NOT_FOUND: '502:404',\n\n // Retrieval (600-699)\n RETRIEVAL_FAILED: '600:500',\n RETRIEVAL_SOURCE_NOT_FOUND: '601:404',\n\n // RAG (700-799)\n RAG_FAILED: '700:500',\n RAG_CONTEXT_BUILD_FAILED: '701:500',\n\n // Knowledge (800-899)\n KNOWLEDGE_SETUP_FAILED: '800:500',\n KNOWLEDGE_INGEST_FAILED: '801:500',\n KNOWLEDGE_RETRIEVE_FAILED: '802:500',\n KNOWLEDGE_ENTITY_EXTRACT_FAILED: '803:500',\n KNOWLEDGE_NOT_SETUP: '804:500',\n KNOWLEDGE_COLLECTION_NOT_FOUND: '805:404',\n\n // Memory (900-949)\n MEMORY_EXTRACT_FAILED: '900:500',\n MEMORY_STORE_FAILED: '901:500',\n MEMORY_RECALL_FAILED: '902:500',\n MEMORY_NOT_FOUND: '903:404',\n MEMORY_ENRICH_FAILED: '904:500',\n MEMORY_PROMOTE_FAILED: '905:500',\n MEMORY_LIST_INCOMPLETE: '906:422',\n\n // Persona (910-919)\n PERSONA_NOT_FOUND: '910:404',\n PERSONA_SAVE_FAILED: '911:500',\n\n // File (030-049)\n FILE_PARSE_FAILED: '030:500',\n FILE_UNSUPPORTED_FORMAT: '031:400',\n FILE_OCR_FAILED: '032:500',\n FILE_INVALID_CONTENT: '033:400',\n\n // Audio (050-059)\n AUDIO_INVALID_REQUEST: '050:400',\n AUDIO_MODEL_NOT_FOUND: '051:404',\n AUDIO_PROVIDER_NOT_FOUND: '052:404',\n AUDIO_UNSUPPORTED_INPUT: '053:400',\n AUDIO_UPSTREAM_ERROR: '054:502',\n AUDIO_PROTOCOL_ERROR: '055:502',\n AUDIO_CONNECTION_FAILED: '056:502',\n AUDIO_TIMEOUT: '057:504',\n AUDIO_INPUT_TOO_LARGE: '058:413',\n AUDIO_CANCELLED: '059:499',\n\n // Image (060-069)\n IMAGE_INVALID_REQUEST: '060:400',\n IMAGE_MODEL_NOT_FOUND: '061:404',\n IMAGE_PROVIDER_NOT_FOUND: '062:404',\n IMAGE_UPSTREAM_ERROR: '063:502',\n IMAGE_PROTOCOL_ERROR: '064:502',\n IMAGE_CANCELLED: '065:499',\n IMAGE_DOWNLOAD_BLOCKED: '066:502',\n IMAGE_TOO_LARGE: '067:413',\n IMAGE_TIMEOUT: '068:504',\n\n // 可维护资源清单(090-094)\n RESOURCE_READ_ONLY: '090:403',\n RESOURCE_NOT_FOUND: '091:404',\n RESOURCE_CONFLICT: '092:409',\n RESOURCE_INVALID: '093:400',\n RESOURCE_OPERATION_FAILED: '094:500',\n\n // Context (950-999)\n CONTEXT_COMPRESS_FAILED: '950:500',\n CONTEXT_SUMMARIZE_FAILED: '951:500',\n CONTEXT_TOKEN_ESTIMATE_FAILED: '952:500',\n CONTEXT_BUDGET_EXCEEDED: '953:400',\n CONTEXT_TURN_NOT_FOUND: '954:404',\n CONTEXT_TURN_INVALID_STATE: '955:409',\n CONTEXT_BUSY: '956:409',\n\n // Store (960-969)\n STORE_FAILED: '960:500',\n STORE_NOT_AVAILABLE: '961:503',\n\n // Session (970-979)\n SESSION_NOT_FOUND: '970:404',\n SESSION_FAILED: '971:500',\n\n // A2A (980-999)\n A2A_NOT_CONFIGURED: '980:500',\n A2A_HANDLE_FAILED: '981:500',\n A2A_REMOTE_CALL_FAILED: '982:502',\n A2A_AUTH_FAILED: '983:401',\n A2A_LIST_MESSAGES_FAILED: '984:500',\n} as const satisfies ErrorInfo\n\n/**\n * AI 模块标准错误定义。通过错误码比较分支,用户文案由业务边界本地化。\n *\n * @example\n * ```ts\n * import { HaiAIError } from '@h-ai/ai'\n * import { err } from '@h-ai/core'\n * const result = err(HaiAIError.NOT_INITIALIZED, 'AI is not initialized')\n * if (!result.success) {\n * const status = result.error.httpStatus\n * const code = result.error.code\n * }\n * ```\n */\nexport const HaiAIError = core.error.buildHaiErrorsDef('ai', AIErrorInfo)\n\n// ─── 初始化选项 ───\n\n/**\n * AI 初始化运行时选项\n *\n * 用于传入运行时对象(如自定义 StoreProvider),\n * 这些对象无法通过 Zod 配置 Schema 传递。\n *\n * @example\n * ```ts\n * import { ai, type AIConfigInput, type AIInitOptions, type AIStoreProvider } from '@h-ai/ai'\n * async function start(config: AIConfigInput, storeProvider: AIStoreProvider) {\n * const options: AIInitOptions = { storeProvider }\n * const result = await ai.init(config, options)\n * if (!result.success) throw new Error(result.error.message)\n * }\n * ```\n */\nexport interface AIInitOptions {\n /** 由应用初始化和关闭的受管执行实例。 */\n runner?: RunnerFunctions\n /** 应用对受管 ACP 请求执行的可信授权。 */\n acpPolicy?: ACPPlatformPolicy\n /** 在作业领取者上验证文件权限、读入对象和暂存结果。 */\n mcpJobFiles?: MCPJobFiles\n /** 可信服务端扩展:为其他 ACP 智能体生成原生配置。 */\n acpAdapters?: Record<string, ACPAgentAdapter>\n /**\n * 自定义存储 Provider\n *\n * 提供后 AI 模块将使用此 Provider,而不采用自动选择的存储实现。\n * 未提供时:reldb + vecdb 已初始化则使用持久化 DB Provider,否则使用进程内临时 Provider。\n */\n storeProvider?: AIStoreProvider\n}\n\n// ─── AIFunctions 接口 ───\n\n/**\n * AI 服务接口(通过 `ai` 对象访问)\n *\n * 所有 AI 功能的统一入口,需先调用 `init()` 初始化后才能使用 `llm`、`mcp` 操作。\n * `tools` 和 `stream` 为纯函数,无需初始化即可使用。\n *\n * @example\n * ```ts\n * import { ai, type AIConfigInput, type AIInitOptions } from '@h-ai/ai'\n * // 一次性脚本示例;服务应用在启动阶段 init,在停止接入请求后 close。\n * async function run(config: AIConfigInput, options: AIInitOptions) {\n * const ready = await ai.init(config, options)\n * if (!ready.success) throw new Error(ready.error.message)\n * try {\n * const answer = await ai.llm.ask('你好', { objectId: 'user-1' })\n * if (!answer.success) throw new Error(answer.error.message)\n * return answer.data\n * }\n * finally {\n * await ai.close()\n * }\n * }\n * ```\n */\nexport interface AIFunctions {\n /**\n * 初始化 AI 服务\n *\n * 使用 Zod Schema 校验配置,失败返回 `CONFIGURATION_ERROR`。\n * 重复调用会先关闭旧实例再重新初始化。\n *\n * @param config - AI 配置(可选,默认使用空对象并应用 Schema 默认值)\n * @param options - 运行时选项(可选,用于传入自定义 StoreProvider 等运行时对象)\n * @returns 成功返回 `ok(undefined)`;配置校验失败返回 `err(HaiAIError.CONFIGURATION_ERROR)`\n */\n init: (config?: AIConfigInput, options?: AIInitOptions) => Promise<HaiResult<void>>\n /**\n * 关闭 AI 服务,释放内部状态\n *\n * 关闭后 `llm`、`mcp` 操作将返回 `NOT_INITIALIZED` 错误。\n * 重复关闭不会报错。\n */\n close: () => Promise<void>\n /** 当前脱敏后的配置快照(未初始化时为 `null`) */\n readonly config: AIConfig | null\n /** 是否已初始化(`init()` 成功后为 `true`,`close()` 后为 `false`) */\n readonly isInitialized: boolean\n /** LLM 操作(聊天、流式、模型列表),需要先调用 `init()` */\n readonly llm: ManagedLLMOperations\n /** ACP 智能体、工作区与原生会话,需要先调用 `init()`。 */\n readonly acp: ACPOperations\n /** MCP 本地函数注册及配置/数据库外部服务清单,需要先调用 `init()`。 */\n readonly mcp: ManagedMCPOperations\n /** 工具操作(定义工具与注册表),纯函数,无需初始化 */\n readonly tools: ToolsOperations\n /** 流处理操作(流处理器、SSE 编解码),纯函数,无需初始化 */\n readonly stream: StreamOperations\n /** Embedding 操作(向量嵌入),需要先调用 `init()` */\n readonly embedding: EmbeddingOperations\n /** 推理操作(ReAct / CoT / Plan-Execute),需要先调用 `init()` */\n readonly reasoning: ReasoningOperations\n /** 检索操作(向量检索),需要先调用 `init()` */\n readonly retrieval: ManagedRetrievalOperations\n /** RAG 操作(检索增强生成),需要先调用 `init()` */\n readonly rag: RagOperations\n /** Knowledge 操作(知识库管理与检索),需要先调用 `init()` 和 `knowledge.setup()` */\n readonly knowledge: KnowledgeOperations\n /** Memory 操作(记忆提取、存储、检索、注入),需要先调用 `init()` */\n readonly memory: MemoryOperations\n /** Persona 操作(AI 角色人格档案与系统提示词组合),需要先调用 `init()` */\n readonly persona: PersonaOperations\n /** Token 操作(Token 估算),需要先调用 `init()` */\n readonly token: TokenOperations\n /** Summary 操作(消息摘要生成),需要先调用 `init()` */\n readonly summary: SummaryOperations\n /** Compress 操作(上下文压缩),需要先调用 `init()` */\n readonly compress: CompressOperations\n /** Context 操作(有状态上下文管理器,编排 LLM + Memory + RAG + Reasoning),需要先调用 `init()` */\n readonly context: ContextOperations\n /** Rerank 操作(文档重排序),需要先调用 `init()` */\n readonly rerank: RerankOperations\n /** File 操作(文件内容解析),需要先调用 `init()` */\n readonly file: FileOperations\n /** A2A 操作(Agent-to-Agent 协议),需要先调用 `init()` 并配置 `a2a` */\n readonly a2a: A2AOperations\n /** Audio 操作(语音识别 / 语音合成),需要先调用 `init()` 并配置 `audio` */\n readonly audio: ManagedAudioOperations\n /** Image 操作(文生图),需要先调用 `init()` 并配置 `image` */\n readonly image: ManagedImageOperations\n}\n"]}
|
package/tools/.dockerignore
DELETED
package/tools/README.md
DELETED
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
# 独立文档、Office、OCR 与浏览器工具
|
|
2
|
-
|
|
3
|
-
四个镜像使用同一个 JSON 协议。工具以非 root 用户执行一次请求,由部署方选择镜像并分配资源。文档、Office 和 OCR 支持通过受管 MCP 作业调用,应用也可直接提交这些作业。浏览器镜像由部署方独立运行,远程导航需先验收下文的代理和出网限制。
|
|
4
|
-
|
|
5
|
-
| 镜像 | 操作 | 输入与输出 |
|
|
6
|
-
| ----------- | -------------------- | ---------------------------------------------------------------------------------------------------- |
|
|
7
|
-
| `documents` | `documents.extract` | TXT、Markdown、CSV、TSV、文本 PDF、DOCX、XLSX → 文本。XLSX 读已有单元格值与缓存,公式重算使用 Office |
|
|
8
|
-
| `office` | `office.convert` | DOCX、ODT、XLSX、ODS、PPTX、ODP → PDF |
|
|
9
|
-
| `office` | `office.recalculate` | XLSX、ODS → 同格式文件。LibreOffice 重新计算公式 |
|
|
10
|
-
| `ocr` | `ocr.recognize` | PNG、JPEG、TIFF → 文本。可选 `language` 为 `eng`、`chi_sim`、`jpn`、`eng+chi_sim` 或 `eng+jpn` |
|
|
11
|
-
| `browser` | `browser.navigate` | 访问受控代理允许的 HTTPS 地址,输出 1280 × 720 PNG。关闭 JavaScript、下载和 Service Worker |
|
|
12
|
-
|
|
13
|
-
## 快速开始
|
|
14
|
-
|
|
15
|
-
在仓库根目录构建,选择需要的镜像。发布时应为每种镜像独立版本化,并在执行环境中登记产物 digest。
|
|
16
|
-
|
|
17
|
-
```sh
|
|
18
|
-
# 输入 documents 的 Dockerfile 与共用构建目录,输出可由 Podman 启动的本地镜像。
|
|
19
|
-
podman build -f packages/ai/tools/documents/Dockerfile -t localhost/hai-tools-documents:local packages/ai/tools
|
|
20
|
-
```
|
|
21
|
-
|
|
22
|
-
入口 `/usr/local/bin/hai-tool` 从标准输入读取一个 UTF-8 JSON 对象,在 EOF 后运行。每次请求最多 64 KiB。文件名最多 128 个 ASCII 字符,可用字母、数字、点、下划线和连字符,首字符必须是字母或数字。挂载独立的 `/input` 只读目录和空的 `/output` 目录,UID 1000 必须能够读取输入及写入输出。输入单文件和产物上限 50 MiB,抽取文本上限 256 KiB,文本 PDF 上限 100 页。
|
|
23
|
-
|
|
24
|
-
文本结果形如 `{"success":true,"data":{"text":"..."}}`。产物结果形如 `{"success":true,"data":{"artifact":{"name":"report.pdf","bytes":1234}}}`。业务失败返回 `success: false` 和稳定的 `error.code`;调用方须检查结果和实际产物。每个进程只处理一个请求,成功后回收工作环境。
|
|
25
|
-
|
|
26
|
-
## 功能
|
|
27
|
-
|
|
28
|
-
### 提取文档文字
|
|
29
|
-
|
|
30
|
-
使用 `documents` 镜像读取 `/input/report.pdf`,文件中已有的文本通过标准输出返回。例如包含单行 `Release checklist` 的文本 PDF 会得到 `data.text` 中的 `Release checklist`。扫描图像交给 OCR。
|
|
31
|
-
|
|
32
|
-
```json
|
|
33
|
-
{ "operation": "documents.extract", "input": "report.pdf" }
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
### 转换 Office 文档与重算公式
|
|
37
|
-
|
|
38
|
-
使用 `office` 镜像。第一个请求读入 `/input/report.docx`,成功写出 `/output/report.pdf`,返回 `data.artifact.name` 和实际字节数。第二个请求读入 `/input/budget.xlsx`,成功写出 `/output/calculated.xlsx`,重新计算公式缓存并返回同样的产物元数据。两次请求各自启动一个容器。
|
|
39
|
-
|
|
40
|
-
```json
|
|
41
|
-
{ "operation": "office.convert", "input": "report.docx", "output": "report.pdf" }
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
```json
|
|
45
|
-
{ "operation": "office.recalculate", "input": "budget.xlsx", "output": "calculated.xlsx" }
|
|
46
|
-
```
|
|
47
|
-
|
|
48
|
-
### 识别扫描图像
|
|
49
|
-
|
|
50
|
-
使用 `ocr` 镜像。此例识别 `/input/label.png` 中的英文和简体中文,成功返回 `data.text`,如 `Warehouse 仓库`。`language` 省略时使用 `eng`,支持的组合见上表。图像由部署侧按文件授权提供。
|
|
51
|
-
|
|
52
|
-
```json
|
|
53
|
-
{ "operation": "ocr.recognize", "input": "label.png", "language": "eng+chi_sim" }
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
### 从受控网站生成截图
|
|
57
|
-
|
|
58
|
-
使用 `browser` 镜像。代理允许访问示例地址且页面返回成功时,生成 `/output/page.png`,返回 `data.artifact.name: "page.png"` 和字节数。截图固定为 1280 × 720,应用在交付产物前复核归属。
|
|
59
|
-
|
|
60
|
-
```json
|
|
61
|
-
{ "operation": "browser.navigate", "url": "https://example.com/", "output": "page.png" }
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
## 配置
|
|
65
|
-
|
|
66
|
-
部署时将文件工具连接到无网络的独立作业容器,使用只读根文件系统、受限临时目录、PID/CPU/内存上限。LibreOffice 使用每次新建的 profile,以 UNO 设置禁用宏执行和链接更新,且拒绝包含外部关系、嵌入对象、宏及超限 ZIP 的输入。需要访问外部资源的文档应事先在受控流程中移除这些引用。[LibreOffice 宏执行模式](https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1document_1_1MacroExecMode.html) · [文档更新模式](https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1document_1_1UpdateDocMode.html)
|
|
67
|
-
|
|
68
|
-
应用可将文档、Office、OCR 环境登记到 Runner,再在 `mcp.servers` 用 `transport: job` 绑定环境和工具白名单。任务只传授权文件 ID,执行节点通过 `mcpJobFiles` 复核权限后读入对象和暂存产物。Runner 用独立的工具容量领取作业,服务的 `pool.maxRunning` 控制所有执行节点上的并发上限。应用按产物所有者验证下载权限。配置示例见 [MCP 配置](../../../docs/usage/configuration/ai.md#mcp和a2a)。
|
|
69
|
-
|
|
70
|
-
部署配置可设置 `pool.minReady` 和 `pool.maxTotal`。预热实例为空容器,每次只交给一个作业,完成后销毁。工具实例准备、领取和销毁期间持续占用资源额度。
|
|
71
|
-
|
|
72
|
-
浏览器镜像要求部署提供 `HAI_TOOL_BROWSER_PROXY=http://<代理的 IPv4 地址>:<端口>`。作业网络必须只允许连接该代理的地址和端口。代理逐个校验 CONNECT 目的地,执行任务授权、DNS/IP、内网限制及重定向和子资源策略。镜像启用 Chromium 沙箱,启动失败时由上层报告环境错误。部署未提供这些边界前保持操作停用。[Chromium 代理规则](https://chromium.googlesource.com/chromium/src/+/HEAD/net/docs/proxy.md)
|
|
73
|
-
|
|
74
|
-
## 错误处理
|
|
75
|
-
|
|
76
|
-
校验 `success` 后再读 `data.text` 或 `data.artifact`。输入或输出文件名不合规时返回 `INVALID_REQUEST`。浏览器没有可用的部署代理配置时返回 `NETWORK_POLICY_REQUIRED`,工具子进程失败时返回 `TOOL_FAILED`。容器未返回成功时,宿主丢弃本次工作目录及未确认产物。
|
|
77
|
-
|
|
78
|
-
## 开发测试
|
|
79
|
-
|
|
80
|
-
```sh
|
|
81
|
-
python3 -B -m unittest discover -s packages/ai/tools/tests
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
用已构建的文档和 Office 镜像复测受管工具。测试包含真实的 MCP HTTP 入口、Runner、离线容器以及 PDF 产物提交。
|
|
85
|
-
|
|
86
|
-
```sh
|
|
87
|
-
HAI_TOOL_IMAGE_DOCUMENTS=localhost/hai-tools-documents:local \
|
|
88
|
-
HAI_TOOL_IMAGE_OFFICE=localhost/hai-tools-office:local \
|
|
89
|
-
pnpm --filter @h-ai/ai exec vitest run tests/ai-mcp-services.test.ts
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
`HAI_TEST_CONTAINER_ENGINE=docker` 可选择 Docker,缺省使用 Podman。构建环境应先明确准备两种镜像。未设置对应镜像时,Vitest 会跳过其真实容器测试。
|
|
93
|
-
|
|
94
|
-
在根目录构建各镜像后执行只读、禁网的镜像启动检查。
|
|
95
|
-
|
|
96
|
-
```sh
|
|
97
|
-
for kind in documents office ocr browser; do
|
|
98
|
-
podman build -f "packages/ai/tools/$kind/Dockerfile" -t "localhost/hai-tools-$kind:local" packages/ai/tools || exit 1
|
|
99
|
-
done
|
|
100
|
-
HAI_TOOL_IMAGE_DOCUMENTS=localhost/hai-tools-documents:local \
|
|
101
|
-
HAI_TOOL_IMAGE_OFFICE=localhost/hai-tools-office:local \
|
|
102
|
-
HAI_TOOL_IMAGE_OCR=localhost/hai-tools-ocr:local \
|
|
103
|
-
HAI_TOOL_IMAGE_BROWSER=localhost/hai-tools-browser:local \
|
|
104
|
-
node packages/ai/tools/tests/image-smoke.mjs
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
工具验收需用实际镜像补齐代表性输入、输出内容、离线与网络边界。`office` 还需验证宏、链接和外部数据源不会执行,`browser` 需用受控 HTTPS 站点及代理核对最终截图和拒绝访问的场景。单元测试覆盖请求协议、文件范围与上限、文档链接、OCR 参数和浏览器代理前置条件。
|
|
108
|
-
|
|
109
|
-
## 许可证
|
|
110
|
-
|
|
111
|
-
Apache-2.0
|
package/tools/archives.py
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
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')
|
package/tools/browser/Dockerfile
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
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"]
|
|
@@ -1,50 +0,0 @@
|
|
|
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)}
|
package/tools/browser/render.mjs
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
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
|
-
})
|
|
@@ -1,20 +0,0 @@
|
|
|
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"]
|
|
@@ -1,80 +0,0 @@
|
|
|
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)}
|
package/tools/ocr/Dockerfile
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
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"]
|
package/tools/ocr/operation.py
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
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)}
|
package/tools/office/Dockerfile
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
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"]
|
|
@@ -1,65 +0,0 @@
|
|
|
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()
|
|
@@ -1,43 +0,0 @@
|
|
|
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
|
-
}
|