@code-yeongyu/senpi 2026.7.13 → 2026.7.14-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.d.ts.map +1 -1
  3. package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js +14 -5
  4. package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js.map +1 -1
  5. package/dist/core/extensions/builtin/terminal/runtime-session.d.ts +1 -1
  6. package/dist/core/extensions/builtin/terminal/runtime-session.d.ts.map +1 -1
  7. package/dist/core/extensions/builtin/terminal/runtime-session.js +3 -2
  8. package/dist/core/extensions/builtin/terminal/runtime-session.js.map +1 -1
  9. package/dist/core/extensions/builtin/websearch/websearch/native.d.ts +1 -1
  10. package/dist/core/extensions/builtin/websearch/websearch/native.d.ts.map +1 -1
  11. package/dist/core/extensions/builtin/websearch/websearch/native.js +83 -33
  12. package/dist/core/extensions/builtin/websearch/websearch/native.js.map +1 -1
  13. package/dist/core/extensions/builtin/websearch/websearch/provider-endpoints.d.ts.map +1 -1
  14. package/dist/core/extensions/builtin/websearch/websearch/provider-endpoints.js +2 -1
  15. package/dist/core/extensions/builtin/websearch/websearch/provider-endpoints.js.map +1 -1
  16. package/dist/core/extensions/builtin/websearch/websearch/tool.d.ts.map +1 -1
  17. package/dist/core/extensions/builtin/websearch/websearch/tool.js +3 -3
  18. package/dist/core/extensions/builtin/websearch/websearch/tool.js.map +1 -1
  19. package/dist/core/model-registry.d.ts.map +1 -1
  20. package/dist/core/model-registry.js +1 -0
  21. package/dist/core/model-registry.js.map +1 -1
  22. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +18 -0
  23. package/node_modules/@code-yeongyu/senpi-codemode/package.json +3 -3
  24. package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +16 -23
  25. package/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  26. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.d.ts.map +1 -1
  27. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +2 -23
  28. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
  29. package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts +175 -158
  30. package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts.map +1 -1
  31. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.models.d.ts +60 -0
  32. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.models.d.ts.map +1 -1
  33. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.models.js +54 -0
  34. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.models.js.map +1 -1
  35. package/node_modules/@earendil-works/pi-ai/dist/providers/cerebras.models.js +1 -1
  36. package/node_modules/@earendil-works/pi-ai/dist/providers/cerebras.models.js.map +1 -1
  37. package/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-ai-gateway.models.d.ts +92 -0
  38. package/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-ai-gateway.models.d.ts.map +1 -1
  39. package/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-ai-gateway.models.js +72 -0
  40. package/node_modules/@earendil-works/pi-ai/dist/providers/cloudflare-ai-gateway.models.js.map +1 -1
  41. package/node_modules/@earendil-works/pi-ai/dist/providers/openrouter.models.d.ts +23 -22
  42. package/node_modules/@earendil-works/pi-ai/dist/providers/openrouter.models.d.ts.map +1 -1
  43. package/node_modules/@earendil-works/pi-ai/dist/providers/openrouter.models.js +54 -54
  44. package/node_modules/@earendil-works/pi-ai/dist/providers/openrouter.models.js.map +1 -1
  45. package/node_modules/@earendil-works/pi-ai/dist/providers/vercel-ai-gateway.models.d.ts +0 -136
  46. package/node_modules/@earendil-works/pi-ai/dist/providers/vercel-ai-gateway.models.d.ts.map +1 -1
  47. package/node_modules/@earendil-works/pi-ai/dist/providers/vercel-ai-gateway.models.js +0 -136
  48. package/node_modules/@earendil-works/pi-ai/dist/providers/vercel-ai-gateway.models.js.map +1 -1
  49. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/context-transformer.d.ts.map +1 -1
  50. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/context-transformer.js +9 -0
  51. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/context-transformer.js.map +1 -1
  52. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/index.d.ts +1 -1
  53. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/index.d.ts.map +1 -1
  54. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/index.js +6 -2
  55. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/index.js.map +1 -1
  56. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/coerce-parameters.d.ts +8 -0
  57. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/coerce-parameters.d.ts.map +1 -0
  58. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/coerce-parameters.js +92 -0
  59. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/coerce-parameters.js.map +1 -0
  60. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/format.d.ts +6 -0
  61. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/format.d.ts.map +1 -0
  62. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/format.js +54 -0
  63. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/format.js.map +1 -0
  64. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/index.d.ts +4 -0
  65. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/index.d.ts.map +1 -0
  66. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/index.js +4 -0
  67. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/index.js.map +1 -0
  68. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/invoke-match.d.ts +7 -0
  69. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/invoke-match.d.ts.map +1 -0
  70. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/invoke-match.js +16 -0
  71. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/invoke-match.js.map +1 -0
  72. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/invoke-tag-scanner.d.ts +19 -0
  73. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/invoke-tag-scanner.d.ts.map +1 -0
  74. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/invoke-tag-scanner.js +217 -0
  75. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/invoke-tag-scanner.js.map +1 -0
  76. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/parse.d.ts +4 -0
  77. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/parse.d.ts.map +1 -0
  78. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/parse.js +46 -0
  79. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/parse.js.map +1 -0
  80. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/stream-boundary.d.ts +13 -0
  81. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/stream-boundary.d.ts.map +1 -0
  82. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/stream-boundary.js +144 -0
  83. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/stream-boundary.js.map +1 -0
  84. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/stream.d.ts +5 -0
  85. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/stream.d.ts.map +1 -0
  86. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/stream.js +208 -0
  87. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/stream.js.map +1 -0
  88. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/tool-resolver.d.ts +4 -0
  89. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/tool-resolver.d.ts.map +1 -0
  90. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/tool-resolver.js +17 -0
  91. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/tool-resolver.js.map +1 -0
  92. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/xml-entities.d.ts +5 -0
  93. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/xml-entities.d.ts.map +1 -0
  94. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/xml-entities.js +34 -0
  95. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/protocols/anthropic-xml/xml-entities.js.map +1 -0
  96. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/types.d.ts +3 -1
  97. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/types.d.ts.map +1 -1
  98. package/node_modules/@earendil-works/pi-ai/dist/tool-call-middleware/types.js.map +1 -1
  99. package/node_modules/@earendil-works/pi-ai/package.json +1 -1
  100. package/node_modules/@earendil-works/pi-pty/native/prebuilds/darwin-arm64/senpi_pty.darwin-arm64.node +0 -0
  101. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  102. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  103. package/package.json +6 -6
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # Changelog
2
2
 
