modkh 0.1.0 → 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 +42 -0
- package/dist/agent/bundled-skills.d.ts +1 -1
- package/dist/agent/bundled-skills.js +1 -1
- package/dist/agent/compaction.d.ts +53 -0
- package/dist/agent/compaction.js +191 -0
- package/dist/agent/loop.d.ts +55 -8
- package/dist/agent/loop.js +119 -7
- package/dist/agent/skills.d.ts +7 -1
- package/dist/agent/skills.js +26 -5
- package/dist/agent/types.d.ts +14 -9
- package/dist/cli/agenticreplay.d.ts +1 -0
- package/dist/cli/agenticreplay.js +66 -0
- package/dist/cli/answer-markdown.d.ts +3 -0
- package/dist/cli/answer-markdown.js +29 -0
- package/dist/cli/approval.d.ts +2 -0
- package/dist/cli/approval.js +35 -5
- package/dist/cli/catalog.d.ts +30 -32
- package/dist/cli/catalog.js +37 -67
- package/dist/cli/chat.js +406 -78
- package/dist/cli/clipboard.d.ts +2 -0
- package/dist/cli/clipboard.js +28 -0
- package/dist/cli/color.d.ts +20 -3
- package/dist/cli/color.js +87 -19
- 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 +9 -0
- package/dist/cli/config.js +5 -1
- package/dist/cli/editor.d.ts +7 -0
- package/dist/cli/editor.js +43 -5
- 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 +12 -1
- package/dist/cli/keys.js +29 -4
- package/dist/cli/model-catalog.d.ts +16 -0
- package/dist/cli/model-catalog.js +130 -0
- package/dist/cli/models.d.ts +2 -2
- package/dist/cli/models.js +51 -19
- 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/providers.d.ts +6 -42
- package/dist/cli/providers.js +44 -38
- 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 +95 -7
- package/dist/cli/terminal.js +783 -108
- 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 +9 -16
- package/dist/cli/usage.js +60 -18
- 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.js +30 -8
- package/dist/language/commonlisp-install.d.ts +1 -0
- package/dist/language/commonlisp-install.js +3 -2
- package/dist/language/lsp/client.js +4 -1
- package/dist/language/lsp/pool.d.ts +8 -0
- package/dist/language/lsp/pool.js +21 -3
- package/dist/language/lsp/service.d.ts +8 -4
- package/dist/language/lsp/service.js +51 -15
- package/dist/language/syntax/parser.d.ts +10 -1
- package/dist/language/syntax/parser.js +34 -16
- package/dist/lisp/builtin-agents.d.ts +5 -0
- package/dist/lisp/builtin-agents.js +52 -0
- package/dist/lisp/config.d.ts +9 -0
- package/dist/lisp/config.js +50 -7
- package/dist/lisp/routing.js +2 -2
- package/dist/lisp/runtime.d.ts +5 -0
- package/dist/lisp/runtime.js +26 -2
- package/dist/model/ai-sdk.js +13 -8
- package/dist/model/chatgpt/login.js +1 -1
- package/dist/model/chatgpt/responses.js +56 -4
- package/dist/model/connection.js +2 -0
- package/dist/model/context-window.d.ts +3 -0
- package/dist/model/context-window.js +64 -0
- package/dist/model/context.d.ts +3 -1
- package/dist/model/context.js +24 -24
- package/dist/model/factory.d.ts +3 -1
- package/dist/model/factory.js +28 -27
- 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 +3 -3
- package/dist/model/reasoning.js +30 -8
- package/dist/model/record-fetch.d.ts +2 -0
- package/dist/model/record-fetch.js +19 -0
- package/dist/plugins/manager.d.ts +2 -1
- package/dist/plugins/manager.js +21 -2
- package/dist/session/store.d.ts +11 -0
- package/dist/session/store.js +27 -1
- 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/request.js +18 -1
- package/dist/subagents/service.d.ts +36 -2
- package/dist/subagents/service.js +331 -38
- package/dist/subagents/types.d.ts +20 -0
- package/dist/subagents/verification.d.ts +5 -2
- package/dist/subagents/verification.js +59 -22
- 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/formal-input.d.ts +6 -0
- package/dist/tools/formal-input.js +29 -0
- package/dist/tools/formal.d.ts +3 -2
- package/dist/tools/formal.js +54 -52
- package/dist/tools/jobs.d.ts +2 -0
- package/dist/tools/jobs.js +5 -0
- package/dist/tools/language.js +25 -27
- package/dist/tools/lean-proof.d.ts +38 -0
- package/dist/tools/lean-proof.js +83 -0
- package/dist/tools/registry.d.ts +5 -3
- package/dist/tools/registry.js +13 -5
- package/dist/tools/run.js +13 -9
- package/dist/tools/shell-process.js +17 -6
- 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.js +7 -2
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/docs/commonlisp-build-output.md +14 -0
- package/docs/context-efficiency.md +25 -3
- package/docs/input.md +63 -3
- package/docs/languages.md +3 -3
- package/docs/models.md +30 -6
- package/docs/modkh.md +11 -7
- package/docs/presets.md +45 -0
- package/docs/setup.md +3 -16
- package/docs/stateright.md +45 -0
- package/docs/subagents.md +21 -3
- package/docs/web.md +1 -1
- package/experiments/presets/formal.lisp +15 -4
- package/experiments/presets/language-microagents.lisp +29 -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 +10 -2
package/dist/cli/models.js
CHANGED
|
@@ -1,28 +1,61 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
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
|
+
}
|
|
4
21
|
function entries(refs, current) {
|
|
5
|
-
return refs.map(ref => {
|
|
6
|
-
const detail = [
|
|
7
|
-
isRecommended(ref) ? 'おすすめ' : '',
|
|
8
|
-
ref === current ? '選択中' : '',
|
|
9
|
-
noteFor(ref) ?? '',
|
|
10
|
-
].filter(Boolean).join(' · ');
|
|
11
|
-
return { value: ref, label: ref, ...(detail ? { detail } : {}) };
|
|
12
|
-
});
|
|
22
|
+
return refs.map(ref => ({ value: ref, label: ref, ...(ref === current ? { detail: '選択中' } : {}) }));
|
|
13
23
|
}
|
|
14
24
|
export async function selectModel(lines, query, current) {
|
|
15
|
-
const
|
|
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] : [])])];
|
|
16
53
|
// The search row is pinned first in both modes so Enter never connects to an arbitrary model.
|
|
17
54
|
const searchRow = { value: SEARCH_ROW_VALUE, label: '🔍 キーワード検索', pinned: true };
|
|
18
55
|
if (lines.interactive) {
|
|
19
|
-
const provider = query.trim().split(/\s+/)[0];
|
|
20
|
-
const providerList = provider && !provider.includes('/') && /^[a-z][a-z0-9-]*$/.test(provider)
|
|
21
|
-
? suggestionsFor(provider, current) : [];
|
|
22
|
-
const ordered = [...new Set([...providerList, ...candidates])];
|
|
23
56
|
let keyword = query;
|
|
24
57
|
for (;;) {
|
|
25
|
-
const selected = await lines.choose('モデル候補 — 利用可否はアカウントによります', [searchRow, ...entries(
|
|
58
|
+
const selected = await lines.choose('モデル候補 — 利用可否はアカウントによります', [searchRow, ...entries(candidates, current)], keyword);
|
|
26
59
|
if (selected !== SEARCH_ROW_VALUE)
|
|
27
60
|
return selected;
|
|
28
61
|
const answer = (await lines.ask('キーワード検索(空白区切りは語順自由。例: seek deep / 空行・/cancelで戻る)'))?.trim();
|
|
@@ -43,8 +76,7 @@ export async function selectModel(lines, query, current) {
|
|
|
43
76
|
const matches = candidates.filter((ref) => terms.every((term) => ref.toLowerCase().includes(term)));
|
|
44
77
|
lines.write('モデル候補 (利用可否は接続先・アカウントによります):\n');
|
|
45
78
|
matches.forEach((ref, i) => {
|
|
46
|
-
|
|
47
|
-
lines.write(`${i + 1}. ${ref}${note ? ` ${note}` : ''}${ref === current ? ' (選択中)' : ''}\n`);
|
|
79
|
+
lines.write(`${i + 1}. ${ref}${ref === current ? ' (選択中)' : ''}\n`);
|
|
48
80
|
});
|
|
49
81
|
if (matches.length === 0)
|
|
50
82
|
lines.write('該当するモデルはありません。\n');
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type OfficialProvider = 'openai' | 'chatgpt';
|
|
2
|
+
export declare function hasModelCredentials(provider: OfficialProvider): boolean;
|
|
3
|
+
/** Fetch afresh for each picker; never substitute a baked-in list or persist account entitlements. */
|
|
4
|
+
export declare function fetchOfficialModels(provider: OfficialProvider, signal: AbortSignal): Promise<string[]>;
|
|
5
|
+
/** Own cancellation and diagnostics, keeping failed retrieval distinct from an empty catalogue. */
|
|
6
|
+
export declare function officialModelChoices(provider: OfficialProvider, write: (text: string) => void, signal?: AbortSignal): Promise<string[] | null>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { currentChatGptTokens } from "../model/chatgpt/login.js";
|
|
2
|
+
import { loadChatGptTokens } from "../model/chatgpt/tokens.js";
|
|
3
|
+
import { resolveApiKey } from "./keys.js";
|
|
4
|
+
// Codex catalogue protocol compatibility, not the MoDKH application version.
|
|
5
|
+
// https://github.com/openai/codex/releases/tag/rust-v0.169.0
|
|
6
|
+
const CODEX_CATALOG_VERSION = '0.169.0';
|
|
7
|
+
export function hasModelCredentials(provider) {
|
|
8
|
+
return provider === 'chatgpt' ? loadChatGptTokens() !== null
|
|
9
|
+
: Boolean(resolveApiKey('openai', process.env, 'OPENAI_API_KEY'));
|
|
10
|
+
}
|
|
11
|
+
/** Fetch afresh for each picker; never substitute a baked-in list or persist account entitlements. */
|
|
12
|
+
export async function fetchOfficialModels(provider, signal) {
|
|
13
|
+
const headers = { accept: 'application/json' };
|
|
14
|
+
let endpoint;
|
|
15
|
+
if (provider === 'chatgpt') {
|
|
16
|
+
const tokens = await currentChatGptTokens(signal);
|
|
17
|
+
headers.authorization = `Bearer ${tokens.accessToken}`;
|
|
18
|
+
if (tokens.accountId)
|
|
19
|
+
headers['ChatGPT-Account-Id'] = tokens.accountId;
|
|
20
|
+
endpoint = `https://chatgpt.com/backend-api/codex/models?client_version=${CODEX_CATALOG_VERSION}`;
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
const key = resolveApiKey('openai', process.env, 'OPENAI_API_KEY');
|
|
24
|
+
if (!key)
|
|
25
|
+
throw new Error('OPENAI_API_KEY が未設定です。/connect openai で認証してください');
|
|
26
|
+
headers.authorization = `Bearer ${key}`;
|
|
27
|
+
endpoint = 'https://api.openai.com/v1/models';
|
|
28
|
+
}
|
|
29
|
+
const response = await fetch(endpoint, { headers, signal, redirect: 'error' });
|
|
30
|
+
if (!response.ok)
|
|
31
|
+
throw new Error(`公式モデル一覧の取得に失敗しました: HTTP ${response.status}`);
|
|
32
|
+
const body = await response.json();
|
|
33
|
+
const rows = body && typeof body === 'object'
|
|
34
|
+
? body[provider === 'chatgpt' ? 'models' : 'data'] : undefined;
|
|
35
|
+
if (!Array.isArray(rows))
|
|
36
|
+
throw new Error('公式モデル一覧の応答形式が不正です');
|
|
37
|
+
const ids = [];
|
|
38
|
+
for (const row of rows) {
|
|
39
|
+
if (!row || typeof row !== 'object')
|
|
40
|
+
throw new Error('公式モデル一覧のモデル形式が不正です');
|
|
41
|
+
const id = row[provider === 'chatgpt' ? 'slug' : 'id'];
|
|
42
|
+
if (typeof id !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$/.test(id)) {
|
|
43
|
+
throw new Error('公式モデル一覧のモデルIDが不正です');
|
|
44
|
+
}
|
|
45
|
+
if (provider === 'chatgpt' && row.visibility !== 'list')
|
|
46
|
+
continue;
|
|
47
|
+
ids.push(`${provider}/${id}`);
|
|
48
|
+
}
|
|
49
|
+
return [...new Set(ids)];
|
|
50
|
+
}
|
|
51
|
+
/** Own cancellation and diagnostics, keeping failed retrieval distinct from an empty catalogue. */
|
|
52
|
+
export async function officialModelChoices(provider, write, signal) {
|
|
53
|
+
const controller = new AbortController();
|
|
54
|
+
const cancel = () => controller.abort();
|
|
55
|
+
if (!signal)
|
|
56
|
+
process.on('SIGINT', cancel);
|
|
57
|
+
const activeSignal = signal ?? controller.signal;
|
|
58
|
+
write(`${provider}: 公式モデル一覧を取得中…(Ctrl+Cで中止)\n`);
|
|
59
|
+
try {
|
|
60
|
+
const models = await fetchOfficialModels(provider, AbortSignal.any([activeSignal, AbortSignal.timeout(10_000)]));
|
|
61
|
+
write(`${provider}: 公式モデル一覧 ${models.length}件\n`);
|
|
62
|
+
return models;
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
const message = activeSignal.aborted ? '取得を中止しました'
|
|
66
|
+
: error instanceof Error && error.name === 'TimeoutError' ? '取得がタイムアウトしました'
|
|
67
|
+
: error instanceof Error && error.message.startsWith('公式モデル一覧') ? error.message
|
|
68
|
+
: hasModelCredentials(provider) ? '公式モデル一覧を取得できませんでした。通信と認証を確認してください'
|
|
69
|
+
: provider === 'openai' ? 'OPENAI_API_KEY が未設定です。/connect openai から接続してください'
|
|
70
|
+
: 'ChatGPT認証が必要です。/connect chatgpt から接続してください';
|
|
71
|
+
write(`(${provider}: ${message}。一覧を開き直すと再取得します。モデルIDの直接入力も使えます)\n`);
|
|
72
|
+
return activeSignal.aborted ? null : [];
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
process.removeListener('SIGINT', cancel);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type ImageAttachment } from '../agent/images.ts';
|
|
2
|
+
export declare const pdfUsage = "/pdf [--pages 2-4] @<PDF\u306E\u30D1\u30B9> [| <\u4F9D\u983C\u6587>]";
|
|
3
|
+
export declare function isPdfPathPrefix(text: string): boolean;
|
|
4
|
+
export declare function readPdfRequest(root: string, line: string, signal: AbortSignal, availableImages: number): Promise<{
|
|
5
|
+
prompt: string;
|
|
6
|
+
text: string;
|
|
7
|
+
images: ImageAttachment[];
|
|
8
|
+
}>;
|
package/dist/cli/pdf.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
import { assertRealInRoot, resolveInRoot } from "../tools/guard.js";
|
|
5
|
+
import { MAX_IMAGES, MAX_IMAGE_BYTES, parseImage } from "../agent/images.js";
|
|
6
|
+
const run = promisify(execFile);
|
|
7
|
+
export const pdfUsage = '/pdf [--pages 2-4] @<PDFのパス> [| <依頼文>]';
|
|
8
|
+
const pdfPrefix = /^\/pdf[ \t]+(?:--pages[ \t]+(\d+)(?:-(\d+))?[ \t]+)?/;
|
|
9
|
+
export function isPdfPathPrefix(text) {
|
|
10
|
+
return pdfPrefix.exec(text.trimStart())?.[0] === text.trimStart() && !text.includes('\n');
|
|
11
|
+
}
|
|
12
|
+
function parsePdfRequest(line) {
|
|
13
|
+
const prefix = pdfPrefix.exec(line);
|
|
14
|
+
if (!prefix)
|
|
15
|
+
throw new Error(pdfUsage);
|
|
16
|
+
const args = line.slice(prefix[0].length);
|
|
17
|
+
const mention = /^@("(?:[^"\\\r\n]|\\["\\])*"|[^\s"|]+)\s*(?:\|(.+))?$/.exec(args);
|
|
18
|
+
if (mention) {
|
|
19
|
+
const filename = mention[1].startsWith('"') ? JSON.parse(mention[1]) : mention[1];
|
|
20
|
+
if (!filename.trim() || (mention[2] !== undefined && !mention[2].trim()))
|
|
21
|
+
throw new Error(pdfUsage);
|
|
22
|
+
return { filename, prompt: mention[2]?.trim() ?? 'このPDFの内容を要約してください。', start: prefix[1], end: prefix[2] };
|
|
23
|
+
}
|
|
24
|
+
const legacy = /^([^|]+)\|(.+)$/.exec(args);
|
|
25
|
+
if (args.startsWith('@') || !legacy?.[1].trim() || !legacy[2].trim())
|
|
26
|
+
throw new Error(pdfUsage);
|
|
27
|
+
return { filename: legacy[1].trim(), prompt: legacy[2].trim(), start: prefix[1], end: prefix[2] };
|
|
28
|
+
}
|
|
29
|
+
async function poppler(command, args, maxBuffer, signal) {
|
|
30
|
+
try {
|
|
31
|
+
const { stdout } = await run(command, args, {
|
|
32
|
+
encoding: 'buffer', env: { ...process.env, LC_ALL: 'C' }, maxBuffer, signal, timeout: 15000,
|
|
33
|
+
});
|
|
34
|
+
return stdout;
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error.code === 'ENOENT')
|
|
38
|
+
throw new Error(`Poppler の ${command} が必要です`);
|
|
39
|
+
if (error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
|
|
40
|
+
throw new Error('ページの変換結果が大きすぎます');
|
|
41
|
+
}
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export async function readPdfRequest(root, line, signal, availableImages) {
|
|
46
|
+
const { filename, prompt, start, end } = parsePdfRequest(line);
|
|
47
|
+
const file = resolveInRoot(root, filename);
|
|
48
|
+
assertRealInRoot(root, file);
|
|
49
|
+
const stat = await fs.stat(file);
|
|
50
|
+
if (!stat.isFile() || stat.size > 32 * 1024 * 1024)
|
|
51
|
+
throw new Error('32 MiB以内のPDFファイルを指定してください');
|
|
52
|
+
const info = await poppler('pdfinfo', [file], 1024 * 1024, signal);
|
|
53
|
+
const pages = Number(/^Pages:\s+(\d+)\s*$/m.exec(info.toString())?.[1]);
|
|
54
|
+
if (!Number.isSafeInteger(pages) || pages < 1)
|
|
55
|
+
throw new Error('PDFのページ数を取得できません');
|
|
56
|
+
const first = Number(start ?? 1), last = Number(end ?? start ?? pages);
|
|
57
|
+
if (first < 1 || last < first || last > pages)
|
|
58
|
+
throw new Error(`ページ範囲は1〜${pages}で指定してください`);
|
|
59
|
+
if (last - first + 1 > availableImages)
|
|
60
|
+
throw new Error(`全${pages}ページ。添付は画像と合わせて最大${MAX_IMAGES}枚です。--pages で範囲を指定してください`);
|
|
61
|
+
const images = [];
|
|
62
|
+
const text = [`PDF資料: ${filename}(全${pages}ページ)`];
|
|
63
|
+
for (let page = first; page <= last; page++) {
|
|
64
|
+
const range = ['-f', String(page), '-l', String(page)];
|
|
65
|
+
const body = await poppler('pdftotext', [...range, '-layout', '-enc', 'UTF-8', file, '-'], 32 * 1024, signal);
|
|
66
|
+
const png = await poppler('pdftoppm', [...range, '-singlefile', '-scale-to', '1600', '-png', file], MAX_IMAGE_BYTES, signal);
|
|
67
|
+
images.push(parseImage({ mediaType: 'image/png', data: png.toString('base64') }));
|
|
68
|
+
text.push(`ページ ${page}\n${body.toString().trim() || '(テキスト層なし。添付画像を参照)'}`);
|
|
69
|
+
}
|
|
70
|
+
return { prompt, text: text.join('\n\n'), images };
|
|
71
|
+
}
|
package/dist/cli/providers.d.ts
CHANGED
|
@@ -1,46 +1,10 @@
|
|
|
1
1
|
import type { ChatTerminal } from './terminal.ts';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
readonly label: "OpenAI";
|
|
5
|
-
readonly detail: "ChatGPT OAuth (chatgpt) / OPENAI_API_KEY";
|
|
6
|
-
readonly key: "OPENAI_API_KEY";
|
|
7
|
-
}, {
|
|
8
|
-
readonly value: "opencode";
|
|
9
|
-
readonly label: "OpenCode";
|
|
10
|
-
readonly detail: "Console · OPENCODE_API_KEY";
|
|
11
|
-
readonly key: "OPENCODE_API_KEY";
|
|
12
|
-
}, {
|
|
13
|
-
readonly value: "ollama";
|
|
14
|
-
readonly label: "Ollama Local";
|
|
15
|
-
readonly detail: "ローカル · OLLAMA_BASE_URL";
|
|
16
|
-
readonly key: null;
|
|
17
|
-
}, {
|
|
18
|
-
readonly value: "ollama-cloud";
|
|
19
|
-
readonly label: "Ollama Cloud";
|
|
20
|
-
readonly detail: "ollama.com · OLLAMA_API_KEY";
|
|
21
|
-
readonly key: "OLLAMA_API_KEY";
|
|
22
|
-
}, {
|
|
23
|
-
readonly value: "openrouter";
|
|
24
|
-
readonly label: "OpenRouter";
|
|
25
|
-
readonly detail: "OPENROUTER_API_KEY";
|
|
26
|
-
readonly key: "OPENROUTER_API_KEY";
|
|
27
|
-
}, {
|
|
28
|
-
readonly value: "infron";
|
|
29
|
-
readonly label: "Infron";
|
|
30
|
-
readonly detail: "INFRON_API_KEY";
|
|
31
|
-
readonly key: "INFRON_API_KEY";
|
|
32
|
-
}, {
|
|
33
|
-
readonly value: "hermes";
|
|
34
|
-
readonly label: "Hermes Agent";
|
|
35
|
-
readonly detail: "API server · HERMES_API_KEY";
|
|
36
|
-
readonly key: "HERMES_API_KEY";
|
|
37
|
-
}, {
|
|
38
|
-
readonly value: "brave-search";
|
|
39
|
-
readonly label: "Brave Search";
|
|
40
|
-
readonly detail: "web_search 用のキー · BRAVE_SEARCH_API_KEY";
|
|
41
|
-
readonly key: "BRAVE_SEARCH_API_KEY";
|
|
42
|
-
readonly keyOnly: true;
|
|
43
|
-
}];
|
|
2
|
+
import { modelProviders, CONNECT_PROVIDERS } from './catalog.ts';
|
|
3
|
+
export { CONNECT_PROVIDERS, modelProviders };
|
|
44
4
|
export declare function chooseProvider(ui: ChatTerminal, current: string | null): Promise<string | null>;
|
|
45
5
|
export declare function confirmRemoteAgent(ui: ChatTerminal): Promise<boolean>;
|
|
6
|
+
/**
|
|
7
|
+
* プロバイダーのモデルを選ぶ。一覧は開くたびにプロバイダーから取得し、固定値は使わない。
|
|
8
|
+
* 取得できなくても「モデルIDを直接入力」で先へ進める。
|
|
9
|
+
*/
|
|
46
10
|
export declare function chooseProviderModel(ui: ChatTerminal, provider: string): Promise<string | null>;
|
package/dist/cli/providers.js
CHANGED
|
@@ -1,18 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
{ value: 'ollama-cloud', label: 'Ollama Cloud', detail: 'ollama.com · OLLAMA_API_KEY', key: 'OLLAMA_API_KEY' },
|
|
7
|
-
{ value: 'openrouter', label: 'OpenRouter', detail: 'OPENROUTER_API_KEY', key: 'OPENROUTER_API_KEY' },
|
|
8
|
-
{ value: 'infron', label: 'Infron', detail: 'INFRON_API_KEY', key: 'INFRON_API_KEY' },
|
|
9
|
-
{ value: 'hermes', label: 'Hermes Agent', detail: 'API server · HERMES_API_KEY', key: 'HERMES_API_KEY' },
|
|
10
|
-
// Web検索のキー登録専用。モデル接続の一覧には含めない。
|
|
11
|
-
{ value: 'brave-search', label: 'Brave Search', detail: 'web_search 用のキー · BRAVE_SEARCH_API_KEY', key: 'BRAVE_SEARCH_API_KEY', keyOnly: true },
|
|
12
|
-
];
|
|
1
|
+
import { modelProviders, toRefs, SEARCH_ROW_VALUE, CONNECT_PROVIDERS, LOCAL_MODEL_REFS } from "./catalog.js";
|
|
2
|
+
import { officialModelChoices } from "./official-models.js";
|
|
3
|
+
import { providerModelChoices } from "./model-catalog.js";
|
|
4
|
+
import { knownProviders, supportsLiveModels } from "../model/providers.js";
|
|
5
|
+
export { CONNECT_PROVIDERS, modelProviders };
|
|
13
6
|
export async function chooseProvider(ui, current) {
|
|
14
7
|
ui.write(current ? `接続中: ${current}\n` : '未接続です。\n');
|
|
15
|
-
return ui.choose('Connect an integration — 認証先',
|
|
8
|
+
return ui.choose('Connect an integration — 認証先', modelProviders().map(p => ({ ...p,
|
|
16
9
|
detail: `${current?.startsWith(`${p.value}/`) || p.value === 'openai' && current?.startsWith('chatgpt/') ? '選択中 · ' : ''}${p.detail}`,
|
|
17
10
|
})));
|
|
18
11
|
}
|
|
@@ -22,13 +15,44 @@ export async function confirmRemoteAgent(ui) {
|
|
|
22
15
|
{ value: 'connect', label: 'Hermes Agent に接続', detail: 'サーバー側の権限・設定を使用' },
|
|
23
16
|
]) === 'connect';
|
|
24
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* プロバイダーのモデルを選ぶ。一覧は開くたびにプロバイダーから取得し、固定値は使わない。
|
|
20
|
+
* 取得できなくても「モデルIDを直接入力」で先へ進める。
|
|
21
|
+
*/
|
|
25
22
|
export async function chooseProviderModel(ui, provider) {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
23
|
+
let refs;
|
|
24
|
+
if (provider === 'openai' || provider === 'chatgpt') {
|
|
25
|
+
const official = await officialModelChoices(provider, text => ui.write(text));
|
|
26
|
+
if (official === null)
|
|
27
|
+
return null;
|
|
28
|
+
refs = official;
|
|
29
|
+
}
|
|
30
|
+
else if (provider === 'fixed' || provider === 'compatible') {
|
|
31
|
+
// プロバイダーが公開する一覧が無い擬似接続先。IDは直接入力してもらう。
|
|
32
|
+
refs = LOCAL_MODEL_REFS.filter(ref => ref.startsWith(`${provider}/`));
|
|
33
|
+
}
|
|
34
|
+
else if (knownProviders().includes(provider) && supportsLiveModels(provider)) {
|
|
35
|
+
const result = await providerModelChoices(provider, text => ui.write(text));
|
|
36
|
+
if (result === null)
|
|
37
|
+
return null;
|
|
38
|
+
refs = toRefs(provider, result.ids);
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
ui.write(`(${provider}: 一覧APIがないためモデルIDを入力してください)\n`);
|
|
42
|
+
refs = [];
|
|
43
|
+
}
|
|
44
|
+
const choices = refs.map(ref => ({ value: ref, label: ref }));
|
|
31
45
|
choices.push({ value: 'custom', label: 'モデルIDを直接入力', detail: '一覧にないモデル' });
|
|
46
|
+
const askManual = async () => {
|
|
47
|
+
const model = (await ui.ask('モデルID(空行・/cancelで戻る)'))?.trim();
|
|
48
|
+
if (!model || model === '/cancel')
|
|
49
|
+
return null;
|
|
50
|
+
if (model.startsWith('/')) {
|
|
51
|
+
ui.unread(model);
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
return model.startsWith(`${provider}/`) ? model : `${provider}/${model}`;
|
|
55
|
+
};
|
|
32
56
|
for (;;) {
|
|
33
57
|
// The search row is pinned first so a bare Enter never connects to an arbitrary model.
|
|
34
58
|
const selected = await ui.choose(`${provider} — モデルを選択`, [
|
|
@@ -36,16 +60,7 @@ export async function chooseProviderModel(ui, provider) {
|
|
|
36
60
|
...choices,
|
|
37
61
|
]);
|
|
38
62
|
if (selected !== SEARCH_ROW_VALUE) {
|
|
39
|
-
|
|
40
|
-
return selected;
|
|
41
|
-
const model = (await ui.ask('モデルID(空行・/cancelで戻る)'))?.trim();
|
|
42
|
-
if (!model || model === '/cancel')
|
|
43
|
-
return null;
|
|
44
|
-
if (model.startsWith('/')) {
|
|
45
|
-
ui.unread(model);
|
|
46
|
-
return null;
|
|
47
|
-
}
|
|
48
|
-
return model.startsWith(`${provider}/`) ? model : `${provider}/${model}`;
|
|
63
|
+
return selected === 'custom' ? await askManual() : selected;
|
|
49
64
|
}
|
|
50
65
|
// Choosing the row with a keyword already typed just reopens the same filtered list; an empty
|
|
51
66
|
// box asks for the keyword explicitly so the row is never a dead end.
|
|
@@ -62,15 +77,6 @@ export async function chooseProviderModel(ui, provider) {
|
|
|
62
77
|
], keyword);
|
|
63
78
|
if (reopened === SEARCH_ROW_VALUE)
|
|
64
79
|
continue;
|
|
65
|
-
|
|
66
|
-
return reopened;
|
|
67
|
-
const model = (await ui.ask('モデルID(空行・/cancelで戻る)'))?.trim();
|
|
68
|
-
if (!model || model === '/cancel')
|
|
69
|
-
return null;
|
|
70
|
-
if (model.startsWith('/')) {
|
|
71
|
-
ui.unread(model);
|
|
72
|
-
return null;
|
|
73
|
-
}
|
|
74
|
-
return model.startsWith(`${provider}/`) ? model : `${provider}/${model}`;
|
|
80
|
+
return reopened === 'custom' ? await askManual() : reopened;
|
|
75
81
|
}
|
|
76
82
|
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Display-only shell presentation. Model results and session records keep their full evidence. */
|
|
2
|
+
export declare function shellCall(args: Record<string, unknown>): string;
|
|
3
|
+
export declare function shellOutput(result: {
|
|
4
|
+
status: string;
|
|
5
|
+
output: string;
|
|
6
|
+
}): string;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Display-only shell presentation. Model results and session records keep their full evidence. */
|
|
2
|
+
export function shellCall(args) {
|
|
3
|
+
const title = typeof args.description === 'string' ? args.description.replace(/\s+/g, ' ').trim() : '';
|
|
4
|
+
const command = typeof args.command === 'string' ? args.command : '';
|
|
5
|
+
const lines = command.split('\n');
|
|
6
|
+
return `\n╭ ${title || 'コマンド実行'}\n${lines.map((line, i) => `│ ${i === 0 ? '$ ' : ' '}${line}`).join('\n')}\n`;
|
|
7
|
+
}
|
|
8
|
+
export function shellOutput(result) {
|
|
9
|
+
const lines = result.output.split('\n');
|
|
10
|
+
// Only the protocol header introduces stdout/stderr. Do not reinterpret arbitrary text
|
|
11
|
+
// from tools without a shell result (approval denial, background promotion, etc.).
|
|
12
|
+
const header = lines.findIndex(line => /^\[exit code: [^\]]+\](?: \[signal: [^\]]+\])?$/.test(line));
|
|
13
|
+
const exit = header < 0 ? undefined : lines[header].match(/^\[exit code: ([^\]]+)\](.*)$/);
|
|
14
|
+
const body = lines.filter((_line, index) => index !== header).map((line, index) => {
|
|
15
|
+
if (header >= 0 && index >= header) {
|
|
16
|
+
if (line === '--- stdout ---')
|
|
17
|
+
return null;
|
|
18
|
+
if (line === '--- stderr ---')
|
|
19
|
+
return '標準エラー';
|
|
20
|
+
}
|
|
21
|
+
return line;
|
|
22
|
+
}).filter((line) => line !== null);
|
|
23
|
+
while (body[0] === '')
|
|
24
|
+
body.shift();
|
|
25
|
+
while (body.at(-1) === '')
|
|
26
|
+
body.pop();
|
|
27
|
+
const visible = body.length > 20
|
|
28
|
+
? [...body.slice(0, 8), `… ${body.length - 20}行省略(全文はセッション記録)`, ...body.slice(-12)] : body;
|
|
29
|
+
const status = result.status === 'ok'
|
|
30
|
+
? exit ? exit[1] === '0' ? '終了' : '失敗' : '受付'
|
|
31
|
+
: result.status === 'unknown' ? '中断・結果不明'
|
|
32
|
+
: result.status === 'not-executed' ? '未実行' : '実行エラー';
|
|
33
|
+
const footer = `${status}${exit ? ` · exit ${exit[1]}${exit[2]}` : ''}`;
|
|
34
|
+
return `${visible.map(line => `│ ${line}`).join('\n')}${visible.length ? '\n' : ''}╰ ${footer}\n\n`;
|
|
35
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runStaterightCommand(action: string): Promise<void>;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { executeBounded } from "../lisp/runtime.js";
|
|
3
|
+
import { findStateright, staterightRoot } from "../tools/stateright-runtime.js";
|
|
4
|
+
export async function runStaterightCommand(action) {
|
|
5
|
+
if (!['install', 'status'].includes(action))
|
|
6
|
+
throw new Error('使い方: modkh stateright install | status');
|
|
7
|
+
const root = fileURLToPath(new URL('../../', import.meta.url));
|
|
8
|
+
const controller = new AbortController();
|
|
9
|
+
const abort = () => controller.abort();
|
|
10
|
+
process.once('SIGINT', abort);
|
|
11
|
+
try {
|
|
12
|
+
if (action === 'install') {
|
|
13
|
+
process.stdout.write('Stateright検証器を構築・導入中(Rust/Cargoが必要)…\n');
|
|
14
|
+
const receipt = await executeBounded('cargo', ['install', '--locked', '--path', `${root}native/stateright`, '--root', staterightRoot(), '--force'], { cwd: root, env: process.env, inputDigest: '', timeoutMs: 600_000, maxOutputBytes: 32768, outputOverflow: 'tail', signal: controller.signal });
|
|
15
|
+
if (receipt.state !== 'exited' || receipt.exitCode !== 0 || receipt.cleanup !== 'settled')
|
|
16
|
+
throw new Error(`Stateright導入失敗: ${receipt.state}\n${receipt.stderr}`);
|
|
17
|
+
}
|
|
18
|
+
const command = findStateright();
|
|
19
|
+
if (!command) {
|
|
20
|
+
process.stdout.write('Stateright: 未導入。modkh stateright install で導入できます。\n');
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const receipt = await executeBounded(command, ['--protocol'], { cwd: root, env: process.env, inputDigest: '', timeoutMs: 5000, signal: controller.signal });
|
|
24
|
+
let info;
|
|
25
|
+
try {
|
|
26
|
+
info = JSON.parse(receipt.stdout);
|
|
27
|
+
}
|
|
28
|
+
catch { /* invalid protocol */ }
|
|
29
|
+
if (receipt.state !== 'exited' || receipt.exitCode !== 0 || receipt.cleanup !== 'settled' || info?.name !== 'modkh-stateright' || info?.schemaVersion !== 1) {
|
|
30
|
+
throw new Error('Stateright検証器のプロトコルが不正です。modkh stateright install で更新してください。');
|
|
31
|
+
}
|
|
32
|
+
process.stdout.write(`Stateright: 利用可能\n${command}\n次のmodkh起動で前鬼が自動登録されます。\n`);
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
process.removeListener('SIGINT', abort);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface ScreenPoint {
|
|
2
|
+
row: number;
|
|
3
|
+
column: number;
|
|
4
|
+
}
|
|
5
|
+
export interface MouseReport extends ScreenPoint {
|
|
6
|
+
button: number;
|
|
7
|
+
released: boolean;
|
|
8
|
+
}
|
|
9
|
+
/** Deliver mouse reports before readline can interpret them as keyboard input. */
|
|
10
|
+
export declare class TerminalMouseInput {
|
|
11
|
+
private readonly decoder;
|
|
12
|
+
private tail;
|
|
13
|
+
private timer?;
|
|
14
|
+
private readonly keyboard;
|
|
15
|
+
private readonly mouse;
|
|
16
|
+
private readonly inPaste;
|
|
17
|
+
constructor(keyboard: (text: string) => void, mouse: (event: MouseReport) => void, inPaste: () => boolean);
|
|
18
|
+
write: (chunk: Buffer | string) => void;
|
|
19
|
+
close(): void;
|
|
20
|
+
private flush;
|
|
21
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
2
|
+
const report = /\x1b\[<(\d{1,3});(\d{1,5});(\d{1,5})([Mm])/g;
|
|
3
|
+
const incomplete = /\x1b(?:\[(?:<(?:\d{0,3}(?:;\d{0,5}(?:;\d{0,5})?)?)?)?)?(?![\s\S])/;
|
|
4
|
+
/** Deliver mouse reports before readline can interpret them as keyboard input. */
|
|
5
|
+
export class TerminalMouseInput {
|
|
6
|
+
decoder = new StringDecoder('utf8');
|
|
7
|
+
tail = '';
|
|
8
|
+
timer;
|
|
9
|
+
keyboard;
|
|
10
|
+
mouse;
|
|
11
|
+
inPaste;
|
|
12
|
+
constructor(keyboard, mouse, inPaste) {
|
|
13
|
+
this.keyboard = keyboard;
|
|
14
|
+
this.mouse = mouse;
|
|
15
|
+
this.inPaste = inPaste;
|
|
16
|
+
}
|
|
17
|
+
write = (chunk) => {
|
|
18
|
+
clearTimeout(this.timer);
|
|
19
|
+
const input = this.tail + (typeof chunk === 'string' ? chunk : this.decoder.write(chunk));
|
|
20
|
+
this.tail = '';
|
|
21
|
+
let offset = 0;
|
|
22
|
+
for (const match of input.matchAll(report)) {
|
|
23
|
+
this.keyboard(input.slice(offset, match.index));
|
|
24
|
+
if (this.inPaste())
|
|
25
|
+
this.keyboard(match[0]);
|
|
26
|
+
else
|
|
27
|
+
this.mouse({ button: Number(match[1]), column: Number(match[2]), row: Number(match[3]), released: match[4] === 'm' });
|
|
28
|
+
offset = match.index + match[0].length;
|
|
29
|
+
}
|
|
30
|
+
const rest = input.slice(offset);
|
|
31
|
+
const partial = incomplete.exec(rest);
|
|
32
|
+
if (partial) {
|
|
33
|
+
this.tail = partial[0];
|
|
34
|
+
this.keyboard(rest.slice(0, partial.index));
|
|
35
|
+
// A standalone Escape is also a key. Give fragmented reports time to arrive.
|
|
36
|
+
this.timer = setTimeout(this.flush, 35).unref();
|
|
37
|
+
}
|
|
38
|
+
else
|
|
39
|
+
this.keyboard(rest);
|
|
40
|
+
};
|
|
41
|
+
close() {
|
|
42
|
+
clearTimeout(this.timer);
|
|
43
|
+
this.tail = '';
|
|
44
|
+
}
|
|
45
|
+
flush = () => {
|
|
46
|
+
const text = this.tail;
|
|
47
|
+
this.tail = '';
|
|
48
|
+
if (!text.startsWith('\x1b[<'))
|
|
49
|
+
this.keyboard(text);
|
|
50
|
+
};
|
|
51
|
+
}
|