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,185 @@
|
|
|
1
|
+
import { streamText, jsonSchema, tool, } from 'ai';
|
|
2
|
+
import { toolContext } from "./context.js";
|
|
3
|
+
import { harnessProfile, CODEX_62_DEFAULTS } from "./harness-profile.js";
|
|
4
|
+
import { reasoningProviderOptions } from "./reasoning.js";
|
|
5
|
+
import { parseImages } from "../agent/images.js";
|
|
6
|
+
function toCoreMessages(req) {
|
|
7
|
+
const out = [];
|
|
8
|
+
const outputs = toolContext(req.messages);
|
|
9
|
+
for (const [index, m] of req.messages.entries()) {
|
|
10
|
+
if (m.role === 'user') {
|
|
11
|
+
const images = parseImages(m.images);
|
|
12
|
+
out.push({ role: 'user', content: images.length ? [
|
|
13
|
+
...(m.content ? [{ type: 'text', text: m.content }] : []),
|
|
14
|
+
...images.map(image => ({ type: 'file', data: Buffer.from(image.data, 'base64'), mediaType: image.mediaType })),
|
|
15
|
+
] : m.content });
|
|
16
|
+
}
|
|
17
|
+
else if (m.role === 'assistant') {
|
|
18
|
+
const content = [];
|
|
19
|
+
if (m.content.length > 0)
|
|
20
|
+
content.push({ type: 'text', text: m.content });
|
|
21
|
+
for (const c of m.toolCalls ?? []) {
|
|
22
|
+
const part = {
|
|
23
|
+
type: 'tool-call',
|
|
24
|
+
toolCallId: c.id,
|
|
25
|
+
toolName: c.name,
|
|
26
|
+
input: c.args,
|
|
27
|
+
};
|
|
28
|
+
content.push(part);
|
|
29
|
+
}
|
|
30
|
+
out.push({ role: 'assistant', content });
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
const parts = m.results.map((r, resultIndex) => ({
|
|
34
|
+
type: 'tool-result',
|
|
35
|
+
toolCallId: r.callId,
|
|
36
|
+
toolName: r.name,
|
|
37
|
+
output: { type: 'text', value: JSON.stringify({ status: r.status, output: outputs.get(`${index}:${resultIndex}`) }) },
|
|
38
|
+
}));
|
|
39
|
+
out.push({ role: 'tool', content: parts });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
/** モデルへ渡すツール定義。execute は持たせず、実行は CLI 側で承認付きで行う。 */
|
|
45
|
+
function toAiSdkTools(specs) {
|
|
46
|
+
const out = {};
|
|
47
|
+
for (const s of specs) {
|
|
48
|
+
out[s.name] = tool({
|
|
49
|
+
description: s.description,
|
|
50
|
+
inputSchema: jsonSchema(s.parameters),
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* AI SDK (Vercel AI SDK) 経由の Model 実装。1回の stream() は1ステップ
|
|
57
|
+
* (テキスト+ツール要求まで)。ツール実行と次ステップは Agent ループが担う。
|
|
58
|
+
* 中断は abortSignal で伝え、'aborted' で静かに終わる。
|
|
59
|
+
*/
|
|
60
|
+
export class AiSdkModel {
|
|
61
|
+
id;
|
|
62
|
+
lm;
|
|
63
|
+
timeoutMs;
|
|
64
|
+
provider;
|
|
65
|
+
constructor(opts) {
|
|
66
|
+
this.id = opts.id;
|
|
67
|
+
this.lm = opts.languageModel;
|
|
68
|
+
this.provider = opts.provider;
|
|
69
|
+
this.timeoutMs = opts.timeoutMs ?? 600000;
|
|
70
|
+
if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0)
|
|
71
|
+
throw new Error('timeoutMs must be a positive integer');
|
|
72
|
+
}
|
|
73
|
+
/** 無通信タイムアウト。受信が続く限り延期され、何も来なければ締め切る。 */
|
|
74
|
+
async *stream(req, signal) {
|
|
75
|
+
let aborted = false;
|
|
76
|
+
let timedOut = false;
|
|
77
|
+
const deadline = new AbortController();
|
|
78
|
+
let timer;
|
|
79
|
+
const arm = () => { clearTimeout(timer); timer = setTimeout(() => { timedOut = true; deadline.abort(); }, this.timeoutMs); };
|
|
80
|
+
arm();
|
|
81
|
+
const requestSignal = AbortSignal.any([signal, deadline.signal]);
|
|
82
|
+
let activity;
|
|
83
|
+
let usage;
|
|
84
|
+
let errorMessage;
|
|
85
|
+
let sawToolCall = false;
|
|
86
|
+
let finishReason;
|
|
87
|
+
const defaults = harnessProfile(this.id) ? CODEX_62_DEFAULTS : undefined;
|
|
88
|
+
const reasoning = reasoningProviderOptions(this.provider ?? '', req.reasoning ?? defaults?.reasoning, this.id);
|
|
89
|
+
// Only native OpenAI Responses is known to support text.verbosity.
|
|
90
|
+
const providerOptions = defaults && this.provider === 'openai'
|
|
91
|
+
? { openai: { ...reasoning?.openai, textVerbosity: defaults.verbosity } } : reasoning;
|
|
92
|
+
const thinking = this.provider === 'anthropic' && reasoning?.anthropic !== undefined;
|
|
93
|
+
const thinkingBudget = thinking
|
|
94
|
+
? reasoning.anthropic.thinking.budgetTokens : undefined;
|
|
95
|
+
try {
|
|
96
|
+
const result = streamText({
|
|
97
|
+
model: this.lm,
|
|
98
|
+
messages: toCoreMessages(req),
|
|
99
|
+
system: req.system,
|
|
100
|
+
tools: toAiSdkTools(req.tools),
|
|
101
|
+
abortSignal: requestSignal,
|
|
102
|
+
// fullStream below owns errors; the SDK default logs entire request bodies to stderr.
|
|
103
|
+
onError: () => { },
|
|
104
|
+
maxRetries: 0, // A transport failure does not establish that the request was unsent.
|
|
105
|
+
// providerOptions の実値はすべて JSON オブジェクト。SDK型は index signature が緩いため型の詰め替え。
|
|
106
|
+
...(providerOptions ? { providerOptions: providerOptions } : {}),
|
|
107
|
+
...(thinking ? { maxOutputTokens: (thinkingBudget ?? 0) + 8192 } : {}),
|
|
108
|
+
});
|
|
109
|
+
for await (const part of result.fullStream) {
|
|
110
|
+
arm(); // 受信が継続している間は制限時間を延ばす
|
|
111
|
+
if (part.type === 'reasoning-start' || part.type === 'reasoning-delta') {
|
|
112
|
+
if (activity !== 'reasoning') {
|
|
113
|
+
activity = 'reasoning';
|
|
114
|
+
yield { type: 'activity', stage: activity };
|
|
115
|
+
}
|
|
116
|
+
if (part.type === 'reasoning-delta' && part.text.length > 0)
|
|
117
|
+
yield { type: 'reasoning-delta', text: part.text };
|
|
118
|
+
}
|
|
119
|
+
else if (part.type === 'tool-input-start') {
|
|
120
|
+
activity = 'tool-input';
|
|
121
|
+
yield { type: 'activity', stage: activity, toolName: part.toolName };
|
|
122
|
+
}
|
|
123
|
+
else if (part.type === 'text-delta') {
|
|
124
|
+
activity = undefined;
|
|
125
|
+
yield { type: 'text-delta', text: part.text };
|
|
126
|
+
}
|
|
127
|
+
else if (part.type === 'tool-call') {
|
|
128
|
+
sawToolCall = true;
|
|
129
|
+
yield {
|
|
130
|
+
type: 'tool-call',
|
|
131
|
+
call: {
|
|
132
|
+
id: part.toolCallId,
|
|
133
|
+
name: part.toolName,
|
|
134
|
+
args: (part.input ?? {}),
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
else if (part.type === 'finish') {
|
|
139
|
+
// totalUsage is the provider's own count; undefined means unreported, not zero.
|
|
140
|
+
if (part.totalUsage) {
|
|
141
|
+
usage = {
|
|
142
|
+
input: part.totalUsage.inputTokens,
|
|
143
|
+
uncachedInput: part.totalUsage.inputTokenDetails?.noCacheTokens,
|
|
144
|
+
output: part.totalUsage.outputTokens,
|
|
145
|
+
cacheRead: part.totalUsage.inputTokenDetails?.cacheReadTokens,
|
|
146
|
+
cacheWrite: part.totalUsage.inputTokenDetails?.cacheWriteTokens,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
if (part.finishReason === 'stop' || part.finishReason === 'tool-calls' || part.finishReason === 'length') {
|
|
150
|
+
finishReason = part.finishReason;
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
errorMessage = `モデル応答は未完了: ${part.finishReason}`;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
else if (part.type === 'error') {
|
|
157
|
+
errorMessage = part.error?.message ?? String(part.error);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
aborted = signal.aborted;
|
|
161
|
+
}
|
|
162
|
+
catch (e) {
|
|
163
|
+
aborted = signal.aborted;
|
|
164
|
+
if (!aborted)
|
|
165
|
+
errorMessage = e.message;
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
clearTimeout(timer);
|
|
169
|
+
}
|
|
170
|
+
if (timedOut && !signal.aborted)
|
|
171
|
+
errorMessage = `モデル応答が制限時間(${this.timeoutMs}ms)を超えるまで何も受信しませんでした。自動再送はしません。`;
|
|
172
|
+
if (usage && (usage.input !== undefined || usage.output !== undefined))
|
|
173
|
+
yield { type: 'usage', ...usage };
|
|
174
|
+
if (aborted) {
|
|
175
|
+
yield { type: 'finish', stopReason: 'aborted' };
|
|
176
|
+
}
|
|
177
|
+
else if (errorMessage !== undefined || finishReason === undefined ||
|
|
178
|
+
(finishReason !== 'length' && (finishReason === 'tool-calls') !== sawToolCall)) {
|
|
179
|
+
yield { type: 'finish', stopReason: 'error', errorMessage: errorMessage ?? 'モデル終了イベントがない、またはツール要求と終了理由が不整合' };
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
yield { type: 'finish', stopReason: finishReason };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type ChatGptTokens } from './tokens.ts';
|
|
2
|
+
export interface LoginConfig {
|
|
3
|
+
issuer: string;
|
|
4
|
+
clientId: string;
|
|
5
|
+
redirectPort: number;
|
|
6
|
+
}
|
|
7
|
+
export declare const DEFAULT_LOGIN: LoginConfig;
|
|
8
|
+
export interface PkcePair {
|
|
9
|
+
verifier: string;
|
|
10
|
+
challenge: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function createPkcePair(): PkcePair;
|
|
13
|
+
export interface AuthorizeOptions {
|
|
14
|
+
issuer: string;
|
|
15
|
+
clientId: string;
|
|
16
|
+
redirectUri: string;
|
|
17
|
+
verifier: string;
|
|
18
|
+
state: string;
|
|
19
|
+
}
|
|
20
|
+
export declare function buildAuthorizeUrl(o: AuthorizeOptions): string;
|
|
21
|
+
export type TokenResponse = ChatGptTokens;
|
|
22
|
+
export interface ExchangeOptions {
|
|
23
|
+
issuer: string;
|
|
24
|
+
clientId: string;
|
|
25
|
+
code: string;
|
|
26
|
+
verifier: string;
|
|
27
|
+
redirectUri: string;
|
|
28
|
+
fetchImpl?: typeof fetch;
|
|
29
|
+
signal?: AbortSignal;
|
|
30
|
+
}
|
|
31
|
+
export declare function exchangeCode(o: ExchangeOptions): Promise<TokenResponse>;
|
|
32
|
+
/** Refresh only before sending a new model request; never replay a failed model request. */
|
|
33
|
+
export declare function currentChatGptTokens(signal?: AbortSignal): Promise<ChatGptTokens>;
|
|
34
|
+
export interface LoginOptions {
|
|
35
|
+
config?: LoginConfig;
|
|
36
|
+
openUrl?: (url: string) => void | Promise<void>;
|
|
37
|
+
write?: (text: string) => void;
|
|
38
|
+
signal?: AbortSignal;
|
|
39
|
+
timeoutMs?: number;
|
|
40
|
+
}
|
|
41
|
+
/** Own the listener from bind through exchange/save; the browser reports success only after saving. */
|
|
42
|
+
export declare function loginChatGpt(opts?: LoginOptions): Promise<ChatGptTokens>;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { saveChatGptTokens, loadChatGptTokens } from "./tokens.js";
|
|
5
|
+
export const DEFAULT_LOGIN = {
|
|
6
|
+
issuer: 'https://auth.openai.com', clientId: 'app_EMoamEEZ73f0CkXaXp7hrann', redirectPort: 1455,
|
|
7
|
+
};
|
|
8
|
+
export function createPkcePair() {
|
|
9
|
+
const verifier = crypto.randomBytes(48).toString('base64url');
|
|
10
|
+
return { verifier, challenge: crypto.createHash('sha256').update(verifier).digest('base64url') };
|
|
11
|
+
}
|
|
12
|
+
export function buildAuthorizeUrl(o) {
|
|
13
|
+
const u = new URL('/oauth/authorize', o.issuer);
|
|
14
|
+
u.search = new URLSearchParams({ response_type: 'code', client_id: o.clientId,
|
|
15
|
+
redirect_uri: o.redirectUri, scope: 'openid profile email offline_access', state: o.state,
|
|
16
|
+
code_challenge: crypto.createHash('sha256').update(o.verifier).digest('base64url'),
|
|
17
|
+
code_challenge_method: 'S256', id_token_add_organizations: 'true', codex_cli_simplified_flow: 'true',
|
|
18
|
+
}).toString();
|
|
19
|
+
return u.toString();
|
|
20
|
+
}
|
|
21
|
+
function jwtExpiry(token) {
|
|
22
|
+
try {
|
|
23
|
+
const exp = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()).exp;
|
|
24
|
+
return typeof exp === 'number' && Number.isFinite(exp) && exp > 0 ? new Date(exp * 1000).toISOString() : undefined;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Read account routing metadata, not an authorization decision. The server validates the token. */
|
|
31
|
+
function tokenAccount(token) {
|
|
32
|
+
if (typeof token !== 'string')
|
|
33
|
+
return undefined;
|
|
34
|
+
try {
|
|
35
|
+
const body = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());
|
|
36
|
+
const account = body['https://api.openai.com/auth']?.chatgpt_account_id;
|
|
37
|
+
return typeof account === 'string' ? account : undefined;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
async function requestTokens(config, fields, signal, fetchImpl = fetch) {
|
|
44
|
+
const res = await fetchImpl(new URL('/oauth/token', config.issuer), {
|
|
45
|
+
method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
46
|
+
body: new URLSearchParams({ client_id: config.clientId, ...fields }),
|
|
47
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(30_000),
|
|
48
|
+
redirect: 'error',
|
|
49
|
+
});
|
|
50
|
+
// Never print token endpoint bodies: they may include credentials or the submitted code.
|
|
51
|
+
if (!res.ok)
|
|
52
|
+
throw new Error(`トークン交換に失敗した: HTTP ${res.status}。/connect chatgpt で再認証してください`);
|
|
53
|
+
const body = await res.json();
|
|
54
|
+
if (typeof body.access_token !== 'string' || !body.access_token)
|
|
55
|
+
throw new Error('トークン応答に access_token がない');
|
|
56
|
+
return {
|
|
57
|
+
accessToken: body.access_token,
|
|
58
|
+
refreshToken: typeof body.refresh_token === 'string' ? body.refresh_token : undefined,
|
|
59
|
+
expiresAt: typeof body.expires_in === 'number' && body.expires_in > 0
|
|
60
|
+
? new Date(Date.now() + body.expires_in * 1000).toISOString() : jwtExpiry(body.access_token),
|
|
61
|
+
accountId: typeof body.account_id === 'string' ? body.account_id
|
|
62
|
+
: tokenAccount(body.id_token) ?? tokenAccount(body.access_token),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
export function exchangeCode(o) {
|
|
66
|
+
return requestTokens(o, { grant_type: 'authorization_code', code: o.code,
|
|
67
|
+
redirect_uri: o.redirectUri, code_verifier: o.verifier }, o.signal, o.fetchImpl);
|
|
68
|
+
}
|
|
69
|
+
/** Refresh only before sending a new model request; never replay a failed model request. */
|
|
70
|
+
export async function currentChatGptTokens(signal) {
|
|
71
|
+
const tokens = loadChatGptTokens();
|
|
72
|
+
if (!tokens)
|
|
73
|
+
throw new Error('ChatGPTにログインしていない: /connect chatgpt で認証してください');
|
|
74
|
+
const expiry = tokens.expiresAt ?? jwtExpiry(tokens.accessToken);
|
|
75
|
+
if (!expiry || Date.parse(expiry) > Date.now() + 60_000)
|
|
76
|
+
return tokens;
|
|
77
|
+
if (!tokens.refreshToken)
|
|
78
|
+
throw new Error('ChatGPTの認証期限が切れています。/connect chatgpt で再認証してください');
|
|
79
|
+
const renewed = await requestTokens(DEFAULT_LOGIN, { grant_type: 'refresh_token', refresh_token: tokens.refreshToken }, signal);
|
|
80
|
+
signal?.throwIfAborted();
|
|
81
|
+
const result = { ...renewed, refreshToken: renewed.refreshToken ?? tokens.refreshToken, accountId: renewed.accountId ?? tokens.accountId };
|
|
82
|
+
saveChatGptTokens(result);
|
|
83
|
+
return result;
|
|
84
|
+
}
|
|
85
|
+
async function openBrowser(url) {
|
|
86
|
+
const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32' : 'xdg-open';
|
|
87
|
+
const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];
|
|
88
|
+
await new Promise((resolve, reject) => {
|
|
89
|
+
const child = spawn(command, args, { stdio: 'ignore' });
|
|
90
|
+
const timer = setTimeout(() => { child.kill(); reject(new Error('ブラウザ起動がタイムアウトしました')); }, 5000);
|
|
91
|
+
child.once('error', (e) => { clearTimeout(timer); reject(e); });
|
|
92
|
+
child.once('close', (code) => { clearTimeout(timer); code === 0 ? resolve() : reject(new Error('ブラウザを開けません')); });
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/** Own the listener from bind through exchange/save; the browser reports success only after saving. */
|
|
96
|
+
export async function loginChatGpt(opts = {}) {
|
|
97
|
+
const cfg = opts.config ?? DEFAULT_LOGIN;
|
|
98
|
+
const write = opts.write ?? ((text) => process.stdout.write(text));
|
|
99
|
+
const ac = new AbortController();
|
|
100
|
+
const signal = AbortSignal.any([ac.signal, ...(opts.signal ? [opts.signal] : []), AbortSignal.timeout(opts.timeoutMs ?? 300_000)]);
|
|
101
|
+
signal.throwIfAborted();
|
|
102
|
+
const onSigint = () => ac.abort(new Error('認証を中止しました'));
|
|
103
|
+
process.on('SIGINT', onSigint);
|
|
104
|
+
const { verifier } = createPkcePair();
|
|
105
|
+
const state = crypto.randomBytes(24).toString('hex');
|
|
106
|
+
let redirectUri = '';
|
|
107
|
+
let claimed = false;
|
|
108
|
+
let resolveResult;
|
|
109
|
+
let rejectResult;
|
|
110
|
+
const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject; });
|
|
111
|
+
// Attach a handler immediately; bind/browser failures can happen before the caller awaits result.
|
|
112
|
+
void result.catch(() => { });
|
|
113
|
+
const server = http.createServer((req, res) => {
|
|
114
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
115
|
+
const reply = (status, text) => {
|
|
116
|
+
res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' });
|
|
117
|
+
res.end(text);
|
|
118
|
+
};
|
|
119
|
+
if (req.method !== 'GET' || url.pathname !== '/auth/callback') {
|
|
120
|
+
reply(404, 'Not found');
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (url.searchParams.get('state') !== state) {
|
|
124
|
+
reply(400, '不正な認証stateです。元の認証画面からやり直してください。');
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (claimed) {
|
|
128
|
+
reply(409, '認証処理中です。端末を確認してください。');
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const code = url.searchParams.get('code');
|
|
132
|
+
if (url.searchParams.has('error') || !code) {
|
|
133
|
+
reply(400, '認証は完了しませんでした。MODKHで再試行してください。');
|
|
134
|
+
rejectResult(new Error('認証が拒否されたか、認可コードがありません。/connect chatgpt で再試行してください'));
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
claimed = true;
|
|
138
|
+
write('認可を受信しました。トークンを交換しています…\n');
|
|
139
|
+
void exchangeCode({ ...cfg, code, verifier, redirectUri, signal }).then((tokens) => {
|
|
140
|
+
signal.throwIfAborted();
|
|
141
|
+
saveChatGptTokens(tokens);
|
|
142
|
+
reply(200, 'MODKH: 認証情報を保存しました。このタブを閉じて端末へ戻ってください。');
|
|
143
|
+
resolveResult(tokens);
|
|
144
|
+
}).catch((error) => { reply(500, 'MODKH: 認証を保存できませんでした。端末の案内を確認してください。'); rejectResult(error); });
|
|
145
|
+
});
|
|
146
|
+
const onAbort = () => rejectResult(new Error(signal.reason?.name === 'TimeoutError'
|
|
147
|
+
? '認証がタイムアウトしました。/connect chatgpt で再試行してください' : '認証を中止しました'));
|
|
148
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
149
|
+
try {
|
|
150
|
+
await new Promise((resolve, reject) => {
|
|
151
|
+
server.once('error', reject);
|
|
152
|
+
server.listen(cfg.redirectPort, '127.0.0.1', () => { server.removeListener('error', reject); resolve(); });
|
|
153
|
+
});
|
|
154
|
+
server.on('error', rejectResult);
|
|
155
|
+
signal.throwIfAborted();
|
|
156
|
+
const port = server.address().port;
|
|
157
|
+
redirectUri = `http://127.0.0.1:${port}/auth/callback`;
|
|
158
|
+
const url = buildAuthorizeUrl({ ...cfg, redirectUri, verifier, state });
|
|
159
|
+
if (opts.openUrl)
|
|
160
|
+
await opts.openUrl(url);
|
|
161
|
+
else {
|
|
162
|
+
write(`ChatGPTのブラウザ認証を開きます。開かない場合は次のURLを使用してください:\n${url}\n待機中… Ctrl+C で中止\n`);
|
|
163
|
+
await openBrowser(url).catch(() => write('ブラウザを自動起動できませんでした。上のURLを手動で開いてください。\n'));
|
|
164
|
+
}
|
|
165
|
+
return await result;
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
if (error.code === 'EADDRINUSE') {
|
|
169
|
+
throw new Error(`認証ポート ${cfg.redirectPort} は使用中です。他のログイン処理を終了してから /connect chatgpt で再試行してください`);
|
|
170
|
+
}
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
ac.abort();
|
|
175
|
+
signal.removeEventListener('abort', onAbort);
|
|
176
|
+
process.removeListener('SIGINT', onSigint);
|
|
177
|
+
server.closeAllConnections();
|
|
178
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { AgentMessage, Model, ModelEvent, ModelRequest } from '../../agent/types.ts';
|
|
2
|
+
export declare const DEFAULT_RESPONSES_BASE_URL = "https://chatgpt.com/backend-api/codex";
|
|
3
|
+
export interface ResponsesModelOptions {
|
|
4
|
+
accessToken: string;
|
|
5
|
+
accountId?: string;
|
|
6
|
+
credentials?: (signal: AbortSignal) => Promise<{
|
|
7
|
+
accessToken: string;
|
|
8
|
+
accountId?: string;
|
|
9
|
+
}>;
|
|
10
|
+
model: string;
|
|
11
|
+
baseUrl?: string;
|
|
12
|
+
fetchImpl?: typeof fetch;
|
|
13
|
+
}
|
|
14
|
+
interface ResponsesInputItem {
|
|
15
|
+
type?: string;
|
|
16
|
+
role?: string;
|
|
17
|
+
content?: unknown;
|
|
18
|
+
call_id?: string;
|
|
19
|
+
name?: string;
|
|
20
|
+
arguments?: string;
|
|
21
|
+
output?: string;
|
|
22
|
+
}
|
|
23
|
+
/** 会話履歴(CLI 保持)を Responses API の input へ変換する。 */
|
|
24
|
+
export declare function toResponsesInput(messages: AgentMessage[]): ResponsesInputItem[];
|
|
25
|
+
/**
|
|
26
|
+
* ChatGPT Codex Responses アダプター(APIキー用の公開APIとは分離)。
|
|
27
|
+
* 会話状態は CLI 側が保持するため store:false で毎回全履歴を送る。
|
|
28
|
+
* 関数ツールは公式の名前空間契約(type:'function' のフラット形式)に合わせる。
|
|
29
|
+
*/
|
|
30
|
+
export declare class ResponsesApiModel implements Model {
|
|
31
|
+
readonly id: string;
|
|
32
|
+
private readonly accessToken;
|
|
33
|
+
private readonly accountId?;
|
|
34
|
+
private readonly credentials?;
|
|
35
|
+
private readonly model;
|
|
36
|
+
private readonly baseUrl;
|
|
37
|
+
private readonly fetchImpl;
|
|
38
|
+
constructor(opts: ResponsesModelOptions);
|
|
39
|
+
stream(req: ModelRequest, signal: AbortSignal): AsyncIterable<ModelEvent>;
|
|
40
|
+
}
|
|
41
|
+
export {};
|