@eminent337/aery-core 0.67.119 → 0.67.121

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 (127) hide show
  1. package/README.md +14 -0
  2. package/dist/agent-loop.d.ts.map +1 -1
  3. package/dist/agent-loop.js +31 -1
  4. package/dist/agent-loop.js.map +1 -1
  5. package/dist/agent.d.ts +4 -3
  6. package/dist/agent.d.ts.map +1 -1
  7. package/dist/agent.js +7 -3
  8. package/dist/agent.js.map +1 -1
  9. package/dist/harness/agent-harness.d.ts +103 -0
  10. package/dist/harness/agent-harness.d.ts.map +1 -0
  11. package/dist/harness/agent-harness.js +788 -0
  12. package/dist/harness/agent-harness.js.map +1 -0
  13. package/dist/harness/compaction/branch-summarization.d.ts +88 -0
  14. package/dist/harness/compaction/branch-summarization.d.ts.map +1 -0
  15. package/dist/harness/compaction/branch-summarization.js +243 -0
  16. package/dist/harness/compaction/branch-summarization.js.map +1 -0
  17. package/dist/harness/compaction/compaction.d.ts +122 -0
  18. package/dist/harness/compaction/compaction.d.ts.map +1 -0
  19. package/dist/harness/compaction/compaction.js +631 -0
  20. package/dist/harness/compaction/compaction.js.map +1 -0
  21. package/dist/harness/compaction/utils.d.ts +38 -0
  22. package/dist/harness/compaction/utils.d.ts.map +1 -0
  23. package/dist/harness/compaction/utils.js +153 -0
  24. package/dist/harness/compaction/utils.js.map +1 -0
  25. package/dist/harness/env/nodejs.d.ts +50 -0
  26. package/dist/harness/env/nodejs.d.ts.map +1 -0
  27. package/dist/harness/env/nodejs.js +487 -0
  28. package/dist/harness/env/nodejs.js.map +1 -0
  29. package/dist/harness/execution-env.d.ts +4 -0
  30. package/dist/harness/execution-env.d.ts.map +1 -0
  31. package/dist/harness/execution-env.js +3 -0
  32. package/dist/harness/execution-env.js.map +1 -0
  33. package/dist/harness/factory.d.ts +6 -0
  34. package/dist/harness/factory.d.ts.map +1 -0
  35. package/dist/harness/factory.js +9 -0
  36. package/dist/harness/factory.js.map +1 -0
  37. package/dist/harness/messages.d.ts +51 -0
  38. package/dist/harness/messages.d.ts.map +1 -0
  39. package/dist/harness/messages.js +102 -0
  40. package/dist/harness/messages.js.map +1 -0
  41. package/dist/harness/prompt-templates.d.ts +47 -0
  42. package/dist/harness/prompt-templates.d.ts.map +1 -0
  43. package/dist/harness/prompt-templates.js +201 -0
  44. package/dist/harness/prompt-templates.js.map +1 -0
  45. package/dist/harness/session/jsonl-repo.d.ts +26 -0
  46. package/dist/harness/session/jsonl-repo.d.ts.map +1 -0
  47. package/dist/harness/session/jsonl-repo.js +97 -0
  48. package/dist/harness/session/jsonl-repo.js.map +1 -0
  49. package/dist/harness/session/jsonl-storage.d.ts +33 -0
  50. package/dist/harness/session/jsonl-storage.d.ts.map +1 -0
  51. package/dist/harness/session/jsonl-storage.js +159 -0
  52. package/dist/harness/session/jsonl-storage.js.map +1 -0
  53. package/dist/harness/session/memory-repo.d.ts +18 -0
  54. package/dist/harness/session/memory-repo.d.ts.map +1 -0
  55. package/dist/harness/session/memory-repo.js +42 -0
  56. package/dist/harness/session/memory-repo.js.map +1 -0
  57. package/dist/harness/session/memory-storage.d.ts +26 -0
  58. package/dist/harness/session/memory-storage.d.ts.map +1 -0
  59. package/dist/harness/session/memory-storage.js +89 -0
  60. package/dist/harness/session/memory-storage.js.map +1 -0
  61. package/dist/harness/session/repo/jsonl.d.ts +20 -0
  62. package/dist/harness/session/repo/jsonl.d.ts.map +1 -0
  63. package/dist/harness/session/repo/jsonl.js +92 -0
  64. package/dist/harness/session/repo/jsonl.js.map +1 -0
  65. package/dist/harness/session/repo/memory.d.ts +18 -0
  66. package/dist/harness/session/repo/memory.d.ts.map +1 -0
  67. package/dist/harness/session/repo/memory.js +42 -0
  68. package/dist/harness/session/repo/memory.js.map +1 -0
  69. package/dist/harness/session/repo/shared.d.ts +10 -0
  70. package/dist/harness/session/repo/shared.d.ts.map +1 -0
  71. package/dist/harness/session/repo/shared.js +31 -0
  72. package/dist/harness/session/repo/shared.js.map +1 -0
  73. package/dist/harness/session/repo-utils.d.ts +10 -0
  74. package/dist/harness/session/repo-utils.d.ts.map +1 -0
  75. package/dist/harness/session/repo-utils.js +31 -0
  76. package/dist/harness/session/repo-utils.js.map +1 -0
  77. package/dist/harness/session/session.d.ts +32 -0
  78. package/dist/harness/session/session.d.ts.map +1 -0
  79. package/dist/harness/session/session.js +196 -0
  80. package/dist/harness/session/session.js.map +1 -0
  81. package/dist/harness/session/storage/jsonl.d.ts +30 -0
  82. package/dist/harness/session/storage/jsonl.d.ts.map +1 -0
  83. package/dist/harness/session/storage/jsonl.js +170 -0
  84. package/dist/harness/session/storage/jsonl.js.map +1 -0
  85. package/dist/harness/session/storage/memory.d.ts +26 -0
  86. package/dist/harness/session/storage/memory.d.ts.map +1 -0
  87. package/dist/harness/session/storage/memory.js +90 -0
  88. package/dist/harness/session/storage/memory.js.map +1 -0
  89. package/dist/harness/session/uuid.d.ts +2 -0
  90. package/dist/harness/session/uuid.d.ts.map +1 -0
  91. package/dist/harness/session/uuid.js +50 -0
  92. package/dist/harness/session/uuid.js.map +1 -0
  93. package/dist/harness/skills.d.ts +43 -0
  94. package/dist/harness/skills.d.ts.map +1 -0
  95. package/dist/harness/skills.js +255 -0
  96. package/dist/harness/skills.js.map +1 -0
  97. package/dist/harness/system-prompt.d.ts +3 -0
  98. package/dist/harness/system-prompt.d.ts.map +1 -0
  99. package/dist/harness/system-prompt.js +30 -0
  100. package/dist/harness/system-prompt.js.map +1 -0
  101. package/dist/harness/types.d.ts +578 -0
  102. package/dist/harness/types.d.ts.map +1 -0
  103. package/dist/harness/types.js +56 -0
  104. package/dist/harness/types.js.map +1 -0
  105. package/dist/harness/utils/shell-output.d.ts +14 -0
  106. package/dist/harness/utils/shell-output.d.ts.map +1 -0
  107. package/dist/harness/utils/shell-output.js +125 -0
  108. package/dist/harness/utils/shell-output.js.map +1 -0
  109. package/dist/harness/utils/truncate.d.ts +70 -0
  110. package/dist/harness/utils/truncate.d.ts.map +1 -0
  111. package/dist/harness/utils/truncate.js +288 -0
  112. package/dist/harness/utils/truncate.js.map +1 -0
  113. package/dist/index.d.ts +15 -0
  114. package/dist/index.d.ts.map +1 -1
  115. package/dist/index.js +16 -0
  116. package/dist/index.js.map +1 -1
  117. package/dist/node.d.ts +3 -0
  118. package/dist/node.d.ts.map +1 -0
  119. package/dist/node.js +3 -0
  120. package/dist/node.js.map +1 -0
  121. package/dist/proxy.d.ts.map +1 -1
  122. package/dist/proxy.js +5 -2
  123. package/dist/proxy.js.map +1 -1
  124. package/dist/types.d.ts +50 -4
  125. package/dist/types.d.ts.map +1 -1
  126. package/dist/types.js.map +1 -1
  127. package/package.json +19 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,mBAAmB,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAC5G,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjG,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAEpD,uGAAuG;AACvG,MAAM,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,IAAI;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAEhG,0CAA0C;AAC1C,wBAAgB,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAExE;AAED,sCAAsC;AACtC,wBAAgB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAA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,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,YAAY,CAAC,EAAE,SAAS,CAAC;IACzB,YAAY,CAAC,EAAE,SAAS,CAAC;CACzB;AAED,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["import type { ImageContent, Model, SimpleStreamOptions, TextContent, Transport } from \"@eminent337/aery-ai\";\nimport type { AgentEvent, AgentMessage, AgentTool, QueueMode, ThinkingLevel } from \"../index.js\";\nimport type { Session } from \"./session/session.js\";\n\n/** Result of a fallible operation. Expected failures are returned as `ok: false` instead of thrown. */\nexport type Result<TValue, TError> = { ok: true; value: TValue } | { ok: false; error: TError };\n\n/** Create a successful {@link Result}. */\nexport function ok<TValue, TError>(value: TValue): Result<TValue, TError> {\n\treturn { ok: true, value };\n}\n\n/** Create a failed {@link Result}. */\nexport function err<TValue, TError>(error: TError): Result<TValue, TError> {\n\treturn { ok: false, error };\n}\n\n/** Return the success value or throw the failure error. Intended for tests and explicit adapter boundaries. */\nexport function getOrThrow<TValue, TError>(result: Result<TValue, TError>): TValue {\n\tif (!result.ok) throw result.error;\n\treturn result.value;\n}\n\n/** Return the success value or `undefined`. Only object values are allowed to avoid truthiness bugs with primitives. */\nexport function getOrUndefined<TValue extends object, TError>(result: Result<TValue, TError>): TValue | undefined {\n\treturn result.ok ? result.value : undefined;\n}\n\n/**\n * Skill loaded from a `SKILL.md` file or provided by an application.\n *\n * `name`, `description`, and `filePath` are inserted into the system prompt in an XML-formatted block as suggested by agentskills.io.\n * Use {@link formatSkillsForSystemPrompt} to generate the spec-compatible system prompt block.\n */\nexport interface Skill {\n\t/** Stable skill name used for lookup and model-visible listings. */\n\tname: string;\n\t/** Short model-visible description of when to use the skill. */\n\tdescription: string;\n\t/** Full skill instructions. */\n\tcontent: string;\n\t/** Absolute path to the skill file. Used for model-visible location and resolving relative references. */\n\tfilePath: string;\n\t/** Exclude this skill from model-visible skill lists while still allowing explicit application invocation. */\n\tdisableModelInvocation?: boolean;\n}\n\n/** Prompt template that can be formatted into a prompt for explicit invocation. */\nexport interface PromptTemplate {\n\t/** Stable template name used for lookup or application command routing. */\n\tname: string;\n\t/** Optional description for command lists or autocomplete. */\n\tdescription?: string;\n\t/** Template content. Argument placeholders are formatted by `formatPromptTemplateInvocation`. */\n\tcontent: string;\n}\n\n/** Resources made available to explicit invocation methods and system-prompt callbacks. */\nexport interface AgentHarnessResources<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\t/** Prompt templates available for explicit invocation. */\n\tpromptTemplates?: TPromptTemplate[];\n\t/** Skills available to the model and explicit skill invocation. */\n\tskills?: TSkill[];\n}\n\n/** Curated provider request options owned by the harness and snapshotted per turn. */\nexport interface AgentHarnessStreamOptions {\n\t/** Preferred transport forwarded to the stream function. */\n\ttransport?: Transport;\n\t/** Provider request timeout in milliseconds. */\n\ttimeoutMs?: number;\n\t/** Maximum provider retry attempts. */\n\tmaxRetries?: number;\n\t/** Optional cap for provider-requested retry delays. */\n\tmaxRetryDelayMs?: number;\n\t/** Additional request headers merged with auth and lifecycle headers. */\n\theaders?: Record<string, string>;\n\t/** Provider metadata forwarded with requests. */\n\tmetadata?: SimpleStreamOptions[\"metadata\"];\n\t/** Provider cache retention hint. */\n\tcacheRetention?: SimpleStreamOptions[\"cacheRetention\"];\n}\n\n/** Per-request stream option patch returned by provider hooks. */\nexport interface AgentHarnessStreamOptionsPatch\n\textends Omit<Partial<AgentHarnessStreamOptions>, \"headers\" | \"metadata\"> {\n\t/** Header patch. `undefined` values delete keys; explicit `headers: undefined` clears all headers. */\n\theaders?: Record<string, string | undefined>;\n\t/** Metadata patch. `undefined` values delete keys; explicit `metadata: undefined` clears all metadata. */\n\tmetadata?: Record<string, unknown | undefined>;\n}\n\n/** Kind of filesystem object as addressed by a {@link FileSystem}. Symlinks are not followed automatically. */\nexport type FileKind = \"file\" | \"directory\" | \"symlink\";\n\n/** Stable, backend-independent file error codes returned by {@link FileSystem} file operations. */\nexport type FileErrorCode =\n\t| \"aborted\"\n\t| \"not_found\"\n\t| \"permission_denied\"\n\t| \"not_directory\"\n\t| \"is_directory\"\n\t| \"invalid\"\n\t| \"not_supported\"\n\t| \"unknown\";\n\n/** Error returned by {@link FileSystem} file operations. */\nexport class FileError extends Error {\n\tconstructor(\n\t\t/** Backend-independent error code. */\n\t\tpublic code: FileErrorCode,\n\t\tmessage: string,\n\t\t/** Absolute addressed path associated with the failure, when available. */\n\t\tpublic path?: string,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"FileError\";\n\t}\n}\n\n/** Stable, backend-independent execution error codes returned by {@link ExecutionEnv.exec}. */\nexport type ExecutionErrorCode = \"aborted\" | \"timeout\" | \"shell_unavailable\" | \"spawn_error\" | \"unknown\";\n\n/** Error returned by {@link ExecutionEnv.exec}. */\nexport class ExecutionError extends Error {\n\tconstructor(\n\t\t/** Backend-independent error code. */\n\t\tpublic code: ExecutionErrorCode,\n\t\tmessage: string,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"ExecutionError\";\n\t}\n}\n\n/** Stable compaction error codes returned by compaction helpers. */\nexport type CompactionErrorCode = \"aborted\" | \"summarization_failed\" | \"invalid_session\" | \"unknown\";\n\n/** Error returned by compaction helpers. */\nexport class CompactionError extends Error {\n\tconstructor(\n\t\t/** Backend-independent error code. */\n\t\tpublic code: CompactionErrorCode,\n\t\tmessage: string,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"CompactionError\";\n\t}\n}\n\n/** Metadata for one filesystem object in a {@link FileSystem}. */\nexport interface FileInfo {\n\t/** Basename of {@link path}. */\n\tname: string;\n\t/** Absolute, syntactically normalized addressed path in the execution environment. Symlinks are not followed. */\n\tpath: string;\n\t/** Object kind. Symlink targets are not followed; use {@link FileSystem.canonicalPath} explicitly. */\n\tkind: FileKind;\n\t/** Size in bytes for the addressed filesystem object. */\n\tsize: number;\n\t/** Modification time as milliseconds since Unix epoch. */\n\tmtimeMs: number;\n}\n\n/** Options for {@link Shell.exec}. */\nexport interface ExecutionEnvExecOptions {\n\t/** Working directory for the command. Relative paths are resolved against {@link ExecutionEnv.cwd}. Defaults to {@link ExecutionEnv.cwd}. */\n\tcwd?: string;\n\t/** Additional environment variables for the command. Values override the environment defaults. Defaults to no overrides. */\n\tenv?: Record<string, string>;\n\t/** Timeout in seconds. Implementations should return a timeout error when the command exceeds this duration. Defaults to no timeout. */\n\ttimeout?: number;\n\t/** Abort signal used to terminate the command. Defaults to no abort signal. */\n\tabortSignal?: AbortSignal;\n\t/** Called with stdout chunks as they are produced. */\n\tonStdout?: (chunk: string) => void;\n\t/** Called with stderr chunks as they are produced. */\n\tonStderr?: (chunk: string) => void;\n}\n\n/**\n * Filesystem capability used by the harness.\n *\n * Paths passed to methods may be absolute or relative to {@link cwd}. Paths returned by file operations are addressed paths\n * in the filesystem namespace, but are not canonicalized through symlinks unless returned by {@link canonicalPath}.\n *\n * Operation methods must never throw or reject. All filesystem failures, including unexpected backend failures, must be\n * encoded in the returned {@link Result}. Implementations must preserve this invariant.\n */\nexport interface FileSystem {\n\t/** Current working directory for relative paths. */\n\tcwd: string;\n\n\t/** Return an absolute addressed path without requiring it to exist and without resolving symlinks. */\n\tabsolutePath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Join path segments in the filesystem namespace without requiring the result to exist. */\n\tjoinPath(parts: string[], abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Read a UTF-8 text file. */\n\treadTextFile(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Read a binary file. */\n\treadBinaryFile(path: string, abortSignal?: AbortSignal): Promise<Result<Uint8Array, FileError>>;\n\t/** Create or overwrite a file, creating parent directories when supported. */\n\twriteFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;\n\t/** Create or append to a file, creating parent directories when supported. */\n\tappendFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;\n\t/** Return metadata for the addressed path without following symlinks. */\n\tfileInfo(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo, FileError>>;\n\t/** List direct children of a directory without following symlinks. */\n\tlistDir(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo[], FileError>>;\n\t/** Return the canonical path for an existing path, resolving symlinks where supported. */\n\tcanonicalPath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Return false for missing paths. Other errors, such as permission failures, return a {@link FileError}. */\n\texists(path: string, abortSignal?: AbortSignal): Promise<Result<boolean, FileError>>;\n\t/** Create a directory. Defaults: `recursive: true`, no abort signal. */\n\tcreateDir(\n\t\tpath: string,\n\t\toptions?: { recursive?: boolean; abortSignal?: AbortSignal },\n\t): Promise<Result<void, FileError>>;\n\t/** Remove a file or directory. Defaults: `recursive: false`, `force: false`, no abort signal. */\n\tremove(\n\t\tpath: string,\n\t\toptions?: { recursive?: boolean; force?: boolean; abortSignal?: AbortSignal },\n\t): Promise<Result<void, FileError>>;\n\t/** Create a temporary directory and return its absolute path. Defaults: `prefix: \"tmp-\"`, no abort signal. */\n\tcreateTempDir(prefix?: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Create a temporary file and return its absolute path. Defaults: `prefix: \"\"`, `suffix: \"\"`, no abort signal. */\n\tcreateTempFile(options?: {\n\t\tprefix?: string;\n\t\tsuffix?: string;\n\t\tabortSignal?: AbortSignal;\n\t}): Promise<Result<string, FileError>>;\n\n\t/** Release filesystem resources. Must be best-effort and must not throw or reject. */\n\tcleanup(): Promise<void>;\n}\n\n/** Shell execution capability used by the harness. */\nexport interface Shell {\n\t/** Execute a shell command in {@link FileSystem.cwd} unless `options.cwd` is provided. */\n\texec(\n\t\tcommand: string,\n\t\toptions?: ExecutionEnvExecOptions,\n\t): Promise<Result<{ stdout: string; stderr: string; exitCode: number }, ExecutionError>>;\n\t/** Release shell resources. Must be best-effort and must not throw or reject. */\n\tcleanup(): Promise<void>;\n}\n\n/** Filesystem and process execution environment used by the harness. */\nexport interface ExecutionEnv extends FileSystem, Shell {}\n\nexport interface SessionTreeEntryBase {\n\ttype: string;\n\tid: string;\n\tparentId: string | null;\n\ttimestamp: string;\n}\n\nexport interface MessageEntry extends SessionTreeEntryBase {\n\ttype: \"message\";\n\tmessage: AgentMessage;\n}\n\nexport interface ThinkingLevelChangeEntry extends SessionTreeEntryBase {\n\ttype: \"thinking_level_change\";\n\tthinkingLevel: string;\n}\n\nexport interface ModelChangeEntry extends SessionTreeEntryBase {\n\ttype: \"model_change\";\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport interface CompactionEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"compaction\";\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tdetails?: T;\n\tfromHook?: boolean;\n}\n\nexport interface BranchSummaryEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"branch_summary\";\n\tfromId: string;\n\tsummary: string;\n\tdetails?: T;\n\tfromHook?: boolean;\n}\n\nexport interface CustomEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"custom\";\n\tcustomType: string;\n\tdata?: T;\n}\n\nexport interface CustomMessageEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"custom_message\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdetails?: T;\n\tdisplay: boolean;\n}\n\nexport interface LabelEntry extends SessionTreeEntryBase {\n\ttype: \"label\";\n\ttargetId: string;\n\tlabel: string | undefined;\n}\n\nexport interface SessionInfoEntry extends SessionTreeEntryBase {\n\ttype: \"session_info\"; // legacy name, kept for backwards compatibility\n\tname?: string;\n}\n\nexport type SessionTreeEntry =\n\t| MessageEntry\n\t| ThinkingLevelChangeEntry\n\t| ModelChangeEntry\n\t| CompactionEntry\n\t| BranchSummaryEntry\n\t| CustomEntry\n\t| CustomMessageEntry\n\t| LabelEntry\n\t| SessionInfoEntry;\n\nexport interface SessionContext {\n\tmessages: AgentMessage[];\n\tthinkingLevel: string;\n\tmodel: { provider: string; modelId: string } | null;\n}\n\nexport interface SessionMetadata {\n\tid: string;\n\tcreatedAt: string;\n}\n\nexport interface JsonlSessionMetadata extends SessionMetadata {\n\tcwd: string;\n\tpath: string;\n\tparentSessionPath?: string;\n}\n\nexport interface SessionStorage<TMetadata extends SessionMetadata = SessionMetadata> {\n\tgetMetadata(): Promise<TMetadata>;\n\tgetLeafId(): Promise<string | null>;\n\tsetLeafId(leafId: string | null): Promise<void>;\n\tcreateEntryId(): Promise<string>;\n\tappendEntry(entry: SessionTreeEntry): Promise<void>;\n\tgetEntry(id: string): Promise<SessionTreeEntry | undefined>;\n\tfindEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>>;\n\tgetLabel(id: string): Promise<string | undefined>;\n\tgetPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]>;\n\tgetEntries(): Promise<SessionTreeEntry[]>;\n}\n\nexport type { Session } from \"./session/session.js\";\n\nexport interface SessionCreateOptions {\n\tid?: string;\n}\n\nexport interface SessionForkOptions {\n\tentryId?: string;\n\tposition?: \"before\" | \"at\";\n\tid?: string;\n}\n\nexport interface SessionRepo<\n\tTMetadata extends SessionMetadata = SessionMetadata,\n\tTCreateOptions extends SessionCreateOptions = SessionCreateOptions,\n\tTListOptions = void,\n> {\n\tcreate(options: TCreateOptions): Promise<Session<TMetadata>>;\n\topen(metadata: TMetadata): Promise<Session<TMetadata>>;\n\tlist(options?: TListOptions): Promise<TMetadata[]>;\n\tdelete(metadata: TMetadata): Promise<void>;\n\tfork(source: TMetadata, options: SessionForkOptions & TCreateOptions): Promise<Session<TMetadata>>;\n}\n\nexport interface JsonlSessionCreateOptions extends SessionCreateOptions {\n\tcwd: string;\n\tparentSessionPath?: string;\n}\n\nexport interface JsonlSessionListOptions {\n\tcwd?: string;\n}\n\nexport interface JsonlSessionRepoApi\n\textends SessionRepo<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions> {}\n\nexport type AgentHarnessPhase = \"idle\" | \"turn\" | \"compaction\" | \"branch_summary\" | \"retry\";\n\nexport type PendingSessionWrite = SessionTreeEntry extends infer TEntry\n\t? TEntry extends SessionTreeEntry\n\t\t? Omit<TEntry, \"id\" | \"parentId\" | \"timestamp\">\n\t\t: never\n\t: never;\n\nexport interface QueueUpdateEvent {\n\ttype: \"queue_update\";\n\tsteer: AgentMessage[];\n\tfollowUp: AgentMessage[];\n\tnextTurn: AgentMessage[];\n}\n\nexport interface SavePointEvent {\n\ttype: \"save_point\";\n\thadPendingMutations: boolean;\n}\n\nexport interface AbortEvent {\n\ttype: \"abort\";\n\tclearedSteer: AgentMessage[];\n\tclearedFollowUp: AgentMessage[];\n}\n\nexport interface SettledEvent {\n\ttype: \"settled\";\n\tnextTurnCount: number;\n}\n\nexport interface BeforeAgentStartEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\ttype: \"before_agent_start\";\n\tprompt: string;\n\timages?: ImageContent[];\n\tsystemPrompt: string;\n\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n}\n\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tmodel: Model<any>;\n\tsessionId: string;\n\tstreamOptions: AgentHarnessStreamOptions;\n}\n\nexport interface BeforeProviderPayloadEvent {\n\ttype: \"before_provider_payload\";\n\tmodel: Model<any>;\n\tpayload: unknown;\n}\n\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\nexport interface ToolCallEvent {\n\ttype: \"tool_call\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n}\n\nexport interface ToolResultEvent {\n\ttype: \"tool_result\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n\tcontent: Array<TextContent | ImageContent>;\n\tdetails: unknown;\n\tisError: boolean;\n}\n\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\tpreparation: CompactionPreparation;\n\tbranchEntries: SessionTreeEntry[];\n\tcustomInstructions?: string;\n\tsignal: AbortSignal;\n}\n\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromHook: boolean;\n}\n\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\tpreparation: TreePreparation;\n\tsignal: AbortSignal;\n}\n\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\tnewLeafId: string | null;\n\toldLeafId: string | null;\n\tsummaryEntry?: BranchSummaryEntry;\n\tfromHook?: boolean;\n}\n\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<any>;\n\tpreviousModel: Model<any> | undefined;\n\tsource: \"set\" | \"restore\";\n}\n\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\nexport interface ResourcesUpdateEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\ttype: \"resources_update\";\n\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tpreviousResources: AgentHarnessResources<TSkill, TPromptTemplate>;\n}\n\nexport type AgentHarnessOwnEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> =\n\t| QueueUpdateEvent\n\t| SavePointEvent\n\t| AbortEvent\n\t| SettledEvent\n\t| BeforeAgentStartEvent<TSkill, TPromptTemplate>\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderPayloadEvent\n\t| AfterProviderResponseEvent\n\t| ToolCallEvent\n\t| ToolResultEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent\n\t| ModelSelectEvent\n\t| ThinkingLevelSelectEvent\n\t| ResourcesUpdateEvent<TSkill, TPromptTemplate>;\n\nexport type AgentHarnessEvent<TSkill extends Skill = Skill, TPromptTemplate extends PromptTemplate = PromptTemplate> =\n\t| AgentEvent\n\t| AgentHarnessOwnEvent<TSkill, TPromptTemplate>;\n\nexport interface BeforeAgentStartResult {\n\tmessages?: AgentMessage[];\n\tsystemPrompt?: string;\n}\n\nexport interface ContextResult {\n\tmessages: AgentMessage[];\n}\n\nexport interface BeforeProviderRequestResult {\n\tstreamOptions?: AgentHarnessStreamOptionsPatch;\n}\n\nexport interface BeforeProviderPayloadResult {\n\tpayload: unknown;\n}\n\nexport interface ToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\nexport interface ToolResultPatch {\n\tcontent?: Array<TextContent | ImageContent>;\n\tdetails?: unknown;\n\tisError?: boolean;\n\tterminate?: boolean;\n}\n\nexport interface SessionBeforeCompactResult {\n\tcancel?: boolean;\n\tcompaction?: CompactResult;\n}\n\nexport interface SessionBeforeTreeResult {\n\tcancel?: boolean;\n\tsummary?: { summary: string; details?: unknown };\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\tlabel?: string;\n}\n\nexport type AgentHarnessEventResultMap = {\n\tbefore_agent_start: BeforeAgentStartResult | undefined;\n\tcontext: ContextResult | undefined;\n\tbefore_provider_request: BeforeProviderRequestResult | undefined;\n\tbefore_provider_payload: BeforeProviderPayloadResult | undefined;\n\tafter_provider_response: undefined;\n\ttool_call: ToolCallResult | undefined;\n\ttool_result: ToolResultPatch | undefined;\n\tsession_before_compact: SessionBeforeCompactResult | undefined;\n\tsession_compact: undefined;\n\tsession_before_tree: SessionBeforeTreeResult | undefined;\n\tsession_tree: undefined;\n\tmodel_select: undefined;\n\tthinking_level_select: undefined;\n\tresources_update: undefined;\n\tqueue_update: undefined;\n\tsave_point: undefined;\n\tabort: undefined;\n\tsettled: undefined;\n};\n\nexport interface AgentHarnessPromptOptions {\n\timages?: ImageContent[];\n}\n\nexport interface AbortResult {\n\tclearedSteer: AgentMessage[];\n\tclearedFollowUp: AgentMessage[];\n}\n\nexport interface CompactResult {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tdetails?: unknown;\n}\n\nexport interface NavigateTreeResult {\n\tcancelled: boolean;\n\teditorText?: string;\n\tsummaryEntry?: BranchSummaryEntry;\n}\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\tkeepRecentTokens: number;\n}\n\nexport interface CompactionPreparation {\n\tfirstKeptEntryId: string;\n\tmessagesToSummarize: AgentMessage[];\n\tturnPrefixMessages: AgentMessage[];\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\tpreviousSummary?: string;\n\tfileOps: FileOperations;\n\tsettings: CompactionSettings;\n}\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport interface TreePreparation {\n\ttargetId: string;\n\toldLeafId: string | null;\n\tcommonAncestorId: string | null;\n\tentriesToSummarize: SessionTreeEntry[];\n\tuserWantsSummary: boolean;\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\tlabel?: string;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\tmodel: Model<any>;\n\tapiKey: string;\n\theaders?: Record<string, string>;\n\tsignal: AbortSignal;\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\treserveTokens?: number;\n}\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\taborted?: boolean;\n\terror?: string;\n}\n\nexport interface AgentHarnessOptions<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n\tTTool extends AgentTool = AgentTool,\n> {\n\tenv: ExecutionEnv;\n\tsession: Session;\n\ttools?: TTool[];\n\t/**\n\t * Concrete resources available to explicit invocation methods and system-prompt callbacks.\n\t * Applications own loading/reloading resources and should call `setResources()` with new values.\n\t */\n\tresources?: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tsystemPrompt?:\n\t\t| string\n\t\t| ((context: {\n\t\t\t\tenv: ExecutionEnv;\n\t\t\t\tsession: Session;\n\t\t\t\tmodel: Model<any>;\n\t\t\t\tthinkingLevel: ThinkingLevel;\n\t\t\t\tactiveTools: TTool[];\n\t\t\t\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\t\t }) => string | Promise<string>);\n\tgetApiKeyAndHeaders?: (\n\t\tmodel: Model<any>,\n\t) => Promise<{ apiKey: string; headers?: Record<string, string> } | undefined>;\n\t/** Curated stream/provider request options. Snapshotted at turn start. */\n\tstreamOptions?: AgentHarnessStreamOptions;\n\tmodel: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tactiveToolNames?: string[];\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n}\n\nexport type { AgentHarness } from \"./agent-harness.js\";\n"]}
