返回 DeepSeek-Reasonix
refs.go
根目录 / internal / control / refs.go
1 package control
2
3 import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "io"
11 "net/http"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "regexp"
16 "sort"
17 "strings"
18 "time"
19
20 "reasonix/internal/fileref"
21 "reasonix/internal/instruction"
22 "reasonix/internal/proc"
23 "reasonix/internal/secrets"
24 )
25
26 // maxFileRefBytes caps how much of an @-referenced file is injected into a
27 // message, so "@somehuge.log" can't blow the context window. The head is kept
28 // and the rest noted as truncated.
29 const maxFileRefBytes = 64 * 1024
30
31 const pdfExtractTimeout = 8 * time.Second
32 const pdfExtractWaitDelay = 1 * time.Second
33
34 var extractPDFText = extractPDFTextDefault
35
36 type pdfExtractResult struct {
37 text string
38 tool string
39 truncated bool
40 }
41
42 // refKind distinguishes the two things an @reference can resolve to.
43 type refKind int
44
45 const (
46 refResource refKind = iota // an MCP resource: @<server>:<uri>
47 refFile // a local file or directory: @<path>
48 refImage // a local image attachment: @.reasonix/attachments/<file>
49 refRemoteImage // an http(s) image URL
50 refFileID // a Files API file-api- id
51 )
52
53 // ref is a resolved @reference found in a submitted line.
54 type ref struct {
55 kind refKind
56 server string // refResource
57 uri string // refResource
58 path string // refFile, relative to baseDir when baseDir is set
59 baseDir string // refFile override for session-authorized external roots
60 displayPath string // refFile label/path exposed in the resolved context block
61 raw string // the original token after '@', for labelling
62 }
63
64 // ExternalFolderRefEntry is a session-authorized entry under a dropped external
65 // folder. Path is the opaque @ token path to submit; display fields are safe for
66 // UI labels and transcripts.
67 type ExternalFolderRefEntry struct {
68 Name string
69 Path string
70 DisplayName string
71 DisplayPath string
72 IsDir bool
73 }
74
75 var pathLocationSuffixRe = regexp.MustCompile(`:\d+(?::\d+)?:?$`)
76
77 const externalFolderRefPrefix = "__reasonix_external_folder"
78
79 // parseRefTokens extracts the deduped, punctuation-trimmed tokens following '@'
80 // in a line. A token is a run of non-whitespace bytes, except that a
81 // backslash-escaped space or tab is part of the token with the backslash
82 // dropped — that is how a path containing spaces survives the
83 // whitespace-delimited grammar (EscapeRefPath produces that form). Any other
84 // backslash stays literal so Windows separators keep their meaning. Pure:
85 // classification (server? file?) happens in classifyRef.
86 func parseRefTokens(line string) []string {
87 var toks []string
88 seen := map[string]bool{}
89 for i := 0; i < len(line); i++ {
90 if line[i] != '@' {
91 continue
92 }
93 var b strings.Builder
94 j := i + 1
95 for j < len(line) {
96 ch := line[j]
97 if ch == '\\' && j+1 < len(line) && (line[j+1] == ' ' || line[j+1] == '\t') {
98 b.WriteByte(line[j+1])
99 j += 2
100 continue
101 }
102 if isRefTokenBoundary(ch) {
103 break
104 }
105 b.WriteByte(ch)
106 j++
107 }
108 i = j - 1
109 t := strings.TrimRight(b.String(), ".,;!?)]}")
110 if t == "" || seen[t] {
111 continue
112 }
113 seen[t] = true
114 toks = append(toks, t)
115 }
116 return toks
117 }
118
119 // isRefTokenBoundary matches the whitespace class the old `@([^\s]+)` token
120 // regexp stopped at.
121 func isRefTokenBoundary(ch byte) bool {
122 switch ch {
123 case ' ', '\t', '\n', '\r', '\f':
124 return true
125 default:
126 return false
127 }
128 }
129
130 // EscapeRefPath returns path with spaces and tabs backslash-escaped so the
131 // result survives whitespace-delimited @-token parsing (parseRefTokens
132 // reverses it). Every other byte, including backslashes, passes through
133 // unchanged so Windows separators keep their meaning.
134 func EscapeRefPath(path string) string {
135 if !strings.ContainsAny(path, " \t") {
136 return path
137 }
138 var b strings.Builder
139 b.Grow(len(path) + 8)
140 for i := range len(path) {
141 if path[i] == ' ' || path[i] == '\t' {
142 b.WriteByte('\\')
143 }
144 b.WriteByte(path[i])
145 }
146 return b.String()
147 }
148
149 // UnescapeRefPath reverses EscapeRefPath: a backslash before a space or tab is
150 // dropped; any other backslash stays literal.
151 func UnescapeRefPath(path string) string {
152 if !strings.Contains(path, `\`) {
153 return path
154 }
155 var b strings.Builder
156 b.Grow(len(path))
157 for i := range len(path) {
158 if path[i] == '\\' && i+1 < len(path) && (path[i+1] == ' ' || path[i+1] == '\t') {
159 continue
160 }
161 b.WriteByte(path[i])
162 }
163 return b.String()
164 }
165
166 // classifyRef decides what a token refers to. A "server:uri" token whose server
167 // is connected is an MCP resource; otherwise a token that names an existing path
168 // is a file. Anything else (an @mention, an email) is not a reference. exists is
169 // injected so the rule is testable without touching the filesystem.
170 func classifyRef(token string, known map[string]bool, exists func(string) bool) (ref, bool) {
171 if i := strings.Index(token, ":"); i > 0 && i+1 < len(token) && known[token[:i]] {
172 return ref{kind: refResource, server: token[:i], uri: token[i+1:], raw: token}, true
173 }
174 if isAttachmentRef(token) && exists(token) {
175 if isImageAttachmentRef(token) {
176 return ref{kind: refImage, path: token, raw: token}, true
177 }
178 return ref{kind: refFile, path: token, raw: token}, true
179 }
180 if exists(token) {
181 return ref{kind: refFile, path: token, raw: token}, true
182 }
183 return ref{}, false
184 }
185
186 // RegisterExternalFolderRef authorizes one dropped directory outside the
187 // workspace as a structured @reference for this controller session. The returned
188 // token is path-like and whitespace-free so it survives the existing @ token
189 // parser even when the real directory path contains spaces or Windows drive
190 // punctuation.
191 func (c *Controller) RegisterExternalFolderRef(path string) (token, displayPath string, err error) {
192 if c == nil {
193 return "", "", fmt.Errorf("controller is not ready")
194 }
195 abs, err := normalizeExternalFolderRoot(path)
196 if err != nil {
197 return "", "", err
198 }
199 token = externalFolderRefToken(abs)
200 c.externalFolderRefsMu.Lock()
201 if c.externalFolderRefs == nil {
202 c.externalFolderRefs = map[string]string{}
203 }
204 c.externalFolderRefs[token] = abs
205 c.externalFolderRefsMu.Unlock()
206 if c.externalFolderToolRefs != nil {
207 c.externalFolderToolRefs.RegisterReadRoot(token, abs)
208 }
209 return token, filepath.ToSlash(abs), nil
210 }
211
212 func normalizeExternalFolderRoot(path string) (string, error) {
213 path = strings.TrimSpace(path)
214 if path == "" {
215 return "", os.ErrInvalid
216 }
217 abs, err := filepath.Abs(path)
218 if err != nil {
219 return "", err
220 }
221 abs = filepath.Clean(abs)
222 if resolved, err := filepath.EvalSymlinks(abs); err == nil {
223 abs = filepath.Clean(resolved)
224 }
225 info, err := os.Stat(abs)
226 if err != nil {
227 return "", err
228 }
229 if !info.IsDir() {
230 return "", fmt.Errorf("%s is not a directory", path)
231 }
232 return abs, nil
233 }
234
235 func externalFolderRefToken(abs string) string {
236 sum := sha256.Sum256([]byte(filepath.Clean(abs)))
237 hash := hex.EncodeToString(sum[:])[:12]
238 name := safeExternalFolderRefComponent(filepath.Base(abs))
239 return externalFolderRefPrefix + "/" + hash + "/" + name
240 }
241
242 func safeExternalFolderRefComponent(name string) string {
243 name = strings.TrimSpace(name)
244 if name == "" || name == "." || name == string(filepath.Separator) {
245 return "folder"
246 }
247 var b strings.Builder
248 lastDash := false
249 for _, r := range name {
250 ok := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '.' || r == '_' || r == '-'
251 if ok {
252 b.WriteRune(r)
253 lastDash = false
254 continue
255 }
256 if !lastDash {
257 b.WriteByte('-')
258 lastDash = true
259 }
260 }
261 out := strings.Trim(b.String(), ".-")
262 if out == "" {
263 return "folder"
264 }
265 return out
266 }
267
268 func normalizeExternalFolderRefToken(token string) string {
269 token = strings.TrimSpace(token)
270 token = strings.TrimPrefix(token, "@")
271 token = filepath.ToSlash(token)
272 token = strings.TrimRight(token, "/")
273 return token
274 }
275
276 func (c *Controller) externalFolderRef(token string) (ref, bool) {
277 if r, ok := c.externalFileRef(token); ok {
278 return r, true
279 }
280 _, rel, abs, ok := c.externalFolderRefTarget(token)
281 if !ok {
282 return ref{}, false
283 }
284 displayPath := externalFolderDisplayPath(abs, rel)
285 return ref{kind: refFile, path: rel, baseDir: abs, displayPath: displayPath, raw: token}, true
286 }
287
288 func (c *Controller) externalFolderRefTarget(token string) (rootToken, rel, abs string, ok bool) {
289 key := normalizeExternalFolderRefToken(token)
290 if !strings.HasPrefix(key, externalFolderRefPrefix+"/") {
291 return "", "", "", false
292 }
293 c.externalFolderRefsMu.RLock()
294 defer c.externalFolderRefsMu.RUnlock()
295 if abs, ok := c.externalFolderRefs[key]; ok {
296 return key, ".", abs, true
297 }
298 for registered, abs := range c.externalFolderRefs {
299 if !strings.HasPrefix(key, registered+"/") {
300 continue
301 }
302 sub, ok := cleanExternalFolderSubpath(strings.TrimPrefix(key, registered+"/"))
303 if !ok {
304 return "", "", "", false
305 }
306 return registered, sub, abs, true
307 }
308 return "", "", "", false
309 }
310
311 func cleanExternalFolderSubpath(sub string) (string, bool) {
312 sub = strings.TrimPrefix(filepath.ToSlash(strings.TrimSpace(sub)), "/")
313 if sub == "" || sub == "." {
314 return ".", true
315 }
316 cleaned := filepath.Clean(filepath.FromSlash(sub))
317 if cleaned == "." {
318 return ".", true
319 }
320 if !filepath.IsLocal(cleaned) {
321 return "", false
322 }
323 return filepath.ToSlash(cleaned), true
324 }
325
326 func externalFolderDisplayPath(abs, rel string) string {
327 if rel == "" || rel == "." {
328 return filepath.ToSlash(abs)
329 }
330 return filepath.ToSlash(filepath.Join(abs, filepath.FromSlash(rel)))
331 }
332
333 func externalFolderDisplayName(abs, rel string) string {
334 name := filepath.Base(abs)
335 if rel != "" && rel != "." {
336 name = filepath.ToSlash(filepath.Join(name, filepath.FromSlash(rel)))
337 }
338 return name
339 }
340
341 // ListExternalFolderRefDir lists one directory level under a registered
342 // external folder token. handled is true only when tokenPath targets a
343 // registered external folder; callers can fall back to workspace listing when it
344 // is false.
345 func (c *Controller) ListExternalFolderRefDir(tokenPath string) (entries []ExternalFolderRefEntry, handled bool) {
346 rootToken, rel, abs, ok := c.externalFolderRefTarget(tokenPath)
347 if !ok {
348 return nil, false
349 }
350 root, err := os.OpenRoot(abs)
351 if err != nil {
352 return nil, true
353 }
354 defer root.Close()
355 info, err := root.Stat(rel)
356 if err != nil || !info.IsDir() {
357 return nil, true
358 }
359 f, err := root.Open(rel)
360 if err != nil {
361 return nil, true
362 }
363 dirEntries, err := f.ReadDir(-1)
364 f.Close()
365 if err != nil {
366 return nil, true
367 }
368 dirs, files := []ExternalFolderRefEntry{}, []ExternalFolderRefEntry{}
369 for _, e := range dirEntries {
370 name := e.Name()
371 if skipRefDirEntry(name, e.IsDir()) {
372 continue
373 }
374 childRel := name
375 if rel != "." {
376 childRel = filepath.ToSlash(filepath.Join(rel, name))
377 }
378 item := ExternalFolderRefEntry{
379 Name: name,
380 Path: rootToken + "/" + childRel,
381 DisplayName: name,
382 DisplayPath: externalFolderDisplayPath(abs, childRel),
383 IsDir: e.IsDir(),
384 }
385 if e.IsDir() {
386 dirs = append(dirs, item)
387 continue
388 }
389 info, err := e.Info()
390 if err != nil || !info.Mode().IsRegular() {
391 continue
392 }
393 files = append(files, item)
394 }
395 sortExternalFolderRefEntries(dirs)
396 sortExternalFolderRefEntries(files)
397 return append(dirs, files...), true
398 }
399
400 // SearchExternalFolderRefs finds entries under all registered external folders.
401 // Returned Path values are opaque token paths, so selecting one stays within the
402 // current session's authorization boundary.
403 func (c *Controller) SearchExternalFolderRefs(query string, limit int) []ExternalFolderRefEntry {
404 query = strings.TrimSpace(query)
405 if limit <= 0 || len(query) < 2 || strings.ContainsAny(query, `/\`) {
406 return nil
407 }
408 c.externalFolderRefsMu.RLock()
409 roots := make([]struct {
410 token string
411 abs string
412 }, 0, len(c.externalFolderRefs))
413 for token, abs := range c.externalFolderRefs {
414 roots = append(roots, struct {
415 token string
416 abs string
417 }{token: token, abs: abs})
418 }
419 c.externalFolderRefsMu.RUnlock()
420 sort.Slice(roots, func(i, j int) bool {
421 return externalFolderDisplayPath(roots[i].abs, ".") < externalFolderDisplayPath(roots[j].abs, ".")
422 })
423 out := make([]ExternalFolderRefEntry, 0, limit)
424 queryLower := strings.ToLower(query)
425 for _, root := range roots {
426 if len(out) >= limit {
427 break
428 }
429 if info, err := os.Stat(root.abs); err != nil || !info.IsDir() {
430 continue
431 }
432 if strings.Contains(strings.ToLower(filepath.Base(root.abs)), queryLower) {
433 out = append(out, ExternalFolderRefEntry{
434 Name: filepath.Base(root.abs),
435 Path: root.token,
436 DisplayName: externalFolderDisplayName(root.abs, "."),
437 DisplayPath: externalFolderDisplayPath(root.abs, "."),
438 IsDir: true,
439 })
440 if len(out) >= limit {
441 break
442 }
443 }
444 for _, result := range fileref.Search(root.abs, query, limit-len(out)) {
445 rel := filepath.ToSlash(result.Path)
446 out = append(out, ExternalFolderRefEntry{
447 Name: rel,
448 Path: root.token + "/" + rel,
449 DisplayName: externalFolderDisplayName(root.abs, rel),
450 DisplayPath: externalFolderDisplayPath(root.abs, rel),
451 IsDir: result.IsDir,
452 })
453 if len(out) >= limit {
454 break
455 }
456 }
457 }
458 return out
459 }
460
461 func sortExternalFolderRefEntries(entries []ExternalFolderRefEntry) {
462 sort.Slice(entries, func(i, j int) bool {
463 return fileref.NaturalLess(entries[i].DisplayName, entries[j].DisplayName)
464 })
465 }
466
467 func skipRefDirEntry(name string, isDir bool) bool {
468 switch name {
469 case ".DS_Store", "Thumbs.db":
470 return true
471 }
472 if !isDir {
473 return false
474 }
475 switch name {
476 case ".codex", ".git", ".idea", ".npm", ".pnpm-store", ".vscode", "__pycache__", "build", "dist", "node_modules":
477 return true
478 }
479 return false
480 }
481
482 // detectRefs finds the @references in a line: MCP resources for connected
483 // servers, and local paths that exist on disk.
484 func (c *Controller) detectRefs(line string) []ref {
485 return c.detectRefsMode(line, false)
486 }
487
488 func (c *Controller) detectRefsMode(line string, scopedOnly bool) []ref {
489 known := map[string]bool{}
490 for _, n := range c.mcp.serverNames() {
491 known[n] = true
492 }
493
494 var refs []ref
495 for _, tok := range parseRefTokens(line) {
496 if i := strings.Index(tok, ":"); i > 0 && i+1 < len(tok) && known[tok[:i]] {
497 refs = append(refs, ref{kind: refResource, server: tok[:i], uri: tok[i+1:], raw: tok})
498 continue
499 }
500 if r, ok := c.externalFolderRef(tok); ok {
501 refs = append(refs, r)
502 continue
503 }
504 if r, ok := classifyVisionToken(tok); ok {
505 refs = append(refs, r)
506 continue
507 }
508 // Keep missing composer images resolvable so admission rejects the turn
509 // instead of silently sending only path text. Non-image attachments retain
510 // the existing best-effort reference behavior.
511 if isAttachmentRef(tok) && isImageAttachmentRef(tok) {
512 refs = append(refs, ref{kind: refImage, path: tok, raw: tok})
513 continue
514 }
515 if c.workspaceRoot != "" {
516 if rel, ok := workspaceRefPath(tok, c.workspaceRoot); ok {
517 kind := refFile
518 if isAttachmentRef(rel) && isImageAttachmentRef(rel) {
519 kind = refImage
520 }
521 refs = append(refs, ref{kind: kind, path: rel, raw: tok})
522 }
523 continue
524 }
525 if scopedOnly {
526 continue
527 }
528 if r, ok := classifyRef(tok, known, func(p string) bool {
529 _, err := os.Stat(p)
530 return err == nil
531 }); ok {
532 refs = append(refs, r)
533 }
534 }
535 return refs
536 }
537
538 // HasRefs reports whether a line contains any resolvable @references, so a
539 // frontend can decide to resolve off its event loop only when needed.
540 func (c *Controller) HasRefs(line string) bool {
541 return len(c.detectRefs(line)) > 0
542 }
543
544 // resolveBareNames batch-resolves simple filenames (no path separator) that
545 // don't exist in cwd. It walks the working tree once and matches every
546 // unresolved name against the set, stopping when all are found. This runs in
547 // the async ResolveRefs path, never on the TUI event loop.
548 func resolveBareNames(refs []ref, workspaceRoot string) []ref {
549 need := map[string]*ref{}
550 var names []string
551 for i := range refs {
552 r := &refs[i]
553 if r.kind != refFile || r.path != "" || !isSafeBareRefName(r.raw) {
554 continue
555 }
556 if workspaceRoot != "" {
557 if rel, ok := workspaceRefPath(r.raw, workspaceRoot); ok {
558 r.path = rel
559 continue
560 }
561 }
562 need[r.raw] = r
563 names = append(names, r.raw)
564 }
565 if len(names) == 0 {
566 return refs
567 }
568 found := 0
569 cwd := workspaceRoot
570 if cwd == "" {
571 cwd, _ = os.Getwd()
572 }
573 _ = filepath.WalkDir(cwd, func(p string, d os.DirEntry, wErr error) error {
574 if wErr != nil || found == len(names) {
575 return filepath.SkipAll
576 }
577 if d.IsDir() {
578 switch d.Name() {
579 case ".git", "node_modules", ".DS_Store", "__pycache__", ".idea", ".vscode":
580 return filepath.SkipDir
581 }
582 return nil
583 }
584 if r, ok := need[d.Name()]; ok {
585 rel, _ := filepath.Rel(cwd, p)
586 r.path = filepath.ToSlash(rel)
587 delete(need, d.Name())
588 found++
589 }
590 return nil
591 })
592 return refs
593 }
594
595 func isSafeBareRefName(name string) bool {
596 if name == "" || name == "." || name == ".." {
597 return false
598 }
599 if strings.ContainsAny(name, "/\\") || strings.Contains(name, "..") {
600 return false
601 }
602 return filepath.Base(name) == name && filepath.IsLocal(name)
603 }
604
605 // FileRefLine reports whether a submitted line is nothing but a path to an
606 // existing file — a dragged or pasted file lands as its bare path, which on
607 // POSIX starts with '/' and would otherwise be misread as a slash command. The
608 // returned string is that path turned into an @reference so it attaches.
609 func FileRefLine(line string) (string, bool) {
610 p := strings.Trim(strings.TrimSpace(line), `"'`)
611 if p == "" {
612 return "", false
613 }
614 if info, err := os.Stat(p); err != nil || info.IsDir() {
615 return "", false
616 }
617 return "@" + EscapeRefPath(p), true
618 }
619
620 // SlashCodeCommentLine reports whether a slash-prefixed line is ordinary source
621 // text rather than a Reasonix slash command.
622 func SlashCodeCommentLine(line string) bool {
623 trimmed := strings.TrimSpace(line)
624 return strings.HasPrefix(trimmed, "//") || strings.HasPrefix(trimmed, "/*")
625 }
626
627 // SlashPathLineRef reports whether a slash-prefixed line starts with a local file
628 // path, including common compiler-location suffixes like ":12" or ":12:34".
629 // It returns an @reference for the file so diagnostics that begin with an
630 // absolute path can keep their original text while also attaching file context.
631 func SlashPathLineRef(line, baseDir string) (string, bool) {
632 token, ok := leadingSlashPathToken(line)
633 if !ok {
634 return "", false
635 }
636 for _, p := range pathTokenCandidates(token) {
637 if fileRefExists(p, baseDir) {
638 return "@" + p, true
639 }
640 }
641 return "", false
642 }
643
644 // SlashPathLikeLine reports whether a slash-prefixed line looks like a POSIX
645 // absolute path rather than a slash command. It intentionally stays conservative:
646 // unknown "/foo" remains an unknown command, while "/foo/bar..." is sent as
647 // ordinary prompt text even if the path no longer exists.
648 func SlashPathLikeLine(line string) bool {
649 token, ok := leadingSlashPathToken(line)
650 if !ok {
651 return false
652 }
653 for _, p := range pathTokenCandidates(token) {
654 if strings.Contains(p[1:], "/") {
655 return true
656 }
657 }
658 return false
659 }
660
661 func leadingSlashPathToken(line string) (string, bool) {
662 fields := strings.Fields(strings.TrimSpace(line))
663 if len(fields) == 0 {
664 return "", false
665 }
666 token := strings.Trim(fields[0], `"'`)
667 if !strings.HasPrefix(token, "/") || strings.HasPrefix(token, "//") {
668 return "", false
669 }
670 return token, true
671 }
672
673 func pathTokenCandidates(token string) []string {
674 token = strings.TrimRight(strings.Trim(token, `"'`), ".,;!?)]}")
675 if token == "" {
676 return nil
677 }
678 candidates := []string{token}
679 if stripped := pathLocationSuffixRe.ReplaceAllString(token, ""); stripped != token {
680 candidates = append(candidates, stripped)
681 }
682 return candidates
683 }
684
685 func fileRefExists(path, baseDir string) bool {
686 if baseDir != "" {
687 rel, _, absBase, ok := workspaceRel(path, baseDir)
688 if !ok {
689 return false
690 }
691 root, err := os.OpenRoot(absBase)
692 if err != nil {
693 return false
694 }
695 defer root.Close()
696 info, err := root.Stat(rel)
697 return err == nil && !info.IsDir()
698 }
699 info, err := os.Stat(path)
700 return err == nil && !info.IsDir()
701 }
702
703 func workspaceRefPath(path, baseDir string) (string, bool) {
704 rel, _, absBase, ok := workspaceRel(path, baseDir)
705 if !ok {
706 return "", false
707 }
708 root, err := os.OpenRoot(absBase)
709 if err != nil {
710 return "", false
711 }
712 defer root.Close()
713 if _, err := root.Stat(rel); err != nil {
714 return "", false
715 }
716 return filepath.ToSlash(rel), true
717 }
718
719 func workspaceRel(path, baseDir string) (rel, absPath, absBase string, ok bool) {
720 absPath, absBase, ok = resolveAbsRef(path, baseDir)
721 if !ok || absBase == "" {
722 return "", "", "", false
723 }
724 rel, err := filepath.Rel(absBase, absPath)
725 if err != nil || !filepath.IsLocal(rel) {
726 return "", "", "", false
727 }
728 return rel, absPath, absBase, true
729 }
730
731 func (c *Controller) resolveReferencedInstructions(r ref, baseDir string, includedPaths, includedBodies map[string]bool) (string, []instruction.Diagnostic) {
732 mem := c.memory.current()
733 if mem == nil || strings.TrimSpace(c.workspaceRoot) == "" || r.baseDir != "" {
734 return "", nil
735 }
736 absPath, absBase, ok := resolveAbsRef(r.path, baseDir)
737 if !ok || cleanAbsPath(absBase) != cleanAbsPath(c.workspaceRoot) {
738 return "", nil
739 }
740 targetDir := absPath
741 if info, err := os.Stat(absPath); err != nil || !info.IsDir() {
742 targetDir = filepath.Dir(absPath)
743 }
744 resolved := instruction.Resolve(instruction.ResolveOptions{
745 WorkspaceRoot: c.workspaceRoot,
746 TargetDir: targetDir,
747 UserDir: mem.UserDir,
748 })
749 var delta []instruction.Document
750 for _, doc := range resolved.Documents {
751 pathKey := cleanAbsPath(doc.Path)
752 if includedPaths[pathKey] || includedBodies[doc.Body] {
753 continue
754 }
755 includedPaths[pathKey] = true
756 includedBodies[doc.Body] = true
757 delta = append(delta, doc)
758 }
759 return instruction.Block(delta), resolved.Diagnostics
760 }
761
762 func displayPathForRef(r ref) string {
763 if r.displayPath != "" {
764 return r.displayPath
765 }
766 return r.path
767 }
768
769 func cleanAbsPath(path string) string {
770 abs, err := filepath.Abs(path)
771 if err != nil {
772 return filepath.Clean(path)
773 }
774 return filepath.Clean(abs)
775 }
776
777 func appendRefBlock(b *strings.Builder, tag, attr, body string) {
778 if b.Len() > 0 {
779 b.WriteString("\n\n")
780 }
781 fmt.Fprintf(b, "<%s %s>\n%s\n</%s>", tag, attr, body, tag)
782 }
783
784 // maxDirEntries caps how many directory entries are injected so @some-huge-dir
785 // can't blow the context window.
786 const maxDirEntries = 100
787
788 const maxDirDepth = 16
789
790 func directoryRefNote() string {
791 return fmt.Sprintf("[directory listing only; file contents are not inlined. Mention a listed file path to read its content. Common generated/vendor folders are skipped. Listing is capped at %d entries and %d nested levels.]", maxDirEntries, maxDirDepth)
792 }
793
794 // readFileRef reads an @-referenced path for injection. A directory yields a
795 // recursive listing capped at maxDirEntries; a binary file (NUL in the first
796 // 8 KiB) is noted rather than dumped; a large file is truncated to
797 // maxFileRefBytes with a marker. isDir lets the caller pick the wrapping tag.
798 // When baseDir is non-empty the read is sandboxed under it via os.Root so
799 // user-supplied paths cannot escape the workspace; otherwise the path is
800 // used as-is (CLI single-workspace compatibility).
801 func readFileRef(path, baseDir string) (content string, isDir bool, err error) {
802 return readFileRefWithVision(path, baseDir, false)
803 }
804
805 func readFileRefWithVision(path, baseDir string, vision bool) (content string, isDir bool, err error) {
806 absPath, absBase, ok := resolveAbsRef(path, baseDir)
807 if !ok {
808 return "", false, os.ErrNotExist
809 }
810 if absBase == "" {
811 return readFileRefUnscoped(absPath, vision)
812 }
813
814 root, rerr := os.OpenRoot(absBase)
815 if rerr != nil {
816 return "", false, rerr
817 }
818 defer root.Close()
819
820 rel, rerr := filepath.Rel(absBase, absPath)
821 if rerr != nil {
822 return "", false, rerr
823 }
824 displayPath := filepath.ToSlash(rel)
825
826 info, err := root.Stat(rel)
827 if err != nil {
828 return "", false, err
829 }
830 if info.IsDir() {
831 var b strings.Builder
832 b.WriteString(directoryRefNote())
833 b.WriteString("\n\n")
834 n := 0
835 err := walkRootDir(root, rel, rel, &b, &n, 0)
836 if n >= maxDirEntries {
837 b.WriteString("\n…[truncated; directory has more entries]…")
838 }
839 if err != nil {
840 return "", true, err
841 }
842 return b.String(), true, nil
843 }
844
845 if strings.EqualFold(filepath.Ext(rel), ".pdf") {
846 return readPDFRef(absPath, info.Size()), false, nil
847 }
848
849 f, err := root.Open(rel)
850 if err != nil {
851 return "", false, err
852 }
853 defer f.Close()
854
855 buf := make([]byte, maxFileRefBytes+1)
856 n, rerr := io.ReadFull(f, buf)
857 if rerr != nil && !errors.Is(rerr, io.ErrUnexpectedEOF) && !errors.Is(rerr, io.EOF) {
858 return "", false, rerr
859 }
860 data := buf[:n]
861
862 if mime := imageMime(data, rel); mime != "" {
863 return imageFileRefNote(displayPath, mime, info.Size(), true, vision), false, nil
864 }
865 if bytes.IndexByte(data[:min(n, 8192)], 0) >= 0 {
866 return fmt.Sprintf("[binary file %s, %d bytes — not shown]", displayPath, info.Size()), false, nil
867 }
868 if n > maxFileRefBytes {
869 return string(data[:maxFileRefBytes]) + fmt.Sprintf("\n…[truncated; file is %d bytes]…", info.Size()), false, nil
870 }
871 return string(data), false, nil
872 }
873
874 // readFileRefUnscoped is the legacy readFileRef body kept for CLI single-workspace
875 // compatibility, where no controller-scoped sandbox is in effect.
876 func readFileRefUnscoped(path string, vision bool) (content string, isDir bool, err error) {
877 info, err := os.Stat(path)
878 if err != nil {
879 return "", false, err
880 }
881 if info.IsDir() {
882 var b strings.Builder
883 b.WriteString(directoryRefNote())
884 b.WriteString("\n\n")
885 n := 0
886 err := filepath.WalkDir(path, func(p string, d os.DirEntry, wErr error) error {
887 if wErr != nil {
888 return wErr
889 }
890 if n >= maxDirEntries {
891 return filepath.SkipAll
892 }
893 if p == path {
894 return nil
895 }
896 if skipRefDirEntry(d.Name(), d.IsDir()) {
897 if d.IsDir() {
898 return filepath.SkipDir
899 }
900 return nil
901 }
902 rel, rErr := filepath.Rel(path, p)
903 if rErr != nil {
904 rel = p
905 }
906 rel = strings.ReplaceAll(rel, string(os.PathSeparator), "/")
907 if d.IsDir() {
908 rel += "/"
909 }
910 b.WriteString(rel)
911 b.WriteByte('\n')
912 n++
913 return nil
914 })
915 if n >= maxDirEntries {
916 b.WriteString("\n…[truncated; directory has more entries]…")
917 }
918 if err != nil {
919 return "", true, err
920 }
921 return b.String(), true, nil
922 }
923
924 if strings.EqualFold(filepath.Ext(path), ".pdf") {
925 return readPDFRef(path, info.Size()), false, nil
926 }
927
928 f, err := os.Open(path)
929 if err != nil {
930 return "", false, err
931 }
932 defer f.Close()
933
934 buf := make([]byte, maxFileRefBytes+1)
935 n, rerr := io.ReadFull(f, buf)
936 if rerr != nil && !errors.Is(rerr, io.ErrUnexpectedEOF) && !errors.Is(rerr, io.EOF) {
937 return "", false, rerr
938 }
939 data := buf[:n]
940
941 if mime := imageMime(data, path); mime != "" {
942 return imageFileRefNote(path, mime, info.Size(), false, vision), false, nil
943 }
944 if bytes.IndexByte(data[:min(n, 8192)], 0) >= 0 {
945 return fmt.Sprintf("[binary file %s, %d bytes — not shown]", path, info.Size()), false, nil
946 }
947 if n > maxFileRefBytes {
948 return string(data[:maxFileRefBytes]) + fmt.Sprintf("\n…[truncated; file is %d bytes]…", info.Size()), false, nil
949 }
950 return string(data), false, nil
951 }
952
953 // walkRootDir walks a directory under a sandboxed *os.Root and writes each
954 // entry relative to base (skipping noisy ones like .git and node_modules) into b
955 // until n hits maxDirEntries.
956 func walkRootDir(root *os.Root, dir, base string, b *strings.Builder, n *int, depth int) error {
957 if depth > maxDirDepth || *n >= maxDirEntries {
958 return nil
959 }
960 f, err := root.Open(dir)
961 if err != nil {
962 return err
963 }
964 entries, err := f.ReadDir(-1)
965 f.Close()
966 if err != nil {
967 return err
968 }
969 sort.Slice(entries, func(i, j int) bool {
970 if entries[i].IsDir() != entries[j].IsDir() {
971 return entries[i].IsDir()
972 }
973 return fileref.NaturalLess(entries[i].Name(), entries[j].Name())
974 })
975 for _, e := range entries {
976 if *n >= maxDirEntries {
977 return nil
978 }
979 name := e.Name()
980 child := filepath.ToSlash(filepath.Join(dir, name))
981 entry := name
982 if rel, err := filepath.Rel(base, child); err == nil && filepath.IsLocal(rel) {
983 entry = filepath.ToSlash(rel)
984 }
985 if skipRefDirEntry(name, e.IsDir()) {
986 continue
987 }
988 if e.IsDir() {
989 entry += "/"
990 }
991 b.WriteString(entry)
992 b.WriteByte('\n')
993 *n++
994 if e.IsDir() {
995 if err := walkRootDir(root, child, base, b, n, depth+1); err != nil {
996 return err
997 }
998 }
999 }
1000 return nil
1001 }
1002
1003 // resolveAbsRef resolves the user-supplied @-reference path against baseDir
1004 // and returns the absolute path plus the absolute base root to sandbox I/O
1005 // under. With a baseDir, the path is confined under it (a relative path that
1006 // escapes via ".." is rejected). With an empty baseDir, the path is returned
1007 // as-is and the caller falls back to plain os.Stat/os.Open so CLI usage
1008 // (where there is no controller-scoped workspace) keeps working.
1009 func resolveAbsRef(path, baseDir string) (absPath, absBase string, ok bool) {
1010 if baseDir == "" {
1011 return path, "", true
1012 }
1013 absBase = baseDir
1014 if !filepath.IsAbs(absBase) {
1015 var err error
1016 absBase, err = filepath.Abs(absBase)
1017 if err != nil {
1018 return "", "", false
1019 }
1020 }
1021 cleaned := filepath.Clean(path)
1022 if !filepath.IsAbs(cleaned) {
1023 cleaned = filepath.Join(absBase, cleaned)
1024 }
1025 rel, err := filepath.Rel(absBase, cleaned)
1026 if err != nil || !filepath.IsLocal(rel) {
1027 return "", "", false
1028 }
1029 return cleaned, absBase, true
1030 }
1031
1032 func readPDFRef(path string, size int64) string {
1033 result, err := extractPDFText(path)
1034 if err != nil {
1035 return fmt.Sprintf("[PDF file %s, %d bytes — text extraction unavailable: %v. If this is a scanned/image-only PDF, use OCR or an available multimodal/vision tool with this path.]", path, size, err)
1036 }
1037 text := strings.TrimSpace(result.text)
1038 if text == "" {
1039 return fmt.Sprintf("[PDF file %s, %d bytes — no extractable text found. It may be scanned/image-only; use OCR or an available multimodal/vision tool with this path.]", path, size)
1040 }
1041 var b strings.Builder
1042 fmt.Fprintf(&b, "[PDF text extracted from %s using %s", path, result.tool)
1043 if result.truncated {
1044 fmt.Fprintf(&b, "; truncated to the first %d bytes", maxFileRefBytes)
1045 }
1046 b.WriteString("]\n")
1047 b.WriteString(text)
1048 return b.String()
1049 }
1050
1051 func extractPDFTextDefault(path string) (pdfExtractResult, error) {
1052 var firstErr error
1053 if pdftotext, err := exec.LookPath("pdftotext"); err == nil {
1054 if text, truncated, err := runPDFTextCommand(pdftotext, []string{"-enc", "UTF-8", "-layout", path, "-"}); err == nil {
1055 return pdfExtractResult{text: text, tool: "pdftotext", truncated: truncated}, nil
1056 } else {
1057 firstErr = err
1058 }
1059 }
1060 python, err := findPython()
1061 if err != nil {
1062 if firstErr != nil {
1063 return pdfExtractResult{}, fmt.Errorf("pdftotext failed (%w), and Python PDF libraries are not available", firstErr)
1064 }
1065 return pdfExtractResult{}, fmt.Errorf("pdftotext and Python PDF libraries are not available")
1066 }
1067 text, truncated, err := runPDFTextCommand(python, []string{"-c", pythonPDFExtractScript, path})
1068 if err != nil {
1069 if firstErr != nil {
1070 return pdfExtractResult{}, fmt.Errorf("pdftotext failed (%w), Python PDF extraction failed (%w)", firstErr, err)
1071 }
1072 return pdfExtractResult{}, err
1073 }
1074 return pdfExtractResult{text: text, tool: "Python PDF library", truncated: truncated}, nil
1075 }
1076
1077 func findPython() (string, error) {
1078 for _, name := range []string{"python3", "python", "py"} {
1079 if p, err := exec.LookPath(name); err == nil {
1080 return p, nil
1081 }
1082 }
1083 return "", fmt.Errorf("python not found")
1084 }
1085
1086 func runPDFTextCommand(name string, args []string) (string, bool, error) {
1087 ctx, cancel := context.WithTimeout(context.Background(), pdfExtractTimeout)
1088 defer cancel()
1089 cmd := proc.CommandContext(ctx, name, args...)
1090 cmd.Env = secrets.ProcessEnv()
1091 setShellKillTree(cmd)
1092 cmd.WaitDelay = pdfExtractWaitDelay
1093 proc.HideWindow(cmd)
1094 var stdout limitedBuffer
1095 var stderr limitedBuffer
1096 cmd.Stdout = &stdout
1097 cmd.Stderr = &stderr
1098 waitErr := cmd.Run()
1099 if ctx.Err() == context.DeadlineExceeded {
1100 return "", false, fmt.Errorf("PDF text extraction timed out")
1101 }
1102 if waitErr != nil {
1103 msg := strings.TrimSpace(stderr.String())
1104 if msg != "" {
1105 if stderr.Truncated() {
1106 msg += "\n…[truncated]…"
1107 }
1108 return "", false, fmt.Errorf("%w: %s", waitErr, msg)
1109 }
1110 return "", false, waitErr
1111 }
1112 return stdout.String(), stdout.Truncated(), nil
1113 }
1114
1115 type limitedBuffer struct {
1116 buf bytes.Buffer
1117 truncated bool
1118 }
1119
1120 func (b *limitedBuffer) Write(p []byte) (int, error) {
1121 remaining := maxFileRefBytes - b.buf.Len()
1122 if remaining > 0 {
1123 if len(p) > remaining {
1124 _, _ = b.buf.Write(p[:remaining])
1125 b.truncated = true
1126 } else {
1127 _, _ = b.buf.Write(p)
1128 }
1129 } else if len(p) > 0 {
1130 b.truncated = true
1131 }
1132 return len(p), nil
1133 }
1134
1135 func (b *limitedBuffer) String() string { return b.buf.String() }
1136
1137 func (b *limitedBuffer) Truncated() bool { return b.truncated }
1138
1139 const pythonPDFExtractScript = `
1140 import sys
1141
1142 path = sys.argv[1]
1143
1144 try:
1145 from pypdf import PdfReader
1146 except Exception:
1147 try:
1148 from PyPDF2 import PdfReader
1149 except Exception:
1150 PdfReader = None
1151
1152 if PdfReader is not None:
1153 reader = PdfReader(path)
1154 for page in reader.pages:
1155 text = page.extract_text() or ""
1156 if text:
1157 print(text)
1158 sys.exit(0)
1159
1160 try:
1161 import pdfplumber
1162 except Exception as exc:
1163 raise SystemExit("no supported Python PDF library found") from exc
1164
1165 with pdfplumber.open(path) as pdf:
1166 for page in pdf.pages:
1167 text = page.extract_text() or ""
1168 if text:
1169 print(text)
1170 `
1171
1172 func imageMime(data []byte, path string) string {
1173 mime := http.DetectContentType(data[:min(len(data), 512)])
1174 if strings.HasPrefix(mime, "image/") {
1175 return mime
1176 }
1177 switch strings.ToLower(filepath.Ext(path)) {
1178 case ".png":
1179 return "image/png"
1180 case ".jpg", ".jpeg":
1181 return "image/jpeg"
1182 case ".gif":
1183 return "image/gif"
1184 case ".webp":
1185 return "image/webp"
1186 case ".tiff", ".tif":
1187 return "image/tiff"
1188 }
1189 return ""
1190 }
1191
1191 lines GO