@kolisachint/hoocode-agent 0.4.136 → 0.4.138
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.
- package/CHANGELOG.md +28 -0
- package/dist/cli/args.d.ts +4 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +13 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +2 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/extensions/plugins/formats/platform-targets.d.ts +7 -1
- package/dist/core/extensions/plugins/formats/platform-targets.d.ts.map +1 -1
- package/dist/core/extensions/plugins/formats/platform-targets.js +8 -2
- package/dist/core/extensions/plugins/formats/platform-targets.js.map +1 -1
- package/dist/core/light.d.ts +61 -0
- package/dist/core/light.d.ts.map +1 -0
- package/dist/core/light.js +127 -0
- package/dist/core/light.js.map +1 -0
- package/dist/core/sdk.d.ts +7 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +1 -0
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +1 -0
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager.d.ts +2 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +8 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-types.d.ts +1 -0
- package/dist/core/settings-types.d.ts.map +1 -1
- package/dist/core/settings-types.js.map +1 -1
- package/dist/core/tools/propose-plugin.d.ts.map +1 -1
- package/dist/core/tools/propose-plugin.js +22 -22
- package/dist/core/tools/propose-plugin.js.map +1 -1
- package/dist/extensions/core/modes.d.ts.map +1 -1
- package/dist/extensions/core/modes.js +7 -0
- package/dist/extensions/core/modes.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +46 -9
- package/dist/main.js.map +1 -1
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-targets.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/plugins/formats/platform-targets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtD
|
|
1
|
+
{"version":3,"file":"platform-targets.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/plugins/formats/platform-targets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtD;;;;;;GAMG;AACH,eAAO,MAAM,2BAA2B,EAAE,SAAS,mBAAmB,EAAe,CAAC;AAEtF,wEAAwE;AACxE,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,mBAAmB,GAAG,SAAS,CAcrF;AAED,MAAM,WAAW,oBAAoB;IACpC,kEAAkE;IAClE,SAAS,EAAE,mBAAmB,EAAE,CAAC;IACjC,oFAAoF;IACpF,OAAO,EAAE,MAAM,EAAE,CAAC;CAClB;AAED,0FAA0F;AAC1F,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,oBAAoB,CAWrF;AAKD,oFAAoF;AACpF,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,SAAS,mBAAmB,EAAE,GAAG,SAAS,GAAG,IAAI,CAE/F;AAED,8FAA8F;AAC9F,wBAAgB,mBAAmB,IAAI,mBAAmB,EAAE,GAAG,SAAS,CAEvE;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,CAAC,EAAE,SAAS,mBAAmB,EAAE,GAAG,mBAAmB,EAAE,CAG1G","sourcesContent":["/**\n * Session-wide artifact platform targeting (`--support-platform`).\n *\n * hoocode reads resources from every vendor convention, but when it *writes*\n * artifacts — authored plugins via ProposePlugin, workspace scaffolds via\n * /new-skill //new-agent //new-command — it needs a target layout. This module\n * owns that choice for the whole process:\n *\n * token vocabulary `agents` (alias `native`), `claude`,\n * `github` (aliases `copilot`, `gh`)\n * session state set once at startup from the `--support-platform` flag\n * or the `supportPlatform` setting (main.ts)\n * resolution explicit per-call platforms → session targets →\n * {@link DEFAULT_AUTHORING_PLATFORMS}\n *\n * Kept beside the format registry (and importing only `types.ts`) so the\n * platform vocabulary and the adapters stay a one-directory concern: adding a\n * vendor means a new adapter file plus a token here, nothing else.\n */\n\nimport type { MarketplacePlatform } from \"./types.js\";\n\n/**\n * Default authoring target when neither the call nor the session picked any: the\n * portable native format. Authored artifacts are meant to be reusable, so they\n * default to one vendor-neutral layout (a strict superset hoocode reads directly)\n * rather than forking into vendor copies. Vendor layouts are an opt-in interop\n * concern, requested only via the `--support-platform` session flag.\n */\nexport const DEFAULT_AUTHORING_PLATFORMS: readonly MarketplacePlatform[] = [\"agents\"];\n\n/** Canonicalize one platform token, folding the user-facing aliases. */\nexport function normalizePlatformToken(token: string): MarketplacePlatform | undefined {\n\tswitch (token.trim().toLowerCase()) {\n\t\tcase \"agents\":\n\t\tcase \"native\":\n\t\t\treturn \"agents\";\n\t\tcase \"claude\":\n\t\t\treturn \"claude\";\n\t\tcase \"github\":\n\t\tcase \"copilot\":\n\t\tcase \"gh\":\n\t\t\treturn \"github\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nexport interface SupportPlatformParse {\n\t/** Canonical platforms, deduped, in the order first mentioned. */\n\tplatforms: MarketplacePlatform[];\n\t/** Tokens that matched no known platform (surfaced as diagnostics, never fatal). */\n\tinvalid: string[];\n}\n\n/** Parse raw `--support-platform` / `supportPlatform` tokens into canonical platforms. */\nexport function parseSupportPlatforms(tokens: readonly string[]): SupportPlatformParse {\n\tconst platforms: MarketplacePlatform[] = [];\n\tconst invalid: string[] = [];\n\tfor (const token of tokens) {\n\t\tconst trimmed = token.trim();\n\t\tif (!trimmed) continue;\n\t\tconst canonical = normalizePlatformToken(trimmed);\n\t\tif (!canonical) invalid.push(trimmed);\n\t\telse if (!platforms.includes(canonical)) platforms.push(canonical);\n\t}\n\treturn { platforms, invalid };\n}\n\n/** Session-wide targets. Undefined = not configured (fall back to defaults). */\nlet sessionSupportPlatforms: MarketplacePlatform[] | undefined;\n\n/** Set (or clear, with undefined/empty) the session's artifact platform targets. */\nexport function setSupportPlatforms(platforms: readonly MarketplacePlatform[] | undefined): void {\n\tsessionSupportPlatforms = platforms && platforms.length > 0 ? [...platforms] : undefined;\n}\n\n/** The session's configured targets, or undefined when `--support-platform` was not given. */\nexport function getSupportPlatforms(): MarketplacePlatform[] | undefined {\n\treturn sessionSupportPlatforms ? [...sessionSupportPlatforms] : undefined;\n}\n\n/**\n * Resolve the platforms an authoring write should target: an explicit per-call\n * selection wins, then the session's `--support-platform` targets, then\n * {@link DEFAULT_AUTHORING_PLATFORMS}.\n */\nexport function resolveAuthoringPlatforms(explicit?: readonly MarketplacePlatform[]): MarketplacePlatform[] {\n\tif (explicit && explicit.length > 0) return [...explicit];\n\treturn [...(sessionSupportPlatforms ?? DEFAULT_AUTHORING_PLATFORMS)];\n}\n"]}
|
|
@@ -17,8 +17,14 @@
|
|
|
17
17
|
* platform vocabulary and the adapters stay a one-directory concern: adding a
|
|
18
18
|
* vendor means a new adapter file plus a token here, nothing else.
|
|
19
19
|
*/
|
|
20
|
-
/**
|
|
21
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Default authoring target when neither the call nor the session picked any: the
|
|
22
|
+
* portable native format. Authored artifacts are meant to be reusable, so they
|
|
23
|
+
* default to one vendor-neutral layout (a strict superset hoocode reads directly)
|
|
24
|
+
* rather than forking into vendor copies. Vendor layouts are an opt-in interop
|
|
25
|
+
* concern, requested only via the `--support-platform` session flag.
|
|
26
|
+
*/
|
|
27
|
+
export const DEFAULT_AUTHORING_PLATFORMS = ["agents"];
|
|
22
28
|
/** Canonicalize one platform token, folding the user-facing aliases. */
|
|
23
29
|
export function normalizePlatformToken(token) {
|
|
24
30
|
switch (token.trim().toLowerCase()) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-targets.js","sourceRoot":"","sources":["../../../../../src/core/extensions/plugins/formats/platform-targets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAIH
|
|
1
|
+
{"version":3,"file":"platform-targets.js","sourceRoot":"","sources":["../../../../../src/core/extensions/plugins/formats/platform-targets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAIH;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAmC,CAAC,QAAQ,CAAC,CAAC;AAEtF,wEAAwE;AACxE,MAAM,UAAU,sBAAsB,CAAC,KAAa,EAAmC;IACtF,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC;QACpC,KAAK,QAAQ,CAAC;QACd,KAAK,QAAQ;YACZ,OAAO,QAAQ,CAAC;QACjB,KAAK,QAAQ;YACZ,OAAO,QAAQ,CAAC;QACjB,KAAK,QAAQ,CAAC;QACd,KAAK,SAAS,CAAC;QACf,KAAK,IAAI;YACR,OAAO,QAAQ,CAAC;QACjB;YACC,OAAO,SAAS,CAAC;IACnB,CAAC;AAAA,CACD;AASD,0FAA0F;AAC1F,MAAM,UAAU,qBAAqB,CAAC,MAAyB,EAAwB;IACtF,MAAM,SAAS,GAA0B,EAAE,CAAC;IAC5C,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC5B,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,OAAO;YAAE,SAAS;QACvB,MAAM,SAAS,GAAG,sBAAsB,CAAC,OAAO,CAAC,CAAC;QAClD,IAAI,CAAC,SAAS;YAAE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;aACjC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC;YAAE,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC;AAAA,CAC9B;AAED,gFAAgF;AAChF,IAAI,uBAA0D,CAAC;AAE/D,oFAAoF;AACpF,MAAM,UAAU,mBAAmB,CAAC,SAAqD,EAAQ;IAChG,uBAAuB,GAAG,SAAS,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CACzF;AAED,8FAA8F;AAC9F,MAAM,UAAU,mBAAmB,GAAsC;IACxE,OAAO,uBAAuB,CAAC,CAAC,CAAC,CAAC,GAAG,uBAAuB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAC1E;AAED;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CAAC,QAAyC,EAAyB;IAC3G,IAAI,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC;IAC1D,OAAO,CAAC,GAAG,CAAC,uBAAuB,IAAI,2BAA2B,CAAC,CAAC,CAAC;AAAA,CACrE","sourcesContent":["/**\n * Session-wide artifact platform targeting (`--support-platform`).\n *\n * hoocode reads resources from every vendor convention, but when it *writes*\n * artifacts — authored plugins via ProposePlugin, workspace scaffolds via\n * /new-skill //new-agent //new-command — it needs a target layout. This module\n * owns that choice for the whole process:\n *\n * token vocabulary `agents` (alias `native`), `claude`,\n * `github` (aliases `copilot`, `gh`)\n * session state set once at startup from the `--support-platform` flag\n * or the `supportPlatform` setting (main.ts)\n * resolution explicit per-call platforms → session targets →\n * {@link DEFAULT_AUTHORING_PLATFORMS}\n *\n * Kept beside the format registry (and importing only `types.ts`) so the\n * platform vocabulary and the adapters stay a one-directory concern: adding a\n * vendor means a new adapter file plus a token here, nothing else.\n */\n\nimport type { MarketplacePlatform } from \"./types.js\";\n\n/**\n * Default authoring target when neither the call nor the session picked any: the\n * portable native format. Authored artifacts are meant to be reusable, so they\n * default to one vendor-neutral layout (a strict superset hoocode reads directly)\n * rather than forking into vendor copies. Vendor layouts are an opt-in interop\n * concern, requested only via the `--support-platform` session flag.\n */\nexport const DEFAULT_AUTHORING_PLATFORMS: readonly MarketplacePlatform[] = [\"agents\"];\n\n/** Canonicalize one platform token, folding the user-facing aliases. */\nexport function normalizePlatformToken(token: string): MarketplacePlatform | undefined {\n\tswitch (token.trim().toLowerCase()) {\n\t\tcase \"agents\":\n\t\tcase \"native\":\n\t\t\treturn \"agents\";\n\t\tcase \"claude\":\n\t\t\treturn \"claude\";\n\t\tcase \"github\":\n\t\tcase \"copilot\":\n\t\tcase \"gh\":\n\t\t\treturn \"github\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nexport interface SupportPlatformParse {\n\t/** Canonical platforms, deduped, in the order first mentioned. */\n\tplatforms: MarketplacePlatform[];\n\t/** Tokens that matched no known platform (surfaced as diagnostics, never fatal). */\n\tinvalid: string[];\n}\n\n/** Parse raw `--support-platform` / `supportPlatform` tokens into canonical platforms. */\nexport function parseSupportPlatforms(tokens: readonly string[]): SupportPlatformParse {\n\tconst platforms: MarketplacePlatform[] = [];\n\tconst invalid: string[] = [];\n\tfor (const token of tokens) {\n\t\tconst trimmed = token.trim();\n\t\tif (!trimmed) continue;\n\t\tconst canonical = normalizePlatformToken(trimmed);\n\t\tif (!canonical) invalid.push(trimmed);\n\t\telse if (!platforms.includes(canonical)) platforms.push(canonical);\n\t}\n\treturn { platforms, invalid };\n}\n\n/** Session-wide targets. Undefined = not configured (fall back to defaults). */\nlet sessionSupportPlatforms: MarketplacePlatform[] | undefined;\n\n/** Set (or clear, with undefined/empty) the session's artifact platform targets. */\nexport function setSupportPlatforms(platforms: readonly MarketplacePlatform[] | undefined): void {\n\tsessionSupportPlatforms = platforms && platforms.length > 0 ? [...platforms] : undefined;\n}\n\n/** The session's configured targets, or undefined when `--support-platform` was not given. */\nexport function getSupportPlatforms(): MarketplacePlatform[] | undefined {\n\treturn sessionSupportPlatforms ? [...sessionSupportPlatforms] : undefined;\n}\n\n/**\n * Resolve the platforms an authoring write should target: an explicit per-call\n * selection wins, then the session's `--support-platform` targets, then\n * {@link DEFAULT_AUTHORING_PLATFORMS}.\n */\nexport function resolveAuthoringPlatforms(explicit?: readonly MarketplacePlatform[]): MarketplacePlatform[] {\n\tif (explicit && explicit.length > 0) return [...explicit];\n\treturn [...(sessionSupportPlatforms ?? DEFAULT_AUTHORING_PLATFORMS)];\n}\n"]}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Light mode — a minimal, low-token preset for small/local models.
|
|
3
|
+
*
|
|
4
|
+
* The preset restricts the session to the four core tools (read, write, edit,
|
|
5
|
+
* bash) with shortened descriptions and undocumented parameter schemas,
|
|
6
|
+
* replaces the default system prompt with a terse one, and disables
|
|
7
|
+
* subagents, TodoWrite, skills, context files, and the mode-prompt appendix.
|
|
8
|
+
* The goal is the smallest possible fixed per-turn surface (system prompt +
|
|
9
|
+
* serialized tool schemas) so weak tool-callers waste no context on harness
|
|
10
|
+
* boilerplate. bash subsumes grep/find/ls: search happens via the shell.
|
|
11
|
+
*/
|
|
12
|
+
import type { AgentTool } from "@kolisachint/hoocode-agent-core";
|
|
13
|
+
import type { ToolInfo } from "./extensions/types.js";
|
|
14
|
+
/** The only tools a light session exposes. */
|
|
15
|
+
export declare const LIGHT_TOOL_NAMES: readonly ["read", "write", "edit", "bash"];
|
|
16
|
+
/**
|
|
17
|
+
* Terse replacement for the default system prompt. buildSystemPrompt appends
|
|
18
|
+
* the current date and working directory; nothing else rides along because
|
|
19
|
+
* light mode also disables skills, context files, and the mode appendix.
|
|
20
|
+
*/
|
|
21
|
+
export declare const LIGHT_SYSTEM_PROMPT = "You are a coding agent. Use the tools to read, edit, and write files and run shell commands.\nSearch with bash (grep/find/ls). Prefer edit for changes; write for new files.\nBe concise. No preamble.";
|
|
22
|
+
/**
|
|
23
|
+
* Environment flag signaling light mode to code that cannot see CLI flags or
|
|
24
|
+
* settings — notably the hoo-core modes extension, which reads it to skip the
|
|
25
|
+
* `<!-- hoo-core: mode= -->` system-prompt appendix. Same pattern as
|
|
26
|
+
* WARM_SUBAGENTS_ENV / SUBAGENT_MAX_DEPTH_ENV.
|
|
27
|
+
*/
|
|
28
|
+
export declare const LIGHT_MODE_ENV = "HOOCODE_LIGHT";
|
|
29
|
+
/** Whether light mode was signaled through the environment. */
|
|
30
|
+
export declare function isLightModeEnv(): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Build the four light tools for `baseToolsOverride`: the real tool
|
|
33
|
+
* implementations wearing short descriptions and stripped parameter schemas.
|
|
34
|
+
*/
|
|
35
|
+
export declare function createLightTools(cwd: string): Record<string, AgentTool>;
|
|
36
|
+
/** Token breakdown of a session's fixed per-turn surface. */
|
|
37
|
+
export interface PromptSurface {
|
|
38
|
+
/** Estimated tokens in the assembled system prompt. */
|
|
39
|
+
systemPromptTokens: number;
|
|
40
|
+
/** Estimated tokens across the serialized active tool schemas. */
|
|
41
|
+
toolSchemaTokens: number;
|
|
42
|
+
/** systemPromptTokens + toolSchemaTokens. */
|
|
43
|
+
totalTokens: number;
|
|
44
|
+
/** Per-tool breakdown of the serialized schema estimate. */
|
|
45
|
+
tools: Array<{
|
|
46
|
+
name: string;
|
|
47
|
+
tokens: number;
|
|
48
|
+
}>;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Measure the fixed per-turn surface a session sends on every request: the
|
|
52
|
+
* assembled system prompt plus the serialized schemas (name, description,
|
|
53
|
+
* parameters) of the active tools. Providers add their own envelope on top,
|
|
54
|
+
* so treat the result as a floor estimate.
|
|
55
|
+
*/
|
|
56
|
+
export declare function measurePromptSurface(session: {
|
|
57
|
+
systemPrompt: string;
|
|
58
|
+
getActiveToolNames(): string[];
|
|
59
|
+
getAllTools(): ToolInfo[];
|
|
60
|
+
}): PromptSurface;
|
|
61
|
+
//# sourceMappingURL=light.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"light.d.ts","sourceRoot":"","sources":["../../src/core/light.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAEjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAGtD,8CAA8C;AAC9C,eAAO,MAAM,gBAAgB,4CAA6C,CAAC;AAE3E;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,2MAEP,CAAC;AAE1B;;;;;GAKG;AACH,eAAO,MAAM,cAAc,kBAAkB,CAAC;AAE9C,+DAA+D;AAC/D,wBAAgB,cAAc,IAAI,OAAO,CAExC;AA4BD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAgDvE;AAED,6DAA6D;AAC7D,MAAM,WAAW,aAAa;IAC7B,uDAAuD;IACvD,kBAAkB,EAAE,MAAM,CAAC;IAC3B,kEAAkE;IAClE,gBAAgB,EAAE,MAAM,CAAC;IACzB,6CAA6C;IAC7C,WAAW,EAAE,MAAM,CAAC;IACpB,4DAA4D;IAC5D,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC/C;AAOD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE;IAC7C,YAAY,EAAE,MAAM,CAAC;IACrB,kBAAkB,IAAI,MAAM,EAAE,CAAC;IAC/B,WAAW,IAAI,QAAQ,EAAE,CAAC;CAC1B,GAAG,aAAa,CAmBhB","sourcesContent":["/**\n * Light mode — a minimal, low-token preset for small/local models.\n *\n * The preset restricts the session to the four core tools (read, write, edit,\n * bash) with shortened descriptions and undocumented parameter schemas,\n * replaces the default system prompt with a terse one, and disables\n * subagents, TodoWrite, skills, context files, and the mode-prompt appendix.\n * The goal is the smallest possible fixed per-turn surface (system prompt +\n * serialized tool schemas) so weak tool-callers waste no context on harness\n * boilerplate. bash subsumes grep/find/ls: search happens via the shell.\n */\n\nimport type { AgentTool } from \"@kolisachint/hoocode-agent-core\";\nimport { Type } from \"typebox\";\nimport type { ToolInfo } from \"./extensions/types.js\";\nimport { createBashTool, createEditTool, createReadTool, createWriteTool } from \"./tools/index.js\";\n\n/** The only tools a light session exposes. */\nexport const LIGHT_TOOL_NAMES = [\"read\", \"write\", \"edit\", \"bash\"] as const;\n\n/**\n * Terse replacement for the default system prompt. buildSystemPrompt appends\n * the current date and working directory; nothing else rides along because\n * light mode also disables skills, context files, and the mode appendix.\n */\nexport const LIGHT_SYSTEM_PROMPT = `You are a coding agent. Use the tools to read, edit, and write files and run shell commands.\nSearch with bash (grep/find/ls). Prefer edit for changes; write for new files.\nBe concise. No preamble.`;\n\n/**\n * Environment flag signaling light mode to code that cannot see CLI flags or\n * settings — notably the hoo-core modes extension, which reads it to skip the\n * `<!-- hoo-core: mode= -->` system-prompt appendix. Same pattern as\n * WARM_SUBAGENTS_ENV / SUBAGENT_MAX_DEPTH_ENV.\n */\nexport const LIGHT_MODE_ENV = \"HOOCODE_LIGHT\";\n\n/** Whether light mode was signaled through the environment. */\nexport function isLightModeEnv(): boolean {\n\treturn process.env[LIGHT_MODE_ENV] === \"1\";\n}\n\n// Light parameter schemas: same shapes the real tools accept, minus the\n// per-property descriptions (that is where most schema tokens live).\nconst lightReadSchema = Type.Object({\n\tpath: Type.String(),\n\toffset: Type.Optional(Type.Number()),\n\tlimit: Type.Optional(Type.Number()),\n});\n\nconst lightWriteSchema = Type.Object({\n\tpath: Type.String(),\n\tcontent: Type.String(),\n});\n\n// Flat single-replacement shape instead of the full edits[] batch schema. The\n// execute shim below converts it to the batch form the real edit tool expects.\nconst lightEditSchema = Type.Object({\n\tpath: Type.String(),\n\toldText: Type.String(),\n\tnewText: Type.String(),\n});\n\nconst lightBashSchema = Type.Object({\n\tcommand: Type.String(),\n\ttimeout: Type.Optional(Type.Number()),\n});\n\n/**\n * Build the four light tools for `baseToolsOverride`: the real tool\n * implementations wearing short descriptions and stripped parameter schemas.\n */\nexport function createLightTools(cwd: string): Record<string, AgentTool> {\n\tconst read = createReadTool(cwd);\n\tconst write = createWriteTool(cwd);\n\tconst edit = createEditTool(cwd);\n\tconst bash = createBashTool(cwd);\n\n\tconst lightRead: AgentTool<typeof lightReadSchema> = {\n\t\t...read,\n\t\tdescription: \"Read a file. args: path, offset?, limit?\",\n\t\tparameters: lightReadSchema,\n\t};\n\n\tconst lightWrite: AgentTool<typeof lightWriteSchema> = {\n\t\t...write,\n\t\tdescription: \"Write file (overwrites). args: path, content\",\n\t\tparameters: lightWriteSchema,\n\t};\n\n\t// The real edit tool validates against its edits[] schema after\n\t// prepareArguments runs, so the flat light shape must skip the original\n\t// prepareArguments (validation sees the raw flat args against the flat\n\t// schema) and convert to the batch form at execute time instead.\n\tconst lightEdit: AgentTool<typeof lightEditSchema> = {\n\t\t...edit,\n\t\tdescription: \"Replace exact text. args: path, oldText, newText\",\n\t\tparameters: lightEditSchema,\n\t\tprepareArguments: undefined,\n\t\texecute: (toolCallId, params, signal, onUpdate) =>\n\t\t\tedit.execute(\n\t\t\t\ttoolCallId,\n\t\t\t\t{ path: params.path, edits: [{ oldText: params.oldText, newText: params.newText }] },\n\t\t\t\tsignal,\n\t\t\t\tonUpdate,\n\t\t\t),\n\t};\n\n\tconst lightBash: AgentTool<typeof lightBashSchema> = {\n\t\t...bash,\n\t\tdescription: \"Run a shell command. args: command, timeout?\",\n\t\tparameters: lightBashSchema,\n\t};\n\n\treturn {\n\t\tread: lightRead as AgentTool,\n\t\twrite: lightWrite as AgentTool,\n\t\tedit: lightEdit as AgentTool,\n\t\tbash: lightBash as AgentTool,\n\t};\n}\n\n/** Token breakdown of a session's fixed per-turn surface. */\nexport interface PromptSurface {\n\t/** Estimated tokens in the assembled system prompt. */\n\tsystemPromptTokens: number;\n\t/** Estimated tokens across the serialized active tool schemas. */\n\ttoolSchemaTokens: number;\n\t/** systemPromptTokens + toolSchemaTokens. */\n\ttotalTokens: number;\n\t/** Per-tool breakdown of the serialized schema estimate. */\n\ttools: Array<{ name: string; tokens: number }>;\n}\n\n/** Same conservative chars/4 heuristic the agent harness uses for context estimates. */\nfunction estimateStringTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\n/**\n * Measure the fixed per-turn surface a session sends on every request: the\n * assembled system prompt plus the serialized schemas (name, description,\n * parameters) of the active tools. Providers add their own envelope on top,\n * so treat the result as a floor estimate.\n */\nexport function measurePromptSurface(session: {\n\tsystemPrompt: string;\n\tgetActiveToolNames(): string[];\n\tgetAllTools(): ToolInfo[];\n}): PromptSurface {\n\tconst activeNames = new Set(session.getActiveToolNames());\n\tconst tools = session\n\t\t.getAllTools()\n\t\t.filter((tool) => activeNames.has(tool.name))\n\t\t.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\ttokens: estimateStringTokens(\n\t\t\t\tJSON.stringify({ name: tool.name, description: tool.description, parameters: tool.parameters }),\n\t\t\t),\n\t\t}));\n\tconst systemPromptTokens = estimateStringTokens(session.systemPrompt);\n\tconst toolSchemaTokens = tools.reduce((sum, tool) => sum + tool.tokens, 0);\n\treturn {\n\t\tsystemPromptTokens,\n\t\ttoolSchemaTokens,\n\t\ttotalTokens: systemPromptTokens + toolSchemaTokens,\n\t\ttools,\n\t};\n}\n"]}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Light mode — a minimal, low-token preset for small/local models.
|
|
3
|
+
*
|
|
4
|
+
* The preset restricts the session to the four core tools (read, write, edit,
|
|
5
|
+
* bash) with shortened descriptions and undocumented parameter schemas,
|
|
6
|
+
* replaces the default system prompt with a terse one, and disables
|
|
7
|
+
* subagents, TodoWrite, skills, context files, and the mode-prompt appendix.
|
|
8
|
+
* The goal is the smallest possible fixed per-turn surface (system prompt +
|
|
9
|
+
* serialized tool schemas) so weak tool-callers waste no context on harness
|
|
10
|
+
* boilerplate. bash subsumes grep/find/ls: search happens via the shell.
|
|
11
|
+
*/
|
|
12
|
+
import { Type } from "typebox";
|
|
13
|
+
import { createBashTool, createEditTool, createReadTool, createWriteTool } from "./tools/index.js";
|
|
14
|
+
/** The only tools a light session exposes. */
|
|
15
|
+
export const LIGHT_TOOL_NAMES = ["read", "write", "edit", "bash"];
|
|
16
|
+
/**
|
|
17
|
+
* Terse replacement for the default system prompt. buildSystemPrompt appends
|
|
18
|
+
* the current date and working directory; nothing else rides along because
|
|
19
|
+
* light mode also disables skills, context files, and the mode appendix.
|
|
20
|
+
*/
|
|
21
|
+
export const LIGHT_SYSTEM_PROMPT = `You are a coding agent. Use the tools to read, edit, and write files and run shell commands.
|
|
22
|
+
Search with bash (grep/find/ls). Prefer edit for changes; write for new files.
|
|
23
|
+
Be concise. No preamble.`;
|
|
24
|
+
/**
|
|
25
|
+
* Environment flag signaling light mode to code that cannot see CLI flags or
|
|
26
|
+
* settings — notably the hoo-core modes extension, which reads it to skip the
|
|
27
|
+
* `<!-- hoo-core: mode= -->` system-prompt appendix. Same pattern as
|
|
28
|
+
* WARM_SUBAGENTS_ENV / SUBAGENT_MAX_DEPTH_ENV.
|
|
29
|
+
*/
|
|
30
|
+
export const LIGHT_MODE_ENV = "HOOCODE_LIGHT";
|
|
31
|
+
/** Whether light mode was signaled through the environment. */
|
|
32
|
+
export function isLightModeEnv() {
|
|
33
|
+
return process.env[LIGHT_MODE_ENV] === "1";
|
|
34
|
+
}
|
|
35
|
+
// Light parameter schemas: same shapes the real tools accept, minus the
|
|
36
|
+
// per-property descriptions (that is where most schema tokens live).
|
|
37
|
+
const lightReadSchema = Type.Object({
|
|
38
|
+
path: Type.String(),
|
|
39
|
+
offset: Type.Optional(Type.Number()),
|
|
40
|
+
limit: Type.Optional(Type.Number()),
|
|
41
|
+
});
|
|
42
|
+
const lightWriteSchema = Type.Object({
|
|
43
|
+
path: Type.String(),
|
|
44
|
+
content: Type.String(),
|
|
45
|
+
});
|
|
46
|
+
// Flat single-replacement shape instead of the full edits[] batch schema. The
|
|
47
|
+
// execute shim below converts it to the batch form the real edit tool expects.
|
|
48
|
+
const lightEditSchema = Type.Object({
|
|
49
|
+
path: Type.String(),
|
|
50
|
+
oldText: Type.String(),
|
|
51
|
+
newText: Type.String(),
|
|
52
|
+
});
|
|
53
|
+
const lightBashSchema = Type.Object({
|
|
54
|
+
command: Type.String(),
|
|
55
|
+
timeout: Type.Optional(Type.Number()),
|
|
56
|
+
});
|
|
57
|
+
/**
|
|
58
|
+
* Build the four light tools for `baseToolsOverride`: the real tool
|
|
59
|
+
* implementations wearing short descriptions and stripped parameter schemas.
|
|
60
|
+
*/
|
|
61
|
+
export function createLightTools(cwd) {
|
|
62
|
+
const read = createReadTool(cwd);
|
|
63
|
+
const write = createWriteTool(cwd);
|
|
64
|
+
const edit = createEditTool(cwd);
|
|
65
|
+
const bash = createBashTool(cwd);
|
|
66
|
+
const lightRead = {
|
|
67
|
+
...read,
|
|
68
|
+
description: "Read a file. args: path, offset?, limit?",
|
|
69
|
+
parameters: lightReadSchema,
|
|
70
|
+
};
|
|
71
|
+
const lightWrite = {
|
|
72
|
+
...write,
|
|
73
|
+
description: "Write file (overwrites). args: path, content",
|
|
74
|
+
parameters: lightWriteSchema,
|
|
75
|
+
};
|
|
76
|
+
// The real edit tool validates against its edits[] schema after
|
|
77
|
+
// prepareArguments runs, so the flat light shape must skip the original
|
|
78
|
+
// prepareArguments (validation sees the raw flat args against the flat
|
|
79
|
+
// schema) and convert to the batch form at execute time instead.
|
|
80
|
+
const lightEdit = {
|
|
81
|
+
...edit,
|
|
82
|
+
description: "Replace exact text. args: path, oldText, newText",
|
|
83
|
+
parameters: lightEditSchema,
|
|
84
|
+
prepareArguments: undefined,
|
|
85
|
+
execute: (toolCallId, params, signal, onUpdate) => edit.execute(toolCallId, { path: params.path, edits: [{ oldText: params.oldText, newText: params.newText }] }, signal, onUpdate),
|
|
86
|
+
};
|
|
87
|
+
const lightBash = {
|
|
88
|
+
...bash,
|
|
89
|
+
description: "Run a shell command. args: command, timeout?",
|
|
90
|
+
parameters: lightBashSchema,
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
read: lightRead,
|
|
94
|
+
write: lightWrite,
|
|
95
|
+
edit: lightEdit,
|
|
96
|
+
bash: lightBash,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** Same conservative chars/4 heuristic the agent harness uses for context estimates. */
|
|
100
|
+
function estimateStringTokens(text) {
|
|
101
|
+
return Math.ceil(text.length / 4);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Measure the fixed per-turn surface a session sends on every request: the
|
|
105
|
+
* assembled system prompt plus the serialized schemas (name, description,
|
|
106
|
+
* parameters) of the active tools. Providers add their own envelope on top,
|
|
107
|
+
* so treat the result as a floor estimate.
|
|
108
|
+
*/
|
|
109
|
+
export function measurePromptSurface(session) {
|
|
110
|
+
const activeNames = new Set(session.getActiveToolNames());
|
|
111
|
+
const tools = session
|
|
112
|
+
.getAllTools()
|
|
113
|
+
.filter((tool) => activeNames.has(tool.name))
|
|
114
|
+
.map((tool) => ({
|
|
115
|
+
name: tool.name,
|
|
116
|
+
tokens: estimateStringTokens(JSON.stringify({ name: tool.name, description: tool.description, parameters: tool.parameters })),
|
|
117
|
+
}));
|
|
118
|
+
const systemPromptTokens = estimateStringTokens(session.systemPrompt);
|
|
119
|
+
const toolSchemaTokens = tools.reduce((sum, tool) => sum + tool.tokens, 0);
|
|
120
|
+
return {
|
|
121
|
+
systemPromptTokens,
|
|
122
|
+
toolSchemaTokens,
|
|
123
|
+
totalTokens: systemPromptTokens + toolSchemaTokens,
|
|
124
|
+
tools,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
//# sourceMappingURL=light.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"light.js","sourceRoot":"","sources":["../../src/core/light.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE/B,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnG,8CAA8C;AAC9C,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAU,CAAC;AAE3E;;;;GAIG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;;yBAEV,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,eAAe,CAAC;AAE9C,+DAA+D;AAC/D,MAAM,UAAU,cAAc,GAAY;IACzC,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,KAAK,GAAG,CAAC;AAAA,CAC3C;AAED,wEAAwE;AACxE,qEAAqE;AACrE,MAAM,eAAe,GAAG,IAAI,CAAC,MAAM,CAAC;IACnC,IAAI,EAAE,IAAI,CAAC,MAAM,EAAE;IACnB,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;IACpC,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;CACnC,CAAC,CAAC;AAEH,MAAM,gBAAgB,GAAG,IAAI,CAAC,MAAM,CAAC;IACpC,IAAI,EAAE,IAAI,CAAC,MAAM,EAAE;IACnB,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE;CACtB,CAAC,C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AG,KAAK,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IAC3E,OAAO;QACN,kBAAkB;QAClB,gBAAgB;QAChB,WAAW,EAAE,kBAAkB,GAAG,gBAAgB;QAClD,KAAK;KACL,CAAC;AAAA,CACF","sourcesContent":["/**\n * Light mode — a minimal, low-token preset for small/local models.\n *\n * The preset restricts the session to the four core tools (read, write, edit,\n * bash) with shortened descriptions and undocumented parameter schemas,\n * replaces the default system prompt with a terse one, and disables\n * subagents, TodoWrite, skills, context files, and the mode-prompt appendix.\n * The goal is the smallest possible fixed per-turn surface (system prompt +\n * serialized tool schemas) so weak tool-callers waste no context on harness\n * boilerplate. bash subsumes grep/find/ls: search happens via the shell.\n */\n\nimport type { AgentTool } from \"@kolisachint/hoocode-agent-core\";\nimport { Type } from \"typebox\";\nimport type { ToolInfo } from \"./extensions/types.js\";\nimport { createBashTool, createEditTool, createReadTool, createWriteTool } from \"./tools/index.js\";\n\n/** The only tools a light session exposes. */\nexport const LIGHT_TOOL_NAMES = [\"read\", \"write\", \"edit\", \"bash\"] as const;\n\n/**\n * Terse replacement for the default system prompt. buildSystemPrompt appends\n * the current date and working directory; nothing else rides along because\n * light mode also disables skills, context files, and the mode appendix.\n */\nexport const LIGHT_SYSTEM_PROMPT = `You are a coding agent. Use the tools to read, edit, and write files and run shell commands.\nSearch with bash (grep/find/ls). Prefer edit for changes; write for new files.\nBe concise. No preamble.`;\n\n/**\n * Environment flag signaling light mode to code that cannot see CLI flags or\n * settings — notably the hoo-core modes extension, which reads it to skip the\n * `<!-- hoo-core: mode= -->` system-prompt appendix. Same pattern as\n * WARM_SUBAGENTS_ENV / SUBAGENT_MAX_DEPTH_ENV.\n */\nexport const LIGHT_MODE_ENV = \"HOOCODE_LIGHT\";\n\n/** Whether light mode was signaled through the environment. */\nexport function isLightModeEnv(): boolean {\n\treturn process.env[LIGHT_MODE_ENV] === \"1\";\n}\n\n// Light parameter schemas: same shapes the real tools accept, minus the\n// per-property descriptions (that is where most schema tokens live).\nconst lightReadSchema = Type.Object({\n\tpath: Type.String(),\n\toffset: Type.Optional(Type.Number()),\n\tlimit: Type.Optional(Type.Number()),\n});\n\nconst lightWriteSchema = Type.Object({\n\tpath: Type.String(),\n\tcontent: Type.String(),\n});\n\n// Flat single-replacement shape instead of the full edits[] batch schema. The\n// execute shim below converts it to the batch form the real edit tool expects.\nconst lightEditSchema = Type.Object({\n\tpath: Type.String(),\n\toldText: Type.String(),\n\tnewText: Type.String(),\n});\n\nconst lightBashSchema = Type.Object({\n\tcommand: Type.String(),\n\ttimeout: Type.Optional(Type.Number()),\n});\n\n/**\n * Build the four light tools for `baseToolsOverride`: the real tool\n * implementations wearing short descriptions and stripped parameter schemas.\n */\nexport function createLightTools(cwd: string): Record<string, AgentTool> {\n\tconst read = createReadTool(cwd);\n\tconst write = createWriteTool(cwd);\n\tconst edit = createEditTool(cwd);\n\tconst bash = createBashTool(cwd);\n\n\tconst lightRead: AgentTool<typeof lightReadSchema> = {\n\t\t...read,\n\t\tdescription: \"Read a file. args: path, offset?, limit?\",\n\t\tparameters: lightReadSchema,\n\t};\n\n\tconst lightWrite: AgentTool<typeof lightWriteSchema> = {\n\t\t...write,\n\t\tdescription: \"Write file (overwrites). args: path, content\",\n\t\tparameters: lightWriteSchema,\n\t};\n\n\t// The real edit tool validates against its edits[] schema after\n\t// prepareArguments runs, so the flat light shape must skip the original\n\t// prepareArguments (validation sees the raw flat args against the flat\n\t// schema) and convert to the batch form at execute time instead.\n\tconst lightEdit: AgentTool<typeof lightEditSchema> = {\n\t\t...edit,\n\t\tdescription: \"Replace exact text. args: path, oldText, newText\",\n\t\tparameters: lightEditSchema,\n\t\tprepareArguments: undefined,\n\t\texecute: (toolCallId, params, signal, onUpdate) =>\n\t\t\tedit.execute(\n\t\t\t\ttoolCallId,\n\t\t\t\t{ path: params.path, edits: [{ oldText: params.oldText, newText: params.newText }] },\n\t\t\t\tsignal,\n\t\t\t\tonUpdate,\n\t\t\t),\n\t};\n\n\tconst lightBash: AgentTool<typeof lightBashSchema> = {\n\t\t...bash,\n\t\tdescription: \"Run a shell command. args: command, timeout?\",\n\t\tparameters: lightBashSchema,\n\t};\n\n\treturn {\n\t\tread: lightRead as AgentTool,\n\t\twrite: lightWrite as AgentTool,\n\t\tedit: lightEdit as AgentTool,\n\t\tbash: lightBash as AgentTool,\n\t};\n}\n\n/** Token breakdown of a session's fixed per-turn surface. */\nexport interface PromptSurface {\n\t/** Estimated tokens in the assembled system prompt. */\n\tsystemPromptTokens: number;\n\t/** Estimated tokens across the serialized active tool schemas. */\n\ttoolSchemaTokens: number;\n\t/** systemPromptTokens + toolSchemaTokens. */\n\ttotalTokens: number;\n\t/** Per-tool breakdown of the serialized schema estimate. */\n\ttools: Array<{ name: string; tokens: number }>;\n}\n\n/** Same conservative chars/4 heuristic the agent harness uses for context estimates. */\nfunction estimateStringTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\n/**\n * Measure the fixed per-turn surface a session sends on every request: the\n * assembled system prompt plus the serialized schemas (name, description,\n * parameters) of the active tools. Providers add their own envelope on top,\n * so treat the result as a floor estimate.\n */\nexport function measurePromptSurface(session: {\n\tsystemPrompt: string;\n\tgetActiveToolNames(): string[];\n\tgetAllTools(): ToolInfo[];\n}): PromptSurface {\n\tconst activeNames = new Set(session.getActiveToolNames());\n\tconst tools = session\n\t\t.getAllTools()\n\t\t.filter((tool) => activeNames.has(tool.name))\n\t\t.map((tool) => ({\n\t\t\tname: tool.name,\n\t\t\ttokens: estimateStringTokens(\n\t\t\t\tJSON.stringify({ name: tool.name, description: tool.description, parameters: tool.parameters }),\n\t\t\t),\n\t\t}));\n\tconst systemPromptTokens = estimateStringTokens(session.systemPrompt);\n\tconst toolSchemaTokens = tools.reduce((sum, tool) => sum + tool.tokens, 0);\n\treturn {\n\t\tsystemPromptTokens,\n\t\ttoolSchemaTokens,\n\t\ttotalTokens: systemPromptTokens + toolSchemaTokens,\n\t\ttools,\n\t};\n}\n"]}
|
package/dist/core/sdk.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ThinkingLevel } from "@kolisachint/hoocode-agent-core";
|
|
1
|
+
import { type AgentTool, type ThinkingLevel } from "@kolisachint/hoocode-agent-core";
|
|
2
2
|
import { type Model } from "@kolisachint/hoocode-ai";
|
|
3
3
|
import { AgentSession } from "./agent-session.js";
|
|
4
4
|
import { AuthStorage } from "./auth-storage.js";
|
|
@@ -72,6 +72,12 @@ export interface CreateAgentSessionOptions {
|
|
|
72
72
|
enableFileTools?: boolean;
|
|
73
73
|
/** Custom tools to register (in addition to built-in tools). */
|
|
74
74
|
customTools?: ToolDefinition[];
|
|
75
|
+
/**
|
|
76
|
+
* Replace the built-in base tools entirely (the light preset uses this to
|
|
77
|
+
* swap in short-schema read/write/edit/bash variants). Keys become the
|
|
78
|
+
* default active tool set when no explicit `tools` allowlist is provided.
|
|
79
|
+
*/
|
|
80
|
+
baseToolsOverride?: Record<string, AgentTool>;
|
|
75
81
|
/** Resource loader. When omitted, DefaultResourceLoader is used. */
|
|
76
82
|
resourceLoader?: ResourceLoader;
|
|
77
83
|
/** Session manager. Default: SessionManager.create(cwd) */
|
package/dist/core/sdk.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AACA,OAAO,EAON,KAAK,aAAa,EAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAoC,KAAK,KAAK,EAAgB,MAAM,yBAAyB,CAAC;AAErG,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;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import {\n\tAgent,\n\ttype AgentMessage,\n\tconvertToLlm,\n\tcreateBackgroundPlaceholderText,\n\tcreateBackgroundTaskMessage,\n\testimateContextTokens,\n\ttype ThinkingLevel,\n} from \"@kolisachint/hoocode-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@kolisachint/hoocode-ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { evictSupersededReads } from \"./context-gc.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { peekSubagentPool } from \"./subagent-pool-instance.js\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.hoocode/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, hoocode enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/**\n\t * Optional denylist of tool names, subtracted from whatever set is otherwise\n\t * enabled (allowlist or default). Applied to built-in, extension, and custom tools.\n\t */\n\tdisallowedTools?: string[];\n\t/**\n\t * Enable the built-in `webfetch` + `websearch` tools, which are defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list `webfetch`/`websearch` there instead). Network access is still gated\n\t * per call and filtered by `.webtoolsignore`.\n\t */\n\tenableWebTools?: boolean;\n\t/**\n\t * Enable the built-in `browser_run` + `browser_continue` tools, which drive the\n\t * `browsertools` deterministic browser engine (parent-in-the-loop). Defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list them there instead).\n\t */\n\tenableBrowserTools?: boolean;\n\t/**\n\t * Enable the built-in document tools — `DocRead`/`DocEdit`/`DocWrite` (extract\n\t * and lossless id-based editing) plus `DocScan`/`DocGrep`/`DocPeek` (the\n\t * token-sensitive discovery loop: outline, search, partial read). Defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list them there instead). They shell out to the `filetools` binary to\n\t * losslessly extract/edit structured/binary documents.\n\t */\n\tenableFileTools?: boolean;\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport type { AgentDefinition, AgentSource } from \"./agent-frontmatter.js\";\nexport { AgentRegistry, formatAgentsForPrompt, loadAgentRegistry } from \"./agent-registry.js\";\nexport * from \"./agent-session-runtime.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n): Record<string, string> | undefined {\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://github.com/kolisachint/hoocode\",\n\t\t\t\"X-OpenRouter-Title\": \"hoocode\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@kolisachint/hoocode-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [readTool, bashTool],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"];\n\t// Web tools are registered as base tools but inactive by default; opt-in adds\n\t// them to the default active set. An explicit allowlist (`tools`) takes over\n\t// fully, so callers must list them there to enable in that mode.\n\tconst optInActiveToolNames: ToolName[] = [\n\t\t...(options.enableWebTools ? [\"webfetch\", \"websearch\"] : []),\n\t\t...(options.enableBrowserTools ? [\"browser_run\", \"browser_continue\"] : []),\n\t\t...(options.enableFileTools ? [\"DocRead\", \"DocEdit\", \"DocWrite\", \"DocScan\", \"DocGrep\", \"DocPeek\"] : []),\n\t] as ToolName[];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst initialActiveToolNames: string[] = options.tools\n\t\t? [...options.tools]\n\t\t: options.noTools\n\t\t\t? []\n\t\t\t: [...defaultActiveToolNames, ...optInActiveToolNames];\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\t// Token-budget pressure for context GC: the fraction of the active model's\n\t// context window in use, measured from the real usage on the outgoing\n\t// message copy. It latches to a high-water mark so that our own evictions —\n\t// which shrink the next turn's measured usage — cannot oscillate a message\n\t// in and out of the transcript and thrash the provider's prefix cache. A\n\t// large drop (compaction, fork) resets the latch to the new, smaller size.\n\tlet budgetPressureHighWater = 0;\n\tconst getBudgetPressure = (contextMessages: AgentMessage[]): number => {\n\t\tconst contextWindow = agent.state.model?.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return 0;\n\t\tconst gauge = Math.min(estimateContextTokens(contextMessages).tokens / contextWindow, 1);\n\t\tif (gauge > budgetPressureHighWater) {\n\t\t\tbudgetPressureHighWater = gauge; // rising usage — track it\n\t\t} else if (gauge < budgetPressureHighWater - 0.15) {\n\t\t\tbudgetPressureHighWater = gauge; // context collapsed — reset the latch\n\t\t}\n\t\treturn budgetPressureHighWater;\n\t};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tcreateBackgroundResultMessage: createBackgroundTaskMessage,\n\t\tcreateBackgroundPlaceholder: (toolCall) => createBackgroundPlaceholderText(toolCall),\n\t\t// Report in-process background tool load (e.g. background MCP tools) to the\n\t\t// subagent lifeguard so it widens its heartbeat/timeout tolerance for\n\t\t// concurrently-monitored subagents. Peek (don't create) the pool: background\n\t\t// tools can run before any subagent is ever dispatched.\n\t\tonBackgroundTaskCountChange: (count) => peekSubagentPool()?.setExternalLoad(count),\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tconst transformed = runner ? await runner.emitContext(messages) : messages;\n\t\t\tif (!settingsManager.getContextGcEnabled()) return transformed;\n\t\t\treturn evictSupersededReads(transformed, { cwd, budgetPressure: getBudgetPressure(transformed) });\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tthinkingDisplay: settingsManager.getThinkingDisplay(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\tdisallowedToolNames: options.disallowedTools,\n\t\textensionRunnerRef,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AACA,OAAO,EAGN,KAAK,SAAS,EAKd,KAAK,aAAa,EAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAoC,KAAK,KAAK,EAAgB,MAAM,yBAAyB,CAAC;AAErG,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACtH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EAAwB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAIxD,OAAO,EACN,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,eAAe,EAEf,qBAAqB,EACrB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,yBAAyB;IACzC,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,yDAAyD;IACzD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,oFAAoF;IACpF,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,uFAAuF;IACvF,aAAa,CAAC,EAAE,aAAa,CAAC;IAE9B,iEAAiE;IACjE,KAAK,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,4FA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AAC;AAC9F,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACX,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACd,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EACN,qBAAqB,EAErB,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,GACZ,CAAC;AA2BF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAkQnH","sourcesContent":["import { join } from \"node:path\";\nimport {\n\tAgent,\n\ttype AgentMessage,\n\ttype AgentTool,\n\tconvertToLlm,\n\tcreateBackgroundPlaceholderText,\n\tcreateBackgroundTaskMessage,\n\testimateContextTokens,\n\ttype ThinkingLevel,\n} from \"@kolisachint/hoocode-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@kolisachint/hoocode-ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { evictSupersededReads } from \"./context-gc.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { peekSubagentPool } from \"./subagent-pool-instance.js\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.hoocode/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, hoocode enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/**\n\t * Optional denylist of tool names, subtracted from whatever set is otherwise\n\t * enabled (allowlist or default). Applied to built-in, extension, and custom tools.\n\t */\n\tdisallowedTools?: string[];\n\t/**\n\t * Enable the built-in `webfetch` + `websearch` tools, which are defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list `webfetch`/`websearch` there instead). Network access is still gated\n\t * per call and filtered by `.webtoolsignore`.\n\t */\n\tenableWebTools?: boolean;\n\t/**\n\t * Enable the built-in `browser_run` + `browser_continue` tools, which drive the\n\t * `browsertools` deterministic browser engine (parent-in-the-loop). Defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list them there instead).\n\t */\n\tenableBrowserTools?: boolean;\n\t/**\n\t * Enable the built-in document tools — `DocRead`/`DocEdit`/`DocWrite` (extract\n\t * and lossless id-based editing) plus `DocScan`/`DocGrep`/`DocPeek` (the\n\t * token-sensitive discovery loop: outline, search, partial read). Defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list them there instead). They shell out to the `filetools` binary to\n\t * losslessly extract/edit structured/binary documents.\n\t */\n\tenableFileTools?: boolean;\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\t/**\n\t * Replace the built-in base tools entirely (the light preset uses this to\n\t * swap in short-schema read/write/edit/bash variants). Keys become the\n\t * default active tool set when no explicit `tools` allowlist is provided.\n\t */\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport type { AgentDefinition, AgentSource } from \"./agent-frontmatter.js\";\nexport { AgentRegistry, formatAgentsForPrompt, loadAgentRegistry } from \"./agent-registry.js\";\nexport * from \"./agent-session-runtime.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n): Record<string, string> | undefined {\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://github.com/kolisachint/hoocode\",\n\t\t\t\"X-OpenRouter-Title\": \"hoocode\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@kolisachint/hoocode-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [readTool, bashTool],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"];\n\t// Web tools are registered as base tools but inactive by default; opt-in adds\n\t// them to the default active set. An explicit allowlist (`tools`) takes over\n\t// fully, so callers must list them there to enable in that mode.\n\tconst optInActiveToolNames: ToolName[] = [\n\t\t...(options.enableWebTools ? [\"webfetch\", \"websearch\"] : []),\n\t\t...(options.enableBrowserTools ? [\"browser_run\", \"browser_continue\"] : []),\n\t\t...(options.enableFileTools ? [\"DocRead\", \"DocEdit\", \"DocWrite\", \"DocScan\", \"DocGrep\", \"DocPeek\"] : []),\n\t] as ToolName[];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst initialActiveToolNames: string[] = options.tools\n\t\t? [...options.tools]\n\t\t: options.noTools\n\t\t\t? []\n\t\t\t: [...defaultActiveToolNames, ...optInActiveToolNames];\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\t// Token-budget pressure for context GC: the fraction of the active model's\n\t// context window in use, measured from the real usage on the outgoing\n\t// message copy. It latches to a high-water mark so that our own evictions —\n\t// which shrink the next turn's measured usage — cannot oscillate a message\n\t// in and out of the transcript and thrash the provider's prefix cache. A\n\t// large drop (compaction, fork) resets the latch to the new, smaller size.\n\tlet budgetPressureHighWater = 0;\n\tconst getBudgetPressure = (contextMessages: AgentMessage[]): number => {\n\t\tconst contextWindow = agent.state.model?.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return 0;\n\t\tconst gauge = Math.min(estimateContextTokens(contextMessages).tokens / contextWindow, 1);\n\t\tif (gauge > budgetPressureHighWater) {\n\t\t\tbudgetPressureHighWater = gauge; // rising usage — track it\n\t\t} else if (gauge < budgetPressureHighWater - 0.15) {\n\t\t\tbudgetPressureHighWater = gauge; // context collapsed — reset the latch\n\t\t}\n\t\treturn budgetPressureHighWater;\n\t};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tcreateBackgroundResultMessage: createBackgroundTaskMessage,\n\t\tcreateBackgroundPlaceholder: (toolCall) => createBackgroundPlaceholderText(toolCall),\n\t\t// Report in-process background tool load (e.g. background MCP tools) to the\n\t\t// subagent lifeguard so it widens its heartbeat/timeout tolerance for\n\t\t// concurrently-monitored subagents. Peek (don't create) the pool: background\n\t\t// tools can run before any subagent is ever dispatched.\n\t\tonBackgroundTaskCountChange: (count) => peekSubagentPool()?.setExternalLoad(count),\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tconst transformed = runner ? await runner.emitContext(messages) : messages;\n\t\t\tif (!settingsManager.getContextGcEnabled()) return transformed;\n\t\t\treturn evictSupersededReads(transformed, { cwd, budgetPressure: getBudgetPressure(transformed) });\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tthinkingDisplay: settingsManager.getThinkingDisplay(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tbaseToolsOverride: options.baseToolsOverride,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\tdisallowedToolNames: options.disallowedTools,\n\t\textensionRunnerRef,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
package/dist/core/sdk.js
CHANGED
|
@@ -296,6 +296,7 @@ export async function createAgentSession(options = {}) {
|
|
|
296
296
|
scopedModels: options.scopedModels,
|
|
297
297
|
resourceLoader,
|
|
298
298
|
customTools: options.customTools,
|
|
299
|
+
baseToolsOverride: options.baseToolsOverride,
|
|
299
300
|
modelRegistry,
|
|
300
301
|
initialActiveToolNames,
|
|
301
302
|
allowedToolNames,
|
package/dist/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Ae,CAAC,YAAY,EAAE;QACzC,eAAe,EAAE,eAAe,CAAC,kBAAkB,EAAE;QACrD,eAAe,EAAE,eAAe,CAAC,kBAAkB,EAAE;QACrD,eAAe,EAAE,eAAe,CAAC,wBAAwB,EAAE,CAAC,eAAe;KAC3E,CAAC,CAAC;IAEH,gDAAgD;IAChD,IAAI,kBAAkB,EAAE,CAAC;QACxB,KAAK,CAAC,KAAK,CAAC,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC;QAChD,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACvB,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;QACzD,CAAC;IACF,CAAC;SAAM,CAAC;QACP,2FAA2F;QAC3F,IAAI,KAAK,EAAE,CAAC;YACX,cAAc,CAAC,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;QAC5D,CAAC;QACD,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;IACzD,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC;QAChC,KAAK;QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,aAAa;QACb,sBAAsB;QACtB,gBAAgB;QAChB,mBAAmB,EAAE,OAAO,CAAC,eAAe;QAC5C,kBAAkB;QAClB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport {\n\tAgent,\n\ttype AgentMessage,\n\tconvertToLlm,\n\tcreateBackgroundPlaceholderText,\n\tcreateBackgroundTaskMessage,\n\testimateContextTokens,\n\ttype ThinkingLevel,\n} from \"@kolisachint/hoocode-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@kolisachint/hoocode-ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { evictSupersededReads } from \"./context-gc.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { peekSubagentPool } from \"./subagent-pool-instance.js\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.hoocode/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, hoocode enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/**\n\t * Optional denylist of tool names, subtracted from whatever set is otherwise\n\t * enabled (allowlist or default). Applied to built-in, extension, and custom tools.\n\t */\n\tdisallowedTools?: string[];\n\t/**\n\t * Enable the built-in `webfetch` + `websearch` tools, which are defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list `webfetch`/`websearch` there instead). Network access is still gated\n\t * per call and filtered by `.webtoolsignore`.\n\t */\n\tenableWebTools?: boolean;\n\t/**\n\t * Enable the built-in `browser_run` + `browser_continue` tools, which drive the\n\t * `browsertools` deterministic browser engine (parent-in-the-loop). Defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list them there instead).\n\t */\n\tenableBrowserTools?: boolean;\n\t/**\n\t * Enable the built-in document tools — `DocRead`/`DocEdit`/`DocWrite` (extract\n\t * and lossless id-based editing) plus `DocScan`/`DocGrep`/`DocPeek` (the\n\t * token-sensitive discovery loop: outline, search, partial read). Defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list them there instead). They shell out to the `filetools` binary to\n\t * losslessly extract/edit structured/binary documents.\n\t */\n\tenableFileTools?: boolean;\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport type { AgentDefinition, AgentSource } from \"./agent-frontmatter.js\";\nexport { AgentRegistry, formatAgentsForPrompt, loadAgentRegistry } from \"./agent-registry.js\";\nexport * from \"./agent-session-runtime.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n): Record<string, string> | undefined {\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://github.com/kolisachint/hoocode\",\n\t\t\t\"X-OpenRouter-Title\": \"hoocode\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@kolisachint/hoocode-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [readTool, bashTool],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"];\n\t// Web tools are registered as base tools but inactive by default; opt-in adds\n\t// them to the default active set. An explicit allowlist (`tools`) takes over\n\t// fully, so callers must list them there to enable in that mode.\n\tconst optInActiveToolNames: ToolName[] = [\n\t\t...(options.enableWebTools ? [\"webfetch\", \"websearch\"] : []),\n\t\t...(options.enableBrowserTools ? [\"browser_run\", \"browser_continue\"] : []),\n\t\t...(options.enableFileTools ? [\"DocRead\", \"DocEdit\", \"DocWrite\", \"DocScan\", \"DocGrep\", \"DocPeek\"] : []),\n\t] as ToolName[];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst initialActiveToolNames: string[] = options.tools\n\t\t? [...options.tools]\n\t\t: options.noTools\n\t\t\t? []\n\t\t\t: [...defaultActiveToolNames, ...optInActiveToolNames];\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\t// Token-budget pressure for context GC: the fraction of the active model's\n\t// context window in use, measured from the real usage on the outgoing\n\t// message copy. It latches to a high-water mark so that our own evictions —\n\t// which shrink the next turn's measured usage — cannot oscillate a message\n\t// in and out of the transcript and thrash the provider's prefix cache. A\n\t// large drop (compaction, fork) resets the latch to the new, smaller size.\n\tlet budgetPressureHighWater = 0;\n\tconst getBudgetPressure = (contextMessages: AgentMessage[]): number => {\n\t\tconst contextWindow = agent.state.model?.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return 0;\n\t\tconst gauge = Math.min(estimateContextTokens(contextMessages).tokens / contextWindow, 1);\n\t\tif (gauge > budgetPressureHighWater) {\n\t\t\tbudgetPressureHighWater = gauge; // rising usage — track it\n\t\t} else if (gauge < budgetPressureHighWater - 0.15) {\n\t\t\tbudgetPressureHighWater = gauge; // context collapsed — reset the latch\n\t\t}\n\t\treturn budgetPressureHighWater;\n\t};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tcreateBackgroundResultMessage: createBackgroundTaskMessage,\n\t\tcreateBackgroundPlaceholder: (toolCall) => createBackgroundPlaceholderText(toolCall),\n\t\t// Report in-process background tool load (e.g. background MCP tools) to the\n\t\t// subagent lifeguard so it widens its heartbeat/timeout tolerance for\n\t\t// concurrently-monitored subagents. Peek (don't create) the pool: background\n\t\t// tools can run before any subagent is ever dispatched.\n\t\tonBackgroundTaskCountChange: (count) => peekSubagentPool()?.setExternalLoad(count),\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tconst transformed = runner ? await runner.emitContext(messages) : messages;\n\t\t\tif (!settingsManager.getContextGcEnabled()) return transformed;\n\t\t\treturn evictSupersededReads(transformed, { cwd, budgetPressure: getBudgetPressure(transformed) });\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tthinkingDisplay: settingsManager.getThinkingDisplay(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\tdisallowedToolNames: options.disallowedTools,\n\t\textensionRunnerRef,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallback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AAE;QACzC,eAAe,EAAE,eAAe,CAAC,kBAAkB,EAAE;QACrD,eAAe,EAAE,eAAe,CAAC,kBAAkB,EAAE;QACrD,eAAe,EAAE,eAAe,CAAC,wBAAwB,EAAE,CAAC,eAAe;KAC3E,CAAC,CAAC;IAEH,gDAAgD;IAChD,IAAI,kBAAkB,EAAE,CAAC;QACxB,KAAK,CAAC,KAAK,CAAC,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC;QAChD,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACvB,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;QACzD,CAAC;IACF,CAAC;SAAM,CAAC;QACP,2FAA2F;QAC3F,IAAI,KAAK,EAAE,CAAC;YACX,cAAc,CAAC,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;QAC5D,CAAC;QACD,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;IACzD,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC;QAChC,KAAK;QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;QAC5C,aAAa;QACb,sBAAsB;QACtB,gBAAgB;QAChB,mBAAmB,EAAE,OAAO,CAAC,eAAe;QAC5C,kBAAkB;QAClB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport {\n\tAgent,\n\ttype AgentMessage,\n\ttype AgentTool,\n\tconvertToLlm,\n\tcreateBackgroundPlaceholderText,\n\tcreateBackgroundTaskMessage,\n\testimateContextTokens,\n\ttype ThinkingLevel,\n} from \"@kolisachint/hoocode-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@kolisachint/hoocode-ai\";\nimport { getAgentDir } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { evictSupersededReads } from \"./context-gc.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { peekSubagentPool } from \"./subagent-pool-instance.js\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.hoocode/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, hoocode enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/**\n\t * Optional denylist of tool names, subtracted from whatever set is otherwise\n\t * enabled (allowlist or default). Applied to built-in, extension, and custom tools.\n\t */\n\tdisallowedTools?: string[];\n\t/**\n\t * Enable the built-in `webfetch` + `websearch` tools, which are defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list `webfetch`/`websearch` there instead). Network access is still gated\n\t * per call and filtered by `.webtoolsignore`.\n\t */\n\tenableWebTools?: boolean;\n\t/**\n\t * Enable the built-in `browser_run` + `browser_continue` tools, which drive the\n\t * `browsertools` deterministic browser engine (parent-in-the-loop). Defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list them there instead).\n\t */\n\tenableBrowserTools?: boolean;\n\t/**\n\t * Enable the built-in document tools — `DocRead`/`DocEdit`/`DocWrite` (extract\n\t * and lossless id-based editing) plus `DocScan`/`DocGrep`/`DocPeek` (the\n\t * token-sensitive discovery loop: outline, search, partial read). Defined but\n\t * inactive by default. Ignored when an explicit `tools` allowlist is provided\n\t * (list them there instead). They shell out to the `filetools` binary to\n\t * losslessly extract/edit structured/binary documents.\n\t */\n\tenableFileTools?: boolean;\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\t/**\n\t * Replace the built-in base tools entirely (the light preset uses this to\n\t * swap in short-schema read/write/edit/bash variants). Keys become the\n\t * default active tool set when no explicit `tools` allowlist is provided.\n\t */\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport type { AgentDefinition, AgentSource } from \"./agent-frontmatter.js\";\nexport { AgentRegistry, formatAgentsForPrompt, loadAgentRegistry } from \"./agent-registry.js\";\nexport * from \"./agent-session-runtime.js\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n): Record<string, string> | undefined {\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://github.com/kolisachint/hoocode\",\n\t\t\t\"X-OpenRouter-Title\": \"hoocode\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@kolisachint/hoocode-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [readTool, bashTool],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"];\n\t// Web tools are registered as base tools but inactive by default; opt-in adds\n\t// them to the default active set. An explicit allowlist (`tools`) takes over\n\t// fully, so callers must list them there to enable in that mode.\n\tconst optInActiveToolNames: ToolName[] = [\n\t\t...(options.enableWebTools ? [\"webfetch\", \"websearch\"] : []),\n\t\t...(options.enableBrowserTools ? [\"browser_run\", \"browser_continue\"] : []),\n\t\t...(options.enableFileTools ? [\"DocRead\", \"DocEdit\", \"DocWrite\", \"DocScan\", \"DocGrep\", \"DocPeek\"] : []),\n\t] as ToolName[];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst initialActiveToolNames: string[] = options.tools\n\t\t? [...options.tools]\n\t\t: options.noTools\n\t\t\t? []\n\t\t\t: [...defaultActiveToolNames, ...optInActiveToolNames];\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\t// Token-budget pressure for context GC: the fraction of the active model's\n\t// context window in use, measured from the real usage on the outgoing\n\t// message copy. It latches to a high-water mark so that our own evictions —\n\t// which shrink the next turn's measured usage — cannot oscillate a message\n\t// in and out of the transcript and thrash the provider's prefix cache. A\n\t// large drop (compaction, fork) resets the latch to the new, smaller size.\n\tlet budgetPressureHighWater = 0;\n\tconst getBudgetPressure = (contextMessages: AgentMessage[]): number => {\n\t\tconst contextWindow = agent.state.model?.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return 0;\n\t\tconst gauge = Math.min(estimateContextTokens(contextMessages).tokens / contextWindow, 1);\n\t\tif (gauge > budgetPressureHighWater) {\n\t\t\tbudgetPressureHighWater = gauge; // rising usage — track it\n\t\t} else if (gauge < budgetPressureHighWater - 0.15) {\n\t\t\tbudgetPressureHighWater = gauge; // context collapsed — reset the latch\n\t\t}\n\t\treturn budgetPressureHighWater;\n\t};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tcreateBackgroundResultMessage: createBackgroundTaskMessage,\n\t\tcreateBackgroundPlaceholder: (toolCall) => createBackgroundPlaceholderText(toolCall),\n\t\t// Report in-process background tool load (e.g. background MCP tools) to the\n\t\t// subagent lifeguard so it widens its heartbeat/timeout tolerance for\n\t\t// concurrently-monitored subagents. Peek (don't create) the pool: background\n\t\t// tools can run before any subagent is ever dispatched.\n\t\tonBackgroundTaskCountChange: (count) => peekSubagentPool()?.setExternalLoad(count),\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\ttimeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tconst transformed = runner ? await runner.emitContext(messages) : messages;\n\t\t\tif (!settingsManager.getContextGcEnabled()) return transformed;\n\t\t\treturn evictSupersededReads(transformed, { cwd, budgetPressure: getBudgetPressure(transformed) });\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tthinkingDisplay: settingsManager.getThinkingDisplay(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tbaseToolsOverride: options.baseToolsOverride,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\tdisallowedToolNames: options.disallowedTools,\n\t\textensionRunnerRef,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|