@mcoda/codali 0.1.135-codali.4 → 0.1.135-codali.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +204 -1
- package/ORCHESTRATION.md +356 -21
- package/README.md +234 -22
- package/config/AGENTS.md +17 -0
- package/config/browser-desktop/Dockerfile +7 -0
- package/config/browser-desktop/preview.py +15 -0
- package/config/browser-desktop/start.sh +12 -0
- package/config/deterministic/install-python.mjs +16 -0
- package/config/deterministic/node-worker.mjs +77 -0
- package/config/deterministic/python-worker.py +237 -0
- package/config/deterministic/requirements.txt +6 -0
- package/config/docdex-tools-0.2.99.json +3977 -0
- package/config/documents/install-python.mjs +16 -0
- package/config/documents/requirements.txt +10 -0
- package/config/documents/worker.py +267 -0
- package/config/orchestration.schema.json +131 -0
- package/config/skills/architecture-design/SKILL.md +14 -0
- package/config/skills/browser-session/SKILL.md +16 -0
- package/config/skills/browser-use/SKILL.md +14 -0
- package/config/skills/code-implementation/SKILL.md +18 -0
- package/config/skills/code-review/SKILL.md +14 -0
- package/config/skills/docdex-research/SKILL.md +18 -0
- package/config/skills/docdex-research/references/catalog.md +111 -0
- package/config/skills/docdex-research/references/memory.md +22 -0
- package/config/skills/docdex-research/references/operations.md +19 -0
- package/config/skills/docdex-research/references/retrieval.md +13 -0
- package/config/skills/planning/SKILL.md +14 -0
- package/config/skills/system-diagnostics/SKILL.md +14 -0
- package/config/skills/system-services/SKILL.md +17 -0
- package/config/skills/system-services/references/docker.md +11 -0
- package/config/skills/system-services/references/linux.md +9 -0
- package/config/skills/system-services/references/macos.md +9 -0
- package/config/skills/systematic-debugging/SKILL.md +14 -0
- package/config/skills/testing-and-verification/SKILL.md +16 -0
- package/config/skills/tool-selection/SKILL.md +16 -0
- package/config/skills/ui-ux-design/SKILL.md +16 -0
- package/config/skills/ui-ux-design/references/validation.md +13 -0
- package/config/skills/webapp-testing/SKILL.md +12 -0
- package/config/terminal-long-scenarios.v1.json +3 -2
- package/dist/cli/TerminalArtifacts.d.ts +5 -0
- package/dist/cli/TerminalArtifacts.d.ts.map +1 -0
- package/dist/cli/TerminalArtifacts.js +26 -0
- package/dist/cli/TerminalCommand.d.ts +2 -1
- package/dist/cli/TerminalCommand.d.ts.map +1 -1
- package/dist/cli/TerminalCommand.js +436 -100
- package/dist/cli/TerminalInput.d.ts +13 -0
- package/dist/cli/TerminalInput.d.ts.map +1 -1
- package/dist/cli/TerminalInput.js +55 -7
- package/dist/cli/TerminalModels.d.ts +6 -0
- package/dist/cli/TerminalModels.d.ts.map +1 -0
- package/dist/cli/TerminalModels.js +45 -0
- package/dist/cli/TerminalPlan.d.ts +40 -0
- package/dist/cli/TerminalPlan.d.ts.map +1 -0
- package/dist/cli/TerminalPlan.js +37 -0
- package/dist/cli/ToolsCommand.d.ts.map +1 -1
- package/dist/cli/ToolsCommand.js +8 -1
- package/dist/cli/tui/TerminalCells.d.ts +6 -0
- package/dist/cli/tui/TerminalCells.d.ts.map +1 -0
- package/dist/cli/tui/TerminalCells.js +47 -0
- package/dist/cli/tui/TerminalEditor.d.ts +22 -0
- package/dist/cli/tui/TerminalEditor.d.ts.map +1 -0
- package/dist/cli/tui/TerminalEditor.js +88 -0
- package/dist/cli/tui/TerminalLogo.d.ts +6 -0
- package/dist/cli/tui/TerminalLogo.d.ts.map +1 -0
- package/dist/cli/tui/TerminalLogo.js +26 -0
- package/dist/cli/tui/TerminalMarkdown.d.ts +5 -0
- package/dist/cli/tui/TerminalMarkdown.d.ts.map +1 -0
- package/dist/cli/tui/TerminalMarkdown.js +118 -0
- package/dist/cli/tui/TerminalPresentation.d.ts +6 -0
- package/dist/cli/tui/TerminalPresentation.d.ts.map +1 -0
- package/dist/cli/tui/TerminalPresentation.js +152 -0
- package/dist/cli/tui/TerminalScreen.d.ts +50 -0
- package/dist/cli/tui/TerminalScreen.d.ts.map +1 -0
- package/dist/cli/tui/TerminalScreen.js +137 -0
- package/dist/cli/tui/TerminalSelection.d.ts +15 -0
- package/dist/cli/tui/TerminalSelection.d.ts.map +1 -0
- package/dist/cli/tui/TerminalSelection.js +38 -0
- package/dist/cli/tui/TerminalTui.d.ts +82 -0
- package/dist/cli/tui/TerminalTui.d.ts.map +1 -0
- package/dist/cli/tui/TerminalTui.js +564 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +5 -3
- package/dist/config/OrchestrationConfig.d.ts +40 -0
- package/dist/config/OrchestrationConfig.d.ts.map +1 -1
- package/dist/config/OrchestrationConfig.js +79 -5
- package/dist/connectors/media/MediaJobStore.d.ts +2 -1
- package/dist/connectors/media/MediaJobStore.d.ts.map +1 -1
- package/dist/connectors/media/MediaJobStore.js +11 -3
- package/dist/docdex/DocdexCatalog.d.ts +12 -0
- package/dist/docdex/DocdexCatalog.d.ts.map +1 -0
- package/dist/docdex/DocdexCatalog.js +30 -0
- package/dist/docdex/DocdexClient.d.ts +15 -2
- package/dist/docdex/DocdexClient.d.ts.map +1 -1
- package/dist/docdex/DocdexClient.js +119 -12
- package/dist/docdex/ManagedDocdex.d.ts +4 -0
- package/dist/docdex/ManagedDocdex.d.ts.map +1 -1
- package/dist/docdex/ManagedDocdex.js +42 -5
- package/dist/eval/EvaluationProcess.d.ts.map +1 -1
- package/dist/eval/EvaluationProcess.js +4 -0
- package/dist/eval/TerminalWorkflowCorpus.d.ts +1 -1
- package/dist/eval/TerminalWorkflowCorpus.d.ts.map +1 -1
- package/dist/eval/TerminalWorkflowCorpus.js +9 -6
- package/dist/eval/TrustBenchmark.d.ts +94 -0
- package/dist/eval/TrustBenchmark.d.ts.map +1 -0
- package/dist/eval/TrustBenchmark.js +199 -0
- package/dist/eval/fixtures/ContractReviewProvider.d.ts +4 -0
- package/dist/eval/fixtures/ContractReviewProvider.d.ts.map +1 -0
- package/dist/eval/fixtures/ContractReviewProvider.js +10 -0
- package/dist/eval/fixtures/MixedMediaRecoveryJourney.d.ts +6 -0
- package/dist/eval/fixtures/MixedMediaRecoveryJourney.d.ts.map +1 -0
- package/dist/eval/fixtures/MixedMediaRecoveryJourney.js +145 -0
- package/dist/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -1
- package/dist/eval/fixtures/TerminalRecoveryJourney.js +14 -1
- package/dist/gateway/GroundingMode.d.ts.map +1 -1
- package/dist/gateway/GroundingMode.js +23 -3
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/permissions/PermissionGate.d.ts +4 -1
- package/dist/permissions/PermissionGate.d.ts.map +1 -1
- package/dist/permissions/PermissionGate.js +50 -5
- package/dist/permissions/WorkspacePermissions.d.ts +11 -0
- package/dist/permissions/WorkspacePermissions.d.ts.map +1 -0
- package/dist/permissions/WorkspacePermissions.js +42 -0
- package/dist/providers/ConfiguredModelScope.d.ts +1 -0
- package/dist/providers/ConfiguredModelScope.d.ts.map +1 -1
- package/dist/providers/ConfiguredModelScope.js +19 -2
- package/dist/providers/ConfiguredProvider.d.ts +10 -1
- package/dist/providers/ConfiguredProvider.d.ts.map +1 -1
- package/dist/providers/ConfiguredProvider.js +104 -37
- package/dist/providers/ModelCapacityWait.d.ts +21 -0
- package/dist/providers/ModelCapacityWait.d.ts.map +1 -0
- package/dist/providers/ModelCapacityWait.js +40 -0
- package/dist/providers/ModelServiceError.d.ts +16 -2
- package/dist/providers/ModelServiceError.d.ts.map +1 -1
- package/dist/providers/ModelServiceError.js +37 -5
- package/dist/providers/OpenAiCompatibleProvider.d.ts +8 -0
- package/dist/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
- package/dist/providers/OpenAiCompatibleProvider.js +38 -3
- package/dist/providers/ProviderTypes.d.ts +9 -0
- package/dist/providers/ProviderTypes.d.ts.map +1 -1
- package/dist/providers/RequestSize.d.ts +5 -0
- package/dist/providers/RequestSize.d.ts.map +1 -0
- package/dist/providers/RequestSize.js +10 -0
- package/dist/providers/RequestUsage.d.ts +11 -0
- package/dist/providers/RequestUsage.d.ts.map +1 -0
- package/dist/providers/RequestUsage.js +33 -0
- package/dist/runtime/AnswerVerification.d.ts +31 -0
- package/dist/runtime/AnswerVerification.d.ts.map +1 -0
- package/dist/runtime/AnswerVerification.js +65 -0
- package/dist/runtime/CodaliRuntime.d.ts +1 -0
- package/dist/runtime/CodaliRuntime.d.ts.map +1 -1
- package/dist/runtime/CodaliRuntime.js +1 -0
- package/dist/runtime/CompletionReport.d.ts +8 -0
- package/dist/runtime/CompletionReport.d.ts.map +1 -1
- package/dist/runtime/CompletionReport.js +25 -0
- package/dist/runtime/ComputedAnswer.d.ts +13 -0
- package/dist/runtime/ComputedAnswer.d.ts.map +1 -0
- package/dist/runtime/ComputedAnswer.js +75 -0
- package/dist/runtime/ContextCompression.d.ts +41 -0
- package/dist/runtime/ContextCompression.d.ts.map +1 -0
- package/dist/runtime/ContextCompression.js +292 -0
- package/dist/runtime/FigureCheck.d.ts +20 -0
- package/dist/runtime/FigureCheck.d.ts.map +1 -0
- package/dist/runtime/FigureCheck.js +44 -0
- package/dist/runtime/GatewayRequest.d.ts +5 -0
- package/dist/runtime/GatewayRequest.d.ts.map +1 -0
- package/dist/runtime/GatewayRequest.js +19 -0
- package/dist/runtime/InspectionBudget.d.ts +11 -0
- package/dist/runtime/InspectionBudget.d.ts.map +1 -0
- package/dist/runtime/InspectionBudget.js +23 -0
- package/dist/runtime/InspectionConvergence.d.ts +24 -0
- package/dist/runtime/InspectionConvergence.d.ts.map +1 -0
- package/dist/runtime/InspectionConvergence.js +67 -0
- package/dist/runtime/InteractionContract.d.ts +51 -0
- package/dist/runtime/InteractionContract.d.ts.map +1 -0
- package/dist/runtime/InteractionContract.js +72 -0
- package/dist/runtime/InteractionRouter.d.ts +73 -0
- package/dist/runtime/InteractionRouter.d.ts.map +1 -0
- package/dist/runtime/InteractionRouter.js +139 -0
- package/dist/runtime/OutageWait.d.ts +14 -0
- package/dist/runtime/OutageWait.d.ts.map +1 -0
- package/dist/runtime/OutageWait.js +33 -0
- package/dist/runtime/PlanCoverage.d.ts +9 -0
- package/dist/runtime/PlanCoverage.d.ts.map +1 -0
- package/dist/runtime/PlanCoverage.js +12 -0
- package/dist/runtime/PreparedDocdex.d.ts +4 -0
- package/dist/runtime/PreparedDocdex.d.ts.map +1 -0
- package/dist/runtime/PreparedDocdex.js +55 -0
- package/dist/runtime/PreparedMemory.d.ts +3 -0
- package/dist/runtime/PreparedMemory.d.ts.map +1 -0
- package/dist/runtime/PreparedMemory.js +30 -0
- package/dist/runtime/ProgressTracker.d.ts +1 -0
- package/dist/runtime/ProgressTracker.d.ts.map +1 -1
- package/dist/runtime/ProgressTracker.js +25 -5
- package/dist/runtime/ResearchEvidence.d.ts +25 -0
- package/dist/runtime/ResearchEvidence.d.ts.map +1 -0
- package/dist/runtime/ResearchEvidence.js +101 -0
- package/dist/runtime/ReviewContract.d.ts +35 -0
- package/dist/runtime/ReviewContract.d.ts.map +1 -0
- package/dist/runtime/ReviewContract.js +132 -0
- package/dist/runtime/ReviewCoordinator.d.ts +43 -0
- package/dist/runtime/ReviewCoordinator.d.ts.map +1 -0
- package/dist/runtime/ReviewCoordinator.js +134 -0
- package/dist/runtime/ReviewSource.d.ts +3 -0
- package/dist/runtime/ReviewSource.d.ts.map +1 -1
- package/dist/runtime/ReviewSource.js +17 -1
- package/dist/runtime/Runner.d.ts.map +1 -1
- package/dist/runtime/Runner.js +6 -1
- package/dist/runtime/SessionController.d.ts +146 -6
- package/dist/runtime/SessionController.d.ts.map +1 -1
- package/dist/runtime/SessionController.js +2406 -228
- package/dist/runtime/SpecialistTools.d.ts +8 -0
- package/dist/runtime/SpecialistTools.d.ts.map +1 -0
- package/dist/runtime/SpecialistTools.js +85 -0
- package/dist/runtime/StructuralEvidence.d.ts +4 -2
- package/dist/runtime/StructuralEvidence.d.ts.map +1 -1
- package/dist/runtime/StructuralEvidence.js +22 -5
- package/dist/runtime/TaskReview.d.ts +25 -0
- package/dist/runtime/TaskReview.d.ts.map +1 -0
- package/dist/runtime/TaskReview.js +109 -0
- package/dist/runtime/TaskReviewContext.d.ts +37 -0
- package/dist/runtime/TaskReviewContext.d.ts.map +1 -1
- package/dist/runtime/TaskReviewContext.js +18 -2
- package/dist/runtime/UsageReconciliation.d.ts +28 -0
- package/dist/runtime/UsageReconciliation.d.ts.map +1 -0
- package/dist/runtime/UsageReconciliation.js +68 -0
- package/dist/runtime/VerificationReceiptSelection.d.ts +15 -0
- package/dist/runtime/VerificationReceiptSelection.d.ts.map +1 -0
- package/dist/runtime/VerificationReceiptSelection.js +30 -0
- package/dist/runtime/WorkspaceLedger.d.ts +2 -0
- package/dist/runtime/WorkspaceLedger.d.ts.map +1 -1
- package/dist/runtime/WorkspaceLedger.js +44 -20
- package/dist/runtime/WorkspaceLock.d.ts.map +1 -1
- package/dist/runtime/WorkspaceLock.js +9 -1
- package/dist/runtime/WorkspaceSnapshot.d.ts.map +1 -1
- package/dist/runtime/WorkspaceSnapshot.js +3 -2
- package/dist/runtime/WriteSyntaxCheck.d.ts +10 -0
- package/dist/runtime/WriteSyntaxCheck.d.ts.map +1 -0
- package/dist/runtime/WriteSyntaxCheck.js +34 -0
- package/dist/session/InstructionLoader.d.ts +5 -1
- package/dist/session/InstructionLoader.d.ts.map +1 -1
- package/dist/session/InstructionLoader.js +65 -19
- package/dist/session/SessionStoragePath.d.ts.map +1 -1
- package/dist/session/SessionStoragePath.js +34 -17
- package/dist/session/SessionStore.d.ts +6 -1
- package/dist/session/SessionStore.d.ts.map +1 -1
- package/dist/session/SessionStore.js +108 -43
- package/dist/session/SkillCatalog.d.ts +33 -0
- package/dist/session/SkillCatalog.d.ts.map +1 -0
- package/dist/session/SkillCatalog.js +197 -0
- package/dist/session/WorkState.d.ts +16 -2
- package/dist/session/WorkState.d.ts.map +1 -1
- package/dist/session/WorkState.js +55 -5
- package/dist/session/WorkTypes.d.ts +8 -0
- package/dist/session/WorkTypes.d.ts.map +1 -1
- package/dist/session/WorkspaceScope.d.ts +3 -0
- package/dist/session/WorkspaceScope.d.ts.map +1 -0
- package/dist/session/WorkspaceScope.js +19 -0
- package/dist/tools/SemanticToolRetrieval.d.ts +19 -0
- package/dist/tools/SemanticToolRetrieval.d.ts.map +1 -0
- package/dist/tools/SemanticToolRetrieval.js +52 -0
- package/dist/tools/ToolRetrieval.d.ts +7 -0
- package/dist/tools/ToolRetrieval.d.ts.map +1 -0
- package/dist/tools/ToolRetrieval.js +25 -0
- package/dist/tools/ToolTypes.d.ts +5 -0
- package/dist/tools/ToolTypes.d.ts.map +1 -1
- package/dist/tools/browser/BrowserSessionTool.d.ts +16 -0
- package/dist/tools/browser/BrowserSessionTool.d.ts.map +1 -0
- package/dist/tools/browser/BrowserSessionTool.js +326 -0
- package/dist/tools/browser/BrowserTool.d.ts +17 -0
- package/dist/tools/browser/BrowserTool.d.ts.map +1 -0
- package/dist/tools/browser/BrowserTool.js +291 -0
- package/dist/tools/browser/BrowserWorker.d.ts +2 -0
- package/dist/tools/browser/BrowserWorker.d.ts.map +1 -0
- package/dist/tools/browser/BrowserWorker.js +121 -0
- package/dist/tools/calculation/CalculatorTool.d.ts +5 -0
- package/dist/tools/calculation/CalculatorTool.d.ts.map +1 -0
- package/dist/tools/calculation/CalculatorTool.js +191 -0
- package/dist/tools/deterministic/DeterministicRuntime.d.ts +39 -0
- package/dist/tools/deterministic/DeterministicRuntime.d.ts.map +1 -0
- package/dist/tools/deterministic/DeterministicRuntime.js +98 -0
- package/dist/tools/deterministic/DeterministicTools.d.ts +8 -0
- package/dist/tools/deterministic/DeterministicTools.d.ts.map +1 -0
- package/dist/tools/deterministic/DeterministicTools.js +100 -0
- package/dist/tools/deterministic/node-worker.cjs +38 -0
- package/dist/tools/deterministic/python-worker.py +237 -0
- package/dist/tools/docdex/DocdexCatalogTools.d.ts +4 -0
- package/dist/tools/docdex/DocdexCatalogTools.d.ts.map +1 -0
- package/dist/tools/docdex/DocdexCatalogTools.js +59 -0
- package/dist/tools/docdex/DocdexTools.d.ts +2 -0
- package/dist/tools/docdex/DocdexTools.d.ts.map +1 -1
- package/dist/tools/docdex/DocdexTools.js +81 -106
- package/dist/tools/documents/DocumentRuntime.d.ts +12 -0
- package/dist/tools/documents/DocumentRuntime.d.ts.map +1 -0
- package/dist/tools/documents/DocumentRuntime.js +59 -0
- package/dist/tools/documents/DocumentTools.d.ts +19 -0
- package/dist/tools/documents/DocumentTools.d.ts.map +1 -0
- package/dist/tools/documents/DocumentTools.js +150 -0
- package/dist/tools/documents/worker.py +267 -0
- package/dist/tools/entities/AdesTool.d.ts +7 -0
- package/dist/tools/entities/AdesTool.d.ts.map +1 -0
- package/dist/tools/entities/AdesTool.js +59 -0
- package/dist/tools/filesystem/FileTools.d.ts.map +1 -1
- package/dist/tools/filesystem/FileTools.js +62 -11
- package/dist/tools/research/TnlTool.d.ts +22 -0
- package/dist/tools/research/TnlTool.d.ts.map +1 -0
- package/dist/tools/research/TnlTool.js +246 -0
- package/dist/tools/shell/AsyncProcess.d.ts +4 -0
- package/dist/tools/shell/AsyncProcess.d.ts.map +1 -1
- package/dist/tools/shell/AsyncProcess.js +9 -3
- package/dist/tools/shell/HostToolchain.d.ts +7 -0
- package/dist/tools/shell/HostToolchain.d.ts.map +1 -1
- package/dist/tools/shell/HostToolchain.js +65 -4
- package/dist/tools/shell/IsolatedExecutor.d.ts +5 -2
- package/dist/tools/shell/IsolatedExecutor.d.ts.map +1 -1
- package/dist/tools/shell/IsolatedExecutor.js +148 -29
- package/dist/tools/shell/ShellTool.d.ts +2 -0
- package/dist/tools/shell/ShellTool.d.ts.map +1 -1
- package/dist/tools/shell/ShellTool.js +19 -4
- package/dist/tools/system/CalendarTool.d.ts +15 -0
- package/dist/tools/system/CalendarTool.d.ts.map +1 -0
- package/dist/tools/system/CalendarTool.js +44 -0
- package/dist/tools/system/TextTool.d.ts +4 -0
- package/dist/tools/system/TextTool.d.ts.map +1 -0
- package/dist/tools/system/TextTool.js +39 -0
- package/dist/tools/system/TimeTool.d.ts +4 -0
- package/dist/tools/system/TimeTool.d.ts.map +1 -0
- package/dist/tools/system/TimeTool.js +22 -0
- package/dist/tools/verification/JavaScriptVerificationTool.d.ts +47 -0
- package/dist/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -0
- package/dist/tools/verification/JavaScriptVerificationTool.js +71 -0
- package/dist/tools/verification/JavaScriptVerificationWorker.d.ts +2 -0
- package/dist/tools/verification/JavaScriptVerificationWorker.d.ts.map +1 -0
- package/dist/tools/verification/JavaScriptVerificationWorker.js +91 -0
- package/dist/tools/verification/VitestTool.d.ts +6 -0
- package/dist/tools/verification/VitestTool.d.ts.map +1 -0
- package/dist/tools/verification/VitestTool.js +184 -0
- package/package.json +18 -5
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { promises as fs, constants } from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fork } from "node:child_process";
|
|
5
|
+
import { chromium } from "playwright-core";
|
|
6
|
+
import { ToolExecutionError } from "../ToolTypes.js";
|
|
7
|
+
export const browserUrl = (value) => {
|
|
8
|
+
let url;
|
|
9
|
+
try {
|
|
10
|
+
url = new URL(value);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
throw new ToolExecutionError("tool_invalid_args", "Provide a complete http or https URL");
|
|
14
|
+
}
|
|
15
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
|
|
16
|
+
throw new ToolExecutionError("tool_invalid_args", "Browser access accepts http/https URLs without embedded credentials");
|
|
17
|
+
}
|
|
18
|
+
return url.href;
|
|
19
|
+
};
|
|
20
|
+
export async function resolveBrowserBinary() {
|
|
21
|
+
const explicit = process.env.CODALI_BROWSER_PATH;
|
|
22
|
+
const candidates = explicit ? [explicit] : [
|
|
23
|
+
...[process.env.DOCDEX_WEB_BROWSER, process.env.CHROME_PATH].filter((value) => !!value),
|
|
24
|
+
...String(process.env.PATH ?? "").split(path.delimiter).filter(Boolean).flatMap(directory => ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome.exe"].map(name => path.join(directory, name))),
|
|
25
|
+
// Packaged browsers have OS sandbox profiles that cache downloads may lack.
|
|
26
|
+
chromium.executablePath(),
|
|
27
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
28
|
+
...[process.env.PROGRAMFILES, process.env["PROGRAMFILES(X86)"], process.env.LOCALAPPDATA].filter((value) => !!value)
|
|
29
|
+
.map(directory => path.join(directory, "Google", "Chrome", "Application", "chrome.exe")),
|
|
30
|
+
];
|
|
31
|
+
if (!explicit) {
|
|
32
|
+
for (const root of [path.join(os.homedir(), ".docdex"), path.join(os.homedir(), ".docdex", "state")]) {
|
|
33
|
+
try {
|
|
34
|
+
const value = JSON.parse(await fs.readFile(path.join(root, "bin", "chromium", "manifest.json"), "utf8"));
|
|
35
|
+
if (typeof value.path === "string")
|
|
36
|
+
candidates.push(value.path);
|
|
37
|
+
}
|
|
38
|
+
catch { /* Optional Docdex browser install. */ }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
for (const candidate of candidates) {
|
|
42
|
+
try {
|
|
43
|
+
if (!path.isAbsolute(candidate))
|
|
44
|
+
continue;
|
|
45
|
+
const real = await fs.realpath(candidate);
|
|
46
|
+
if (!(await fs.stat(real)).isFile())
|
|
47
|
+
continue;
|
|
48
|
+
await fs.access(real, process.platform === "win32" ? constants.F_OK : constants.X_OK);
|
|
49
|
+
return real;
|
|
50
|
+
}
|
|
51
|
+
catch { /* Try the next installed browser. */ }
|
|
52
|
+
}
|
|
53
|
+
throw new ToolExecutionError("tool_execution_failed", "Chrome/Chromium was not found. Install it or set CODALI_BROWSER_PATH to its absolute executable path.");
|
|
54
|
+
}
|
|
55
|
+
export function findSnapshotText(content, query, offset = 0) {
|
|
56
|
+
const text = content.toLowerCase(), needle = query.trim().toLowerCase();
|
|
57
|
+
if (!needle)
|
|
58
|
+
return;
|
|
59
|
+
const bodyStart = Math.max(offset, snapshotContentStart(content));
|
|
60
|
+
const bodyExact = text.indexOf(needle, bodyStart);
|
|
61
|
+
const exact = bodyExact >= 0 ? bodyExact : text.indexOf(needle, offset);
|
|
62
|
+
if (exact >= 0) {
|
|
63
|
+
// A documentation title often appears first in navigation. Prefer its
|
|
64
|
+
// actual heading/body occurrence; link-only searches still work.
|
|
65
|
+
let candidate = exact;
|
|
66
|
+
for (let inspected = 0; candidate >= 0 && inspected < 128; inspected++) {
|
|
67
|
+
const line = text.slice(text.lastIndexOf("\n", candidate) + 1, candidate);
|
|
68
|
+
if (!/^\s*-\s*(?:link\b|\/url:)/.test(line))
|
|
69
|
+
return { index: candidate, mode: "exact" };
|
|
70
|
+
candidate = text.indexOf(needle, candidate + Math.max(1, needle.length));
|
|
71
|
+
}
|
|
72
|
+
return { index: exact, mode: "exact" };
|
|
73
|
+
}
|
|
74
|
+
const terms = needle.split(/\s+/);
|
|
75
|
+
if (terms.length < 2 || terms.length > 20)
|
|
76
|
+
return;
|
|
77
|
+
// Bounded literal scanning handles accessibility line breaks and intervening
|
|
78
|
+
// words without regex backtracking or pretending the phrase was quoted.
|
|
79
|
+
for (let start = text.indexOf(terms[0], bodyStart); start >= 0; start = text.indexOf(terms[0], start + 1)) {
|
|
80
|
+
let end = start + terms[0].length;
|
|
81
|
+
const found = terms.slice(1).every(term => {
|
|
82
|
+
const next = text.indexOf(term, end);
|
|
83
|
+
if (next < 0 || next - start > 240)
|
|
84
|
+
return false;
|
|
85
|
+
end = next + term.length;
|
|
86
|
+
return true;
|
|
87
|
+
});
|
|
88
|
+
if (found)
|
|
89
|
+
return { index: start, mode: "ordered_terms" };
|
|
90
|
+
}
|
|
91
|
+
// Models also issue unordered keyword queries. Retrieve a bounded candidate
|
|
92
|
+
// passage without representing lexical overlap as support for the claim.
|
|
93
|
+
const stop = new Set(["the", "and", "for", "with", "that", "this", "from", "are", "was", "were", "does", "not", "can", "must", "should", "have", "has"]);
|
|
94
|
+
const keywords = [...new Set(needle.match(/[\p{L}\p{N}_]{3,}/gu) ?? [])].filter(term => !stop.has(term)).slice(0, 20);
|
|
95
|
+
if (keywords.length < 2)
|
|
96
|
+
return;
|
|
97
|
+
let best;
|
|
98
|
+
for (let start = bodyStart; start < Math.min(text.length, 1000000); start += 600) {
|
|
99
|
+
const window = text.slice(start, start + 1200), words = new Set(window.match(/[\p{L}\p{N}_]{3,}/gu) ?? []);
|
|
100
|
+
const matched = keywords.filter(term => words.has(term));
|
|
101
|
+
if (matched.length < Math.max(2, Math.ceil(keywords.length / 2)))
|
|
102
|
+
continue;
|
|
103
|
+
const score = matched.length + matched.length / Math.max(1, words.size);
|
|
104
|
+
if (!best || score > best.score)
|
|
105
|
+
best = { index: start, matchedTerms: matched, score };
|
|
106
|
+
}
|
|
107
|
+
if (best)
|
|
108
|
+
return { index: best.index, mode: "ranked_terms", matchedTerms: best.matchedTerms };
|
|
109
|
+
}
|
|
110
|
+
export function snapshotSectionContext(content, offset) {
|
|
111
|
+
const prefix = content.slice(0, offset), end = prefix.lastIndexOf("\n");
|
|
112
|
+
const stack = [];
|
|
113
|
+
for (const match of prefix.slice(0, Math.max(0, end)).matchAll(/^\s*- heading (.+?)(?: \[level=(\d+)\])?:?$/gm)) {
|
|
114
|
+
const level = Number(match[2] ?? 1);
|
|
115
|
+
let title = match[1];
|
|
116
|
+
try {
|
|
117
|
+
title = JSON.parse(title);
|
|
118
|
+
}
|
|
119
|
+
catch { /* Unquoted accessibility label. */ }
|
|
120
|
+
while (stack.length && stack.at(-1).level >= level)
|
|
121
|
+
stack.pop();
|
|
122
|
+
stack.push({ level, title: String(title).slice(0, 160) });
|
|
123
|
+
}
|
|
124
|
+
return stack.slice(-4).map(value => value.title);
|
|
125
|
+
}
|
|
126
|
+
/** A starting-position hint only: retain the full snapshot for offset reads. */
|
|
127
|
+
export function snapshotContentStart(content) {
|
|
128
|
+
const heading = /^\s*- heading .+? \[level=[12]\]:?$/m.exec(content.slice(0, 20000));
|
|
129
|
+
if (heading)
|
|
130
|
+
return heading.index;
|
|
131
|
+
// Plain-text specifications commonly indent their contents list but start
|
|
132
|
+
// actual numbered sections at column zero. Keep navigation as a fallback.
|
|
133
|
+
if (/table of contents/i.test(content.slice(0, 20000))) {
|
|
134
|
+
const body = /^\d+(?:\.\d+)*\.\s+\S[^\n]*$/m.exec(content);
|
|
135
|
+
if (body)
|
|
136
|
+
return body.index;
|
|
137
|
+
}
|
|
138
|
+
return 0;
|
|
139
|
+
}
|
|
140
|
+
const MAX_SNAPSHOTS = 48;
|
|
141
|
+
const MAX_SNAPSHOT_CHARS = 24000000;
|
|
142
|
+
const SNAPSHOT_REUSE_MS = 30 * 60000;
|
|
143
|
+
const isErrorSnapshot = (value) => value.httpStatus === null || value.httpStatus >= 400 || !value.content.trim();
|
|
144
|
+
/** Short-lived, unauthenticated browser navigation; the model never supplies JS. */
|
|
145
|
+
export function createBrowserTools(options = {}) {
|
|
146
|
+
let snapshot;
|
|
147
|
+
const snapshots = new Map();
|
|
148
|
+
// Requested URL and scope to snapshot id. Long research reopened the same
|
|
149
|
+
// page dozens of times, spending a browser launch on evidence already held.
|
|
150
|
+
const captured = new Map();
|
|
151
|
+
let snapshotCount = 0;
|
|
152
|
+
const store = (value, key) => {
|
|
153
|
+
snapshots.set(value.id, value);
|
|
154
|
+
captured.set(key, value.id);
|
|
155
|
+
let chars = [...snapshots.values()].reduce((sum, item) => sum + item.content.length, 0);
|
|
156
|
+
for (const [id, item] of snapshots) {
|
|
157
|
+
if (snapshots.size <= MAX_SNAPSHOTS && chars <= MAX_SNAPSHOT_CHARS)
|
|
158
|
+
break;
|
|
159
|
+
snapshots.delete(id);
|
|
160
|
+
chars -= item.content.length;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
const page = (offset = 0, maxChars = 2400, extra = {}) => {
|
|
164
|
+
if (!snapshot)
|
|
165
|
+
throw new ToolExecutionError("tool_invalid_args", "Open a page before reading its snapshot");
|
|
166
|
+
const start = Math.min(snapshot.content.length, offset);
|
|
167
|
+
let end = Math.min(snapshot.content.length, start + Math.min(maxChars, 2400));
|
|
168
|
+
const result = { snapshotId: snapshot.id, url: snapshot.url.slice(0, 1000), title: snapshot.title.slice(0, 200), capturedAt: snapshot.capturedAt,
|
|
169
|
+
httpStatus: snapshot.httpStatus, contentType: snapshot.contentType,
|
|
170
|
+
evidenceStatus: snapshot.httpStatus === null ? "unknown_http_status" : snapshot.httpStatus >= 400 ? "http_error" : !snapshot.content.trim() ? "empty" : "retrieved",
|
|
171
|
+
evidenceNotice: "Retrieval is not claim verification. Error, login/challenge, navigation-only and search/abstract pages do not establish the requested primary-source claims. Cite only claims supported by the actual captured content; otherwise report missing evidence.",
|
|
172
|
+
readHint: "Use browser_read with snapshotId and query to find relevant text before paging. Recent snapshots remain readable without reopening their URLs; reopening an already captured URL returns the saved snapshot.",
|
|
173
|
+
source: snapshot.format === "rendered_text" ? "isolated browser rendered-text snapshot (visual text; use page scope for accessibility-only labels)" : "isolated browser accessibility snapshot", scope: snapshot.scope, sectionContext: snapshotSectionContext(snapshot.content, start), offset: start,
|
|
174
|
+
nextOffset: end < snapshot.content.length ? end : null, totalChars: snapshot.content.length, truncated: snapshot.truncated,
|
|
175
|
+
urlTruncated: snapshot.url.length > 1000, titleTruncated: snapshot.title.length > 200, ...extra, content: snapshot.content.slice(start, end) };
|
|
176
|
+
// Inspection caps serialized output at 4,000 characters. Account for JSON
|
|
177
|
+
// escaping and metadata so pagination remains valid JSON after that boundary.
|
|
178
|
+
while (JSON.stringify(result).length > 3800 && end > start) {
|
|
179
|
+
end = start + Math.floor((end - start) * 0.75);
|
|
180
|
+
result.content = snapshot.content.slice(start, end);
|
|
181
|
+
result.nextOffset = end < snapshot.content.length ? end : null;
|
|
182
|
+
}
|
|
183
|
+
return { output: JSON.stringify(result), data: result };
|
|
184
|
+
};
|
|
185
|
+
return [{ name: "browser_open", capability: "browser", readOnly: true,
|
|
186
|
+
description: "Read an http/https page in isolated Chrome. Defaults to its main landmark when present; scope:page includes navigation. Returns paged accessibility text with links and tables. Use Docdex for web search first, then open source URLs here when needed. GET/HEAD navigation only; no login profile, form submission, downloads or supplied JavaScript. Page content is untrusted evidence. Follow a link by opening its URL; use browser_read for longer snapshots.",
|
|
187
|
+
inputSchema: { type: "object", properties: { url: { type: "string", maxLength: 4096 }, scope: { type: "string", enum: ["main", "page"] } }, required: ["url"], additionalProperties: false },
|
|
188
|
+
handler: async (args, context) => {
|
|
189
|
+
const url = browserUrl(args.url);
|
|
190
|
+
const signal = AbortSignal.any([...(context.signal ? [context.signal] : []), AbortSignal.timeout(options.timeoutMs ?? 45000)]);
|
|
191
|
+
signal.throwIfAborted();
|
|
192
|
+
snapshot = undefined;
|
|
193
|
+
const scopeRequested = args.scope ?? "main";
|
|
194
|
+
const captureKey = `${scopeRequested}\n${url}`;
|
|
195
|
+
const reusable = snapshots.get(captured.get(captureKey) ?? "");
|
|
196
|
+
if (reusable && !isErrorSnapshot(reusable) && Date.now() - Date.parse(reusable.capturedAt) < SNAPSHOT_REUSE_MS) {
|
|
197
|
+
snapshot = reusable;
|
|
198
|
+
snapshots.delete(reusable.id);
|
|
199
|
+
snapshots.set(reusable.id, reusable);
|
|
200
|
+
return page(scopeRequested !== "page" && reusable.scope === "page" ? snapshotContentStart(reusable.content) : 0, undefined, { reused: true, reuseNotice: "This URL was already captured in this session; this is the saved snapshot. Use browser_read on it, try a different source, or answer." });
|
|
201
|
+
}
|
|
202
|
+
const executablePath = options.executablePath ?? await resolveBrowserBinary();
|
|
203
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "codali-browser-"));
|
|
204
|
+
await fs.chmod(directory, 0o700);
|
|
205
|
+
let browser;
|
|
206
|
+
let worker;
|
|
207
|
+
let rejectAbort = () => undefined;
|
|
208
|
+
const aborted = new Promise((_, reject) => { rejectAbort = reject; });
|
|
209
|
+
const abort = () => { rejectAbort(signal.reason); worker?.kill("SIGKILL"); void browser?.close().catch(() => undefined); };
|
|
210
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
211
|
+
if (signal.aborted)
|
|
212
|
+
abort();
|
|
213
|
+
const work = (async () => {
|
|
214
|
+
browser = await chromium.launchServer({ executablePath, headless: true, chromiumSandbox: true, timeout: 10000 });
|
|
215
|
+
if (signal.aborted) {
|
|
216
|
+
await browser.close();
|
|
217
|
+
signal.throwIfAborted();
|
|
218
|
+
}
|
|
219
|
+
// The CLI owns Chrome; cancellation closes it even if the worker dies.
|
|
220
|
+
// Do not let browser-use import a workspace .env or inherit API keys.
|
|
221
|
+
worker = fork(new URL("./BrowserWorker.js", import.meta.url), [], { cwd: directory, execArgv: [],
|
|
222
|
+
env: { PATH: process.env.PATH, SYSTEMROOT: process.env.SYSTEMROOT, WINDIR: process.env.WINDIR,
|
|
223
|
+
HOME: directory, USERPROFILE: directory, TMPDIR: directory, TMP: directory, TEMP: directory,
|
|
224
|
+
XDG_CONFIG_HOME: directory, XDG_CACHE_HOME: directory, XDG_DATA_HOME: directory,
|
|
225
|
+
LANG: "C.UTF-8", ANONYMIZED_TELEMETRY: "false" },
|
|
226
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"] });
|
|
227
|
+
const result = await new Promise((resolve, reject) => {
|
|
228
|
+
worker.once("error", reject);
|
|
229
|
+
worker.once("exit", code => reject(new Error(`Browser worker exited before returning evidence (${code})`)));
|
|
230
|
+
worker.once("message", (message) => {
|
|
231
|
+
const reply = message;
|
|
232
|
+
const value = reply?.value;
|
|
233
|
+
if (!reply?.ok)
|
|
234
|
+
return reject(new Error(typeof reply?.message === "string" ? reply.message.slice(0, 2000) : "Browser navigation failed"));
|
|
235
|
+
if (!value || typeof value.url !== "string" || typeof value.title !== "string" || typeof value.content !== "string" || value.content.length > 1000000 || !["main", "page"].includes(value.scope) || typeof value.truncated !== "boolean")
|
|
236
|
+
return reject(new Error("Browser worker returned invalid evidence"));
|
|
237
|
+
if (!(value.httpStatus === null || Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599) || !(value.contentType === null || typeof value.contentType === "string"))
|
|
238
|
+
return reject(new Error("Browser worker returned invalid HTTP evidence"));
|
|
239
|
+
resolve(value);
|
|
240
|
+
});
|
|
241
|
+
worker.send({ endpoint: browser.wsEndpoint(), url, scope: args.scope ?? "main" }, error => { if (error)
|
|
242
|
+
reject(error); });
|
|
243
|
+
});
|
|
244
|
+
signal.throwIfAborted();
|
|
245
|
+
snapshot = { ...result, id: `snap-${++snapshotCount}`, url: browserUrl(result.url), capturedAt: new Date().toISOString() };
|
|
246
|
+
store(snapshot, captureKey);
|
|
247
|
+
const start = args.scope !== "page" && snapshot.scope === "page" ? snapshotContentStart(snapshot.content) : 0;
|
|
248
|
+
return page(start);
|
|
249
|
+
})().finally(async () => {
|
|
250
|
+
worker?.kill("SIGKILL");
|
|
251
|
+
await browser?.close().catch(() => undefined);
|
|
252
|
+
await fs.rm(directory, { recursive: true, force: true });
|
|
253
|
+
});
|
|
254
|
+
try {
|
|
255
|
+
return await Promise.race([work, aborted]);
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
signal.removeEventListener("abort", abort);
|
|
259
|
+
if (signal.aborted) {
|
|
260
|
+
snapshot = undefined;
|
|
261
|
+
snapshots.clear();
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
}, { name: "browser_read", capability: "browser_snapshot", readOnly: true,
|
|
266
|
+
description: "Find a short phrase/heading in a saved snapshot; keyword queries fall back to explicitly labeled approximate passage matches. Or page using offset/nextOffset. Recent snapshots stay readable. No network or script execution.",
|
|
267
|
+
inputSchema: { type: "object", properties: { snapshotId: { type: "string" }, query: { type: "string", minLength: 1, maxLength: 200 }, offset: { type: "integer", minimum: 0, maximum: 1000000 }, maxChars: { type: "integer", minimum: 100, maximum: 8000 } }, required: ["snapshotId"], additionalProperties: false },
|
|
268
|
+
handler: async (args, context) => {
|
|
269
|
+
context.signal?.throwIfAborted();
|
|
270
|
+
const input = args;
|
|
271
|
+
snapshot = snapshots.get(input.snapshotId);
|
|
272
|
+
if (!snapshot)
|
|
273
|
+
throw new ToolExecutionError("tool_invalid_args", `This browser snapshot is unavailable; open its URL again. Readable snapshots: ${JSON.stringify([...snapshots.values()].slice(-12).map(item => ({ snapshotId: item.id, url: item.url.slice(0, 160) })))}`);
|
|
274
|
+
snapshots.delete(snapshot.id);
|
|
275
|
+
snapshots.set(snapshot.id, snapshot);
|
|
276
|
+
if (input.query !== undefined) {
|
|
277
|
+
if (!input.query.trim() || input.query.length > 200)
|
|
278
|
+
throw new ToolExecutionError("tool_invalid_args", "Supply a nonempty literal search query of up to200 characters");
|
|
279
|
+
const found = findSnapshotText(snapshot.content, input.query, input.offset ?? 0);
|
|
280
|
+
if (!found)
|
|
281
|
+
return { output: JSON.stringify({ snapshotId: snapshot.id, url: snapshot.url, query: input.query, matchFound: false,
|
|
282
|
+
notice: "No matching passage in this captured snapshot; this does not prove the fact is absent from the underlying source. Try fewer distinctive words or another source page." }) };
|
|
283
|
+
return page(Math.max(0, found.index - (found.mode === "ranked_terms" ? 0 : 200)), input.maxChars, {
|
|
284
|
+
matchFound: true, matchMode: found.mode,
|
|
285
|
+
...(found.mode === "ranked_terms" ? { matchedTerms: found.matchedTerms, matchNotice: "Approximate keyword overlap, not a literal quotation or verification of the query's claim." } : {}),
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
return page(input.offset, input.maxChars);
|
|
289
|
+
},
|
|
290
|
+
}];
|
|
291
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BrowserWorker.d.ts","sourceRoot":"","sources":["../../../src/tools/browser/BrowserWorker.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { chromium } from "playwright-core";
|
|
2
|
+
// This process runs in a private empty directory with an explicit environment.
|
|
3
|
+
// browser-use reads .env at import time, so never import it in the CLI process.
|
|
4
|
+
process.once("message", async (input) => {
|
|
5
|
+
let browser;
|
|
6
|
+
let session;
|
|
7
|
+
let reply;
|
|
8
|
+
try {
|
|
9
|
+
browser = await chromium.connect(input.endpoint, { timeout: 10000 });
|
|
10
|
+
const context = await browser.newContext({ acceptDownloads: false, serviceWorkers: "block", permissions: [] });
|
|
11
|
+
context.setDefaultTimeout(5000);
|
|
12
|
+
await context.route("**/*", route => {
|
|
13
|
+
const request = route.request();
|
|
14
|
+
let url;
|
|
15
|
+
try {
|
|
16
|
+
url = new URL(request.url());
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return route.abort("blockedbyclient");
|
|
20
|
+
}
|
|
21
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || !["GET", "HEAD"].includes(request.method()))
|
|
22
|
+
return route.abort("blockedbyclient");
|
|
23
|
+
return route.continue();
|
|
24
|
+
});
|
|
25
|
+
await context.routeWebSocket("**/*", socket => socket.close());
|
|
26
|
+
const tab = await context.newPage();
|
|
27
|
+
let httpStatus = null;
|
|
28
|
+
let contentType = null;
|
|
29
|
+
tab.on("response", response => {
|
|
30
|
+
if (response.request().isNavigationRequest() && response.frame() === tab.mainFrame()) {
|
|
31
|
+
httpStatus = response.status();
|
|
32
|
+
contentType = response.headers()["content-type"] ?? null;
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
context.on("page", popup => { if (popup !== tab)
|
|
36
|
+
void popup.close().catch(() => undefined); });
|
|
37
|
+
tab.on("dialog", dialog => { void dialog.dismiss().catch(() => undefined); });
|
|
38
|
+
const { BrowserSession } = await import("browser-use/dist/browser/session.js");
|
|
39
|
+
session = new BrowserSession({ browser, browser_context: context, page: tab,
|
|
40
|
+
profile: { accept_downloads: false, enable_default_extensions: false, captcha_solver: false,
|
|
41
|
+
keep_alive: false, permissions: [], minimum_wait_page_load_time: 0,
|
|
42
|
+
wait_for_network_idle_page_load_time: 0.1, maximum_wait_page_load_time: 1 } });
|
|
43
|
+
// A network-interface change aborts navigation immediately and says nothing
|
|
44
|
+
// about the page itself, so a single retry is cheap and cannot mask a 404.
|
|
45
|
+
for (let attempt = 0;; attempt++) {
|
|
46
|
+
try {
|
|
47
|
+
await session.navigate_to(input.url, { wait_until: "domcontentloaded", timeout_ms: 25000 });
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (attempt >= 1 || !String(error).includes("ERR_NETWORK_CHANGED"))
|
|
52
|
+
throw error;
|
|
53
|
+
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
// Accessibility snapshots otherwise flatten deleted/struck-through text
|
|
57
|
+
// into apparently current prose. Mark revisions in this disposable DOM;
|
|
58
|
+
// no page action, form submission or remote mutation is performed.
|
|
59
|
+
await tab.locator('del, s, strike, [style*="line-through"]').evaluateAll(elements => {
|
|
60
|
+
for (const element of elements.slice(0, 100)) {
|
|
61
|
+
if (element.parentElement?.closest('del, s, strike, [style*="line-through"]'))
|
|
62
|
+
continue;
|
|
63
|
+
element.prepend(document.createTextNode("[DELETED/STRUCK-THROUGH TEXT — not current guidance: "));
|
|
64
|
+
element.append(document.createTextNode("]"));
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
const main = tab.getByRole("main");
|
|
68
|
+
const useMain = input.scope !== "page" && await main.count() > 0;
|
|
69
|
+
const root = useMain ? main.first() : tab.locator("body");
|
|
70
|
+
let content;
|
|
71
|
+
let format = "accessibility";
|
|
72
|
+
if (input.scope !== "page") {
|
|
73
|
+
// Inline links/emphasis split ordinary prose into many ARIA records. Read
|
|
74
|
+
// rendered text for research, retaining heading scopes and revision marks.
|
|
75
|
+
// The disposable page is never submitted or persisted remotely.
|
|
76
|
+
const links = await root.locator("a[href]").evaluateAll(elements => elements.slice(0, 128).flatMap(element => {
|
|
77
|
+
const link = element;
|
|
78
|
+
if (link.closest('nav,[role="navigation"]') || !link.getClientRects().length)
|
|
79
|
+
return [];
|
|
80
|
+
try {
|
|
81
|
+
const url = new URL(link.href);
|
|
82
|
+
return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password
|
|
83
|
+
? [`- link ${JSON.stringify((link.innerText || link.textContent || "").trim().slice(0, 160))}\n - /url: ${url.href.slice(0, 1000)}`] : [];
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return [];
|
|
87
|
+
}
|
|
88
|
+
}));
|
|
89
|
+
await root.locator('h1,h2,h3,h4,h5,h6,[role="heading"]').evaluateAll(elements => {
|
|
90
|
+
for (const element of elements) {
|
|
91
|
+
const heading = element;
|
|
92
|
+
const level = Number(heading.getAttribute("aria-level") || heading.tagName.slice(1)) || 2;
|
|
93
|
+
const label = heading.innerText?.trim();
|
|
94
|
+
if (label)
|
|
95
|
+
heading.textContent = `- heading ${JSON.stringify(label)} [level=${Math.min(6, Math.max(1, level))}]`;
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
content = await root.innerText({ timeout: 5000 });
|
|
99
|
+
if (content.trim()) {
|
|
100
|
+
format = "rendered_text";
|
|
101
|
+
if (links.length)
|
|
102
|
+
content += `\n\nSource links (first 128, bounded; not additional retrieved evidence):\n${links.join("\n").slice(0, 16000)}`;
|
|
103
|
+
}
|
|
104
|
+
else
|
|
105
|
+
content = await root.ariaSnapshot({ timeout: 5000 });
|
|
106
|
+
}
|
|
107
|
+
else
|
|
108
|
+
content = await tab.ariaSnapshot({ mode: "default", depth: 20, timeout: 5000 });
|
|
109
|
+
reply = { ok: true, value: { url: tab.url(), httpStatus, contentType, title: (await tab.title()).slice(0, 1000), scope: useMain ? "main" : "page",
|
|
110
|
+
format, content: content.slice(0, 1000000), truncated: content.length > 1000000 } };
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
reply = { ok: false, message: error instanceof Error ? error.message : String(error) };
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
await session?.stop().catch(() => undefined);
|
|
117
|
+
await browser?.close().catch(() => undefined);
|
|
118
|
+
}
|
|
119
|
+
if (process.connected)
|
|
120
|
+
process.send?.(reply, () => process.disconnect());
|
|
121
|
+
});
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type ToolDefinition } from "../ToolTypes.js";
|
|
2
|
+
/** Bounded Pratt parser; exponentiation is right associative and binds more tightly than unary minus. */
|
|
3
|
+
export declare const evaluateCalculation: (expression: string) => number;
|
|
4
|
+
export declare const createCalculatorTool: () => ToolDefinition;
|
|
5
|
+
//# sourceMappingURL=CalculatorTool.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CalculatorTool.d.ts","sourceRoot":"","sources":["../../../src/tools/calculation/CalculatorTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAsE1E,yGAAyG;AACzG,eAAO,MAAM,mBAAmB,GAAI,YAAY,MAAM,KAAG,MA0DxD,CAAC;AAEF,eAAO,MAAM,oBAAoB,QAAO,cA0BtC,CAAC"}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { ToolExecutionError } from "../ToolTypes.js";
|
|
2
|
+
const finite = (value) => {
|
|
3
|
+
if (!Number.isFinite(value))
|
|
4
|
+
throw new Error("Calculation is undefined or exceeds finite numeric range");
|
|
5
|
+
if (Number.isInteger(value) && !Number.isSafeInteger(value))
|
|
6
|
+
throw new Error("Integer exceeds exact supported range");
|
|
7
|
+
return value;
|
|
8
|
+
};
|
|
9
|
+
/** A numeric grammar, not JavaScript: every character is consumed, and nothing is evaluated as code. */
|
|
10
|
+
const tokenize = (expression) => {
|
|
11
|
+
if (typeof expression !== "string" || !expression.trim() || expression.length > 4096)
|
|
12
|
+
throw new Error("Expected an expression of 1 to 4096 characters");
|
|
13
|
+
const pattern = /\s+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|Math\.[A-Za-z_][A-Za-z_0-9]*|[A-Za-z_][A-Za-z_0-9]*|\*\*|[+*/%^(),-]/y;
|
|
14
|
+
const tokens = [];
|
|
15
|
+
let offset = 0;
|
|
16
|
+
while (offset < expression.length) {
|
|
17
|
+
pattern.lastIndex = offset;
|
|
18
|
+
const match = pattern.exec(expression);
|
|
19
|
+
if (!match)
|
|
20
|
+
throw new Error(`Unsupported character at position ${offset + 1}`);
|
|
21
|
+
offset = pattern.lastIndex;
|
|
22
|
+
// Literal aliases enter the same bounded grammar; no object lookup or code execution.
|
|
23
|
+
const token = match[0].startsWith("Math.") ? match[0].slice(5) : match[0];
|
|
24
|
+
if (token.trim())
|
|
25
|
+
tokens.push(token === "PI" ? "pi" : token === "E" ? "e" : token);
|
|
26
|
+
if (tokens.length > 1024)
|
|
27
|
+
throw new Error("Expression exceeds 1024 tokens");
|
|
28
|
+
}
|
|
29
|
+
return tokens;
|
|
30
|
+
};
|
|
31
|
+
const countArgs = (n, k) => {
|
|
32
|
+
if (!Number.isInteger(n) || !Number.isInteger(k) || n < 0 || k < 0)
|
|
33
|
+
throw new Error("Counting functions take non-negative integers");
|
|
34
|
+
};
|
|
35
|
+
/** n choose k, exact while the result is a safe integer (each partial product is). */
|
|
36
|
+
const combinations = (n, k) => {
|
|
37
|
+
countArgs(n, k);
|
|
38
|
+
if (k > n)
|
|
39
|
+
return 0;
|
|
40
|
+
let result = 1;
|
|
41
|
+
for (let i = 1; i <= Math.min(k, n - k); i++)
|
|
42
|
+
result = finite(result * (n - Math.min(k, n - k) + i) / i);
|
|
43
|
+
return Math.round(result);
|
|
44
|
+
};
|
|
45
|
+
const permutations = (n, k) => {
|
|
46
|
+
countArgs(n, k);
|
|
47
|
+
if (k > n)
|
|
48
|
+
return 0;
|
|
49
|
+
let result = 1;
|
|
50
|
+
for (let i = 0; i < k; i++)
|
|
51
|
+
result = finite(result * (n - i));
|
|
52
|
+
return result;
|
|
53
|
+
};
|
|
54
|
+
const functions = new Map([
|
|
55
|
+
["abs", { min: 1, max: 1, run: Math.abs }],
|
|
56
|
+
["sqrt", { min: 1, max: 1, run: Math.sqrt }],
|
|
57
|
+
["exp", { min: 1, max: 1, run: Math.exp }],
|
|
58
|
+
["ln", { min: 1, max: 1, run: Math.log }],
|
|
59
|
+
["log", { min: 1, max: 1, run: Math.log }],
|
|
60
|
+
["log10", { min: 1, max: 1, run: Math.log10 }],
|
|
61
|
+
["sin", { min: 1, max: 1, run: Math.sin }],
|
|
62
|
+
["cos", { min: 1, max: 1, run: Math.cos }],
|
|
63
|
+
["tan", { min: 1, max: 1, run: Math.tan }],
|
|
64
|
+
["pow", { min: 2, max: 2, run: Math.pow }],
|
|
65
|
+
["floor", { min: 1, max: 1, run: Math.floor }],
|
|
66
|
+
["ceil", { min: 1, max: 1, run: Math.ceil }],
|
|
67
|
+
["round", { min: 1, max: 1, run: Math.round }],
|
|
68
|
+
["min", { min: 1, max: 128, run: Math.min }],
|
|
69
|
+
["max", { min: 1, max: 128, run: Math.max }],
|
|
70
|
+
["sum", { min: 1, max: 128, run: (...args) => args.reduce((total, value) => finite(total + value), 0) }],
|
|
71
|
+
// Counting functions: hypergeometric and sampling questions need them, and a
|
|
72
|
+
// rejected C(40,8) made the model type binomial coefficients from memory.
|
|
73
|
+
...["comb", "choose", "nCr", "C"].map(name => [name, { min: 2, max: 2, run: combinations }]),
|
|
74
|
+
...["perm", "nPr", "P"].map(name => [name, { min: 2, max: 2, run: permutations }]),
|
|
75
|
+
["factorial", { min: 1, max: 1, run: (n) => permutations(n, n) }],
|
|
76
|
+
]);
|
|
77
|
+
/** Bounded Pratt parser; exponentiation is right associative and binds more tightly than unary minus. */
|
|
78
|
+
export const evaluateCalculation = (expression) => {
|
|
79
|
+
const tokens = tokenize(expression);
|
|
80
|
+
let position = 0;
|
|
81
|
+
const expect = (token) => {
|
|
82
|
+
if (tokens[position++] !== token)
|
|
83
|
+
throw new Error(`Expected ${token}`);
|
|
84
|
+
};
|
|
85
|
+
const parse = (precedence = 0, depth = 0) => {
|
|
86
|
+
if (depth > 32)
|
|
87
|
+
throw new Error("Expression nesting exceeds 32 levels");
|
|
88
|
+
const token = tokens[position++];
|
|
89
|
+
let value;
|
|
90
|
+
if (token === "+" || token === "-") {
|
|
91
|
+
const operand = parse(25, depth + 1);
|
|
92
|
+
value = token === "-" ? -operand : operand;
|
|
93
|
+
}
|
|
94
|
+
else if (token === "(") {
|
|
95
|
+
value = parse(0, depth + 1);
|
|
96
|
+
expect(")");
|
|
97
|
+
}
|
|
98
|
+
else if (token && /^(?:\d|\.)/.test(token))
|
|
99
|
+
value = finite(Number(token));
|
|
100
|
+
else if (token === "pi")
|
|
101
|
+
value = Math.PI;
|
|
102
|
+
else if (token === "e")
|
|
103
|
+
value = Math.E;
|
|
104
|
+
else {
|
|
105
|
+
const fn = functions.get(token);
|
|
106
|
+
if (!fn)
|
|
107
|
+
throw new Error(`Expected a number or supported function, received ${token ?? "end of expression"}`);
|
|
108
|
+
expect("(");
|
|
109
|
+
const args = [];
|
|
110
|
+
if (tokens[position] !== ")") {
|
|
111
|
+
do {
|
|
112
|
+
if (args.length >= fn.max)
|
|
113
|
+
throw new Error(`${token} accepts at most ${fn.max} arguments`);
|
|
114
|
+
args.push(parse(0, depth + 1));
|
|
115
|
+
if (tokens[position] !== ",")
|
|
116
|
+
break;
|
|
117
|
+
position++;
|
|
118
|
+
} while (true);
|
|
119
|
+
}
|
|
120
|
+
expect(")");
|
|
121
|
+
if (args.length < fn.min)
|
|
122
|
+
throw new Error(`${token} requires at least ${fn.min} argument`);
|
|
123
|
+
value = finite(fn.run(...args));
|
|
124
|
+
}
|
|
125
|
+
while (position < tokens.length) {
|
|
126
|
+
const operator = tokens[position];
|
|
127
|
+
const power = operator === "^" || operator === "**";
|
|
128
|
+
const binding = power ? 30 : ["*", "/", "%"].includes(operator) ? 20 : ["+", "-"].includes(operator) ? 10 : 0;
|
|
129
|
+
if (binding === 0 || binding <= precedence)
|
|
130
|
+
break;
|
|
131
|
+
position++;
|
|
132
|
+
const right = parse(power ? binding - 1 : binding, depth + 1);
|
|
133
|
+
switch (operator) {
|
|
134
|
+
case "+":
|
|
135
|
+
value += right;
|
|
136
|
+
break;
|
|
137
|
+
case "-":
|
|
138
|
+
value -= right;
|
|
139
|
+
break;
|
|
140
|
+
case "*":
|
|
141
|
+
value *= right;
|
|
142
|
+
break;
|
|
143
|
+
case "/":
|
|
144
|
+
value /= right;
|
|
145
|
+
break;
|
|
146
|
+
case "%":
|
|
147
|
+
value %= right;
|
|
148
|
+
break;
|
|
149
|
+
default: value **= right;
|
|
150
|
+
}
|
|
151
|
+
value = finite(value);
|
|
152
|
+
}
|
|
153
|
+
return finite(value);
|
|
154
|
+
};
|
|
155
|
+
const result = parse();
|
|
156
|
+
if (position !== tokens.length)
|
|
157
|
+
throw new Error(`Unexpected token ${tokens[position]}`);
|
|
158
|
+
// JSON has a single zero representation; keep the exported numeric API consistent.
|
|
159
|
+
return result === 0 ? 0 : result;
|
|
160
|
+
};
|
|
161
|
+
export const createCalculatorTool = () => ({
|
|
162
|
+
name: "calculate", capability: "calculation", readOnly: true,
|
|
163
|
+
description: "Calculate {expression:'formula'} OR {expressions:{label:'formula'}} (up to16). Supports exp,ln/log(natural),log10,pow,sin/cos/tan(radians),abs,sqrt,floor,ceil,round,min,max,sum,comb/C(n,k),perm/P(n,k),factorial; + - * / %, ^ **, pi,e. Math.function aliases accepted only for this allowlist. No variables, assignments or code. IEEE-754 approximate; exact decimals use decimal_calculate. Tool success checks arithmetic, not whether your formula models the request.",
|
|
164
|
+
inputSchema: { type: "object", properties: { expression: { type: "string", description: "One numeric formula, e.g. exp(-2)*3. Supply this OR expressions.", minLength: 1, maxLength: 4096 },
|
|
165
|
+
expressions: { type: "object", description: "Map labels to complete formula STRINGS, e.g. {total:'2*3+4',check:'10'}. Each formula is independent; labels are not variables. Supply this OR expression.", minProperties: 1, maxProperties: 16, propertyNames: { pattern: "^[A-Za-z][A-Za-z0-9_]{0,63}$" }, additionalProperties: true },
|
|
166
|
+
}, oneOf: [{ required: ["expression"] }, { required: ["expressions"] }], additionalProperties: false },
|
|
167
|
+
handler: async (args, context) => {
|
|
168
|
+
context.signal?.throwIfAborted();
|
|
169
|
+
try {
|
|
170
|
+
const input = args;
|
|
171
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || input.expression === undefined && input.expressions === undefined)
|
|
172
|
+
throw new Error('Use {"expression":"2+3"} or {"expressions":{"total":"2+3"}}; formulas must be strings');
|
|
173
|
+
if (input.expressions !== undefined) {
|
|
174
|
+
if (input.expression !== undefined || !input.expressions || Array.isArray(input.expressions) || Object.keys(input.expressions).length < 1 || Object.keys(input.expressions).length > 16)
|
|
175
|
+
throw new Error("Supply expression or up to16 named expressions, not both");
|
|
176
|
+
const results = Object.fromEntries(Object.entries(input.expressions).map(([label, expression]) => {
|
|
177
|
+
if (!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(label))
|
|
178
|
+
throw new Error("Invalid calculation label");
|
|
179
|
+
return [label, evaluateCalculation(expression)];
|
|
180
|
+
}));
|
|
181
|
+
return { output: JSON.stringify({ results, arithmetic: "IEEE-754 double; not exact decimal arithmetic" }) };
|
|
182
|
+
}
|
|
183
|
+
const result = evaluateCalculation(input.expression);
|
|
184
|
+
return { output: JSON.stringify({ result, arithmetic: "IEEE-754 double; not exact decimal arithmetic" }) };
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
188
|
+
throw new ToolExecutionError("tool_invalid_args", `${message}. Correct the arguments before retrying; use tools_describe for the schema. No assignments or arbitrary code; supported functions include exp(x), ln(x), log10(x), pow(x,y).`, { retryable: false });
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
});
|