package tools import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "path" "strings" "time" "academy/internal/logger" "academy/internal/models/chat" "academy/internal/types" "academy/internal/types/interfaces" "academy/internal/utils" "academy/internal/xlsxtranslate" "github.com/google/uuid" ) // 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 to the user. Reference the uploaded workbook by its sandbox path (file_path, from ) or by the uploaded attachment's file name (attachment_name) — pass whichever the conversation shows. 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 together with the translated workbook as a downloadable deliverable.` // XlsxTranslateInput is the tool argument schema. Exactly one of file_path / // attachment_name is required; file_path wins when both are given. type XlsxTranslateInput struct { FilePath string `json:"file_path,omitempty" jsonschema:"Absolute sandbox path of the uploaded workbook when is present (for example /workspace/input/part.xlsx)"` AttachmentName string `json:"attachment_name,omitempty" jsonschema:"File name of the uploaded attachment when the conversation shows no sandbox workspace (for example part.xlsx)"` } // SessionDirEnsurer is the slice of SessionFileStore that provisions the // output directory before writing. Exported because the agent service wires // the same store into both the sink and the ensurer slots. type SessionDirEnsurer interface { EnsureSessionDir(ctx context.Context, sessionID, dir string) error } // MessageArtifactSink persists deliverables onto the assistant message so // they surface as clickable artifact cards in the chat, the conversation // artifact library, and the standard artifact download route (which serves // Content-Disposition: attachment) — all without a workspace sandbox. type MessageArtifactSink interface { GetMessage(ctx context.Context, sessionID string, id string) (*types.Message, error) UpdateMessage(ctx context.Context, message *types.Message) error } // XlsxTranslateTool translates an uploaded workbook through the xlsxtranslate // pipeline and delivers the English workbook as a session deliverable. // // Delivery adapts to the session's capabilities: with a workspace sandbox the // output lands in the artifact output directory (collected as a downloadable // artifact); without one the output is saved as a session attachment through // the temporary-document service and linked by preview URL. The same // adaptation applies to reading the upload. This is why registration must NOT // be gated on the sandbox: a deployment without a workspace sandbox would // otherwise hide the tool while the agent prompt still instructs the model to // call it ("tool not found"). type XlsxTranslateTool struct { BaseTool store SandboxFileSink ensure SessionDirEnsurer tempDoc interfaces.TemporaryDocumentService files interfaces.FileService artifacts MessageArtifactSink model chat.Chat timeout time.Duration } // NewXlsxTranslateTool constructs the tool. store/ensure may be nil when the // session has no workspace sandbox (the temporary-document channel is used // instead); tempDoc may be nil only when neither channel can exist. model // MUST NOT be nil. // NewXlsxTranslateTool constructs the tool. Delivery adapts to session // capabilities: a workspace sandbox delivers through the artifact output // directory; otherwise the workbook is saved through the file service and // attached to the assistant message as a chat artifact. tempDoc is the // fallback input reader for the uploaded attachment; files + artifacts carry // the no-sandbox delivery and MUST NOT both be nil. func NewXlsxTranslateTool( store SandboxFileSink, ensure SessionDirEnsurer, tempDoc interfaces.TemporaryDocumentService, files interfaces.FileService, artifacts MessageArtifactSink, model chat.Chat, ) *XlsxTranslateTool { return &XlsxTranslateTool{ BaseTool: BaseTool{ name: ToolXlsxTranslate, description: xlsxTranslateDescription, schema: utils.GenerateSchema[XlsxTranslateInput](), }, store: store, ensure: ensure, tempDoc: tempDoc, files: files, artifacts: artifacts, 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 } 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 } tenantID, _ := types.TenantIDFromContext(ctx) // ---- Resolve the input workbook ---- data, source := t.readInput(ctx, sessionID, tenantID, &input) if len(data) == 0 { return &types.ToolResult{Success: false, Error: source}, nil // source carries the error text } if len(data) > maxTranslateBytes { return &types.ToolResult{Success: false, Error: fmt.Sprintf("workbook is %d MB, above the %d MB translation limit", 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(source))}, nil } baseName := path.Base(source) if !strings.HasSuffix(strings.ToLower(baseName), ".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", baseName)}, nil } // ---- Translate ---- runCtx, cancel := context.WithTimeout(ctx, t.timeout) defer cancel() translated, report, err := xlsxtranslate.Translate(runCtx, data, &xlsxtranslate.Options{}, &chatBatchTranslator{model: t.model}) if err != nil { logger.Warnf(ctx, "[Tool][XlsxTranslate] session=%s file=%s failed: %v", sessionID, source, err) return &types.ToolResult{Success: false, Error: fmt.Sprintf("translation failed: %v", err)}, nil } ext := path.Ext(baseName) outName := strings.TrimSuffix(baseName, ext) + "_EN.xlsx" // ---- Deliver: sandbox artifact dir when available, attachment otherwise ---- var deliverable string var outputLinks []string if t.store != nil { if layout, layoutErr := executeWorkspaceLayout(ctx, sessionID, t.store); layoutErr == nil { if outputDir := layoutOutputDir(layout); outputDir != "" { 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 { deliverable = outPath outputLinks = sandboxOutputLinksIn(outputDir, outPath) } else { logger.Warnf(ctx, "[Tool][XlsxTranslate] sandbox write failed, falling back to attachment: %v", err) } } } } attached := false if deliverable == "" { assistantMessageID := assistantMessageIDFromContext(ctx) var derr error attached, derr = t.saveAsMessageArtifact(ctx, tenantID, sessionID, assistantMessageID, outName, translated) if derr != nil { return &types.ToolResult{Success: false, Error: fmt.Sprintf("translation finished but delivering the workbook failed: %v", derr)}, nil } deliverable = outName } logger.Infof(ctx, "[Tool][XlsxTranslate] session=%s file=%s -> %s units=%d residual=%d llm_calls=%d", sessionID, source, deliverable, report.TranslatedUnits, report.ResidualCJKCount, report.LLMCalls) // The file name is written as a Markdown link whose destination is the // canonical sandbox: spelling. The stream handler rebinds that // destination to the artifact's stable reference (resource:// handle, or // sandbox: without a catalog), so the file name inside the answer // itself renders clickable — clicking opens the translated workbook. fileLink := "[" + outName + "](sandbox:" + outName + ")" var b strings.Builder switch { case len(outputLinks) > 0: b.WriteString("Translation finished. The English workbook " + fileLink + " is saved in the output directory (available as a downloadable artifact).\n\n") case attached: b.WriteString("Translation finished. The English workbook " + fileLink + " is attached to this reply — click the file name or the file card to view details and download.\n\n") default: b.WriteString("Translation finished. Download the English workbook **" + outName + "** here: " + deliverable + "\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: outputLinks, Data: map[string]interface{}{ "deliverable": deliverable, "artifact_attached": attached, "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 } // readInput fetches the workbook bytes: sandbox first (staged attachment), // temporary-document lookup second. The returned string is the resolved // source path/name, or the error text when no bytes could be read. func (t *XlsxTranslateTool) readInput(ctx context.Context, sessionID string, tenantID uint64, input *XlsxTranslateInput) ([]byte, string) { if t.store != nil && strings.TrimSpace(input.FilePath) != "" { if layout, layoutErr := executeWorkspaceLayout(ctx, sessionID, t.store); layoutErr == nil { clean := resolveIn(layout, input.FilePath) data, err := t.store.ReadSessionFile(ctx, sessionID, clean) if err == nil && len(data) > 0 { return data, clean } logger.Warnf(ctx, "[Tool][XlsxTranslate] sandbox read of %s failed (%v); trying session attachments", clean, err) } } if t.tempDoc == nil { return nil, "no input source: pass file_path when a sandbox workspace is present, or attachment_name for the uploaded attachment" } name := strings.TrimSpace(input.AttachmentName) if name == "" { name = path.Base(strings.TrimSpace(input.FilePath)) } if name == "" || name == "." { return nil, "input required: pass file_path (sandbox path) or attachment_name (uploaded file name)" } docs, err := t.tempDoc.List(ctx, tenantID, sessionID) if err != nil { return nil, fmt.Sprintf("failed to list session attachments: %v", err) } var doc *types.TemporaryDocument for i := range docs { // last match wins: the newest upload with that name if docs[i] != nil && docs[i].FileName == name { doc = docs[i] } } if doc == nil { return nil, fmt.Sprintf("no uploaded attachment named %q found in this session", name) } reader, _, err := t.tempDoc.OpenFile(ctx, tenantID, sessionID, doc.ID) if err != nil { return nil, fmt.Sprintf("failed to open attachment %q: %v", name, err) } defer reader.Close() data, err := io.ReadAll(reader) if err != nil { return nil, fmt.Sprintf("failed to read attachment %q: %v", name, err) } return data, doc.FileName } // assistantMessageIDFromContext reads the assistant message the current tool // call belongs to; empty outside agent turns. func assistantMessageIDFromContext(ctx context.Context) string { if meta, ok := ToolExecFromContext(ctx); ok && meta != nil { return meta.AssistantMessageID } return "" } // saveAsMessageArtifact persists the translated workbook through the file // service and records it on the assistant message. The stream handler's // post-run merge matches the file name in the answer against session // artifacts, so the record surfaces as a clickable artifact card on this // reply, in the conversation artifact library, and through the artifact // download route (Content-Disposition: attachment — the browser saves it to // the download location, e.g. Desktop, under the translated file name). // Returns attached=false when the assistant message is not known yet. func (t *XlsxTranslateTool) saveAsMessageArtifact( ctx context.Context, tenantID uint64, sessionID, assistantMessageID, name string, data []byte, ) (bool, error) { if t.files == nil || t.artifacts == nil { return false, fmt.Errorf("no delivery channel: session has neither a workspace sandbox nor the artifact service") } if assistantMessageID == "" { return false, fmt.Errorf("assistant message is not known yet; resend the translation request in this conversation") } storageName := "artifact_" + uuid.NewString() + "_" + name storagePath, err := t.files.SaveBytes(ctx, data, tenantID, storageName, false) if err != nil { return false, fmt.Errorf("save workbook: %w", err) } msg, err := t.artifacts.GetMessage(ctx, sessionID, assistantMessageID) if err != nil || msg == nil { return false, fmt.Errorf("assistant message %s not found: %v", assistantMessageID, err) } for _, a := range msg.Artifacts { if a.FileName == name && !a.Deleted() { return true, nil // idempotent: this turn already delivered the file } } msg.Artifacts = append(msg.Artifacts, types.MessageArtifact{ URL: storagePath, FileName: name, FileType: ".xlsx", FileSize: int64(len(data)), SourcePath: name, // no sandbox path; the name keeps the known-set stable ModTime: time.Now().UTC(), CreatedAt: time.Now().UTC(), }) if err := t.artifacts.UpdateMessage(ctx, msg); err != nil { return false, fmt.Errorf("attach artifact to message: %w", err) } logger.Infof(ctx, "[Tool][XlsxTranslate] artifact attached: session=%s message=%s file=%s bytes=%d", sessionID, assistantMessageID, name, len(data)) return true, 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) { return c.translateRecover(ctx, texts, bisectDepth(len(texts))) } // bisectDepth bounds the halving steps needed to reach single strings. func bisectDepth(n int) int { depth := 0 for n > 1 { n /= 2 depth++ } return depth + 1 } // translateRecover aligns model answers with inputs. A positional JSON // protocol fails in one deterministic way: the model merges or drops an item // (near-duplicate strings, symbol-only entries) and returns N-1 results, so // blind retries reproduce the same mismatch forever. On a count mismatch the // batch is halved and each half retried; a single stubborn string degrades to // keeping the original text, which the engine's residual scan reports. func (c *chatBatchTranslator) translateRecover(ctx context.Context, texts []string, depth int) ([]string, error) { out, err := c.attempt(ctx, texts) if err == nil && len(out) == len(texts) { return out, nil } if len(texts) == 1 { if err == nil && len(out) >= 1 && strings.TrimSpace(out[0]) != "" { return []string{out[0]}, nil } // Keep the original untranslated; the residual scan reports it. return []string{texts[0]}, nil } if depth <= 0 { if err != nil { return nil, err } return nil, fmt.Errorf("model returned %d translations for %d inputs", len(out), len(texts)) } mid := len(texts) / 2 left, err := c.translateRecover(ctx, texts[:mid], depth-1) if err != nil { return nil, err } right, err := c.translateRecover(ctx, texts[mid:], depth-1) if err != nil { return nil, err } return append(left, right...), nil } // attempt issues one streaming call. Transport and JSON-shape errors get one // immediate retry; count mismatches are content-deterministic and returned // (wrapped) so the caller bisects instead of repeating the same failure. func (c *chatBatchTranslator) attempt(ctx context.Context, texts []string) ([]string, error) { payload, err := json.Marshal(texts) if err != nil { return nil, err } var lastErr error for a := 0; a < 2; a++ { if a > 0 { select { case <-ctx.Done(): return nil, ctx.Err() case <-time.After(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) content, err := c.translateOnce(ctx, user) if err != nil { lastErr = err continue } out, perr := parseTranslationArray(content, len(texts)) if perr != nil { var mismatch *countMismatchError if errors.As(perr, &mismatch) { return mismatch.items, perr } lastErr = perr continue } return out, nil } return nil, fmt.Errorf("translation call failed after retries: %w", lastErr) } // countMismatchError carries the model's items so bisection can still use // them when the counts do not line up. type countMismatchError struct { got, want int items []string } func (e *countMismatchError) Error() string { return fmt.Sprintf("model returned %d translations for %d inputs", e.got, e.want) } // translateOnce issues one streaming batch call and returns the concatenated // answer. Streaming is deliberate: long batches then fall under the chat // client's stall-based timeout instead of a single non-stream HTTP timeout. func (c *chatBatchTranslator) translateOnce(ctx context.Context, user string) (string, error) { ch, err := c.model.ChatStream(ctx, []chat.Message{ {Role: "system", Content: translateSystemPrompt}, {Role: "user", Content: user}, }, &chat.ChatOptions{Temperature: 0.2, MaxCompletionTokens: 8192}) if err != nil { return "", err } var content strings.Builder for chunk := range ch { switch chunk.ResponseType { case types.ResponseTypeError: return "", fmt.Errorf("%s", chunk.Content) default: content.WriteString(chunk.Content) } } return content.String(), nil } // 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, &countMismatchError{got: len(out), want: want, items: out} } return out, nil }