package tools import ( "bytes" "context" "encoding/json" "fmt" "path" "strings" "time" "academy/internal/logger" "academy/internal/models/chat" "academy/internal/types" "academy/internal/utils" "academy/internal/xlsxtranslate" ) // maxTranslateBytes caps one translation run. The largest known real file is // a 63 MB bilingual SIP; the cap leaves headroom for heavier workbooks while // still bounding memory (the package is processed in memory by design, which // is what keeps media byte-identical). const maxTranslateBytes = 256 << 20 // 256 MB // xlsxMagic is the ZIP local-file header every .xlsx container starts with. var xlsxMagic = []byte{0x50, 0x4B, 0x03, 0x04} var legacyXLSMagicBytes = []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1} const xlsxTranslateDescription = `Translate a Chinese engineering Excel workbook (SIP / SOP / inspection standard, .xlsx only) into English and deliver the translated workbook as a downloadable output file. Pass the absolute sandbox path of the uploaded workbook from as file_path. The tool preserves the workbook exactly — merged cells, images, styles, formulas and sheet layout are copied byte-for-byte; only Chinese text (cell strings, inline strings and drawing text boxes) is translated. Part numbers, tolerances and dates are protected as placeholders and never altered. A verification report (residual Chinese, number/part integrity) is returned; the translated workbook lands in the artifact output directory for the user to download.` // XlsxTranslateInput is the tool argument schema. type XlsxTranslateInput struct { FilePath string `json:"file_path" jsonschema:"Absolute sandbox path of the uploaded .xlsx workbook, taken from (for example /workspace/input/part.xlsx)"` } // sessionDirEnsurer is the slice of SessionFileStore that provisions the // output directory before writing. type sessionDirEnsurer interface { EnsureSessionDir(ctx context.Context, sessionID, dir string) error } // XlsxTranslateTool translates an uploaded workbook through the // xlsxtranslate pipeline, writing the English deliverable into the session // artifact output directory. type XlsxTranslateTool struct { BaseTool store SandboxFileSink ensure sessionDirEnsurer model chat.Chat timeout time.Duration } // NewXlsxTranslateTool constructs the tool. store and model MUST NOT be nil; // the tool is only registered when a session sandbox exists, because the // deliverable is delivered through the artifact output directory. func NewXlsxTranslateTool(store SandboxFileSink, ensure sessionDirEnsurer, model chat.Chat) *XlsxTranslateTool { return &XlsxTranslateTool{ BaseTool: BaseTool{ name: ToolXlsxTranslate, description: xlsxTranslateDescription, schema: utils.GenerateSchema[XlsxTranslateInput](), }, store: store, ensure: ensure, model: model, timeout: 20 * time.Minute, } } // Execute runs the translation pipeline over the requested workbook. func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) { var input XlsxTranslateInput if err := json.Unmarshal(args, &input); err != nil { return &types.ToolResult{Success: false, Error: fmt.Sprintf("invalid arguments: %v", err)}, nil } filePath := strings.TrimSpace(input.FilePath) if filePath == "" { return &types.ToolResult{Success: false, Error: "file_path is required: pass the absolute sandbox path of the uploaded workbook from "}, nil } sessionID := resolveSessionID(ctx) if sessionID == "" { return &types.ToolResult{Success: false, Error: "no session ID in context; xlsx_translate must run inside an agent turn"}, nil } layout, layoutErr := executeWorkspaceLayout(ctx, sessionID, t.store) if layoutErr != nil { return layoutErr, nil } // Same relative-path semantics as the file primitives: a bare filename // or workspace-relative path resolves against the workspace root. filePath = resolveIn(layout, filePath) lower := strings.ToLower(filePath) if !strings.HasSuffix(lower, ".xlsx") { return &types.ToolResult{Success: false, Error: fmt.Sprintf("only .xlsx workbooks are supported, got %q; re-save legacy .xls as .xlsx and upload again", path.Base(filePath))}, nil } data, err := t.store.ReadSessionFile(ctx, sessionID, filePath) if err != nil { return &types.ToolResult{Success: false, Error: fmt.Sprintf("failed to read %s: %v", filePath, err)}, nil } if len(data) == 0 { return &types.ToolResult{Success: false, Error: fmt.Sprintf("%s is empty", filePath)}, nil } if len(data) > maxTranslateBytes { return &types.ToolResult{Success: false, Error: fmt.Sprintf("%s is %d MB, above the %d MB translation limit", path.Base(filePath), len(data)>>20, maxTranslateBytes>>20)}, nil } if bytes.HasPrefix(data, legacyXLSMagicBytes) { return &types.ToolResult{Success: false, Error: "this is a legacy binary .xls workbook; re-save it as .xlsx and upload again"}, nil } if !bytes.HasPrefix(data, xlsxMagic) { return &types.ToolResult{Success: false, Error: fmt.Sprintf("%s is not a valid .xlsx (ZIP) package", path.Base(filePath))}, nil } runCtx, cancel := context.WithTimeout(ctx, t.timeout) defer cancel() translated, report, err := xlsxtranslate.Translate(runCtx, data, &xlsxtranslate.Options{ BatchSize: 40, }, &chatBatchTranslator{model: t.model}) if err != nil { logger.Warnf(ctx, "[Tool][XlsxTranslate] session=%s file=%s failed: %v", sessionID, filePath, err) return &types.ToolResult{Success: false, Error: fmt.Sprintf("translation failed: %v", err)}, nil } baseName := path.Base(filePath) ext := path.Ext(baseName) outName := strings.TrimSuffix(baseName, ext) + "_EN.xlsx" outputDir := layoutOutputDir(layout) if outputDir == "" { return &types.ToolResult{Success: false, Error: "session has no artifact output directory; the sandbox workspace is unavailable"}, nil } outPath := outputDir + "/" + outName if t.ensure != nil { if err := t.ensure.EnsureSessionDir(ctx, sessionID, outputDir); err != nil { logger.Warnf(ctx, "[Tool][XlsxTranslate] ensure output dir failed: %v", err) } } if err := t.store.WriteSessionWorkspaceFile(ctx, sessionID, outPath, translated); err != nil { return &types.ToolResult{Success: false, Error: fmt.Sprintf("failed to write translated workbook to %s: %v", outPath, err)}, nil } logger.Infof(ctx, "[Tool][XlsxTranslate] session=%s file=%s -> %s units=%d residual=%d llm_calls=%d", sessionID, filePath, outPath, report.TranslatedUnits, report.ResidualCJKCount, report.LLMCalls) var b strings.Builder b.WriteString("Translation finished. The English workbook is saved as **" + outName + "** in the output directory (available as a downloadable artifact).\n\n") b.WriteString(report.Markdown()) if report.ResidualCJKCount > 0 { b.WriteString("\nNote: residual Chinese remains (see samples above) — usually oversized or untranslatable entries. Review them manually.\n") } if len(report.NumberMismatches) > 0 || len(report.PartMismatches) > 0 { b.WriteString("\nNote: numeric/part token integrity check found differences — do not deliver without manual review.\n") } return &types.ToolResult{ Success: true, Output: b.String(), OutputFiles: sandboxOutputLinksIn(outputDir, outPath), Data: map[string]interface{}{ "output_path": outPath, "translated_units": report.TranslatedUnits, "glossary_hits": report.GlossaryHits, "llm_calls": report.LLMCalls, "residual_cjk": report.ResidualCJKCount, "number_mismatches": len(report.NumberMismatches), "part_mismatches": len(report.PartMismatches), "duration_ms": report.DurationMs, }, }, nil } // chatBatchTranslator adapts the session chat model to the engine's // Translator interface: one call = one JSON array round trip. type chatBatchTranslator struct { model chat.Chat } const translateSystemPrompt = `You are a professional translator for engineering quality documents (SIP standard inspection procedures, SOP standard operating procedures, rack/enclosure manufacturing). Translate each Chinese string into concise, professional English as used in factory inspection documents. Rules: 1. Keep every placeholder token exactly as written: __T0__, __T1__, ... must appear unchanged in the translation at the position of the value they replace. 2. Keep numbering prefixes (1. / 2. / 1.1 / (1)), line breaks (\n) and list structure. 3. Keep units, model names and standard references (MIL-STD-1916, IP20, M8) unchanged. 4. Use established inspection terminology: 检验=inspection, 目视=visual, 抽样=sampling, 检具=inspection gauge, 平面度=flatness, 对角线=diagonal, 接地=grounding, 料号=part number, 工单=work order. 5. Output ONLY a JSON array of translated strings with the same length and order as the input array. No commentary.` func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string) ([]string, error) { payload, err := json.Marshal(texts) if err != nil { return nil, err } var lastErr error for attempt := 0; attempt < 3; attempt++ { if attempt > 0 { select { case <-ctx.Done(): return nil, ctx.Err() case <-time.After(time.Duration(attempt) * 2 * time.Second): } } user := fmt.Sprintf("Translate the following JSON array of strings to English. Return a JSON array with exactly %d items in the same order.\n\n%s", len(texts), payload) resp, err := c.model.Chat(ctx, []chat.Message{ {Role: "system", Content: translateSystemPrompt}, {Role: "user", Content: user}, }, &chat.ChatOptions{Temperature: 0.2, MaxCompletionTokens: 16384}) if err != nil { lastErr = err continue } out, err := parseTranslationArray(resp.Content, len(texts)) if err != nil { lastErr = err continue } return out, nil } return nil, fmt.Errorf("translation call failed after retries: %w", lastErr) } // parseTranslationArray extracts the JSON array from a model response that // may wrap it in markdown fences or prose. func parseTranslationArray(content string, want int) ([]string, error) { trimmed := strings.TrimSpace(content) trimmed = strings.TrimPrefix(trimmed, "```json") trimmed = strings.TrimPrefix(trimmed, "```") trimmed = strings.TrimSuffix(trimmed, "```") trimmed = strings.TrimSpace(trimmed) start := strings.IndexByte(trimmed, '[') end := strings.LastIndexByte(trimmed, ']') if start < 0 || end <= start { return nil, fmt.Errorf("no JSON array in model response: %.120s", content) } var out []string if err := json.Unmarshal([]byte(trimmed[start:end+1]), &out); err != nil { return nil, fmt.Errorf("model response is not a valid string array: %w", err) } if len(out) != want { return nil, fmt.Errorf("model returned %d translations for %d inputs", len(out), want) } return out, nil }