modkh 0.0.0-stage → 0.2.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/README.md +66 -2
- package/dist/agent/bundled-skills.d.ts +13 -0
- package/dist/agent/bundled-skills.js +95 -0
- package/dist/agent/compaction.d.ts +53 -0
- package/dist/agent/compaction.js +191 -0
- package/dist/agent/images.d.ts +10 -0
- package/dist/agent/images.js +33 -0
- package/dist/agent/loop.d.ts +103 -0
- package/dist/agent/loop.js +267 -0
- package/dist/agent/skills.d.ts +26 -0
- package/dist/agent/skills.js +190 -0
- package/dist/agent/types.d.ts +137 -0
- package/dist/agent/types.js +12 -0
- package/dist/cli/agenticreplay.d.ts +1 -0
- package/dist/cli/agenticreplay.js +66 -0
- package/dist/cli/agents.d.ts +8 -0
- package/dist/cli/agents.js +12 -0
- package/dist/cli/answer-markdown.d.ts +3 -0
- package/dist/cli/answer-markdown.js +29 -0
- package/dist/cli/approval.d.ts +29 -0
- package/dist/cli/approval.js +92 -0
- package/dist/cli/catalog.d.ts +37 -0
- package/dist/cli/catalog.js +46 -0
- package/dist/cli/chat.d.ts +18 -0
- package/dist/cli/chat.js +1061 -0
- package/dist/cli/clipboard.d.ts +11 -0
- package/dist/cli/clipboard.js +82 -0
- package/dist/cli/color.d.ts +59 -0
- package/dist/cli/color.js +244 -0
- package/dist/cli/compaction-settings.d.ts +21 -0
- package/dist/cli/compaction-settings.js +54 -0
- package/dist/cli/completion-art.d.ts +2 -0
- package/dist/cli/completion-art.js +62 -0
- package/dist/cli/config.d.ts +50 -0
- package/dist/cli/config.js +192 -0
- package/dist/cli/editor.d.ts +23 -0
- package/dist/cli/editor.js +115 -0
- package/dist/cli/file-mentions.d.ts +14 -0
- package/dist/cli/file-mentions.js +141 -0
- package/dist/cli/head-checks.d.ts +41 -0
- package/dist/cli/head-checks.js +146 -0
- package/dist/cli/initial-connection.d.ts +7 -0
- package/dist/cli/initial-connection.js +20 -0
- package/dist/cli/keys.d.ts +29 -0
- package/dist/cli/keys.js +107 -0
- package/dist/cli/language.d.ts +1 -0
- package/dist/cli/language.js +105 -0
- package/dist/cli/limits.d.ts +13 -0
- package/dist/cli/limits.js +19 -0
- package/dist/cli/lines.d.ts +18 -0
- package/dist/cli/lines.js +80 -0
- package/dist/cli/model-catalog.d.ts +16 -0
- package/dist/cli/model-catalog.js +130 -0
- package/dist/cli/models.d.ts +4 -0
- package/dist/cli/models.js +101 -0
- package/dist/cli/official-models.d.ts +6 -0
- package/dist/cli/official-models.js +77 -0
- package/dist/cli/pdf.d.ts +8 -0
- package/dist/cli/pdf.js +71 -0
- package/dist/cli/permissions.d.ts +25 -0
- package/dist/cli/permissions.js +30 -0
- package/dist/cli/plugins.d.ts +1 -0
- package/dist/cli/plugins.js +53 -0
- package/dist/cli/providers.d.ts +10 -0
- package/dist/cli/providers.js +82 -0
- package/dist/cli/shell-display.d.ts +6 -0
- package/dist/cli/shell-display.js +35 -0
- package/dist/cli/stateright.d.ts +1 -0
- package/dist/cli/stateright.js +37 -0
- package/dist/cli/terminal-mouse.d.ts +21 -0
- package/dist/cli/terminal-mouse.js +51 -0
- package/dist/cli/terminal.d.ts +231 -0
- package/dist/cli/terminal.js +1417 -0
- package/dist/cli/tool-display.d.ts +9 -0
- package/dist/cli/tool-display.js +87 -0
- package/dist/cli/transcript-selection.d.ts +22 -0
- package/dist/cli/transcript-selection.js +75 -0
- package/dist/cli/usage.d.ts +22 -0
- package/dist/cli/usage.js +117 -0
- package/dist/cli/waiting-nyan.d.ts +3 -0
- package/dist/cli/waiting-nyan.js +17 -0
- package/dist/cli/waiting-whales.d.ts +3 -0
- package/dist/cli/waiting-whales.js +24 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +186 -0
- package/dist/language/catalog.d.ts +44 -0
- package/dist/language/catalog.js +100 -0
- package/dist/language/commonlisp-bundled.d.ts +11 -0
- package/dist/language/commonlisp-bundled.js +22 -0
- package/dist/language/commonlisp-dependencies.d.ts +16 -0
- package/dist/language/commonlisp-dependencies.js +68 -0
- package/dist/language/commonlisp-install.d.ts +15 -0
- package/dist/language/commonlisp-install.js +214 -0
- package/dist/language/commonlisp-reader.d.ts +17 -0
- package/dist/language/commonlisp-reader.js +47 -0
- package/dist/language/commonlisp-systems.d.ts +3 -0
- package/dist/language/commonlisp-systems.js +32 -0
- package/dist/language/commonlisp-tls.d.ts +10 -0
- package/dist/language/commonlisp-tls.js +51 -0
- package/dist/language/detect.d.ts +29 -0
- package/dist/language/detect.js +103 -0
- package/dist/language/grammars/LICENSE +24 -0
- package/dist/language/grammars/manifest.json +76 -0
- package/dist/language/grammars/tree-sitter-c.wasm +0 -0
- package/dist/language/grammars/tree-sitter-cpp.wasm +0 -0
- package/dist/language/grammars/tree-sitter-css.wasm +0 -0
- package/dist/language/grammars/tree-sitter-html.wasm +0 -0
- package/dist/language/grammars/tree-sitter-javascript.wasm +0 -0
- package/dist/language/grammars/tree-sitter-php.wasm +0 -0
- package/dist/language/grammars/tree-sitter-python.wasm +0 -0
- package/dist/language/grammars/tree-sitter-ruby.wasm +0 -0
- package/dist/language/grammars/tree-sitter-rust.wasm +0 -0
- package/dist/language/grammars/tree-sitter-swift.wasm +0 -0
- package/dist/language/grammars/tree-sitter-tsx.wasm +0 -0
- package/dist/language/grammars/tree-sitter-typescript.wasm +0 -0
- package/dist/language/install.d.ts +50 -0
- package/dist/language/install.js +293 -0
- package/dist/language/lsp/client.d.ts +97 -0
- package/dist/language/lsp/client.js +340 -0
- package/dist/language/lsp/pool.d.ts +75 -0
- package/dist/language/lsp/pool.js +140 -0
- package/dist/language/lsp/service.d.ts +50 -0
- package/dist/language/lsp/service.js +174 -0
- package/dist/language/native.d.ts +8 -0
- package/dist/language/native.js +100 -0
- package/dist/language/platform.d.ts +14 -0
- package/dist/language/platform.js +20 -0
- package/dist/language/positions.d.ts +20 -0
- package/dist/language/positions.js +46 -0
- package/dist/language/syntax/assets.d.ts +9 -0
- package/dist/language/syntax/assets.js +73 -0
- package/dist/language/syntax/parser.d.ts +33 -0
- package/dist/language/syntax/parser.js +162 -0
- package/dist/language/typescript-capability.d.ts +6 -0
- package/dist/language/typescript-capability.js +42 -0
- package/dist/lisp/builtin-agents.d.ts +5 -0
- package/dist/lisp/builtin-agents.js +52 -0
- package/dist/lisp/config.d.ts +25 -0
- package/dist/lisp/config.js +202 -0
- package/dist/lisp/routing.d.ts +5 -0
- package/dist/lisp/routing.js +24 -0
- package/dist/lisp/runtime.d.ts +26 -0
- package/dist/lisp/runtime.js +107 -0
- package/dist/memory/kiokuko.d.ts +32 -0
- package/dist/memory/kiokuko.js +102 -0
- package/dist/memory/mcp.d.ts +38 -0
- package/dist/memory/mcp.js +211 -0
- package/dist/model/ai-sdk.d.ts +27 -0
- package/dist/model/ai-sdk.js +185 -0
- package/dist/model/chatgpt/login.d.ts +42 -0
- package/dist/model/chatgpt/login.js +180 -0
- package/dist/model/chatgpt/responses.d.ts +41 -0
- package/dist/model/chatgpt/responses.js +254 -0
- package/dist/model/chatgpt/tokens.d.ts +11 -0
- package/dist/model/chatgpt/tokens.js +50 -0
- package/dist/model/connection.d.ts +6 -0
- package/dist/model/connection.js +67 -0
- package/dist/model/context-window.d.ts +3 -0
- package/dist/model/context-window.js +64 -0
- package/dist/model/context.d.ts +11 -0
- package/dist/model/context.js +69 -0
- package/dist/model/factory.d.ts +27 -0
- package/dist/model/factory.js +89 -0
- package/dist/model/fixed.d.ts +17 -0
- package/dist/model/fixed.js +41 -0
- package/dist/model/harness-profile.d.ts +6 -0
- package/dist/model/harness-profile.js +23 -0
- package/dist/model/providers.d.ts +32 -0
- package/dist/model/providers.js +72 -0
- package/dist/model/reasoning.d.ts +16 -0
- package/dist/model/reasoning.js +84 -0
- package/dist/model/record-fetch.d.ts +2 -0
- package/dist/model/record-fetch.js +19 -0
- package/dist/plugins/api.d.ts +60 -0
- package/dist/plugins/api.js +1 -0
- package/dist/plugins/manager.d.ts +35 -0
- package/dist/plugins/manager.js +280 -0
- package/dist/plugins/package.d.ts +13 -0
- package/dist/plugins/package.js +99 -0
- package/dist/plugins/registry.d.ts +8 -0
- package/dist/plugins/registry.js +14 -0
- package/dist/session/store.d.ts +93 -0
- package/dist/session/store.js +311 -0
- package/dist/session/workspace.d.ts +19 -0
- package/dist/session/workspace.js +73 -0
- package/dist/subagents/head-assignment.d.ts +11 -0
- package/dist/subagents/head-assignment.js +47 -0
- package/dist/subagents/limits.d.ts +4 -0
- package/dist/subagents/limits.js +6 -0
- package/dist/subagents/processes.d.ts +18 -0
- package/dist/subagents/processes.js +73 -0
- package/dist/subagents/request.d.ts +4 -0
- package/dist/subagents/request.js +38 -0
- package/dist/subagents/service.d.ts +73 -0
- package/dist/subagents/service.js +645 -0
- package/dist/subagents/settings.d.ts +10 -0
- package/dist/subagents/settings.js +32 -0
- package/dist/subagents/types.d.ts +63 -0
- package/dist/subagents/types.js +1 -0
- package/dist/subagents/verification.d.ts +34 -0
- package/dist/subagents/verification.js +215 -0
- package/dist/tools/browse.d.ts +13 -0
- package/dist/tools/browse.js +117 -0
- package/dist/tools/browser-capability.d.ts +3 -0
- package/dist/tools/browser-capability.js +29 -0
- package/dist/tools/diff.d.ts +6 -0
- package/dist/tools/diff.js +82 -0
- package/dist/tools/edit.d.ts +3 -0
- package/dist/tools/edit.js +152 -0
- package/dist/tools/files.d.ts +6 -0
- package/dist/tools/files.js +96 -0
- package/dist/tools/formal-input.d.ts +6 -0
- package/dist/tools/formal-input.js +29 -0
- package/dist/tools/formal.d.ts +9 -0
- package/dist/tools/formal.js +79 -0
- package/dist/tools/guard.d.ts +7 -0
- package/dist/tools/guard.js +48 -0
- package/dist/tools/job-tools.d.ts +19 -0
- package/dist/tools/job-tools.js +148 -0
- package/dist/tools/jobs.d.ts +79 -0
- package/dist/tools/jobs.js +186 -0
- package/dist/tools/language.d.ts +6 -0
- package/dist/tools/language.js +172 -0
- package/dist/tools/lean-proof.d.ts +38 -0
- package/dist/tools/lean-proof.js +83 -0
- package/dist/tools/registry.d.ts +30 -0
- package/dist/tools/registry.js +113 -0
- package/dist/tools/run.d.ts +13 -0
- package/dist/tools/run.js +163 -0
- package/dist/tools/search.d.ts +2 -0
- package/dist/tools/search.js +156 -0
- package/dist/tools/shell-process.d.ts +115 -0
- package/dist/tools/shell-process.js +297 -0
- package/dist/tools/skills.d.ts +2 -0
- package/dist/tools/skills.js +46 -0
- package/dist/tools/stateright-runtime.d.ts +3 -0
- package/dist/tools/stateright-runtime.js +16 -0
- package/dist/tools/stateright.d.ts +3 -0
- package/dist/tools/stateright.js +78 -0
- package/dist/tools/web.d.ts +24 -0
- package/dist/tools/web.js +391 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/docs/ci-repair-20261116.md +30 -0
- package/docs/commonlisp-build-output.md +14 -0
- package/docs/commonlisp-provider-migration.md +22 -0
- package/docs/commonlisp-qlot-recovery.md +28 -0
- package/docs/commonlisp-tls-recovery.md +28 -0
- package/docs/context-efficiency.md +122 -0
- package/docs/input.md +126 -0
- package/docs/languages.md +117 -0
- package/docs/models.md +109 -0
- package/docs/modkh-evidence.json +641 -0
- package/docs/modkh-failure-comparison.json +675 -0
- package/docs/modkh-namespace.md +39 -0
- package/docs/modkh-qlot-evidence.json +37 -0
- package/docs/modkh-verification.md +173 -0
- package/docs/modkh.md +128 -0
- package/docs/presets.md +64 -0
- package/docs/setup.md +99 -0
- package/docs/stateright.md +45 -0
- package/docs/subagents.md +152 -0
- package/docs/web.md +57 -0
- package/experiments/presets/common-lisp.lisp +38 -0
- package/experiments/presets/css.lisp +38 -0
- package/experiments/presets/formal.lisp +18 -0
- package/experiments/presets/html.lisp +38 -0
- package/experiments/presets/js.lisp +38 -0
- package/experiments/presets/language-microagents.lisp +29 -0
- package/experiments/presets/php.lisp +38 -0
- package/experiments/presets/svelte.lisp +38 -0
- package/experiments/presets/tailwindcss.lisp +24 -0
- package/experiments/presets/ts.lisp +38 -0
- package/native/stateright/Cargo.lock +478 -0
- package/native/stateright/Cargo.toml +11 -0
- package/native/stateright/src/lib.rs +163 -0
- package/native/stateright/src/main.rs +38 -0
- package/package.json +57 -4
- package/plugins/modkh-explorer/index.mjs +3 -0
- package/plugins/modkh-explorer/plugin.json +1 -0
- package/plugins/modkh-worker/index.mjs +3 -0
- package/plugins/modkh-worker/plugin.json +1 -0
- package/skills/kiokuko-dsh/LICENSE +21 -0
- package/skills/kiokuko-dsh/coding-ideal-routine-skill/SKILL.md +106 -0
- package/skills/kiokuko-dsh/japanese-translation-for-oss-models/SKILL.md +65 -0
- package/skills/kiokuko-dsh/kiokuko-architecture/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-architecture/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-benchmark/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-benchmark/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-investigate/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-investigate/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-lisp/SKILL.md +390 -0
- package/skills/kiokuko-dsh/kiokuko-review/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-review/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-simple-work/SKILL.md +70 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/SKILL.md +79 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/boundaries-and-ownership.md +52 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/domain-and-types.md +48 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/effects-and-data.md +43 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/kiokuko-patterns.md +314 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/problem-shaping-and-language.md +90 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/protocols-and-idempotency.md +42 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/review-checklist.md +92 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/verification.md +45 -0
- package/skills/kiokuko-dsh/kiokuko-skill-authoring/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-skill-authoring/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-soul/SKILL.md +25 -0
- package/skills/kiokuko-dsh/kiokuko-technical-writing/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-technical-writing/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/SKILL.md +64 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/accessibility-and-navigation.md +31 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/async-recovery.md +49 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/forms-and-controls.md +35 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/interaction-feedback.md +34 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/responsive-and-platform.md +38 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/safety-and-review.md +43 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/ui-checklist.md +75 -0
- package/skills/kiokuko-dsh/kiokuko-verification/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-verification/references/cases.md +11 -0
- package/skills/kiokuko-dsh/manifest.json +168 -0
- package/skills/kiokuko-dsh/memory-reasoning/SKILL.md +44 -0
- package/skills/kiokuko-dsh/one-shot-software-completion/SKILL.md +113 -0
- package/skills/kiokuko-dsh/one-shot-software-completion/references/boundaries-and-lifecycle.md +70 -0
- package/skills/kiokuko-dsh/one-shot-software-completion/references/discovery-and-scope.md +71 -0
- package/skills/kiokuko-dsh/one-shot-software-completion/references/failure-recovery.md +43 -0
- package/skills/kiokuko-dsh/one-shot-software-completion/references/verification-and-completion.md +73 -0
- package/skills/kiokuko-dsh/veteran-programmer-skill/SKILL.md +66 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Session, SessionStore } from '../session/store.ts';
|
|
2
|
+
import type { LiteConfig } from './config.ts';
|
|
3
|
+
export declare function selectInitialConnection(args: Readonly<Record<string, string | undefined>>, config: Pick<LiteConfig, 'model' | 'modelBaseUrl'>, session?: Pick<Session, 'model' | 'modelBaseUrl'>): {
|
|
4
|
+
model: string | undefined;
|
|
5
|
+
baseUrl: string | undefined;
|
|
6
|
+
};
|
|
7
|
+
export declare function loadResumedSession(store: SessionStore, id: string, cwd: string): Session;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
export function selectInitialConnection(args, config, session) {
|
|
3
|
+
const savedModel = typeof config.model === 'string' ? config.model : undefined;
|
|
4
|
+
const savedUrl = typeof config.modelBaseUrl === 'string' && config.modelBaseUrl.length > 0
|
|
5
|
+
? config.modelBaseUrl : undefined;
|
|
6
|
+
const resumedModel = session?.model === 'unconnected' ? undefined : session?.model;
|
|
7
|
+
const explicitModel = args.model;
|
|
8
|
+
const model = explicitModel ?? resumedModel ?? savedModel;
|
|
9
|
+
const baseUrl = args['base-url'] ?? (resumedModel && !explicitModel
|
|
10
|
+
? session?.modelBaseUrl ?? (resumedModel === savedModel ? savedUrl : undefined)
|
|
11
|
+
: !explicitModel || explicitModel === savedModel ? savedUrl : undefined);
|
|
12
|
+
return { model, baseUrl };
|
|
13
|
+
}
|
|
14
|
+
export function loadResumedSession(store, id, cwd) {
|
|
15
|
+
const session = store.load(id);
|
|
16
|
+
if (realpathSync(session.cwd) !== realpathSync(cwd)) {
|
|
17
|
+
throw new Error(`セッションの作業ルートが異なる: ${session.cwd} → ${cwd}。元のルートで再開するか新規セッションを使う`);
|
|
18
|
+
}
|
|
19
|
+
return session;
|
|
20
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider API keys entered at /connect. Kept in the MODKH config directory with mode 0600 and
|
|
3
|
+
* never written to a session log or echoed back by a command. Environment variables still win,
|
|
4
|
+
* so an exported key is not silently overridden by a stale saved one.
|
|
5
|
+
*/
|
|
6
|
+
export type SavedKeys = Record<string, string>;
|
|
7
|
+
/**
|
|
8
|
+
* 1つのキーで複数の接続先を使うプロバイダー。OpenCode Zen と Go は同じ
|
|
9
|
+
* OPENCODE_API_KEY を共有するため、保存名を代表名へ寄せて片方の入力で両方を使えるようにする。
|
|
10
|
+
*/
|
|
11
|
+
export declare const KEY_ALIASES: Readonly<Record<string, string>>;
|
|
12
|
+
/** キーの保存・解決に使う代表名。別名なら代表名を返す。 */
|
|
13
|
+
export declare function canonicalKeyProvider(provider: string): string;
|
|
14
|
+
export declare function keysPath(): string;
|
|
15
|
+
/** A malformed or unreadable file is treated as empty rather than granting a partial identity. */
|
|
16
|
+
export declare function loadSavedKeys(): SavedKeys;
|
|
17
|
+
export declare function saveKey(provider: string, key: string): {
|
|
18
|
+
provider: string;
|
|
19
|
+
path: string;
|
|
20
|
+
};
|
|
21
|
+
export declare function removeKey(provider: string): boolean;
|
|
22
|
+
/** Names only; callers must never print the secret itself. */
|
|
23
|
+
export declare function savedKeyProviders(): string[];
|
|
24
|
+
/**
|
|
25
|
+
* Environment first, then the saved key. An empty environment value is ignored.
|
|
26
|
+
* Aliased providers resolve through the representative name, so one saved key serves every
|
|
27
|
+
* endpoint of the same account (OpenCode Zen and Go) whether it is exported or stored.
|
|
28
|
+
*/
|
|
29
|
+
export declare function resolveApiKey(provider: string, env?: NodeJS.ProcessEnv, envName?: string | null): string | undefined;
|
package/dist/cli/keys.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { configDir } from "./config.js";
|
|
4
|
+
const PROVIDER_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
|
|
5
|
+
const MAX_KEY_LENGTH = 4096;
|
|
6
|
+
/**
|
|
7
|
+
* 1つのキーで複数の接続先を使うプロバイダー。OpenCode Zen と Go は同じ
|
|
8
|
+
* OPENCODE_API_KEY を共有するため、保存名を代表名へ寄せて片方の入力で両方を使えるようにする。
|
|
9
|
+
*/
|
|
10
|
+
export const KEY_ALIASES = {
|
|
11
|
+
'opencode-go': 'opencode',
|
|
12
|
+
};
|
|
13
|
+
/** キーの保存・解決に使う代表名。別名なら代表名を返す。 */
|
|
14
|
+
export function canonicalKeyProvider(provider) {
|
|
15
|
+
const name = normalizeProvider(provider);
|
|
16
|
+
return KEY_ALIASES[name] ?? name;
|
|
17
|
+
}
|
|
18
|
+
export function keysPath() {
|
|
19
|
+
return path.join(configDir(), 'keys.json');
|
|
20
|
+
}
|
|
21
|
+
/** Values are opaque; only format problems are rejected. Unknown providers are not accepted. */
|
|
22
|
+
function normalizeProvider(provider) {
|
|
23
|
+
const name = provider.trim().toLowerCase();
|
|
24
|
+
if (!PROVIDER_PATTERN.test(name))
|
|
25
|
+
throw new Error(`プロバイダー名が不正です: ${provider}`);
|
|
26
|
+
return name;
|
|
27
|
+
}
|
|
28
|
+
function normalizeKey(key) {
|
|
29
|
+
const trimmed = key.trim();
|
|
30
|
+
if (trimmed.length === 0)
|
|
31
|
+
throw new Error('APIキーが空です');
|
|
32
|
+
if (trimmed.length > MAX_KEY_LENGTH)
|
|
33
|
+
throw new Error('APIキーが長すぎます');
|
|
34
|
+
if (/[\r\n\0]/.test(trimmed))
|
|
35
|
+
throw new Error('APIキーに改行や制御文字は使えません');
|
|
36
|
+
return trimmed;
|
|
37
|
+
}
|
|
38
|
+
/** A malformed or unreadable file is treated as empty rather than granting a partial identity. */
|
|
39
|
+
export function loadSavedKeys() {
|
|
40
|
+
try {
|
|
41
|
+
const parsed = JSON.parse(fs.readFileSync(keysPath(), 'utf8'));
|
|
42
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
43
|
+
return {};
|
|
44
|
+
const keys = {};
|
|
45
|
+
for (const [provider, value] of Object.entries(parsed)) {
|
|
46
|
+
if (!PROVIDER_PATTERN.test(provider) || typeof value !== 'string')
|
|
47
|
+
continue;
|
|
48
|
+
const key = value.trim();
|
|
49
|
+
if (key.length === 0 || key.length > MAX_KEY_LENGTH)
|
|
50
|
+
continue;
|
|
51
|
+
keys[provider] = key;
|
|
52
|
+
}
|
|
53
|
+
return keys;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return {};
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function writeKeys(keys) {
|
|
60
|
+
fs.mkdirSync(configDir(), { recursive: true });
|
|
61
|
+
const target = keysPath();
|
|
62
|
+
const temporary = `${target}.${process.pid}.tmp`;
|
|
63
|
+
// Create with 0600 from the start so the secret is never briefly world-readable.
|
|
64
|
+
fs.writeFileSync(temporary, `${JSON.stringify(keys, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
65
|
+
fs.renameSync(temporary, target);
|
|
66
|
+
fs.chmodSync(target, 0o600);
|
|
67
|
+
}
|
|
68
|
+
export function saveKey(provider, key) {
|
|
69
|
+
const name = canonicalKeyProvider(provider), value = normalizeKey(key);
|
|
70
|
+
const keys = loadSavedKeys();
|
|
71
|
+
keys[name] = value;
|
|
72
|
+
writeKeys(keys);
|
|
73
|
+
return { provider: name, path: keysPath() };
|
|
74
|
+
}
|
|
75
|
+
export function removeKey(provider) {
|
|
76
|
+
const name = canonicalKeyProvider(provider);
|
|
77
|
+
const keys = loadSavedKeys();
|
|
78
|
+
if (!(name in keys))
|
|
79
|
+
return false;
|
|
80
|
+
delete keys[name];
|
|
81
|
+
writeKeys(keys);
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
/** Names only; callers must never print the secret itself. */
|
|
85
|
+
export function savedKeyProviders() {
|
|
86
|
+
return Object.keys(loadSavedKeys()).sort();
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Environment first, then the saved key. An empty environment value is ignored.
|
|
90
|
+
* Aliased providers resolve through the representative name, so one saved key serves every
|
|
91
|
+
* endpoint of the same account (OpenCode Zen and Go) whether it is exported or stored.
|
|
92
|
+
*/
|
|
93
|
+
export function resolveApiKey(provider, env = process.env, envName) {
|
|
94
|
+
const fromEnv = envName ? env[envName]?.trim() : undefined;
|
|
95
|
+
if (fromEnv)
|
|
96
|
+
return fromEnv;
|
|
97
|
+
const saved = loadSavedKeys();
|
|
98
|
+
const name = canonicalKeyProvider(provider);
|
|
99
|
+
if (saved[name])
|
|
100
|
+
return saved[name];
|
|
101
|
+
// 別名で保存された値も代表名から解決する(同じアカウントのキーを共有する)。
|
|
102
|
+
for (const [alias, canonical] of Object.entries(KEY_ALIASES)) {
|
|
103
|
+
if (canonical === name && saved[alias])
|
|
104
|
+
return saved[alias];
|
|
105
|
+
}
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runLanguageCommand(positional: string, cwd?: string): Promise<void>;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { LANGUAGES, languageById } from "../language/catalog.js";
|
|
2
|
+
import { clearFailure, ensureInstalled, resolveServer, statusReport } from "../language/install.js";
|
|
3
|
+
import { detectedLanguages, parseLanguageSettings } from "../language/detect.js";
|
|
4
|
+
import { availableGrammars, missingGrammars } from "../language/syntax/assets.js";
|
|
5
|
+
import { verifyGrammar } from "../language/syntax/parser.js";
|
|
6
|
+
import { loadConfig } from "./config.js";
|
|
7
|
+
const USAGE = `使い方:
|
|
8
|
+
modkh language status 検出・導入状態と文法を表示
|
|
9
|
+
modkh language install [--detected] 検出した言語(またはすべて)のサーバーを導入
|
|
10
|
+
modkh language retry <id> 失敗記録を消して再試行
|
|
11
|
+
modkh language update 既存の導入を検証し直す
|
|
12
|
+
`;
|
|
13
|
+
export async function runLanguageCommand(positional, cwd = process.cwd()) {
|
|
14
|
+
const [action, ...rest] = positional.trim().split(/\s+/).filter(Boolean);
|
|
15
|
+
const settings = parseLanguageSettings(loadConfig().language);
|
|
16
|
+
if (!action || action === 'status')
|
|
17
|
+
return status(cwd, settings);
|
|
18
|
+
if (action === 'install')
|
|
19
|
+
return install(cwd, settings, rest.includes('--detected'));
|
|
20
|
+
if (action === 'retry') {
|
|
21
|
+
const id = rest[0];
|
|
22
|
+
if (!id || !languageById(id)) {
|
|
23
|
+
process.stderr.write(`言語IDが必要です。対象: ${LANGUAGES.map(l => l.id).join(', ')}\n`);
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
26
|
+
clearFailure(id);
|
|
27
|
+
process.stdout.write(`${id} の失敗記録を消しました。次の利用で再試行します。\n`);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (action === 'update')
|
|
31
|
+
return update(settings);
|
|
32
|
+
process.stderr.write(USAGE);
|
|
33
|
+
process.exit(1);
|
|
34
|
+
}
|
|
35
|
+
async function status(cwd, settings) {
|
|
36
|
+
const detected = new Set(detectedLanguages(cwd).map(language => language.id));
|
|
37
|
+
const grammarSet = new Set(availableGrammars());
|
|
38
|
+
const installed = new Map(statusReport().map(entry => [entry.id, entry]));
|
|
39
|
+
process.stdout.write('ID 検出 サーバー 文法 状態\n');
|
|
40
|
+
for (const language of LANGUAGES) {
|
|
41
|
+
const resolved = resolveServer(language, { disabled: settings.disabled.includes(language.id) });
|
|
42
|
+
const grammar = language.grammar ? (grammarSet.has(language.grammar) ? '同梱' : 'なし') : '—';
|
|
43
|
+
const entry = installed.get(language.id);
|
|
44
|
+
const detail = resolved.status === 'ready'
|
|
45
|
+
? `${entry?.version ?? '導入済み'}${settings.servers[language.id] ? '(設定)' : ''}`
|
|
46
|
+
: resolved.detail ?? '未導入';
|
|
47
|
+
process.stdout.write(`${language.id.padEnd(13)} ${(detected.has(language.id) ? 'yes' : '-').padEnd(4)} `
|
|
48
|
+
+ `${resolved.status.padEnd(14)} ${grammar.padEnd(8)} ${detail}\n`);
|
|
49
|
+
}
|
|
50
|
+
const missing = missingGrammars(LANGUAGES.map(language => language.grammar).filter((g) => Boolean(g)));
|
|
51
|
+
if (missing.length)
|
|
52
|
+
process.stdout.write(`\n文法WASM未収録(その言語は構文解析を縮退): ${missing.join(', ')}\n`);
|
|
53
|
+
if (!settings.autoInstall)
|
|
54
|
+
process.stdout.write('\n自動導入は無効(config.json の language.autoInstall)。\n');
|
|
55
|
+
}
|
|
56
|
+
async function install(cwd, settings, detectedOnly) {
|
|
57
|
+
const targets = detectedOnly ? detectedLanguages(cwd) : LANGUAGES;
|
|
58
|
+
if (targets.length === 0) {
|
|
59
|
+
process.stdout.write('対象言語を検出できませんでした。\n');
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
let failures = 0;
|
|
63
|
+
for (const language of targets) {
|
|
64
|
+
const before = resolveServer(language, { disabled: settings.disabled.includes(language.id) });
|
|
65
|
+
if (before.status === 'ready') {
|
|
66
|
+
process.stdout.write(`${language.id}: 導入済み\n`);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (before.status === 'disabled') {
|
|
70
|
+
process.stdout.write(`${language.id}: 無効\n`);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
process.stdout.write(`${language.id}: 導入中…\n`);
|
|
74
|
+
const outcome = await ensureInstalled(language, {
|
|
75
|
+
autoInstall: settings.autoInstall,
|
|
76
|
+
...(settings.servers[language.id] ? { server: settings.servers[language.id] } : {}),
|
|
77
|
+
});
|
|
78
|
+
process.stdout.write(`${language.id}: ${outcome.status === 'ready' ? '完了' : `未導入 — ${outcome.detail ?? ''}`}\n`);
|
|
79
|
+
if (outcome.status !== 'ready')
|
|
80
|
+
failures++;
|
|
81
|
+
}
|
|
82
|
+
if (failures)
|
|
83
|
+
process.exitCode = 1;
|
|
84
|
+
}
|
|
85
|
+
async function update(settings) {
|
|
86
|
+
const report = statusReport();
|
|
87
|
+
if (report.length === 0) {
|
|
88
|
+
process.stdout.write('管理下のサーバーはありません。\n');
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
for (const entry of report) {
|
|
92
|
+
const language = languageById(entry.id);
|
|
93
|
+
if (!language)
|
|
94
|
+
continue;
|
|
95
|
+
const resolved = resolveServer(language, {});
|
|
96
|
+
if (resolved.status !== 'ready') {
|
|
97
|
+
process.stdout.write(`${entry.id}: 見つかりません(retry で再導入)\n`);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const grammar = language.grammar;
|
|
101
|
+
const grammarCheck = grammar ? await verifyGrammar(grammar) : { ok: true };
|
|
102
|
+
process.stdout.write(`${entry.id}: サーバー ${resolved.installed ? '確認済み' : '設定済み'}`
|
|
103
|
+
+ `${grammar ? ` / 文法 ${grammarCheck.ok ? 'ロード成功' : `失敗 — ${'detail' in grammarCheck ? grammarCheck.detail : ''}`}` : ''}\n`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-turn tool round-trip limit.
|
|
3
|
+
*
|
|
4
|
+
* This is a safety valve against a model that loops forever, not a work budget. Long tasks
|
|
5
|
+
* legitimately need hundreds of round trips, so the default sits well above ordinary work and
|
|
6
|
+
* the configured value can be raised up to hard ceiling that still bounds a runaway loop.
|
|
7
|
+
*/
|
|
8
|
+
import { DEFAULT_MAX_TURNS } from '../agent/loop.ts';
|
|
9
|
+
export { DEFAULT_MAX_TURNS };
|
|
10
|
+
/** Highest accepted value. Beyond this a single unattended turn could run for hours. */
|
|
11
|
+
export declare const MAX_TURNS_CEILING = 10000;
|
|
12
|
+
/** Positive integers only; strings of digits are accepted because config files are hand-edited. */
|
|
13
|
+
export declare function parseMaxTurns(value: unknown): number | null;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-turn tool round-trip limit.
|
|
3
|
+
*
|
|
4
|
+
* This is a safety valve against a model that loops forever, not a work budget. Long tasks
|
|
5
|
+
* legitimately need hundreds of round trips, so the default sits well above ordinary work and
|
|
6
|
+
* the configured value can be raised up to hard ceiling that still bounds a runaway loop.
|
|
7
|
+
*/
|
|
8
|
+
import { DEFAULT_MAX_TURNS } from "../agent/loop.js";
|
|
9
|
+
export { DEFAULT_MAX_TURNS };
|
|
10
|
+
/** Highest accepted value. Beyond this a single unattended turn could run for hours. */
|
|
11
|
+
export const MAX_TURNS_CEILING = 10_000;
|
|
12
|
+
/** Positive integers only; strings of digits are accepted because config files are hand-edited. */
|
|
13
|
+
export function parseMaxTurns(value) {
|
|
14
|
+
const numeric = typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value.trim())
|
|
15
|
+
: typeof value === 'number' ? value : Number.NaN;
|
|
16
|
+
if (!Number.isSafeInteger(numeric) || numeric < 1 || numeric > MAX_TURNS_CEILING)
|
|
17
|
+
return null;
|
|
18
|
+
return numeric;
|
|
19
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** stdin から1行ずつ取得する。ターン実行中に届いた行も失わない。 */
|
|
2
|
+
export declare class LineSource {
|
|
3
|
+
private buffer;
|
|
4
|
+
private queue;
|
|
5
|
+
private closed;
|
|
6
|
+
private waiters;
|
|
7
|
+
private readonly stdin;
|
|
8
|
+
constructor(stdin?: NodeJS.ReadableStream);
|
|
9
|
+
private onData;
|
|
10
|
+
private onEnd;
|
|
11
|
+
private onError;
|
|
12
|
+
/** メニュー中のコマンドを通常入力へ戻す。 */
|
|
13
|
+
unread(line: string): void;
|
|
14
|
+
/** 次の1行。入力終端なら null。 */
|
|
15
|
+
next(signal?: AbortSignal): Promise<string | null>;
|
|
16
|
+
close(): void;
|
|
17
|
+
private wake;
|
|
18
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/** stdin から1行ずつ取得する。ターン実行中に届いた行も失わない。 */
|
|
2
|
+
export class LineSource {
|
|
3
|
+
buffer = '';
|
|
4
|
+
queue = [];
|
|
5
|
+
closed = false;
|
|
6
|
+
waiters = [];
|
|
7
|
+
stdin;
|
|
8
|
+
constructor(stdin) {
|
|
9
|
+
this.stdin = stdin ?? process.stdin;
|
|
10
|
+
this.stdin.setEncoding?.('utf8');
|
|
11
|
+
this.stdin.on('data', this.onData);
|
|
12
|
+
this.stdin.on('end', this.onEnd);
|
|
13
|
+
this.stdin.on('error', this.onError);
|
|
14
|
+
}
|
|
15
|
+
onData = (chunk) => {
|
|
16
|
+
this.buffer += chunk;
|
|
17
|
+
let at = this.buffer.indexOf('\n');
|
|
18
|
+
while (at >= 0) {
|
|
19
|
+
this.queue.push(this.buffer.slice(0, at).replace(/\r$/, ''));
|
|
20
|
+
this.buffer = this.buffer.slice(at + 1);
|
|
21
|
+
at = this.buffer.indexOf('\n');
|
|
22
|
+
}
|
|
23
|
+
this.wake();
|
|
24
|
+
};
|
|
25
|
+
onEnd = () => {
|
|
26
|
+
if (this.buffer.length > 0) {
|
|
27
|
+
this.queue.push(this.buffer.replace(/\r$/, ''));
|
|
28
|
+
this.buffer = '';
|
|
29
|
+
}
|
|
30
|
+
this.closed = true;
|
|
31
|
+
this.wake();
|
|
32
|
+
};
|
|
33
|
+
onError = () => { this.closed = true; this.wake(); };
|
|
34
|
+
/** メニュー中のコマンドを通常入力へ戻す。 */
|
|
35
|
+
unread(line) { this.queue.unshift(line); }
|
|
36
|
+
/** 次の1行。入力終端なら null。 */
|
|
37
|
+
next(signal) {
|
|
38
|
+
// Stop must not consume a queued instruction belonging to the next turn.
|
|
39
|
+
if (signal?.aborted)
|
|
40
|
+
return Promise.resolve(null);
|
|
41
|
+
const line = this.queue.shift();
|
|
42
|
+
if (line !== undefined)
|
|
43
|
+
return Promise.resolve(line);
|
|
44
|
+
if (this.closed)
|
|
45
|
+
return Promise.resolve(null);
|
|
46
|
+
return new Promise((resolve) => {
|
|
47
|
+
const finish = (value) => {
|
|
48
|
+
signal?.removeEventListener('abort', onAbort);
|
|
49
|
+
this.waiters = this.waiters.filter((waiter) => waiter !== finish);
|
|
50
|
+
resolve(value);
|
|
51
|
+
};
|
|
52
|
+
const onAbort = () => finish(null);
|
|
53
|
+
this.waiters.push(finish);
|
|
54
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
close() {
|
|
58
|
+
this.closed = true;
|
|
59
|
+
this.stdin.removeListener('data', this.onData);
|
|
60
|
+
this.stdin.removeListener('end', this.onEnd);
|
|
61
|
+
this.stdin.removeListener('error', this.onError);
|
|
62
|
+
this.stdin.pause();
|
|
63
|
+
const waiters = this.waiters;
|
|
64
|
+
this.waiters = [];
|
|
65
|
+
for (const waiter of waiters)
|
|
66
|
+
waiter(null);
|
|
67
|
+
}
|
|
68
|
+
wake() {
|
|
69
|
+
while (this.queue.length > 0 && this.waiters.length > 0) {
|
|
70
|
+
const w = this.waiters.shift();
|
|
71
|
+
w?.(this.queue.shift() ?? null);
|
|
72
|
+
}
|
|
73
|
+
if (this.closed && this.queue.length === 0) {
|
|
74
|
+
const ws = this.waiters;
|
|
75
|
+
this.waiters = [];
|
|
76
|
+
for (const w of ws)
|
|
77
|
+
w(null);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export interface ModelListResult {
|
|
2
|
+
/** 取得できたモデルID(接頭辞なし)。 */
|
|
3
|
+
ids: string[];
|
|
4
|
+
/** 表示に使う短い説明。取得できなかった場合は理由。 */
|
|
5
|
+
note?: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* 1プロバイダーのモデル一覧を取得する。
|
|
9
|
+
* 失敗しても例外にせず理由を返す。呼び出し側は「取得できなかった」と「空だった」を区別できる。
|
|
10
|
+
*/
|
|
11
|
+
export declare function fetchProviderModels(provider: string, signal: AbortSignal, env?: NodeJS.ProcessEnv): Promise<ModelListResult>;
|
|
12
|
+
/**
|
|
13
|
+
* 取得をユーザーが中断・失敗しても操作を続けられるようにする。
|
|
14
|
+
* 固定リストへは落とさない。取得できなければ空の一覧と理由を返す。
|
|
15
|
+
*/
|
|
16
|
+
export declare function providerModelChoices(provider: string, write: (text: string) => void, env?: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<ModelListResult | null>;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { modelBaseUrl } from "../model/factory.js";
|
|
2
|
+
import { providerDefinition, supportsLiveModels } from "../model/providers.js";
|
|
3
|
+
import { resolveApiKey } from "./keys.js";
|
|
4
|
+
/**
|
|
5
|
+
* モデル一覧をプロバイダーから実行時に取得する。
|
|
6
|
+
*
|
|
7
|
+
* AIプロバイダーはモデルの追加・廃止が頻繁なので、固定値の一覧はすぐ実態とずれる。
|
|
8
|
+
* 一覧は毎回取得し、キャッシュや同梱リストへのフォールバックは行わない
|
|
9
|
+
* (古いIDを選ばせるより、取得失敗をそのまま見せるほうが安全)。
|
|
10
|
+
*/
|
|
11
|
+
/** 一覧取得の待ち時間。応答が遅いプロバイダーでも操作を止めすぎない。 */
|
|
12
|
+
const MODELS_TIMEOUT_MS = 10_000;
|
|
13
|
+
/** 一覧APIの応答から配列部分を取り出す。OpenAI互換は data、Ollama 系は models を使う。 */
|
|
14
|
+
function rowsOf(body) {
|
|
15
|
+
if (Array.isArray(body))
|
|
16
|
+
return body;
|
|
17
|
+
if (!body || typeof body !== 'object')
|
|
18
|
+
return null;
|
|
19
|
+
const record = body;
|
|
20
|
+
for (const key of ['data', 'models']) {
|
|
21
|
+
const rows = record[key];
|
|
22
|
+
if (Array.isArray(rows))
|
|
23
|
+
return rows;
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
/** モデルIDとして妥当か。プロバイダーごとに許される文字が違うため緩めに検証する。 */
|
|
28
|
+
function modelId(value) {
|
|
29
|
+
if (typeof value !== 'string')
|
|
30
|
+
return null;
|
|
31
|
+
const id = value.trim();
|
|
32
|
+
if (id.length === 0 || id.length > 256)
|
|
33
|
+
return null;
|
|
34
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:/@+-]*$/.test(id))
|
|
35
|
+
return null;
|
|
36
|
+
return id;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* 1プロバイダーのモデル一覧を取得する。
|
|
40
|
+
* 失敗しても例外にせず理由を返す。呼び出し側は「取得できなかった」と「空だった」を区別できる。
|
|
41
|
+
*/
|
|
42
|
+
export async function fetchProviderModels(provider, signal, env = process.env) {
|
|
43
|
+
const definition = providerDefinition(provider);
|
|
44
|
+
if (!definition)
|
|
45
|
+
return { ids: [], note: '未知のプロバイダー' };
|
|
46
|
+
if (!supportsLiveModels(provider) || !definition.modelsPath) {
|
|
47
|
+
return { ids: [], note: '一覧APIが未定義。モデルIDを直接入力する' };
|
|
48
|
+
}
|
|
49
|
+
const base = (modelBaseUrl(provider, undefined, env) ?? definition.baseURL)?.replace(/\/$/, '');
|
|
50
|
+
if (!base)
|
|
51
|
+
return { ids: [], note: '接続先URLが未設定' };
|
|
52
|
+
const key = resolveApiKey(provider, env, definition.env);
|
|
53
|
+
if (definition.env && !key) {
|
|
54
|
+
return { ids: [], note: `環境変数 ${definition.env} が未設定` };
|
|
55
|
+
}
|
|
56
|
+
const headers = { accept: 'application/json', ...(definition.headers?.() ?? {}) };
|
|
57
|
+
if (provider === 'anthropic' && key)
|
|
58
|
+
headers['x-api-key'] = key;
|
|
59
|
+
else if (key)
|
|
60
|
+
headers.authorization = `Bearer ${key}`;
|
|
61
|
+
// Google の一覧APIはキーをクエリで受け取る。
|
|
62
|
+
const url = provider === 'google'
|
|
63
|
+
? `${base}${definition.modelsPath}?key=${encodeURIComponent(key ?? '')}`
|
|
64
|
+
: `${base}${definition.modelsPath}`;
|
|
65
|
+
try {
|
|
66
|
+
const response = await fetch(url, {
|
|
67
|
+
headers, redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(MODELS_TIMEOUT_MS)]),
|
|
68
|
+
});
|
|
69
|
+
if (!response.ok)
|
|
70
|
+
return { ids: [], note: `HTTP ${response.status}` };
|
|
71
|
+
const rows = rowsOf(await response.json());
|
|
72
|
+
if (rows === null)
|
|
73
|
+
return { ids: [], note: '応答形式が不正' };
|
|
74
|
+
const ids = [];
|
|
75
|
+
for (const row of rows) {
|
|
76
|
+
if (!row || typeof row !== 'object')
|
|
77
|
+
continue;
|
|
78
|
+
const record = row;
|
|
79
|
+
const raw = definition.idField
|
|
80
|
+
? record[definition.idField]
|
|
81
|
+
: record['id'] ?? record['slug'] ?? record['model'] ?? record['model_id'] ?? record['name'];
|
|
82
|
+
const id = modelId(raw);
|
|
83
|
+
if (id === null)
|
|
84
|
+
continue;
|
|
85
|
+
const stripped = definition.idStripPrefix && id.startsWith(definition.idStripPrefix)
|
|
86
|
+
? id.slice(definition.idStripPrefix.length) : id;
|
|
87
|
+
if (stripped.length > 0)
|
|
88
|
+
ids.push(stripped);
|
|
89
|
+
}
|
|
90
|
+
return { ids: [...new Set(ids)] };
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
const reason = error instanceof Error && error.name === 'TimeoutError' ? 'タイムアウト'
|
|
94
|
+
: error instanceof Error && error.name === 'AbortError' ? '中止'
|
|
95
|
+
: '通信エラー';
|
|
96
|
+
return { ids: [], note: reason };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* 取得をユーザーが中断・失敗しても操作を続けられるようにする。
|
|
101
|
+
* 固定リストへは落とさない。取得できなければ空の一覧と理由を返す。
|
|
102
|
+
*/
|
|
103
|
+
export async function providerModelChoices(provider, write, env = process.env, signal) {
|
|
104
|
+
const controller = new AbortController();
|
|
105
|
+
const cancel = () => controller.abort();
|
|
106
|
+
if (!signal)
|
|
107
|
+
process.on('SIGINT', cancel);
|
|
108
|
+
const activeSignal = signal ?? controller.signal;
|
|
109
|
+
write(`${provider}: モデル一覧を取得中…(Ctrl+Cで中止)\n`);
|
|
110
|
+
try {
|
|
111
|
+
const result = await fetchProviderModels(provider, activeSignal, env);
|
|
112
|
+
if (activeSignal.aborted) {
|
|
113
|
+
write(`(${provider}: 取得を中止しました。モデルIDの直接入力も使えます)\n`);
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
if (result.note) {
|
|
117
|
+
write(`(${provider}: モデル一覧を取得できませんでした: ${result.note}。モデルIDの直接入力も使えます)\n`);
|
|
118
|
+
}
|
|
119
|
+
else if (result.ids.length === 0) {
|
|
120
|
+
write(`(${provider}: 利用できるモデルが一覧にありませんでした。モデルIDの直接入力も使えます)\n`);
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
write(`${provider}: モデル一覧 ${result.ids.length}件\n`);
|
|
124
|
+
}
|
|
125
|
+
return result;
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
process.removeListener('SIGINT', cancel);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ChatTerminal } from './terminal.ts';
|
|
2
|
+
/** 一覧APIを持つプロバイダーか。chatgpt は公式Codexの一覧を使うため別扱いにする。 */
|
|
3
|
+
export declare function listsModels(provider: string): boolean;
|
|
4
|
+
export declare function selectModel(lines: ChatTerminal, query: string, current: string | null): Promise<string | null>;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { toRefs, SEARCH_ROW_VALUE, LOCAL_MODEL_REFS } from "./catalog.js";
|
|
2
|
+
import { hasModelCredentials, officialModelChoices } from "./official-models.js";
|
|
3
|
+
import { providerModelChoices } from "./model-catalog.js";
|
|
4
|
+
import { knownProviders, providerDefinition, supportsLiveModels } from "../model/providers.js";
|
|
5
|
+
import { resolveApiKey } from "./keys.js";
|
|
6
|
+
/** 一覧APIを持つプロバイダーか。chatgpt は公式Codexの一覧を使うため別扱いにする。 */
|
|
7
|
+
export function listsModels(provider) {
|
|
8
|
+
return provider === 'chatgpt' || supportsLiveModels(provider);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* `/models` の候補。固定リストは持たず、指定または接続済みのプロバイダーから毎回取得する。
|
|
12
|
+
* 取得できなければ空のまま「一覧外は直接指定」を案内する。
|
|
13
|
+
*/
|
|
14
|
+
async function liveSuggestions(provider, write, signal) {
|
|
15
|
+
if (provider === 'openai' || provider === 'chatgpt') {
|
|
16
|
+
return await officialModelChoices(provider, write, signal);
|
|
17
|
+
}
|
|
18
|
+
const result = await providerModelChoices(provider, write, process.env, signal);
|
|
19
|
+
return result === null ? null : toRefs(provider, result.ids);
|
|
20
|
+
}
|
|
21
|
+
function entries(refs, current) {
|
|
22
|
+
return refs.map(ref => ({ value: ref, label: ref, ...(ref === current ? { detail: '選択中' } : {}) }));
|
|
23
|
+
}
|
|
24
|
+
export async function selectModel(lines, query, current) {
|
|
25
|
+
const requested = query.trim().split(/[\s/]/)[0];
|
|
26
|
+
const currentProvider = current?.split('/')[0];
|
|
27
|
+
const providers = requested && listsModels(requested) ? [requested]
|
|
28
|
+
: [...knownProviders(), 'chatgpt'].filter(provider => {
|
|
29
|
+
if (!listsModels(provider))
|
|
30
|
+
return false;
|
|
31
|
+
if (provider === currentProvider)
|
|
32
|
+
return true;
|
|
33
|
+
if (provider === 'chatgpt')
|
|
34
|
+
return hasModelCredentials(provider);
|
|
35
|
+
const envName = providerDefinition(provider)?.env;
|
|
36
|
+
return Boolean(envName && resolveApiKey(provider, process.env, envName));
|
|
37
|
+
});
|
|
38
|
+
const controller = new AbortController();
|
|
39
|
+
const cancel = () => controller.abort();
|
|
40
|
+
process.on('SIGINT', cancel);
|
|
41
|
+
let fetched;
|
|
42
|
+
try {
|
|
43
|
+
const results = await Promise.all(providers.map(provider => liveSuggestions(provider, text => lines.write(text), controller.signal)));
|
|
44
|
+
if (controller.signal.aborted)
|
|
45
|
+
return null;
|
|
46
|
+
fetched = results.flatMap(refs => refs ?? []);
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
process.removeListener('SIGINT', cancel);
|
|
50
|
+
}
|
|
51
|
+
// MODKH 自身の擬似モデル(fixed)は取得元がないため、常に候補へ含める。
|
|
52
|
+
const candidates = [...new Set([...LOCAL_MODEL_REFS, ...fetched, ...(current ? [current] : [])])];
|
|
53
|
+
// The search row is pinned first in both modes so Enter never connects to an arbitrary model.
|
|
54
|
+
const searchRow = { value: SEARCH_ROW_VALUE, label: '🔍 キーワード検索', pinned: true };
|
|
55
|
+
if (lines.interactive) {
|
|
56
|
+
let keyword = query;
|
|
57
|
+
for (;;) {
|
|
58
|
+
const selected = await lines.choose('モデル候補 — 利用可否はアカウントによります', [searchRow, ...entries(candidates, current)], keyword);
|
|
59
|
+
if (selected !== SEARCH_ROW_VALUE)
|
|
60
|
+
return selected;
|
|
61
|
+
const answer = (await lines.ask('キーワード検索(空白区切りは語順自由。例: seek deep / 空行・/cancelで戻る)'))?.trim();
|
|
62
|
+
if (!answer || answer === '/cancel') {
|
|
63
|
+
keyword = '';
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (answer.startsWith('/')) {
|
|
67
|
+
lines.unread(answer);
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
keyword = answer;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
let filter = query;
|
|
74
|
+
for (;;) {
|
|
75
|
+
const terms = filter.toLowerCase().trim().split(/\s+/).filter(Boolean);
|
|
76
|
+
const matches = candidates.filter((ref) => terms.every((term) => ref.toLowerCase().includes(term)));
|
|
77
|
+
lines.write('モデル候補 (利用可否は接続先・アカウントによります):\n');
|
|
78
|
+
matches.forEach((ref, i) => {
|
|
79
|
+
lines.write(`${i + 1}. ${ref}${ref === current ? ' (選択中)' : ''}\n`);
|
|
80
|
+
});
|
|
81
|
+
if (matches.length === 0)
|
|
82
|
+
lines.write('該当するモデルはありません。\n');
|
|
83
|
+
lines.write('番号で選択 / 文字列で再検索(語順自由: seek deep)/ * で全件 / 空行・/cancel で戻る\n一覧外: /connect <provider>/<model> [--base-url <url>]\n');
|
|
84
|
+
const answer = (await lines.next())?.trim();
|
|
85
|
+
if (!answer || answer === '/cancel')
|
|
86
|
+
return null;
|
|
87
|
+
if (answer.startsWith('/')) {
|
|
88
|
+
lines.unread(answer);
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
if (/^\d+$/.test(answer)) {
|
|
92
|
+
const selected = matches[Number(answer) - 1];
|
|
93
|
+
if (selected)
|
|
94
|
+
return selected;
|
|
95
|
+
lines.write('番号が範囲外です。\n');
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
filter = answer === '*' ? '' : answer;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|