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,311 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { parseImages } from "../agent/images.js";
|
|
6
|
+
import { safeBoundary } from "../agent/compaction.js";
|
|
7
|
+
import { parseDelegation, delegationDigest } from "../subagents/request.js";
|
|
8
|
+
/** 圧縮要約の保存上限。壊れた・巨大な記録で入力が膨らむのを防ぐ。 */
|
|
9
|
+
export const MAX_SUMMARY_CHARS = 20_000;
|
|
10
|
+
/** 既定の保存先。MODKH_HOME で差し替え可能(検証用)。 */
|
|
11
|
+
export function defaultSessionDir() {
|
|
12
|
+
if (process.env['MODKH_HOME']) {
|
|
13
|
+
return path.join(process.env['MODKH_HOME'], 'sessions');
|
|
14
|
+
}
|
|
15
|
+
const configBase = process.env['XDG_CONFIG_HOME'] ?? path.join(os.homedir(), '.config');
|
|
16
|
+
return path.join(configBase, 'modkh', 'sessions');
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* JSONL セッションストア。1行1イベント。append で追記し、読み込みで再構築する。
|
|
20
|
+
* ステータスはイベントとして追記し、最後のものが有効。完了と中断を区別する。
|
|
21
|
+
*/
|
|
22
|
+
export class SessionStore {
|
|
23
|
+
dir;
|
|
24
|
+
constructor(dir = defaultSessionDir()) {
|
|
25
|
+
this.dir = dir;
|
|
26
|
+
}
|
|
27
|
+
create(cwd, model, child) {
|
|
28
|
+
const createdAt = new Date().toISOString();
|
|
29
|
+
const id = child?.id ?? `${createdAt.slice(0, 10)}-${randomUUID().slice(0, 8)}`;
|
|
30
|
+
fs.mkdirSync(this.dir, { recursive: true });
|
|
31
|
+
const seq = fs.readdirSync(this.dir).filter((n) => n.endsWith('.jsonl')).length;
|
|
32
|
+
const file = this.fileOf(id);
|
|
33
|
+
const header = { type: 'session', version: 2, ...child, id, createdAt, cwd, model, seq };
|
|
34
|
+
fs.writeFileSync(file, `${JSON.stringify(header)}\n`, { encoding: 'utf8', flag: 'wx', flush: true });
|
|
35
|
+
return Session.fromText(id, file, `${JSON.stringify(header)}\n`);
|
|
36
|
+
}
|
|
37
|
+
load(id) {
|
|
38
|
+
const file = this.fileOf(id);
|
|
39
|
+
let text;
|
|
40
|
+
try {
|
|
41
|
+
text = fs.readFileSync(file, 'utf8');
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
throw new Error(`セッションが見つからない: ${id}(${file})`);
|
|
45
|
+
}
|
|
46
|
+
return Session.fromText(id, file, text);
|
|
47
|
+
}
|
|
48
|
+
list() {
|
|
49
|
+
fs.mkdirSync(this.dir, { recursive: true });
|
|
50
|
+
const out = [];
|
|
51
|
+
for (const name of fs.readdirSync(this.dir)) {
|
|
52
|
+
if (!name.endsWith('.jsonl'))
|
|
53
|
+
continue;
|
|
54
|
+
const file = path.join(this.dir, name);
|
|
55
|
+
try {
|
|
56
|
+
out.push(summarize(file, fs.readFileSync(file, 'utf8')));
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// 読めない・壊れたファイルは一覧に載せない(保存先の掃除はユーザーの判断に任せる)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
out.sort((a, b) => {
|
|
63
|
+
if (a.createdAt !== b.createdAt)
|
|
64
|
+
return a.createdAt < b.createdAt ? 1 : -1;
|
|
65
|
+
return b.seq - a.seq; // 同一時刻は作成順で決定的に
|
|
66
|
+
});
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
fileOf(id) {
|
|
70
|
+
if (!/^[A-Za-z0-9-]+$/.test(id)) {
|
|
71
|
+
throw new Error(`セッションIDが不正: ${id}`);
|
|
72
|
+
}
|
|
73
|
+
return path.join(this.dir, `${id}.jsonl`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export class Session {
|
|
77
|
+
messages = [];
|
|
78
|
+
status = 'active';
|
|
79
|
+
lastError;
|
|
80
|
+
/** 直近の圧縮状態。未圧縮なら undefined。原文の messages は常に全文。 */
|
|
81
|
+
compaction;
|
|
82
|
+
id;
|
|
83
|
+
/** ヘッダの作成時刻(ワークスペース記録に使う)。古いファイルは作成時刻がない。 */
|
|
84
|
+
createdAt = '';
|
|
85
|
+
cwd;
|
|
86
|
+
model;
|
|
87
|
+
file;
|
|
88
|
+
modelBaseUrl;
|
|
89
|
+
persistedCount = 0;
|
|
90
|
+
version = 1;
|
|
91
|
+
parentSessionId;
|
|
92
|
+
rootSessionId;
|
|
93
|
+
delegationLog = new Map();
|
|
94
|
+
constructor(id, file, cwd, model) {
|
|
95
|
+
this.id = id;
|
|
96
|
+
this.file = file;
|
|
97
|
+
this.cwd = cwd;
|
|
98
|
+
this.model = model;
|
|
99
|
+
}
|
|
100
|
+
static fromText(id, file, text) {
|
|
101
|
+
const lines = text.split('\n').filter((l) => l.length > 0);
|
|
102
|
+
if (lines.length === 0)
|
|
103
|
+
throw new Error(`空のセッション: ${id}`);
|
|
104
|
+
let header;
|
|
105
|
+
const session = new Session(id, file, '', '');
|
|
106
|
+
lines.forEach((line, i) => {
|
|
107
|
+
let ev;
|
|
108
|
+
try {
|
|
109
|
+
ev = JSON.parse(line);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
throw new Error(`壊れたセッション行(${i + 1}行目): ${id}`);
|
|
113
|
+
}
|
|
114
|
+
if (i === 0) {
|
|
115
|
+
if (ev.type !== 'session')
|
|
116
|
+
throw new Error(`ヘッダが先頭にない: ${id}`);
|
|
117
|
+
if (ev.version !== undefined && ev.version !== 2)
|
|
118
|
+
throw new Error('Unsupported session format');
|
|
119
|
+
header = ev;
|
|
120
|
+
session.version = ev.version ?? 1;
|
|
121
|
+
session.parentSessionId = ev.parentSessionId;
|
|
122
|
+
session.rootSessionId = ev.rootSessionId;
|
|
123
|
+
session.cwd = ev.cwd;
|
|
124
|
+
session.model = ev.model;
|
|
125
|
+
session.createdAt = typeof ev.createdAt === 'string' ? ev.createdAt : '';
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (ev.type === 'format') {
|
|
129
|
+
if (ev.version !== 2)
|
|
130
|
+
throw new Error('Unsupported session format');
|
|
131
|
+
session.version = 2;
|
|
132
|
+
}
|
|
133
|
+
else if (ev.type === 'connection') {
|
|
134
|
+
session.model = ev.model;
|
|
135
|
+
session.modelBaseUrl = ev.baseUrl;
|
|
136
|
+
}
|
|
137
|
+
else if (ev.type === 'delegation')
|
|
138
|
+
session.acceptDelegation(ev.record);
|
|
139
|
+
else if (ev.type === 'compaction') {
|
|
140
|
+
// 妥当な index だけを受け入れる。壊れた記録は無視して全文送信へ戻す(安全側)。
|
|
141
|
+
if (Number.isSafeInteger(ev.from) && ev.from > (session.compaction?.from ?? 0)
|
|
142
|
+
&& ev.from < session.messages.length && typeof ev.summary === 'string' && ev.summary.trim()) {
|
|
143
|
+
session.compaction = { summary: ev.summary.slice(0, MAX_SUMMARY_CHARS), from: ev.from };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
else if (ev.type === 'status') {
|
|
147
|
+
session.status = ev.status;
|
|
148
|
+
session.lastError = typeof ev.diagnostic === 'string' ? ev.diagnostic.slice(0, 2048) : undefined;
|
|
149
|
+
}
|
|
150
|
+
else if (ev.type === 'message') {
|
|
151
|
+
if (ev.message.role === 'user' && ev.message.images !== undefined)
|
|
152
|
+
ev.message.images = parseImages(ev.message.images);
|
|
153
|
+
session.messages.push(ev.message);
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
if (header === undefined)
|
|
157
|
+
throw new Error(`ヘッダが先頭にない: ${id}`);
|
|
158
|
+
session.persistedCount = session.messages.length;
|
|
159
|
+
// A crash after the request journal but before a receipt is not proof of no effect.
|
|
160
|
+
const pending = new Map();
|
|
161
|
+
for (const message of session.messages) {
|
|
162
|
+
if (message.role === 'assistant') {
|
|
163
|
+
for (const call of message.toolCalls ?? [])
|
|
164
|
+
pending.set(call.id, call);
|
|
165
|
+
}
|
|
166
|
+
else if (message.role === 'tool') {
|
|
167
|
+
for (const result of message.results)
|
|
168
|
+
pending.delete(result.callId);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (pending.size) {
|
|
172
|
+
const results = [...pending.values()].map(call => session.recoverPending(call));
|
|
173
|
+
session.messages.push({ role: 'tool', results });
|
|
174
|
+
if (results.some(result => result.status === 'unknown'))
|
|
175
|
+
session.status = 'interrupted';
|
|
176
|
+
}
|
|
177
|
+
if (session.compaction && safeBoundary(session.messages, session.compaction.from) !== session.compaction.from) {
|
|
178
|
+
session.compaction = undefined;
|
|
179
|
+
}
|
|
180
|
+
if (session.delegations().some(r => !r.result || r.result.status === 'unknown'))
|
|
181
|
+
session.status = 'interrupted';
|
|
182
|
+
return session;
|
|
183
|
+
}
|
|
184
|
+
recoverPending(call) {
|
|
185
|
+
const base = { callId: call.id, name: call.name };
|
|
186
|
+
if (call.name === 'run_subagent' || call.name === 'start_subagent') {
|
|
187
|
+
const record = [...this.delegationLog.values()].find(row => row.callId === call.id);
|
|
188
|
+
if (record?.state === 'finished' && record.result) {
|
|
189
|
+
try {
|
|
190
|
+
if (delegationDigest(parseDelegation(call.args)) === record.requestDigest) {
|
|
191
|
+
const result = record.result;
|
|
192
|
+
return { ...base, status: result.status === 'completed' ? 'ok' : result.status === 'unknown' ? 'unknown' : 'error', output: JSON.stringify(result) };
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
catch { /* Invalid or mismatched requests never inherit a completion receipt. */ }
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return { ...base, status: 'unknown', output: '保存された要求に結果がない。実行状態は不明。自動再実行せず状態を確認する' };
|
|
199
|
+
}
|
|
200
|
+
append(msg) {
|
|
201
|
+
if (msg.role === 'user' && msg.images !== undefined)
|
|
202
|
+
msg = { ...msg, images: parseImages(msg.images) };
|
|
203
|
+
this.messages.push(msg);
|
|
204
|
+
this.persistFrom(0);
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* ループが配列へ直接追加したメッセージをファイルへ追記する(メモリには既にある)。
|
|
208
|
+
* 既存呼び出しのindex引数は互換用。保存済み位置はSession自身が追跡し、二重追記しない。
|
|
209
|
+
*/
|
|
210
|
+
persistFrom(_index) {
|
|
211
|
+
while (this.persistedCount < this.messages.length) {
|
|
212
|
+
this.write({ type: 'message', message: this.messages[this.persistedCount] });
|
|
213
|
+
this.persistedCount++;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
recordMemory(observation) {
|
|
217
|
+
this.write({ ...observation, type: 'memory', at: new Date().toISOString() });
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* 圧縮を記録する。原文の messages は変更しない(監査・再実行防止の根拠を保つ)。
|
|
221
|
+
* 書き込みに失敗した場合はメモリ上の状態も戻し、保存と表示の不一致を作らない。
|
|
222
|
+
*/
|
|
223
|
+
recordCompaction(state, keptTurns) {
|
|
224
|
+
this.write({ type: 'compaction', summary: state.summary, from: state.from, keptTurns, at: new Date().toISOString() });
|
|
225
|
+
this.compaction = { ...state };
|
|
226
|
+
}
|
|
227
|
+
setConnection(model, baseUrl) {
|
|
228
|
+
this.write({ type: 'connection', model, ...(baseUrl ? { baseUrl } : {}) });
|
|
229
|
+
this.model = model;
|
|
230
|
+
this.modelBaseUrl = baseUrl;
|
|
231
|
+
}
|
|
232
|
+
setStatus(status, diagnostic) {
|
|
233
|
+
this.persistFrom(0);
|
|
234
|
+
const detail = diagnostic?.slice(0, 2048);
|
|
235
|
+
this.write({ type: 'status', status, at: new Date().toISOString(), ...(detail ? { diagnostic: detail } : {}) });
|
|
236
|
+
this.status = status;
|
|
237
|
+
this.lastError = detail;
|
|
238
|
+
}
|
|
239
|
+
get delegationCount() { return this.delegationLog.size; }
|
|
240
|
+
delegations() { return [...this.delegationLog.values()].map(record => structuredClone(record)); }
|
|
241
|
+
acceptDelegation(record) {
|
|
242
|
+
if (!record || record.parentSessionId !== this.id || typeof record.runId !== 'string' || typeof record.callId !== 'string'
|
|
243
|
+
|| !/^[a-f0-9]{64}$/.test(record.requestDigest) || !/^[a-f0-9]{64}$/.test(record.operationDigest)
|
|
244
|
+
|| !['starting', 'running', 'stopping', 'finished'].includes(record.state)
|
|
245
|
+
|| (record.state === 'finished') !== !!record.result
|
|
246
|
+
|| (record.result && (!['completed', 'error', 'cancelled', 'unknown'].includes(record.result.status) || typeof record.result.text !== 'string' || record.result.runId !== record.runId || record.result.agentId !== record.childSessionId || !['settled', 'unknown'].includes(record.result.cleanup) || (record.result.status === 'completed' && record.result.cleanup !== 'settled'))))
|
|
247
|
+
throw new Error('Invalid delegation journal');
|
|
248
|
+
if ([...this.delegationLog.values()].some(row => row.callId === record.callId && row.runId !== record.runId))
|
|
249
|
+
throw new Error('Conflicting delegation call ID');
|
|
250
|
+
const previous = this.delegationLog.get(record.runId);
|
|
251
|
+
if (previous && (previous.state === 'finished' || previous.requestDigest !== record.requestDigest || previous.operationDigest !== record.operationDigest || previous.callId !== record.callId))
|
|
252
|
+
throw new Error('Conflicting delegation journal');
|
|
253
|
+
this.delegationLog.set(record.runId, structuredClone(record));
|
|
254
|
+
}
|
|
255
|
+
recordDelegation(record) {
|
|
256
|
+
// Validate without changing the live projection until persistence succeeds.
|
|
257
|
+
const before = this.delegationLog;
|
|
258
|
+
this.delegationLog = new Map(before);
|
|
259
|
+
try {
|
|
260
|
+
this.acceptDelegation(record);
|
|
261
|
+
if (this.version === 1) {
|
|
262
|
+
this.write({ type: 'format', version: 2 });
|
|
263
|
+
this.version = 2;
|
|
264
|
+
}
|
|
265
|
+
this.write({ type: 'delegation', record });
|
|
266
|
+
}
|
|
267
|
+
catch (e) {
|
|
268
|
+
this.delegationLog = before;
|
|
269
|
+
throw e;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
/** 結果不明のツール呼び出し(中断の痕跡)。再開時の表示と再実行禁止の根拠に使う。 */
|
|
273
|
+
unknownToolResults() {
|
|
274
|
+
const out = [];
|
|
275
|
+
for (const m of this.messages) {
|
|
276
|
+
if (m.role === 'tool') {
|
|
277
|
+
for (const r of m.results) {
|
|
278
|
+
if (r.status === 'unknown')
|
|
279
|
+
out.push(r);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return out;
|
|
284
|
+
}
|
|
285
|
+
write(ev) {
|
|
286
|
+
fs.appendFileSync(this.file, `${JSON.stringify(ev)}\n`, { encoding: 'utf8', flush: true });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
function summarize(file, text) {
|
|
290
|
+
const lines = text.split('\n').filter((l) => l.length > 0);
|
|
291
|
+
const header = JSON.parse(lines[0] ?? '');
|
|
292
|
+
if (header.type !== 'session')
|
|
293
|
+
throw new Error(`ヘッダが先頭にない: ${file}`);
|
|
294
|
+
let status = 'active';
|
|
295
|
+
let model = header.model;
|
|
296
|
+
for (const line of lines.slice(1)) {
|
|
297
|
+
const ev = JSON.parse(line);
|
|
298
|
+
if (ev.type === 'status')
|
|
299
|
+
status = ev.status;
|
|
300
|
+
if (ev.type === 'connection')
|
|
301
|
+
model = ev.model;
|
|
302
|
+
}
|
|
303
|
+
return {
|
|
304
|
+
id: header.id,
|
|
305
|
+
createdAt: header.createdAt,
|
|
306
|
+
cwd: header.cwd,
|
|
307
|
+
model,
|
|
308
|
+
status,
|
|
309
|
+
seq: header.seq ?? 0,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AgentMessage } from '../agent/types.ts';
|
|
2
|
+
export interface RecordableSession {
|
|
3
|
+
id: string;
|
|
4
|
+
createdAt: string;
|
|
5
|
+
cwd: string;
|
|
6
|
+
model: string;
|
|
7
|
+
status: string;
|
|
8
|
+
messages: AgentMessage[];
|
|
9
|
+
}
|
|
10
|
+
/** ワークスペースに置く実行記録の保存先(.modkh/sessions/<id>.md)。 */
|
|
11
|
+
export declare function workspaceRecordDir(root: string): string;
|
|
12
|
+
export declare function workspaceRecordPath(root: string, id: string): string;
|
|
13
|
+
/** 人間が読める実行記録(逐次の会話・ツール実行)。内部の推論は含めない。 */
|
|
14
|
+
export declare function renderSessionRecord(session: RecordableSession, unknownToolNames?: string[]): string;
|
|
15
|
+
/**
|
|
16
|
+
* セッションをワークスペースに記録する(.modkh/sessions/<id>.md)。
|
|
17
|
+
* 失敗する理由(書き込み不可・ディスク満杯)は呼び出し元へ伝える。上書きは同一セッションのみが対象。
|
|
18
|
+
*/
|
|
19
|
+
export declare function recordSessionRecord(root: string, session: RecordableSession, unknownToolNames?: string[]): string;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
/** 1メッセージあたりの記録上限。超過は末尾を省いて切る(全文はJSONLに残る)。 */
|
|
4
|
+
const MAX_OUTPUT_CHARS = 4000;
|
|
5
|
+
const MAX_RECORD_FILES = 50;
|
|
6
|
+
/** ワークスペースに置く実行記録の保存先(.modkh/sessions/<id>.md)。 */
|
|
7
|
+
export function workspaceRecordDir(root) {
|
|
8
|
+
return path.join(root, '.modkh', 'sessions');
|
|
9
|
+
}
|
|
10
|
+
export function workspaceRecordPath(root, id) {
|
|
11
|
+
return path.join(workspaceRecordDir(root), `${id}.md`);
|
|
12
|
+
}
|
|
13
|
+
function clip(text, limit = MAX_OUTPUT_CHARS) {
|
|
14
|
+
if (text.length <= limit)
|
|
15
|
+
return text;
|
|
16
|
+
return `${text.slice(0, limit)}\n…(省略 ${text.length - limit} 文字。全文はセッションJSONLを参照)`;
|
|
17
|
+
}
|
|
18
|
+
/** 人間が読める実行記録(逐次の会話・ツール実行)。内部の推論は含めない。 */
|
|
19
|
+
export function renderSessionRecord(session, unknownToolNames = []) {
|
|
20
|
+
const lines = [
|
|
21
|
+
`# modkh セッション ${session.id}`,
|
|
22
|
+
'',
|
|
23
|
+
`- 作成: ${session.createdAt}`,
|
|
24
|
+
`- モデル: ${session.model}`,
|
|
25
|
+
`- 状態: ${session.status}`,
|
|
26
|
+
...(unknownToolNames.length ? [`- 注意: 結果不明のツール: ${unknownToolNames.join(', ')}`] : []),
|
|
27
|
+
'',
|
|
28
|
+
];
|
|
29
|
+
for (const message of session.messages) {
|
|
30
|
+
if (message.role === 'user') {
|
|
31
|
+
lines.push('## You', '', clip(message.content), '');
|
|
32
|
+
}
|
|
33
|
+
else if (message.role === 'assistant') {
|
|
34
|
+
if (message.content.length > 0)
|
|
35
|
+
lines.push('## Assistant', '', clip(message.content), '');
|
|
36
|
+
for (const call of message.toolCalls ?? []) {
|
|
37
|
+
lines.push(`### ツール ${call.name}`, '', clip(JSON.stringify(call.args)), '');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
for (const result of message.results) {
|
|
42
|
+
lines.push(`### 結果 ${result.name} (${result.status})`, '', clip(result.output), '');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return `${lines.join('\n').trimEnd()}\n`;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* セッションをワークスペースに記録する(.modkh/sessions/<id>.md)。
|
|
50
|
+
* 失敗する理由(書き込み不可・ディスク満杯)は呼び出し元へ伝える。上書きは同一セッションのみが対象。
|
|
51
|
+
*/
|
|
52
|
+
export function recordSessionRecord(root, session, unknownToolNames = []) {
|
|
53
|
+
const file = workspaceRecordPath(root, session.id);
|
|
54
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
55
|
+
// 同一セッションの追記/再書き込みは許し、他セッションの記録を消さない。
|
|
56
|
+
if (fs.existsSync(file))
|
|
57
|
+
fs.unlinkSync(file);
|
|
58
|
+
fs.writeFileSync(file, renderSessionRecord(session, unknownToolNames), { encoding: 'utf8' });
|
|
59
|
+
pruneOldRecords(path.dirname(file));
|
|
60
|
+
return file;
|
|
61
|
+
}
|
|
62
|
+
function pruneOldRecords(dir) {
|
|
63
|
+
const entries = fs.readdirSync(dir)
|
|
64
|
+
.filter((n) => n.endsWith('.md'))
|
|
65
|
+
.map((n) => ({ n, stat: fs.statSync(path.join(dir, n)) }))
|
|
66
|
+
.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
|
|
67
|
+
// 新しい50件を残す(既定のワークスペース記録の上限)。削除は .modkh 配下だけを対象にする。
|
|
68
|
+
for (const entry of entries.slice(MAX_RECORD_FILES)) {
|
|
69
|
+
const target = path.join(dir, entry.n);
|
|
70
|
+
if (path.dirname(target) === dir)
|
|
71
|
+
fs.unlinkSync(target);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { DelegationRequest, HeadAssignment } from './types.ts';
|
|
2
|
+
export interface HeadInputs {
|
|
3
|
+
model: string;
|
|
4
|
+
lean: string;
|
|
5
|
+
editor?: {
|
|
6
|
+
id: string;
|
|
7
|
+
path: string;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
/** Admit exactly the configured operation and its evidence before recording a child. */
|
|
11
|
+
export declare function headAssignment(inputs: HeadInputs, request: DelegationRequest, editRole: boolean, userRequest?: string): HeadAssignment | undefined;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { ToolError } from "../agent/types.js";
|
|
2
|
+
const vagueBehavior = /^(?:works?(?: as expected| correctly)?|correct|fixed|done|ok|pass(?:ed)?|tests? pass|成功|正常|変更前|変更後|確認済み|修正済み|(?:正しく|正常に)動(?:く|作する))[.!。]?$/i;
|
|
3
|
+
function observableBehavior(value) {
|
|
4
|
+
return Boolean(value) && !/[\r\n\u2028\u2029]/.test(value) && !vagueBehavior.test(value);
|
|
5
|
+
}
|
|
6
|
+
/** Admit exactly the configured operation and its evidence before recording a child. */
|
|
7
|
+
export function headAssignment(inputs, request, editRole, userRequest) {
|
|
8
|
+
const { pluginId, formalInput, behaviorChange, targetPaths } = request;
|
|
9
|
+
if (pluginId === 'micro-zenki' || pluginId === 'micro-goki') {
|
|
10
|
+
const stateright = pluginId === 'micro-zenki';
|
|
11
|
+
const path = stateright ? inputs.model : inputs.lean;
|
|
12
|
+
if (formalInput?.path !== path || formalInput.config !== undefined || behaviorChange) {
|
|
13
|
+
throw new ToolError('INVALID_ARGS', `Use configured formalInput ${JSON.stringify({ path })} for ${pluginId}`);
|
|
14
|
+
}
|
|
15
|
+
return stateright ? {
|
|
16
|
+
task: '設定された有限モデルをStaterightで検査する',
|
|
17
|
+
targets: [path],
|
|
18
|
+
completion: { condition: '指定したモデルと設定で不変条件違反なく探索が完了する', evidence: 'verify_stateright.status=passed' },
|
|
19
|
+
} : {
|
|
20
|
+
task: '証明元の対象定理をホスト指定の期待命題と照合する',
|
|
21
|
+
targets: [path],
|
|
22
|
+
completion: { condition: '指定定理の証明が期待命題と一致する', evidence: 'verify_lean.proofStatus=proved' },
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
if (!editRole && pluginId !== inputs.editor?.id) {
|
|
26
|
+
if (behaviorChange)
|
|
27
|
+
throw new ToolError('INVALID_ARGS', 'behaviorChange is reserved for the configured editor');
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const editor = inputs.editor;
|
|
31
|
+
if (!editor || editor.id !== pluginId)
|
|
32
|
+
throw new ToolError('DENIED', 'Use the editor selected in Lisp head checks');
|
|
33
|
+
if (targetPaths?.length !== 1 || targetPaths[0] !== editor.path) {
|
|
34
|
+
throw new ToolError('INVALID_ARGS', `Use exactly the configured targetPaths ${JSON.stringify([editor.path])}`);
|
|
35
|
+
}
|
|
36
|
+
if (!behaviorChange || !observableBehavior(behaviorChange.before) || !observableBehavior(behaviorChange.after) ||
|
|
37
|
+
behaviorChange.before.toLowerCase() === behaviorChange.after.toLowerCase()) {
|
|
38
|
+
throw new ToolError('INVALID_ARGS', 'behaviorChange.before and behaviorChange.after must state distinct, observable behavior for one change');
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
task: request.task,
|
|
42
|
+
targets: [editor.path],
|
|
43
|
+
behaviorChange,
|
|
44
|
+
...(userRequest ? { userRequest } : {}),
|
|
45
|
+
completion: { condition: behaviorChange.after, evidence: 'verification.status=passed and verification.application=applied' },
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Child slots only; the parent always retains its own model slot. */
|
|
2
|
+
export const DEFAULT_SUBAGENT_LIMIT = 2;
|
|
3
|
+
export const MAX_SUBAGENT_LIMIT = 16;
|
|
4
|
+
export function parseSubagentLimit(value) {
|
|
5
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 && value <= MAX_SUBAGENT_LIMIT ? value : null;
|
|
6
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ApprovalGate } from '../agent/types.ts';
|
|
2
|
+
import type { ExternalHost, ProcessRequest, ProcessResult } from '../plugins/api.ts';
|
|
3
|
+
import type { Session } from '../session/store.ts';
|
|
4
|
+
/** Tracks every host-managed process even if a plugin forgets to await it. */
|
|
5
|
+
export declare class ExternalProcesses implements ExternalHost {
|
|
6
|
+
readonly signal: AbortSignal;
|
|
7
|
+
private controller;
|
|
8
|
+
private closed;
|
|
9
|
+
private jobs;
|
|
10
|
+
readonly outcomes: ProcessResult[];
|
|
11
|
+
private root;
|
|
12
|
+
private approval;
|
|
13
|
+
private session;
|
|
14
|
+
constructor(root: string, approval: ApprovalGate, session: Session, signal: AbortSignal);
|
|
15
|
+
run(request: ProcessRequest): Promise<ProcessResult>;
|
|
16
|
+
private execute;
|
|
17
|
+
close(): Promise<void>;
|
|
18
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { ToolError } from "../agent/types.js";
|
|
4
|
+
import { object, fields, text } from "../plugins/package.js";
|
|
5
|
+
import { runShell } from "../tools/run.js";
|
|
6
|
+
function shellQuote(value) { return `'${value.replaceAll("'", "'\\''")}'`; }
|
|
7
|
+
/** Tracks every host-managed process even if a plugin forgets to await it. */
|
|
8
|
+
export class ExternalProcesses {
|
|
9
|
+
signal;
|
|
10
|
+
controller = new AbortController();
|
|
11
|
+
closed = false;
|
|
12
|
+
jobs = [];
|
|
13
|
+
outcomes = [];
|
|
14
|
+
root;
|
|
15
|
+
approval;
|
|
16
|
+
session;
|
|
17
|
+
constructor(root, approval, session, signal) {
|
|
18
|
+
this.root = root;
|
|
19
|
+
this.approval = approval;
|
|
20
|
+
this.session = session;
|
|
21
|
+
this.signal = AbortSignal.any([signal, this.controller.signal]);
|
|
22
|
+
}
|
|
23
|
+
run(request) {
|
|
24
|
+
if (this.closed || this.signal.aborted)
|
|
25
|
+
return Promise.reject(new ToolError('NOT_EXECUTED', 'External host is closed'));
|
|
26
|
+
const raw = object(request);
|
|
27
|
+
fields(raw, ['command', 'args']);
|
|
28
|
+
const command = text(raw.command, 'command', 4096);
|
|
29
|
+
if (!Array.isArray(raw.args) || raw.args.length > 256 || !raw.args.every(a => typeof a === 'string' && !a.includes('\0')) || Buffer.byteLength(JSON.stringify(raw.args)) > 131072)
|
|
30
|
+
throw new Error('Invalid process arguments');
|
|
31
|
+
const line = [command, ...raw.args].map(shellQuote).join(' ');
|
|
32
|
+
const job = this.execute(line);
|
|
33
|
+
this.jobs.push(job);
|
|
34
|
+
// Observe rejection without detaching its ownership; close() collects it again.
|
|
35
|
+
void job.catch(() => { });
|
|
36
|
+
return job;
|
|
37
|
+
}
|
|
38
|
+
async execute(command) {
|
|
39
|
+
const callId = randomUUID();
|
|
40
|
+
this.session.append({ role: 'assistant', content: '', toolCalls: [{ id: callId, name: 'external_process', args: { command, cwd: this.root } }] });
|
|
41
|
+
let result;
|
|
42
|
+
try {
|
|
43
|
+
if (this.signal.aborted)
|
|
44
|
+
throw new ToolError('NOT_EXECUTED', '中断済み');
|
|
45
|
+
const approved = await this.approval.approve({ signal: this.signal, kind: 'command', title: '外部プラグインのプロセス起動', detail: `${command}\n作業場所: ${this.root}\nOSサンドボックスではありません。リモート処理の停止は保証できません。` });
|
|
46
|
+
if (!approved)
|
|
47
|
+
throw new ToolError('DENIED', '実行は承認されませんでした');
|
|
48
|
+
if (this.signal.aborted || fs.realpathSync(this.root) !== this.root)
|
|
49
|
+
throw new ToolError('NOT_EXECUTED', '停止済み、または作業場所が変更されました');
|
|
50
|
+
// No inherited provider credentials. A trusted CLI can still access its own files.
|
|
51
|
+
const env = {};
|
|
52
|
+
for (const key of ['PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL'])
|
|
53
|
+
if (process.env[key] !== undefined)
|
|
54
|
+
env[key] = process.env[key];
|
|
55
|
+
result = { status: 'ok', output: await runShell(command, this.root, this.signal, env), cleanup: 'settled' };
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
const code = e instanceof ToolError ? e.code : 'RESULT_UNKNOWN';
|
|
59
|
+
result = { status: code === 'NOT_EXECUTED' || code === 'DENIED' ? 'not-executed' : code === 'RUN_FAILED' ? 'error' : 'unknown', output: String(e), cleanup: code === 'RESULT_UNKNOWN' ? 'unknown' : 'settled' };
|
|
60
|
+
}
|
|
61
|
+
this.outcomes.push(result);
|
|
62
|
+
this.session.append({ role: 'tool', results: [{ callId, name: 'external_process', status: result.status, output: result.output }] });
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
async close() {
|
|
66
|
+
this.closed = true;
|
|
67
|
+
this.controller.abort();
|
|
68
|
+
const settled = await Promise.allSettled(this.jobs);
|
|
69
|
+
const failures = settled.filter(r => r.status === 'rejected');
|
|
70
|
+
if (failures.length || this.outcomes.some(r => r.cleanup === 'unknown'))
|
|
71
|
+
throw new Error('External process cleanup or journaling is unconfirmed');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { DelegationRequest } from './types.ts';
|
|
2
|
+
/** Canonical field order is shared by admission and durable receipt recovery. */
|
|
3
|
+
export declare function parseDelegation(value: unknown): DelegationRequest;
|
|
4
|
+
export declare function delegationDigest(request: DelegationRequest): string;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { fields, object, pluginId, text } from "../plugins/package.js";
|
|
3
|
+
/** Canonical field order is shared by admission and durable receipt recovery. */
|
|
4
|
+
export function parseDelegation(value) {
|
|
5
|
+
const raw = object(value);
|
|
6
|
+
fields(raw, ['pluginId', 'task', 'context', 'targetPaths', 'formalInput', 'behaviorChange']);
|
|
7
|
+
const request = { pluginId: pluginId(raw.pluginId), task: text(raw.task, 'task', 32768) };
|
|
8
|
+
if (raw.context !== undefined)
|
|
9
|
+
request.context = text(raw.context, 'context', 131072);
|
|
10
|
+
if (raw.behaviorChange !== undefined) {
|
|
11
|
+
const change = object(raw.behaviorChange);
|
|
12
|
+
fields(change, ['before', 'after']);
|
|
13
|
+
request.behaviorChange = {
|
|
14
|
+
before: text(change.before, 'behaviorChange.before', 512).trim(),
|
|
15
|
+
after: text(change.after, 'behaviorChange.after', 512).trim(),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
if (raw.targetPaths !== undefined) {
|
|
19
|
+
if (!Array.isArray(raw.targetPaths) || raw.targetPaths.length < 1 || raw.targetPaths.length > 8 ||
|
|
20
|
+
!raw.targetPaths.every(p => typeof p === 'string' && p.length < 1024 && !p.startsWith('/') && !p.includes('\\') && !p.split('/').some((s) => !s || s === '.' || s === '..')) ||
|
|
21
|
+
new Set(raw.targetPaths).size !== raw.targetPaths.length)
|
|
22
|
+
throw new Error('Invalid targetPaths: 1..8 unique relative file paths required');
|
|
23
|
+
request.targetPaths = [...raw.targetPaths].sort();
|
|
24
|
+
}
|
|
25
|
+
if (raw.formalInput !== undefined) {
|
|
26
|
+
const input = object(raw.formalInput);
|
|
27
|
+
fields(input, ['path', 'config']);
|
|
28
|
+
request.formalInput = { path: text(input.path, 'formalInput.path', 1024) };
|
|
29
|
+
if (input.config !== undefined)
|
|
30
|
+
request.formalInput.config = text(input.config, 'formalInput.config', 1024);
|
|
31
|
+
if (request.targetPaths)
|
|
32
|
+
throw new Error('formalInput and targetPaths are mutually exclusive');
|
|
33
|
+
}
|
|
34
|
+
return request;
|
|
35
|
+
}
|
|
36
|
+
export function delegationDigest(request) {
|
|
37
|
+
return createHash('sha256').update(JSON.stringify(request)).digest('hex');
|
|
38
|
+
}
|