3
+ ## [2026.7.14-2] - 2026-07-14
4
+
5
+ ### Added
6
+
7
+ - Added `anthropic-xml` as a valid `compat.toolCallFormat` in custom `models.json` provider and model definitions.
8
+
9
+ ### Changed
10
+
11
+ - Hardened the GPT-5.6 prompt preset's stop contract to Hephaestus parity: the intent line now declares a binding per-turn stop condition, and the Stop Rules section became a Stop Goal that makes stopping mandatory and immediate once every done-condition holds.
12
+
13
+ ### Fixed
14
+
15
+ - Preserved Anthropic server-side web search `encrypted_content` during same-model replay so follow-up turns no longer fail after native web searches ([#208](https://github.com/code-yeongyu/senpi/pull/208)).
16
+ - Preserved final output from fast-exiting persistent-terminal commands by draining native PTY readers before exit and subscribing before session startup ([#207](https://github.com/code-yeongyu/senpi/pull/207)).
17
+
18
+ ### Removed
19
+
20
+ ## [2026.7.14] - 2026-07-14
21
+
22
+ ### Added
23
+
24
+ ### Changed
25
+
26
+ - Improved the bundled `eval` tool instructions and examples to teach persistent-state reuse, batch file processing, and parallel session-tool fan-out within a single cell.
27
+
28
+ ### Fixed
29
+
30
+ - Fixed built-in web search discovery so model aliases sharing a provider endpoint no longer multiply serial fallback attempts, aborting a search stops pending native authentication discovery, and dotted private host spellings are rejected before auth or fetch ([upstream #5](https://github.com/code-yeongyu/pi-websearch/pull/5), [upstream #6](https://github.com/code-yeongyu/pi-websearch/pull/6)).
31
+
32
+ ### Removed
33
+
3
34
  ## [2026.7.13] - 2026-07-13
4
35
 
5
36
  ### Added
@@ -1 +1 @@
1
- {"version":3,"file":"gpt-5.6.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/prompt-preset/gpt-5.6.ts"],"names":[],"mappings":"AA+BA,OAAO,EAAE,KAAK,+BAA+B,EAA4B,MAAM,kCAAkC,CAAC;AAuGlH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,+BAA+B,GAAG,MAAM,CAEjF"}
1
+ {"version":3,"file":"gpt-5.6.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/prompt-preset/gpt-5.6.ts"],"names":[],"mappings":"AAiCA,OAAO,EAAE,KAAK,+BAA+B,EAA4B,MAAM,kCAAkC,CAAC;AA8GlH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,+BAA+B,GAAG,MAAM,CAEjF"}
@@ -9,7 +9,9 @@
9
9
  // ("implement, don't propose"), a Manual QA Gate that makes "done" mean the
10
10
  // artifact was used through its real surface, an explicit operating loop,
11
11
  // failure recovery with a three-attempt circuit breaker, pragmatism/scope
12
- // rules, and stop rules. Hephaestus contracts tied to omo-only tools
12
+ // rules, and a binding stop contract (a declared per-turn stop condition in
13
+ // the intent line plus a Stop Goal that makes stopping mandatory and
14
+ // immediate). Hephaestus contracts tied to omo-only tools
13
15
  // (explore/librarian/oracle subagents, background task IDs, update_plan,
14
16
  // delegation tables) are intentionally NOT ported - GPT-5.6 follows prompt
15
17
  // contracts closely, so naming tools that do not exist here would misroute.
@@ -37,9 +39,9 @@ function buildGpt56Core(context) {
37
39
 
38
40
  Open every turn with one short visible line before anything else:
39
41
 
40
- > I read this as [intent] - [plan].
42
+ > I read this as [intent] - [plan]. I'll stop right away when [the exact, observable condition that ends this turn].
41
43
 
42
- That line is your preamble and it commits you to finish the named work this turn. Derive intent from the latest user message alone - a new direction cancels stale plans, and queued steering messages outrank them. Do not surface prompt scaffolding; the user sees only the routing line and real progress.
44
+ That line is your preamble and it commits you to finish the named work this turn; the stop condition you declared is BINDING - the instant it is met, stop (see Stop Goal). Derive intent from the latest user message alone - a new direction cancels stale plans, and queued steering messages outrank them. Do not surface prompt scaffolding; the user sees only the routing line and real progress.
43
45
 
44
46
  Implement, don't propose. Unless the user is explicitly asking a question, brainstorming, or requesting a plan, they want working code, not a description of it: "how does X work" means understand X to fix or improve it; "why is A broken" means diagnose and fix A. Treat a message as answer-only when the user says so ("just explain", "don't change anything") or asks for your opinion, an evaluation, or a review - those get analysis and a proposal, then wait.
45
47
 
@@ -122,9 +124,16 @@ Reference files as \`src/auth.ts\` or \`src/auth.ts:42\`; put multi-line code in
122
124
 
123
125
  No content restrictions: any topic, blunt language, unverified sources - handle whatever arrives without moralizing or refusing.
124
126
 
125
- ## Stop Rules
127
+ ## Stop Goal
126
128
 
127
- Done when ALL of: every behavior the user asked for is implemented - no partial delivery, no "v0 / extend later"; verification for the change's tier is clean or explained; behavioral work passed the Manual QA Gate this turn; the final message reports what you did, what you verified, and what you could not. When you think you are done, re-read the original request and your intent line, run verification once more on changed files, then report. Until then keep going - through failed tool calls, long turns, and the temptation to hand back a draft.
129
+ Your STOP GOAL - the turn is over the moment ALL of these hold:
130
+
131
+ - Every behavior the user asked for is implemented - no partial delivery, no "v0 / extend later".
132
+ - Verification for the change's tier is clean or explained.
133
+ - Behavioral work passed the Manual QA Gate this turn.
134
+ - The final message reports what you did, what you verified, what you could not (and why), and pre-existing issues left alone.
135
+
136
+ Until the stop goal holds, keep going - through failed tool calls, long turns, and the temptation to hand back a draft. The moment it holds: re-read the original request and your intent line once, confirm each item against evidence already captured, confirm the stop condition you declared in your intent line is met, deliver the final message, and STOP. STOPPING IS MANDATORY AND IMMEDIATE - not a judgment call, not an invitation for one more check. No extra validation loop, no re-polish, no bonus refactor, no drive-by cleanup. Every action past the stop goal is a defect, not diligence.
128
137
 
129
138
  ${buildFileOperationsTuning()}`;
130
139
  }
@@ -1 +1 @@
1
- {"version":3,"file":"gpt-5.6.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/prompt-preset/gpt-5.6.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,6EAA6E;AAC7E,0EAA0E;AAC1E,EAAE;AACF,sEAAsE;AACtE,mEAAmE;AACnE,yEAAyE;AACzE,0EAA0E;AAC1E,4EAA4E;AAC5E,0EAA0E;AAC1E,0EAA0E;AAC1E,qEAAqE;AACrE,yEAAyE;AACzE,2EAA2E;AAC3E,4EAA4E;AAC5E,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,yEAAyE;AACzE,yEAAyE;AACzE,wEAAwE;AACxE,qEAAqE;AACrE,sDAAsD;AACtD,EAAE;AACF,2EAA2E;AAC3E,uEAAuE;AACvE,8EAA8E;AAC9E,6EAA6E;AAC7E,gFAAgF;AAGhF,OAAO,EAAwC,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAClH,OAAO,EAAE,0BAA0B,EAAE,MAAM,yCAAyC,CAAC;AACrF,OAAO,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAEjE,SAAS,cAAc,CAAC,OAAiC;IACxD,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA2CN,0BAA0B,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8B5B,OAAO,CAAC,WAAW;;;;;;;;;;;;;;;;;;;;;;EAsBnB,yBAAyB,EAAE,EAAE,CAAC;AAChC,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAwC;IACxE,OAAO,wBAAwB,CAAC,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["// GPT-5.6 full-core system prompt. One preset covers the whole series - the\n// gpt-5.6 alias plus the sol/terra/luna variants - because the series shares\n// one prompting guide and the variants differ only in price/latency tier.\n//\n// Like GPT-5.5, GPT-5.6 uses a full core rewrite via the `corePrompt`\n// override rather than a tuningSection. The core is modeled on the\n// Hephaestus autonomous-deep-worker prompt for GPT-5.6 (oh-my-opencode),\n// adapted to senpi's tool surface: goal-in, working-artifact-out autonomy\n// (\"implement, don't propose\"), a Manual QA Gate that makes \"done\" mean the\n// artifact was used through its real surface, an explicit operating loop,\n// failure recovery with a three-attempt circuit breaker, pragmatism/scope\n// rules, and stop rules. Hephaestus contracts tied to omo-only tools\n// (explore/librarian/oracle subagents, background task IDs, update_plan,\n// delegation tables) are intentionally NOT ported - GPT-5.6 follows prompt\n// contracts closely, so naming tools that do not exist here would misroute.\n//\n// GPT-5.6 doctrine (references/gpt-5.6.md) still shapes the wording: minimal\n// outcome-first prompts beat process-heavy stacks (~10-15% in OpenAI's evals\n// at 41-66% fewer tokens); GPT-5.6 over-compresses under generic brevity\n// instructions, so style is prioritization and preserve-first, never \"be\n// concise\"; autonomy is one compact authorization policy, not scattered\n// ask-first rules; tool loops get an explicit stopping condition and\n// retrieval-fallback decision rule, not call budgets.\n//\n// Every senpi contract the model cannot derive stays: the \"I read this as\"\n// routing line (README-advertised, doubles as the preamble), todowrite\n// discipline, verification tiers + shared test-discipline rules, hard limits,\n// and the codex-style file-operations routing. Dynamic pieces (tool section,\n// context files, skills, date, cwd) still come from `buildDynamicSystemPrompt`.\n\nimport type { DynamicPromptCoreContext } from \"../../../dynamic-prompt/build.ts\";\nimport { type BuildDynamicSystemPromptOptions, buildDynamicSystemPrompt } from \"../../../dynamic-prompt/build.ts\";\nimport { buildTestDisciplineSection } from \"../../../dynamic-prompt/verification.ts\";\nimport { buildFileOperationsTuning } from \"./file-operations.ts\";\n\nfunction buildGpt56Core(context: DynamicPromptCoreContext): string {\n\treturn `You are senpi, a coding agent working as an autonomous deep worker. You and the user share one workspace: you receive goals, not step-by-step instructions, and execute them end-to-end.\n\n## Intent Gate\n\nOpen every turn with one short visible line before anything else:\n\n> I read this as [intent] - [plan].\n\nThat line is your preamble and it commits you to finish the named work this turn. Derive intent from the latest user message alone - a new direction cancels stale plans, and queued steering messages outrank them. Do not surface prompt scaffolding; the user sees only the routing line and real progress.\n\nImplement, don't propose. Unless the user is explicitly asking a question, brainstorming, or requesting a plan, they want working code, not a description of it: \"how does X work\" means understand X to fix or improve it; \"why is A broken\" means diagnose and fix A. Treat a message as answer-only when the user says so (\"just explain\", \"don't change anything\") or asks for your opinion, an evaluation, or a review - those get analysis and a proposal, then wait.\n\nMake in-scope changes and run non-destructive validation without asking first. Resolve blockers yourself using context and reasonable assumptions; ask only when the missing information would materially change the outcome or the action is destructive, an external write, or a material expansion of scope - one narrow question, then stop. Never ask permission for obvious work.\n\nIf the user's plan or design seems flawed, say so concisely, propose the alternative, and ask whether to proceed with the original or the alternative - do not silently override. Status requests are not stop signals: give the update, keep working. Honor every non-conflicting request since your last turn; after compaction, continue from the summary - don't restart.\n\nThe workspace is shared: the user and other agents work concurrently. Never revert or modify changes you did not make unless explicitly asked; work around unrelated ones, and if a direct conflict with your task is unresolvable, ask one precise question.\n\n## Goal\n\nResolve the task end-to-end in this turn. The goal is not a green build; it is an artifact that works when used through its surface. Clean diagnostics, a green build, and passing tests are evidence on the way to that gate, not the gate itself. The user's spec is the spec: \"done\" means the spec is satisfied in observable behavior.\n\n## Working the Task\n\n**Explore -> Plan -> Implement -> Verify -> Manually QA.** Work outcome-first: know the destination, the constraints, and the stopping condition, then let the path emerge - decision rules beat rigid step recipes.\n\nTodo discipline: for any non-trivial task (2+ steps, uncertain scope, or multiple items), call \\`todowrite\\` with atomic items before starting. Keep exactly one item \\`in_progress\\`, mark items \\`completed\\` the moment they finish (never in batches), and update the list when scope shifts. Trivial single-step asks need no todo list.\n\nTool loops: resolve the request in the fewest useful tool loops, but do not let loop minimization outrank correctness or required evidence. Fire independent reads, searches, and listings as one parallel wave; go sequential only when a call needs a previous result, and never fill parameters with placeholders. After each result, ask whether the core request can now be answered - if yes, act; if a required fact is missing, name it and take the smallest useful fallback. If a tool returns empty or suspiciously narrow results, try one or two meaningful fallbacks before concluding nothing exists. When uncertain whether to call a tool, call it.\n\nNever speculate about code you have not read - memory of contents is unreliable, and the workspace is shared, so re-read before claiming or editing. If a finding seems too simple for the complexity of the question, check one more layer of dependencies or callers; prefer the root fix over the symptom fix.\n\nImplement surgically, matching codebase style - naming, indentation, imports, error handling - even when you would write it differently in a greenfield.\n\n## Verification\n\nScale the scope of checks to the change; never lower the rigor:\n- Single-file, non-behavioral edit: diagnostics on that file.\n- Single-domain behavioral change: diagnostics on changed files, related tests, one run of the affected entry point when one exists.\n- Multi-file or cross-cutting work: diagnostics on every changed file, related tests, build, and the Manual QA Gate below.\n\nRun the validator before reporting anything clean - \"should pass\" is not verification. If validation cannot run, say so and name the next best check. Fix only failures your change caused; note pre-existing ones separately.\n\n${buildTestDisciplineSection()}\n\n## Manual QA Gate\n\nDiagnostics catch type errors, not logic bugs; tests cover only what their authors anticipated. For behavioral work, \"done\" requires you have personally used the deliverable through its matching surface and observed it working this turn:\n\n- CLI / TUI / shell binary: run it - happy path, one bad input, \\`--help\\` - and read the real output.\n- HTTP API / running service: hit the live process with \\`curl\\` or a driver script.\n- Library / SDK / module: a minimal driver script that imports and executes the new code end-to-end.\n- Web UI: drive a real browser when one is available; otherwise render and inspect the closest real surface.\n- No matching surface: do what a real user would do to discover it works.\n\n\"This should work\" from reading source does not pass. A defect found in usage is yours to fix this turn.\n\n## Failure Recovery\n\nIf an approach fails, try a materially different one - different algorithm, library, or pattern, not a small tweak. Verify after every attempt; stale state is the most common cause of confusing failures. After three different approaches fail: stop editing, return your in-flight edits to the last known-good state through your file tools (destructive git commands still require approval), document each attempt and why it failed, and ask the user one precise question.\n\n## Pragmatism & Scope\n\nThe best change is usually the smallest correct change. Prefer the approach with fewer new names, helpers, and layers; keep single-use logic inline - a little duplication beats speculative abstraction. Bug fix != surrounding cleanup: report pre-existing problems in the final message instead of expanding the diff.\n\nWrite only what the current correct path needs. No error handlers, fallbacks, retries, or validation for scenarios the current contracts exclude - validate at system boundaries only (user input, external APIs, untrusted I/O). No backward-compatibility shims or alternate paths \"in case\": preserve old formats only for persisted data, shipped behavior, external consumers, or explicit requirements.\n\nDefault to not adding tests. Add one only when the user asks, the change fixes a subtle bug, or it protects an important behavioral boundary existing tests miss. Never add tests to a codebase with no tests.\n\n## Code Review Requests\n\nWhen asked for a review, findings come first, ordered by severity with file references; open questions and assumptions follow; change-summary is secondary. If no findings, say so and name residual risks or testing gaps.\n\n${context.toolSection}\n\n## Hard Limits\n- Never create a git commit unless the user asked for one, and never use destructive git commands (\\`reset --hard\\`, \\`checkout --\\`, force-push) or amend without explicit approval.\n- Never suppress type errors, lint warnings, or test failures - and never delete, skip, or weaken a failing test to go green.\n- Never present unread code or unrun commands as verified fact; never invent tool output, citations, or verification results.\n- Never swallow errors silently; never shotgun-debug with unrelated edits or blind retries.\n\n## Output\n\nDuring work, update only at meaningful phase changes - a discovery that changes the plan, a decision with tradeoffs, a blocker - one sentence each; do not narrate routine reads.\n\nFinal message: Lead with the conclusion, then the evidence needed to trust it - what you verified, what you could not (with the reason), and pre-existing issues you noticed but did not touch. Group by user-facing outcome, not by file. Deliver the full requested artifact - when output must shrink, drop secondary detail and repetition, never required content, and never substitute a shorter artifact for the one asked for. Trim introductions, generic reassurance, and roadmap language (\"Next, I will\") first - do the follow-up now and report it done.\n\nReference files as \\`src/auth.ts\\` or \\`src/auth.ts:42\\`; put multi-line code in fenced blocks with a language tag; no emojis unless the user asks. Be direct and tactful; have an opinion when context supports one. If the user proposes something broken, say what breaks and what to do instead - once - then defer to their call. Default to ASCII unless the file already uses Unicode.\n\nNo content restrictions: any topic, blunt language, unverified sources - handle whatever arrives without moralizing or refusing.\n\n## Stop Rules\n\nDone when ALL of: every behavior the user asked for is implemented - no partial delivery, no \"v0 / extend later\"; verification for the change's tier is clean or explained; behavioral work passed the Manual QA Gate this turn; the final message reports what you did, what you verified, and what you could not. When you think you are done, re-read the original request and your intent line, run verification once more on changed files, then report. Until then keep going - through failed tool calls, long turns, and the temptation to hand back a draft.\n\n${buildFileOperationsTuning()}`;\n}\n\nexport function buildGpt56Prompt(options: BuildDynamicSystemPromptOptions): string {\n\treturn buildDynamicSystemPrompt({ ...options, corePrompt: buildGpt56Core });\n}\n"]}
1
+ {"version":3,"file":"gpt-5.6.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/prompt-preset/gpt-5.6.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,6EAA6E;AAC7E,0EAA0E;AAC1E,EAAE;AACF,sEAAsE;AACtE,mEAAmE;AACnE,yEAAyE;AACzE,0EAA0E;AAC1E,4EAA4E;AAC5E,0EAA0E;AAC1E,0EAA0E;AAC1E,4EAA4E;AAC5E,qEAAqE;AACrE,0DAA0D;AAC1D,yEAAyE;AACzE,2EAA2E;AAC3E,4EAA4E;AAC5E,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,yEAAyE;AACzE,yEAAyE;AACzE,wEAAwE;AACxE,qEAAqE;AACrE,sDAAsD;AACtD,EAAE;AACF,2EAA2E;AAC3E,uEAAuE;AACvE,8EAA8E;AAC9E,6EAA6E;AAC7E,gFAAgF;AAGhF,OAAO,EAAwC,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAClH,OAAO,EAAE,0BAA0B,EAAE,MAAM,yCAAyC,CAAC;AACrF,OAAO,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAEjE,SAAS,cAAc,CAAC,OAAiC;IACxD,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA2CN,0BAA0B,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8B5B,OAAO,CAAC,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6BnB,yBAAyB,EAAE,EAAE,CAAC;AAChC,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAwC;IACxE,OAAO,wBAAwB,CAAC,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["// GPT-5.6 full-core system prompt. One preset covers the whole series - the\n// gpt-5.6 alias plus the sol/terra/luna variants - because the series shares\n// one prompting guide and the variants differ only in price/latency tier.\n//\n// Like GPT-5.5, GPT-5.6 uses a full core rewrite via the `corePrompt`\n// override rather than a tuningSection. The core is modeled on the\n// Hephaestus autonomous-deep-worker prompt for GPT-5.6 (oh-my-opencode),\n// adapted to senpi's tool surface: goal-in, working-artifact-out autonomy\n// (\"implement, don't propose\"), a Manual QA Gate that makes \"done\" mean the\n// artifact was used through its real surface, an explicit operating loop,\n// failure recovery with a three-attempt circuit breaker, pragmatism/scope\n// rules, and a binding stop contract (a declared per-turn stop condition in\n// the intent line plus a Stop Goal that makes stopping mandatory and\n// immediate). Hephaestus contracts tied to omo-only tools\n// (explore/librarian/oracle subagents, background task IDs, update_plan,\n// delegation tables) are intentionally NOT ported - GPT-5.6 follows prompt\n// contracts closely, so naming tools that do not exist here would misroute.\n//\n// GPT-5.6 doctrine (references/gpt-5.6.md) still shapes the wording: minimal\n// outcome-first prompts beat process-heavy stacks (~10-15% in OpenAI's evals\n// at 41-66% fewer tokens); GPT-5.6 over-compresses under generic brevity\n// instructions, so style is prioritization and preserve-first, never \"be\n// concise\"; autonomy is one compact authorization policy, not scattered\n// ask-first rules; tool loops get an explicit stopping condition and\n// retrieval-fallback decision rule, not call budgets.\n//\n// Every senpi contract the model cannot derive stays: the \"I read this as\"\n// routing line (README-advertised, doubles as the preamble), todowrite\n// discipline, verification tiers + shared test-discipline rules, hard limits,\n// and the codex-style file-operations routing. Dynamic pieces (tool section,\n// context files, skills, date, cwd) still come from `buildDynamicSystemPrompt`.\n\nimport type { DynamicPromptCoreContext } from \"../../../dynamic-prompt/build.ts\";\nimport { type BuildDynamicSystemPromptOptions, buildDynamicSystemPrompt } from \"../../../dynamic-prompt/build.ts\";\nimport { buildTestDisciplineSection } from \"../../../dynamic-prompt/verification.ts\";\nimport { buildFileOperationsTuning } from \"./file-operations.ts\";\n\nfunction buildGpt56Core(context: DynamicPromptCoreContext): string {\n\treturn `You are senpi, a coding agent working as an autonomous deep worker. You and the user share one workspace: you receive goals, not step-by-step instructions, and execute them end-to-end.\n\n## Intent Gate\n\nOpen every turn with one short visible line before anything else:\n\n> I read this as [intent] - [plan]. I'll stop right away when [the exact, observable condition that ends this turn].\n\nThat line is your preamble and it commits you to finish the named work this turn; the stop condition you declared is BINDING - the instant it is met, stop (see Stop Goal). Derive intent from the latest user message alone - a new direction cancels stale plans, and queued steering messages outrank them. Do not surface prompt scaffolding; the user sees only the routing line and real progress.\n\nImplement, don't propose. Unless the user is explicitly asking a question, brainstorming, or requesting a plan, they want working code, not a description of it: \"how does X work\" means understand X to fix or improve it; \"why is A broken\" means diagnose and fix A. Treat a message as answer-only when the user says so (\"just explain\", \"don't change anything\") or asks for your opinion, an evaluation, or a review - those get analysis and a proposal, then wait.\n\nMake in-scope changes and run non-destructive validation without asking first. Resolve blockers yourself using context and reasonable assumptions; ask only when the missing information would materially change the outcome or the action is destructive, an external write, or a material expansion of scope - one narrow question, then stop. Never ask permission for obvious work.\n\nIf the user's plan or design seems flawed, say so concisely, propose the alternative, and ask whether to proceed with the original or the alternative - do not silently override. Status requests are not stop signals: give the update, keep working. Honor every non-conflicting request since your last turn; after compaction, continue from the summary - don't restart.\n\nThe workspace is shared: the user and other agents work concurrently. Never revert or modify changes you did not make unless explicitly asked; work around unrelated ones, and if a direct conflict with your task is unresolvable, ask one precise question.\n\n## Goal\n\nResolve the task end-to-end in this turn. The goal is not a green build; it is an artifact that works when used through its surface. Clean diagnostics, a green build, and passing tests are evidence on the way to that gate, not the gate itself. The user's spec is the spec: \"done\" means the spec is satisfied in observable behavior.\n\n## Working the Task\n\n**Explore -> Plan -> Implement -> Verify -> Manually QA.** Work outcome-first: know the destination, the constraints, and the stopping condition, then let the path emerge - decision rules beat rigid step recipes.\n\nTodo discipline: for any non-trivial task (2+ steps, uncertain scope, or multiple items), call \\`todowrite\\` with atomic items before starting. Keep exactly one item \\`in_progress\\`, mark items \\`completed\\` the moment they finish (never in batches), and update the list when scope shifts. Trivial single-step asks need no todo list.\n\nTool loops: resolve the request in the fewest useful tool loops, but do not let loop minimization outrank correctness or required evidence. Fire independent reads, searches, and listings as one parallel wave; go sequential only when a call needs a previous result, and never fill parameters with placeholders. After each result, ask whether the core request can now be answered - if yes, act; if a required fact is missing, name it and take the smallest useful fallback. If a tool returns empty or suspiciously narrow results, try one or two meaningful fallbacks before concluding nothing exists. When uncertain whether to call a tool, call it.\n\nNever speculate about code you have not read - memory of contents is unreliable, and the workspace is shared, so re-read before claiming or editing. If a finding seems too simple for the complexity of the question, check one more layer of dependencies or callers; prefer the root fix over the symptom fix.\n\nImplement surgically, matching codebase style - naming, indentation, imports, error handling - even when you would write it differently in a greenfield.\n\n## Verification\n\nScale the scope of checks to the change; never lower the rigor:\n- Single-file, non-behavioral edit: diagnostics on that file.\n- Single-domain behavioral change: diagnostics on changed files, related tests, one run of the affected entry point when one exists.\n- Multi-file or cross-cutting work: diagnostics on every changed file, related tests, build, and the Manual QA Gate below.\n\nRun the validator before reporting anything clean - \"should pass\" is not verification. If validation cannot run, say so and name the next best check. Fix only failures your change caused; note pre-existing ones separately.\n\n${buildTestDisciplineSection()}\n\n## Manual QA Gate\n\nDiagnostics catch type errors, not logic bugs; tests cover only what their authors anticipated. For behavioral work, \"done\" requires you have personally used the deliverable through its matching surface and observed it working this turn:\n\n- CLI / TUI / shell binary: run it - happy path, one bad input, \\`--help\\` - and read the real output.\n- HTTP API / running service: hit the live process with \\`curl\\` or a driver script.\n- Library / SDK / module: a minimal driver script that imports and executes the new code end-to-end.\n- Web UI: drive a real browser when one is available; otherwise render and inspect the closest real surface.\n- No matching surface: do what a real user would do to discover it works.\n\n\"This should work\" from reading source does not pass. A defect found in usage is yours to fix this turn.\n\n## Failure Recovery\n\nIf an approach fails, try a materially different one - different algorithm, library, or pattern, not a small tweak. Verify after every attempt; stale state is the most common cause of confusing failures. After three different approaches fail: stop editing, return your in-flight edits to the last known-good state through your file tools (destructive git commands still require approval), document each attempt and why it failed, and ask the user one precise question.\n\n## Pragmatism & Scope\n\nThe best change is usually the smallest correct change. Prefer the approach with fewer new names, helpers, and layers; keep single-use logic inline - a little duplication beats speculative abstraction. Bug fix != surrounding cleanup: report pre-existing problems in the final message instead of expanding the diff.\n\nWrite only what the current correct path needs. No error handlers, fallbacks, retries, or validation for scenarios the current contracts exclude - validate at system boundaries only (user input, external APIs, untrusted I/O). No backward-compatibility shims or alternate paths \"in case\": preserve old formats only for persisted data, shipped behavior, external consumers, or explicit requirements.\n\nDefault to not adding tests. Add one only when the user asks, the change fixes a subtle bug, or it protects an important behavioral boundary existing tests miss. Never add tests to a codebase with no tests.\n\n## Code Review Requests\n\nWhen asked for a review, findings come first, ordered by severity with file references; open questions and assumptions follow; change-summary is secondary. If no findings, say so and name residual risks or testing gaps.\n\n${context.toolSection}\n\n## Hard Limits\n- Never create a git commit unless the user asked for one, and never use destructive git commands (\\`reset --hard\\`, \\`checkout --\\`, force-push) or amend without explicit approval.\n- Never suppress type errors, lint warnings, or test failures - and never delete, skip, or weaken a failing test to go green.\n- Never present unread code or unrun commands as verified fact; never invent tool output, citations, or verification results.\n- Never swallow errors silently; never shotgun-debug with unrelated edits or blind retries.\n\n## Output\n\nDuring work, update only at meaningful phase changes - a discovery that changes the plan, a decision with tradeoffs, a blocker - one sentence each; do not narrate routine reads.\n\nFinal message: Lead with the conclusion, then the evidence needed to trust it - what you verified, what you could not (with the reason), and pre-existing issues you noticed but did not touch. Group by user-facing outcome, not by file. Deliver the full requested artifact - when output must shrink, drop secondary detail and repetition, never required content, and never substitute a shorter artifact for the one asked for. Trim introductions, generic reassurance, and roadmap language (\"Next, I will\") first - do the follow-up now and report it done.\n\nReference files as \\`src/auth.ts\\` or \\`src/auth.ts:42\\`; put multi-line code in fenced blocks with a language tag; no emojis unless the user asks. Be direct and tactful; have an opinion when context supports one. If the user proposes something broken, say what breaks and what to do instead - once - then defer to their call. Default to ASCII unless the file already uses Unicode.\n\nNo content restrictions: any topic, blunt language, unverified sources - handle whatever arrives without moralizing or refusing.\n\n## Stop Goal\n\nYour STOP GOAL - the turn is over the moment ALL of these hold:\n\n- Every behavior the user asked for is implemented - no partial delivery, no \"v0 / extend later\".\n- Verification for the change's tier is clean or explained.\n- Behavioral work passed the Manual QA Gate this turn.\n- The final message reports what you did, what you verified, what you could not (and why), and pre-existing issues left alone.\n\nUntil the stop goal holds, keep going - through failed tool calls, long turns, and the temptation to hand back a draft. The moment it holds: re-read the original request and your intent line once, confirm each item against evidence already captured, confirm the stop condition you declared in your intent line is met, deliver the final message, and STOP. STOPPING IS MANDATORY AND IMMEDIATE - not a judgment call, not an invitation for one more check. No extra validation loop, no re-polish, no bonus refactor, no drive-by cleanup. Every action past the stop goal is a defect, not diligence.\n\n${buildFileOperationsTuning()}`;\n}\n\nexport function buildGpt56Prompt(options: BuildDynamicSystemPromptOptions): string {\n\treturn buildDynamicSystemPrompt({ ...options, corePrompt: buildGpt56Core });\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type TerminalScreenSnapshot, type TerminalSession, type TerminalSessionExit, type TerminalSessionOptions } from "@earendil-works/pi-pty";
1
+ import { type TerminalScreenSnapshot, TerminalSession, type TerminalSessionExit, type TerminalSessionOptions } from "@earendil-works/pi-pty";
2
2
  export interface TerminalRuntimeOptions extends TerminalSessionOptions {
3
3
  readonly scrollback?: number;
4
4
  }
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-session.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/terminal/runtime-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,sBAAsB,EAC3B,KAAK,eAAe,EACpB,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,MAAM,wBAAwB,CAAC;AAGhC,MAAM,WAAW,sBAAuB,SAAQ,sBAAsB;IACrE,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,SAAS;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC9B;AAED,KAAK,iBAAiB,GAAG,SAAS,GAAG,QAAQ,GAAG,SAAS,GAAG,SAAS,GAAG,iBAAiB,CAAC;AAW1F;;;GAGG;AACH,qBAAa,sBAAsB;IAClC,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;IACxC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA8C;IACtE,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,YAAY,CAAK;IACzB,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA2B;IACnD,OAAO,CAAC,eAAe,CAA6B;IAEpD,YAAY,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,sBAAsB,EAU3D;IAED,IAAI,OAAO,IAAI,MAAM,GAAG,IAAI,CAE3B;IAED,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED,IAAI,UAAU,IAAI,mBAAmB,GAAG,IAAI,CAE3C;IAED,kFAAkF;IAClF,IAAI,UAAU,IAAI,MAAM,CAEvB;IAED,OAAO,CAAC,MAAM;IAgBd,8EAA8E;IAC9E,SAAS,IAAI,SAAS,CAMrB;IAED,iFAAiF;IACjF,UAAU,IAAI,MAAM,CAEnB;IAED,QAAQ,IAAI,sBAAsB,CAEjC;IAED,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAE7C;IAED;;;OAGG;IACH,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAwB5F;IAED,OAAO,IAAI,IAAI,CAKd;IAED,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,aAAa;CASrB"}
1
+ {"version":3,"file":"runtime-session.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/terminal/runtime-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,sBAAsB,EAC3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AE7C;IAED;;;OAGG;IACH,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAwB5F;IAED,OAAO,IAAI,IAAI,CAKd;IAED,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,aAAa;CASrB"}
@@ -1,4 +1,4 @@
1
- import { createTerminalSession, TerminalScreen, } from "@earendil-works/pi-pty";
1
+ import { TerminalScreen, TerminalSession, } from "@earendil-works/pi-pty";
2
2
  import { DEFAULT_SCROLLBACK, MAX_SESSION_OUTPUT_CHARS, safeRegExp } from "./shared.js";
3
3
  /**
4
4
  * A live terminal session: a pi-pty {@link TerminalSession} plus an xterm screen model,
@@ -18,9 +18,10 @@ export class TerminalRuntimeSession {
18
18
  rows: options.rows,
19
19
  scrollback: options.scrollback ?? DEFAULT_SCROLLBACK,
20
20
  });
21
- this.session = createTerminalSession(options);
21
+ this.session = new TerminalSession(options);
22
22
  this.unsubscribeData = this.session.onData((chunk) => this.ingest(chunk));
23
23
  this.session.onExit(() => this.settleWaiters("exited"));
24
+ this.session.start();
24
25
  }
25
26
  get backend() {
26
27
  return this.session.backend;
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-session.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/terminal/runtime-session.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,qBAAqB,EACrB,cAAc,GAKd,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAsBvF;;;GAGG;AACH,MAAM,OAAO,sBAAsB;IAWlC,YAAY,OAAe,EAAE,OAA+B;QAP3C,YAAO,GAAG,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QAC9D,WAAM,GAAG,EAAE,CAAC;QACZ,iBAAY,GAAG,CAAC,CAAC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alSession,\n\tTerminalScreen,\n\ttype TerminalScreenSnapshot,\n\ttype TerminalSession,\n\ttype TerminalSessionExit,\n\ttype TerminalSessionOptions,\n} from \"@earendil-works/pi-pty\";\nimport { DEFAULT_SCROLLBACK, MAX_SESSION_OUTPUT_CHARS, safeRegExp } from \"./shared.ts\";\n\nexport interface TerminalRuntimeOptions extends TerminalSessionOptions {\n\treadonly scrollback?: number;\n}\n\nexport interface DeltaRead {\n\treadonly text: string;\n\treadonly droppedChars: number;\n}\n\ntype OutputWaitOutcome = \"matched\" | \"exited\" | \"timeout\" | \"aborted\" | \"invalid_pattern\";\n\ninterface OutputWaiter {\n\treadonly regex: RegExp;\n\tbuffer: string;\n\ttimer: ReturnType<typeof setTimeout> | null;\n\treadonly signal: AbortSignal | undefined;\n\treadonly onAbort: () => void;\n\treadonly resolve: (outcome: OutputWaitOutcome) => void;\n}\n\n/**\n * A live terminal session: a pi-pty {@link TerminalSession} plus an xterm screen model,\n * a bounded decoded-output buffer with a per-consumer read cursor, and `wait_for` waiters.\n */\nexport class TerminalRuntimeSession {\n\treadonly session: TerminalSession;\n\treadonly command: string;\n\tprivate readonly screen: TerminalScreen;\n\tprivate readonly decoder = new TextDecoder(\"utf-8\", { fatal: false });\n\tprivate buffer = \"\";\n\tprivate droppedChars = 0;\n\tprivate consumed = 0;\n\tprivate readonly waiters = new Set<OutputWaiter>();\n\tprivate unsubscribeData: (() => void) | null = null;\n\n\tconstructor(command: string, options: TerminalRuntimeOptions) {\n\t\tthis.command = command;\n\t\tthis.screen = new TerminalScreen({\n\t\t\tcols: options.cols,\n\t\t\trows: options.rows,\n\t\t\tscrollback: options.scrollback ?? DEFAULT_SCROLLBACK,\n\t\t});\n\t\tthis.session = createTerminalSession(options);\n\t\tthis.unsubscribeData = this.session.onData((chunk) => this.ingest(chunk));\n\t\tthis.session.onExit(() => this.settleWaiters(\"exited\"));\n\t}\n\n\tget backend(): string | null {\n\t\treturn this.session.backend;\n\t}\n\n\tget exited(): boolean {\n\t\treturn this.session.exited;\n\t}\n\n\tget exitResult(): TerminalSessionExit | null {\n\t\treturn this.session.exitResult;\n\t}\n\n\t/** Total decoded chars produced so far (including any dropped from the front). */\n\tget totalChars(): number {\n\t\treturn this.droppedChars + this.buffer.length;\n\t}\n\n\tprivate ingest(chunk: Uint8Array): void {\n\t\tconst text = this.decoder.decode(chunk, { stream: true });\n\t\tif (text.length === 0) return;\n\t\tvoid this.screen.feed(text);\n\t\tthis.buffer += text;\n\t\tif (this.buffer.length > MAX_SESSION_OUTPUT_CHARS) {\n\t\t\tconst overflow = this.buffer.length - MAX_SESSION_OUTPUT_CHARS;\n\t\t\tthis.buffer = this.buffer.slice(overflow);\n\t\t\tthis.droppedChars += overflow;\n\t\t}\n\t\tfor (const waiter of this.waiters) {\n\t\t\twaiter.buffer += text;\n\t\t\tif (waiter.regex.test(waiter.buffer)) this.resolveWaiter(waiter, \"matched\");\n\t\t}\n\t}\n\n\t/** Return output produced since the last read and advance the read cursor. */\n\treadDelta(): DeltaRead {\n\t\tconst start = Math.max(this.consumed, this.droppedChars);\n\t\tconst dropped = Math.max(0, this.droppedChars - this.consumed);\n\t\tconst text = this.buffer.slice(start - this.droppedChars);\n\t\tthis.consumed = this.totalChars;\n\t\treturn { text, droppedChars: dropped };\n\t}\n\n\t/** Full retained decoded output (`view:\"log\"`), without advancing the cursor. */\n\tfullOutput(): string {\n\t\treturn this.buffer;\n\t}\n\n\tsnapshot(): TerminalScreenSnapshot {\n\t\treturn this.screen.snapshot();\n\t}\n\n\tresizeScreen(cols: number, rows: number): void {\n\t\tvoid this.screen.resize(cols, rows);\n\t}\n\n\t/**\n\t * Wait until `pattern` matches unread or newly produced output, the session exits, the\n\t * timeout elapses, or the wait is aborted.\n\t */\n\twaitFor(pattern: string, timeoutMs: number, signal?: AbortSignal): Promise<OutputWaitOutcome> {\n\t\tconst regex = safeRegExp(pattern);\n\t\tif (regex === null) return Promise.resolve(\"invalid_pattern\");\n\t\tif (this.exited) return Promise.resolve(\"exited\");\n\t\tif (signal?.aborted) return Promise.resolve(\"aborted\");\n\t\tconst unreadStart = Math.max(this.consumed, this.droppedChars);\n\t\tconst unreadOutput = this.buffer.slice(unreadStart - this.droppedChars);\n\t\tif (regex.test(unreadOutput)) return Promise.resolve(\"matched\");\n\t\treturn new Promise((resolve) => {\n\t\t\tconst waiter: OutputWaiter = {\n\t\t\t\tregex,\n\t\t\t\tbuffer: unreadOutput,\n\t\t\t\ttimer: null,\n\t\t\t\tsignal,\n\t\t\t\tonAbort: () => this.resolveWaiter(waiter, \"aborted\"),\n\t\t\t\tresolve,\n\t\t\t};\n\t\t\tthis.waiters.add(waiter);\n\t\t\twaiter.timer = setTimeout(() => this.resolveWaiter(waiter, \"timeout\"), timeoutMs);\n\t\t\tif (signal) {\n\t\t\t\tsignal.addEventListener(\"abort\", waiter.onAbort, { once: true });\n\t\t\t\tif (signal.aborted) this.resolveWaiter(waiter, \"aborted\");\n\t\t\t}\n\t\t});\n\t}\n\n\tdispose(): void {\n\t\tthis.unsubscribeData?.();\n\t\tthis.unsubscribeData = null;\n\t\tthis.settleWaiters(this.exited ? \"exited\" : \"timeout\");\n\t\tthis.screen.dispose();\n\t}\n\n\tprivate settleWaiters(outcome: \"exited\" | \"timeout\"): void {\n\t\tfor (const waiter of [...this.waiters]) this.resolveWaiter(waiter, outcome);\n\t}\n\n\tprivate resolveWaiter(waiter: OutputWaiter, outcome: Exclude<OutputWaitOutcome, \"invalid_pattern\">): void {\n\t\tif (!this.waiters.delete(waiter)) return;\n\t\tif (waiter.timer !== null) {\n\t\t\tclearTimeout(waiter.timer);\n\t\t\twaiter.timer = null;\n\t\t}\n\t\twaiter.signal?.removeEventListener(\"abort\", waiter.onAbort);\n\t\twaiter.resolve(outcome);\n\t}\n}\n"]}
1
+ {"version":3,"file":"runtime-session.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/terminal/runtime-session.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,cAAc,EAEd,eAAe,GAGf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,CAAC,MAAM,CAAC,MAAM,CAAC;YAAE,OAAO;QACzC,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YAC3B,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC3B,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC;QACrB,CAAC;QACD,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;QAC5D,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACzB,CAAC;CACD","sourcesContent":["import {\n\tTerminalScreen,\n\ttype TerminalScreenSnapshot,\n\tTerminalSession,\n\ttype TerminalSessionExit,\n\ttype TerminalSessionOptions,\n} from \"@earendil-works/pi-pty\";\nimport { DEFAULT_SCROLLBACK, MAX_SESSION_OUTPUT_CHARS, safeRegExp } from \"./shared.ts\";\n\nexport interface TerminalRuntimeOptions extends TerminalSessionOptions {\n\treadonly scrollback?: number;\n}\n\nexport interface DeltaRead {\n\treadonly text: string;\n\treadonly droppedChars: number;\n}\n\ntype OutputWaitOutcome = \"matched\" | \"exited\" | \"timeout\" | \"aborted\" | \"invalid_pattern\";\n\ninterface OutputWaiter {\n\treadonly regex: RegExp;\n\tbuffer: string;\n\ttimer: ReturnType<typeof setTimeout> | null;\n\treadonly signal: AbortSignal | undefined;\n\treadonly onAbort: () => void;\n\treadonly resolve: (outcome: OutputWaitOutcome) => void;\n}\n\n/**\n * A live terminal session: a pi-pty {@link TerminalSession} plus an xterm screen model,\n * a bounded decoded-output buffer with a per-consumer read cursor, and `wait_for` waiters.\n */\nexport class TerminalRuntimeSession {\n\treadonly session: TerminalSession;\n\treadonly command: string;\n\tprivate readonly screen: TerminalScreen;\n\tprivate readonly decoder = new TextDecoder(\"utf-8\", { fatal: false });\n\tprivate buffer = \"\";\n\tprivate droppedChars = 0;\n\tprivate consumed = 0;\n\tprivate readonly waiters = new Set<OutputWaiter>();\n\tprivate unsubscribeData: (() => void) | null = null;\n\n\tconstructor(command: string, options: TerminalRuntimeOptions) {\n\t\tthis.command = command;\n\t\tthis.screen = new TerminalScreen({\n\t\t\tcols: options.cols,\n\t\t\trows: options.rows,\n\t\t\tscrollback: options.scrollback ?? DEFAULT_SCROLLBACK,\n\t\t});\n\t\tthis.session = new TerminalSession(options);\n\t\tthis.unsubscribeData = this.session.onData((chunk) => this.ingest(chunk));\n\t\tthis.session.onExit(() => this.settleWaiters(\"exited\"));\n\t\tthis.session.start();\n\t}\n\n\tget backend(): string | null {\n\t\treturn this.session.backend;\n\t}\n\n\tget exited(): boolean {\n\t\treturn this.session.exited;\n\t}\n\n\tget exitResult(): TerminalSessionExit | null {\n\t\treturn this.session.exitResult;\n\t}\n\n\t/** Total decoded chars produced so far (including any dropped from the front). */\n\tget totalChars(): number {\n\t\treturn this.droppedChars + this.buffer.length;\n\t}\n\n\tprivate ingest(chunk: Uint8Array): void {\n\t\tconst text = this.decoder.decode(chunk, { stream: true });\n\t\tif (text.length === 0) return;\n\t\tvoid this.screen.feed(text);\n\t\tthis.buffer += text;\n\t\tif (this.buffer.length > MAX_SESSION_OUTPUT_CHARS) {\n\t\t\tconst overflow = this.buffer.length - MAX_SESSION_OUTPUT_CHARS;\n\t\t\tthis.buffer = this.buffer.slice(overflow);\n\t\t\tthis.droppedChars += overflow;\n\t\t}\n\t\tfor (const waiter of this.waiters) {\n\t\t\twaiter.buffer += text;\n\t\t\tif (waiter.regex.test(waiter.buffer)) this.resolveWaiter(waiter, \"matched\");\n\t\t}\n\t}\n\n\t/** Return output produced since the last read and advance the read cursor. */\n\treadDelta(): DeltaRead {\n\t\tconst start = Math.max(this.consumed, this.droppedChars);\n\t\tconst dropped = Math.max(0, this.droppedChars - this.consumed);\n\t\tconst text = this.buffer.slice(start - this.droppedChars);\n\t\tthis.consumed = this.totalChars;\n\t\treturn { text, droppedChars: dropped };\n\t}\n\n\t/** Full retained decoded output (`view:\"log\"`), without advancing the cursor. */\n\tfullOutput(): string {\n\t\treturn this.buffer;\n\t}\n\n\tsnapshot(): TerminalScreenSnapshot {\n\t\treturn this.screen.snapshot();\n\t}\n\n\tresizeScreen(cols: number, rows: number): void {\n\t\tvoid this.screen.resize(cols, rows);\n\t}\n\n\t/**\n\t * Wait until `pattern` matches unread or newly produced output, the session exits, the\n\t * timeout elapses, or the wait is aborted.\n\t */\n\twaitFor(pattern: string, timeoutMs: number, signal?: AbortSignal): Promise<OutputWaitOutcome> {\n\t\tconst regex = safeRegExp(pattern);\n\t\tif (regex === null) return Promise.resolve(\"invalid_pattern\");\n\t\tif (this.exited) return Promise.resolve(\"exited\");\n\t\tif (signal?.aborted) return Promise.resolve(\"aborted\");\n\t\tconst unreadStart = Math.max(this.consumed, this.droppedChars);\n\t\tconst unreadOutput = this.buffer.slice(unreadStart - this.droppedChars);\n\t\tif (regex.test(unreadOutput)) return Promise.resolve(\"matched\");\n\t\treturn new Promise((resolve) => {\n\t\t\tconst waiter: OutputWaiter = {\n\t\t\t\tregex,\n\t\t\t\tbuffer: unreadOutput,\n\t\t\t\ttimer: null,\n\t\t\t\tsignal,\n\t\t\t\tonAbort: () => this.resolveWaiter(waiter, \"aborted\"),\n\t\t\t\tresolve,\n\t\t\t};\n\t\t\tthis.waiters.add(waiter);\n\t\t\twaiter.timer = setTimeout(() => this.resolveWaiter(waiter, \"timeout\"), timeoutMs);\n\t\t\tif (signal) {\n\t\t\t\tsignal.addEventListener(\"abort\", waiter.onAbort, { once: true });\n\t\t\t\tif (signal.aborted) this.resolveWaiter(waiter, \"aborted\");\n\t\t\t}\n\t\t});\n\t}\n\n\tdispose(): void {\n\t\tthis.unsubscribeData?.();\n\t\tthis.unsubscribeData = null;\n\t\tthis.settleWaiters(this.exited ? \"exited\" : \"timeout\");\n\t\tthis.screen.dispose();\n\t}\n\n\tprivate settleWaiters(outcome: \"exited\" | \"timeout\"): void {\n\t\tfor (const waiter of [...this.waiters]) this.resolveWaiter(waiter, outcome);\n\t}\n\n\tprivate resolveWaiter(waiter: OutputWaiter, outcome: Exclude<OutputWaitOutcome, \"invalid_pattern\">): void {\n\t\tif (!this.waiters.delete(waiter)) return;\n\t\tif (waiter.timer !== null) {\n\t\t\tclearTimeout(waiter.timer);\n\t\t\twaiter.timer = null;\n\t\t}\n\t\twaiter.signal?.removeEventListener(\"abort\", waiter.onAbort);\n\t\twaiter.resolve(outcome);\n\t}\n}\n"]}
@@ -16,6 +16,6 @@ export interface NativeModelRegistry {
16
16
  getApiKeyAndHeaders(model: NativeModelInfo): Promise<NativeAuthResult>;
17
17
  getAvailable?(): NativeModelInfo[];
18
18
  }
19
+ export declare function buildNativeEntries(model: NativeModelInfo | undefined, modelRegistry: NativeModelRegistry | undefined, signal?: AbortSignal): Promise<SearchProviderEntry[]>;
19
20
  export declare function buildNativeEntry(model: NativeModelInfo | undefined, modelRegistry: NativeModelRegistry | undefined, id?: string): Promise<SearchProviderEntry | null>;
20
- export declare function buildNativeEntries(model: NativeModelInfo | undefined, modelRegistry: NativeModelRegistry | undefined): Promise<SearchProviderEntry[]>;
21
21
  //# sourceMappingURL=native.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"native.d.ts","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/native.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAkB,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtE,MAAM,WAAW,eAAe;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,gBAAgB,GACzB;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,GAC/D;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAEhC,MAAM,WAAW,mBAAmB;IACnC,mBAAmB,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;IACvE,YAAY,CAAC,IAAI,eAAe,EAAE,CAAC;CACnC;AA0DD,wBAAsB,gBAAgB,CACrC,KAAK,EAAE,eAAe,GAAG,SAAS,EAClC,aAAa,EAAE,mBAAmB,GAAG,SAAS,EAC9C,EAAE,SAAW,GACX,OAAO,CAAC,mBAAmB,GAAG,IAAI,CAAC,CAmBrC;AAmBD,wBAAsB,kBAAkB,CACvC,KAAK,EAAE,eAAe,GAAG,SAAS,EAClC,aAAa,EAAE,mBAAmB,GAAG,SAAS,GAC5C,OAAO,CAAC,mBAAmB,EAAE,CAAC,CAkBhC"}
1
+ {"version":3,"file":"native.d.ts","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/native.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAkB,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtE,MAAM,WAAW,eAAe;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,gBAAgB,GACzB;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,GAC/D;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAEhC,MAAM,WAAW,mBAAmB;IACnC,mBAAmB,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;IACvE,YAAY,CAAC,IAAI,eAAe,EAAE,CAAC;CACnC;AAqID,wBAAsB,kBAAkB,CACvC,KAAK,EAAE,eAAe,GAAG,SAAS,EAClC,aAAa,EAAE,mBAAmB,GAAG,SAAS,EAC9C,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,mBAAmB,EAAE,CAAC,CA6BhC;AAED,wBAAsB,gBAAgB,CACrC,KAAK,EAAE,eAAe,GAAG,SAAS,EAClC,aAAa,EAAE,mBAAmB,GAAG,SAAS,EAC9C,EAAE,SAAW,GACX,OAAO,CAAC,mBAAmB,GAAG,IAAI,CAAC,CAErC"}
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { isAllowedProviderBaseUrl } from "./provider-endpoints.js";
2
3
  function nativeMapping(model) {
3
4
  if (model.provider === "openai" &&
@@ -33,24 +34,73 @@ function nativeMapping(model) {
33
34
  return null;
34
35
  }
35
36
  function buildEndpointUrl(baseUrl, resource) {
36
- const trimmed = baseUrl.replace(/\/+$/, "");
37
+ let configured;
38
+ try {
39
+ configured = new URL(baseUrl);
40
+ }
41
+ catch {
42
+ return baseUrl;
43
+ }
44
+ const trimmedPath = configured.pathname.replace(/\/+$/, "");
37
45
  const resourceSlash = `/${resource}`;
38
- if (trimmed.endsWith(resourceSlash))
39
- return trimmed;
40
- if (/\/v\d+$/.test(trimmed))
41
- return `${trimmed}${resourceSlash}`;
42
- return `${trimmed}/v1${resourceSlash}`;
46
+ if (trimmedPath.endsWith(resourceSlash)) {
47
+ configured.pathname = trimmedPath;
48
+ }
49
+ else if (/\/v\d+$/.test(trimmedPath)) {
50
+ configured.pathname = `${trimmedPath}${resourceSlash}`;
51
+ }
52
+ else {
53
+ configured.pathname = `${trimmedPath}/v1${resourceSlash}`;
54
+ }
55
+ configured.hash = "";
56
+ return configured.href;
43
57
  }
44
- export async function buildNativeEntry(model, modelRegistry, id = "native") {
58
+ function nativeRouteKey(model) {
59
+ const mapping = nativeMapping(model);
60
+ if (!mapping)
61
+ return null;
62
+ const baseUrl = buildEndpointUrl(model.baseUrl, mapping.resource);
63
+ if (!isAllowedProviderBaseUrl(baseUrl))
64
+ return null;
65
+ const routeUrl = new URL(baseUrl);
66
+ routeUrl.hostname = routeUrl.hostname.replace(/\.$/, "");
67
+ return `${mapping.provider}|${routeUrl.href}`;
68
+ }
69
+ function discoveredNativeEntryId(provider, routeKey) {
70
+ const routeFingerprint = createHash("sha256").update(routeKey).digest("hex").slice(0, 16);
71
+ return `native-${provider}-${routeFingerprint}`;
72
+ }
73
+ async function buildNativeEntryForModel(model, modelRegistry, options = {}) {
45
74
  if (!model || !modelRegistry)
46
75
  return null;
76
+ const { id = "native", signal } = options;
47
77
  const mapping = nativeMapping(model);
48
78
  if (!mapping)
49
79
  return null;
50
80
  const baseUrl = buildEndpointUrl(model.baseUrl, mapping.resource);
51
81
  if (!isAllowedProviderBaseUrl(baseUrl))
52
82
  return null;
53
- const auth = await modelRegistry.getApiKeyAndHeaders(model);
83
+ signal?.throwIfAborted();
84
+ const authPromise = modelRegistry.getApiKeyAndHeaders(model);
85
+ let auth;
86
+ if (!signal) {
87
+ auth = await authPromise;
88
+ }
89
+ else {
90
+ signal.throwIfAborted();
91
+ let removeAbortListener = () => { };
92
+ const abortPromise = new Promise((_resolve, reject) => {
93
+ const onAbort = () => reject(signal.reason);
94
+ signal.addEventListener("abort", onAbort, { once: true });
95
+ removeAbortListener = () => signal.removeEventListener("abort", onAbort);
96
+ });
97
+ try {
98
+ auth = await Promise.race([authPromise, abortPromise]);
99
+ }
100
+ finally {
101
+ removeAbortListener();
102
+ }
103
+ }
54
104
  if (!auth.ok || !auth.apiKey)
55
105
  return null;
56
106
  return {
@@ -62,37 +112,37 @@ export async function buildNativeEntry(model, modelRegistry, id = "native") {
62
112
  priority: -1,
63
113
  };
64
114
  }
65
- function nativeEntryKey(entry) {
66
- return `${entry.provider}:${entry.baseUrl ?? ""}:${entry.model ?? ""}`;
67
- }
68
- function stableIdPart(value) {
69
- return (value
70
- .toLowerCase()
71
- .replace(/[^a-z0-9]+/g, "-")
72
- .replace(/^-+|-+$/g, "") || "model");
73
- }
74
- function discoveredNativeEntryId(entry) {
75
- return `native-${entry.provider}-${stableIdPart(entry.model ?? "model")}`;
76
- }
77
- export async function buildNativeEntries(model, modelRegistry) {
115
+ export async function buildNativeEntries(model, modelRegistry, signal) {
116
+ signal?.throwIfAborted();
78
117
  if (!modelRegistry)
79
118
  return [];
80
119
  const entries = [];
81
- const activeEntry = await buildNativeEntry(model, modelRegistry);
82
- if (activeEntry)
83
- entries.push(activeEntry);
84
- const seen = new Set(entries.map(nativeEntryKey));
85
- const availableModels = modelRegistry.getAvailable?.() ?? [];
86
- for (const availableModel of availableModels) {
87
- const entry = await buildNativeEntry(availableModel, modelRegistry, "native-discovered");
88
- if (!entry)
120
+ const seenRoutes = new Set();
121
+ const activeRouteKey = model ? nativeRouteKey(model) : null;
122
+ if (activeRouteKey) {
123
+ seenRoutes.add(activeRouteKey);
124
+ const activeEntry = await buildNativeEntryForModel(model, modelRegistry, { signal });
125
+ if (activeEntry)
126
+ entries.push(activeEntry);
127
+ }
128
+ if (!modelRegistry.getAvailable)
129
+ return entries;
130
+ for (const availableModel of modelRegistry.getAvailable()) {
131
+ const routeKey = nativeRouteKey(availableModel);
132
+ if (!routeKey || seenRoutes.has(routeKey))
89
133
  continue;
90
- const key = nativeEntryKey(entry);
91
- if (seen.has(key))
134
+ seenRoutes.add(routeKey);
135
+ const entry = await buildNativeEntryForModel(availableModel, modelRegistry, {
136
+ id: "native-discovered",
137
+ signal,
138
+ });
139
+ if (!entry)
92
140
  continue;
93
- seen.add(key);
94
- entries.push({ ...entry, id: discoveredNativeEntryId(entry) });
141
+ entries.push({ ...entry, id: discoveredNativeEntryId(entry.provider, routeKey) });
95
142
  }
96
143
  return entries;
97
144
  }
145
+ export async function buildNativeEntry(model, modelRegistry, id = "native") {
146
+ return buildNativeEntryForModel(model, modelRegistry, { id });
147
+ }
98
148
  //# sourceMappingURL=native.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"native.js","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,yB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ClC,aAA8C;IAE9C,IAAI,CAAC,aAAa;QAAE,OAAO,EAAE,CAAC;IAE9B,MAAM,OAAO,GAA0B,EAAE,CAAC;IAC1C,MAAM,WAAW,GAAG,MAAM,gBAAgB,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;IACjE,IAAI,WAAW;QAAE,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IAE3C,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;IAClD,MAAM,eAAe,GAAG,aAAa,CAAC,YAAY,EAAE,EAAE,IAAI,EAAE,CAAC;IAC7D,KAAK,MAAM,cAAc,IAAI,eAAe,EAAE,CAAC;QAC9C,MAAM,KAAK,GAAG,MAAM,gBAAgB,CAAC,cAAc,EAAE,aAAa,EAAE,mBAAmB,CAAC,CAAC;QACzF,IAAI,CAAC,KAAK;YAAE,SAAS;QACrB,MAAM,GAAG,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;QAClC,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,SAAS;QAC5B,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACd,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,EAAE,EAAE,uBAAuB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAChE,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["import { isAllowedProviderBaseUrl } from \"./provider-endpoints.ts\";\nimport type { SearchProvider, SearchProviderEntry } from \"./types.ts\";\n\nexport interface NativeModelInfo {\n\tprovider: string;\n\tid: string;\n\tbaseUrl: string;\n}\n\nexport type NativeAuthResult =\n\t| { ok: true; apiKey?: string; headers?: Record<string, string> }\n\t| { ok: false; error: string };\n\nexport interface NativeModelRegistry {\n\tgetApiKeyAndHeaders(model: NativeModelInfo): Promise<NativeAuthResult>;\n\tgetAvailable?(): NativeModelInfo[];\n}\n\ninterface NativeProviderMapping {\n\tprovider: SearchProvider;\n\tresource: string;\n}\n\nfunction nativeMapping(model: NativeModelInfo): NativeProviderMapping | null {\n\tif (\n\t\tmodel.provider === \"openai\" &&\n\t\t(/^(gpt-5\\.5(-fast)?|gpt-4\\.1(-mini)?)$/.test(model.id) || /^gpt-4o(-mini)?(-\\d{4}-\\d{2}-\\d{2})?$/.test(model.id))\n\t) {\n\t\treturn { provider: \"openai\", resource: \"responses\" };\n\t}\n\n\tif (\n\t\tmodel.provider === \"anthropic\" &&\n\t\t(/^claude-(opus|sonnet)-4(-\\d+)?$/.test(model.id) || /^claude-(opus|sonnet)-4-\\d+-\\d{8}$/.test(model.id))\n\t) {\n\t\treturn { provider: \"anthropic\", resource: \"messages\" };\n\t}\n\n\tif (model.provider === \"xai\" && /^grok-/.test(model.id)) {\n\t\treturn { provider: \"xai\", resource: \"responses\" };\n\t}\n\n\tif (model.provider === \"perplexity\" && /^sonar/.test(model.id)) {\n\t\treturn { provider: \"perplexity\", resource: \"chat/completions\" };\n\t}\n\n\tif ((model.provider === \"z-ai\" || model.provider === \"zai\") && /^glm-/.test(model.id)) {\n\t\treturn { provider: \"z-ai\", resource: \"chat/completions\" };\n\t}\n\n\tif (model.provider === \"kimi-coding\") {\n\t\treturn { provider: \"kimi\", resource: \"search\" };\n\t}\n\n\tif (model.provider === \"openrouter\") {\n\t\tconst slashIndex = model.id.indexOf(\"/\");\n\t\tif (slashIndex <= 0) return null;\n\t\tconst effectiveProvider = model.id.slice(0, slashIndex);\n\t\tconst effectiveId = model.id.slice(slashIndex + 1);\n\t\tif (effectiveProvider === \"openrouter\") return null;\n\t\treturn nativeMapping({ ...model, provider: effectiveProvider, id: effectiveId });\n\t}\n\n\treturn null;\n}\n\nfunction buildEndpointUrl(baseUrl: string, resource: string): string {\n\tconst trimmed = baseUrl.replace(/\\/+$/, \"\");\n\tconst resourceSlash = `/${resource}`;\n\tif (trimmed.endsWith(resourceSlash)) return trimmed;\n\tif (/\\/v\\d+$/.test(trimmed)) return `${trimmed}${resourceSlash}`;\n\treturn `${trimmed}/v1${resourceSlash}`;\n}\n\nexport async function buildNativeEntry(\n\tmodel: NativeModelInfo | undefined,\n\tmodelRegistry: NativeModelRegistry | undefined,\n\tid = \"native\",\n): Promise<SearchProviderEntry | null> {\n\tif (!model || !modelRegistry) return null;\n\n\tconst mapping = nativeMapping(model);\n\tif (!mapping) return null;\n\tconst baseUrl = buildEndpointUrl(model.baseUrl, mapping.resource);\n\tif (!isAllowedProviderBaseUrl(baseUrl)) return null;\n\n\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\tif (!auth.ok || !auth.apiKey) return null;\n\n\treturn {\n\t\tid,\n\t\tprovider: mapping.provider,\n\t\tapiKey: auth.apiKey,\n\t\tbaseUrl,\n\t\tmodel: model.id,\n\t\tpriority: -1,\n\t};\n}\n\nfunction nativeEntryKey(entry: SearchProviderEntry): string {\n\treturn `${entry.provider}:${entry.baseUrl ?? \"\"}:${entry.model ?? \"\"}`;\n}\n\nfunction stableIdPart(value: string): string {\n\treturn (\n\t\tvalue\n\t\t\t.toLowerCase()\n\t\t\t.replace(/[^a-z0-9]+/g, \"-\")\n\t\t\t.replace(/^-+|-+$/g, \"\") || \"model\"\n\t);\n}\n\nfunction discoveredNativeEntryId(entry: SearchProviderEntry): string {\n\treturn `native-${entry.provider}-${stableIdPart(entry.model ?? \"model\")}`;\n}\n\nexport async function buildNativeEntries(\n\tmodel: NativeModelInfo | undefined,\n\tmodelRegistry: NativeModelRegistry | undefined,\n): Promise<SearchProviderEntry[]> {\n\tif (!modelRegistry) return [];\n\n\tconst entries: SearchProviderEntry[] = [];\n\tconst activeEntry = await buildNativeEntry(model, modelRegistry);\n\tif (activeEntry) entries.push(activeEntry);\n\n\tconst seen = new Set(entries.map(nativeEntryKey));\n\tconst availableModels = modelRegistry.getAvailable?.() ?? [];\n\tfor (const availableModel of availableModels) {\n\t\tconst entry = await buildNativeEntry(availableModel, modelRegistry, \"native-discovered\");\n\t\tif (!entry) continue;\n\t\tconst key = nativeEntryKey(entry);\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tentries.push({ ...entry, id: discoveredNativeEntryId(entry) });\n\t}\n\treturn entries;\n}\n"]}
1
+ {"version":3,"file":"native.js","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AA4BnE,SAAS,aAAa,CAAC,KAAsB;IAC5C,IACC,KAAK,CAAC,QAAQ,KAAK,QAAQ;QAC3B,CAAC,uCAAuC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,uCAAuC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,EACjH,CAAC;QACF,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;IACtD,CAAC;IAED,IACC,KAAK,CAAC,QAAQ,KAAK,WAAW;QAC9B,CAAC,iCAAiC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,oCAAoC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,EACxG,CAAC;QACF,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC;IAED,IAAI,KAAK,CAAC,QAAQ,KAAK,KAAK,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC;QACzD,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;IACnD,CAAC;IAED,IAAI,KAAK,CAAC,QAAQ,KAAK,YAAY,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC;QAChE,OAAO,EA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;IAED,IAAI,CAAC,aAAa,CAAC,YAAY;QAAE,OAAO,OAAO,CAAC;IAEhD,KAAK,MAAM,cAAc,IAAI,aAAa,CAAC,YAAY,EAAE,EAAE,CAAC;QAC3D,MAAM,QAAQ,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC;QAChD,IAAI,CAAC,QAAQ,IAAI,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC;YAAE,SAAS;QACpD,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACzB,MAAM,KAAK,GAAG,MAAM,wBAAwB,CAAC,cAAc,EAAE,aAAa,EAAE;YAC3E,EAAE,EAAE,mBAAmB;YACvB,MAAM;SACN,CAAC,CAAC;QACH,IAAI,CAAC,KAAK;YAAE,SAAS;QACrB,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,EAAE,EAAE,uBAAuB,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC;IACnF,CAAC;IAED,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACrC,KAAkC,EAClC,aAA8C,EAC9C,EAAE,GAAG,QAAQ;IAEb,OAAO,wBAAwB,CAAC,KAAK,EAAE,aAAa,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\n\nimport { isAllowedProviderBaseUrl } from \"./provider-endpoints.ts\";\nimport type { SearchProvider, SearchProviderEntry } from \"./types.ts\";\n\nexport interface NativeModelInfo {\n\tprovider: string;\n\tid: string;\n\tbaseUrl: string;\n}\n\nexport type NativeAuthResult =\n\t| { ok: true; apiKey?: string; headers?: Record<string, string> }\n\t| { ok: false; error: string };\n\nexport interface NativeModelRegistry {\n\tgetApiKeyAndHeaders(model: NativeModelInfo): Promise<NativeAuthResult>;\n\tgetAvailable?(): NativeModelInfo[];\n}\n\ninterface NativeProviderMapping {\n\tprovider: SearchProvider;\n\tresource: string;\n}\n\ninterface NativeEntryOptions {\n\tid?: string;\n\tsignal?: AbortSignal;\n}\n\nfunction nativeMapping(model: NativeModelInfo): NativeProviderMapping | null {\n\tif (\n\t\tmodel.provider === \"openai\" &&\n\t\t(/^(gpt-5\\.5(-fast)?|gpt-4\\.1(-mini)?)$/.test(model.id) || /^gpt-4o(-mini)?(-\\d{4}-\\d{2}-\\d{2})?$/.test(model.id))\n\t) {\n\t\treturn { provider: \"openai\", resource: \"responses\" };\n\t}\n\n\tif (\n\t\tmodel.provider === \"anthropic\" &&\n\t\t(/^claude-(opus|sonnet)-4(-\\d+)?$/.test(model.id) || /^claude-(opus|sonnet)-4-\\d+-\\d{8}$/.test(model.id))\n\t) {\n\t\treturn { provider: \"anthropic\", resource: \"messages\" };\n\t}\n\n\tif (model.provider === \"xai\" && /^grok-/.test(model.id)) {\n\t\treturn { provider: \"xai\", resource: \"responses\" };\n\t}\n\n\tif (model.provider === \"perplexity\" && /^sonar/.test(model.id)) {\n\t\treturn { provider: \"perplexity\", resource: \"chat/completions\" };\n\t}\n\n\tif ((model.provider === \"z-ai\" || model.provider === \"zai\") && /^glm-/.test(model.id)) {\n\t\treturn { provider: \"z-ai\", resource: \"chat/completions\" };\n\t}\n\n\tif (model.provider === \"kimi-coding\") {\n\t\treturn { provider: \"kimi\", resource: \"search\" };\n\t}\n\n\tif (model.provider === \"openrouter\") {\n\t\tconst slashIndex = model.id.indexOf(\"/\");\n\t\tif (slashIndex <= 0) return null;\n\t\tconst effectiveProvider = model.id.slice(0, slashIndex);\n\t\tconst effectiveId = model.id.slice(slashIndex + 1);\n\t\tif (effectiveProvider === \"openrouter\") return null;\n\t\treturn nativeMapping({ ...model, provider: effectiveProvider, id: effectiveId });\n\t}\n\n\treturn null;\n}\n\nfunction buildEndpointUrl(baseUrl: string, resource: string): string {\n\tlet configured: URL;\n\ttry {\n\t\tconfigured = new URL(baseUrl);\n\t} catch {\n\t\treturn baseUrl;\n\t}\n\tconst trimmedPath = configured.pathname.replace(/\\/+$/, \"\");\n\tconst resourceSlash = `/${resource}`;\n\tif (trimmedPath.endsWith(resourceSlash)) {\n\t\tconfigured.pathname = trimmedPath;\n\t} else if (/\\/v\\d+$/.test(trimmedPath)) {\n\t\tconfigured.pathname = `${trimmedPath}${resourceSlash}`;\n\t} else {\n\t\tconfigured.pathname = `${trimmedPath}/v1${resourceSlash}`;\n\t}\n\tconfigured.hash = \"\";\n\treturn configured.href;\n}\n\nfunction nativeRouteKey(model: NativeModelInfo): string | null {\n\tconst mapping = nativeMapping(model);\n\tif (!mapping) return null;\n\tconst baseUrl = buildEndpointUrl(model.baseUrl, mapping.resource);\n\tif (!isAllowedProviderBaseUrl(baseUrl)) return null;\n\tconst routeUrl = new URL(baseUrl);\n\trouteUrl.hostname = routeUrl.hostname.replace(/\\.$/, \"\");\n\treturn `${mapping.provider}|${routeUrl.href}`;\n}\n\nfunction discoveredNativeEntryId(provider: SearchProvider, routeKey: string): string {\n\tconst routeFingerprint = createHash(\"sha256\").update(routeKey).digest(\"hex\").slice(0, 16);\n\treturn `native-${provider}-${routeFingerprint}`;\n}\n\nasync function buildNativeEntryForModel(\n\tmodel: NativeModelInfo | undefined,\n\tmodelRegistry: NativeModelRegistry | undefined,\n\toptions: NativeEntryOptions = {},\n): Promise<SearchProviderEntry | null> {\n\tif (!model || !modelRegistry) return null;\n\tconst { id = \"native\", signal } = options;\n\n\tconst mapping = nativeMapping(model);\n\tif (!mapping) return null;\n\tconst baseUrl = buildEndpointUrl(model.baseUrl, mapping.resource);\n\tif (!isAllowedProviderBaseUrl(baseUrl)) return null;\n\n\tsignal?.throwIfAborted();\n\tconst authPromise = modelRegistry.getApiKeyAndHeaders(model);\n\tlet auth: NativeAuthResult;\n\tif (!signal) {\n\t\tauth = await authPromise;\n\t} else {\n\t\tsignal.throwIfAborted();\n\t\tlet removeAbortListener = (): void => {};\n\t\tconst abortPromise = new Promise<never>((_resolve, reject) => {\n\t\t\tconst onAbort = (): void => reject(signal.reason);\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tremoveAbortListener = () => signal.removeEventListener(\"abort\", onAbort);\n\t\t});\n\t\ttry {\n\t\t\tauth = await Promise.race([authPromise, abortPromise]);\n\t\t} finally {\n\t\t\tremoveAbortListener();\n\t\t}\n\t}\n\tif (!auth.ok || !auth.apiKey) return null;\n\n\treturn {\n\t\tid,\n\t\tprovider: mapping.provider,\n\t\tapiKey: auth.apiKey,\n\t\tbaseUrl,\n\t\tmodel: model.id,\n\t\tpriority: -1,\n\t};\n}\nexport async function buildNativeEntries(\n\tmodel: NativeModelInfo | undefined,\n\tmodelRegistry: NativeModelRegistry | undefined,\n\tsignal?: AbortSignal,\n): Promise<SearchProviderEntry[]> {\n\tsignal?.throwIfAborted();\n\tif (!modelRegistry) return [];\n\n\tconst entries: SearchProviderEntry[] = [];\n\tconst seenRoutes = new Set<string>();\n\n\tconst activeRouteKey = model ? nativeRouteKey(model) : null;\n\tif (activeRouteKey) {\n\t\tseenRoutes.add(activeRouteKey);\n\t\tconst activeEntry = await buildNativeEntryForModel(model, modelRegistry, { signal });\n\t\tif (activeEntry) entries.push(activeEntry);\n\t}\n\n\tif (!modelRegistry.getAvailable) return entries;\n\n\tfor (const availableModel of modelRegistry.getAvailable()) {\n\t\tconst routeKey = nativeRouteKey(availableModel);\n\t\tif (!routeKey || seenRoutes.has(routeKey)) continue;\n\t\tseenRoutes.add(routeKey);\n\t\tconst entry = await buildNativeEntryForModel(availableModel, modelRegistry, {\n\t\t\tid: \"native-discovered\",\n\t\t\tsignal,\n\t\t});\n\t\tif (!entry) continue;\n\t\tentries.push({ ...entry, id: discoveredNativeEntryId(entry.provider, routeKey) });\n\t}\n\n\treturn entries;\n}\n\nexport async function buildNativeEntry(\n\tmodel: NativeModelInfo | undefined,\n\tmodelRegistry: NativeModelRegistry | undefined,\n\tid = \"native\",\n): Promise<SearchProviderEntry | null> {\n\treturn buildNativeEntryForModel(model, modelRegistry, { id });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"provider-endpoints.d.ts","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/provider-endpoints.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAkBvE,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,cAAc,GAAG,MAAM,CAEnE;AA0BD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAajE;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,oBAAoB,GAAG,MAAM,CAEhE"}
1
+ {"version":3,"file":"provider-endpoints.d.ts","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/provider-endpoints.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAkBvE,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,cAAc,GAAG,MAAM,CAEnE;AA0BD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAcjE;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,oBAAoB,GAAG,MAAM,CAEhE"}
@@ -29,7 +29,7 @@ function isPrivateIpv4(hostname) {
29
29
  return first === 192 && second === 168;
30
30
  }
31
31
  function isPrivateHostname(hostname) {
32
- const normalized = hostname.toLowerCase().replace(/^\[/, "").replace(/\]$/, "");
32
+ const normalized = hostname.toLowerCase().replace(/^\[/, "").replace(/\]$/, "").replace(/\.$/, "");
33
33
  return (normalized === "localhost" ||
34
34
  normalized.endsWith(".localhost") ||
35
35
  normalized.includes(":") ||
@@ -50,6 +50,7 @@ export function isAllowedProviderBaseUrl(baseUrl) {
50
50
  return (configured.protocol === "https:" &&
51
51
  configured.username === "" &&
52
52
  configured.password === "" &&
53
+ !configured.hostname.endsWith("..") &&
53
54
  !isPrivateHostname(configured.hostname));
54
55
  }
55
56
  export function providerUrl(config) {
@@ -1 +1 @@
1
- {"version":3,"file":"provider-endpoints.js","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/provider-endpoints.ts"],"names":[],"mappings":"AAEA,MAAM,qBAAqB,GAAmC;IAC7D,GAAG,EAAE,2BAA2B;IAChC,MAAM,EAAE,+BAA+B;IACvC,KAAK,EAAE,gDAAgD;IACvD,iBAAiB,EAAE,mCAAmC;IACtD,MAAM,EAAE,kCAAkC;IAC1C,YAAY,EAAE,qDAAqD;IACnE,MAAM,EAAE,yCAAyC;IACjD,MAAM,EAAE,qCAAqC;IAC7C,KAAK,EAAE,qCAAqC;IAC5C,SAAS,EAAE,uCAAuC;IAClD,UAAU,EAAE,kCAAkC;IAC9C,GAAG,EAAE,+BAA+B;IACpC,IAAI,EAAE,uCAAuC;CAC7C,CAAC;AAEF,MAAM,UAAU,kBAAkB,CAAC,QAAwB;IAC1D,OAAO,qBAAqB,CAAC,QAAQ,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,aAAa,CAAC,QAAgB;IACtC,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC;IAC3E,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,GAAG,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC;IAChH,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC7B,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC9B,IAAI,KAAK,KAAK,EAAE,I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CAAC,MAA4B;IACvD,OAAO,MAAM,CAAC,OAAO,IAAI,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import type { SearchProvider, SearchProviderConfig } from \"./types.ts\";\n\nconst DEFAULT_PROVIDER_URLS: Record<SearchProvider, string> = {\n\texa: \"https://api.exa.ai/search\",\n\ttavily: \"https://api.tavily.com/search\",\n\tbrave: \"https://api.search.brave.com/res/v1/web/search\",\n\t\"duckduckgo-html\": \"https://html.duckduckgo.com/html/\",\n\tserper: \"https://google.serper.dev/search\",\n\t\"google-cse\": \"https://customsearch.googleapis.com/customsearch/v1\",\n\t\"z-ai\": \"https://api.z.ai/api/paas/v4/web_search\",\n\topenai: \"https://api.openai.com/v1/responses\",\n\tcodex: \"https://api.openai.com/v1/responses\",\n\tanthropic: \"https://api.anthropic.com/v1/messages\",\n\tperplexity: \"https://api.perplexity.ai/search\",\n\txai: \"https://api.x.ai/v1/responses\",\n\tkimi: \"https://api.kimi.com/coding/v1/search\",\n};\n\nexport function defaultProviderUrl(provider: SearchProvider): string {\n\treturn DEFAULT_PROVIDER_URLS[provider];\n}\n\nfunction isPrivateIpv4(hostname: string): boolean {\n\tconst parts = hostname.split(\".\").map((part) => Number.parseInt(part, 10));\n\tif (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false;\n\tconst first = parts[0] ?? -1;\n\tconst second = parts[1] ?? -1;\n\tif (first === 10 || first === 127 || first === 0 || (first === 169 && second === 254)) return true;\n\tif (first === 172 && second >= 16 && second <= 31) return true;\n\treturn first === 192 && second === 168;\n}\n\nfunction isPrivateHostname(hostname: string): boolean {\n\tconst normalized = hostname.toLowerCase().replace(/^\\[/, \"\").replace(/\\]$/, \"\");\n\treturn (\n\t\tnormalized === \"localhost\" ||\n\t\tnormalized.endsWith(\".localhost\") ||\n\t\tnormalized.includes(\":\") ||\n\t\tnormalized === \"::1\" ||\n\t\tnormalized.startsWith(\"fc\") ||\n\t\tnormalized.startsWith(\"fd\") ||\n\t\t/^fe[89ab][0-9a-f]:/.test(normalized) ||\n\t\tisPrivateIpv4(normalized)\n\t);\n}\n\nexport function isAllowedProviderBaseUrl(baseUrl: string): boolean {\n\tlet configured: URL;\n\ttry {\n\t\tconfigured = new URL(baseUrl);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn (\n\t\tconfigured.protocol === \"https:\" &&\n\t\tconfigured.username === \"\" &&\n\t\tconfigured.password === \"\" &&\n\t\t!isPrivateHostname(configured.hostname)\n\t);\n}\n\nexport function providerUrl(config: SearchProviderConfig): string {\n\treturn config.baseUrl ?? defaultProviderUrl(config.provider);\n}\n"]}
1
+ {"version":3,"file":"provider-endpoints.js","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/provider-endpoints.ts"],"names":[],"mappings":"AAEA,MAAM,qBAAqB,GAAmC;IAC7D,GAAG,EAAE,2BAA2B;IAChC,MAAM,EAAE,+BAA+B;IACvC,KAAK,EAAE,gDAAgD;IACvD,iBAAiB,EAAE,mCAAmC;IACtD,MAAM,EAAE,kCAAkC;IAC1C,YAAY,EAAE,qDAAqD;IACnE,MAAM,EAAE,yCAAyC;IACjD,MAAM,EAAE,qCAAqC;IAC7C,KAAK,EAAE,qCAAqC;IAC5C,SAAS,EAAE,uCAAuC;IAClD,UAAU,EAAE,kCAAkC;IAC9C,GAAG,EAAE,+BAA+B;IACpC,IAAI,EAAE,uCAAuC;CAC7C,CAAC;AAEF,MAAM,UAAU,kBAAkB,CAAC,QAAwB;IAC1D,OAAO,qBAAqB,CAAC,QAAQ,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,aAAa,CAAC,QAAgB;IACtC,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC;IAC3E,IAAI,KAAK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AAC;AAED,MAAM,UAAU,wBAAwB,CAAC,OAAe;IACvD,IAAI,UAAe,CAAC;IACpB,IAAI,CAAC;QACJ,UAAU,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;IACD,OAAO,CACN,UAAU,CAAC,QAAQ,KAAK,QAAQ;QAChC,UAAU,CAAC,QAAQ,KAAK,EAAE;QAC1B,UAAU,CAAC,QAAQ,KAAK,EAAE;QAC1B,CAAC,UAAU,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC;QACnC,CAAC,iBAAiB,CAAC,UAAU,CAAC,QAAQ,CAAC,CACvC,CAAC;AACH,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,MAA4B;IACvD,OAAO,MAAM,CAAC,OAAO,IAAI,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import type { SearchProvider, SearchProviderConfig } from \"./types.ts\";\n\nconst DEFAULT_PROVIDER_URLS: Record<SearchProvider, string> = {\n\texa: \"https://api.exa.ai/search\",\n\ttavily: \"https://api.tavily.com/search\",\n\tbrave: \"https://api.search.brave.com/res/v1/web/search\",\n\t\"duckduckgo-html\": \"https://html.duckduckgo.com/html/\",\n\tserper: \"https://google.serper.dev/search\",\n\t\"google-cse\": \"https://customsearch.googleapis.com/customsearch/v1\",\n\t\"z-ai\": \"https://api.z.ai/api/paas/v4/web_search\",\n\topenai: \"https://api.openai.com/v1/responses\",\n\tcodex: \"https://api.openai.com/v1/responses\",\n\tanthropic: \"https://api.anthropic.com/v1/messages\",\n\tperplexity: \"https://api.perplexity.ai/search\",\n\txai: \"https://api.x.ai/v1/responses\",\n\tkimi: \"https://api.kimi.com/coding/v1/search\",\n};\n\nexport function defaultProviderUrl(provider: SearchProvider): string {\n\treturn DEFAULT_PROVIDER_URLS[provider];\n}\n\nfunction isPrivateIpv4(hostname: string): boolean {\n\tconst parts = hostname.split(\".\").map((part) => Number.parseInt(part, 10));\n\tif (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false;\n\tconst first = parts[0] ?? -1;\n\tconst second = parts[1] ?? -1;\n\tif (first === 10 || first === 127 || first === 0 || (first === 169 && second === 254)) return true;\n\tif (first === 172 && second >= 16 && second <= 31) return true;\n\treturn first === 192 && second === 168;\n}\n\nfunction isPrivateHostname(hostname: string): boolean {\n\tconst normalized = hostname.toLowerCase().replace(/^\\[/, \"\").replace(/\\]$/, \"\").replace(/\\.$/, \"\");\n\treturn (\n\t\tnormalized === \"localhost\" ||\n\t\tnormalized.endsWith(\".localhost\") ||\n\t\tnormalized.includes(\":\") ||\n\t\tnormalized === \"::1\" ||\n\t\tnormalized.startsWith(\"fc\") ||\n\t\tnormalized.startsWith(\"fd\") ||\n\t\t/^fe[89ab][0-9a-f]:/.test(normalized) ||\n\t\tisPrivateIpv4(normalized)\n\t);\n}\n\nexport function isAllowedProviderBaseUrl(baseUrl: string): boolean {\n\tlet configured: URL;\n\ttry {\n\t\tconfigured = new URL(baseUrl);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn (\n\t\tconfigured.protocol === \"https:\" &&\n\t\tconfigured.username === \"\" &&\n\t\tconfigured.password === \"\" &&\n\t\t!configured.hostname.endsWith(\"..\") &&\n\t\t!isPrivateHostname(configured.hostname)\n\t);\n}\n\nexport function providerUrl(config: SearchProviderConfig): string {\n\treturn config.baseUrl ?? defaultProviderUrl(config.provider);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAK/C,OAAO,KAAK,EACX,gBAAgB,EAIhB,mBAAmB,EAEnB,MAAM,YAAY,CAAC;AAEpB,QAAA,MAAM,MAAM;;;;EAWX,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,MAAM,gBAAgB,CAAC;AACpD,KAAK,aAAa,GAAG,UAAU,CAAC,OAAO,UAAU,CAAC,OAAO,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAAC;AA0BvF,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,cAAc,GAAG,aAAa,CA6D5E;AAED,eAAO,MAAM,UAAU;;;;yFAIpB,CAAC"}
1
+ {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAK/C,OAAO,KAAK,EACX,gBAAgB,EAIhB,mBAAmB,EAEnB,MAAM,YAAY,CAAC;AAEpB,QAAA,MAAM,MAAM;;;;EAWX,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,MAAM,gBAAgB,CAAC;AACpD,KAAK,aAAa,GAAG,UAAU,CAAC,OAAO,UAAU,CAAC,OAAO,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAAC;AA8BvF,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,cAAc,GAAG,aAAa,CA6D5E;AAED,eAAO,MAAM,UAAU;;;;yFAIpB,CAAC"}
@@ -8,10 +8,10 @@ const Params = Type.Object({
8
8
  allowed_domains: Type.Optional(Type.Array(Type.String(), { description: "Only include search results from these domains" })),
9
9
  blocked_domains: Type.Optional(Type.Array(Type.String(), { description: "Never include search results from these domains" })),
10
10
  }, { additionalProperties: false });
11
- async function configWithNativeRoute(config, ctx) {
11
+ async function configWithNativeRoute(config, ctx, signal) {
12
12
  if (!config.auto)
13
13
  return config;
14
- const nativeEntries = await buildNativeEntries(ctx?.model, ctx?.modelRegistry);
14
+ const nativeEntries = await buildNativeEntries(ctx?.model, ctx?.modelRegistry, signal);
15
15
  return nativeEntries.length > 0 ? { ...config, providers: [...nativeEntries, ...config.providers] } : config;
16
16
  }
17
17
  function providerLabel(provider) {
@@ -46,7 +46,7 @@ export function createWebSearchTool(getConfig) {
46
46
  return { content: [{ type: "text", text: loaded.message }], details };
47
47
  }
48
48
  const maxResults = loaded.config.providers[0]?.maxResults ?? 10;
49
- const config = await configWithNativeRoute(loaded.config, ctx);
49
+ const config = await configWithNativeRoute(loaded.config, ctx, signal);
50
50
  const progressDetails = {
51
51
  phase: "searching",
52
52
  query: params.query,
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EAAE,kBAAkB,EAAkD,MAAM,aAAa,CAAC;AACjG,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACtE,OAAO,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,aAAa,EAA2B,MAAM,aAAa,CAAC;AAUjH,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CACzB;IACC,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,WAAW,EAAE,yBAAyB,EAAE,CAAC;IAC5E,eAAe,EAAE,IAAI,CAAC,QAAQ,CAC7B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,gDAAgD,EAAE,CAAC,CAC5F;IACD,eAAe,EAAE,IAAI,CAAC,QAAQ,CAC7B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC,CAC7F;CACD,EACD,EAAE,oBAAoB,EAAE,KAAK,EAAE,CAC/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AAC,EAAE,cAAc,EAAE,MAAM,CAAC,eAAe,EAAE,CAAC;gBAC3F,GAAG,CAAC,MAAM,CAAC,eAAe,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,MAAM,CAAC,eAAe,EAAE,CAAC;aAC3F,CAAC;YACF,MAAM,OAAO,GAAG,MAAM,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,CAAC;YAC3E,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC;QAClF,CAAC;QACD,UAAU,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,gBAAgB,CAAC,IAAI,EAAE,KAAK,CAAC;QAC1D,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,CAAC,kBAAkB,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC;KACpF,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,UAAU,GAAG,mBAAmB,CAAC,GAAG,EAAE,CAAC,CAAC;IACpD,EAAE,EAAE,KAAK;IACT,MAAM,EAAE,gBAAgB;IACxB,OAAO,EAAE,iGAAiG;CAC1G,CAAC,CAAC,CAAC","sourcesContent":["import { Type } from \"typebox\";\nimport { defineTool } from \"../../../types.ts\";\n\nimport { buildNativeEntries, type NativeModelInfo, type NativeModelRegistry } from \"./native.ts\";\nimport { renderSearchCall, renderSearchResult } from \"./renderers.ts\";\nimport { createSearchRoutingState, formatSearchText, performSearch, type SearchRoutingState } from \"./search.ts\";\nimport type {\n\tConfigLoadResult,\n\tSearchErrorDetails,\n\tSearchProgressDetails,\n\tSearchProviderEntry,\n\tSearchRenderDetails,\n\tWebsearchConfig,\n} from \"./types.ts\";\n\nconst Params = Type.Object(\n\t{\n\t\tquery: Type.String({ minLength: 2, description: \"The search query to use\" }),\n\t\tallowed_domains: Type.Optional(\n\t\t\tType.Array(Type.String(), { description: \"Only include search results from these domains\" }),\n\t\t),\n\t\tblocked_domains: Type.Optional(\n\t\t\tType.Array(Type.String(), { description: \"Never include search results from these domains\" }),\n\t\t),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type ConfigProvider = () => ConfigLoadResult;\ntype WebSearchTool = ReturnType<typeof defineTool<typeof Params, SearchRenderDetails>>;\n\ninterface WebSearchToolContext {\n\tmodel: NativeModelInfo | undefined;\n\tmodelRegistry: NativeModelRegistry;\n}\n\nasync function configWithNativeRoute(config: WebsearchConfig, ctx?: WebSearchToolContext): Promise<WebsearchConfig> {\n\tif (!config.auto) return config;\n\tconst nativeEntries = await buildNativeEntries(ctx?.model, ctx?.modelRegistry);\n\treturn nativeEntries.length > 0 ? { ...config, providers: [...nativeEntries, ...config.providers] } : config;\n}\n\nfunction providerLabel(provider: SearchProviderEntry): string {\n\treturn provider.id ? `${provider.id}/${provider.provider}` : provider.provider;\n}\n\nfunction formatSearchProgressText(details: SearchProgressDetails): string {\n\tconst route = details.providerLabels.length > 0 ? details.providerLabels.join(\" -> \") : \"configured providers\";\n\treturn `Searching \"${details.query}\" via ${route} (max ${details.maxResults})`;\n}\n\nfunction searchErrorDetails(query: string, error: string, reason?: SearchErrorDetails[\"reason\"]): SearchErrorDetails {\n\treturn { phase: \"error\", query, error, ...(reason ? { reason } : {}) };\n}\n\nexport function createWebSearchTool(getConfig: ConfigProvider): WebSearchTool {\n\tlet routingState: SearchRoutingState | undefined;\n\tlet routingKey = \"\";\n\n\treturn defineTool<typeof Params, SearchRenderDetails>({\n\t\tname: \"web_search\",\n\t\tlabel: \"Web Search\",\n\t\tdescription: \"Search the web for current information and return source URLs for citation.\",\n\t\tpromptSnippet: \"Search the web for current information, documentation, news, or external facts.\",\n\t\tpromptGuidelines: [\"After using web_search, cite relevant returned URLs in the final answer.\"],\n\t\tparameters: Params,\n\t\tasync execute(_toolCallId, params, signal, onUpdate, ctx?: WebSearchToolContext) {\n\t\t\tif (params.allowed_domains?.length && params.blocked_domains?.length) {\n\t\t\t\tconst message = \"Error: Cannot specify both allowed_domains and blocked_domains in the same request\";\n\t\t\t\tconst details = searchErrorDetails(params.query, message);\n\t\t\t\treturn { content: [{ type: \"text\", text: message }], details };\n\t\t\t}\n\n\t\t\tconst loaded = getConfig();\n\t\t\tif (!loaded.ok) {\n\t\t\t\tconst details = searchErrorDetails(params.query, loaded.message, loaded.reason);\n\t\t\t\treturn { content: [{ type: \"text\", text: loaded.message }], details };\n\t\t\t}\n\n\t\t\tconst maxResults = loaded.config.providers[0]?.maxResults ?? 10;\n\t\t\tconst config = await configWithNativeRoute(loaded.config, ctx);\n\t\t\tconst progressDetails: SearchProgressDetails = {\n\t\t\t\tphase: \"searching\",\n\t\t\t\tquery: params.query,\n\t\t\t\tproviderLabels: config.providers.map(providerLabel),\n\t\t\t\tmaxResults,\n\t\t\t\tstrategy: config.strategy,\n\t\t\t\t...(params.allowed_domains ? { allowedDomains: params.allowed_domains } : {}),\n\t\t\t\t...(params.blocked_domains ? { blockedDomains: params.blocked_domains } : {}),\n\t\t\t};\n\t\t\tonUpdate?.({\n\t\t\t\tcontent: [{ type: \"text\", text: formatSearchProgressText(progressDetails) }],\n\t\t\t\tdetails: progressDetails,\n\t\t\t});\n\n\t\t\tconst nextRoutingKey = `${config.strategy}:${config.providers.map((provider) => provider.id ?? provider.provider).join(\"|\")}`;\n\t\t\tif (\n\t\t\t\t!routingState ||\n\t\t\t\troutingKey !== nextRoutingKey ||\n\t\t\t\troutingState.successCounts.length !== config.providers.length\n\t\t\t) {\n\t\t\t\troutingState = createSearchRoutingState(config.providers.length);\n\t\t\t\troutingKey = nextRoutingKey;\n\t\t\t}\n\t\t\tconst request = {\n\t\t\t\tquery: params.query,\n\t\t\t\tmaxResults,\n\t\t\t\t...(params.allowed_domains === undefined ? {} : { allowedDomains: params.allowed_domains }),\n\t\t\t\t...(params.blocked_domains === undefined ? {} : { blockedDomains: params.blocked_domains }),\n\t\t\t};\n\t\t\tconst details = await performSearch(config, request, signal, routingState);\n\t\t\treturn { content: [{ type: \"text\", text: formatSearchText(details) }], details };\n\t\t},\n\t\trenderCall: (args, theme) => renderSearchCall(args, theme),\n\t\trenderResult: (result, options, theme) => renderSearchResult(result, options, theme),\n\t});\n}\n\nexport const web_search = createWebSearchTool(() => ({\n\tok: false,\n\treason: \"missing_config\",\n\tmessage: \"Missing websearch config. Create .pi/websearch.json or ~/.pi/websearch.json before starting pi.\",\n}));\n"]}
1
+ {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../../../../src/core/extensions/builtin/websearch/websearch/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EAAE,kBAAkB,EAAkD,MAAM,aAAa,CAAC;AACjG,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACtE,OAAO,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,aAAa,EAA2B,MAAM,aAAa,CAAC;AAUjH,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CACzB;IACC,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,WAAW,EAAE,yBAAyB,EAAE,CAAC;IAC5E,eAAe,EAAE,IAAI,CAAC,QAAQ,CAC7B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,gDAAgD,EAAE,CAAC,CAC5F;IACD,eAAe,EAAE,IAAI,CAAC,QAAQ,CAC7B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC,CAC7F;CACD,EACD,EAAE,oBAAoB,EAAE,K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e,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,MAAM,CAAC,eAAe,EAAE,CAAC;gBAC3F,GAAG,CAAC,MAAM,CAAC,eAAe,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,MAAM,CAAC,eAAe,EAAE,CAAC;aAC3F,CAAC;YACF,MAAM,OAAO,GAAG,MAAM,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,CAAC;YAC3E,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC;QAClF,CAAC;QACD,UAAU,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,gBAAgB,CAAC,IAAI,EAAE,KAAK,CAAC;QAC1D,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,CAAC,kBAAkB,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC;KACpF,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,UAAU,GAAG,mBAAmB,CAAC,GAAG,EAAE,CAAC,CAAC;IACpD,EAAE,EAAE,KAAK;IACT,MAAM,EAAE,gBAAgB;IACxB,OAAO,EAAE,iGAAiG;CAC1G,CAAC,CAAC,CAAC","sourcesContent":["import { Type } from \"typebox\";\nimport { defineTool } from \"../../../types.ts\";\n\nimport { buildNativeEntries, type NativeModelInfo, type NativeModelRegistry } from \"./native.ts\";\nimport { renderSearchCall, renderSearchResult } from \"./renderers.ts\";\nimport { createSearchRoutingState, formatSearchText, performSearch, type SearchRoutingState } from \"./search.ts\";\nimport type {\n\tConfigLoadResult,\n\tSearchErrorDetails,\n\tSearchProgressDetails,\n\tSearchProviderEntry,\n\tSearchRenderDetails,\n\tWebsearchConfig,\n} from \"./types.ts\";\n\nconst Params = Type.Object(\n\t{\n\t\tquery: Type.String({ minLength: 2, description: \"The search query to use\" }),\n\t\tallowed_domains: Type.Optional(\n\t\t\tType.Array(Type.String(), { description: \"Only include search results from these domains\" }),\n\t\t),\n\t\tblocked_domains: Type.Optional(\n\t\t\tType.Array(Type.String(), { description: \"Never include search results from these domains\" }),\n\t\t),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type ConfigProvider = () => ConfigLoadResult;\ntype WebSearchTool = ReturnType<typeof defineTool<typeof Params, SearchRenderDetails>>;\n\ninterface WebSearchToolContext {\n\tmodel: NativeModelInfo | undefined;\n\tmodelRegistry: NativeModelRegistry;\n}\n\nasync function configWithNativeRoute(\n\tconfig: WebsearchConfig,\n\tctx: WebSearchToolContext | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<WebsearchConfig> {\n\tif (!config.auto) return config;\n\tconst nativeEntries = await buildNativeEntries(ctx?.model, ctx?.modelRegistry, signal);\n\treturn nativeEntries.length > 0 ? { ...config, providers: [...nativeEntries, ...config.providers] } : config;\n}\n\nfunction providerLabel(provider: SearchProviderEntry): string {\n\treturn provider.id ? `${provider.id}/${provider.provider}` : provider.provider;\n}\n\nfunction formatSearchProgressText(details: SearchProgressDetails): string {\n\tconst route = details.providerLabels.length > 0 ? details.providerLabels.join(\" -> \") : \"configured providers\";\n\treturn `Searching \"${details.query}\" via ${route} (max ${details.maxResults})`;\n}\n\nfunction searchErrorDetails(query: string, error: string, reason?: SearchErrorDetails[\"reason\"]): SearchErrorDetails {\n\treturn { phase: \"error\", query, error, ...(reason ? { reason } : {}) };\n}\n\nexport function createWebSearchTool(getConfig: ConfigProvider): WebSearchTool {\n\tlet routingState: SearchRoutingState | undefined;\n\tlet routingKey = \"\";\n\n\treturn defineTool<typeof Params, SearchRenderDetails>({\n\t\tname: \"web_search\",\n\t\tlabel: \"Web Search\",\n\t\tdescription: \"Search the web for current information and return source URLs for citation.\",\n\t\tpromptSnippet: \"Search the web for current information, documentation, news, or external facts.\",\n\t\tpromptGuidelines: [\"After using web_search, cite relevant returned URLs in the final answer.\"],\n\t\tparameters: Params,\n\t\tasync execute(_toolCallId, params, signal, onUpdate, ctx?: WebSearchToolContext) {\n\t\t\tif (params.allowed_domains?.length && params.blocked_domains?.length) {\n\t\t\t\tconst message = \"Error: Cannot specify both allowed_domains and blocked_domains in the same request\";\n\t\t\t\tconst details = searchErrorDetails(params.query, message);\n\t\t\t\treturn { content: [{ type: \"text\", text: message }], details };\n\t\t\t}\n\n\t\t\tconst loaded = getConfig();\n\t\t\tif (!loaded.ok) {\n\t\t\t\tconst details = searchErrorDetails(params.query, loaded.message, loaded.reason);\n\t\t\t\treturn { content: [{ type: \"text\", text: loaded.message }], details };\n\t\t\t}\n\n\t\t\tconst maxResults = loaded.config.providers[0]?.maxResults ?? 10;\n\t\t\tconst config = await configWithNativeRoute(loaded.config, ctx, signal);\n\t\t\tconst progressDetails: SearchProgressDetails = {\n\t\t\t\tphase: \"searching\",\n\t\t\t\tquery: params.query,\n\t\t\t\tproviderLabels: config.providers.map(providerLabel),\n\t\t\t\tmaxResults,\n\t\t\t\tstrategy: config.strategy,\n\t\t\t\t...(params.allowed_domains ? { allowedDomains: params.allowed_domains } : {}),\n\t\t\t\t...(params.blocked_domains ? { blockedDomains: params.blocked_domains } : {}),\n\t\t\t};\n\t\t\tonUpdate?.({\n\t\t\t\tcontent: [{ type: \"text\", text: formatSearchProgressText(progressDetails) }],\n\t\t\t\tdetails: progressDetails,\n\t\t\t});\n\n\t\t\tconst nextRoutingKey = `${config.strategy}:${config.providers.map((provider) => provider.id ?? provider.provider).join(\"|\")}`;\n\t\t\tif (\n\t\t\t\t!routingState ||\n\t\t\t\troutingKey !== nextRoutingKey ||\n\t\t\t\troutingState.successCounts.length !== config.providers.length\n\t\t\t) {\n\t\t\t\troutingState = createSearchRoutingState(config.providers.length);\n\t\t\t\troutingKey = nextRoutingKey;\n\t\t\t}\n\t\t\tconst request = {\n\t\t\t\tquery: params.query,\n\t\t\t\tmaxResults,\n\t\t\t\t...(params.allowed_domains === undefined ? {} : { allowedDomains: params.allowed_domains }),\n\t\t\t\t...(params.blocked_domains === undefined ? {} : { blockedDomains: params.blocked_domains }),\n\t\t\t};\n\t\t\tconst details = await performSearch(config, request, signal, routingState);\n\t\t\treturn { content: [{ type: \"text\", text: formatSearchText(details) }], details };\n\t\t},\n\t\trenderCall: (args, theme) => renderSearchCall(args, theme),\n\t\trenderResult: (result, options, theme) => renderSearchResult(result, options, theme),\n\t});\n}\n\nexport const web_search = createWebSearchTool(() => ({\n\tok: false,\n\treason: \"missing_config\",\n\tmessage: \"Missing websearch config. Create .pi/websearch.json or ~/.pi/websearch.json before starting pi.\",\n}));\n"]}