@ai-agent-forge/agent-forge 0.88.6 → 0.88.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/bundled-plugins/agent-loop-policy/agent-forge.json +1 -1
  3. package/bundled-plugins/agent-loop-policy/plugin.json +1 -1
  4. package/bundled-plugins/alignment/agent-forge.json +1 -1
  5. package/bundled-plugins/alignment/dist/engine.d.ts.map +1 -1
  6. package/bundled-plugins/alignment/dist/engine.js +6 -0
  7. package/bundled-plugins/alignment/dist/engine.js.map +1 -1
  8. package/bundled-plugins/alignment/dist/index.d.ts.map +1 -1
  9. package/bundled-plugins/alignment/dist/index.js +1 -0
  10. package/bundled-plugins/alignment/dist/index.js.map +1 -1
  11. package/bundled-plugins/alignment/dist/page.d.ts.map +1 -1
  12. package/bundled-plugins/alignment/dist/page.js +41 -4
  13. package/bundled-plugins/alignment/dist/page.js.map +1 -1
  14. package/bundled-plugins/alignment/dist/types.d.ts +1 -1
  15. package/bundled-plugins/alignment/dist/types.d.ts.map +1 -1
  16. package/bundled-plugins/alignment/dist/types.js.map +1 -1
  17. package/bundled-plugins/alignment/plugin.json +1 -1
  18. package/bundled-plugins/browser-playwright/agent-forge.json +1 -1
  19. package/bundled-plugins/browser-playwright/plugin.json +1 -1
  20. package/bundled-plugins/coding-tools/agent-forge.json +1 -1
  21. package/bundled-plugins/coding-tools/dist/read.d.ts +2 -0
  22. package/bundled-plugins/coding-tools/dist/read.d.ts.map +1 -1
  23. package/bundled-plugins/coding-tools/dist/read.js +11 -0
  24. package/bundled-plugins/coding-tools/dist/read.js.map +1 -1
  25. package/bundled-plugins/coding-tools/plugin.json +1 -1
  26. package/bundled-plugins/compaction-policy/agent-forge.json +1 -1
  27. package/bundled-plugins/compaction-policy/plugin.json +1 -1
  28. package/bundled-plugins/overflow-policy/agent-forge.json +1 -1
  29. package/bundled-plugins/overflow-policy/plugin.json +1 -1
  30. package/bundled-plugins/provider-failover/agent-forge.json +1 -1
  31. package/bundled-plugins/provider-failover/plugin.json +1 -1
  32. package/bundled-plugins/retry-policy/agent-forge.json +1 -1
  33. package/bundled-plugins/retry-policy/plugin.json +1 -1
  34. package/dist/bundle/.build-manifest.json +3 -3
  35. package/dist/bundle/chunks/{chunk-POLDAUYA.js → chunk-L2SXIPI5.js} +1 -1
  36. package/dist/bundle/cli.js +1 -1
  37. package/dist/bundle/index.js +1 -1
  38. package/dist/bundle/rpc-entry.js +1 -1
  39. package/dist/plugins/ecosystem/node-plugin-bootstrap.d.ts.map +1 -1
  40. package/dist/plugins/ecosystem/node-plugin-bootstrap.js +26 -0
  41. package/dist/plugins/ecosystem/node-plugin-bootstrap.js.map +1 -1
  42. package/examples/extensions/with-deps/package-lock.json +2 -2
  43. package/examples/extensions/with-deps/package.json +1 -1
  44. package/examples/extensions/with-deps/plugin.json +1 -1
  45. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../src/read.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,cAAc,EAA+C,MAAM,mCAAmC,CAAC;AACrH,OAAO,EAIN,KAAK,gBAAgB,EAErB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,KAAK,EAAE,SAAS,EAAwC,MAAM,YAAY,CAAC;AAGlF,QAAA,MAAM,UAAU;;;;EAId,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC9B;AASD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,qCAAqC;IACrC,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,+CAA+C;IAC/C,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,sEAAsE;IACtE,mBAAmB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;CACnF;AAQD,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AA4ID,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAoJhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["// Migrated from packages/agent-forge/src/core/tools/read.ts (batch 1, copy-then-delete);\n// host modules are imported through supply keys (@agent-forge/host/*).\n\nimport { constants } from \"node:fs\";\nimport { access as fsAccess, readFile as fsReadFile } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport { t } from \"@agent-forge/host/i18n\";\nimport { processImage } from \"@agent-forge/host/image-process\";\nimport { keyHint, keyText } from \"@agent-forge/host/keybinding-hints\";\nimport { detectSupportedImageMimeTypeFromFile } from \"@agent-forge/host/mime\";\nimport { resolveReadPathAsync, resolveToCwd } from \"@agent-forge/host/path-utils\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"@agent-forge/host/paths\";\nimport { getTextOutput, renderToolPath, replaceTabs, str } from \"@agent-forge/host/render-utils\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"@agent-forge/host/theme\";\nimport type { ToolDefinition, ToolExecuteContext, ToolRenderResultOptions } from \"@agent-forge/host/tool-definition\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationResult,\n\ttruncateHead,\n} from \"@agent-forge/host/truncate\";\nimport { Text } from \"@agent-forge/tui\";\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"./config.ts\";\nimport type { AgentTool, ImageContent, TextContent, ToolModel } from \"./types.ts\";\nimport { wrapToolDefinition } from \"./types.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport const readToolSystemPromptContribution = {\n\tsnippet: \"Read file contents\",\n\tguidelines: [\"Use read to examine files instead of cat or sed.\"],\n} as const;\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\n\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.override.md\", \"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: number; limit?: number };\n\nfunction formatReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tif (args?.offset === undefined && args?.limit === undefined) return \"\";\n\tconst startLine = args.offset ?? 1;\n\tconst endLine = args.limit !== undefined ? startLine + args.limit - 1 : \"\";\n\treturn theme.fg(\"warning\", `:${startLine}${endLine ? `-${endLine}` : \"\"}`);\n}\n\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction getNonVisionImageNote(model: ToolModel | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\n\nfunction getPiDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\n\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\n\treturn undefined;\n}\n\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} ${t(\"to expand\")})`);\n\tif (classification.kind === \"skill\") {\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\n\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: { content: (TextContent | ImageContent)[]; details?: ReadToolDetails },\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\t_cwd: string,\n\tisError: boolean,\n): string {\n\tif (!options.expanded && !isError) {\n\t\treturn \"\";\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = !isError && rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t\t} else {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n\t\t}\n\t}\n\treturn text;\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\treadonlySafe: true,\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: readToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...readToolSystemPromptContribution.guidelines],\n\t\tparameters: readSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, offset, limit }: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ToolExecuteContext,\n\t\t) {\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(path, ctx?.cwd || cwd);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t// Check if file exists and is readable.\n\t\t\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst processed = await processImage(buffer, mimeType, { autoResizeImages });\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read text content.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst textContent = buffer.toString(\"utf-8\");\n\t\t\t\t\t\t\t\tconst allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\t// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\tt(\"Offset {offset} is beyond end of file ({totalLines} lines total)\", {\n\t\t\t\t\t\t\t\t\t\t\toffset: offset ?? 1,\n\t\t\t\t\t\t\t\t\t\t\ttotalLines: allLines.length,\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\t// If limit is specified by the user, honor it first. Otherwise truncateHead decides.\n\t\t\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine, endLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Apply truncation, respecting both line and byte limits.\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\ttext.setText(\n\t\t\t\tclassification\n\t\t\t\t\t? formatCompactReadCall(classification, args, theme)\n\t\t\t\t\t: formatReadCall(args, theme, context.cwd),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../src/read.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,cAAc,EAA+C,MAAM,mCAAmC,CAAC;AACrH,OAAO,EAIN,KAAK,gBAAgB,EAErB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,KAAK,EAAE,SAAS,EAAwC,MAAM,YAAY,CAAC;AAGlF,QAAA,MAAM,UAAU;;;;EAId,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,6EAA6E;IAC7E,SAAS,CAAC,EAAE,OAAO,CAAC;CACpB;AASD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,qCAAqC;IACrC,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,+CAA+C;IAC/C,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,sEAAsE;IACtE,mBAAmB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;CACnF;AAQD,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AA4ID,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CA+JhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["// Migrated from packages/agent-forge/src/core/tools/read.ts (batch 1, copy-then-delete);\n// host modules are imported through supply keys (@agent-forge/host/*).\n\nimport { constants } from \"node:fs\";\nimport { access as fsAccess, readFile as fsReadFile } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport { t } from \"@agent-forge/host/i18n\";\nimport { processImage } from \"@agent-forge/host/image-process\";\nimport { keyHint, keyText } from \"@agent-forge/host/keybinding-hints\";\nimport { detectSupportedImageMimeTypeFromFile } from \"@agent-forge/host/mime\";\nimport { resolveReadPathAsync, resolveToCwd } from \"@agent-forge/host/path-utils\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"@agent-forge/host/paths\";\nimport { getTextOutput, renderToolPath, replaceTabs, str } from \"@agent-forge/host/render-utils\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"@agent-forge/host/theme\";\nimport type { ToolDefinition, ToolExecuteContext, ToolRenderResultOptions } from \"@agent-forge/host/tool-definition\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationResult,\n\ttruncateHead,\n} from \"@agent-forge/host/truncate\";\nimport { Text } from \"@agent-forge/tui\";\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"./config.ts\";\nimport type { AgentTool, ImageContent, TextContent, ToolModel } from \"./types.ts\";\nimport { wrapToolDefinition } from \"./types.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport const readToolSystemPromptContribution = {\n\tsnippet: \"Read file contents\",\n\tguidelines: [\"Use read to examine files instead of cat or sed.\"],\n} as const;\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n\t/** Set when the file exists but is 0 bytes (see the \"[Empty file]\" note). */\n\temptyFile?: boolean;\n}\n\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\n\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.override.md\", \"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: number; limit?: number };\n\nfunction formatReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tif (args?.offset === undefined && args?.limit === undefined) return \"\";\n\tconst startLine = args.offset ?? 1;\n\tconst endLine = args.limit !== undefined ? startLine + args.limit - 1 : \"\";\n\treturn theme.fg(\"warning\", `:${startLine}${endLine ? `-${endLine}` : \"\"}`);\n}\n\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction getNonVisionImageNote(model: ToolModel | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\n\nfunction getPiDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\n\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\n\treturn undefined;\n}\n\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} ${t(\"to expand\")})`);\n\tif (classification.kind === \"skill\") {\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\n\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: { content: (TextContent | ImageContent)[]; details?: ReadToolDetails },\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\t_cwd: string,\n\tisError: boolean,\n): string {\n\tif (!options.expanded && !isError) {\n\t\treturn \"\";\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = !isError && rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t\t} else {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n\t\t}\n\t}\n\treturn text;\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\treadonlySafe: true,\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: readToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...readToolSystemPromptContribution.guidelines],\n\t\tparameters: readSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, offset, limit }: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ToolExecuteContext,\n\t\t) {\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(path, ctx?.cwd || cwd);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t// Check if file exists and is readable.\n\t\t\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst processed = await processImage(buffer, mimeType, { autoResizeImages });\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read text content.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tif (buffer.length === 0) {\n\t\t\t\t\t\t\t\t\t// Empty text payloads are rejected downstream (transform event\n\t\t\t\t\t\t\t\t\t// validation requires non-empty text), and an empty string\n\t\t\t\t\t\t\t\t\t// tells the model nothing anyway. Mirror the bracketed-note\n\t\t\t\t\t\t\t\t\t// style used by the other synthetic read annotations.\n\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"[Empty file]\" }],\n\t\t\t\t\t\t\t\t\t\tdetails: { emptyFile: true },\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst textContent = buffer.toString(\"utf-8\");\n\t\t\t\t\t\t\t\tconst allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\t// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\tt(\"Offset {offset} is beyond end of file ({totalLines} lines total)\", {\n\t\t\t\t\t\t\t\t\t\t\toffset: offset ?? 1,\n\t\t\t\t\t\t\t\t\t\t\ttotalLines: allLines.length,\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\t// If limit is specified by the user, honor it first. Otherwise truncateHead decides.\n\t\t\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine, endLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Apply truncation, respecting both line and byte limits.\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\ttext.setText(\n\t\t\t\tclassification\n\t\t\t\t\t? formatCompactReadCall(classification, args, theme)\n\t\t\t\t\t: formatReadCall(args, theme, context.cwd),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
@@ -196,6 +196,17 @@ export function createReadToolDefinition(cwd, options) {
196
196
  else {
197
197
  // Read text content.
198
198
  const buffer = await ops.readFile(absolutePath);
199
+ if (buffer.length === 0) {
200
+ // Empty text payloads are rejected downstream (transform event
201
+ // validation requires non-empty text), and an empty string
202
+ // tells the model nothing anyway. Mirror the bracketed-note
203
+ // style used by the other synthetic read annotations.
204
+ resolve({
205
+ content: [{ type: "text", text: "[Empty file]" }],
206
+ details: { emptyFile: true },
207
+ });
208
+ return;
209
+ }
199
210
  const textContent = buffer.toString("utf-8");
200
211
  const allLines = textContent.split("\n");
201
212
  const totalFileLines = allLines.length;
@@ -1 +1 @@
1
- {"version":3,"file":"read.js","sourceRoot":"","sources":["../src/read.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,uEAAuE;AAEvE,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACjG,OAAO,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAC/D,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,oCAAoC,CAAC;AACtE,OAAO,EAAE,oCAAoC,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAClF,OAAO,EAAE,iCAAiC,EAAE,MAAM,yBAAyB,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACjG,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAc,MAAM,yBAAyB,CAAC;AAEzF,OAAO,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AO,CACX,cAAc;gBACb,CAAC,CAAC,qBAAqB,CAAC,cAAc,EAAE,IAAI,EAAE,KAAK,CAAC;gBACpD,CAAC,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,GAAG,CAAC,CAC3C,CAAC;YACF,OAAO,IAAI,CAAC;QAAA,CACZ;QACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;YAC7C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CACX,gBAAgB,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,CACxG,CAAC;YACF,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB,EAAgC;IACpG,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAClE","sourcesContent":["// Migrated from packages/agent-forge/src/core/tools/read.ts (batch 1, copy-then-delete);\n// host modules are imported through supply keys (@agent-forge/host/*).\n\nimport { constants } from \"node:fs\";\nimport { access as fsAccess, readFile as fsReadFile } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport { t } from \"@agent-forge/host/i18n\";\nimport { processImage } from \"@agent-forge/host/image-process\";\nimport { keyHint, keyText } from \"@agent-forge/host/keybinding-hints\";\nimport { detectSupportedImageMimeTypeFromFile } from \"@agent-forge/host/mime\";\nimport { resolveReadPathAsync, resolveToCwd } from \"@agent-forge/host/path-utils\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"@agent-forge/host/paths\";\nimport { getTextOutput, renderToolPath, replaceTabs, str } from \"@agent-forge/host/render-utils\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"@agent-forge/host/theme\";\nimport type { ToolDefinition, ToolExecuteContext, ToolRenderResultOptions } from \"@agent-forge/host/tool-definition\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationResult,\n\ttruncateHead,\n} from \"@agent-forge/host/truncate\";\nimport { Text } from \"@agent-forge/tui\";\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"./config.ts\";\nimport type { AgentTool, ImageContent, TextContent, ToolModel } from \"./types.ts\";\nimport { wrapToolDefinition } from \"./types.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport const readToolSystemPromptContribution = {\n\tsnippet: \"Read file contents\",\n\tguidelines: [\"Use read to examine files instead of cat or sed.\"],\n} as const;\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\n\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.override.md\", \"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: number; limit?: number };\n\nfunction formatReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tif (args?.offset === undefined && args?.limit === undefined) return \"\";\n\tconst startLine = args.offset ?? 1;\n\tconst endLine = args.limit !== undefined ? startLine + args.limit - 1 : \"\";\n\treturn theme.fg(\"warning\", `:${startLine}${endLine ? `-${endLine}` : \"\"}`);\n}\n\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction getNonVisionImageNote(model: ToolModel | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\n\nfunction getPiDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\n\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\n\treturn undefined;\n}\n\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} ${t(\"to expand\")})`);\n\tif (classification.kind === \"skill\") {\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\n\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: { content: (TextContent | ImageContent)[]; details?: ReadToolDetails },\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\t_cwd: string,\n\tisError: boolean,\n): string {\n\tif (!options.expanded && !isError) {\n\t\treturn \"\";\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = !isError && rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t\t} else {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n\t\t}\n\t}\n\treturn text;\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\treadonlySafe: true,\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: readToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...readToolSystemPromptContribution.guidelines],\n\t\tparameters: readSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, offset, limit }: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ToolExecuteContext,\n\t\t) {\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(path, ctx?.cwd || cwd);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t// Check if file exists and is readable.\n\t\t\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst processed = await processImage(buffer, mimeType, { autoResizeImages });\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read text content.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst textContent = buffer.toString(\"utf-8\");\n\t\t\t\t\t\t\t\tconst allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\t// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\tt(\"Offset {offset} is beyond end of file ({totalLines} lines total)\", {\n\t\t\t\t\t\t\t\t\t\t\toffset: offset ?? 1,\n\t\t\t\t\t\t\t\t\t\t\ttotalLines: allLines.length,\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\t// If limit is specified by the user, honor it first. Otherwise truncateHead decides.\n\t\t\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine, endLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Apply truncation, respecting both line and byte limits.\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\ttext.setText(\n\t\t\t\tclassification\n\t\t\t\t\t? formatCompactReadCall(classification, args, theme)\n\t\t\t\t\t: formatReadCall(args, theme, context.cwd),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"read.js","sourceRoot":"","sources":["../src/read.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,uEAAuE;AAEvE,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACjG,OAAO,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAC/D,OAAO,EAAE,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,EAAE,OAAO,CAAC,OAAO,CAAC,CACxG,CAAC;YACF,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB,EAAgC;IACpG,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAClE","sourcesContent":["// Migrated from packages/agent-forge/src/core/tools/read.ts (batch 1, copy-then-delete);\n// host modules are imported through supply keys (@agent-forge/host/*).\n\nimport { constants } from \"node:fs\";\nimport { access as fsAccess, readFile as fsReadFile } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport { t } from \"@agent-forge/host/i18n\";\nimport { processImage } from \"@agent-forge/host/image-process\";\nimport { keyHint, keyText } from \"@agent-forge/host/keybinding-hints\";\nimport { detectSupportedImageMimeTypeFromFile } from \"@agent-forge/host/mime\";\nimport { resolveReadPathAsync, resolveToCwd } from \"@agent-forge/host/path-utils\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"@agent-forge/host/paths\";\nimport { getTextOutput, renderToolPath, replaceTabs, str } from \"@agent-forge/host/render-utils\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"@agent-forge/host/theme\";\nimport type { ToolDefinition, ToolExecuteContext, ToolRenderResultOptions } from \"@agent-forge/host/tool-definition\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationResult,\n\ttruncateHead,\n} from \"@agent-forge/host/truncate\";\nimport { Text } from \"@agent-forge/tui\";\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"./config.ts\";\nimport type { AgentTool, ImageContent, TextContent, ToolModel } from \"./types.ts\";\nimport { wrapToolDefinition } from \"./types.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport const readToolSystemPromptContribution = {\n\tsnippet: \"Read file contents\",\n\tguidelines: [\"Use read to examine files instead of cat or sed.\"],\n} as const;\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n\t/** Set when the file exists but is 0 bytes (see the \"[Empty file]\" note). */\n\temptyFile?: boolean;\n}\n\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\n\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.override.md\", \"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: number; limit?: number };\n\nfunction formatReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tif (args?.offset === undefined && args?.limit === undefined) return \"\";\n\tconst startLine = args.offset ?? 1;\n\tconst endLine = args.limit !== undefined ? startLine + args.limit - 1 : \"\";\n\treturn theme.fg(\"warning\", `:${startLine}${endLine ? `-${endLine}` : \"\"}`);\n}\n\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction getNonVisionImageNote(model: ToolModel | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\n\nfunction getPiDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\n\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\n\treturn undefined;\n}\n\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} ${t(\"to expand\")})`);\n\tif (classification.kind === \"skill\") {\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\n\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: { content: (TextContent | ImageContent)[]; details?: ReadToolDetails },\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\t_cwd: string,\n\tisError: boolean,\n): string {\n\tif (!options.expanded && !isError) {\n\t\treturn \"\";\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = !isError && rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t\t} else {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n\t\t}\n\t}\n\treturn text;\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\treadonlySafe: true,\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: readToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...readToolSystemPromptContribution.guidelines],\n\t\tparameters: readSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, offset, limit }: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ToolExecuteContext,\n\t\t) {\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(path, ctx?.cwd || cwd);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t// Check if file exists and is readable.\n\t\t\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst processed = await processImage(buffer, mimeType, { autoResizeImages });\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read text content.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tif (buffer.length === 0) {\n\t\t\t\t\t\t\t\t\t// Empty text payloads are rejected downstream (transform event\n\t\t\t\t\t\t\t\t\t// validation requires non-empty text), and an empty string\n\t\t\t\t\t\t\t\t\t// tells the model nothing anyway. Mirror the bracketed-note\n\t\t\t\t\t\t\t\t\t// style used by the other synthetic read annotations.\n\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"[Empty file]\" }],\n\t\t\t\t\t\t\t\t\t\tdetails: { emptyFile: true },\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst textContent = buffer.toString(\"utf-8\");\n\t\t\t\t\t\t\t\tconst allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\t// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\tt(\"Offset {offset} is beyond end of file ({totalLines} lines total)\", {\n\t\t\t\t\t\t\t\t\t\t\toffset: offset ?? 1,\n\t\t\t\t\t\t\t\t\t\t\ttotalLines: allLines.length,\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\t// If limit is specified by the user, honor it first. Otherwise truncateHead decides.\n\t\t\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine, endLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Apply truncation, respecting both line and byte limits.\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\ttext.setText(\n\t\t\t\tclassification\n\t\t\t\t\t? formatCompactReadCall(classification, args, theme)\n\t\t\t\t\t: formatReadCall(args, theme, context.cwd),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "agent-forge.plugin.coding-tools",
3
- "version": "0.88.6",
3
+ "version": "0.88.8",
4
4
  "apiVersion": "1-draft",
5
5
  "entry": "./dist/entry.js",
6
6
  "hostVersion": ">=0.88.0",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "packageFormatVersion": 1,
3
3
  "id": "agent-forge.plugin.compaction-policy",
4
- "pluginVersion": "0.88.6",
4
+ "pluginVersion": "0.88.8",
5
5
  "apiVersion": "1",
6
6
  "minHostVersion": "0.88.0",
7
7
  "platform": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "agent-forge.plugin.compaction-policy",
3
- "version": "0.88.6",
3
+ "version": "0.88.8",
4
4
  "apiVersion": "1-draft",
5
5
  "entry": "./dist/entry.js",
6
6
  "hostVersion": ">=0.88.0",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "packageFormatVersion": 1,
3
3
  "id": "agent-forge.plugin.overflow-policy",
4
- "pluginVersion": "0.88.6",
4
+ "pluginVersion": "0.88.8",
5
5
  "apiVersion": "1",
6
6
  "minHostVersion": "0.88.0",
7
7
  "platform": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "agent-forge.plugin.overflow-policy",
3
- "version": "0.88.6",
3
+ "version": "0.88.8",
4
4
  "apiVersion": "1-draft",
5
5
  "entry": "./dist/entry.js",
6
6
  "hostVersion": ">=0.88.0",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "packageFormatVersion": 1,
3
3
  "id": "agent-forge.plugin.provider-failover",
4
- "pluginVersion": "0.88.6",
4
+ "pluginVersion": "0.88.8",
5
5
  "apiVersion": "1",
6
6
  "minHostVersion": "0.88.0",
7
7
  "platform": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "agent-forge.plugin.provider-failover",
3
- "version": "0.88.6",
3
+ "version": "0.88.8",
4
4
  "apiVersion": "1-draft",
5
5
  "entry": "./dist/entry.js",
6
6
  "hostVersion": ">=0.88.0"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "packageFormatVersion": 1,
3
3
  "id": "agent-forge.plugin.retry-policy",
4
- "pluginVersion": "0.88.6",
4
+ "pluginVersion": "0.88.8",
5
5
  "apiVersion": "1",
6
6
  "minHostVersion": "0.88.0",
7
7
  "platform": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "agent-forge.plugin.retry-policy",
3
- "version": "0.88.6",
3
+ "version": "0.88.8",
4
4
  "apiVersion": "1-draft",
5
5
  "entry": "./dist/entry.js",
6
6
  "hostVersion": ">=0.88.0",
@@ -1,5 +1,5 @@
1
1
  {
2
- "generatedAt": "2026-10-08T11:40:07.784Z",
2
+ "generatedAt": "2026-10-08T15:09:12.663Z",
3
3
  "inputCount": 3615,
4
4
  "inputs": {
5
5
  "node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs": "717f9403f2d3ee0f2077aeb7f0ca7eaff7cc9bcdbb054ac23c6c0361fa03cd1f",
@@ -2284,7 +2284,7 @@
2284
2284
  "packages/agent-forge/dist/plugins/ecosystem/node-package-install-stack.js": "93673d75ccb1cb33640364e8e8a025b5467288b98a5524c92b00415294aa03fd",
2285
2285
  "packages/agent-forge/dist/plugins/ecosystem/node-package-media.js": "62591d510f7ab735923afacef387f95b3f435ca92811c6319fe07f98a992f045",
2286
2286
  "packages/agent-forge/dist/plugins/ecosystem/node-plugin-acquisition-host.js": "43a653cfb4d631d7a802599202a1a7f1a5320b1a81f0f2c78acb4a55193c2b05",
2287
- "packages/agent-forge/dist/plugins/ecosystem/node-plugin-bootstrap.js": "b61b72d3a82fbdd463ea6cd55facd5329a67391e095c885eaf50ca29de5194e6",
2287
+ "packages/agent-forge/dist/plugins/ecosystem/node-plugin-bootstrap.js": "e2844cea6a74e0374ad5f7d2be00417bba864d552fc3338947e901adee15654f",
2288
2288
  "packages/agent-forge/dist/plugins/ecosystem/node-plugin-trust-root.js": "89795dfeacbdd1634869c1a20c538cfba0ee34b3e6cf4250320f885d9b112c87",
2289
2289
  "packages/agent-forge/dist/plugins/ecosystem/node-registry-source.js": "de727dc1e7e9b91289fbe744fd7af161ba9cee8a03d2b3b91c4b364ad06626d9",
2290
2290
  "packages/agent-forge/dist/plugins/ecosystem/node-release-package-source.js": "5b01b720fba082fd07e346eb29376e9d659c412ec5b10f3756c2a19ea2db48d7",
@@ -2762,7 +2762,7 @@
2762
2762
  "packages/agent-forge/src/plugins/ecosystem/node-package-install-stack.ts": "eabe0245e1fc7229c2206c9ce760c06e398da7c77285da84659744ec33da84bc",
2763
2763
  "packages/agent-forge/src/plugins/ecosystem/node-package-media.ts": "ed65beb1832088ce86032da67e1de39a8d369ac2c876cab0bf37d35da62646c5",
2764
2764
  "packages/agent-forge/src/plugins/ecosystem/node-plugin-acquisition-host.ts": "b4b1c96d78510a0b2eee0664ef780d8846f9a69b7f3c6973314e0045f3b19a7f",
2765
- "packages/agent-forge/src/plugins/ecosystem/node-plugin-bootstrap.ts": "973b2f63ebd73629633716dff393d035f48efd6cad078c43baaff41cb1537ba6",
2765
+ "packages/agent-forge/src/plugins/ecosystem/node-plugin-bootstrap.ts": "b53eade690d3ba946b870932aadbb4ab64f0d9eed594cfdfb71358af34cf6b7e",
2766
2766
  "packages/agent-forge/src/plugins/ecosystem/node-plugin-trust-root.ts": "51a327037640a46d835dc2ba0ee3c68b88105fcff14d2c12f844103fc7a37218",
2767
2767
  "packages/agent-forge/src/plugins/ecosystem/node-registry-source.ts": "5c4cbbd4c2739d6929ae50c8a663667cb30fef400bb2a46e4ed8124b90bd8385",
2768
2768
  "packages/agent-forge/src/plugins/ecosystem/node-release-package-source.ts": "e76f641e610c9d9d5d5d4082ae49b627044b9d936a57aceb94d2b3d43ba6f9c2",
@@ -796,7 +796,7 @@ changes anytime in settings.json.`)),1,0)),this.addChild(new Spacer(1)),this.add
796
796
  ${value.stack}`}
797
797
  `}return`${JSON.stringify(toSafeJson(value))}
798
798
  `}function createHostLogger(options){if(options.level!==void 0&&!HOST_LOG_LEVELS.includes(options.level))throw new Error(t("Host logger level must be one of {levels}; got {value}",{levels:HOST_LOG_LEVELS.map(level=>`"${level}"`).join(" | "),value:JSON.stringify(options.level)}));let minRank=LEVEL_RANK[options.level??"info"],now=options.now??Date.now,maxAgeDays=options.maxAgeDays??DEFAULT_MAX_AGE_DAYS,processHost=options.processHost??NODE_PROCESS_HOST,closed=!1,dirReady=!1,written=0,failed=0,write=(level,src,msg,context)=>{if(closed||LEVEL_RANK[level]<minRank)return;let entry={v:1,t:now(),level,src,msg,sessionId:context?.sessionId,traceId:context?.traceId,fields:context?.fields===void 0?void 0:toSafeJson(context.fields),cause:context?.cause===void 0?void 0:boundCause(context.cause)};try{dirReady||(mkdirSync13(options.dir,{recursive:!0}),dirReady=!0),appendFileSync(join46(options.dir,logFileName(entry.t)),`${JSON.stringify(entry)}
799
- `),written+=1}catch{failed+=1,dirReady=!1}};(()=>{if(maxAgeDays<=0)return;let cutoff=now()-maxAgeDays*DAY_MS2,currentName=logFileName(now()),names;try{names=readdirSync11(options.dir)}catch(error){if(error.code==="ENOENT")return;write("warn","logger","log sweep failed: cannot read log directory",{cause:error});return}let removed=0,errors=0;for(let name of names){if(!name.endsWith(".log")||name===currentName)continue;let fullPath=join46(options.dir,name);try{let stats=statSync12(fullPath);if(!stats.isFile()||stats.mtimeMs>=cutoff)continue;unlinkSync4(fullPath),removed+=1}catch{errors+=1}}errors>0&&write("warn","logger","log sweep finished with failures",{fields:{removed,errors}})})();let exit=processHost.exit??NODE_PROCESS_CRASH_HOST.exit,writeStderr=processHost.writeStderr??NODE_PROCESS_CRASH_HOST.writeStderr,deferThrow=processHost.deferThrow??NODE_PROCESS_CRASH_HOST.deferThrow,loggedFatalValues=new WeakSet,isFatalValueLogged=value=>value!==null&&(typeof value=="object"||typeof value=="function")&&loggedFatalValues.has(value),markFatalValueLogged=value=>{value!==null&&(typeof value=="object"||typeof value=="function")&&loggedFatalValues.add(value)};return processHost.onUncaughtException&&processHost.onUncaughtException(error=>{isFatalValueLogged(error)||(markFatalValueLogged(error),write("error","process","uncaughtException",{cause:error})),writeStderr(fatalStderrText(error)),exit(1)}),processHost.onUnhandledRejection&&processHost.onUnhandledRejection(reason=>{markFatalValueLogged(reason),write("error","process","unhandledRejection",{cause:reason}),deferThrow(()=>{throw reason})}),{debug:(src,msg,context)=>write("debug",src,msg,context),info:(src,msg,context)=>write("info",src,msg,context),warn:(src,msg,context)=>write("warn",src,msg,context),error:(src,msg,context)=>write("error",src,msg,context),close:()=>(closed=!0,{written,failed})}}function collectSettingsDiagnostics(settingsManager){return settingsManager.drainErrors().map(({scope,path:path8,error})=>({type:"warning",message:path8?`Invalid settings file ${path8}: ${error.message}`:`Invalid ${scope} settings: ${error.message}`}))}function deduplicateDiagnostics(diagnostics){let seen=new Set;return diagnostics.filter(diagnostic5=>{let key=`${diagnostic5.type}\0${diagnostic5.message}`;return seen.has(key)?!1:(seen.add(key),!0)})}import{readdirSync as readdirSync12,statSync as statSync13,unlinkSync as unlinkSync5}from"node:fs";import{join as join47}from"node:path";var DAY_MS3=1440*60*1e3,TRACE_FILE_SUFFIX=".trace.jsonl",DEFAULT_TRACE_MAX_AGE_DAYS=14,DEFAULT_TRACE_MAX_FILES_PER_DIRECTORY=500;function sweepTraceFiles(sessionsRoot,options){let capActive=options.maxFilesPerDirectory!==void 0&&options.maxFilesPerDirectory>0;if(options.maxAgeDays<=0&&!capActive)return{scanned:0,deleted:0,failed:0};let now=options.now??Date.now,unlink5=options.unlink??(path8=>unlinkSync5(path8)),cutoff=now()-options.maxAgeDays*DAY_MS3,maxFilesPerDirectory=capActive?options.maxFilesPerDirectory:0,scanned=0,deleted=0,failed=0,readEntries=dir=>{try{return readdirSync12(dir,{withFileTypes:!0})}catch{return}},sweepFilesIn=(dir,entries)=>{let traceFiles=[];for(let entry of entries){if(!entry.name.endsWith(TRACE_FILE_SUFFIX))continue;let fullPath=join47(dir,entry.name);try{let stats=statSync13(fullPath);stats.isFile()&&traceFiles.push({path:fullPath,mtimeMs:stats.mtimeMs})}catch{}}scanned+=traceFiles.length;let expiredPaths=new Set(options.maxAgeDays>0?traceFiles.filter(file=>file.mtimeMs<cutoff).map(file=>file.path):[]),survivors=traceFiles.filter(file=>!expiredPaths.has(file.path)).sort((a,b)=>a.mtimeMs-b.mtimeMs),overCapCount=capActive?Math.max(0,survivors.length-maxFilesPerDirectory):0,removals=[...traceFiles.filter(file=>expiredPaths.has(file.path)),...survivors.slice(0,overCapCount)];for(let file of removals)try{unlink5(file.path),deleted+=1}catch{failed+=1}},rootEntries=readEntries(sessionsRoot);if(rootEntries===void 0)return{scanned:0,deleted:0,failed:0};sweepFilesIn(sessionsRoot,rootEntries);for(let entry of rootEntries){if(!entry.isDirectory())continue;let subdirectory=join47(sessionsRoot,entry.name),subEntries=readEntries(subdirectory);subEntries!==void 0&&sweepFilesIn(subdirectory,subEntries)}return{scanned,deleted,failed}}import{join as join48}from"node:path";var PLUGIN_BOOTSTRAP_VERSION_V1=1;function satisfiesRangeV1(version,range2){return selectNpmPackageVersionV1([version],range2)===version}function pluginBootstrapInstallCommandV1(entry){return`agent-forge plugin install ${entry.npmName}@${entry.range??"latest"}`}function errorMessage(error){return error instanceof Error?error.message:String(error)}function acquireErrorCode(error){return error instanceof PluginAcquisitionErrorV1?error.code:"install_failed"}function actionOf(entry,status,reason){return Object.freeze({pluginId:entry.pluginId,status,reason,npmName:entry.npmName,...entry.range===void 0?{}:{range:entry.range}})}async function runPluginBootstrapV1(input){let now=input.deps.now??Date.now,startedAt=now(),finish=(status2,actions2,diagnostics2)=>Object.freeze({version:PLUGIN_BOOTSTRAP_VERSION_V1,status:status2,actions:Object.freeze([...actions2]),diagnostics:Object.freeze([...diagnostics2]),durationMs:Math.max(0,now()-startedAt)});if(input.manifest.length===0)return finish("succeeded",[],[]);let signal=input.deps.signal,active;try{active=await input.deps.listActive({...signal===void 0?{}:{signal}})}catch(error){return finish("failed",[],[{code:"list_active_failed",message:`Active plugin state could not be read; bootstrap installed nothing: ${errorMessage(error)}`}])}let actions=[],diagnostics=[],record=action=>{actions.push(action),input.onAction?.(action)};if(input.onPendingInstalls!==void 0){let pending=input.manifest.filter(entry=>!active.has(entry.pluginId)).length;pending>0&&input.onPendingInstalls(pending)}for(let entry of input.manifest){if(signal?.aborted===!0){diagnostics.push({code:"cancelled",message:"Plugin bootstrap was cancelled before all factory entries were processed"});break}let activeVersion=active.get(entry.pluginId);if(activeVersion!==void 0&&satisfiesRangeV1(activeVersion,entry.range)){record(Object.freeze({...actionOf(entry,"skipped","satisfies_range"),activeVersion}));continue}try{let installed=await input.deps.installFromNpm({npmName:entry.npmName,...entry.range===void 0?{}:{range:entry.range},...signal===void 0?{}:{signal}});record(Object.freeze({...actionOf(entry,"installed",activeVersion===void 0?"installed":"range_aligned"),installedVersion:installed.pluginVersion,source:installed.source}))}catch(error){let errorCode2=acquireErrorCode(error),aligning=activeVersion!==void 0;record(Object.freeze({...actionOf(entry,"failed",aligning?"align_failed":"install_failed"),errorCode:errorCode2})),diagnostics.push({code:"install_failed",pluginId:entry.pluginId,message:aligning?`Bootstrap could not align ${entry.pluginId} (active ${activeVersion}) to the factory range ${entry.range??"latest"} from npm (${errorCode2}: ${errorMessage(error)}). Startup continues; the factory range stays unsatisfied, so the next startup retries automatically. Run \`${pluginBootstrapInstallCommandV1(entry)}\` to align it now.`:`Bootstrap could not install ${entry.pluginId} from npm (${errorCode2}: ${errorMessage(error)}). Startup continues without it; its capabilities stay unavailable until installed, and the next startup retries automatically. Run \`${pluginBootstrapInstallCommandV1(entry)}\` to install it manually.`})}}let status=actions.some(action=>action.status==="failed")?"failed":"succeeded";return finish(status,actions,diagnostics)}var AGENT_FORGE_PLUGIN_BOOTSTRAP_ENV_V1="AGENT_FORGE_PLUGIN_BOOTSTRAP",PLUGIN_BOOTSTRAP_DISABLED_VALUE_V1="off";function readActiveVersions(store,scope,scopeRef,signal){return(async()=>{let result=await store.read({...signal===void 0?{}:{signal}});if(result.status!=="ok"&&result.status!=="missing")throw new Error(t("plugin state read failed ({detail}) for the {scope} scope",{detail:result.diagnostics[0]?.code??result.status,scope}));let versions=new Map;for(let record of result.snapshot.records)record.state.scope!==scope||record.state.scopeRef!==scopeRef||record.state.lifecycle==="active"&&versions.set(record.pluginId,record.pluginVersion);return versions})()}async function readPreviousActiveRecord(store,pluginId,signal){let result=await store.read({...signal===void 0?{}:{signal}});if(result.status!=="ok"&&result.status!=="missing")throw new Error(t("plugin state read failed ({detail}) for the {scope} scope",{detail:result.diagnostics[0]?.code??result.status,scope:"global"}));return result.snapshot.records.find(record=>record.pluginId===pluginId&&record.state.scope==="global"&&record.state.scopeRef===DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1&&record.state.lifecycle==="active")}async function runNodePluginBootstrapV1(options){if(process.env[AGENT_FORGE_PLUGIN_BOOTSTRAP_ENV_V1]?.trim()===PLUGIN_BOOTSTRAP_DISABLED_VALUE_V1)return Object.freeze({version:1,status:"succeeded",actions:Object.freeze([]),diagnostics:Object.freeze([]),durationMs:0,skipped:"disabled"});if(isOfflineModeEnabled())return Object.freeze({version:1,status:"succeeded",actions:Object.freeze([]),diagnostics:Object.freeze([{code:"bootstrap_skipped_offline",message:t("Offline posture (AGENT_FORGE_OFFLINE) skips the startup plugin bootstrap; run `agent-forge plugin install <package>` explicitly to install plugins.")}]),durationMs:0,skipped:"offline"});if(options.deps!==void 0)return await runPluginBootstrapV1({manifest:options.manifest??BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1,deps:options.deps,...options.onPendingInstalls===void 0?{}:{onPendingInstalls:options.onPendingInstalls},...options.onAction===void 0?{}:{onAction:options.onAction}});let session,ensureSession=async()=>{if(session!==void 0)return session;let acquisition=createNodePluginAcquisitionHostV1({...options.npmRegistry===void 0?{}:{npmRegistry:options.npmRegistry},...options.npmToken===void 0?{}:{npmToken:options.npmToken},...options.fetch===void 0?{}:{fetch:options.fetch},...options.limits===void 0?{}:{limits:options.limits}}),installHost=await createNodePackageInstallHostV1({openArtifact:input=>acquisition.openArtifact(input),installationDirectory:defaultPluginInstallStoreDirectoryV1(options.agentDir),persistence:"persistent",supportedScopes:["global","project"],...options.limits===void 0?{}:{...options.limits}});return session={acquisition,installHost,installer:createPluginInstallerV1({host:installHost}),stateStore:createPluginStateStoreV1({filePath:join48(options.agentDir,DEFAULT_PLUGIN_STATE_FILE_V1)})},session},deps={listActive:async({signal})=>{let globalVersions=readActiveVersions(createPluginStateStoreV1({filePath:join48(options.agentDir,DEFAULT_PLUGIN_STATE_FILE_V1)}),"global",DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1,signal),projectVersions=readActiveVersions(createPluginStateStoreV1({filePath:join48(options.cwd,CONFIG_DIR_NAME,DEFAULT_PLUGIN_STATE_FILE_V1)}),"project",projectPluginScopeRefV1(options.cwd),signal),[globalResult,projectResult]=await Promise.all([globalVersions,projectVersions]);return new Map([...globalResult,...projectResult])},installFromNpm:async({npmName,range:range2,signal})=>{let lastError;for(let attempt2=1;attempt2<=3;attempt2++){if(signal?.aborted===!0)throw lastError??new Error("install aborted");try{return await installFromNpmOnce({npmName,range:range2,signal})}catch(error){if(lastError=error,attempt2===3)throw error;await new Promise((resolve22,reject2)=>{let timer=setTimeout(resolve22,400*2**(attempt2-1));signal?.addEventListener("abort",()=>{clearTimeout(timer),reject2(lastError)},{once:!0})})}}throw lastError},...options.signal===void 0?{}:{signal:options.signal}},installFromNpmOnce=async input=>{let{npmName,range:range2,signal}=input;{let active=await ensureSession(),ref=range2===void 0?npmName:`${npmName}@${range2}`,acquired=await active.acquisition.resolvePackage({ref,...signal===void 0?{}:{signal}}),released=!1,release=async()=>{released||(released=!0,await acquired.release())};try{let verified=active.installer.prepare({manifest:acquired.manifest,source:acquired.source,host:defaultPluginHostFactsV1()});if(verified.status!=="verified")throw new Error(t("installer prepare rejected {pluginId}: {reason}",{pluginId:acquired.manifest.id,reason:verified.reason}));let installed=await active.installer.install({record:verified.record,scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1,artifact:acquired.artifact,...signal===void 0?{}:{signal}});if(installed.status!=="succeeded")throw new Error(t("plugin install failed ({code}) for {pluginId}",{code:installed.error.code,pluginId:acquired.manifest.id}));let activated=await active.installer.activate({installation:installed.installation,record:verified.record,scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1,...signal===void 0?{}:{signal}});if(activated.status!=="succeeded"){let restoreFailure;try{let previous=await readPreviousActiveRecord(active.stateStore,acquired.manifest.id,signal);if(previous!==void 0){let rolledBack=await active.installer.rollback({failed:installed.installation,previous:{version:1,pluginId:previous.pluginId,pluginVersion:previous.pluginVersion,manifestDigest:previous.manifestDigest,scope:previous.state.scope,scopeRef:previous.state.scopeRef,installationRef:previous.installationRef,state:"active"},scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1,...signal===void 0?{}:{signal}});rolledBack.status!=="succeeded"&&(restoreFailure=rolledBack.error.code)}}catch(error){restoreFailure=error instanceof Error?error.message:String(error)}await active.installer.remove({installation:installed.installation,scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1}).catch(()=>{});let activationMessage=t("plugin activation failed ({code}) for {pluginId}",{code:activated.error.code,pluginId:acquired.manifest.id});throw new Error(restoreFailure===void 0?activationMessage:`${activationMessage}; previous version restore failed: ${restoreFailure}`)}let persisted=await active.stateStore.upsert({installation:activated.installation,scope:"global",enabled:!0,source:acquired.source,...signal===void 0?{}:{signal}});if(persisted.status!=="ok")throw await active.installer.remove({installation:activated.installation,scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1}).catch(()=>{}),new Error(t("plugin state persist failed ({status}) for {pluginId}",{status:persisted.status,pluginId:acquired.manifest.id}));return{pluginVersion:activated.installation.pluginVersion,source:acquired.source}}finally{await release()}}};try{return await runPluginBootstrapV1({manifest:options.manifest??BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1,deps,onPendingInstalls:options.onPendingInstalls??(count=>{console.error(t("First run: installing {count} factory plugins\u2026",{count}))}),onAction:options.onAction??(action=>{action.status==="installed"?console.error(t("{pluginId}: installed {version}",{pluginId:action.pluginId,version:action.installedVersion??""})):action.status==="failed"&&console.error(t("{pluginId}: install failed ({code}) \u2014 startup continues; the next startup retries automatically",{pluginId:action.pluginId,code:action.errorCode??"install_failed"}))})})}finally{let active=session;session=void 0,active!==void 0&&(await active.installHost.close().catch(()=>{}),await active.acquisition.close().catch(()=>{}))}}import{existsSync as existsSync25,mkdirSync as mkdirSync14,readdirSync as readdirSync13,readFileSync as readFileSync24,renameSync as renameSync2,rmSync as rmSync4,writeFileSync as writeFileSync16}from"fs";import{dirname as dirname26,join as join49}from"path";var MIGRATION_GUIDE_URL="https://github.com/agent-forge/agent-forge/blob/main/packages/agent-forge/CHANGELOG.md#extensions-migration",EXTENSIONS_DOC_URL="https://github.com/agent-forge/agent-forge/blob/main/packages/agent-forge/docs/extensions.md";function migrateAuthToAuthJson(){let agentDir=getAgentDir(),authPath=join49(agentDir,"auth.json"),oauthPath=join49(agentDir,"oauth.json"),settingsPath=join49(agentDir,"settings.json");if(existsSync25(authPath))return[];let migrated={},providers=[];if(existsSync25(oauthPath))try{let oauth=JSON.parse(stripBom(readFileSync24(oauthPath,"utf-8")));for(let[provider,cred]of Object.entries(oauth))migrated[provider]={type:"oauth",...cred},providers.push(provider);renameSync2(oauthPath,`${oauthPath}.migrated`)}catch{}if(existsSync25(settingsPath))try{let content=readFileSync24(settingsPath,"utf-8"),settings=JSON.parse(stripBom(content));if(settings.apiKeys&&typeof settings.apiKeys=="object"){for(let[provider,key]of Object.entries(settings.apiKeys))!migrated[provider]&&typeof key=="string"&&(migrated[provider]={type:"api_key",key},providers.push(provider));delete settings.apiKeys,writeFileSync16(settingsPath,JSON.stringify(settings,null,2))}}catch{}return Object.keys(migrated).length>0&&(mkdirSync14(dirname26(authPath),{recursive:!0}),writeFileSync16(authPath,JSON.stringify(migrated,null,2),{mode:384})),providers}function migrateSessionsFromAgentRoot(){let agentDir=getAgentDir(),files;try{files=readdirSync13(agentDir).filter(f=>f.endsWith(".jsonl")).map(f=>join49(agentDir,f))}catch{return}if(files.length!==0)for(let file of files)try{let firstLine=readFileSync24(file,"utf8").split(`
799
+ `),written+=1}catch{failed+=1,dirReady=!1}};(()=>{if(maxAgeDays<=0)return;let cutoff=now()-maxAgeDays*DAY_MS2,currentName=logFileName(now()),names;try{names=readdirSync11(options.dir)}catch(error){if(error.code==="ENOENT")return;write("warn","logger","log sweep failed: cannot read log directory",{cause:error});return}let removed=0,errors=0;for(let name of names){if(!name.endsWith(".log")||name===currentName)continue;let fullPath=join46(options.dir,name);try{let stats=statSync12(fullPath);if(!stats.isFile()||stats.mtimeMs>=cutoff)continue;unlinkSync4(fullPath),removed+=1}catch{errors+=1}}errors>0&&write("warn","logger","log sweep finished with failures",{fields:{removed,errors}})})();let exit=processHost.exit??NODE_PROCESS_CRASH_HOST.exit,writeStderr=processHost.writeStderr??NODE_PROCESS_CRASH_HOST.writeStderr,deferThrow=processHost.deferThrow??NODE_PROCESS_CRASH_HOST.deferThrow,loggedFatalValues=new WeakSet,isFatalValueLogged=value=>value!==null&&(typeof value=="object"||typeof value=="function")&&loggedFatalValues.has(value),markFatalValueLogged=value=>{value!==null&&(typeof value=="object"||typeof value=="function")&&loggedFatalValues.add(value)};return processHost.onUncaughtException&&processHost.onUncaughtException(error=>{isFatalValueLogged(error)||(markFatalValueLogged(error),write("error","process","uncaughtException",{cause:error})),writeStderr(fatalStderrText(error)),exit(1)}),processHost.onUnhandledRejection&&processHost.onUnhandledRejection(reason=>{markFatalValueLogged(reason),write("error","process","unhandledRejection",{cause:reason}),deferThrow(()=>{throw reason})}),{debug:(src,msg,context)=>write("debug",src,msg,context),info:(src,msg,context)=>write("info",src,msg,context),warn:(src,msg,context)=>write("warn",src,msg,context),error:(src,msg,context)=>write("error",src,msg,context),close:()=>(closed=!0,{written,failed})}}function collectSettingsDiagnostics(settingsManager){return settingsManager.drainErrors().map(({scope,path:path8,error})=>({type:"warning",message:path8?`Invalid settings file ${path8}: ${error.message}`:`Invalid ${scope} settings: ${error.message}`}))}function deduplicateDiagnostics(diagnostics){let seen=new Set;return diagnostics.filter(diagnostic5=>{let key=`${diagnostic5.type}\0${diagnostic5.message}`;return seen.has(key)?!1:(seen.add(key),!0)})}import{readdirSync as readdirSync12,statSync as statSync13,unlinkSync as unlinkSync5}from"node:fs";import{join as join47}from"node:path";var DAY_MS3=1440*60*1e3,TRACE_FILE_SUFFIX=".trace.jsonl",DEFAULT_TRACE_MAX_AGE_DAYS=14,DEFAULT_TRACE_MAX_FILES_PER_DIRECTORY=500;function sweepTraceFiles(sessionsRoot,options){let capActive=options.maxFilesPerDirectory!==void 0&&options.maxFilesPerDirectory>0;if(options.maxAgeDays<=0&&!capActive)return{scanned:0,deleted:0,failed:0};let now=options.now??Date.now,unlink5=options.unlink??(path8=>unlinkSync5(path8)),cutoff=now()-options.maxAgeDays*DAY_MS3,maxFilesPerDirectory=capActive?options.maxFilesPerDirectory:0,scanned=0,deleted=0,failed=0,readEntries=dir=>{try{return readdirSync12(dir,{withFileTypes:!0})}catch{return}},sweepFilesIn=(dir,entries)=>{let traceFiles=[];for(let entry of entries){if(!entry.name.endsWith(TRACE_FILE_SUFFIX))continue;let fullPath=join47(dir,entry.name);try{let stats=statSync13(fullPath);stats.isFile()&&traceFiles.push({path:fullPath,mtimeMs:stats.mtimeMs})}catch{}}scanned+=traceFiles.length;let expiredPaths=new Set(options.maxAgeDays>0?traceFiles.filter(file=>file.mtimeMs<cutoff).map(file=>file.path):[]),survivors=traceFiles.filter(file=>!expiredPaths.has(file.path)).sort((a,b)=>a.mtimeMs-b.mtimeMs),overCapCount=capActive?Math.max(0,survivors.length-maxFilesPerDirectory):0,removals=[...traceFiles.filter(file=>expiredPaths.has(file.path)),...survivors.slice(0,overCapCount)];for(let file of removals)try{unlink5(file.path),deleted+=1}catch{failed+=1}},rootEntries=readEntries(sessionsRoot);if(rootEntries===void 0)return{scanned:0,deleted:0,failed:0};sweepFilesIn(sessionsRoot,rootEntries);for(let entry of rootEntries){if(!entry.isDirectory())continue;let subdirectory=join47(sessionsRoot,entry.name),subEntries=readEntries(subdirectory);subEntries!==void 0&&sweepFilesIn(subdirectory,subEntries)}return{scanned,deleted,failed}}import{join as join48}from"node:path";var PLUGIN_BOOTSTRAP_VERSION_V1=1;function satisfiesRangeV1(version,range2){return selectNpmPackageVersionV1([version],range2)===version}function pluginBootstrapInstallCommandV1(entry){return`agent-forge plugin install ${entry.npmName}@${entry.range??"latest"}`}function errorMessage(error){return error instanceof Error?error.message:String(error)}function acquireErrorCode(error){return error instanceof PluginAcquisitionErrorV1?error.code:"install_failed"}function actionOf(entry,status,reason){return Object.freeze({pluginId:entry.pluginId,status,reason,npmName:entry.npmName,...entry.range===void 0?{}:{range:entry.range}})}async function runPluginBootstrapV1(input){let now=input.deps.now??Date.now,startedAt=now(),finish=(status2,actions2,diagnostics2)=>Object.freeze({version:PLUGIN_BOOTSTRAP_VERSION_V1,status:status2,actions:Object.freeze([...actions2]),diagnostics:Object.freeze([...diagnostics2]),durationMs:Math.max(0,now()-startedAt)});if(input.manifest.length===0)return finish("succeeded",[],[]);let signal=input.deps.signal,active;try{active=await input.deps.listActive({...signal===void 0?{}:{signal}})}catch(error){return finish("failed",[],[{code:"list_active_failed",message:`Active plugin state could not be read; bootstrap installed nothing: ${errorMessage(error)}`}])}let actions=[],diagnostics=[],record=action=>{actions.push(action),input.onAction?.(action)};if(input.onPendingInstalls!==void 0){let pending=input.manifest.filter(entry=>!active.has(entry.pluginId)).length;pending>0&&input.onPendingInstalls(pending)}for(let entry of input.manifest){if(signal?.aborted===!0){diagnostics.push({code:"cancelled",message:"Plugin bootstrap was cancelled before all factory entries were processed"});break}let activeVersion=active.get(entry.pluginId);if(activeVersion!==void 0&&satisfiesRangeV1(activeVersion,entry.range)){record(Object.freeze({...actionOf(entry,"skipped","satisfies_range"),activeVersion}));continue}try{let installed=await input.deps.installFromNpm({npmName:entry.npmName,...entry.range===void 0?{}:{range:entry.range},...signal===void 0?{}:{signal}});record(Object.freeze({...actionOf(entry,"installed",activeVersion===void 0?"installed":"range_aligned"),installedVersion:installed.pluginVersion,source:installed.source}))}catch(error){let errorCode2=acquireErrorCode(error),aligning=activeVersion!==void 0;record(Object.freeze({...actionOf(entry,"failed",aligning?"align_failed":"install_failed"),errorCode:errorCode2})),diagnostics.push({code:"install_failed",pluginId:entry.pluginId,message:aligning?`Bootstrap could not align ${entry.pluginId} (active ${activeVersion}) to the factory range ${entry.range??"latest"} from npm (${errorCode2}: ${errorMessage(error)}). Startup continues; the factory range stays unsatisfied, so the next startup retries automatically. Run \`${pluginBootstrapInstallCommandV1(entry)}\` to align it now.`:`Bootstrap could not install ${entry.pluginId} from npm (${errorCode2}: ${errorMessage(error)}). Startup continues without it; its capabilities stay unavailable until installed, and the next startup retries automatically. Run \`${pluginBootstrapInstallCommandV1(entry)}\` to install it manually.`})}}let status=actions.some(action=>action.status==="failed")?"failed":"succeeded";return finish(status,actions,diagnostics)}var AGENT_FORGE_PLUGIN_BOOTSTRAP_ENV_V1="AGENT_FORGE_PLUGIN_BOOTSTRAP",PLUGIN_BOOTSTRAP_DISABLED_VALUE_V1="off";function readActiveVersions(store,scope,scopeRef,signal){return(async()=>{let result=await store.read({...signal===void 0?{}:{signal}});if(result.status!=="ok"&&result.status!=="missing")throw new Error(t("plugin state read failed ({detail}) for the {scope} scope",{detail:result.diagnostics[0]?.code??result.status,scope}));let versions=new Map;for(let record of result.snapshot.records)record.state.scope!==scope||record.state.scopeRef!==scopeRef||record.state.lifecycle==="active"&&versions.set(record.pluginId,record.pluginVersion);return versions})()}async function readPreviousActiveRecord(store,pluginId,signal){let result=await store.read({...signal===void 0?{}:{signal}});if(result.status!=="ok"&&result.status!=="missing")throw new Error(t("plugin state read failed ({detail}) for the {scope} scope",{detail:result.diagnostics[0]?.code??result.status,scope:"global"}));return result.snapshot.records.find(record=>record.pluginId===pluginId&&record.state.scope==="global"&&record.state.scopeRef===DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1&&record.state.lifecycle==="active")}async function runNodePluginBootstrapV1(options){if(process.env[AGENT_FORGE_PLUGIN_BOOTSTRAP_ENV_V1]?.trim()===PLUGIN_BOOTSTRAP_DISABLED_VALUE_V1)return Object.freeze({version:1,status:"succeeded",actions:Object.freeze([]),diagnostics:Object.freeze([]),durationMs:0,skipped:"disabled"});if(isOfflineModeEnabled())return Object.freeze({version:1,status:"succeeded",actions:Object.freeze([]),diagnostics:Object.freeze([{code:"bootstrap_skipped_offline",message:t("Offline posture (AGENT_FORGE_OFFLINE) skips the startup plugin bootstrap; run `agent-forge plugin install <package>` explicitly to install plugins.")}]),durationMs:0,skipped:"offline"});if(options.deps!==void 0)return await runPluginBootstrapV1({manifest:options.manifest??BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1,deps:options.deps,...options.onPendingInstalls===void 0?{}:{onPendingInstalls:options.onPendingInstalls},...options.onAction===void 0?{}:{onAction:options.onAction}});let session,ensureSession=async()=>{if(session!==void 0)return session;let acquisition=createNodePluginAcquisitionHostV1({...options.npmRegistry===void 0?{}:{npmRegistry:options.npmRegistry},...options.npmToken===void 0?{}:{npmToken:options.npmToken},...options.fetch===void 0?{}:{fetch:options.fetch},...options.limits===void 0?{}:{limits:options.limits}}),installHost=await createNodePackageInstallHostV1({openArtifact:input=>acquisition.openArtifact(input),installationDirectory:defaultPluginInstallStoreDirectoryV1(options.agentDir),persistence:"persistent",supportedScopes:["global","project"],...options.limits===void 0?{}:{...options.limits}});return session={acquisition,installHost,installer:createPluginInstallerV1({host:installHost}),stateStore:createPluginStateStoreV1({filePath:join48(options.agentDir,DEFAULT_PLUGIN_STATE_FILE_V1)})},session},deps={listActive:async({signal})=>{let globalVersions=readActiveVersions(createPluginStateStoreV1({filePath:join48(options.agentDir,DEFAULT_PLUGIN_STATE_FILE_V1)}),"global",DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1,signal),projectVersions=readActiveVersions(createPluginStateStoreV1({filePath:join48(options.cwd,CONFIG_DIR_NAME,DEFAULT_PLUGIN_STATE_FILE_V1)}),"project",projectPluginScopeRefV1(options.cwd),signal),[globalResult,projectResult]=await Promise.all([globalVersions,projectVersions]);return new Map([...globalResult,...projectResult])},installFromNpm:async({npmName,range:range2,signal})=>{let lastError;for(let attempt2=1;attempt2<=3;attempt2++){if(signal?.aborted===!0)throw lastError??new Error("install aborted");try{return await installFromNpmOnce({npmName,range:range2,signal})}catch(error){if(lastError=error,attempt2===3)throw error;await new Promise((resolve22,reject2)=>{let timer=setTimeout(resolve22,400*2**(attempt2-1));signal?.addEventListener("abort",()=>{clearTimeout(timer),reject2(lastError)},{once:!0})})}}throw lastError},...options.signal===void 0?{}:{signal:options.signal}},installFromNpmOnce=async input=>{let{npmName,range:range2,signal}=input;{let active=await ensureSession(),ref=range2===void 0?npmName:`${npmName}@${range2}`,acquired=await active.acquisition.resolvePackage({ref,...signal===void 0?{}:{signal}}),released=!1,release=async()=>{released||(released=!0,await acquired.release())};try{let verified=active.installer.prepare({manifest:acquired.manifest,source:acquired.source,host:defaultPluginHostFactsV1()});if(verified.status!=="verified")throw new Error(t("installer prepare rejected {pluginId}: {reason}",{pluginId:acquired.manifest.id,reason:verified.reason}));let installed=await active.installer.install({record:verified.record,scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1,artifact:acquired.artifact,...signal===void 0?{}:{signal}});if(installed.status!=="succeeded")throw new Error(t("plugin install failed ({code}) for {pluginId}",{code:installed.error.code,pluginId:acquired.manifest.id}));let activated=await active.installer.activate({installation:installed.installation,record:verified.record,scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1,...signal===void 0?{}:{signal}});if(activated.status!=="succeeded"){let restoreFailure;try{let previous=await readPreviousActiveRecord(active.stateStore,acquired.manifest.id,signal);if(previous!==void 0){let rolledBack=await active.installer.rollback({failed:installed.installation,previous:{version:1,pluginId:previous.pluginId,pluginVersion:previous.pluginVersion,manifestDigest:previous.manifestDigest,scope:previous.state.scope,scopeRef:previous.state.scopeRef,installationRef:previous.installationRef,state:"active"},scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1,...signal===void 0?{}:{signal}});rolledBack.status!=="succeeded"&&(restoreFailure=rolledBack.error.code)}}catch(error){restoreFailure=error instanceof Error?error.message:String(error)}await active.installer.remove({installation:installed.installation,scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1}).catch(()=>{});let activationMessage=t("plugin activation failed ({code}) for {pluginId}",{code:activated.error.code,pluginId:acquired.manifest.id});throw new Error(restoreFailure===void 0?activationMessage:`${activationMessage}; previous version restore failed: ${restoreFailure}`)}let persisted=await active.stateStore.upsert({installation:activated.installation,scope:"global",enabled:!0,source:acquired.source,...signal===void 0?{}:{signal}});if(persisted.status!=="ok")throw await active.installer.remove({installation:activated.installation,scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1}).catch(()=>{}),new Error(t("plugin state persist failed ({status}) for {pluginId}",{status:persisted.status,pluginId:acquired.manifest.id}));let allRecords=await active.stateStore.read({...signal===void 0?{}:{signal}});if(allRecords.status==="ok")for(let record of allRecords.snapshot.records)record.pluginId===activated.installation.pluginId&&record.pluginVersion!==activated.installation.pluginVersion&&record.state.scope==="global"&&record.state.scopeRef===DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1&&record.state.lifecycle==="active"&&await active.stateStore.remove({pluginId:record.pluginId,pluginVersion:record.pluginVersion,scope:"global",scopeRef:DEFAULT_GLOBAL_PLUGIN_SCOPE_REF_V1,...signal===void 0?{}:{signal}}).catch(()=>{});return{pluginVersion:activated.installation.pluginVersion,source:acquired.source}}finally{await release()}}};try{return await runPluginBootstrapV1({manifest:options.manifest??BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1,deps,onPendingInstalls:options.onPendingInstalls??(count=>{console.error(t("First run: installing {count} factory plugins\u2026",{count}))}),onAction:options.onAction??(action=>{action.status==="installed"?console.error(t("{pluginId}: installed {version}",{pluginId:action.pluginId,version:action.installedVersion??""})):action.status==="failed"&&console.error(t("{pluginId}: install failed ({code}) \u2014 startup continues; the next startup retries automatically",{pluginId:action.pluginId,code:action.errorCode??"install_failed"}))})})}finally{let active=session;session=void 0,active!==void 0&&(await active.installHost.close().catch(()=>{}),await active.acquisition.close().catch(()=>{}))}}import{existsSync as existsSync25,mkdirSync as mkdirSync14,readdirSync as readdirSync13,readFileSync as readFileSync24,renameSync as renameSync2,rmSync as rmSync4,writeFileSync as writeFileSync16}from"fs";import{dirname as dirname26,join as join49}from"path";var MIGRATION_GUIDE_URL="https://github.com/agent-forge/agent-forge/blob/main/packages/agent-forge/CHANGELOG.md#extensions-migration",EXTENSIONS_DOC_URL="https://github.com/agent-forge/agent-forge/blob/main/packages/agent-forge/docs/extensions.md";function migrateAuthToAuthJson(){let agentDir=getAgentDir(),authPath=join49(agentDir,"auth.json"),oauthPath=join49(agentDir,"oauth.json"),settingsPath=join49(agentDir,"settings.json");if(existsSync25(authPath))return[];let migrated={},providers=[];if(existsSync25(oauthPath))try{let oauth=JSON.parse(stripBom(readFileSync24(oauthPath,"utf-8")));for(let[provider,cred]of Object.entries(oauth))migrated[provider]={type:"oauth",...cred},providers.push(provider);renameSync2(oauthPath,`${oauthPath}.migrated`)}catch{}if(existsSync25(settingsPath))try{let content=readFileSync24(settingsPath,"utf-8"),settings=JSON.parse(stripBom(content));if(settings.apiKeys&&typeof settings.apiKeys=="object"){for(let[provider,key]of Object.entries(settings.apiKeys))!migrated[provider]&&typeof key=="string"&&(migrated[provider]={type:"api_key",key},providers.push(provider));delete settings.apiKeys,writeFileSync16(settingsPath,JSON.stringify(settings,null,2))}}catch{}return Object.keys(migrated).length>0&&(mkdirSync14(dirname26(authPath),{recursive:!0}),writeFileSync16(authPath,JSON.stringify(migrated,null,2),{mode:384})),providers}function migrateSessionsFromAgentRoot(){let agentDir=getAgentDir(),files;try{files=readdirSync13(agentDir).filter(f=>f.endsWith(".jsonl")).map(f=>join49(agentDir,f))}catch{return}if(files.length!==0)for(let file of files)try{let firstLine=readFileSync24(file,"utf8").split(`
800
800
  `)[0];if(!firstLine?.trim())continue;let header=JSON.parse(firstLine);if(header.type!=="session"||!header.cwd)continue;let safePath=`--${header.cwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`,correctDir=join49(agentDir,"sessions",safePath);existsSync25(correctDir)||mkdirSync14(correctDir,{recursive:!0});let fileName=file.split("/").pop()||file.split("\\").pop(),newPath=join49(correctDir,fileName);if(existsSync25(newPath))continue;renameSync2(file,newPath)}catch{}}function migrateCommandsToPrompts(baseDir,label){let commandsDir=join49(baseDir,"commands"),promptsDir=join49(baseDir,"prompts");if(existsSync25(commandsDir)&&!existsSync25(promptsDir))try{return renameSync2(commandsDir,promptsDir),console.log(source_default.green(`Migrated ${label} commands/ \u2192 prompts/`)),!0}catch(err){console.log(source_default.yellow(`Warning: Could not migrate ${label} commands/ to prompts/: ${err instanceof Error?err.message:err}`))}return!1}function migrateKeybindingsConfigFile(){let configPath=join49(getAgentDir(),"keybindings.json");if(existsSync25(configPath))try{let parsed=JSON.parse(stripBom(readFileSync24(configPath,"utf-8")));if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return;let{config,migrated}=migrateKeybindingsConfig(parsed);if(!migrated)return;writeFileSync16(configPath,`${JSON.stringify(config,null,2)}
801
801
  `,"utf-8")}catch{}}function migrateToolsToBin(){let agentDir=getAgentDir(),toolsDir=join49(agentDir,"tools"),binDir=getBinDir();if(!existsSync25(toolsDir))return;let binaries=["fd","rg","fd.exe","rg.exe"],movedAny=!1;for(let bin of binaries){let oldPath=join49(toolsDir,bin),newPath=join49(binDir,bin);if(existsSync25(oldPath))if(existsSync25(binDir)||mkdirSync14(binDir,{recursive:!0}),existsSync25(newPath))try{rmSync4?.(oldPath,{force:!0})}catch{}else try{renameSync2(oldPath,newPath),movedAny=!0}catch{}}movedAny&&console.log(source_default.green("Migrated managed binaries tools/ \u2192 bin/"))}function checkDeprecatedExtensionDirs(baseDir,label){let hooksDir=join49(baseDir,"hooks"),toolsDir=join49(baseDir,"tools"),warnings=[];if(existsSync25(hooksDir)&&warnings.push(`${label} hooks/ directory found. Hooks have been renamed to extensions.`),existsSync25(toolsDir))try{readdirSync13(toolsDir).filter(e=>{let lower=e.toLowerCase();return lower!=="fd"&&lower!=="rg"&&lower!=="fd.exe"&&lower!=="rg.exe"&&!e.startsWith(".")}).length>0&&warnings.push(`${label} tools/ directory contains custom tools. Custom tools have been merged into extensions.`)}catch{}return warnings}function migrateExtensionSystem(cwd){let agentDir=getAgentDir(),projectDir=join49(cwd,CONFIG_DIR_NAME);return migrateCommandsToPrompts(agentDir,"Global"),migrateCommandsToPrompts(projectDir,"Project"),[...checkDeprecatedExtensionDirs(agentDir,"Global"),...checkDeprecatedExtensionDirs(projectDir,"Project")]}async function showDeprecationWarnings(warnings){if(warnings.length!==0){for(let warning of warnings)console.log(source_default.yellow(`Warning: ${warning}`));console.log(source_default.yellow(`
802
802
  Move your extensions to the extensions/ directory.`)),console.log(source_default.yellow(`Migration guide: ${MIGRATION_GUIDE_URL}`)),console.log(source_default.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`)),console.log()}}function runMigrations(cwd){let migratedAuthProviders=migrateAuthToAuthJson();migrateSessionsFromAgentRoot(),migrateToolsToBin(),migrateKeybindingsConfigFile();let deprecationWarnings=migrateExtensionSystem(cwd);return{migratedAuthProviders,deprecationWarnings}}import{existsSync as existsSync27,mkdirSync as mkdirSync16,mkdtempSync as mkdtempSync2,readdirSync as readdirSync14,readFileSync as readFileSync25,renameSync as renameSync4,rmSync as rmSync6,writeFileSync as writeFileSync17}from"node:fs";import{join as join52,resolve as resolve21}from"node:path";var import_proper_lockfile3=__toESM(require_proper_lockfile(),1);import{homedir as homedir4}from"node:os";import{basename as basename14,dirname as dirname27,join as join50,relative as relative9}from"node:path";var MAX_PROFILE_ID_CHARS=128,MAX_SELECTION_IDS=128,MAX_CATALOG_ENTRIES=256,MAX_DIAGNOSTIC_CODES2=16;function boundedCount(value,maximum){return value===void 0?{count:0,truncated:!1}:{count:Math.min(value.length,maximum),truncated:value.length>maximum}}function summarizePluginSelectionV1(selection){if(selection===void 0)return Object.freeze({present:!1,selectedCount:0,disabledCount:0,truncated:!1});let selected=boundedCount(selection.selectedPluginIds,MAX_SELECTION_IDS),disabled=boundedCount(selection.disabledPluginIds,MAX_SELECTION_IDS);return Object.freeze({present:!0,selectedCount:selected.count,disabledCount:disabled.count,truncated:selected.truncated||disabled.truncated})}function summarizePluginCatalogV1(catalog){if(catalog===void 0)return Object.freeze({present:!1,entryCount:0,readyCount:0,unavailableCount:0,truncated:!1});let entries=catalog.entries.slice(0,MAX_CATALOG_ENTRIES),readyCount=entries.filter(entry=>entry.resolution.status==="installed-ready").length;return Object.freeze({present:!0,entryCount:entries.length,readyCount,unavailableCount:entries.length-readyCount,truncated:catalog.truncated||catalog.entries.length>MAX_CATALOG_ENTRIES})}function validateProfileId(profileId){if(typeof profileId!="string"||profileId.trim().length===0||profileId.length>MAX_PROFILE_ID_CHARS||/[\u0000-\u001f]/u.test(profileId))throw new Error(t("invalid plugin selection profile ID"));return profileId}function emptySelectionSummary(){return Object.freeze({present:!1,selectedCount:0,disabledCount:0,truncated:!1})}function diagnosticCodes2(result){return result.status==="ok"||result.status==="missing"?Object.freeze([]):Object.freeze(result.diagnostics.slice(0,MAX_DIAGNOSTIC_CODES2).map(item=>item.code))}function selectionForProfile2(result,profileId){return result.snapshot.selections.find(selection=>selection.profileId===profileId)}var PluginSelectionEntryComponent=class{profileId;store;controller;onOpen;onClose;requestRender;selection;catalog;uiProfile;uiPluginIndex=0;_focused=!1;get focused(){return this._focused}set focused(value){this._focused=value}constructor(options){if(this.profileId=validateProfileId(options.profileId),options.selection!==void 0&&options.selection.profileId!==this.profileId)throw new Error(t("plugin selection profile does not match the entry profile"));this.store=options.store,this.controller=options.controller,this.onOpen=options.onOpen,this.onClose=options.onClose,this.requestRender=options.requestRender,this.selection=summarizePluginSelectionV1(options.selection),this.catalog=summarizePluginCatalogV1(options.catalog),this.uiProfile=options.snapshot?.profiles.find(profile=>profile.profileId===this.profileId)}hasHostEntry(){return this.store!==void 0||this.controller!==void 0||this.onOpen!==void 0}render(width){if(!this.hasHostEntry())return[truncateToWidth(theme.fg("dim",` ${t("Plugins: unsupported (host selection entry not injected)")}`),width,"...")];if(this._focused&&this.uiProfile!==void 0){let lines=[truncateToWidth(theme.bold(` ${t("Plugins \xB7 {profile}",{profile:this.uiProfile.profileId})}`),width,"...")];for(let[index,plugin]of this.uiProfile.plugins.entries()){let cursor=index===this.uiPluginIndex?">":" ",state=plugin.state==="selected"?"on":plugin.state==="disabled"?"off":"available",availability=plugin.availability==="ready"?"ready":"unavailable";lines.push(truncateToWidth(` ${cursor} [${state}] ${plugin.pluginId} (${availability})`,width,"..."))}return lines.push(truncateToWidth(theme.fg("dim",` ${t("Enter/Space toggle \xB7 Esc close")}`),width,"...")),lines}let selectionText=this.selection.present?t("selected {selected}, disabled {disabled}",{selected:this.selection.selectedCount,disabled:this.selection.disabledCount})+(this.selection.truncated?t(", bounded"):""):this.store===void 0?t("selection pending"):t("selection not loaded"),catalogText=this.catalog.present?t("catalog {count} ({ready} ready, {unavailable} unavailable)",{count:this.catalog.entryCount,ready:this.catalog.readyCount,unavailable:this.catalog.unavailableCount})+(this.catalog.truncated?t(", bounded"):""):t("catalog unavailable"),suffix=this.onOpen===void 0?t("host store"):t("open via host callback");return[truncateToWidth(theme.fg("muted",` ${t("Plugins: profile {profile} \xB7 {selection} \xB7 {catalog} \xB7 {suffix}",{profile:this.profileId,selection:selectionText,catalog:catalogText,suffix})}`),width,"...")]}setUiSnapshot(result){result.status==="ok"&&(this.uiProfile=result.snapshot.profiles.find(profile=>profile.profileId===this.profileId),this.uiProfile!==void 0&&(this.uiPluginIndex=Math.min(this.uiPluginIndex,Math.max(0,this.uiProfile.plugins.length-1))))}currentUiPlugin(){return this.uiProfile?.plugins[this.uiPluginIndex]}handleInput(data){if(!this._focused||this.uiProfile===void 0)return;let keybindings=getKeybindings();if(keybindings.matches(data,"tui.select.up")){this.uiPluginIndex=Math.max(0,this.uiPluginIndex-1),this.requestRender?.();return}if(keybindings.matches(data,"tui.select.down")){this.uiPluginIndex=Math.min(this.uiProfile.plugins.length-1,this.uiPluginIndex+1),this.requestRender?.();return}if(keybindings.matches(data,"tui.select.cancel")){this._focused=!1,this.onClose?.(),this.requestRender?.();return}if(!keybindings.matches(data,"tui.select.confirm")&&data!==" ")return;let plugin=this.currentUiPlugin();plugin===void 0||this.controller===void 0||plugin.state==="disabled"&&plugin.availability!=="ready"||this.controller.toggle({profileId:this.profileId,pluginId:plugin.pluginId}).then(result=>{this.setUiSnapshot(result),this.requestRender?.()}).catch(()=>this.requestRender?.())}async openPluginSelection(){let controllerResult;this.controller!==void 0&&(controllerResult=await this.controller.getSnapshot(),this.setUiSnapshot(controllerResult));let status=this.hasHostEntry()?"ready":"unsupported",selection=this.selection,codes=Object.freeze([]);if(controllerResult?.status==="error"&&(status=controllerResult.code==="store-cancelled"?"cancelled":"invalid"),this.store!==void 0){let result=await this.store.read();if(codes=diagnosticCodes2(result),result.status==="ok"||result.status==="missing"){let storedSelection=selectionForProfile2(result,this.profileId);selection=summarizePluginSelectionV1(storedSelection),status=result.status==="ok"?"ready":"missing"}else selection=emptySelectionSummary(),status=result.status;this.selection=selection}let context=Object.freeze({profileId:this.profileId,status,selection,catalog:this.catalog,diagnosticCodes:codes});return this.onOpen!==void 0&&await this.onOpen(context),context}invalidate(){}getSelectionSummary(){return this.selection}getCatalogSummary(){return this.catalog}};var RESOURCE_TYPES2=["skills","prompts","themes"],RESOURCE_TYPE_LABELS={skills:"Skills",prompts:"Prompts",themes:"Themes"};function formatBaseDir(baseDir){let homeDir=homedir4(),displayPath;return baseDir===homeDir?displayPath="~":baseDir.startsWith(homeDir)?displayPath=`~${baseDir.slice(homeDir.length).replace(/\\/g,"/")}`:displayPath=baseDir.replace(/\\/g,"/"),displayPath.endsWith("/")?displayPath:`${displayPath}/`}function getGroupLabel(metadata,agentDir){return metadata.origin==="package"?`${metadata.source} (${metadata.scope})`:metadata.source==="auto"?metadata.baseDir?metadata.scope==="user"?t("User ({dir})",{dir:formatBaseDir(metadata.baseDir)}):t("Project ({dir})",{dir:formatBaseDir(metadata.baseDir)}):metadata.scope==="user"?t("User ({dir})",{dir:formatBaseDir(agentDir)}):t("Project ({dir})",{dir:`${CONFIG_DIR_NAME}/`}):metadata.scope==="user"?t("User settings"):t("Project settings")}function buildGroups(resolved,agentDir){let groupMap=new Map,addToGroup=(resources,resourceType)=>{for(let res of resources){let{path:path8,enabled,metadata}=res,groupKey2=`${metadata.origin}:${metadata.scope}:${metadata.source}:${metadata.baseDir??""}`;groupMap.has(groupKey2)||groupMap.set(groupKey2,{key:groupKey2,label:getGroupLabel(metadata,agentDir),scope:metadata.scope,origin:metadata.origin,source:metadata.source,subgroups:[]});let group=groupMap.get(groupKey2),subgroupKey=`${groupKey2}:${resourceType}`,subgroup=group.subgroups.find(sg=>sg.type===resourceType);subgroup||(subgroup={type:resourceType,label:t(RESOURCE_TYPE_LABELS[resourceType]),items:[]},group.subgroups.push(subgroup));let fileName=basename14(path8),parentFolder=basename14(dirname27(path8)),displayName;resourceType==="skills"&&fileName==="SKILL.md"?displayName=parentFolder:displayName=fileName,subgroup.items.push({path:path8,enabled,metadata,resourceType,displayName,groupKey:groupKey2,subgroupKey})}};addToGroup(resolved.skills,"skills"),addToGroup(resolved.prompts,"prompts"),addToGroup(resolved.themes,"themes");let groups=Array.from(groupMap.values());groups.sort((a,b)=>a.origin!==b.origin?a.origin==="package"?-1:1:a.scope!==b.scope?a.scope==="user"?-1:1:a.source.localeCompare(b.source));let typeOrder={skills:0,prompts:1,themes:2};for(let group of groups){group.subgroups.sort((a,b)=>typeOrder[a.type]-typeOrder[b.type]);for(let subgroup of group.subgroups)subgroup.items.sort((a,b)=>a.displayName.localeCompare(b.displayName))}return groups}var ConfigSelectorHeader=class{writeScope;projectModeAvailable;constructor(writeScope,projectModeAvailable){this.writeScope=writeScope,this.projectModeAvailable=projectModeAvailable}setWriteScope(writeScope){this.writeScope=writeScope}invalidate(){}render(width){let title=theme.bold(this.writeScope==="project"?t("Project Local Resources"):t("Global Resources")),sep12=theme.fg("muted"," \xB7 "),switchHint=this.projectModeAvailable?keyHint("tui.input.tab",t("switch mode"))+sep12:"",actionHint=this.writeScope==="project"?rawKeyHint("space",t("cycle inherit/+/-")):rawKeyHint("space",t("toggle")),hint=switchHint+actionHint+sep12+rawKeyHint("esc",t("close")),spacing=Math.max(1,width-visibleWidth(title)-visibleWidth(hint)),scopeHint=this.writeScope==="project"?theme.fg("muted",t("{config}/settings.json \xB7 inherited global resources are dimmed",{config:CONFIG_DIR_NAME})):theme.fg("muted",`~/${CONFIG_DIR_NAME}/agent/settings.json`);return[truncateToWidth(`${title}${" ".repeat(spacing)}${hint}`,width,""),truncateToWidth(scopeHint,width,"")]}},ResourceList=class{groupsByScope;flatItems=[];filteredItems=[];selectedIndex=0;searchInput;maxVisible;settingsManager;cwd;agentDir;writeScope;inheritedEnabledByKey;pluginSelectionEntry;pluginManagerEntry;pluginManagerScope;onCancel;onExit;onToggle;onSwitchMode;_focused=!1;get focused(){return this._focused}set focused(value){this._focused=value,this.searchInput.focused=value}constructor(groupsByScope,settingsManager,cwd,agentDir,terminalHeight,writeScope="global",pluginSelectionEntry,pluginManagerEntry,pluginManagerScope="global"){this.groupsByScope=groupsByScope,this.settingsManager=settingsManager,this.cwd=cwd,this.agentDir=agentDir,this.writeScope=writeScope,this.pluginSelectionEntry=pluginSelectionEntry,this.pluginManagerEntry=pluginManagerEntry,this.pluginManagerScope=pluginManagerScope,this.inheritedEnabledByKey=this.buildInheritedEnabledMap(groupsByScope.global),this.searchInput=new Input;let chrome=8;this.maxVisible=Math.max(5,(terminalHeight??24)-chrome),this.buildFlatList(),this.filteredItems=[...this.flatItems]}setWriteScope(writeScope){this.writeScope=writeScope,this.buildFlatList(),this.filterItems(this.searchInput.getValue())}get groups(){return this.groupsByScope[this.writeScope]}buildInheritedEnabledMap(groups){let result=new Map;for(let group of groups)for(let subgroup of group.subgroups)for(let item of subgroup.items)result.set(this.getResourceItemKey(item),item.enabled);return result}buildFlatList(){this.flatItems=[];for(let group of this.groups){this.flatItems.push({type:"group",group});for(let subgroup of group.subgroups){this.flatItems.push({type:"subgroup",subgroup,group});for(let item of subgroup.items)this.flatItems.push({type:"item",item})}}this.pluginSelectionEntry!==void 0&&this.flatItems.push({type:"plugin",entry:this.pluginSelectionEntry}),this.pluginManagerEntry!==void 0&&this.writeScope===this.pluginManagerScope&&this.flatItems.push({type:"plugin-manager",entry:this.pluginManagerEntry}),this.selectedIndex=this.flatItems.findIndex(e=>e.type==="item"||e.type==="plugin"||e.type==="plugin-manager"),this.selectedIndex<0&&(this.selectedIndex=0)}findNextItem(fromIndex,direction){let idx=fromIndex+direction;for(;idx>=0&&idx<this.filteredItems.length;){if(this.filteredItems[idx].type==="item"||this.filteredItems[idx].type==="plugin"||this.filteredItems[idx].type==="plugin-manager")return idx;idx+=direction}return fromIndex}filterItems(query){if(!query.trim()){this.filteredItems=[...this.flatItems],this.selectFirstItem();return}let lowerQuery=query.toLowerCase(),matchingItems=new Set,matchingSubgroups=new Set,matchingGroups=new Set;for(let entry of this.flatItems)if(entry.type==="item"){let item=entry.item;(item.displayName.toLowerCase().includes(lowerQuery)||item.resourceType.toLowerCase().includes(lowerQuery)||item.path.toLowerCase().includes(lowerQuery))&&matchingItems.add(item)}for(let group of this.groups)for(let subgroup of group.subgroups)for(let item of subgroup.items)matchingItems.has(item)&&(matchingSubgroups.add(subgroup),matchingGroups.add(group));this.filteredItems=[];for(let entry of this.flatItems)entry.type==="group"&&matchingGroups.has(entry.group)?this.filteredItems.push(entry):entry.type==="subgroup"&&matchingSubgroups.has(entry.subgroup)?this.filteredItems.push(entry):entry.type==="item"&&matchingItems.has(entry.item)&&this.filteredItems.push(entry);this.selectFirstItem()}selectFirstItem(){let firstItemIndex=this.filteredItems.findIndex(e=>e.type==="item"||e.type==="plugin"||e.type==="plugin-manager");this.selectedIndex=firstItemIndex>=0?firstItemIndex:0}updateItem(item,enabled){item.enabled=enabled;for(let group of this.groups)for(let subgroup of group.subgroups){let found=subgroup.items.find(i=>i.path===item.path&&i.resourceType===item.resourceType);if(found){found.enabled=enabled;return}}}invalidate(){}render(width){let lines=[];if(lines.push(...this.searchInput.render(width)),lines.push(""),this.filteredItems.length===0)return lines.push(theme.fg("muted",` ${t("No resources found")}`)),lines;let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),endIndex=Math.min(startIndex+this.maxVisible,this.filteredItems.length);for(let i=startIndex;i<endIndex;i++){let entry=this.filteredItems[i],isSelected=i===this.selectedIndex;if(entry.type==="group"){let inherited=this.writeScope==="project"&&entry.group.scope==="user",label=theme.bold(`${entry.group.label}${inherited?` \xB7 ${t("inherited global")}`:""}`),groupLine=theme.fg(inherited?"dim":"accent",label);lines.push(truncateToWidth(` ${groupLine}`,width,""))}else if(entry.type==="subgroup"){let color=this.writeScope==="project"&&entry.group.scope==="user"?"dim":"muted",subgroupLine=theme.fg(color,entry.subgroup.label);lines.push(truncateToWidth(` ${subgroupLine}`,width,""))}else if(entry.type==="plugin"){let prefix=isSelected?"> ":" ";for(let line of entry.entry.render(width))lines.push(truncateToWidth(`${prefix}${line.trimStart()}`,width,"..."))}else if(entry.type==="plugin-manager"){let prefix=isSelected?"> ":" ";for(let line of entry.entry.render(width))lines.push(truncateToWidth(`${prefix}${line.trimStart()}`,width,"..."))}else{let item=entry.item,cursor=isSelected?"> ":" ",dimmed=this.isDimmedItem(item),nameText=isSelected&&!dimmed?theme.bold(item.displayName):item.displayName,name=dimmed?theme.fg("dim",nameText):nameText;lines.push(truncateToWidth(`${cursor} ${this.renderCheckbox(item)} ${name}${this.getItemSuffix(item)}`,width,"..."))}}if(startIndex>0||endIndex<this.filteredItems.length){let itemCount=this.filteredItems.filter(e=>e.type==="item"||e.type==="plugin"||e.type==="plugin-manager").length,currentItemIndex=this.filteredItems.slice(0,this.selectedIndex).filter(e=>e.type==="item"||e.type==="plugin"||e.type==="plugin-manager").length+1;lines.push(theme.fg("dim",` (${currentItemIndex}/${itemCount})`))}return lines}handleInput(data){let kb=getKeybindings();if(this.pluginSelectionEntry?.focused===!0){this.pluginSelectionEntry.handleInput(data);return}if(this.pluginManagerEntry?.focused===!0){this.pluginManagerEntry.handleInput(data);return}if(kb.matches(data,"tui.select.up")){this.selectedIndex=this.findNextItem(this.selectedIndex,-1);return}if(kb.matches(data,"tui.select.down")){this.selectedIndex=this.findNextItem(this.selectedIndex,1);return}if(kb.matches(data,"tui.select.pageUp")){let target=Math.max(0,this.selectedIndex-this.maxVisible);for(;target<this.filteredItems.length&&this.filteredItems[target].type!=="item"&&this.filteredItems[target].type!=="plugin"&&this.filteredItems[target].type!=="plugin-manager";)target++;target<this.filteredItems.length&&(this.selectedIndex=target);return}if(kb.matches(data,"tui.select.pageDown")){let target=Math.min(this.filteredItems.length-1,this.selectedIndex+this.maxVisible);for(;target>=0&&this.filteredItems[target].type!=="item"&&this.filteredItems[target].type!=="plugin"&&this.filteredItems[target].type!=="plugin-manager";)target--;target>=0&&(this.selectedIndex=target);return}if(kb.matches(data,"tui.select.cancel")){this.onCancel?.();return}if(kb.matches(data,"app.config.exit")){this.onExit?.();return}if(kb.matches(data,"tui.input.tab")){this.onSwitchMode?.();return}if(data===" "||kb.matches(data,"tui.select.confirm")){let entry=this.filteredItems[this.selectedIndex];if(entry?.type==="plugin"&&this.writeScope==="global"){entry.entry.focused=!0,entry.entry.openPluginSelection();return}if(entry?.type==="plugin-manager"&&this.writeScope===this.pluginManagerScope){entry.entry.focused=!0,entry.entry.openPluginManager();return}if(entry?.type==="item"&&(this.writeScope==="project"||this.getItemScope(entry.item)==="user")){let newEnabled=this.toggleResource(entry.item);newEnabled!==void 0&&(this.updateItem(entry.item,newEnabled),this.onToggle?.(entry.item,newEnabled))}return}this.searchInput.handleInput(data),this.filterItems(this.searchInput.getValue())}toggleResource(item){if(this.writeScope==="project"){let state=this.getNextOverrideState(item);return this.setProjectResourceOverride(item,state)?state==="inherit"?this.getInheritedEnabled(item):state==="load":void 0}let enabled=!item.enabled;return item.metadata.origin==="top-level"?this.toggleTopLevelResource(item,enabled):this.togglePackageResource(item,enabled),enabled}toggleTopLevelResource(item,enabled){let scope=item.metadata.scope,settings=scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings(),arrayKey=item.resourceType,current=settings[arrayKey]??[],pattern=this.getResourcePattern(item),disablePattern=`-${pattern}`,enablePattern=`+${pattern}`,updated=current.filter(p=>(p.startsWith("!")||p.startsWith("+")||p.startsWith("-")?p.slice(1):p)!==pattern);enabled?updated.push(enablePattern):updated.push(disablePattern),scope==="project"?arrayKey==="skills"?this.settingsManager.setProjectSkillPaths(updated):arrayKey==="prompts"?this.settingsManager.setProjectPromptTemplatePaths(updated):arrayKey==="themes"&&this.settingsManager.setProjectThemePaths(updated):arrayKey==="skills"?this.settingsManager.setSkillPaths(updated):arrayKey==="prompts"?this.settingsManager.setPromptTemplatePaths(updated):arrayKey==="themes"&&this.settingsManager.setThemePaths(updated)}togglePackageResource(item,enabled){let scope=item.metadata.scope,packages=[...(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[]],pkgIndex=packages.findIndex(pkg2=>(typeof pkg2=="string"?pkg2:pkg2.source)===item.metadata.source);if(pkgIndex===-1)return;let pkg=packages[pkgIndex];typeof pkg=="string"&&(pkg={source:pkg},packages[pkgIndex]=pkg);let arrayKey=item.resourceType,current=pkg[arrayKey]??[],pattern=this.getPackageResourcePattern(item),disablePattern=`-${pattern}`,enablePattern=`+${pattern}`,updated=current.filter(p=>(p.startsWith("!")||p.startsWith("+")||p.startsWith("-")?p.slice(1):p)!==pattern);enabled?updated.push(enablePattern):updated.push(disablePattern),pkg[arrayKey]=updated.length>0?updated:void 0,["skills","prompts","themes"].some(k=>pkg[k]!==void 0)||(packages[pkgIndex]=pkg.source),scope==="project"?this.settingsManager.setProjectPackages(packages):this.settingsManager.setPackages(packages)}renderCheckbox(item){if(this.writeScope==="project"){let state=this.getProjectOverrideState(item);return state==="load"?theme.fg("success","[+]"):state==="unload"?theme.fg("warning","[-]"):theme.fg("dim",item.enabled?"[x]":"[ ]")}return item.enabled?theme.fg("success","[x]"):theme.fg("dim","[ ]")}getItemSuffix(item){if(this.writeScope!=="project")return"";let state=this.getProjectOverrideState(item);return state==="load"?theme.fg("muted",` ${t("project load")}`):state==="unload"?theme.fg("muted",` ${t("project unload")}`):this.isInheritedGlobalItem(item)?theme.fg("dim",` ${t("inherited global")}`):""}isDimmedItem(item){return this.writeScope==="project"&&this.isInheritedGlobalItem(item)&&this.getProjectOverrideState(item)==="inherit"}setProjectResourceOverride(item,state){return item.metadata.origin==="top-level"?this.setProjectTopLevelOverride(item,state):this.setProjectPackageOverride(item,state)}setProjectTopLevelOverride(item,state){let current=this.settingsManager.getProjectSettings()[item.resourceType]??[],pattern=this.isInheritedGlobalItem(item)?item.path:this.getResourcePatternForScope(item,"project"),patterns=this.getTopLevelOverridePatterns(item,"project"),updated=current.filter(entry=>{let target=this.getPatternEntryTarget(entry);return(entry.startsWith("!")||entry.startsWith("+")||entry.startsWith("-"))&&patterns.has(target)?!1:!(state==="inherit"&&this.isInheritedGlobalItem(item)&&target===pattern)});return state!=="inherit"&&(this.isInheritedGlobalItem(item)&&!updated.includes(pattern)&&updated.push(pattern),updated.push(`${state==="load"?"+":"-"}${pattern}`)),this.setProjectTopLevelPaths(item.resourceType,updated),!0}setProjectTopLevelPaths(key,paths){key==="skills"?this.settingsManager.setProjectSkillPaths(paths):key==="prompts"?this.settingsManager.setProjectPromptTemplatePaths(paths):this.settingsManager.setProjectThemePaths(paths)}setProjectPackageOverride(item,state){let packages=[...this.settingsManager.getProjectSettings().packages??[]],pkgIndex=packages.findIndex(pkg2=>this.packageSourceStringMatches(item.metadata.source,this.getItemScope(item),typeof pkg2=="string"?pkg2:pkg2.source,"project"));if(pkgIndex===-1){if(state==="inherit")return!1;packages.push(this.createPackageOverrideSource(item)),pkgIndex=packages.length-1}let pkg=packages[pkgIndex];if(pkg===void 0)return!1;typeof pkg=="string"&&(pkg={source:pkg},packages[pkgIndex]=pkg);let pattern=this.getPackageResourcePattern(item),updated=(pkg[item.resourceType]??[]).filter(entry=>this.getPatternEntryTarget(entry)!==pattern);return state!=="inherit"&&updated.push(`${state==="load"?"+":"-"}${pattern}`),pkg[item.resourceType]=updated.length>0?updated:void 0,RESOURCE_TYPES2.some(key=>pkg[key]!==void 0)||(pkg.autoload===!1?packages.splice(pkgIndex,1):packages[pkgIndex]=pkg.source),this.settingsManager.setProjectPackages(packages),!0}getNextOverrideState(item){let state=this.getProjectOverrideState(item),inheritedEnabled=this.getInheritedEnabled(item);return state==="inherit"?inheritedEnabled?"unload":"load":state==="unload"?inheritedEnabled?"load":"inherit":inheritedEnabled?"inherit":"unload"}getProjectOverrideState(item){if(this.writeScope!=="project")return"inherit";if(item.metadata.origin==="top-level")return this.getOverrideStateFromEntries(this.settingsManager.getProjectSettings()[item.resourceType]??[],this.getTopLevelOverridePatterns(item,"project"),!1);let pkg=this.findMatchingPackageSource(item,"project");if(typeof pkg!="object")return"inherit";let entries=pkg[item.resourceType];return entries===void 0?"inherit":this.getOverrideStateFromEntries(entries,new Set([this.getPackageResourcePattern(item)]),pkg.autoload!==!1)}getOverrideStateFromEntries(entries,patterns,emptyArrayIsUnload){if(entries.length===0&&emptyArrayIsUnload)return"unload";let state="inherit";for(let entry of entries)patterns.has(this.getPatternEntryTarget(entry))&&(entry.startsWith("!")||entry.startsWith("-")?state="unload":state="load");return state}getInheritedEnabled(item){return this.inheritedEnabledByKey.get(this.getResourceItemKey(item))??(this.getItemScope(item)==="user"?item.enabled:!0)}isInheritedGlobalItem(item){return this.getItemScope(item)==="user"||this.inheritedEnabledByKey.has(this.getResourceItemKey(item))}getTopLevelOverridePatterns(item,scope){let baseDir=this.getTopLevelBaseDir(scope),patterns=new Set([this.getResourcePatternForScope(item,scope),item.path,relative9(baseDir,item.path)]);return item.metadata.baseDir&&patterns.add(relative9(item.metadata.baseDir,item.path)),patterns}getResourcePatternForScope(item,scope){let sourceScope=this.getItemScope(item);if(scope!==sourceScope)return item.path;let baseDir=item.metadata.baseDir??this.getTopLevelBaseDir(sourceScope);return relative9(baseDir,item.path)}createPackageOverrideSource(item){let source=item.metadata.source;if(!isLocalPath(source))return{source,autoload:!1};let sourcePath=resolvePath(source,this.getTopLevelBaseDir(this.getItemScope(item)),{trim:!0});return{source:relative9(this.getTopLevelBaseDir("project"),sourcePath)||".",autoload:!1}}packageSourceStringMatches(leftSource,leftScope,rightSource,rightScope){if(leftSource===rightSource)return!0;if(!isLocalPath(leftSource)||!isLocalPath(rightSource))return!1;let left=resolvePath(leftSource,this.getTopLevelBaseDir(leftScope),{trim:!0}),right=resolvePath(rightSource,this.getTopLevelBaseDir(rightScope),{trim:!0});return left===right}findMatchingPackageSource(item,targetScope){return((targetScope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[]).find(pkg=>this.packageSourceStringMatches(item.metadata.source,this.getItemScope(item),typeof pkg=="string"?pkg:pkg.source,targetScope))}getPatternEntryTarget(entry){return entry.startsWith("!")||entry.startsWith("+")||entry.startsWith("-")?entry.slice(1):entry}getResourceItemKey(item){return`${item.resourceType}:${canonicalizePath(item.path)}`}getItemScope(item){return item.metadata.scope==="project"?"project":"user"}getTopLevelBaseDir(scope){return scope==="project"?join50(this.cwd,CONFIG_DIR_NAME):this.agentDir}getResourcePattern(item){let scope=item.metadata.scope,baseDir=item.metadata.baseDir??this.getTopLevelBaseDir(scope);return relative9(baseDir,item.path)}getPackageResourcePattern(item){let baseDir=item.metadata.baseDir??dirname27(item.path);return relative9(baseDir,item.path)}},ConfigSelectorComponent=class extends Container{header;resourceList;pluginSelectionEntry;pluginManagerEntry;writeScope;_focused=!1;get focused(){return this._focused}set focused(value){this._focused=value,this.resourceList.focused=value}constructor(resolvedPaths,settingsManager,cwd,agentDir,onClose,onExit,requestRender,terminalHeight,writeScope="global",projectModeAvailable=!0,pluginSelection,pluginManager,pluginManagerScope="global"){super(),this.writeScope=writeScope;let groupsByScope={global:buildGroups(resolvedPaths.global,agentDir),project:buildGroups(resolvedPaths.project,agentDir)},pluginSelectionEntry=pluginSelection===void 0?void 0:new PluginSelectionEntryComponent({...pluginSelection,onClose:()=>{pluginSelection.onClose?.()},requestRender});this.pluginSelectionEntry=pluginSelectionEntry;let pluginManagerEntry=pluginManager===void 0?void 0:new PluginManagerEntryComponent({...pluginManager,onClose:()=>{pluginManager.onClose?.()},requestRender});this.pluginManagerEntry=pluginManagerEntry,this.addChild(new Spacer(1)),this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.header=new ConfigSelectorHeader(this.writeScope,projectModeAvailable),this.addChild(this.header),this.addChild(new Spacer(1)),this.resourceList=new ResourceList(groupsByScope,settingsManager,cwd,agentDir,terminalHeight===void 0?void 0:Math.max(5,terminalHeight-(pluginSelection===void 0?0:2)-(pluginManager===void 0?0:2)),this.writeScope,pluginSelectionEntry,pluginManagerEntry,pluginManagerScope),this.resourceList.onCancel=onClose,this.resourceList.onExit=onExit,this.resourceList.onToggle=()=>requestRender(),projectModeAvailable&&(this.resourceList.onSwitchMode=()=>{this.switchWriteScope(),requestRender()}),this.addChild(this.resourceList),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder)}switchWriteScope(){this.writeScope=this.writeScope==="global"?"project":"global",this.header.setWriteScope(this.writeScope),this.resourceList.setWriteScope(this.writeScope)}getResourceList(){return this.resourceList}getPluginSelectionEntry(){return this.pluginSelectionEntry}getPluginManagerEntry(){return this.pluginManagerEntry}async openPluginSelection(){return this.pluginSelectionEntry===void 0?void 0:await this.pluginSelectionEntry.openPluginSelection()}async openPluginManager(){return this.pluginManagerEntry===void 0?void 0:await this.pluginManagerEntry.openPluginManager()}};async function selectConfig(options){initTheme(options.settingsManager.getTheme(),!0);let pluginSnapshot=options.pluginSelectionController?await options.pluginSelectionController.getSnapshot():void 0,pluginManagerSnapshot=options.pluginManagerController?await options.pluginManagerController.getSnapshot():void 0;return new Promise(resolve22=>{let ui=new TuiMainScreen(new ProcessTerminal,void 0,options.agentDir),resolved=!1,selector=new ConfigSelectorComponent(options.resolvedPaths,options.settingsManager,options.cwd,options.agentDir,()=>{resolved||(resolved=!0,ui.stop(),stopThemeWatcher(),resolve22())},()=>{ui.stop(),stopThemeWatcher(),process.exit(0)},()=>ui.requestRender(),ui.terminal.rows,options.writeScope,options.projectModeAvailable,options.pluginSelectionController===void 0?void 0:{profileId:options.pluginSelectionProfileId??"coding-core",controller:options.pluginSelectionController,snapshot:pluginSnapshot?.status==="ok"?pluginSnapshot.snapshot:void 0,onOpen:()=>ui.requestRender(),requestRender:()=>ui.requestRender()},options.pluginManagerController===void 0?void 0:{controller:options.pluginManagerController,snapshot:pluginManagerSnapshot?.status==="ok"?pluginManagerSnapshot.snapshot:void 0,requestRender:()=>ui.requestRender()},options.pluginManagerScope);ui.addChild(selector),ui.setFocus(selector.getResourceList()),ui.start()})}import{randomUUID as randomUUID19}from"node:crypto";import{copyFileSync as copyFileSync2,existsSync as existsSync26,mkdirSync as mkdirSync15,renameSync as renameSync3,rmSync as rmSync5}from"node:fs";import{basename as basename15,dirname as dirname28,join as join51,relative as relative10,resolve as resolve20,toNamespacedPath}from"node:path";var QUARANTINE_DIR_NAME=".agent-forge-native-quarantine";function normalizePath3(path8){return toNamespacedPath(resolve20(path8))}function getQuarantineRoot(packageDir){let current=resolve20(packageDir);for(;;){if(basename15(current).toLowerCase()==="node_modules")return join51(current,QUARANTINE_DIR_NAME);let parent=dirname28(current);if(parent===current)return;current=parent}}function getLoadedSharedObjectsInPackageDir(packageDir){let sharedObjects=process.report.getReport().sharedObjects;if(!Array.isArray(sharedObjects))return[];let root=normalizePath3(packageDir).toLowerCase(),seen=new Set,loadedFiles=[];for(let value of sharedObjects){if(typeof value!="string")continue;let filePath=normalizePath3(value),comparisonPath=filePath.toLowerCase();getCwdRelativePath(comparisonPath,root)===void 0||seen.has(comparisonPath)||(seen.add(comparisonPath),loadedFiles.push(filePath))}return loadedFiles}function cleanupWindowsSelfUpdateQuarantine(packageDir){let quarantineRoot=getQuarantineRoot(packageDir);if(quarantineRoot)try{rmSync5(quarantineRoot,{recursive:!0,force:!0})}catch{}}function quarantineWindowsNativeDependencies(packageDir){let resolvedPackageDir=normalizePath3(packageDir),quarantineRoot=getQuarantineRoot(resolvedPackageDir);if(!quarantineRoot)return;let loadedFiles=getLoadedSharedObjectsInPackageDir(resolvedPackageDir);if(loadedFiles.length===0)return;let quarantineRunDir=join51(quarantineRoot,`${Date.now()}-${process.pid}-${randomUUID19()}`);for(let loadedFile of loadedFiles){if(!existsSync26(loadedFile))continue;let quarantinePath=join51(quarantineRunDir,relative10(resolvedPackageDir,loadedFile));mkdirSync15(dirname28(quarantinePath),{recursive:!0}),renameSync3(loadedFile,quarantinePath),copyFileSync2(quarantinePath,loadedFile)}}var MANAGED_INSTALL_MARKER="managed-install.json",MANAGED_RELEASE_VERSION_RE=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;function getActiveManagedInstallRoot(){let configuredRoot=process.env.AGENT_FORGE_MANAGED_INSTALL_ROOT?.trim();if(!configuredRoot)return;let managedRoot=resolve21(configuredRoot),releasesDir=canonicalizePath(join52(managedRoot,"releases"));if(getCwdRelativePath(canonicalizePath(getPackageDir()),releasesDir)===void 0)return;let markerPath=join52(managedRoot,MANAGED_INSTALL_MARKER);try{let marker=JSON.parse(readFileSync25(markerPath,"utf8"));if(marker.kind!=="agent-forge-managed-install"||marker.schemaVersion!==1||marker.layout!=="releases-v1")throw new Error}catch{throw new Error(t("Managed install marker is missing or invalid: {path}",{path:markerPath}))}return managedRoot}async function fetchInstallerArtifact(url,label){let response2=await fetch(url,{headers:{"User-Agent":getAgentForgeUserAgent(VERSION)}});if(!response2.ok)throw new Error(t("Could not download managed installer {label} from {url}: HTTP {status}",{label,url,status:response2.status}));return await response2.text()}async function runManagedNpmCi(stageDir){let args=["ci","--ignore-scripts","--min-release-age=0","--omit=dev","--include=optional","--no-fund","--no-audit","--loglevel=error","--progress=false"],code=await waitForChildProcess(spawnProcess("npm",args,{cwd:stageDir,stdio:"inherit"}));if(code!==0)throw new Error(t("npm {args} exited with code {code}",{args:args.join(" "),code:code??"unknown"}))}function verifyManagedRelease(releaseDir,expectedVersion){let binPath=join52(releaseDir,"node_modules",".bin",process.platform==="win32"?`${APP_NAME}.cmd`:APP_NAME),result=spawnProcessSync(binPath,["--version"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0){let reason=result.error?.message||result.stderr.trim()||`exit code ${result.status??"unknown"}`;throw new Error(t("Could not verify managed {app} {version}: {reason}",{app:APP_NAME,version:expectedVersion,reason}))}let installedVersion=result.stdout.trim();if(installedVersion!==expectedVersion)throw new Error(t("Managed {app} smoke test returned version {installed}; expected {expected}.",{app:APP_NAME,installed:installedVersion,expected:expectedVersion}))}async function activateStagedRelease(stageDir,releaseDir){for(let attempt2=0;;attempt2++)try{renameSync4(stageDir,releaseDir);return}catch(error){if(attempt2>=9||!existsSync27(stageDir))throw error;await sleep2(1e3)}}function activateManagedRelease(managedRoot,version){let currentPath=join52(managedRoot,"current-version"),temporaryPath=join52(managedRoot,`current-version.tmp.${process.pid}-${Date.now()}`);try{writeFileSync17(temporaryPath,`${version}
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
3
- import{configureHttpDispatcher,main}from"./chunks/chunk-POLDAUYA.js";import{APP_NAME}from"./chunks/chunk-ISLHFRER.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import"./chunks/chunk-WJSKB3FC.js";import"./chunks/chunk-BVVSHK6W.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-K3S6GTL7.js";import"./chunks/chunk-5LRQFZFE.js";import"./chunks/chunk-4L3WN2XY.js";process.title=APP_NAME;process.env.AGENT_FORGE="true";process.env.AI_AGENT="agent-forge";process.emitWarning=(()=>{});configureHttpDispatcher();main(process.argv.slice(2));
3
+ import{configureHttpDispatcher,main}from"./chunks/chunk-L2SXIPI5.js";import{APP_NAME}from"./chunks/chunk-ISLHFRER.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import"./chunks/chunk-WJSKB3FC.js";import"./chunks/chunk-BVVSHK6W.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-K3S6GTL7.js";import"./chunks/chunk-5LRQFZFE.js";import"./chunks/chunk-4L3WN2XY.js";process.title=APP_NAME;process.env.AGENT_FORGE="true";process.env.AI_AGENT="agent-forge";process.emitWarning=(()=>{});configureHttpDispatcher();main(process.argv.slice(2));