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,79 @@
|
|
|
1
|
+
import { ShellProcess, type ShellName } from './shell-process.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Background job registry.
|
|
4
|
+
*
|
|
5
|
+
* Ownership and lifetime are the registry's; running the command is the producer's. A job keeps
|
|
6
|
+
* its own output cursor so repeated reads return only what is new, and a settled job stays
|
|
7
|
+
* readable so a late `job_output` still reports how it ended.
|
|
8
|
+
*
|
|
9
|
+
* Registered jobs never outlive the owning session: `close()` stops every job and waits for the
|
|
10
|
+
* process groups to disappear, so MODKH cannot exit leaving orphaned children.
|
|
11
|
+
*/
|
|
12
|
+
export type JobStatus = 'running' | 'stopping' | 'completed' | 'killed' | 'failed';
|
|
13
|
+
export interface JobView {
|
|
14
|
+
id: string;
|
|
15
|
+
kind: 'bash';
|
|
16
|
+
/** First line of the command, is bounded, and is what the human sees. */
|
|
17
|
+
label: string;
|
|
18
|
+
command: string;
|
|
19
|
+
cwd: string;
|
|
20
|
+
shell: ShellName;
|
|
21
|
+
status: JobStatus;
|
|
22
|
+
startedAt: number;
|
|
23
|
+
finishedAt?: number;
|
|
24
|
+
/** Exit code once settled normally; never invented for a killed or failed job. */
|
|
25
|
+
exitCode?: number | null;
|
|
26
|
+
/** Why the job ended, when it did not simply exit. */
|
|
27
|
+
detail?: string;
|
|
28
|
+
}
|
|
29
|
+
export interface JobStartRequest {
|
|
30
|
+
command: string;
|
|
31
|
+
cwd: string;
|
|
32
|
+
shell: ShellName;
|
|
33
|
+
description?: string;
|
|
34
|
+
}
|
|
35
|
+
export declare class JobRegistry {
|
|
36
|
+
private readonly jobs;
|
|
37
|
+
private closed;
|
|
38
|
+
/** Settlements the model has not been told about yet, in completion order. */
|
|
39
|
+
private readonly notices;
|
|
40
|
+
private noticeWake;
|
|
41
|
+
get noticeSignal(): AbortSignal;
|
|
42
|
+
/** Owner-visible label for a notice; never contains the command's full output. */
|
|
43
|
+
private noticeBytes;
|
|
44
|
+
get size(): number;
|
|
45
|
+
/** Drain pending completion notices. Returns [] when every settlement was already reported. */
|
|
46
|
+
takeNotices(): string[];
|
|
47
|
+
get hasNotices(): boolean;
|
|
48
|
+
private notice;
|
|
49
|
+
start(request: JobStartRequest): JobView;
|
|
50
|
+
/**
|
|
51
|
+
* Take ownership of a process that is already running.
|
|
52
|
+
*
|
|
53
|
+
* This is how a foreground command that reached its deadline keeps its work: the caller
|
|
54
|
+
* abandons its own await and the job registry continues to observe, report, and stop it.
|
|
55
|
+
* Everything already produced on stdout/stderr is available to the first `job_output`.
|
|
56
|
+
*/
|
|
57
|
+
adopt(process: ShellProcess, request: JobStartRequest): JobView;
|
|
58
|
+
private register;
|
|
59
|
+
list(): JobView[];
|
|
60
|
+
get(id: string): JobView | undefined;
|
|
61
|
+
private require;
|
|
62
|
+
/** Output appended since the previous read. The cursor advances only for a delivered read. */
|
|
63
|
+
read(id: string): {
|
|
64
|
+
job: JobView;
|
|
65
|
+
stdout: string;
|
|
66
|
+
stderr: string;
|
|
67
|
+
dropped: number;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Wait until the job settles, new output appears, or the timeout expires.
|
|
71
|
+
*
|
|
72
|
+
* Returning early on new output is what makes polling useful: a long build reports progress
|
|
73
|
+
* instead of forcing the caller to choose between blocking for minutes and busy-looping.
|
|
74
|
+
*/
|
|
75
|
+
wait(id: string, timeoutMs: number, signal?: AbortSignal): Promise<void>;
|
|
76
|
+
kill(id: string, reason?: string): Promise<JobView>;
|
|
77
|
+
/** Stop every job and wait for the process groups to settle. */
|
|
78
|
+
close(): Promise<void>;
|
|
79
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { ShellProcess } from "./shell-process.js";
|
|
3
|
+
const MAX_RETAINED_JOBS = 32;
|
|
4
|
+
const LABEL_MAX = 120;
|
|
5
|
+
function label(command, description) {
|
|
6
|
+
const text = (description?.trim() || command.trim().split('\n')[0] || command).replace(/\s+/g, ' ');
|
|
7
|
+
return text.length <= LABEL_MAX ? text : `${text.slice(0, LABEL_MAX - 1)}…`;
|
|
8
|
+
}
|
|
9
|
+
export class JobRegistry {
|
|
10
|
+
jobs = new Map();
|
|
11
|
+
closed = false;
|
|
12
|
+
/** Settlements the model has not been told about yet, in completion order. */
|
|
13
|
+
notices = [];
|
|
14
|
+
noticeWake = new AbortController();
|
|
15
|
+
get noticeSignal() { return this.noticeWake.signal; }
|
|
16
|
+
/** Owner-visible label for a notice; never contains the command's full output. */
|
|
17
|
+
noticeBytes = 2048;
|
|
18
|
+
get size() { return this.jobs.size; }
|
|
19
|
+
/** Drain pending completion notices. Returns [] when every settlement was already reported. */
|
|
20
|
+
takeNotices() {
|
|
21
|
+
if (this.noticeWake.signal.aborted)
|
|
22
|
+
this.noticeWake = new AbortController();
|
|
23
|
+
return this.notices.splice(0, this.notices.length);
|
|
24
|
+
}
|
|
25
|
+
get hasNotices() { return this.notices.length > 0; }
|
|
26
|
+
notice(record) {
|
|
27
|
+
const view = record.view;
|
|
28
|
+
const status = view.exitCode === undefined || view.exitCode === null ? view.status : `${view.status}, exit ${view.exitCode}`;
|
|
29
|
+
const head = `バックグラウンドジョブ ${view.id} (${view.label}) が終了した [${status}]`;
|
|
30
|
+
// Quote only what the model has not read, and only when it fits; otherwise name the tool.
|
|
31
|
+
const unread = record.process.out.read(record.outCursor).text + record.process.err.read(record.errCursor).text;
|
|
32
|
+
if (unread.trim().length === 0) {
|
|
33
|
+
this.notices.push(`${head}。新しい出力はない。`);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (unread.length <= this.noticeBytes) {
|
|
37
|
+
this.notices.push(`${head}。未読の出力:\n${unread.trimEnd()}\n(job_output で続きを読める)`);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
this.notices.push(`${head}。未読の出力が ${unread.length} 文字ある。job_output で読む。`);
|
|
41
|
+
}
|
|
42
|
+
start(request) {
|
|
43
|
+
if (this.closed)
|
|
44
|
+
throw new Error('ジョブ実行は終了済み');
|
|
45
|
+
const process = new ShellProcess(request.command, request.cwd, { shell: request.shell });
|
|
46
|
+
return this.register(process, request);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Take ownership of a process that is already running.
|
|
50
|
+
*
|
|
51
|
+
* This is how a foreground command that reached its deadline keeps its work: the caller
|
|
52
|
+
* abandons its own await and the job registry continues to observe, report, and stop it.
|
|
53
|
+
* Everything already produced on stdout/stderr is available to the first `job_output`.
|
|
54
|
+
*/
|
|
55
|
+
adopt(process, request) {
|
|
56
|
+
if (this.closed) {
|
|
57
|
+
process.stop('killed');
|
|
58
|
+
throw new Error('ジョブ実行は終了済み');
|
|
59
|
+
}
|
|
60
|
+
return this.register(process, request);
|
|
61
|
+
}
|
|
62
|
+
register(process, request) {
|
|
63
|
+
// Bound retained history: drop the oldest settled record, never a live one.
|
|
64
|
+
if (this.jobs.size >= MAX_RETAINED_JOBS) {
|
|
65
|
+
const settled = [...this.jobs.values()].find(record => record.view.status !== 'running' && record.view.status !== 'stopping');
|
|
66
|
+
if (settled)
|
|
67
|
+
this.jobs.delete(settled.view.id);
|
|
68
|
+
}
|
|
69
|
+
const id = `bash-${randomUUID().replaceAll('-', '').slice(0, 16)}`;
|
|
70
|
+
const view = {
|
|
71
|
+
id, kind: 'bash', label: label(request.command, request.description),
|
|
72
|
+
command: request.command, cwd: request.cwd, shell: request.shell,
|
|
73
|
+
status: 'running', startedAt: Date.now(),
|
|
74
|
+
};
|
|
75
|
+
const record = { view, process, outCursor: 0, errCursor: 0, unreadOut: 0, unreadErr: 0, waiters: new Set() };
|
|
76
|
+
this.jobs.set(id, record);
|
|
77
|
+
void process.result.then(result => {
|
|
78
|
+
view.status = 'completed';
|
|
79
|
+
view.finishedAt = Date.now();
|
|
80
|
+
view.exitCode = result.code;
|
|
81
|
+
}, (error) => {
|
|
82
|
+
view.finishedAt = Date.now();
|
|
83
|
+
if (process.stoppedByKill) {
|
|
84
|
+
view.status = 'killed';
|
|
85
|
+
// A human-supplied reason is more useful than the generic cause; keep it.
|
|
86
|
+
view.detail ??= '停止を要求された';
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
view.status = 'failed';
|
|
90
|
+
view.detail = error.message.split('\n')[0];
|
|
91
|
+
}
|
|
92
|
+
}).finally(() => {
|
|
93
|
+
record.unreadOut = process.out.produced - record.outCursor;
|
|
94
|
+
record.unreadErr = process.err.produced - record.errCursor;
|
|
95
|
+
this.notice(record);
|
|
96
|
+
this.noticeWake.abort();
|
|
97
|
+
for (const wake of record.waiters)
|
|
98
|
+
wake();
|
|
99
|
+
record.waiters.clear();
|
|
100
|
+
});
|
|
101
|
+
return { ...view };
|
|
102
|
+
}
|
|
103
|
+
list() {
|
|
104
|
+
return [...this.jobs.values()].map(record => ({ ...record.view }));
|
|
105
|
+
}
|
|
106
|
+
get(id) {
|
|
107
|
+
const record = this.jobs.get(id);
|
|
108
|
+
return record ? { ...record.view } : undefined;
|
|
109
|
+
}
|
|
110
|
+
require(id) {
|
|
111
|
+
const record = this.jobs.get(id);
|
|
112
|
+
if (!record)
|
|
113
|
+
throw new Error(`不明なジョブ: ${id}`);
|
|
114
|
+
return record;
|
|
115
|
+
}
|
|
116
|
+
/** Output appended since the previous read. The cursor advances only for a delivered read. */
|
|
117
|
+
read(id) {
|
|
118
|
+
const record = this.require(id);
|
|
119
|
+
const out = record.process.out.read(record.outCursor);
|
|
120
|
+
const err = record.process.err.read(record.errCursor);
|
|
121
|
+
record.outCursor = out.next;
|
|
122
|
+
record.errCursor = err.next;
|
|
123
|
+
record.unreadOut = 0;
|
|
124
|
+
record.unreadErr = 0;
|
|
125
|
+
return { job: { ...record.view }, stdout: out.text, stderr: err.text, dropped: out.dropped + err.dropped };
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Wait until the job settles, new output appears, or the timeout expires.
|
|
129
|
+
*
|
|
130
|
+
* Returning early on new output is what makes polling useful: a long build reports progress
|
|
131
|
+
* instead of forcing the caller to choose between blocking for minutes and busy-looping.
|
|
132
|
+
*/
|
|
133
|
+
wait(id, timeoutMs, signal) {
|
|
134
|
+
const record = this.require(id);
|
|
135
|
+
const settledNow = () => record.view.status !== 'running' && record.view.status !== 'stopping';
|
|
136
|
+
if (settledNow())
|
|
137
|
+
return Promise.resolve();
|
|
138
|
+
const outMark = record.process.out.produced;
|
|
139
|
+
const errMark = record.process.err.produced;
|
|
140
|
+
return new Promise(resolve => {
|
|
141
|
+
let done = false;
|
|
142
|
+
const finish = () => {
|
|
143
|
+
if (done)
|
|
144
|
+
return;
|
|
145
|
+
done = true;
|
|
146
|
+
clearTimeout(timer);
|
|
147
|
+
clearInterval(poll);
|
|
148
|
+
signal?.removeEventListener('abort', finish);
|
|
149
|
+
record.waiters.delete(finish);
|
|
150
|
+
resolve();
|
|
151
|
+
};
|
|
152
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
153
|
+
// Output arrives through a stream, not an event the registry owns; a bounded poll keeps
|
|
154
|
+
// the seam small without making every job wake the registry on each chunk.
|
|
155
|
+
const poll = setInterval(() => {
|
|
156
|
+
if (settledNow()
|
|
157
|
+
|| record.process.out.produced !== outMark
|
|
158
|
+
|| record.process.err.produced !== errMark)
|
|
159
|
+
finish();
|
|
160
|
+
}, 10);
|
|
161
|
+
signal?.addEventListener('abort', finish, { once: true });
|
|
162
|
+
record.waiters.add(finish);
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
async kill(id, reason) {
|
|
166
|
+
const record = this.require(id);
|
|
167
|
+
if (record.view.status === 'running') {
|
|
168
|
+
record.view.status = 'stopping';
|
|
169
|
+
if (reason !== undefined && reason.length > 0)
|
|
170
|
+
record.view.detail = reason.slice(0, 200);
|
|
171
|
+
record.process.stop('killed');
|
|
172
|
+
}
|
|
173
|
+
return { ...record.view };
|
|
174
|
+
}
|
|
175
|
+
/** Stop every job and wait for the process groups to settle. */
|
|
176
|
+
async close() {
|
|
177
|
+
this.closed = true;
|
|
178
|
+
const live = [...this.jobs.values()].filter(record => record.view.status === 'running' || record.view.status === 'stopping');
|
|
179
|
+
for (const record of live) {
|
|
180
|
+
record.view.status = 'stopping';
|
|
181
|
+
record.process.stop('killed');
|
|
182
|
+
}
|
|
183
|
+
await Promise.allSettled(live.map(record => record.process.result));
|
|
184
|
+
this.jobs.clear();
|
|
185
|
+
}
|
|
186
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type Tool } from '../agent/types.ts';
|
|
2
|
+
import { type LanguageService } from '../language/lsp/service.ts';
|
|
3
|
+
import { verifyGrammar } from '../language/syntax/parser.ts';
|
|
4
|
+
/** Lazy: constructing the tools must stay cheap for subagents with no language work. */
|
|
5
|
+
export declare function languageTools(service: LanguageService): Tool[];
|
|
6
|
+
export { verifyGrammar };
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { commonLispReader } from "../language/commonlisp-reader.js";
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { ToolError } from "../agent/types.js";
|
|
5
|
+
import { resolveInRoot, assertRealInRoot } from "./guard.js";
|
|
6
|
+
import { detectLanguage } from "../language/detect.js";
|
|
7
|
+
import { formatDiagnostics } from "../language/lsp/service.js";
|
|
8
|
+
import { outline, verifyGrammar } from "../language/syntax/parser.js";
|
|
9
|
+
import { offsetToPosition, positionToOffset } from "../language/positions.js";
|
|
10
|
+
function selector(value) {
|
|
11
|
+
if (value !== undefined && value !== 'tailwind')
|
|
12
|
+
throw new ToolError('INVALID_ARGS', 'Unknown server selector');
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
|
16
|
+
function requireString(value, name) {
|
|
17
|
+
if (typeof value !== 'string' || value.length === 0)
|
|
18
|
+
throw new ToolError('INVALID_ARGS', `${name} は空でない文字列で指定する`);
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
function readSource(root, rel) {
|
|
22
|
+
const abs = resolveInRoot(root, rel);
|
|
23
|
+
assertRealInRoot(root, abs);
|
|
24
|
+
let stat;
|
|
25
|
+
try {
|
|
26
|
+
stat = fs.statSync(abs);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
throw new ToolError('NOT_FOUND', `読めないファイル: ${rel}`);
|
|
30
|
+
}
|
|
31
|
+
if (!stat.isFile())
|
|
32
|
+
throw new ToolError('READ_FAILED', `ファイルではない: ${rel}`);
|
|
33
|
+
if (stat.size > MAX_SOURCE_BYTES)
|
|
34
|
+
throw new ToolError('TOO_LARGE', `2 MiBを超えるファイルは解析しない: ${rel}`);
|
|
35
|
+
return { abs, text: fs.readFileSync(abs, 'utf8') };
|
|
36
|
+
}
|
|
37
|
+
function renderDiagnostics(items, root) {
|
|
38
|
+
if (items.length === 0)
|
|
39
|
+
return '診断は0件(サーバーが通知した結果)';
|
|
40
|
+
return items.slice(0, 50).map(item => {
|
|
41
|
+
const rel = path.relative(root, item.path) || item.path;
|
|
42
|
+
return `${rel}:${item.line}:${item.column} ${item.severity}: ${item.message}${item.source ? ` (${item.source})` : ''}`;
|
|
43
|
+
}).join('\n');
|
|
44
|
+
}
|
|
45
|
+
function renderDeclaration(node) {
|
|
46
|
+
const range = node.declaration;
|
|
47
|
+
const name = node.name?.replace(/\s+/g, ' ');
|
|
48
|
+
return `${range.startLine}:${range.startColumn}-${range.endLine}:${range.endColumn} ${node.kind}${name ? ` ${name} (名前位置 ${node.startLine}:${node.startColumn})` : ''}`;
|
|
49
|
+
}
|
|
50
|
+
async function describeSyntax(root, rel, query) {
|
|
51
|
+
const { abs, text } = readSource(root, rel);
|
|
52
|
+
const detection = detectLanguage(abs, root);
|
|
53
|
+
if (!detection?.language.grammar)
|
|
54
|
+
throw new ToolError('UNSUPPORTED', `構造抽出の対象外: ${rel}`);
|
|
55
|
+
const result = await outline(detection.language.grammar, text, { nameIncludes: query });
|
|
56
|
+
if (result.status !== 'ok' || !result.nodes) {
|
|
57
|
+
throw new ToolError(result.status === 'unsupported' ? 'UNSUPPORTED' : 'PARSE_FAILED', `${rel} の構造を取得できない: ${result.detail ?? result.status}`);
|
|
58
|
+
}
|
|
59
|
+
const rows = result.nodes.map(renderDeclaration);
|
|
60
|
+
const summary = `${rel} (${detection.language.id}, ${rows.length}件${result.truncated ? 'まで表示' : ''}, 構文エラー候補${result.errorCount ?? 0})`;
|
|
61
|
+
return `${summary}\n${rows.join('\n') || '(構文上の一致なし)'}`;
|
|
62
|
+
}
|
|
63
|
+
/** Lazy: constructing the tools must stay cheap for subagents with no language work. */
|
|
64
|
+
export function languageTools(service) {
|
|
65
|
+
const outlineTool = {
|
|
66
|
+
readOnly: true,
|
|
67
|
+
name: 'code_outline',
|
|
68
|
+
description: 'Tree-sitterで関数・クラス・メソッド等と宣言全体の範囲を取得する。行・桁は1開始。終了位置は範囲に含まない。',
|
|
69
|
+
parameters: { type: 'object', properties: {
|
|
70
|
+
path: { type: 'string', description: '対象ファイル(ルート相対)' },
|
|
71
|
+
server: { type: 'string', enum: ['tailwind'], description: 'Explicit semantic overlay' },
|
|
72
|
+
}, required: ['path'] },
|
|
73
|
+
async execute(args, ctx) {
|
|
74
|
+
return describeSyntax(ctx.root, requireString(args.path, 'path'));
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
const syntaxSearchTool = {
|
|
78
|
+
readOnly: true,
|
|
79
|
+
name: 'code_syntax_search',
|
|
80
|
+
description: 'Tree-sitterで構文上の宣言名を検索し、対象ファイルと宣言全体の範囲を返す。行・桁は1開始、終了位置は範囲に含まない。同名候補はそれぞれ返す。',
|
|
81
|
+
parameters: { type: 'object', properties: {
|
|
82
|
+
path: { type: 'string', description: '対象ファイル(ルート相対)' },
|
|
83
|
+
server: { type: 'string', enum: ['tailwind'], description: 'Explicit semantic overlay' },
|
|
84
|
+
query: { type: 'string', description: '名前の部分一致(空なら全件)' },
|
|
85
|
+
}, required: ['path'] },
|
|
86
|
+
async execute(args, ctx) {
|
|
87
|
+
const rel = requireString(args.path, 'path');
|
|
88
|
+
if (args.query !== undefined && typeof args.query !== 'string') {
|
|
89
|
+
throw new ToolError('INVALID_ARGS', 'query は宣言名の文字列で指定する');
|
|
90
|
+
}
|
|
91
|
+
return describeSyntax(ctx.root, rel, args.query);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
const diagnosticsTool = {
|
|
95
|
+
readOnly: true,
|
|
96
|
+
name: 'code_diagnostics',
|
|
97
|
+
description: '現在のファイル内容をLSPへ同期し、診断を取得する。診断0件・未通知・古い版を区別して返す。',
|
|
98
|
+
parameters: { type: 'object', properties: {
|
|
99
|
+
path: { type: 'string', description: '対象ファイル(ルート相対)' },
|
|
100
|
+
server: { type: 'string', enum: ['tailwind'], description: 'Explicit semantic overlay' },
|
|
101
|
+
}, required: ['path'] },
|
|
102
|
+
async execute(args, ctx) {
|
|
103
|
+
const rel = requireString(args.path, 'path');
|
|
104
|
+
const { text } = readSource(ctx.root, rel);
|
|
105
|
+
const result = await service.analyze(resolveInRoot(ctx.root, rel), text, ctx.signal, selector(args.server));
|
|
106
|
+
if (result.status !== 'ok') {
|
|
107
|
+
const supplemental = detectLanguage(resolveInRoot(ctx.root, rel), ctx.root)?.language.id === 'commonlisp'
|
|
108
|
+
? await commonLispReader(text, { signal: ctx.signal }) : undefined;
|
|
109
|
+
// Readable input is not a clean LSP diagnostic result. Keep the tool unverified.
|
|
110
|
+
throw new ToolError('LSP_UNVERIFIED', `${formatDiagnostics(result)}${supplemental ? `\nSupplemental ${supplemental.provider}: ${supplemental.status}; ${supplemental.scope}\n${supplemental.line ?? '?'}:${supplemental.column ?? '?'} ${supplemental.detail}` : ''}`);
|
|
111
|
+
}
|
|
112
|
+
return `${formatDiagnostics(result)}\n${renderDiagnostics(result.diagnostics ?? [], ctx.root)}`;
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
const positionTool = (name, description) => ({
|
|
116
|
+
readOnly: true,
|
|
117
|
+
name,
|
|
118
|
+
description,
|
|
119
|
+
parameters: { type: 'object', properties: {
|
|
120
|
+
path: { type: 'string', description: '対象ファイル(ルート相対)' },
|
|
121
|
+
server: { type: 'string', enum: ['tailwind'], description: 'Explicit semantic overlay' },
|
|
122
|
+
line: { type: 'number', description: '1開始の行' },
|
|
123
|
+
column: { type: 'number', description: '1開始の桁(UTF-16)' },
|
|
124
|
+
}, required: ['path', 'line', 'column'] },
|
|
125
|
+
async execute(args, ctx) {
|
|
126
|
+
const rel = requireString(args.path, 'path');
|
|
127
|
+
const line = Number(args.line), column = Number(args.column);
|
|
128
|
+
if (!Number.isSafeInteger(line) || line < 1 || !Number.isSafeInteger(column) || column < 1) {
|
|
129
|
+
throw new ToolError('INVALID_ARGS', 'line と column は1以上の整数');
|
|
130
|
+
}
|
|
131
|
+
const { abs, text } = readSource(ctx.root, rel);
|
|
132
|
+
const offset = positionToOffset(text, { line: line - 1, character: column - 1 });
|
|
133
|
+
const detection = detectLanguage(abs, ctx.root);
|
|
134
|
+
if (!detection)
|
|
135
|
+
throw new ToolError('UNSUPPORTED', `対応言語ではない: ${rel}`);
|
|
136
|
+
// Ensure the server has the current text before asking about a position.
|
|
137
|
+
await service.analyze(abs, text, ctx.signal, selector(args.server));
|
|
138
|
+
const position = offsetToPosition(text, offset);
|
|
139
|
+
const root = detection.root;
|
|
140
|
+
const configured = service.detect(abs);
|
|
141
|
+
if (!configured)
|
|
142
|
+
throw new ToolError('UNSUPPORTED', `対応言語ではない: ${rel}`);
|
|
143
|
+
try {
|
|
144
|
+
if (name === 'code_hover') {
|
|
145
|
+
const answer = await withServer(service, abs, text, ctx.signal, server => server.hover(abs, position), selector(args.server));
|
|
146
|
+
return answer ?? '型情報は得られなかった';
|
|
147
|
+
}
|
|
148
|
+
const locations = await withServer(service, abs, text, ctx.signal, server => name === 'code_definition' ? server.definition(abs, position) : server.references(abs, position), selector(args.server));
|
|
149
|
+
if (locations.length === 0)
|
|
150
|
+
return `${name}: 該当なし。この結果は未取得ではなく、サーバーが空を返した`;
|
|
151
|
+
return locations.map(location => `${path.relative(root, location.file) || location.file}:${location.line}:${location.character}`).join('\n');
|
|
152
|
+
}
|
|
153
|
+
catch (e) {
|
|
154
|
+
throw new ToolError('LSP_FAILED', e.message);
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
return [outlineTool, syntaxSearchTool, diagnosticsTool,
|
|
159
|
+
positionTool('code_definition', '定義位置を取得する(位置的問い合わせ)'),
|
|
160
|
+
positionTool('code_references', '参照位置を取得する(位置的問い合わせ)'),
|
|
161
|
+
positionTool('code_hover', '型・ドキュメントのホバー情報を取得する')];
|
|
162
|
+
}
|
|
163
|
+
/** Acquire the same pooled server used for diagnostics; absence is reported, never fabricated. */
|
|
164
|
+
async function withServer(service, file, text, signal, action, selector) {
|
|
165
|
+
const server = service.poolFor(file, selector);
|
|
166
|
+
if (!server)
|
|
167
|
+
throw new Error('言語サーバーを初期化できませんでした');
|
|
168
|
+
void text;
|
|
169
|
+
void signal;
|
|
170
|
+
return action(server);
|
|
171
|
+
}
|
|
172
|
+
export { verifyGrammar };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type ExecutionReceipt } from '../lisp/runtime.ts';
|
|
2
|
+
export declare const leanProofDriver = "import Lean\nimport Lean.Replay\nopen Lean\n\ndef fromModule (env : Environment) (decl mod : Name) : Bool :=\n (env.getModuleIdxFor? decl).any fun idx => env.header.moduleNames[idx.toNat]? == some mod\n\ndef checkTarget (target : Name) : IO String := do\n initSearchPath (\u2190 getBuildDir)\n let base \u2190 importModules #[{ module := `Lean }, { module := `MoDKHTarget }] {}\n let loaded \u2190 importModules #[{ module := `Lean }, { module := `MoDKHTarget }, { module := `MoDKHProof }] {}\n let some (.defnInfo expected) := base.find? `modkhExpected | return \"invalid-contract\"\n if !fromModule base `modkhExpected `MoDKHTarget || expected.type != mkSort .zero || !expected.levelParams.isEmpty then\n return \"invalid-contract\"\n let some (.thmInfo theoremInfo) := loaded.find? target | return \"target-missing\"\n if !fromModule loaded target `MoDKHProof then return \"target-missing\"\n if !theoremInfo.levelParams.isEmpty then return \"unsupported-universes\"\n let additions := loaded.constants.fold (init := ({} : Std.HashMap Name ConstantInfo)) fun acc name info =>\n if base.contains name then acc else acc.insert name info\n let env \u2190 base.replay additions\n let proof : Declaration := .thmDecl {\n name := `_modkh.checked, levelParams := [], type := expected.value, value := mkConst target }\n match env.addDeclCore 0 proof none with\n | .error _ => return \"statement-mismatch\"\n | .ok env =>\n let (_, result) := ((CollectAxioms.collect `_modkh.checked).run env).run {}\n if result.axioms.any (fun ax => !([`propext, `Classical.choice, `Quot.sound].contains ax)) then\n return \"disallowed-axioms\"\n return \"proved\"\n\ndef main (args : List String) : IO UInt32 := do\n match args with\n | [target] =>\n IO.println (\u2190 checkTarget (target.splitOn \".\" |>.foldl Name.str .anonymous))\n return 0\n | _ => return 2\n";
|
|
3
|
+
export declare function boundLeanReceipt(receipt: ExecutionReceipt): ExecutionReceipt;
|
|
4
|
+
export declare function checkLeanProof(runtime: string, dir: string, contract: Buffer, theorem: string, options: {
|
|
5
|
+
inputDigest: string;
|
|
6
|
+
timeoutMs: number;
|
|
7
|
+
comparisonTimeoutMs: number;
|
|
8
|
+
signal?: AbortSignal;
|
|
9
|
+
}): Promise<{
|
|
10
|
+
readonly proofStatus: "unverified";
|
|
11
|
+
readonly code: "TARGET_CONTRACT_NOT_CHECKED";
|
|
12
|
+
readonly contractReceipt: ExecutionReceipt;
|
|
13
|
+
} | {
|
|
14
|
+
readonly contractReceipt: ExecutionReceipt;
|
|
15
|
+
readonly proofReceipt: ExecutionReceipt;
|
|
16
|
+
readonly proofStatus: "proved";
|
|
17
|
+
readonly code: "TARGET_PROVED";
|
|
18
|
+
} | {
|
|
19
|
+
readonly contractReceipt: ExecutionReceipt;
|
|
20
|
+
readonly proofReceipt: ExecutionReceipt;
|
|
21
|
+
readonly proofStatus: "rejected";
|
|
22
|
+
readonly code: string;
|
|
23
|
+
} | {
|
|
24
|
+
readonly contractReceipt: ExecutionReceipt;
|
|
25
|
+
readonly proofReceipt: ExecutionReceipt;
|
|
26
|
+
readonly proofStatus: "unverified";
|
|
27
|
+
readonly code: "INVALID_TARGET_CONTRACT";
|
|
28
|
+
} | {
|
|
29
|
+
readonly contractReceipt: ExecutionReceipt;
|
|
30
|
+
readonly proofReceipt: ExecutionReceipt;
|
|
31
|
+
readonly proofStatus: "unverified";
|
|
32
|
+
readonly code: "UNSUPPORTED_TARGET_UNIVERSES";
|
|
33
|
+
} | {
|
|
34
|
+
readonly contractReceipt: ExecutionReceipt;
|
|
35
|
+
readonly proofReceipt: ExecutionReceipt;
|
|
36
|
+
readonly proofStatus: "unverified";
|
|
37
|
+
readonly code: "PROOF_UNVERIFIED";
|
|
38
|
+
}>;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { executeBounded, privateEnvironment } from "../lisp/runtime.js";
|
|
4
|
+
// Load data from compiled modules without enabling candidate initializers. Replay
|
|
5
|
+
// candidate declarations through the kernel before checking the expected type.
|
|
6
|
+
export const leanProofDriver = `import Lean
|
|
7
|
+
import Lean.Replay
|
|
8
|
+
open Lean
|
|
9
|
+
|
|
10
|
+
def fromModule (env : Environment) (decl mod : Name) : Bool :=
|
|
11
|
+
(env.getModuleIdxFor? decl).any fun idx => env.header.moduleNames[idx.toNat]? == some mod
|
|
12
|
+
|
|
13
|
+
def checkTarget (target : Name) : IO String := do
|
|
14
|
+
initSearchPath (← getBuildDir)
|
|
15
|
+
let base ← importModules #[{ module := \`Lean }, { module := \`MoDKHTarget }] {}
|
|
16
|
+
let loaded ← importModules #[{ module := \`Lean }, { module := \`MoDKHTarget }, { module := \`MoDKHProof }] {}
|
|
17
|
+
let some (.defnInfo expected) := base.find? \`modkhExpected | return "invalid-contract"
|
|
18
|
+
if !fromModule base \`modkhExpected \`MoDKHTarget || expected.type != mkSort .zero || !expected.levelParams.isEmpty then
|
|
19
|
+
return "invalid-contract"
|
|
20
|
+
let some (.thmInfo theoremInfo) := loaded.find? target | return "target-missing"
|
|
21
|
+
if !fromModule loaded target \`MoDKHProof then return "target-missing"
|
|
22
|
+
if !theoremInfo.levelParams.isEmpty then return "unsupported-universes"
|
|
23
|
+
let additions := loaded.constants.fold (init := ({} : Std.HashMap Name ConstantInfo)) fun acc name info =>
|
|
24
|
+
if base.contains name then acc else acc.insert name info
|
|
25
|
+
let env ← base.replay additions
|
|
26
|
+
let proof : Declaration := .thmDecl {
|
|
27
|
+
name := \`_modkh.checked, levelParams := [], type := expected.value, value := mkConst target }
|
|
28
|
+
match env.addDeclCore 0 proof none with
|
|
29
|
+
| .error _ => return "statement-mismatch"
|
|
30
|
+
| .ok env =>
|
|
31
|
+
let (_, result) := ((CollectAxioms.collect \`_modkh.checked).run env).run {}
|
|
32
|
+
if result.axioms.any (fun ax => !([\`propext, \`Classical.choice, \`Quot.sound].contains ax)) then
|
|
33
|
+
return "disallowed-axioms"
|
|
34
|
+
return "proved"
|
|
35
|
+
|
|
36
|
+
def main (args : List String) : IO UInt32 := do
|
|
37
|
+
match args with
|
|
38
|
+
| [target] =>
|
|
39
|
+
IO.println (← checkTarget (target.splitOn "." |>.foldl Name.str .anonymous))
|
|
40
|
+
return 0
|
|
41
|
+
| _ => return 2
|
|
42
|
+
`;
|
|
43
|
+
const rejections = new Map([
|
|
44
|
+
['target-missing', 'TARGET_THEOREM_MISSING'],
|
|
45
|
+
['statement-mismatch', 'TARGET_STATEMENT_MISMATCH'],
|
|
46
|
+
['disallowed-axioms', 'DISALLOWED_AXIOMS'],
|
|
47
|
+
]);
|
|
48
|
+
function cleanExit(receipt) {
|
|
49
|
+
return receipt.state === 'exited' && receipt.exitCode === 0 && receipt.cleanup === 'settled';
|
|
50
|
+
}
|
|
51
|
+
export function boundLeanReceipt(receipt) {
|
|
52
|
+
return { ...receipt, stdout: receipt.stdout.slice(0, 1024), stderr: receipt.stderr.slice(0, 1024) };
|
|
53
|
+
}
|
|
54
|
+
export async function checkLeanProof(runtime, dir, contract, theorem, options) {
|
|
55
|
+
const env = privateEnvironment(dir);
|
|
56
|
+
const processOptions = { inputDigest: options.inputDigest, signal: options.signal, cwd: dir, env, maxOutputBytes: 256 * 1024 };
|
|
57
|
+
fs.writeFileSync(path.join(dir, 'MoDKHTarget.lean'), contract, { flag: 'wx', mode: 0o600 });
|
|
58
|
+
const contractReceipt = boundLeanReceipt(await executeBounded(runtime, ['-DwarningAsError=true', '-o', 'MoDKHTarget.olean', 'MoDKHTarget.lean'], {
|
|
59
|
+
...processOptions, timeoutMs: options.timeoutMs,
|
|
60
|
+
}));
|
|
61
|
+
if (!cleanExit(contractReceipt)) {
|
|
62
|
+
return { proofStatus: 'unverified', code: 'TARGET_CONTRACT_NOT_CHECKED', contractReceipt };
|
|
63
|
+
}
|
|
64
|
+
fs.writeFileSync(path.join(dir, 'MoDKHCheck.lean'), leanProofDriver, { flag: 'wx', mode: 0o600 });
|
|
65
|
+
const proofRun = await executeBounded(runtime, ['--run', 'MoDKHCheck.lean', theorem], {
|
|
66
|
+
...processOptions, env: { ...env, LEAN_PATH: dir }, timeoutMs: options.comparisonTimeoutMs,
|
|
67
|
+
});
|
|
68
|
+
const proofReceipt = boundLeanReceipt(proofRun);
|
|
69
|
+
const receipts = { contractReceipt, proofReceipt };
|
|
70
|
+
const verdict = proofRun.stdout.trim();
|
|
71
|
+
if (cleanExit(proofReceipt)) {
|
|
72
|
+
if (verdict === 'proved')
|
|
73
|
+
return { proofStatus: 'proved', code: 'TARGET_PROVED', ...receipts };
|
|
74
|
+
const rejection = rejections.get(verdict);
|
|
75
|
+
if (rejection)
|
|
76
|
+
return { proofStatus: 'rejected', code: rejection, ...receipts };
|
|
77
|
+
if (verdict === 'invalid-contract')
|
|
78
|
+
return { proofStatus: 'unverified', code: 'INVALID_TARGET_CONTRACT', ...receipts };
|
|
79
|
+
if (verdict === 'unsupported-universes')
|
|
80
|
+
return { proofStatus: 'unverified', code: 'UNSUPPORTED_TARGET_UNIVERSES', ...receipts };
|
|
81
|
+
}
|
|
82
|
+
return { proofStatus: 'unverified', code: 'PROOF_UNVERIFIED', ...receipts };
|
|
83
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Tool, ToolCall, ToolContext, ToolResult } from '../agent/types.ts';
|
|
2
|
+
import { type BrowseTabs } from './browse.ts';
|
|
3
|
+
import type { JobRegistry } from './jobs.ts';
|
|
4
|
+
/**
|
|
5
|
+
* ツール名・引数形状・宣言外の引数を検証する。
|
|
6
|
+
* 各フィールドの値は個々のツールが boundary で検証する。
|
|
7
|
+
*/
|
|
8
|
+
export declare class ToolRegistry {
|
|
9
|
+
private tools;
|
|
10
|
+
private readonly onExecute?;
|
|
11
|
+
constructor(tools: Tool[], onExecute?: () => void);
|
|
12
|
+
specs(): {
|
|
13
|
+
name: string;
|
|
14
|
+
description: string;
|
|
15
|
+
parameters: Record<string, unknown>;
|
|
16
|
+
}[];
|
|
17
|
+
get(name: string): Tool | undefined;
|
|
18
|
+
/** Match unresolved effects conservatively. Only trusted tool code defines defaults. */
|
|
19
|
+
sameOperation(a: ToolCall, b: ToolCall, ctx: ToolContext): boolean;
|
|
20
|
+
/**
|
|
21
|
+
* モデルの要求を1件ずつ検証して実行する。
|
|
22
|
+
* 未知のツール・引数不正は結果として返す(例外を握らず、モデルに観測させる)。
|
|
23
|
+
* signal が abort された以降は新規実行しない(status:'not-executed')。
|
|
24
|
+
*/
|
|
25
|
+
executeOne(call: ToolCall, ctx: ToolContext): Promise<ToolResult>;
|
|
26
|
+
}
|
|
27
|
+
/** 初版が提供する5区分のツール群(作成/編集は別ツール)。 */
|
|
28
|
+
export declare function defaultTools(tabs?: BrowseTabs): Tool[];
|
|
29
|
+
/** The same tools plus background execution, which needs a per-session job registry. */
|
|
30
|
+
export declare function defaultToolsWithJobs(jobs: JobRegistry, tabs?: BrowseTabs): Tool[];
|