@@ -0,0 +1,56 @@
1
+ /** Create a successful {@link Result}. */
2
+ export function ok(value) {
3
+ return { ok: true, value };
4
+ }
5
+ /** Create a failed {@link Result}. */
6
+ export function err(error) {
7
+ return { ok: false, error };
8
+ }
9
+ /** Return the success value or throw the failure error. Intended for tests and explicit adapter boundaries. */
10
+ export function getOrThrow(result) {
11
+ if (!result.ok)
12
+ throw result.error;
13
+ return result.value;
14
+ }
15
+ /** Return the success value or `undefined`. Only object values are allowed to avoid truthiness bugs with primitives. */
16
+ export function getOrUndefined(result) {
17
+ return result.ok ? result.value : undefined;
18
+ }
19
+ /** Error returned by {@link FileSystem} file operations. */
20
+ export class FileError extends Error {
21
+ code;
22
+ path;
23
+ constructor(
24
+ /** Backend-independent error code. */
25
+ code, message,
26
+ /** Absolute addressed path associated with the failure, when available. */
27
+ path, cause) {
28
+ super(message, cause === undefined ? undefined : { cause });
29
+ this.code = code;
30
+ this.path = path;
31
+ this.name = "FileError";
32
+ }
33
+ }
34
+ /** Error returned by {@link ExecutionEnv.exec}. */
35
+ export class ExecutionError extends Error {
36
+ code;
37
+ constructor(
38
+ /** Backend-independent error code. */
39
+ code, message, cause) {
40
+ super(message, cause === undefined ? undefined : { cause });
41
+ this.code = code;
42
+ this.name = "ExecutionError";
43
+ }
44
+ }
45
+ /** Error returned by compaction helpers. */
46
+ export class CompactionError extends Error {
47
+ code;
48
+ constructor(
49
+ /** Backend-independent error code. */
50
+ code, message, cause) {
51
+ super(message, cause === undefined ? undefined : { cause });
52
+ this.code = code;
53
+ this.name = "CompactionError";
54
+ }
55
+ }
56
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"AAOA,0CAA0C;AAC1C,MAAM,UAAU,EAAE,CAAiB,KAAa,EAA0B;IACzE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;AAAA,CAC3B;AAED,sCAAsC;AACtC,MAAM,UAAU,GAAG,CAAiB,KAAa,EAA0B;IAC1E,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAAA,CAC5B;AAED,+GAA+G;AAC/G,MAAM,UAAU,UAAU,CAAiB,MAA8B,EAAU;IAClF,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,MAAM,CAAC,KAAK,CAAC;IACnC,OAAO,MAAM,CAAC,KAAK,CAAC;AAAA,CACpB;AAED,wHAAwH;AACxH,MAAM,UAAU,cAAc,CAAgC,MAA8B,EAAsB;IACjH,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAC5C;AAmFD,4DAA4D;AAC5D,MAAM,OAAO,SAAU,SAAQ,KAAK;IAG3B,IAAI;IAGJ,IAAI;IALZ;IACC,sCAAsC;IAC/B,IAAmB,EAC1B,OAAe;IACf,2EAA2E;IACpE,IAAa,EACpB,KAAe,EACd;QACD,KAAK,CAAC,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;oBANrD,IAAI;oBAGJ,IAAI;QAIX,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;IAAA,CACxB;CACD;AAKD,mDAAmD;AACnD,MAAM,OAAO,cAAe,SAAQ,KAAK;IAGhC,IAAI;IAFZ;IACC,sCAAsC;IAC/B,IAAwB,EAC/B,OAAe,EACf,KAAe,EACd;QACD,KAAK,CAAC,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;oBAJrD,IAAI;QAKX,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAAA,CAC7B;CACD;AAKD,4CAA4C;AAC5C,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAGjC,IAAI;IAFZ;IACC,sCAAsC;IAC/B,IAAyB,EAChC,OAAe,EACf,KAAe,EACd;QACD,KAAK,CAAC,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;oBAJrD,IAAI;QAKX,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAAA,CAC9B;CACD","sourcesContent":["import type { ImageContent, Model, SimpleStreamOptions, TextContent, Transport } from \"@eminent337/aery-ai\";\nimport type { AgentEvent, AgentMessage, AgentTool, QueueMode, ThinkingLevel } from \"../index.js\";\nimport type { Session } from \"./session/session.js\";\n\n/** Result of a fallible operation. Expected failures are returned as `ok: false` instead of thrown. */\nexport type Result<TValue, TError> = { ok: true; value: TValue } | { ok: false; error: TError };\n\n/** Create a successful {@link Result}. */\nexport function ok<TValue, TError>(value: TValue): Result<TValue, TError> {\n\treturn { ok: true, value };\n}\n\n/** Create a failed {@link Result}. */\nexport function err<TValue, TError>(error: TError): Result<TValue, TError> {\n\treturn { ok: false, error };\n}\n\n/** Return the success value or throw the failure error. Intended for tests and explicit adapter boundaries. */\nexport function getOrThrow<TValue, TError>(result: Result<TValue, TError>): TValue {\n\tif (!result.ok) throw result.error;\n\treturn result.value;\n}\n\n/** Return the success value or `undefined`. Only object values are allowed to avoid truthiness bugs with primitives. */\nexport function getOrUndefined<TValue extends object, TError>(result: Result<TValue, TError>): TValue | undefined {\n\treturn result.ok ? result.value : undefined;\n}\n\n/**\n * Skill loaded from a `SKILL.md` file or provided by an application.\n *\n * `name`, `description`, and `filePath` are inserted into the system prompt in an XML-formatted block as suggested by agentskills.io.\n * Use {@link formatSkillsForSystemPrompt} to generate the spec-compatible system prompt block.\n */\nexport interface Skill {\n\t/** Stable skill name used for lookup and model-visible listings. */\n\tname: string;\n\t/** Short model-visible description of when to use the skill. */\n\tdescription: string;\n\t/** Full skill instructions. */\n\tcontent: string;\n\t/** Absolute path to the skill file. Used for model-visible location and resolving relative references. */\n\tfilePath: string;\n\t/** Exclude this skill from model-visible skill lists while still allowing explicit application invocation. */\n\tdisableModelInvocation?: boolean;\n}\n\n/** Prompt template that can be formatted into a prompt for explicit invocation. */\nexport interface PromptTemplate {\n\t/** Stable template name used for lookup or application command routing. */\n\tname: string;\n\t/** Optional description for command lists or autocomplete. */\n\tdescription?: string;\n\t/** Template content. Argument placeholders are formatted by `formatPromptTemplateInvocation`. */\n\tcontent: string;\n}\n\n/** Resources made available to explicit invocation methods and system-prompt callbacks. */\nexport interface AgentHarnessResources<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\t/** Prompt templates available for explicit invocation. */\n\tpromptTemplates?: TPromptTemplate[];\n\t/** Skills available to the model and explicit skill invocation. */\n\tskills?: TSkill[];\n}\n\n/** Curated provider request options owned by the harness and snapshotted per turn. */\nexport interface AgentHarnessStreamOptions {\n\t/** Preferred transport forwarded to the stream function. */\n\ttransport?: Transport;\n\t/** Provider request timeout in milliseconds. */\n\ttimeoutMs?: number;\n\t/** Maximum provider retry attempts. */\n\tmaxRetries?: number;\n\t/** Optional cap for provider-requested retry delays. */\n\tmaxRetryDelayMs?: number;\n\t/** Additional request headers merged with auth and lifecycle headers. */\n\theaders?: Record<string, string>;\n\t/** Provider metadata forwarded with requests. */\n\tmetadata?: SimpleStreamOptions[\"metadata\"];\n\t/** Provider cache retention hint. */\n\tcacheRetention?: SimpleStreamOptions[\"cacheRetention\"];\n}\n\n/** Per-request stream option patch returned by provider hooks. */\nexport interface AgentHarnessStreamOptionsPatch\n\textends Omit<Partial<AgentHarnessStreamOptions>, \"headers\" | \"metadata\"> {\n\t/** Header patch. `undefined` values delete keys; explicit `headers: undefined` clears all headers. */\n\theaders?: Record<string, string | undefined>;\n\t/** Metadata patch. `undefined` values delete keys; explicit `metadata: undefined` clears all metadata. */\n\tmetadata?: Record<string, unknown | undefined>;\n}\n\n/** Kind of filesystem object as addressed by a {@link FileSystem}. Symlinks are not followed automatically. */\nexport type FileKind = \"file\" | \"directory\" | \"symlink\";\n\n/** Stable, backend-independent file error codes returned by {@link FileSystem} file operations. */\nexport type FileErrorCode =\n\t| \"aborted\"\n\t| \"not_found\"\n\t| \"permission_denied\"\n\t| \"not_directory\"\n\t| \"is_directory\"\n\t| \"invalid\"\n\t| \"not_supported\"\n\t| \"unknown\";\n\n/** Error returned by {@link FileSystem} file operations. */\nexport class FileError extends Error {\n\tconstructor(\n\t\t/** Backend-independent error code. */\n\t\tpublic code: FileErrorCode,\n\t\tmessage: string,\n\t\t/** Absolute addressed path associated with the failure, when available. */\n\t\tpublic path?: string,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"FileError\";\n\t}\n}\n\n/** Stable, backend-independent execution error codes returned by {@link ExecutionEnv.exec}. */\nexport type ExecutionErrorCode = \"aborted\" | \"timeout\" | \"shell_unavailable\" | \"spawn_error\" | \"unknown\";\n\n/** Error returned by {@link ExecutionEnv.exec}. */\nexport class ExecutionError extends Error {\n\tconstructor(\n\t\t/** Backend-independent error code. */\n\t\tpublic code: ExecutionErrorCode,\n\t\tmessage: string,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"ExecutionError\";\n\t}\n}\n\n/** Stable compaction error codes returned by compaction helpers. */\nexport type CompactionErrorCode = \"aborted\" | \"summarization_failed\" | \"invalid_session\" | \"unknown\";\n\n/** Error returned by compaction helpers. */\nexport class CompactionError extends Error {\n\tconstructor(\n\t\t/** Backend-independent error code. */\n\t\tpublic code: CompactionErrorCode,\n\t\tmessage: string,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"CompactionError\";\n\t}\n}\n\n/** Metadata for one filesystem object in a {@link FileSystem}. */\nexport interface FileInfo {\n\t/** Basename of {@link path}. */\n\tname: string;\n\t/** Absolute, syntactically normalized addressed path in the execution environment. Symlinks are not followed. */\n\tpath: string;\n\t/** Object kind. Symlink targets are not followed; use {@link FileSystem.canonicalPath} explicitly. */\n\tkind: FileKind;\n\t/** Size in bytes for the addressed filesystem object. */\n\tsize: number;\n\t/** Modification time as milliseconds since Unix epoch. */\n\tmtimeMs: number;\n}\n\n/** Options for {@link Shell.exec}. */\nexport interface ExecutionEnvExecOptions {\n\t/** Working directory for the command. Relative paths are resolved against {@link ExecutionEnv.cwd}. Defaults to {@link ExecutionEnv.cwd}. */\n\tcwd?: string;\n\t/** Additional environment variables for the command. Values override the environment defaults. Defaults to no overrides. */\n\tenv?: Record<string, string>;\n\t/** Timeout in seconds. Implementations should return a timeout error when the command exceeds this duration. Defaults to no timeout. */\n\ttimeout?: number;\n\t/** Abort signal used to terminate the command. Defaults to no abort signal. */\n\tabortSignal?: AbortSignal;\n\t/** Called with stdout chunks as they are produced. */\n\tonStdout?: (chunk: string) => void;\n\t/** Called with stderr chunks as they are produced. */\n\tonStderr?: (chunk: string) => void;\n}\n\n/**\n * Filesystem capability used by the harness.\n *\n * Paths passed to methods may be absolute or relative to {@link cwd}. Paths returned by file operations are addressed paths\n * in the filesystem namespace, but are not canonicalized through symlinks unless returned by {@link canonicalPath}.\n *\n * Operation methods must never throw or reject. All filesystem failures, including unexpected backend failures, must be\n * encoded in the returned {@link Result}. Implementations must preserve this invariant.\n */\nexport interface FileSystem {\n\t/** Current working directory for relative paths. */\n\tcwd: string;\n\n\t/** Return an absolute addressed path without requiring it to exist and without resolving symlinks. */\n\tabsolutePath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Join path segments in the filesystem namespace without requiring the result to exist. */\n\tjoinPath(parts: string[], abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Read a UTF-8 text file. */\n\treadTextFile(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Read a binary file. */\n\treadBinaryFile(path: string, abortSignal?: AbortSignal): Promise<Result<Uint8Array, FileError>>;\n\t/** Create or overwrite a file, creating parent directories when supported. */\n\twriteFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;\n\t/** Create or append to a file, creating parent directories when supported. */\n\tappendFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;\n\t/** Return metadata for the addressed path without following symlinks. */\n\tfileInfo(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo, FileError>>;\n\t/** List direct children of a directory without following symlinks. */\n\tlistDir(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo[], FileError>>;\n\t/** Return the canonical path for an existing path, resolving symlinks where supported. */\n\tcanonicalPath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Return false for missing paths. Other errors, such as permission failures, return a {@link FileError}. */\n\texists(path: string, abortSignal?: AbortSignal): Promise<Result<boolean, FileError>>;\n\t/** Create a directory. Defaults: `recursive: true`, no abort signal. */\n\tcreateDir(\n\t\tpath: string,\n\t\toptions?: { recursive?: boolean; abortSignal?: AbortSignal },\n\t): Promise<Result<void, FileError>>;\n\t/** Remove a file or directory. Defaults: `recursive: false`, `force: false`, no abort signal. */\n\tremove(\n\t\tpath: string,\n\t\toptions?: { recursive?: boolean; force?: boolean; abortSignal?: AbortSignal },\n\t): Promise<Result<void, FileError>>;\n\t/** Create a temporary directory and return its absolute path. Defaults: `prefix: \"tmp-\"`, no abort signal. */\n\tcreateTempDir(prefix?: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;\n\t/** Create a temporary file and return its absolute path. Defaults: `prefix: \"\"`, `suffix: \"\"`, no abort signal. */\n\tcreateTempFile(options?: {\n\t\tprefix?: string;\n\t\tsuffix?: string;\n\t\tabortSignal?: AbortSignal;\n\t}): Promise<Result<string, FileError>>;\n\n\t/** Release filesystem resources. Must be best-effort and must not throw or reject. */\n\tcleanup(): Promise<void>;\n}\n\n/** Shell execution capability used by the harness. */\nexport interface Shell {\n\t/** Execute a shell command in {@link FileSystem.cwd} unless `options.cwd` is provided. */\n\texec(\n\t\tcommand: string,\n\t\toptions?: ExecutionEnvExecOptions,\n\t): Promise<Result<{ stdout: string; stderr: string; exitCode: number }, ExecutionError>>;\n\t/** Release shell resources. Must be best-effort and must not throw or reject. */\n\tcleanup(): Promise<void>;\n}\n\n/** Filesystem and process execution environment used by the harness. */\nexport interface ExecutionEnv extends FileSystem, Shell {}\n\nexport interface SessionTreeEntryBase {\n\ttype: string;\n\tid: string;\n\tparentId: string | null;\n\ttimestamp: string;\n}\n\nexport interface MessageEntry extends SessionTreeEntryBase {\n\ttype: \"message\";\n\tmessage: AgentMessage;\n}\n\nexport interface ThinkingLevelChangeEntry extends SessionTreeEntryBase {\n\ttype: \"thinking_level_change\";\n\tthinkingLevel: string;\n}\n\nexport interface ModelChangeEntry extends SessionTreeEntryBase {\n\ttype: \"model_change\";\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport interface CompactionEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"compaction\";\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tdetails?: T;\n\tfromHook?: boolean;\n}\n\nexport interface BranchSummaryEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"branch_summary\";\n\tfromId: string;\n\tsummary: string;\n\tdetails?: T;\n\tfromHook?: boolean;\n}\n\nexport interface CustomEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"custom\";\n\tcustomType: string;\n\tdata?: T;\n}\n\nexport interface CustomMessageEntry<T = unknown> extends SessionTreeEntryBase {\n\ttype: \"custom_message\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdetails?: T;\n\tdisplay: boolean;\n}\n\nexport interface LabelEntry extends SessionTreeEntryBase {\n\ttype: \"label\";\n\ttargetId: string;\n\tlabel: string | undefined;\n}\n\nexport interface SessionInfoEntry extends SessionTreeEntryBase {\n\ttype: \"session_info\"; // legacy name, kept for backwards compatibility\n\tname?: string;\n}\n\nexport type SessionTreeEntry =\n\t| MessageEntry\n\t| ThinkingLevelChangeEntry\n\t| ModelChangeEntry\n\t| CompactionEntry\n\t| BranchSummaryEntry\n\t| CustomEntry\n\t| CustomMessageEntry\n\t| LabelEntry\n\t| SessionInfoEntry;\n\nexport interface SessionContext {\n\tmessages: AgentMessage[];\n\tthinkingLevel: string;\n\tmodel: { provider: string; modelId: string } | null;\n}\n\nexport interface SessionMetadata {\n\tid: string;\n\tcreatedAt: string;\n}\n\nexport interface JsonlSessionMetadata extends SessionMetadata {\n\tcwd: string;\n\tpath: string;\n\tparentSessionPath?: string;\n}\n\nexport interface SessionStorage<TMetadata extends SessionMetadata = SessionMetadata> {\n\tgetMetadata(): Promise<TMetadata>;\n\tgetLeafId(): Promise<string | null>;\n\tsetLeafId(leafId: string | null): Promise<void>;\n\tcreateEntryId(): Promise<string>;\n\tappendEntry(entry: SessionTreeEntry): Promise<void>;\n\tgetEntry(id: string): Promise<SessionTreeEntry | undefined>;\n\tfindEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>>;\n\tgetLabel(id: string): Promise<string | undefined>;\n\tgetPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]>;\n\tgetEntries(): Promise<SessionTreeEntry[]>;\n}\n\nexport type { Session } from \"./session/session.js\";\n\nexport interface SessionCreateOptions {\n\tid?: string;\n}\n\nexport interface SessionForkOptions {\n\tentryId?: string;\n\tposition?: \"before\" | \"at\";\n\tid?: string;\n}\n\nexport interface SessionRepo<\n\tTMetadata extends SessionMetadata = SessionMetadata,\n\tTCreateOptions extends SessionCreateOptions = SessionCreateOptions,\n\tTListOptions = void,\n> {\n\tcreate(options: TCreateOptions): Promise<Session<TMetadata>>;\n\topen(metadata: TMetadata): Promise<Session<TMetadata>>;\n\tlist(options?: TListOptions): Promise<TMetadata[]>;\n\tdelete(metadata: TMetadata): Promise<void>;\n\tfork(source: TMetadata, options: SessionForkOptions & TCreateOptions): Promise<Session<TMetadata>>;\n}\n\nexport interface JsonlSessionCreateOptions extends SessionCreateOptions {\n\tcwd: string;\n\tparentSessionPath?: string;\n}\n\nexport interface JsonlSessionListOptions {\n\tcwd?: string;\n}\n\nexport interface JsonlSessionRepoApi\n\textends SessionRepo<JsonlSessionMetadata, JsonlSessionCreateOptions, JsonlSessionListOptions> {}\n\nexport type AgentHarnessPhase = \"idle\" | \"turn\" | \"compaction\" | \"branch_summary\" | \"retry\";\n\nexport type PendingSessionWrite = SessionTreeEntry extends infer TEntry\n\t? TEntry extends SessionTreeEntry\n\t\t? Omit<TEntry, \"id\" | \"parentId\" | \"timestamp\">\n\t\t: never\n\t: never;\n\nexport interface QueueUpdateEvent {\n\ttype: \"queue_update\";\n\tsteer: AgentMessage[];\n\tfollowUp: AgentMessage[];\n\tnextTurn: AgentMessage[];\n}\n\nexport interface SavePointEvent {\n\ttype: \"save_point\";\n\thadPendingMutations: boolean;\n}\n\nexport interface AbortEvent {\n\ttype: \"abort\";\n\tclearedSteer: AgentMessage[];\n\tclearedFollowUp: AgentMessage[];\n}\n\nexport interface SettledEvent {\n\ttype: \"settled\";\n\tnextTurnCount: number;\n}\n\nexport interface BeforeAgentStartEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\ttype: \"before_agent_start\";\n\tprompt: string;\n\timages?: ImageContent[];\n\tsystemPrompt: string;\n\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n}\n\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tmodel: Model<any>;\n\tsessionId: string;\n\tstreamOptions: AgentHarnessStreamOptions;\n}\n\nexport interface BeforeProviderPayloadEvent {\n\ttype: \"before_provider_payload\";\n\tmodel: Model<any>;\n\tpayload: unknown;\n}\n\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\nexport interface ToolCallEvent {\n\ttype: \"tool_call\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n}\n\nexport interface ToolResultEvent {\n\ttype: \"tool_result\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n\tcontent: Array<TextContent | ImageContent>;\n\tdetails: unknown;\n\tisError: boolean;\n}\n\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\tpreparation: CompactionPreparation;\n\tbranchEntries: SessionTreeEntry[];\n\tcustomInstructions?: string;\n\tsignal: AbortSignal;\n}\n\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromHook: boolean;\n}\n\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\tpreparation: TreePreparation;\n\tsignal: AbortSignal;\n}\n\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\tnewLeafId: string | null;\n\toldLeafId: string | null;\n\tsummaryEntry?: BranchSummaryEntry;\n\tfromHook?: boolean;\n}\n\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<any>;\n\tpreviousModel: Model<any> | undefined;\n\tsource: \"set\" | \"restore\";\n}\n\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\nexport interface ResourcesUpdateEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> {\n\ttype: \"resources_update\";\n\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tpreviousResources: AgentHarnessResources<TSkill, TPromptTemplate>;\n}\n\nexport type AgentHarnessOwnEvent<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n> =\n\t| QueueUpdateEvent\n\t| SavePointEvent\n\t| AbortEvent\n\t| SettledEvent\n\t| BeforeAgentStartEvent<TSkill, TPromptTemplate>\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderPayloadEvent\n\t| AfterProviderResponseEvent\n\t| ToolCallEvent\n\t| ToolResultEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent\n\t| ModelSelectEvent\n\t| ThinkingLevelSelectEvent\n\t| ResourcesUpdateEvent<TSkill, TPromptTemplate>;\n\nexport type AgentHarnessEvent<TSkill extends Skill = Skill, TPromptTemplate extends PromptTemplate = PromptTemplate> =\n\t| AgentEvent\n\t| AgentHarnessOwnEvent<TSkill, TPromptTemplate>;\n\nexport interface BeforeAgentStartResult {\n\tmessages?: AgentMessage[];\n\tsystemPrompt?: string;\n}\n\nexport interface ContextResult {\n\tmessages: AgentMessage[];\n}\n\nexport interface BeforeProviderRequestResult {\n\tstreamOptions?: AgentHarnessStreamOptionsPatch;\n}\n\nexport interface BeforeProviderPayloadResult {\n\tpayload: unknown;\n}\n\nexport interface ToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\nexport interface ToolResultPatch {\n\tcontent?: Array<TextContent | ImageContent>;\n\tdetails?: unknown;\n\tisError?: boolean;\n\tterminate?: boolean;\n}\n\nexport interface SessionBeforeCompactResult {\n\tcancel?: boolean;\n\tcompaction?: CompactResult;\n}\n\nexport interface SessionBeforeTreeResult {\n\tcancel?: boolean;\n\tsummary?: { summary: string; details?: unknown };\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\tlabel?: string;\n}\n\nexport type AgentHarnessEventResultMap = {\n\tbefore_agent_start: BeforeAgentStartResult | undefined;\n\tcontext: ContextResult | undefined;\n\tbefore_provider_request: BeforeProviderRequestResult | undefined;\n\tbefore_provider_payload: BeforeProviderPayloadResult | undefined;\n\tafter_provider_response: undefined;\n\ttool_call: ToolCallResult | undefined;\n\ttool_result: ToolResultPatch | undefined;\n\tsession_before_compact: SessionBeforeCompactResult | undefined;\n\tsession_compact: undefined;\n\tsession_before_tree: SessionBeforeTreeResult | undefined;\n\tsession_tree: undefined;\n\tmodel_select: undefined;\n\tthinking_level_select: undefined;\n\tresources_update: undefined;\n\tqueue_update: undefined;\n\tsave_point: undefined;\n\tabort: undefined;\n\tsettled: undefined;\n};\n\nexport interface AgentHarnessPromptOptions {\n\timages?: ImageContent[];\n}\n\nexport interface AbortResult {\n\tclearedSteer: AgentMessage[];\n\tclearedFollowUp: AgentMessage[];\n}\n\nexport interface CompactResult {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tdetails?: unknown;\n}\n\nexport interface NavigateTreeResult {\n\tcancelled: boolean;\n\teditorText?: string;\n\tsummaryEntry?: BranchSummaryEntry;\n}\n\nexport interface CompactionSettings {\n\tenabled: boolean;\n\treserveTokens: number;\n\tkeepRecentTokens: number;\n}\n\nexport interface CompactionPreparation {\n\tfirstKeptEntryId: string;\n\tmessagesToSummarize: AgentMessage[];\n\tturnPrefixMessages: AgentMessage[];\n\tisSplitTurn: boolean;\n\ttokensBefore: number;\n\tpreviousSummary?: string;\n\tfileOps: FileOperations;\n\tsettings: CompactionSettings;\n}\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport interface TreePreparation {\n\ttargetId: string;\n\toldLeafId: string | null;\n\tcommonAncestorId: string | null;\n\tentriesToSummarize: SessionTreeEntry[];\n\tuserWantsSummary: boolean;\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\tlabel?: string;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\tmodel: Model<any>;\n\tapiKey: string;\n\theaders?: Record<string, string>;\n\tsignal: AbortSignal;\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\treserveTokens?: number;\n}\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\taborted?: boolean;\n\terror?: string;\n}\n\nexport interface AgentHarnessOptions<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n\tTTool extends AgentTool = AgentTool,\n> {\n\tenv: ExecutionEnv;\n\tsession: Session;\n\ttools?: TTool[];\n\t/**\n\t * Concrete resources available to explicit invocation methods and system-prompt callbacks.\n\t * Applications own loading/reloading resources and should call `setResources()` with new values.\n\t */\n\tresources?: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tsystemPrompt?:\n\t\t| string\n\t\t| ((context: {\n\t\t\t\tenv: ExecutionEnv;\n\t\t\t\tsession: Session;\n\t\t\t\tmodel: Model<any>;\n\t\t\t\tthinkingLevel: ThinkingLevel;\n\t\t\t\tactiveTools: TTool[];\n\t\t\t\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\t\t }) => string | Promise<string>);\n\tgetApiKeyAndHeaders?: (\n\t\tmodel: Model<any>,\n\t) => Promise<{ apiKey: string; headers?: Record<string, string> } | undefined>;\n\t/** Curated stream/provider request options. Snapshotted at turn start. */\n\tstreamOptions?: AgentHarnessStreamOptions;\n\tmodel: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tactiveToolNames?: string[];\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n}\n\nexport type { AgentHarness } from \"./agent-harness.js\";\n"]}
@@ -0,0 +1,14 @@
1
+ import { type ExecutionEnv, type ExecutionEnvExecOptions, ExecutionError, type Result } from "../types.js";
2
+ export interface ShellCaptureOptions extends Omit<ExecutionEnvExecOptions, "onStdout" | "onStderr"> {
3
+ onChunk?: (chunk: string) => void;
4
+ }
5
+ export interface ShellCaptureResult {
6
+ output: string;
7
+ exitCode: number | undefined;
8
+ cancelled: boolean;
9
+ truncated: boolean;
10
+ fullOutputPath?: string;
11
+ }
12
+ export declare function sanitizeBinaryOutput(str: string): string;
13
+ export declare function executeShellWithCapture(env: ExecutionEnv, command: string, options?: ShellCaptureOptions): Promise<Result<ShellCaptureResult, ExecutionError>>;
14
+ //# sourceMappingURL=shell-output.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell-output.d.ts","sourceRoot":"","sources":["../../../src/harness/utils/shell-output.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,uBAAuB,EAAE,cAAc,EAAW,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AAGpH,MAAM,WAAW,mBAAoB,SAAQ,IAAI,CAAC,uBAAuB,EAAE,UAAU,GAAG,UAAU,CAAC;IAClG,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;CAClC;AAED,MAAM,WAAW,kBAAkB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAQD,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAWxD;AAED,wBAAsB,uBAAuB,CAC5C,GAAG,EAAE,YAAY,EACjB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,MAAM,CAAC,kBAAkB,EAAE,cAAc,CAAC,CAAC,CAgGrD","sourcesContent":["import { type ExecutionEnv, type ExecutionEnvExecOptions, ExecutionError, err, ok, type Result } from \"../types.js\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./truncate.js\";\n\nexport interface ShellCaptureOptions extends Omit<ExecutionEnvExecOptions, \"onStdout\" | \"onStderr\"> {\n\tonChunk?: (chunk: string) => void;\n}\n\nexport interface ShellCaptureResult {\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n}\n\nfunction toExecutionError(error: unknown): ExecutionError {\n\treturn error instanceof ExecutionError\n\t\t? error\n\t\t: new ExecutionError(\"unknown\", error instanceof Error ? error.message : String(error), error);\n}\n\nexport function sanitizeBinaryOutput(str: string): string {\n\treturn Array.from(str)\n\t\t.filter((char) => {\n\t\t\tconst code = char.codePointAt(0);\n\t\t\tif (code === undefined) return false;\n\t\t\tif (code === 0x09 || code === 0x0a || code === 0x0d) return true;\n\t\t\tif (code <= 0x1f) return false;\n\t\t\tif (code >= 0xfff9 && code <= 0xfffb) return false;\n\t\t\treturn true;\n\t\t})\n\t\t.join(\"\");\n}\n\nexport async function executeShellWithCapture(\n\tenv: ExecutionEnv,\n\tcommand: string,\n\toptions?: ShellCaptureOptions,\n): Promise<Result<ShellCaptureResult, ExecutionError>> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\tconst encoder = new TextEncoder();\n\n\tlet totalBytes = 0;\n\tlet fullOutputPath: string | undefined;\n\tlet writeChain: Promise<Result<void, ExecutionError>> = Promise.resolve(ok(undefined));\n\tlet captureError: ExecutionError | undefined;\n\n\tconst appendFullOutput = (text: string): void => {\n\t\tif (!fullOutputPath || captureError) return;\n\t\tconst path = fullOutputPath;\n\t\twriteChain = writeChain.then(async (previous) => {\n\t\t\tif (!previous.ok) return previous;\n\t\t\tconst appendResult = await env.appendFile(path, text, options?.abortSignal);\n\t\t\treturn appendResult.ok ? ok(undefined) : err(toExecutionError(appendResult.error));\n\t\t});\n\t};\n\n\tconst ensureFullOutputFile = (initialContent: string): void => {\n\t\tif (fullOutputPath || captureError) return;\n\t\twriteChain = writeChain.then(async (previous) => {\n\t\t\tif (!previous.ok) return previous;\n\t\t\tconst tempFile = await env.createTempFile({\n\t\t\t\tprefix: \"bash-\",\n\t\t\t\tsuffix: \".log\",\n\t\t\t\tabortSignal: options?.abortSignal,\n\t\t\t});\n\t\t\tif (!tempFile.ok) return err(toExecutionError(tempFile.error));\n\t\t\tfullOutputPath = tempFile.value;\n\t\t\tconst appendResult = await env.appendFile(tempFile.value, initialContent, options?.abortSignal);\n\t\t\treturn appendResult.ok ? ok(undefined) : err(toExecutionError(appendResult.error));\n\t\t});\n\t};\n\n\tconst onChunk = (chunk: string) => {\n\t\ttry {\n\t\t\ttotalBytes += encoder.encode(chunk).byteLength;\n\t\t\tconst text = sanitizeBinaryOutput(chunk).replace(/\\r/g, \"\");\n\t\t\tif (totalBytes > DEFAULT_MAX_BYTES && !fullOutputPath) {\n\t\t\t\tensureFullOutputFile(outputChunks.join(\"\") + text);\n\t\t\t} else {\n\t\t\t\tappendFullOutput(text);\n\t\t\t}\n\t\t\toutputChunks.push(text);\n\t\t\toutputBytes += text.length;\n\t\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\t\tconst removed = outputChunks.shift()!;\n\t\t\t\toutputBytes -= removed.length;\n\t\t\t}\n\t\t\toptions?.onChunk?.(text);\n\t\t} catch (error) {\n\t\t\tcaptureError = toExecutionError(error);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await env.exec(command, {\n\t\t\t...(options ?? {}),\n\t\t\tonStdout: onChunk,\n\t\t\tonStderr: onChunk,\n\t\t});\n\t\tconst tailOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(tailOutput);\n\t\tif (truncationResult.truncated && !fullOutputPath) {\n\t\t\tensureFullOutputFile(tailOutput);\n\t\t}\n\t\tconst writeResult = await writeChain;\n\t\tif (!writeResult.ok) return err(writeResult.error);\n\t\tif (captureError) return err(captureError);\n\n\t\tif (!result.ok) {\n\t\t\tif (result.error.code === \"aborted\" || options?.abortSignal?.aborted) {\n\t\t\t\treturn ok({\n\t\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : tailOutput,\n\t\t\t\t\texitCode: undefined,\n\t\t\t\t\tcancelled: true,\n\t\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn err(result.error);\n\t\t}\n\t\tconst cancelled = options?.abortSignal?.aborted ?? false;\n\t\treturn ok({\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : tailOutput,\n\t\t\texitCode: cancelled ? undefined : result.value.exitCode,\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath,\n\t\t});\n\t} catch (error) {\n\t\treturn err(toExecutionError(error));\n\t}\n}\n"]}
@@ -0,0 +1,125 @@
1
+ import { ExecutionError, err, ok } from "../types.js";
2
+ import { DEFAULT_MAX_BYTES, truncateTail } from "./truncate.js";
3
+ function toExecutionError(error) {
4
+ return error instanceof ExecutionError
5
+ ? error
6
+ : new ExecutionError("unknown", error instanceof Error ? error.message : String(error), error);
7
+ }
8
+ export function sanitizeBinaryOutput(str) {
9
+ return Array.from(str)
10
+ .filter((char) => {
11
+ const code = char.codePointAt(0);
12
+ if (code === undefined)
13
+ return false;
14
+ if (code === 0x09 || code === 0x0a || code === 0x0d)
15
+ return true;
16
+ if (code <= 0x1f)
17
+ return false;
18
+ if (code >= 0xfff9 && code <= 0xfffb)
19
+ return false;
20
+ return true;
21
+ })
22
+ .join("");
23
+ }
24
+ export async function executeShellWithCapture(env, command, options) {
25
+ const outputChunks = [];
26
+ let outputBytes = 0;
27
+ const maxOutputBytes = DEFAULT_MAX_BYTES * 2;
28
+ const encoder = new TextEncoder();
29
+ let totalBytes = 0;
30
+ let fullOutputPath;
31
+ let writeChain = Promise.resolve(ok(undefined));
32
+ let captureError;
33
+ const appendFullOutput = (text) => {
34
+ if (!fullOutputPath || captureError)
35
+ return;
36
+ const path = fullOutputPath;
37
+ writeChain = writeChain.then(async (previous) => {
38
+ if (!previous.ok)
39
+ return previous;
40
+ const appendResult = await env.appendFile(path, text, options?.abortSignal);
41
+ return appendResult.ok ? ok(undefined) : err(toExecutionError(appendResult.error));
42
+ });
43
+ };
44
+ const ensureFullOutputFile = (initialContent) => {
45
+ if (fullOutputPath || captureError)
46
+ return;
47
+ writeChain = writeChain.then(async (previous) => {
48
+ if (!previous.ok)
49
+ return previous;
50
+ const tempFile = await env.createTempFile({
51
+ prefix: "bash-",
52
+ suffix: ".log",
53
+ abortSignal: options?.abortSignal,
54
+ });
55
+ if (!tempFile.ok)
56
+ return err(toExecutionError(tempFile.error));
57
+ fullOutputPath = tempFile.value;
58
+ const appendResult = await env.appendFile(tempFile.value, initialContent, options?.abortSignal);
59
+ return appendResult.ok ? ok(undefined) : err(toExecutionError(appendResult.error));
60
+ });
61
+ };
62
+ const onChunk = (chunk) => {
63
+ try {
64
+ totalBytes += encoder.encode(chunk).byteLength;
65
+ const text = sanitizeBinaryOutput(chunk).replace(/\r/g, "");
66
+ if (totalBytes > DEFAULT_MAX_BYTES && !fullOutputPath) {
67
+ ensureFullOutputFile(outputChunks.join("") + text);
68
+ }
69
+ else {
70
+ appendFullOutput(text);
71
+ }
72
+ outputChunks.push(text);
73
+ outputBytes += text.length;
74
+ while (outputBytes > maxOutputBytes && outputChunks.length > 1) {
75
+ const removed = outputChunks.shift();
76
+ outputBytes -= removed.length;
77
+ }
78
+ options?.onChunk?.(text);
79
+ }
80
+ catch (error) {
81
+ captureError = toExecutionError(error);
82
+ }
83
+ };
84
+ try {
85
+ const result = await env.exec(command, {
86
+ ...(options ?? {}),
87
+ onStdout: onChunk,
88
+ onStderr: onChunk,
89
+ });
90
+ const tailOutput = outputChunks.join("");
91
+ const truncationResult = truncateTail(tailOutput);
92
+ if (truncationResult.truncated && !fullOutputPath) {
93
+ ensureFullOutputFile(tailOutput);
94
+ }
95
+ const writeResult = await writeChain;
96
+ if (!writeResult.ok)
97
+ return err(writeResult.error);
98
+ if (captureError)
99
+ return err(captureError);
100
+ if (!result.ok) {
101
+ if (result.error.code === "aborted" || options?.abortSignal?.aborted) {
102
+ return ok({
103
+ output: truncationResult.truncated ? truncationResult.content : tailOutput,
104
+ exitCode: undefined,
105
+ cancelled: true,
106
+ truncated: truncationResult.truncated,
107
+ fullOutputPath,
108
+ });
109
+ }
110
+ return err(result.error);
111
+ }
112
+ const cancelled = options?.abortSignal?.aborted ?? false;
113
+ return ok({
114
+ output: truncationResult.truncated ? truncationResult.content : tailOutput,
115
+ exitCode: cancelled ? undefined : result.value.exitCode,
116
+ cancelled,
117
+ truncated: truncationResult.truncated,
118
+ fullOutputPath,
119
+ });
120
+ }
121
+ catch (error) {
122
+ return err(toExecutionError(error));
123
+ }
124
+ }
125
+ //# sourceMappingURL=shell-output.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell-output.js","sourceRoot":"","sources":["../../../src/harness/utils/shell-output.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmD,cAAc,EAAE,GAAG,EAAE,EAAE,EAAe,MAAM,aAAa,CAAC;AACpH,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAchE,SAAS,gBAAgB,CAAC,KAAc,EAAkB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U;YAC1E,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ;YACvD,SAAS;YACT,SAAS,EAAE,gBAAgB,CAAC,SAAS;YACrC,cAAc;SACd,CAAC,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,GAAG,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC;IACrC,CAAC;AAAA,CACD","sourcesContent":["import { type ExecutionEnv, type ExecutionEnvExecOptions, ExecutionError, err, ok, type Result } from \"../types.js\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./truncate.js\";\n\nexport interface ShellCaptureOptions extends Omit<ExecutionEnvExecOptions, \"onStdout\" | \"onStderr\"> {\n\tonChunk?: (chunk: string) => void;\n}\n\nexport interface ShellCaptureResult {\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n}\n\nfunction toExecutionError(error: unknown): ExecutionError {\n\treturn error instanceof ExecutionError\n\t\t? error\n\t\t: new ExecutionError(\"unknown\", error instanceof Error ? error.message : String(error), error);\n}\n\nexport function sanitizeBinaryOutput(str: string): string {\n\treturn Array.from(str)\n\t\t.filter((char) => {\n\t\t\tconst code = char.codePointAt(0);\n\t\t\tif (code === undefined) return false;\n\t\t\tif (code === 0x09 || code === 0x0a || code === 0x0d) return true;\n\t\t\tif (code <= 0x1f) return false;\n\t\t\tif (code >= 0xfff9 && code <= 0xfffb) return false;\n\t\t\treturn true;\n\t\t})\n\t\t.join(\"\");\n}\n\nexport async function executeShellWithCapture(\n\tenv: ExecutionEnv,\n\tcommand: string,\n\toptions?: ShellCaptureOptions,\n): Promise<Result<ShellCaptureResult, ExecutionError>> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\tconst encoder = new TextEncoder();\n\n\tlet totalBytes = 0;\n\tlet fullOutputPath: string | undefined;\n\tlet writeChain: Promise<Result<void, ExecutionError>> = Promise.resolve(ok(undefined));\n\tlet captureError: ExecutionError | undefined;\n\n\tconst appendFullOutput = (text: string): void => {\n\t\tif (!fullOutputPath || captureError) return;\n\t\tconst path = fullOutputPath;\n\t\twriteChain = writeChain.then(async (previous) => {\n\t\t\tif (!previous.ok) return previous;\n\t\t\tconst appendResult = await env.appendFile(path, text, options?.abortSignal);\n\t\t\treturn appendResult.ok ? ok(undefined) : err(toExecutionError(appendResult.error));\n\t\t});\n\t};\n\n\tconst ensureFullOutputFile = (initialContent: string): void => {\n\t\tif (fullOutputPath || captureError) return;\n\t\twriteChain = writeChain.then(async (previous) => {\n\t\t\tif (!previous.ok) return previous;\n\t\t\tconst tempFile = await env.createTempFile({\n\t\t\t\tprefix: \"bash-\",\n\t\t\t\tsuffix: \".log\",\n\t\t\t\tabortSignal: options?.abortSignal,\n\t\t\t});\n\t\t\tif (!tempFile.ok) return err(toExecutionError(tempFile.error));\n\t\t\tfullOutputPath = tempFile.value;\n\t\t\tconst appendResult = await env.appendFile(tempFile.value, initialContent, options?.abortSignal);\n\t\t\treturn appendResult.ok ? ok(undefined) : err(toExecutionError(appendResult.error));\n\t\t});\n\t};\n\n\tconst onChunk = (chunk: string) => {\n\t\ttry {\n\t\t\ttotalBytes += encoder.encode(chunk).byteLength;\n\t\t\tconst text = sanitizeBinaryOutput(chunk).replace(/\\r/g, \"\");\n\t\t\tif (totalBytes > DEFAULT_MAX_BYTES && !fullOutputPath) {\n\t\t\t\tensureFullOutputFile(outputChunks.join(\"\") + text);\n\t\t\t} else {\n\t\t\t\tappendFullOutput(text);\n\t\t\t}\n\t\t\toutputChunks.push(text);\n\t\t\toutputBytes += text.length;\n\t\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\t\tconst removed = outputChunks.shift()!;\n\t\t\t\toutputBytes -= removed.length;\n\t\t\t}\n\t\t\toptions?.onChunk?.(text);\n\t\t} catch (error) {\n\t\t\tcaptureError = toExecutionError(error);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await env.exec(command, {\n\t\t\t...(options ?? {}),\n\t\t\tonStdout: onChunk,\n\t\t\tonStderr: onChunk,\n\t\t});\n\t\tconst tailOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(tailOutput);\n\t\tif (truncationResult.truncated && !fullOutputPath) {\n\t\t\tensureFullOutputFile(tailOutput);\n\t\t}\n\t\tconst writeResult = await writeChain;\n\t\tif (!writeResult.ok) return err(writeResult.error);\n\t\tif (captureError) return err(captureError);\n\n\t\tif (!result.ok) {\n\t\t\tif (result.error.code === \"aborted\" || options?.abortSignal?.aborted) {\n\t\t\t\treturn ok({\n\t\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : tailOutput,\n\t\t\t\t\texitCode: undefined,\n\t\t\t\t\tcancelled: true,\n\t\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn err(result.error);\n\t\t}\n\t\tconst cancelled = options?.abortSignal?.aborted ?? false;\n\t\treturn ok({\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : tailOutput,\n\t\t\texitCode: cancelled ? undefined : result.value.exitCode,\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath,\n\t\t});\n\t} catch (error) {\n\t\treturn err(toExecutionError(error));\n\t}\n}\n"]}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Shared truncation utilities for tool outputs.
3
+ *
4
+ * Truncation is based on two independent limits - whichever is hit first wins:
5
+ * - Line limit (default: 2000 lines)
6
+ * - Byte limit (default: 50KB)
7
+ *
8
+ * Never returns partial lines (except bash tail truncation edge case).
9
+ */
10
+ export declare const DEFAULT_MAX_LINES = 2000;
11
+ export declare const DEFAULT_MAX_BYTES: number;
12
+ export declare const GREP_MAX_LINE_LENGTH = 500;
13
+ export interface TruncationResult {
14
+ /** The truncated content */
15
+ content: string;
16
+ /** Whether truncation occurred */
17
+ truncated: boolean;
18
+ /** Which limit was hit: "lines", "bytes", or null if not truncated */
19
+ truncatedBy: "lines" | "bytes" | null;
20
+ /** Total number of lines in the original content */
21
+ totalLines: number;
22
+ /** Total number of bytes in the original content */
23
+ totalBytes: number;
24
+ /** Number of complete lines in the truncated output */
25
+ outputLines: number;
26
+ /** Number of bytes in the truncated output */
27
+ outputBytes: number;
28
+ /** Whether the last line was partially truncated (only for tail truncation edge case) */
29
+ lastLinePartial: boolean;
30
+ /** Whether the first line exceeded the byte limit (for head truncation) */
31
+ firstLineExceedsLimit: boolean;
32
+ /** The max lines limit that was applied */
33
+ maxLines: number;
34
+ /** The max bytes limit that was applied */
35
+ maxBytes: number;
36
+ }
37
+ export interface TruncationOptions {
38
+ /** Maximum number of lines (default: 2000) */
39
+ maxLines?: number;
40
+ /** Maximum number of bytes (default: 50KB) */
41
+ maxBytes?: number;
42
+ }
43
+ /**
44
+ * Format bytes as human-readable size.
45
+ */
46
+ export declare function formatSize(bytes: number): string;
47
+ /**
48
+ * Truncate content from the head (keep first N lines/bytes).
49
+ * Suitable for file reads where you want to see the beginning.
50
+ *
51
+ * Never returns partial lines. If first line exceeds byte limit,
52
+ * returns empty content with firstLineExceedsLimit=true.
53
+ */
54
+ export declare function truncateHead(content: string, options?: TruncationOptions): TruncationResult;
55
+ /**
56
+ * Truncate content from the tail (keep last N lines/bytes).
57
+ * Suitable for bash output where you want to see the end (errors, final results).
58
+ *
59
+ * May return partial first line if the last line of original content exceeds byte limit.
60
+ */
61
+ export declare function truncateTail(content: string, options?: TruncationOptions): TruncationResult;
62
+ /**
63
+ * Truncate a single line to max characters, adding [truncated] suffix.
64
+ * Used for grep match lines.
65
+ */
66
+ export declare function truncateLine(line: string, maxChars?: number): {
67
+ text: string;
68
+ wasTruncated: boolean;
69
+ };
70
+ //# sourceMappingURL=truncate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trunc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AI,EAAE,MAAM,EACZ,QAAQ,GAAE,MAA6B,GACrC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,OAAO,CAAA;CAAE,CAKzC","sourcesContent":["/**\n * Shared truncation utilities for tool outputs.\n *\n * Truncation is based on two independent limits - whichever is hit first wins:\n * - Line limit (default: 2000 lines)\n * - Byte limit (default: 50KB)\n *\n * Never returns partial lines (except bash tail truncation edge case).\n */\n\nexport const DEFAULT_MAX_LINES = 2000;\nexport const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB\nexport const GREP_MAX_LINE_LENGTH = 500; // Max chars per grep match line\n\nexport interface TruncationResult {\n\t/** The truncated content */\n\tcontent: string;\n\t/** Whether truncation occurred */\n\ttruncated: boolean;\n\t/** Which limit was hit: \"lines\", \"bytes\", or null if not truncated */\n\ttruncatedBy: \"lines\" | \"bytes\" | null;\n\t/** Total number of lines in the original content */\n\ttotalLines: number;\n\t/** Total number of bytes in the original content */\n\ttotalBytes: number;\n\t/** Number of complete lines in the truncated output */\n\toutputLines: number;\n\t/** Number of bytes in the truncated output */\n\toutputBytes: number;\n\t/** Whether the last line was partially truncated (only for tail truncation edge case) */\n\tlastLinePartial: boolean;\n\t/** Whether the first line exceeded the byte limit (for head truncation) */\n\tfirstLineExceedsLimit: boolean;\n\t/** The max lines limit that was applied */\n\tmaxLines: number;\n\t/** The max bytes limit that was applied */\n\tmaxBytes: number;\n}\n\nexport interface TruncationOptions {\n\t/** Maximum number of lines (default: 2000) */\n\tmaxLines?: number;\n\t/** Maximum number of bytes (default: 50KB) */\n\tmaxBytes?: number;\n}\n\ninterface RuntimeBuffer {\n\tbyteLength(content: string, encoding: \"utf8\"): number;\n}\n\nconst runtimeBuffer = (globalThis as { Buffer?: RuntimeBuffer }).Buffer;\nconst nonAsciiPattern = /[^\\x00-\\x7f]/;\n\nfunction utf8ByteLength(content: string): number {\n\tif (runtimeBuffer) return runtimeBuffer.byteLength(content, \"utf8\");\n\n\tconst firstNonAscii = content.search(nonAsciiPattern);\n\tif (firstNonAscii === -1) return content.length;\n\n\tlet bytes = firstNonAscii;\n\tfor (let i = firstNonAscii; i < content.length; i++) {\n\t\tconst code = content.charCodeAt(i);\n\t\tif (code <= 0x7f) {\n\t\t\tbytes += 1;\n\t\t} else if (code <= 0x7ff) {\n\t\t\tbytes += 2;\n\t\t} else if (code >= 0xd800 && code <= 0xdbff && i + 1 < content.length) {\n\t\t\tconst next = content.charCodeAt(i + 1);\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\tbytes += 4;\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tbytes += 3;\n\t\t\t}\n\t\t} else {\n\t\t\tbytes += 3;\n\t\t}\n\t}\n\treturn bytes;\n}\n\nfunction replaceUnpairedSurrogates(content: string): string {\n\tlet output = \"\";\n\tfor (let i = 0; i < content.length; i++) {\n\t\tconst code = content.charCodeAt(i);\n\t\tif (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tif (i + 1 < content.length) {\n\t\t\t\tconst next = content.charCodeAt(i + 1);\n\t\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\t\toutput += content[i] + content[i + 1];\n\t\t\t\t\ti++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\toutput += \"�\";\n\t\t} else if (code >= 0xdc00 && code <= 0xdfff) {\n\t\t\toutput += \"�\";\n\t\t} else {\n\t\t\toutput += content[i];\n\t\t}\n\t}\n\treturn output;\n}\n\n/**\n * Format bytes as human-readable size.\n */\nexport function formatSize(bytes: number): string {\n\tif (bytes < 1024) {\n\t\treturn `${bytes}B`;\n\t} else if (bytes < 1024 * 1024) {\n\t\treturn `${(bytes / 1024).toFixed(1)}KB`;\n\t} else {\n\t\treturn `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n\t}\n}\n\n/**\n * Truncate content from the head (keep first N lines/bytes).\n * Suitable for file reads where you want to see the beginning.\n *\n * Never returns partial lines. If first line exceeds byte limit,\n * returns empty content with firstLineExceedsLimit=true.\n */\nexport function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = utf8ByteLength(content);\n\tconst lines = content.split(\"\\n\");\n\tconst totalLines = lines.length;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Check if first line alone exceeds byte limit\n\tconst firstLineBytes = utf8ByteLength(lines[0]);\n\tif (firstLineBytes > maxBytes) {\n\t\treturn {\n\t\t\tcontent: \"\",\n\t\t\ttruncated: true,\n\t\t\ttruncatedBy: \"bytes\",\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: 0,\n\t\t\toutputBytes: 0,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: true,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Collect complete lines that fit\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\n\tfor (let i = 0; i < lines.length && i < maxLines; i++) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = utf8ByteLength(line) + (i > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.push(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// If we exited due to line limit\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = utf8ByteLength(outputContent);\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial: false,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate content from the tail (keep last N lines/bytes).\n * Suitable for bash output where you want to see the end (errors, final results).\n *\n * May return partial first line if the last line of original content exceeds byte limit.\n */\nexport function truncateTail(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = utf8ByteLength(content);\n\tconst lines = content.split(\"\\n\");\n\tconst totalLines = lines.length;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Work backwards from the end\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\tlet lastLinePartial = false;\n\n\tfor (let i = lines.length - 1; i >= 0 && outputLinesArr.length < maxLines; i--) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = utf8ByteLength(line) + (outputLinesArr.length > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\t// Edge case: if we haven't added ANY lines yet and this line exceeds maxBytes,\n\t\t\t// take the end of the line (partial)\n\t\t\tif (outputLinesArr.length === 0) {\n\t\t\t\tconst truncatedLine = truncateStringToBytesFromEnd(line, maxBytes);\n\t\t\t\toutputLinesArr.unshift(truncatedLine);\n\t\t\t\toutputBytesCount = utf8ByteLength(truncatedLine);\n\t\t\t\tlastLinePartial = true;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.unshift(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// If we exited due to line limit\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = utf8ByteLength(outputContent);\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate a string to fit within a byte limit (from the end).\n * Handles multi-byte UTF-8 characters correctly.\n */\nfunction truncateStringToBytesFromEnd(str: string, maxBytes: number): string {\n\tif (maxBytes <= 0) return \"\";\n\n\tlet outputBytes = 0;\n\tlet start = str.length;\n\tlet needsReplacement = false;\n\tfor (let i = str.length; i > 0; ) {\n\t\tlet characterStart = i - 1;\n\t\tconst code = str.charCodeAt(characterStart);\n\t\tlet characterBytes: number;\n\t\tlet unpairedSurrogate = false;\n\t\tif (code >= 0xdc00 && code <= 0xdfff && characterStart > 0) {\n\t\t\tconst previous = str.charCodeAt(characterStart - 1);\n\t\t\tif (previous >= 0xd800 && previous <= 0xdbff) {\n\t\t\t\tcharacterStart--;\n\t\t\t\tcharacterBytes = 4;\n\t\t\t} else {\n\t\t\t\tcharacterBytes = 3;\n\t\t\t\tunpairedSurrogate = true;\n\t\t\t}\n\t\t} else if (code >= 0xd800 && code <= 0xdfff) {\n\t\t\tcharacterBytes = 3;\n\t\t\tunpairedSurrogate = true;\n\t\t} else {\n\t\t\tcharacterBytes = code <= 0x7f ? 1 : code <= 0x7ff ? 2 : 3;\n\t\t}\n\t\tif (outputBytes + characterBytes > maxBytes) break;\n\t\toutputBytes += characterBytes;\n\t\tstart = characterStart;\n\t\tneedsReplacement ||= unpairedSurrogate;\n\t\ti = characterStart;\n\t}\n\n\tconst output = str.slice(start);\n\treturn needsReplacement ? replaceUnpairedSurrogates(output) : output;\n}\n\n/**\n * Truncate a single line to max characters, adding [truncated] suffix.\n * Used for grep match lines.\n */\nexport function truncateLine(\n\tline: string,\n\tmaxChars: number = GREP_MAX_LINE_LENGTH,\n): { text: string; wasTruncated: boolean } {\n\tif (line.length <= maxChars) {\n\t\treturn { text: line, wasTruncated: false };\n\t}\n\treturn { text: `${line.slice(0, maxChars)}... [truncated]`, wasTruncated: true };\n}\n"]}