march-cli 0.1.0
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/bin/march.mjs +13 -0
- package/package.json +36 -0
- package/src/agent/command-exec-tool.mjs +91 -0
- package/src/agent/context-stats-tool.mjs +57 -0
- package/src/agent/editing/diff-apply.mjs +28 -0
- package/src/agent/editing/diff-format.mjs +57 -0
- package/src/agent/file-edit-tool.mjs +276 -0
- package/src/agent/find-tool.mjs +112 -0
- package/src/agent/model-payload-dumper.mjs +201 -0
- package/src/agent/pi-session/pi-session-sidecar-failure.mjs +10 -0
- package/src/agent/provider/payload-messages.mjs +138 -0
- package/src/agent/read-file-tool.mjs +112 -0
- package/src/agent/runner/fast-model.mjs +36 -0
- package/src/agent/runner/runner-cleanup.mjs +12 -0
- package/src/agent/runner/runner-init.mjs +15 -0
- package/src/agent/runner/runner-session-state.mjs +40 -0
- package/src/agent/runner.mjs +266 -0
- package/src/agent/runtime/runner-runtime-host.mjs +73 -0
- package/src/agent/runtime/runtime-factory.mjs +42 -0
- package/src/agent/runtime/runtime-host.mjs +34 -0
- package/src/agent/session/session-auto-name.mjs +41 -0
- package/src/agent/session/session-binding.mjs +12 -0
- package/src/agent/session/session-options.mjs +46 -0
- package/src/agent/tool-names.mjs +1 -0
- package/src/agent/tool-result.mjs +3 -0
- package/src/agent/tools.mjs +54 -0
- package/src/agent/turn/turn-events.mjs +64 -0
- package/src/agent/turn/turn-runner.mjs +103 -0
- package/src/auth/login-command.mjs +90 -0
- package/src/auth/storage.mjs +33 -0
- package/src/cli/args.mjs +71 -0
- package/src/cli/commands/copy-command.mjs +73 -0
- package/src/cli/commands/export-command.mjs +206 -0
- package/src/cli/commands/extensions-command.mjs +53 -0
- package/src/cli/commands/help-command.mjs +7 -0
- package/src/cli/commands/model-command.mjs +110 -0
- package/src/cli/commands/paste-image-command.mjs +43 -0
- package/src/cli/commands/provider-command.mjs +55 -0
- package/src/cli/commands/status-command.mjs +157 -0
- package/src/cli/commands/thinking-command.mjs +80 -0
- package/src/cli/fallback-ui.mjs +156 -0
- package/src/cli/input/attachment-tokens.mjs +20 -0
- package/src/cli/input/autocomplete.mjs +106 -0
- package/src/cli/input/external-editor.mjs +39 -0
- package/src/cli/input/history-store.mjs +35 -0
- package/src/cli/input/image-clipboard.mjs +55 -0
- package/src/cli/input/keybinding-dispatch.mjs +76 -0
- package/src/cli/input/keybindings.mjs +96 -0
- package/src/cli/input/mode-state.mjs +43 -0
- package/src/cli/input/prompt-templates.mjs +84 -0
- package/src/cli/input/select-with-keyboard.mjs +67 -0
- package/src/cli/permissions.mjs +103 -0
- package/src/cli/repl-commands.mjs +86 -0
- package/src/cli/repl-loop.mjs +157 -0
- package/src/cli/selector-list.mjs +21 -0
- package/src/cli/session/pi-session-switch-command.mjs +41 -0
- package/src/cli/session/session-command.mjs +23 -0
- package/src/cli/session/session-list-command.mjs +68 -0
- package/src/cli/session/session-name-command.mjs +26 -0
- package/src/cli/session/session-source-command.mjs +89 -0
- package/src/cli/session/session-switch-command.mjs +1 -0
- package/src/cli/shell/shell-command.mjs +55 -0
- package/src/cli/shell/shell-drawer-controls.mjs +33 -0
- package/src/cli/shell/shell-drawer.mjs +192 -0
- package/src/cli/shell/shell-split-layout.mjs +70 -0
- package/src/cli/slash-commands.mjs +176 -0
- package/src/cli/startup/startup-banner.mjs +17 -0
- package/src/cli/startup/startup-session.mjs +51 -0
- package/src/cli/status-line-updater.mjs +74 -0
- package/src/cli/tool-output.mjs +9 -0
- package/src/cli/tui/editor/external-editor-runner.mjs +24 -0
- package/src/cli/tui/input/mouse-selection-controller.mjs +89 -0
- package/src/cli/tui/input/mouse-tracking.mjs +20 -0
- package/src/cli/tui/layout/main-pane-layout.mjs +38 -0
- package/src/cli/tui/layout/safe-render-boundary.mjs +46 -0
- package/src/cli/tui/markdown-renderer.mjs +279 -0
- package/src/cli/tui/output/scroll-state.mjs +79 -0
- package/src/cli/tui/output/tool-card-renderer.mjs +59 -0
- package/src/cli/tui/output-buffer.mjs +297 -0
- package/src/cli/tui/permission-request-ui.mjs +18 -0
- package/src/cli/tui/recall-rendering.mjs +25 -0
- package/src/cli/tui/select/editor-select-list.mjs +111 -0
- package/src/cli/tui/selection-screen.mjs +212 -0
- package/src/cli/tui/status/retry-status.mjs +72 -0
- package/src/cli/tui/status/spinner-status.mjs +42 -0
- package/src/cli/tui/status/status-bar.mjs +88 -0
- package/src/cli/tui/syntax/highlighting.mjs +277 -0
- package/src/cli/tui/syntax/languages.mjs +91 -0
- package/src/cli/tui/syntax/tree-sitter/bash.highlights.scm +261 -0
- package/src/cli/tui/syntax/tree-sitter/c.highlights.scm +341 -0
- package/src/cli/tui/syntax/tree-sitter/cpp.highlights.scm +268 -0
- package/src/cli/tui/syntax/tree-sitter/csharp.highlights.scm +577 -0
- package/src/cli/tui/syntax/tree-sitter/css.highlights.scm +109 -0
- package/src/cli/tui/syntax/tree-sitter/diff.highlights.scm +49 -0
- package/src/cli/tui/syntax/tree-sitter/go.highlights.scm +254 -0
- package/src/cli/tui/syntax/tree-sitter/html.highlights.scm +13 -0
- package/src/cli/tui/syntax/tree-sitter/java.highlights.scm +330 -0
- package/src/cli/tui/syntax/tree-sitter/json.highlights.scm +38 -0
- package/src/cli/tui/syntax/tree-sitter/php.highlights.scm +203 -0
- package/src/cli/tui/syntax/tree-sitter/python.highlights.scm +137 -0
- package/src/cli/tui/syntax/tree-sitter/ruby.highlights.scm +309 -0
- package/src/cli/tui/syntax/tree-sitter/rust.highlights.scm +531 -0
- package/src/cli/tui/syntax/tree-sitter/toml.highlights.scm +39 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-bash.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-c-sharp.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-c.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-cpp.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-css.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-diff.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-go.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-html.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-java.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-json.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-php.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-python.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-ruby.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-rust.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-toml.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-tsx.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-typescript.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-yaml.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tsx.highlights.scm +35 -0
- package/src/cli/tui/syntax/tree-sitter/typescript.highlights.scm +35 -0
- package/src/cli/tui/syntax/tree-sitter/yaml.highlights.scm +99 -0
- package/src/cli/tui/tool-rendering.mjs +194 -0
- package/src/cli/tui/tui-diff-rendering.mjs +157 -0
- package/src/cli/tui/tui-handlers.mjs +110 -0
- package/src/cli/tui/tui-input-controller.mjs +61 -0
- package/src/cli/tui/ui-theme.mjs +148 -0
- package/src/cli/ui.mjs +299 -0
- package/src/config/config-json.mjs +73 -0
- package/src/config/dotenv.mjs +20 -0
- package/src/config/features.mjs +75 -0
- package/src/config/loader.mjs +109 -0
- package/src/config/settings-command.mjs +97 -0
- package/src/context/diagnostics.mjs +70 -0
- package/src/context/engine.mjs +148 -0
- package/src/context/injections.mjs +26 -0
- package/src/context/project-context.mjs +20 -0
- package/src/context/session-status.mjs +15 -0
- package/src/context/shell-layers.mjs +23 -0
- package/src/context/system-core/base.md +60 -0
- package/src/context/system-core/prompts/deepseek-v4-pro.md +3 -0
- package/src/context/system-core/prompts/default.md +3 -0
- package/src/context/system-core.mjs +35 -0
- package/src/debug/model-context-dumper.mjs +52 -0
- package/src/extensions/discovery.mjs +40 -0
- package/src/extensions/lifecycle-adapter.mjs +210 -0
- package/src/extensions/lifecycle-manifest.mjs +69 -0
- package/src/image-gen/index.mjs +7 -0
- package/src/image-gen/provider.mjs +231 -0
- package/src/image-gen/tool.mjs +84 -0
- package/src/lsp/client.mjs +204 -0
- package/src/lsp/diagnostic-store.mjs +39 -0
- package/src/lsp/servers.mjs +212 -0
- package/src/lsp/service.mjs +65 -0
- package/src/main.mjs +294 -0
- package/src/mcp/client.mjs +195 -0
- package/src/mcp/config.mjs +130 -0
- package/src/mcp/index.mjs +48 -0
- package/src/mcp/tools.mjs +98 -0
- package/src/memory/database.mjs +219 -0
- package/src/memory/glossary.mjs +124 -0
- package/src/memory/graph/graph-cascades.mjs +109 -0
- package/src/memory/graph/graph-diagnostics.mjs +73 -0
- package/src/memory/graph/graph-path-removal.mjs +50 -0
- package/src/memory/graph/graph-path-utils.mjs +17 -0
- package/src/memory/graph/graph-primitives.mjs +103 -0
- package/src/memory/graph/graph-read.mjs +159 -0
- package/src/memory/graph.mjs +282 -0
- package/src/memory/markdown/markdown-delete.mjs +23 -0
- package/src/memory/markdown/markdown-format.mjs +128 -0
- package/src/memory/markdown/markdown-recall.mjs +28 -0
- package/src/memory/markdown/ripgrep.mjs +16 -0
- package/src/memory/markdown/sqlite-index.mjs +87 -0
- package/src/memory/markdown-store.mjs +286 -0
- package/src/memory/markdown-tools.mjs +103 -0
- package/src/memory/search.mjs +142 -0
- package/src/memory/snapshot.mjs +86 -0
- package/src/memory/system-views.mjs +120 -0
- package/src/memory/tools.mjs +282 -0
- package/src/notification/desktop-notifier.mjs +85 -0
- package/src/platform/open-file.mjs +28 -0
- package/src/provider/config-command.mjs +129 -0
- package/src/provider/presets.mjs +72 -0
- package/src/session/attachment-display.mjs +16 -0
- package/src/session/attachment-references.mjs +65 -0
- package/src/session/attachments.mjs +140 -0
- package/src/session/persist.mjs +1 -0
- package/src/session/pi-manager.mjs +34 -0
- package/src/session/session-utils.mjs +16 -0
- package/src/session/sidecar-sync.mjs +19 -0
- package/src/session/sidecar.mjs +68 -0
- package/src/session/transcript.mjs +83 -0
- package/src/session/tree.mjs +42 -0
- package/src/shell/cli-runtime.mjs +11 -0
- package/src/shell/hints.mjs +12 -0
- package/src/shell/node-pty-adapter.mjs +81 -0
- package/src/shell/runtime-state.mjs +126 -0
- package/src/shell/runtime.mjs +244 -0
- package/src/shell/screen-buffer.mjs +136 -0
- package/src/shell/tool-read.mjs +74 -0
- package/src/shell/tools.mjs +299 -0
- package/src/supergrok/actions/image-generate.mjs +60 -0
- package/src/supergrok/actions/search.mjs +78 -0
- package/src/supergrok/auth.mjs +36 -0
- package/src/supergrok/constants.mjs +18 -0
- package/src/supergrok/oauth-provider.mjs +278 -0
- package/src/supergrok/provider.mjs +36 -0
- package/src/supergrok/response.mjs +76 -0
- package/src/supergrok/tool.mjs +61 -0
- package/src/text/ansi.mjs +3 -0
- package/src/web/config-command.mjs +43 -0
- package/src/web/fetch.mjs +78 -0
- package/src/web/presets.mjs +16 -0
- package/src/web/search.mjs +83 -0
- package/src/web/tools.mjs +107 -0
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import { registerOAuthProvider } from "@earendil-works/pi-ai/oauth";
|
|
4
|
+
import {
|
|
5
|
+
SUPERGROK_OAUTH_PROVIDER_ID,
|
|
6
|
+
XAI_BASE_URL,
|
|
7
|
+
XAI_OAUTH_CLIENT_ID,
|
|
8
|
+
XAI_OAUTH_DISCOVERY_URL,
|
|
9
|
+
XAI_OAUTH_REDIRECT_HOST,
|
|
10
|
+
XAI_OAUTH_REDIRECT_PATH,
|
|
11
|
+
XAI_OAUTH_REDIRECT_PORT,
|
|
12
|
+
XAI_OAUTH_SCOPE,
|
|
13
|
+
XAI_OAUTH_COMPAT_PROVIDER_ID,
|
|
14
|
+
} from "./constants.mjs";
|
|
15
|
+
|
|
16
|
+
export function registerSuperGrokOAuthProvider() {
|
|
17
|
+
registerOAuthProvider(superGrokOAuthProvider);
|
|
18
|
+
registerOAuthProvider({ ...superGrokOAuthProvider, id: XAI_OAUTH_COMPAT_PROVIDER_ID });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const superGrokOAuthProvider = {
|
|
22
|
+
id: SUPERGROK_OAUTH_PROVIDER_ID,
|
|
23
|
+
name: "SuperGrok OAuth (xAI Subscription)",
|
|
24
|
+
usesCallbackServer: true,
|
|
25
|
+
async login(callbacks) {
|
|
26
|
+
return loginSuperGrok(callbacks);
|
|
27
|
+
},
|
|
28
|
+
async refreshToken(credentials) {
|
|
29
|
+
return refreshSuperGrokToken(credentials);
|
|
30
|
+
},
|
|
31
|
+
getApiKey(credentials) {
|
|
32
|
+
return credentials.access;
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
async function loginSuperGrok(callbacks) {
|
|
37
|
+
const discovery = await discoverXaiOAuth();
|
|
38
|
+
const verifier = createCodeVerifier();
|
|
39
|
+
const challenge = createCodeChallenge(verifier);
|
|
40
|
+
const state = randomBytes(16).toString("hex");
|
|
41
|
+
const nonce = randomBytes(16).toString("hex");
|
|
42
|
+
const redirectUri = `http://${XAI_OAUTH_REDIRECT_HOST}:${XAI_OAUTH_REDIRECT_PORT}${XAI_OAUTH_REDIRECT_PATH}`;
|
|
43
|
+
const server = await startCallbackServer(state);
|
|
44
|
+
const authorizeUrl = buildAuthorizeUrl({
|
|
45
|
+
authorizationEndpoint: discovery.authorization_endpoint,
|
|
46
|
+
redirectUri,
|
|
47
|
+
codeChallenge: challenge,
|
|
48
|
+
state,
|
|
49
|
+
nonce,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
callbacks.onAuth({
|
|
53
|
+
url: authorizeUrl,
|
|
54
|
+
instructions: `Complete the xAI authorization. Waiting for callback on ${redirectUri}`,
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
let code = null;
|
|
59
|
+
if (callbacks.onManualCodeInput) {
|
|
60
|
+
let manualInput;
|
|
61
|
+
let manualError;
|
|
62
|
+
const manualPromise = callbacks.onManualCodeInput()
|
|
63
|
+
.then((input) => {
|
|
64
|
+
manualInput = input;
|
|
65
|
+
server.cancelWait();
|
|
66
|
+
})
|
|
67
|
+
.catch((err) => {
|
|
68
|
+
manualError = err instanceof Error ? err : new Error(String(err));
|
|
69
|
+
server.cancelWait();
|
|
70
|
+
});
|
|
71
|
+
const callback = await server.waitForCode();
|
|
72
|
+
if (manualError) throw manualError;
|
|
73
|
+
if (callback?.code) code = callback.code;
|
|
74
|
+
if (!code && manualInput) code = parseAuthorizationInput(manualInput, state).code;
|
|
75
|
+
if (!code) {
|
|
76
|
+
await manualPromise;
|
|
77
|
+
if (manualError) throw manualError;
|
|
78
|
+
if (manualInput) code = parseAuthorizationInput(manualInput, state).code;
|
|
79
|
+
}
|
|
80
|
+
} else {
|
|
81
|
+
const callback = await server.waitForCode();
|
|
82
|
+
if (callback?.code) code = callback.code;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!code) {
|
|
86
|
+
const input = await callbacks.onPrompt({ message: "Paste the xAI redirect URL or authorization code" });
|
|
87
|
+
code = parseAuthorizationInput(input, state).code;
|
|
88
|
+
}
|
|
89
|
+
if (!code) throw new Error("Missing xAI authorization code");
|
|
90
|
+
|
|
91
|
+
const token = await exchangeAuthorizationCode({
|
|
92
|
+
tokenEndpoint: discovery.token_endpoint,
|
|
93
|
+
code,
|
|
94
|
+
verifier,
|
|
95
|
+
redirectUri,
|
|
96
|
+
});
|
|
97
|
+
return normalizeTokenCredentials(token, {
|
|
98
|
+
tokenEndpoint: discovery.token_endpoint,
|
|
99
|
+
redirectUri,
|
|
100
|
+
});
|
|
101
|
+
} finally {
|
|
102
|
+
server.close();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function discoverXaiOAuth(fetchImpl = fetch) {
|
|
107
|
+
const response = await fetchImpl(XAI_OAUTH_DISCOVERY_URL, { headers: { Accept: "application/json" } });
|
|
108
|
+
if (!response.ok) throw new Error(`xAI OIDC discovery failed (${response.status})`);
|
|
109
|
+
const data = await response.json();
|
|
110
|
+
const authorizationEndpoint = String(data.authorization_endpoint || "").trim();
|
|
111
|
+
const tokenEndpoint = String(data.token_endpoint || "").trim();
|
|
112
|
+
if (!authorizationEndpoint || !tokenEndpoint) throw new Error("xAI OIDC discovery missing endpoints");
|
|
113
|
+
validateXaiAuthEndpoint(authorizationEndpoint, "authorization_endpoint");
|
|
114
|
+
validateXaiAuthEndpoint(tokenEndpoint, "token_endpoint");
|
|
115
|
+
return { authorization_endpoint: authorizationEndpoint, token_endpoint: tokenEndpoint };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function buildAuthorizeUrl({ authorizationEndpoint, redirectUri, codeChallenge, state, nonce }) {
|
|
119
|
+
const url = new URL(authorizationEndpoint);
|
|
120
|
+
url.searchParams.set("response_type", "code");
|
|
121
|
+
url.searchParams.set("client_id", XAI_OAUTH_CLIENT_ID);
|
|
122
|
+
url.searchParams.set("redirect_uri", redirectUri);
|
|
123
|
+
url.searchParams.set("scope", XAI_OAUTH_SCOPE);
|
|
124
|
+
url.searchParams.set("code_challenge", codeChallenge);
|
|
125
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
126
|
+
url.searchParams.set("state", state);
|
|
127
|
+
url.searchParams.set("nonce", nonce);
|
|
128
|
+
url.searchParams.set("plan", "generic");
|
|
129
|
+
url.searchParams.set("referrer", "hermes-agent");
|
|
130
|
+
return url.toString();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function exchangeAuthorizationCode({ tokenEndpoint, code, verifier, redirectUri, fetchImpl = fetch }) {
|
|
134
|
+
validateXaiAuthEndpoint(tokenEndpoint, "token_endpoint");
|
|
135
|
+
const response = await fetchImpl(tokenEndpoint, {
|
|
136
|
+
method: "POST",
|
|
137
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
138
|
+
body: new URLSearchParams({
|
|
139
|
+
grant_type: "authorization_code",
|
|
140
|
+
code,
|
|
141
|
+
redirect_uri: redirectUri,
|
|
142
|
+
client_id: XAI_OAUTH_CLIENT_ID,
|
|
143
|
+
code_verifier: verifier,
|
|
144
|
+
}),
|
|
145
|
+
});
|
|
146
|
+
if (!response.ok) {
|
|
147
|
+
const text = await response.text().catch(() => "");
|
|
148
|
+
throw new Error(`xAI token exchange failed (${response.status}): ${text || response.statusText}`);
|
|
149
|
+
}
|
|
150
|
+
return response.json();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function refreshSuperGrokToken(credentials, { fetchImpl = fetch } = {}) {
|
|
154
|
+
const refreshToken = credentials.refresh || credentials.refresh_token;
|
|
155
|
+
if (!refreshToken) throw new Error("SuperGrok OAuth is missing a refresh token");
|
|
156
|
+
const tokenEndpoint = String(credentials.tokenEndpoint || "").trim() || (await discoverXaiOAuth(fetchImpl)).token_endpoint;
|
|
157
|
+
validateXaiAuthEndpoint(tokenEndpoint, "token_endpoint");
|
|
158
|
+
const response = await fetchImpl(tokenEndpoint, {
|
|
159
|
+
method: "POST",
|
|
160
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
161
|
+
body: new URLSearchParams({
|
|
162
|
+
grant_type: "refresh_token",
|
|
163
|
+
client_id: XAI_OAUTH_CLIENT_ID,
|
|
164
|
+
refresh_token: refreshToken,
|
|
165
|
+
}),
|
|
166
|
+
});
|
|
167
|
+
if (!response.ok) {
|
|
168
|
+
const text = await response.text().catch(() => "");
|
|
169
|
+
throw new Error(`xAI token refresh failed (${response.status}): ${text || response.statusText}`);
|
|
170
|
+
}
|
|
171
|
+
const token = await response.json();
|
|
172
|
+
return normalizeTokenCredentials(token, {
|
|
173
|
+
tokenEndpoint,
|
|
174
|
+
redirectUri: credentials.redirectUri,
|
|
175
|
+
previousRefresh: refreshToken,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function normalizeTokenCredentials(token, { tokenEndpoint, redirectUri, previousRefresh = "" } = {}) {
|
|
180
|
+
const access = String(token.access_token || token.access || "").trim();
|
|
181
|
+
const refresh = String(token.refresh_token || token.refresh || previousRefresh || "").trim();
|
|
182
|
+
if (!access) throw new Error("xAI token response missing access_token");
|
|
183
|
+
if (!refresh) throw new Error("xAI token response missing refresh_token");
|
|
184
|
+
const expiresIn = Number(token.expires_in || 3600);
|
|
185
|
+
return {
|
|
186
|
+
access,
|
|
187
|
+
refresh,
|
|
188
|
+
expires: Date.now() + Math.max(60, expiresIn) * 1000,
|
|
189
|
+
idToken: String(token.id_token || token.idToken || ""),
|
|
190
|
+
tokenType: String(token.token_type || token.tokenType || "Bearer"),
|
|
191
|
+
tokenEndpoint,
|
|
192
|
+
redirectUri,
|
|
193
|
+
baseUrl: XAI_BASE_URL,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function startCallbackServer(expectedState) {
|
|
198
|
+
let settle;
|
|
199
|
+
const waitForCodePromise = new Promise((resolve) => {
|
|
200
|
+
settle = resolve;
|
|
201
|
+
});
|
|
202
|
+
const server = http.createServer((req, res) => {
|
|
203
|
+
const url = new URL(req.url || "/", `http://${XAI_OAUTH_REDIRECT_HOST}:${XAI_OAUTH_REDIRECT_PORT}`);
|
|
204
|
+
if (url.pathname !== XAI_OAUTH_REDIRECT_PATH) {
|
|
205
|
+
res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
|
|
206
|
+
res.end("Callback route not found.");
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if (url.searchParams.get("state") !== expectedState) {
|
|
210
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
211
|
+
res.end("State mismatch.");
|
|
212
|
+
settle(null);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
const code = url.searchParams.get("code");
|
|
216
|
+
const error = url.searchParams.get("error");
|
|
217
|
+
if (!code && error) {
|
|
218
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
219
|
+
res.end(`xAI authorization failed: ${error}`);
|
|
220
|
+
settle(null);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
224
|
+
res.end("SuperGrok authentication completed. You can close this window.");
|
|
225
|
+
settle({ code });
|
|
226
|
+
});
|
|
227
|
+
return new Promise((resolve) => {
|
|
228
|
+
server.listen(XAI_OAUTH_REDIRECT_PORT, XAI_OAUTH_REDIRECT_HOST, () => {
|
|
229
|
+
resolve({
|
|
230
|
+
close: () => server.close(),
|
|
231
|
+
cancelWait: () => settle(null),
|
|
232
|
+
waitForCode: () => waitForCodePromise,
|
|
233
|
+
});
|
|
234
|
+
}).on("error", () => {
|
|
235
|
+
settle(null);
|
|
236
|
+
resolve({ close: () => {}, cancelWait: () => settle(null), waitForCode: () => waitForCodePromise });
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function parseAuthorizationInput(input, expectedState) {
|
|
242
|
+
const value = String(input || "").trim();
|
|
243
|
+
if (!value) return {};
|
|
244
|
+
try {
|
|
245
|
+
const url = new URL(value);
|
|
246
|
+
const state = url.searchParams.get("state") || undefined;
|
|
247
|
+
if (state && state !== expectedState) throw new Error("State mismatch");
|
|
248
|
+
return { code: url.searchParams.get("code") || undefined };
|
|
249
|
+
} catch (err) {
|
|
250
|
+
if (err.message === "State mismatch") throw err;
|
|
251
|
+
}
|
|
252
|
+
if (value.includes("code=")) {
|
|
253
|
+
const params = new URLSearchParams(value);
|
|
254
|
+
const state = params.get("state") || undefined;
|
|
255
|
+
if (state && state !== expectedState) throw new Error("State mismatch");
|
|
256
|
+
return { code: params.get("code") || undefined };
|
|
257
|
+
}
|
|
258
|
+
return { code: value };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function createCodeVerifier() {
|
|
262
|
+
return base64Url(randomBytes(32));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function createCodeChallenge(verifier) {
|
|
266
|
+
return base64Url(createHash("sha256").update(verifier).digest());
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function base64Url(buffer) {
|
|
270
|
+
return Buffer.from(buffer).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function validateXaiAuthEndpoint(value, field) {
|
|
274
|
+
const url = new URL(value);
|
|
275
|
+
if (url.protocol !== "https:" || !url.hostname.endsWith("x.ai")) {
|
|
276
|
+
throw new Error(`Invalid xAI OAuth ${field}: ${value}`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { DEFAULT_SUPERGROK_MODEL, SUPERGROK_OAUTH_PROVIDER_ID, XAI_BASE_URL, XAI_OAUTH_COMPAT_PROVIDER_ID } from "./constants.mjs";
|
|
2
|
+
import { registerSuperGrokOAuthProvider, superGrokOAuthProvider } from "./oauth-provider.mjs";
|
|
3
|
+
|
|
4
|
+
const GROK_MODELS = [
|
|
5
|
+
{ id: "grok-4.3", name: "Grok 4.3", contextWindow: 1000000, maxTokens: 128000 },
|
|
6
|
+
{ id: "grok-4.20-reasoning", name: "Grok 4.20 Reasoning", contextWindow: 2000000, maxTokens: 128000 },
|
|
7
|
+
{ id: "grok-4.20-non-reasoning", name: "Grok 4.20 Non Reasoning", contextWindow: 2000000, maxTokens: 128000 },
|
|
8
|
+
{ id: "grok-4.20-multi-agent", name: "Grok 4.20 Multi Agent", contextWindow: 2000000, maxTokens: 128000 },
|
|
9
|
+
{ id: "grok-code-fast-1", name: "Grok Code Fast 1", contextWindow: 256000, maxTokens: 128000 },
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
export function registerSuperGrokProvider(modelRegistry) {
|
|
13
|
+
registerSuperGrokOAuthProvider();
|
|
14
|
+
if (!modelRegistry?.registerProvider) return;
|
|
15
|
+
for (const providerId of [SUPERGROK_OAUTH_PROVIDER_ID, XAI_OAUTH_COMPAT_PROVIDER_ID]) {
|
|
16
|
+
modelRegistry.registerProvider(providerId, {
|
|
17
|
+
name: providerId === SUPERGROK_OAUTH_PROVIDER_ID ? "SuperGrok OAuth (xAI Subscription)" : "xAI OAuth (SuperGrok compatible)",
|
|
18
|
+
baseUrl: XAI_BASE_URL,
|
|
19
|
+
api: "openai-responses",
|
|
20
|
+
oauth: { ...superGrokOAuthProvider, id: providerId },
|
|
21
|
+
models: GROK_MODELS.map((model) => ({
|
|
22
|
+
...model,
|
|
23
|
+
api: "openai-responses",
|
|
24
|
+
baseUrl: XAI_BASE_URL,
|
|
25
|
+
reasoning: false,
|
|
26
|
+
input: ["text"],
|
|
27
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
28
|
+
compat: { supportsLongCacheRetention: true },
|
|
29
|
+
})),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function getDefaultSuperGrokModelId() {
|
|
35
|
+
return DEFAULT_SUPERGROK_MODEL;
|
|
36
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
export function successEnvelope({ credentialSource, action, model, query, answer = "", citations = [], inlineCitations = [], artifacts = [], extra = {} }) {
|
|
2
|
+
return {
|
|
3
|
+
success: true,
|
|
4
|
+
provider: "xai",
|
|
5
|
+
credential_source: credentialSource,
|
|
6
|
+
action,
|
|
7
|
+
model,
|
|
8
|
+
query,
|
|
9
|
+
answer,
|
|
10
|
+
citations,
|
|
11
|
+
inline_citations: inlineCitations,
|
|
12
|
+
artifacts,
|
|
13
|
+
...extra,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function errorEnvelope({ credentialSource = null, action, model = null, query = "", error, errorType = "error" }) {
|
|
18
|
+
return {
|
|
19
|
+
success: false,
|
|
20
|
+
provider: "xai",
|
|
21
|
+
credential_source: credentialSource,
|
|
22
|
+
action,
|
|
23
|
+
model,
|
|
24
|
+
query,
|
|
25
|
+
error,
|
|
26
|
+
error_type: errorType,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function extractResponseText(payload) {
|
|
31
|
+
const outputText = String(payload?.output_text || "").trim();
|
|
32
|
+
if (outputText) return outputText;
|
|
33
|
+
|
|
34
|
+
const parts = [];
|
|
35
|
+
for (const item of payload?.output || []) {
|
|
36
|
+
if (item?.type !== "message") continue;
|
|
37
|
+
for (const content of item.content || []) {
|
|
38
|
+
if (content?.type !== "output_text" && content?.type !== "text") continue;
|
|
39
|
+
const text = String(content.text || "").trim();
|
|
40
|
+
if (text) parts.push(text);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return parts.join("\n\n").trim();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function extractInlineCitations(payload) {
|
|
47
|
+
const citations = [];
|
|
48
|
+
for (const item of payload?.output || []) {
|
|
49
|
+
if (item?.type !== "message") continue;
|
|
50
|
+
for (const content of item.content || []) {
|
|
51
|
+
for (const annotation of content.annotations || []) {
|
|
52
|
+
if (annotation?.type !== "url_citation") continue;
|
|
53
|
+
citations.push({
|
|
54
|
+
url: annotation.url || "",
|
|
55
|
+
title: annotation.title || "",
|
|
56
|
+
start_index: annotation.start_index,
|
|
57
|
+
end_index: annotation.end_index,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return citations;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function readErrorMessage(response) {
|
|
66
|
+
const text = await response.text().catch(() => "");
|
|
67
|
+
if (!text) return response.statusText || `HTTP ${response.status}`;
|
|
68
|
+
try {
|
|
69
|
+
const json = JSON.parse(text);
|
|
70
|
+
if (typeof json.error === "string") return json.code && !json.error.includes(json.code) ? `${json.code}: ${json.error}` : json.error;
|
|
71
|
+
if (json.error?.message) return json.error.message;
|
|
72
|
+
return JSON.stringify(json).slice(0, 500);
|
|
73
|
+
} catch {
|
|
74
|
+
return text.slice(0, 500);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { toolText } from "../agent/tool-result.mjs";
|
|
4
|
+
import { resolveSuperGrokCredentials } from "./auth.mjs";
|
|
5
|
+
import { runSuperGrokImageGenerate } from "./actions/image-generate.mjs";
|
|
6
|
+
import { runSuperGrokSearch } from "./actions/search.mjs";
|
|
7
|
+
import { errorEnvelope } from "./response.mjs";
|
|
8
|
+
|
|
9
|
+
const ACTIONS = ["web_search", "x_search", "image_generate"];
|
|
10
|
+
|
|
11
|
+
export function createSuperGrokTool({ authStorage, projectMarchDir, resolveCredentials = resolveSuperGrokCredentials, fetchImpl = fetch } = {}) {
|
|
12
|
+
return defineTool({
|
|
13
|
+
name: "supergrok",
|
|
14
|
+
label: "SuperGrok",
|
|
15
|
+
description:
|
|
16
|
+
"Use SuperGrok capabilities through xAI: realtime web search, X/Twitter search, and Grok image generation. " +
|
|
17
|
+
"Default search behavior is broad and enables image/video understanding where supported. Requires SuperGrok OAuth or XAI_API_KEY.",
|
|
18
|
+
promptSnippet: "supergrok(action, query, options?) - Use SuperGrok web_search, x_search, or image_generate",
|
|
19
|
+
promptGuidelines: [
|
|
20
|
+
"Use action=web_search for current web/news/documentation facts.",
|
|
21
|
+
"Use action=x_search for current X/Twitter posts, reactions, profiles, and threads.",
|
|
22
|
+
"Use action=image_generate when the user asks Grok/SuperGrok to create an image.",
|
|
23
|
+
"Do not add domain, handle, or date filters unless the user asks for that narrower scope.",
|
|
24
|
+
],
|
|
25
|
+
parameters: Type.Object({
|
|
26
|
+
action: Type.String({ enum: ACTIONS, description: "SuperGrok capability to invoke" }),
|
|
27
|
+
query: Type.String({ description: "Search query or image prompt" }),
|
|
28
|
+
options: Type.Optional(Type.Object({}, { additionalProperties: true, description: "Action-specific optional controls" })),
|
|
29
|
+
}),
|
|
30
|
+
execute: async (_toolCallId, params) => {
|
|
31
|
+
const action = params.action;
|
|
32
|
+
const query = String(params.query || "").trim();
|
|
33
|
+
const options = params.options && typeof params.options === "object" ? params.options : {};
|
|
34
|
+
if (!ACTIONS.includes(action)) return toolJson(errorEnvelope({ action, query, error: `Unsupported SuperGrok action: ${action}`, errorType: "invalid_action" }), { error: true });
|
|
35
|
+
if (!query) return toolJson(errorEnvelope({ action, query, error: "query is required", errorType: "invalid_request" }), { error: true });
|
|
36
|
+
|
|
37
|
+
let credentials;
|
|
38
|
+
try {
|
|
39
|
+
credentials = await resolveCredentials({ authStorage });
|
|
40
|
+
const payload = action === "image_generate"
|
|
41
|
+
? await runSuperGrokImageGenerate({ query, options, credentials, projectMarchDir, fetchImpl })
|
|
42
|
+
: await runSuperGrokSearch({ action, query, options, credentials, fetchImpl });
|
|
43
|
+
return toolJson(payload, payload);
|
|
44
|
+
} catch (err) {
|
|
45
|
+
const payload = errorEnvelope({
|
|
46
|
+
credentialSource: credentials?.credentialSource ?? null,
|
|
47
|
+
action,
|
|
48
|
+
model: options.model ?? null,
|
|
49
|
+
query,
|
|
50
|
+
error: err.message,
|
|
51
|
+
errorType: err.name || "error",
|
|
52
|
+
});
|
|
53
|
+
return toolJson(payload, { ...payload, error: true });
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function toolJson(payload, details = {}) {
|
|
60
|
+
return toolText(JSON.stringify(payload, null, 2), details);
|
|
61
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { createInterface } from "node:readline";
|
|
2
|
+
import { selectWithKeyboard } from "../cli/input/select-with-keyboard.mjs";
|
|
3
|
+
import { globalConfigJsonPath, upsertWebSearchProvider } from "../config/config-json.mjs";
|
|
4
|
+
import { WEB_SEARCH_PRESETS } from "./presets.mjs";
|
|
5
|
+
|
|
6
|
+
export async function runWebSearchConfigCommand({
|
|
7
|
+
homeDir,
|
|
8
|
+
input = process.stdin,
|
|
9
|
+
output = process.stdout,
|
|
10
|
+
select = selectWithKeyboard,
|
|
11
|
+
readSecret = readLine,
|
|
12
|
+
} = {}) {
|
|
13
|
+
const preset = await select({
|
|
14
|
+
input,
|
|
15
|
+
output,
|
|
16
|
+
message: "Choose web search provider to configure",
|
|
17
|
+
items: WEB_SEARCH_PRESETS.map((item) => ({ label: item.label, value: item })),
|
|
18
|
+
});
|
|
19
|
+
if (!preset) {
|
|
20
|
+
output.write("Web search configuration cancelled.\n");
|
|
21
|
+
return 1;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const apiKey = String(await readSecret({ input, output, prompt: `${preset.apiKeyLabel}: ` }) ?? "").trim();
|
|
25
|
+
if (!apiKey) {
|
|
26
|
+
output.write("API key is required.\n");
|
|
27
|
+
return 1;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const path = globalConfigJsonPath(homeDir);
|
|
31
|
+
upsertWebSearchProvider({ path, id: preset.id, apiKey });
|
|
32
|
+
output.write(`Saved web search provider: ${preset.label}\n`);
|
|
33
|
+
output.write(`Config: ${path}\n`);
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function readLine({ input = process.stdin, output = process.stdout, prompt }) {
|
|
38
|
+
const rl = createInterface({ input, output });
|
|
39
|
+
return new Promise((resolve) => rl.question(prompt, (answer) => {
|
|
40
|
+
rl.close();
|
|
41
|
+
resolve(answer);
|
|
42
|
+
}));
|
|
43
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Web fetch tool — fetches a URL and extracts readable content.
|
|
3
|
+
* No API key required. Uses basic HTML-to-text extraction.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const MAX_CONTENT_LENGTH = 50_000;
|
|
7
|
+
|
|
8
|
+
export async function fetchWebPage(url, { timeout = 15_000 } = {}) {
|
|
9
|
+
const controller = new AbortController();
|
|
10
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
11
|
+
|
|
12
|
+
try {
|
|
13
|
+
const res = await fetch(url, {
|
|
14
|
+
signal: controller.signal,
|
|
15
|
+
headers: {
|
|
16
|
+
"User-Agent": "March/0.1 (web-fetch)",
|
|
17
|
+
Accept: "text/html,application/xhtml+xml,text/plain",
|
|
18
|
+
},
|
|
19
|
+
redirect: "follow",
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
if (!res.ok) {
|
|
23
|
+
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
27
|
+
if (!contentType.includes("text/html") && !contentType.includes("text/plain")) {
|
|
28
|
+
throw new Error(`Unsupported content type: ${contentType}`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const raw = await res.text();
|
|
32
|
+
return extractText(raw, url);
|
|
33
|
+
} finally {
|
|
34
|
+
clearTimeout(timer);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function extractText(html, baseUrl) {
|
|
39
|
+
// Strip scripts, styles, and metadata
|
|
40
|
+
let text = html
|
|
41
|
+
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "")
|
|
42
|
+
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "")
|
|
43
|
+
.replace(/<head[^>]*>[\s\S]*?<\/head>/gi, "")
|
|
44
|
+
.replace(/<noscript[^>]*>[\s\S]*?<\/noscript>/gi, "");
|
|
45
|
+
|
|
46
|
+
// Convert block elements to newlines
|
|
47
|
+
text = text.replace(/<\/(div|p|h[1-6]|li|tr|article|section|header|footer|nav|main|aside)[^>]*>/gi, "\n");
|
|
48
|
+
text = text.replace(/<br\s*\/?>/gi, "\n");
|
|
49
|
+
text = text.replace(/<\/?(div|p|h[1-6]|li|tr|article|section|header|footer|nav|main|aside)[^>]*>/gi, "");
|
|
50
|
+
|
|
51
|
+
// Strip remaining tags
|
|
52
|
+
text = text.replace(/<[^>]+>/g, "");
|
|
53
|
+
|
|
54
|
+
// Decode entities
|
|
55
|
+
text = text
|
|
56
|
+
.replace(/&/g, "&")
|
|
57
|
+
.replace(/</g, "<")
|
|
58
|
+
.replace(/>/g, ">")
|
|
59
|
+
.replace(/"/g, '"')
|
|
60
|
+
.replace(/'/g, "'")
|
|
61
|
+
.replace(/ /g, " ");
|
|
62
|
+
|
|
63
|
+
// Collapse whitespace
|
|
64
|
+
text = text.replace(/[ \t]+/g, " ");
|
|
65
|
+
text = text.replace(/\n{3,}/g, "\n\n");
|
|
66
|
+
text = text.trim();
|
|
67
|
+
|
|
68
|
+
if (text.length > MAX_CONTENT_LENGTH) {
|
|
69
|
+
text = text.slice(0, MAX_CONTENT_LENGTH) + "\n\n...(content truncated)";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
text,
|
|
74
|
+
url: baseUrl,
|
|
75
|
+
length: text.length,
|
|
76
|
+
truncated: text.length >= MAX_CONTENT_LENGTH,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export const WEB_SEARCH_PRESETS = [
|
|
2
|
+
{
|
|
3
|
+
id: "tavily",
|
|
4
|
+
label: "Tavily",
|
|
5
|
+
apiKeyLabel: "Tavily API key",
|
|
6
|
+
},
|
|
7
|
+
{
|
|
8
|
+
id: "brave",
|
|
9
|
+
label: "Brave Search",
|
|
10
|
+
apiKeyLabel: "Brave Search API key",
|
|
11
|
+
},
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
export function getWebSearchPreset(id) {
|
|
15
|
+
return WEB_SEARCH_PRESETS.find((preset) => preset.id === id) ?? null;
|
|
16
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Web search tool — supports tavily and brave search APIs.
|
|
3
|
+
* Falls back gracefully if no API key is configured.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const TAVILY_API = "https://api.tavily.com/search";
|
|
7
|
+
|
|
8
|
+
export async function tavilySearch(query, apiKey, { maxResults = 5, searchDepth = "basic" } = {}) {
|
|
9
|
+
if (!apiKey) throw new Error("TAVILY_API_KEY not configured");
|
|
10
|
+
|
|
11
|
+
const res = await fetch(TAVILY_API, {
|
|
12
|
+
method: "POST",
|
|
13
|
+
headers: { "Content-Type": "application/json" },
|
|
14
|
+
body: JSON.stringify({
|
|
15
|
+
api_key: apiKey,
|
|
16
|
+
query,
|
|
17
|
+
max_results: maxResults,
|
|
18
|
+
search_depth: searchDepth,
|
|
19
|
+
}),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
if (!res.ok) {
|
|
23
|
+
const err = await res.text();
|
|
24
|
+
throw new Error(`Tavily search failed (${res.status}): ${err.slice(0, 200)}`);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const data = await res.json();
|
|
28
|
+
return (data.results ?? []).map((r) => ({
|
|
29
|
+
title: r.title ?? "",
|
|
30
|
+
url: r.url ?? "",
|
|
31
|
+
snippet: r.content ?? "",
|
|
32
|
+
score: r.score ?? null,
|
|
33
|
+
}));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const BRAVE_API = "https://api.search.brave.com/res/v1/web/search";
|
|
37
|
+
|
|
38
|
+
export async function braveSearch(query, apiKey, { maxResults = 5 } = {}) {
|
|
39
|
+
if (!apiKey) throw new Error("BRAVE_API_KEY not configured");
|
|
40
|
+
|
|
41
|
+
const res = await fetch(`${BRAVE_API}?q=${encodeURIComponent(query)}&count=${maxResults}`, {
|
|
42
|
+
headers: {
|
|
43
|
+
Accept: "application/json",
|
|
44
|
+
"Accept-Encoding": "gzip",
|
|
45
|
+
"X-Subscription-Token": apiKey,
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
if (!res.ok) {
|
|
50
|
+
const err = await res.text();
|
|
51
|
+
throw new Error(`Brave search failed (${res.status}): ${err.slice(0, 200)}`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const data = await res.json();
|
|
55
|
+
return (data.web?.results ?? []).map((r) => ({
|
|
56
|
+
title: r.title ?? "",
|
|
57
|
+
url: r.url ?? "",
|
|
58
|
+
snippet: r.description ?? "",
|
|
59
|
+
}));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Try available search providers in order.
|
|
64
|
+
* Returns { results, provider } or throws if none are configured.
|
|
65
|
+
*/
|
|
66
|
+
export async function searchWeb(query, { tavilyKey, braveKey, maxResults = 5 } = {}) {
|
|
67
|
+
if (tavilyKey) {
|
|
68
|
+
try {
|
|
69
|
+
const results = await tavilySearch(query, tavilyKey, { maxResults });
|
|
70
|
+
return { results, provider: "tavily" };
|
|
71
|
+
} catch (err) {
|
|
72
|
+
// Fall through to next provider
|
|
73
|
+
if (!braveKey) throw err;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (braveKey) {
|
|
78
|
+
const results = await braveSearch(query, braveKey, { maxResults });
|
|
79
|
+
return { results, provider: "brave" };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
throw new Error("No search API key configured. Run: march websearch --config");
|
|
83
|
+
}
|