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,645 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { DEFAULT_SUBAGENT_LIMIT, parseSubagentLimit } from "./limits.js";
|
|
3
|
+
import { EditVerification } from "./verification.js";
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
5
|
+
import { runAgentLoop } from "../agent/loop.js";
|
|
6
|
+
import { ToolError } from "../agent/types.js";
|
|
7
|
+
import { ToolRegistry } from "../tools/registry.js";
|
|
8
|
+
import { SessionStore } from "../session/store.js";
|
|
9
|
+
import { PluginManager, PluginLoadInterrupted } from "../plugins/manager.js";
|
|
10
|
+
import { fields, object, text } from "../plugins/package.js";
|
|
11
|
+
import { ExternalProcesses } from "./processes.js";
|
|
12
|
+
import { parseDelegation, delegationDigest } from "./request.js";
|
|
13
|
+
import { headAssignment } from "./head-assignment.js";
|
|
14
|
+
export { parseDelegation } from "./request.js";
|
|
15
|
+
const activeRoots = new Map();
|
|
16
|
+
const orchestrationTools = new Set(['run_subagent', 'start_subagent', 'subagent_output', 'cancel_subagent', 'list_subagent_runs', 'list_subagents']);
|
|
17
|
+
// A generic writer owns the workspace; isolated edit-verify writers own exact targets.
|
|
18
|
+
const writers = new Map();
|
|
19
|
+
const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
20
|
+
function localDefinition(value) {
|
|
21
|
+
const raw = object(value);
|
|
22
|
+
fields(raw, ['system', 'tools', 'skillPolicy', 'maxTurns', 'requireAllTools', 'languageServer', 'workflow', 'verificationCommand', 'verificationManifest']);
|
|
23
|
+
const system = text(raw.system, 'system', 256 * 1024);
|
|
24
|
+
if (!Array.isArray(raw.tools) || raw.tools.length > 64 || !raw.tools.every(t => typeof t === 'string' && /^[a-z][a-z0-9_]*$/.test(t)) || new Set(raw.tools).size !== raw.tools.length)
|
|
25
|
+
throw new Error('Invalid local tool requirements');
|
|
26
|
+
if (raw.skillPolicy !== undefined && raw.skillPolicy !== 'none')
|
|
27
|
+
throw new Error('Invalid skillPolicy');
|
|
28
|
+
if (raw.maxTurns !== undefined && (!Number.isInteger(raw.maxTurns) || Number(raw.maxTurns) < 1 || Number(raw.maxTurns) > 32))
|
|
29
|
+
throw new Error('Invalid maxTurns');
|
|
30
|
+
if (raw.requireAllTools !== undefined && typeof raw.requireAllTools !== 'boolean')
|
|
31
|
+
throw new Error('Invalid requireAllTools');
|
|
32
|
+
if (raw.languageServer !== undefined && raw.languageServer !== 'tailwind')
|
|
33
|
+
throw new Error('Invalid languageServer');
|
|
34
|
+
if (raw.workflow !== undefined && raw.workflow !== 'edit-verify')
|
|
35
|
+
throw new Error('Invalid workflow');
|
|
36
|
+
return structuredClone({ ...raw, system, tools: [...raw.tools] });
|
|
37
|
+
}
|
|
38
|
+
function resultText(value) {
|
|
39
|
+
if (typeof value !== 'string' || Buffer.byteLength(value) > 65536)
|
|
40
|
+
throw new Error('Subagent result exceeds 64 KiB or is not text');
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
function waitFor(pending, signal) {
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const abort = () => reject(new Error('Subagent interrupted or timed out'));
|
|
46
|
+
if (signal.aborted)
|
|
47
|
+
abort();
|
|
48
|
+
else
|
|
49
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
50
|
+
pending.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
async function settleWithin(pending, ms) {
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
const timeout = setTimeout(() => controller.abort(), ms);
|
|
56
|
+
try {
|
|
57
|
+
return await waitFor(pending, controller.signal);
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
clearTimeout(timeout);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** The parent captures authority once. Plugins receive neither this owner nor its session. */
|
|
64
|
+
export class SubagentService {
|
|
65
|
+
opts;
|
|
66
|
+
handles = new Map();
|
|
67
|
+
notices = new Map();
|
|
68
|
+
activities = new Map();
|
|
69
|
+
limit;
|
|
70
|
+
get maxConcurrent() { return this.limit; }
|
|
71
|
+
get hasPending() { return this.handles.size > 0; }
|
|
72
|
+
get hasUnknown() {
|
|
73
|
+
return this.opts.parent.delegations().some(r => r.result?.status === 'unknown' || (!r.result && !this.handles.has(r.runId)));
|
|
74
|
+
}
|
|
75
|
+
setMaxConcurrent(value) {
|
|
76
|
+
const limit = parseSubagentLimit(value);
|
|
77
|
+
if (limit === null)
|
|
78
|
+
throw new ToolError('INVALID_ARGS', '子の同時実行数は1〜16の整数です');
|
|
79
|
+
this.limit = limit;
|
|
80
|
+
}
|
|
81
|
+
takeNotices() { const notices = [...this.notices.values()]; this.notices.clear(); return notices; }
|
|
82
|
+
async waitForChange(signal) {
|
|
83
|
+
if (this.hasPending)
|
|
84
|
+
await waitFor(Promise.race([...this.handles.values()].map(h => h.result.catch(() => undefined))), signal).catch(() => { });
|
|
85
|
+
}
|
|
86
|
+
async cancelAll(reason) {
|
|
87
|
+
await Promise.allSettled([...this.handles.values()].map(h => h.cancel(reason)));
|
|
88
|
+
}
|
|
89
|
+
runs() {
|
|
90
|
+
return this.opts.parent.delegations().map(r => ({ runId: r.runId, agentId: r.childSessionId, pluginId: r.pluginId,
|
|
91
|
+
status: this.handles.has(r.runId) ? 'running' : r.result?.status ?? 'unknown' }));
|
|
92
|
+
}
|
|
93
|
+
async output(runId, waitMs, signal) {
|
|
94
|
+
const record = this.opts.parent.delegations().find(r => r.runId === runId);
|
|
95
|
+
if (!record)
|
|
96
|
+
throw new ToolError('INVALID_ARGS', 'この親に属する実行IDではありません');
|
|
97
|
+
const handle = this.handles.get(runId);
|
|
98
|
+
if (handle && waitMs > 0)
|
|
99
|
+
await waitFor(handle.result, AbortSignal.any([signal, AbortSignal.timeout(waitMs)])).catch(() => { });
|
|
100
|
+
if (this.handles.has(runId))
|
|
101
|
+
return { runId, status: 'running' };
|
|
102
|
+
const settled = this.opts.parent.delegations().find(r => r.runId === runId);
|
|
103
|
+
this.notices.delete(runId);
|
|
104
|
+
return settled.result ?? { runId, agentId: record.childSessionId, status: 'unknown', text: '', cleanup: 'unknown', diagnostic: '保存結果がありません。自動再実行しないでください。' };
|
|
105
|
+
}
|
|
106
|
+
async cancel(runId) {
|
|
107
|
+
if (!this.opts.parent.delegations().some(r => r.runId === runId))
|
|
108
|
+
throw new ToolError('INVALID_ARGS', 'この親に属する実行IDではありません');
|
|
109
|
+
await this.handles.get(runId)?.cancel('Parent requested cancellation');
|
|
110
|
+
}
|
|
111
|
+
/** Parent reads remain usable; mutations cannot race a child writer. */
|
|
112
|
+
parentTools(tools) {
|
|
113
|
+
return tools.map(tool => tool.readOnly || tool.name === 'job_kill' ? tool : { ...tool, execute: async (args, ctx) => {
|
|
114
|
+
if (this.hasUnknown)
|
|
115
|
+
throw new ToolError('RESULT_UNKNOWN', '先行する委譲の結果が不明です。状態を確認してください');
|
|
116
|
+
if (writers.get(this.opts.root)?.size)
|
|
117
|
+
throw new ToolError('BUSY', '子が編集中です。別の読み取り・統合作業を進め、編集は結果回収後に実行してください');
|
|
118
|
+
// Reserve through async approval/execution too, so a child cannot start writing meanwhile.
|
|
119
|
+
const claim = `parent-${randomUUID()}`;
|
|
120
|
+
this.claimWriter(claim, null, false);
|
|
121
|
+
try {
|
|
122
|
+
return await tool.execute(args, ctx);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
this.releaseWriter(claim);
|
|
126
|
+
}
|
|
127
|
+
} });
|
|
128
|
+
}
|
|
129
|
+
claimWriter(id, paths, checkJobs = true) {
|
|
130
|
+
if (checkJobs && this.opts.hasBackgroundJobs?.())
|
|
131
|
+
throw new ToolError('BUSY', '親のバックグラウンドコマンドが実行中です。結果を回収してから編集を委譲してください');
|
|
132
|
+
const claims = writers.get(this.opts.root) ?? new Map();
|
|
133
|
+
for (const held of claims.values()) {
|
|
134
|
+
if (!paths || !held || paths.some(p => held.includes(p)))
|
|
135
|
+
throw new ToolError('BUSY', '編集対象が実行中の担当と競合しています。結果回収後に実行してください');
|
|
136
|
+
}
|
|
137
|
+
claims.set(id, paths);
|
|
138
|
+
writers.set(this.opts.root, claims);
|
|
139
|
+
}
|
|
140
|
+
releaseWriter(id) {
|
|
141
|
+
const claims = writers.get(this.opts.root);
|
|
142
|
+
claims?.delete(id);
|
|
143
|
+
if (!claims?.size)
|
|
144
|
+
writers.delete(this.opts.root);
|
|
145
|
+
}
|
|
146
|
+
activity(runId, status) {
|
|
147
|
+
if (status)
|
|
148
|
+
this.activities.set(runId, status);
|
|
149
|
+
else
|
|
150
|
+
this.activities.delete(runId);
|
|
151
|
+
const active = [...this.activities.values()];
|
|
152
|
+
this.opts.activity?.(active.length ? { pluginId: active.map(a => a.pluginId).join(', '), task: active.map(a => a.task).join(' / '),
|
|
153
|
+
runningCount: active.length, phase: active.length === 1 ? active[0].phase : active.map(a => `${a.pluginId}: ${a.phase}`).join(' / ') } : null);
|
|
154
|
+
}
|
|
155
|
+
constructor(options) {
|
|
156
|
+
this.limit = parseSubagentLimit(options.maxConcurrent) ?? DEFAULT_SUBAGENT_LIMIT;
|
|
157
|
+
this.opts = { ...options, root: fs.realpathSync(options.root), tools: [...options.tools] };
|
|
158
|
+
// Recovery never restarts a child. Re-supply its durable evidence once on this service's first turn.
|
|
159
|
+
const asyncCalls = new Set(options.parent.messages.flatMap(m => m.role === 'assistant'
|
|
160
|
+
? (m.toolCalls ?? []).filter(c => c.name === 'start_subagent').map(c => c.id) : []));
|
|
161
|
+
for (const record of options.parent.delegations())
|
|
162
|
+
if (asyncCalls.has(record.callId)) {
|
|
163
|
+
this.notices.set(record.runId, JSON.stringify(record.result ?? { runId: record.runId, status: 'unknown', diagnostic: '前回の子に保存結果がありません。自動再実行しないでください。' }));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
list() {
|
|
167
|
+
if (this.opts.unavailable || this.opts.parent.parentSessionId)
|
|
168
|
+
return [];
|
|
169
|
+
return this.opts.manager.discover().registry.list().filter(d => d.enabled && !this.opts.settings?.[d.id]?.disabled);
|
|
170
|
+
}
|
|
171
|
+
async start(raw, owner) {
|
|
172
|
+
let request;
|
|
173
|
+
try {
|
|
174
|
+
request = parseDelegation(raw);
|
|
175
|
+
text(owner.callId, 'call ID', 256);
|
|
176
|
+
}
|
|
177
|
+
catch (e) {
|
|
178
|
+
throw new ToolError('INVALID_ARGS', String(e));
|
|
179
|
+
}
|
|
180
|
+
const parent = this.opts.parent;
|
|
181
|
+
const requestDigest = delegationDigest(request);
|
|
182
|
+
const records = parent.delegations();
|
|
183
|
+
const prior = records.find(r => r.callId === owner.callId);
|
|
184
|
+
if (prior) {
|
|
185
|
+
if (prior.requestDigest !== requestDigest)
|
|
186
|
+
throw new ToolError('CALL_ID_CONFLICT', '同じIDで委譲内容が異なる');
|
|
187
|
+
const live = this.handles.get(prior.runId);
|
|
188
|
+
if (live)
|
|
189
|
+
return live;
|
|
190
|
+
const result = prior.result ?? { agentId: prior.childSessionId, runId: prior.runId, status: 'unknown', text: '', cleanup: 'unknown', diagnostic: '前回の委譲に結果がない。自動再実行しない。' };
|
|
191
|
+
return { agentId: result.agentId, runId: result.runId, result: Promise.resolve(result), cancel: async () => { } };
|
|
192
|
+
}
|
|
193
|
+
const rootId = parent.rootSessionId ?? parent.id;
|
|
194
|
+
const active = activeRoots.get(rootId) ?? new Set();
|
|
195
|
+
if (active.size >= this.limit)
|
|
196
|
+
throw new ToolError('CAPACITY', `同じルートの子は${this.limit}つまで。結果を回収してから起動してください`);
|
|
197
|
+
if (records.some(r => (!r.result && !active.has(r.runId)) || r.result?.status === 'unknown') || parent.unknownToolResults().some(r => ['run_subagent', 'start_subagent'].includes(r.name)))
|
|
198
|
+
throw new ToolError('RESULT_UNKNOWN', '先行する委譲の結果が不明。新しいID・別プラグインでも再送せず確認する');
|
|
199
|
+
if (owner.signal.aborted)
|
|
200
|
+
throw new ToolError('NOT_EXECUTED', '中断済み');
|
|
201
|
+
if (parent.parentSessionId)
|
|
202
|
+
throw new ToolError('DEPTH_LIMIT', '子からの再委譲はできない');
|
|
203
|
+
const descriptor = this.list().find(d => d.id === request.pluginId);
|
|
204
|
+
if (!descriptor)
|
|
205
|
+
throw new ToolError('PLUGIN_UNAVAILABLE', `利用できないプラグイン: ${request.pluginId}`);
|
|
206
|
+
const assignment = this.opts.headInputs
|
|
207
|
+
? headAssignment(this.opts.headInputs, request, descriptor.taskKind === 'edit', this.opts.headUserRequest?.())
|
|
208
|
+
: undefined;
|
|
209
|
+
const setting = this.opts.settings?.[descriptor.id];
|
|
210
|
+
const tools = this.opts.tools.filter(t => !orchestrationTools.has(t.name) && (!setting?.tools || setting.tools.includes(t.name)));
|
|
211
|
+
if (descriptor.kind === 'external' && !tools.some(t => t.name === 'run_command'))
|
|
212
|
+
throw new ToolError('DENIED', '外部エージェントにはコマンド実行権限が必要');
|
|
213
|
+
let connection;
|
|
214
|
+
try {
|
|
215
|
+
connection = descriptor.kind === 'local' ? this.opts.connection(setting?.model) : undefined;
|
|
216
|
+
}
|
|
217
|
+
catch (e) {
|
|
218
|
+
throw new ToolError('NOT_EXECUTED', `子のモデルに接続できません: ${String(e)}`);
|
|
219
|
+
}
|
|
220
|
+
if (connection?.ref.startsWith('hermes/'))
|
|
221
|
+
throw new ToolError('UNSUPPORTED_CAPABILITY', 'Hermesのサーバー側ツールはlocal子の権限制御対象外。local子としては起動しない。');
|
|
222
|
+
const controller = new AbortController();
|
|
223
|
+
const signal = AbortSignal.any([controller.signal, owner.signal]);
|
|
224
|
+
const childId = randomUUID();
|
|
225
|
+
const model = connection?.ref ?? `external/${descriptor.id}`;
|
|
226
|
+
const record = {
|
|
227
|
+
runId: randomUUID(), childSessionId: childId, parentSessionId: parent.id, rootSessionId: rootId,
|
|
228
|
+
callId: owner.callId, requestDigest, operationDigest: digest({ request, plugin: descriptor.digest, model, root: this.opts.root, tools: tools.map(t => t.name) }),
|
|
229
|
+
pluginId: descriptor.id, pluginVersion: descriptor.version, pluginDigest: descriptor.digest, apiVersion: 1,
|
|
230
|
+
model, root: this.opts.root, tools: tools.map(t => t.name), state: 'starting',
|
|
231
|
+
...(assignment ? { assignment } : {}),
|
|
232
|
+
};
|
|
233
|
+
parent.recordDelegation(record);
|
|
234
|
+
active.add(record.runId);
|
|
235
|
+
activeRoots.set(rootId, active);
|
|
236
|
+
let timeout;
|
|
237
|
+
const startPhaseDeadline = (ms, phase) => {
|
|
238
|
+
clearTimeout(timeout);
|
|
239
|
+
timeout = setTimeout(() => controller.abort(`${phase} exceeded ${ms / 1000} seconds`), ms);
|
|
240
|
+
};
|
|
241
|
+
startPhaseDeadline(120_000, 'Subagent');
|
|
242
|
+
const result = this.execute(record, request, descriptor, tools, connection, signal, startPhaseDeadline).finally(() => {
|
|
243
|
+
clearTimeout(timeout);
|
|
244
|
+
active.delete(record.runId);
|
|
245
|
+
if (!active.size)
|
|
246
|
+
activeRoots.delete(rootId);
|
|
247
|
+
this.releaseWriter(record.runId);
|
|
248
|
+
this.handles.delete(record.runId);
|
|
249
|
+
this.activity(record.runId, null);
|
|
250
|
+
});
|
|
251
|
+
const handle = {
|
|
252
|
+
agentId: childId, runId: record.runId, result,
|
|
253
|
+
cancel: async (reason) => { controller.abort(reason); await result; },
|
|
254
|
+
};
|
|
255
|
+
this.handles.set(record.runId, handle);
|
|
256
|
+
// Observe every rejection immediately; persistence failure must never be unhandled or called success.
|
|
257
|
+
void result.then(value => this.notices.set(record.runId, JSON.stringify(value)), error => this.notices.set(record.runId, JSON.stringify({ runId: record.runId, status: 'unknown', diagnostic: String(error) })));
|
|
258
|
+
return handle;
|
|
259
|
+
}
|
|
260
|
+
async execute(record, request, descriptor, tools, connection, signal, startPhaseDeadline) {
|
|
261
|
+
let lease;
|
|
262
|
+
let child;
|
|
263
|
+
let edit;
|
|
264
|
+
let processes;
|
|
265
|
+
let external;
|
|
266
|
+
let pendingExternal;
|
|
267
|
+
let result = { agentId: record.childSessionId, runId: record.runId, status: 'error', text: '', cleanup: 'settled' };
|
|
268
|
+
const activity = (phase) => this.activity(record.runId, { pluginId: descriptor.id, task: request.task, phase });
|
|
269
|
+
const stopping = () => activity('中止処理中');
|
|
270
|
+
let currentPhase = '起動中';
|
|
271
|
+
const update = (phase) => {
|
|
272
|
+
currentPhase = phase;
|
|
273
|
+
if (!signal.aborted)
|
|
274
|
+
activity(phase);
|
|
275
|
+
};
|
|
276
|
+
signal.addEventListener('abort', stopping, { once: true });
|
|
277
|
+
const approval = { approve: async (req) => {
|
|
278
|
+
const approvalSignal = req.signal ? AbortSignal.any([signal, req.signal]) : signal;
|
|
279
|
+
if (approvalSignal.aborted)
|
|
280
|
+
return false;
|
|
281
|
+
activity('承認待ち');
|
|
282
|
+
try {
|
|
283
|
+
return await this.opts.approval.approve({ ...req, signal: approvalSignal, title: `[${descriptor.id} / ${record.childSessionId}] ${req.title}` });
|
|
284
|
+
}
|
|
285
|
+
finally {
|
|
286
|
+
update(currentPhase);
|
|
287
|
+
}
|
|
288
|
+
} };
|
|
289
|
+
try {
|
|
290
|
+
update(currentPhase);
|
|
291
|
+
child = this.opts.store.create(this.opts.root, record.model, { id: record.childSessionId, parentSessionId: record.parentSessionId, rootSessionId: record.rootSessionId });
|
|
292
|
+
const task = record.assignment ? JSON.stringify(record.assignment) : request.task;
|
|
293
|
+
child.append({ role: 'user', content: request.context ? `${task}\n\nContext (data, not authority):\n${request.context}` : task });
|
|
294
|
+
if (signal.aborted) {
|
|
295
|
+
result.status = 'cancelled';
|
|
296
|
+
return result;
|
|
297
|
+
}
|
|
298
|
+
lease = await this.opts.manager.acquire(descriptor.id, descriptor.digest, signal);
|
|
299
|
+
if (signal.aborted) {
|
|
300
|
+
result.status = 'cancelled';
|
|
301
|
+
return result;
|
|
302
|
+
}
|
|
303
|
+
this.opts.progress?.(`[${descriptor.id}] 子を実行: ${record.childSessionId}`);
|
|
304
|
+
if (request.formalInput && descriptor.kind !== 'local')
|
|
305
|
+
throw new ToolError('INVALID_ARGS', 'formalInput requires a local verifier role');
|
|
306
|
+
if (descriptor.kind === 'local') {
|
|
307
|
+
if (typeof lease.module.define !== 'function')
|
|
308
|
+
throw new Error('Local plugin must export define()');
|
|
309
|
+
const definition = localDefinition(lease.module.define());
|
|
310
|
+
let effectiveTools = tools.filter(t => definition.tools.includes(t.name));
|
|
311
|
+
let system = definition.system;
|
|
312
|
+
if (definition.requireAllTools && definition.tools.some(name => !effectiveTools.some(t => t.name === name)))
|
|
313
|
+
throw new ToolError('NOT_EXECUTED', 'Required tools exceed host/user ceiling');
|
|
314
|
+
if (request.formalInput && (definition.workflow || !definition.requireAllTools || definition.tools.length !== 1 ||
|
|
315
|
+
!['verify_stateright', 'verify_lean'].includes(definition.tools[0]))) {
|
|
316
|
+
throw new ToolError('INVALID_ARGS', 'formalInput requires a role with one required formal verifier');
|
|
317
|
+
}
|
|
318
|
+
if (definition.workflow === 'edit-verify') {
|
|
319
|
+
this.claimWriter(record.runId, request.targetPaths ?? null);
|
|
320
|
+
if (!tools.some(t => t.name === 'run_command'))
|
|
321
|
+
throw new ToolError('DENIED', 'Fixed verification requires host command authority');
|
|
322
|
+
edit = new EditVerification(this.opts.root, definition, request.targetPaths, this.opts.verificationIsolation);
|
|
323
|
+
effectiveTools = edit.tools();
|
|
324
|
+
system += `\n\nHost edit-verify workflow (applies to this assignment): Read and edit only these exact source paths: ${JSON.stringify(request.targetPaths)}. Do not read protected tests or other files. The host runs the fixed acceptance test on your staged candidate. Do not attempt to run tests or commands. Where general coding instructions call for reading or running tests, use the acceptance criteria in the assignment and leave test execution to the host. As soon as a candidate is staged the host checks it. Use edit_file promptly. Implement the delegated responsibility on the supplied source. Use the original userRequest to resolve any ambiguity in the delegated summary. Check both changed and preserved behavior before editing.`;
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
if (request.targetPaths)
|
|
328
|
+
throw new ToolError('INVALID_ARGS', 'targetPaths applies only to edit-verify');
|
|
329
|
+
if (effectiveTools.some(t => !t.readOnly))
|
|
330
|
+
this.claimWriter(record.runId, null);
|
|
331
|
+
}
|
|
332
|
+
if (definition.languageServer)
|
|
333
|
+
effectiveTools = effectiveTools.map(tool => ({ ...tool, execute: async (args, ctx) => {
|
|
334
|
+
if (args.server !== undefined && args.server !== definition.languageServer)
|
|
335
|
+
throw new ToolError('DENIED', 'Contradictory language server selector');
|
|
336
|
+
return tool.execute({ ...args, server: definition.languageServer }, ctx);
|
|
337
|
+
} }));
|
|
338
|
+
effectiveTools = effectiveTools.map(tool => tool.readOnly ? tool : { ...tool, execute: async (args, ctx) => {
|
|
339
|
+
if (this.hasUnknown)
|
|
340
|
+
throw new ToolError('RESULT_UNKNOWN', '別の子の結果が不明です。状態を確認してください');
|
|
341
|
+
return tool.execute(args, ctx);
|
|
342
|
+
} });
|
|
343
|
+
record.effectiveTools = effectiveTools.map(t => t.name);
|
|
344
|
+
this.opts.parent.recordDelegation({ ...record, state: 'running' });
|
|
345
|
+
if (request.formalInput) {
|
|
346
|
+
const name = definition.tools[0];
|
|
347
|
+
if (request.formalInput.config !== undefined) {
|
|
348
|
+
throw new ToolError('INVALID_ARGS', 'Formal verifiers accept only formalInput.path; Stateright uses one JSON model');
|
|
349
|
+
}
|
|
350
|
+
signal.throwIfAborted();
|
|
351
|
+
if (name === 'verify_lean')
|
|
352
|
+
startPhaseDeadline(150_000, 'Host Lean verification');
|
|
353
|
+
update('検証中');
|
|
354
|
+
const call = { id: randomUUID(), name, args: request.formalInput };
|
|
355
|
+
child.append({ role: 'assistant', content: '', toolCalls: [call] });
|
|
356
|
+
const receipt = await new ToolRegistry(effectiveTools).executeOne(call, { root: this.opts.root, signal, approval });
|
|
357
|
+
child.append({ role: 'tool', results: [receipt] });
|
|
358
|
+
result.formalEvidence = [{ name, status: receipt.status, output: receipt.output.slice(0, 32768) }];
|
|
359
|
+
result.status = receipt.status === 'ok' ? 'completed' : receipt.status === 'unknown' ? 'unknown' : signal.aborted ? 'cancelled' : 'error';
|
|
360
|
+
return result;
|
|
361
|
+
}
|
|
362
|
+
if (!connection)
|
|
363
|
+
throw new Error('Missing model connection');
|
|
364
|
+
const model = connection.create();
|
|
365
|
+
const editor = edit;
|
|
366
|
+
const messages = child.messages;
|
|
367
|
+
const toolReceipts = () => messages.flatMap(m => m.role === 'tool' ? m.results : []);
|
|
368
|
+
if (editor && record.assignment) {
|
|
369
|
+
const call = { id: randomUUID(), name: 'read_file', args: { path: request.targetPaths[0], limit: 120 } };
|
|
370
|
+
child.append({ role: 'assistant', content: '', toolCalls: [call] });
|
|
371
|
+
const receipt = await new ToolRegistry(effectiveTools).executeOne(call, { root: editor.root, signal, approval });
|
|
372
|
+
child.append({ role: 'tool', results: [receipt] });
|
|
373
|
+
}
|
|
374
|
+
const missingRequiredTools = () => {
|
|
375
|
+
if (!definition.requireAllTools)
|
|
376
|
+
return false;
|
|
377
|
+
const receipts = toolReceipts();
|
|
378
|
+
return definition.tools.some(name => !receipts.some(r => r.name === name && r.status === 'ok')) ||
|
|
379
|
+
receipts.some(r => r.status !== 'ok');
|
|
380
|
+
};
|
|
381
|
+
const requiredToolError = 'Required tool evidence missing or failed; model completion is not acceptance';
|
|
382
|
+
let lastChecked;
|
|
383
|
+
const checkCandidate = async () => {
|
|
384
|
+
if (!editor?.hasChanges())
|
|
385
|
+
return;
|
|
386
|
+
if (missingRequiredTools())
|
|
387
|
+
return { outcome: 'error', errorMessage: requiredToolError };
|
|
388
|
+
const digest = editor.sourceDigest();
|
|
389
|
+
if (digest === lastChecked)
|
|
390
|
+
return;
|
|
391
|
+
lastChecked = digest;
|
|
392
|
+
startPhaseDeadline(60_000, 'Host acceptance');
|
|
393
|
+
update('検証中');
|
|
394
|
+
const verification = await editor.verify(approval, signal, true);
|
|
395
|
+
result.verification = verification;
|
|
396
|
+
if (verification.receipt?.cleanup === 'unknown')
|
|
397
|
+
result.cleanup = 'unknown';
|
|
398
|
+
if (verification.status === 'passed')
|
|
399
|
+
return { outcome: 'complete' };
|
|
400
|
+
if (verification.status === 'failed' && result.cleanup === 'settled') {
|
|
401
|
+
return { continueWith: '(ホストの保護テスト) この変更候補は不合格で、作業ツリーには反映されていません。同じ対象を続けて修正してください。現在の候補と依頼の期待結果を照らし合わせ、境界値と正常系を満たすよう edit_file を呼んでください。' };
|
|
402
|
+
}
|
|
403
|
+
return { outcome: 'error', errorMessage: 'Host acceptance did not complete' };
|
|
404
|
+
};
|
|
405
|
+
const outcome = await runAgentLoop(child.messages, {
|
|
406
|
+
model, registry: new ToolRegistry(effectiveTools), root: edit?.root ?? this.opts.root,
|
|
407
|
+
skills: definition.skillPolicy !== 'none', maxTurns: definition.maxTurns,
|
|
408
|
+
system, signal, approval, checkpoint: () => child.persistFrom(0),
|
|
409
|
+
...(editor ? { afterToolBatch: checkCandidate, beforeComplete: async () => {
|
|
410
|
+
if (editor.hasChanges()) {
|
|
411
|
+
return { continueWith: '(ホストの編集完了確認) 不合格の変更候補が残っています。同じ対象に修正を加えてください。' };
|
|
412
|
+
}
|
|
413
|
+
if (toolReceipts().some(receipt => receipt.status !== 'ok')) {
|
|
414
|
+
return { errorMessage: 'The editor did not change the source and a tool call failed' };
|
|
415
|
+
}
|
|
416
|
+
return { continueWith: '(ホストの編集完了確認) 対象ソースに変更がありません。同じ作業を続け、今の依頼に必要な最小の変更を edit_file で対象に適用してください。対象の読み取り結果は履歴にあります。変更後は応答を終えてください。ホストが保護テストを実行します。' };
|
|
417
|
+
} } : {}),
|
|
418
|
+
hooks: {
|
|
419
|
+
onModelRequest: () => {
|
|
420
|
+
if (editor)
|
|
421
|
+
startPhaseDeadline(120_000, 'Editor turn');
|
|
422
|
+
update('モデル応答を待機中');
|
|
423
|
+
},
|
|
424
|
+
onUsage: this.opts.onUsage,
|
|
425
|
+
onModelActivity: stage => update(stage === 'accepted' ? 'サーバーが要求を受理' : stage === 'reasoning' ? '推論中' : 'ツール要求を受信中'),
|
|
426
|
+
onText: () => update('応答を受信中'),
|
|
427
|
+
onToolStart: () => update('ツールを実行中'),
|
|
428
|
+
onToolResult: () => update('ツール結果を処理中'),
|
|
429
|
+
onSkillContext: context => {
|
|
430
|
+
for (const warning of context.warnings)
|
|
431
|
+
this.opts.progress?.(`[${descriptor.id}] スキル: ${warning}`);
|
|
432
|
+
},
|
|
433
|
+
},
|
|
434
|
+
});
|
|
435
|
+
const last = [...child.messages].reverse().find(m => m.role === 'assistant');
|
|
436
|
+
result.text = resultText(last?.role === 'assistant' ? last.content : '');
|
|
437
|
+
result.status = child.unknownToolResults().length ? 'unknown' : outcome.outcome === 'complete' ? 'completed' : outcome.outcome === 'interrupted' ? 'cancelled' : 'error';
|
|
438
|
+
result.diagnostic = outcome.errorMessage;
|
|
439
|
+
if (editor && result.status === 'error' && outcome.outcome === 'turn-limit' && !editor.hasChanges()) {
|
|
440
|
+
result.code = 'EDIT_TURN_LIMIT';
|
|
441
|
+
}
|
|
442
|
+
const receipts = toolReceipts();
|
|
443
|
+
result.formalEvidence = receipts.filter(r => r.name === 'verify_stateright' || r.name === 'verify_lean').slice(-8).map(r => ({ name: r.name, status: r.status, output: r.output.slice(0, 32768) }));
|
|
444
|
+
if (missingRequiredTools()) {
|
|
445
|
+
if (result.status === 'completed')
|
|
446
|
+
result.status = 'error';
|
|
447
|
+
result.diagnostic ??= requiredToolError;
|
|
448
|
+
}
|
|
449
|
+
if (result.verification?.status === 'unknown')
|
|
450
|
+
result.status = 'unknown';
|
|
451
|
+
if (signal.aborted)
|
|
452
|
+
result.diagnostic ??= String(signal.reason);
|
|
453
|
+
}
|
|
454
|
+
else {
|
|
455
|
+
this.claimWriter(record.runId, null);
|
|
456
|
+
this.opts.parent.recordDelegation({ ...record, state: 'running' });
|
|
457
|
+
if (typeof lease.module.start !== 'function')
|
|
458
|
+
throw new Error('External plugin must export start(request, host)');
|
|
459
|
+
const accepted = await approval.approve({ kind: 'command', title: '外部エージェントを開始', detail: `${descriptor.id}\n${request.task}\n外部側の権限とリモート処理の停止はMODKHでは保証できません。プロセス起動にはさらに個別承認が必要です。` });
|
|
460
|
+
if (!accepted || signal.aborted) {
|
|
461
|
+
result.status = signal.aborted ? 'cancelled' : 'error';
|
|
462
|
+
result.diagnostic = '外部実行は承認されませんでした';
|
|
463
|
+
return result;
|
|
464
|
+
}
|
|
465
|
+
update('外部の応答を待機中');
|
|
466
|
+
processes = new ExternalProcesses(this.opts.root, approval, child, signal);
|
|
467
|
+
const start = lease.module.start.bind(lease.module);
|
|
468
|
+
const externalRequest = Object.freeze({ task: request.task, ...(request.context === undefined ? {} : { context: request.context }) });
|
|
469
|
+
const host = Object.freeze({ signal: processes.signal, run: processes.run.bind(processes) });
|
|
470
|
+
// Capture synchronous throws as startup rejections too, without deferring
|
|
471
|
+
// invocation past the approval/Stop check above.
|
|
472
|
+
pendingExternal = (async () => start(externalRequest, host))();
|
|
473
|
+
external = await waitFor(pendingExternal, signal);
|
|
474
|
+
if (!external || typeof external.stop !== 'function' || !external.result || typeof external.result.then !== 'function')
|
|
475
|
+
throw new Error('Invalid external run handle');
|
|
476
|
+
const output = object(await waitFor(external.result, signal));
|
|
477
|
+
fields(output, ['text']);
|
|
478
|
+
result.text = resultText(output.text);
|
|
479
|
+
child.append({ role: 'assistant', content: result.text });
|
|
480
|
+
result.status = 'completed';
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
catch (e) {
|
|
484
|
+
result.status = e instanceof ToolError ? 'error' : 'unknown';
|
|
485
|
+
if (e instanceof PluginLoadInterrupted)
|
|
486
|
+
result.cleanup = 'unknown';
|
|
487
|
+
result.diagnostic = String(e);
|
|
488
|
+
}
|
|
489
|
+
finally {
|
|
490
|
+
update('終了処理中');
|
|
491
|
+
if (edit && result.cleanup === 'settled' && result.verification?.receipt?.cleanup !== 'unknown') {
|
|
492
|
+
try {
|
|
493
|
+
edit.close();
|
|
494
|
+
}
|
|
495
|
+
catch (e) {
|
|
496
|
+
result.status = 'unknown';
|
|
497
|
+
result.diagnostic = `Snapshot cleanup failed: ${String(e)}`;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (signal.aborted) {
|
|
501
|
+
try {
|
|
502
|
+
this.opts.parent.recordDelegation({ ...record, state: 'stopping' });
|
|
503
|
+
}
|
|
504
|
+
catch (e) {
|
|
505
|
+
result.status = 'unknown';
|
|
506
|
+
result.diagnostic = String(e);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (processes) {
|
|
510
|
+
try {
|
|
511
|
+
await processes.close();
|
|
512
|
+
}
|
|
513
|
+
catch (e) {
|
|
514
|
+
result.status = 'unknown';
|
|
515
|
+
result.cleanup = 'unknown';
|
|
516
|
+
result.diagnostic = String(e);
|
|
517
|
+
}
|
|
518
|
+
if (processes.outcomes.some(r => r.status === 'unknown'))
|
|
519
|
+
result.status = 'unknown';
|
|
520
|
+
else if (result.status === 'completed' && processes.outcomes.some(r => r.status !== 'ok'))
|
|
521
|
+
result.status = 'error';
|
|
522
|
+
}
|
|
523
|
+
if (pendingExternal && !external) {
|
|
524
|
+
try {
|
|
525
|
+
external = await settleWithin(pendingExternal, 3000);
|
|
526
|
+
if (!external)
|
|
527
|
+
throw new Error('External startup returned no run handle');
|
|
528
|
+
}
|
|
529
|
+
catch (e) {
|
|
530
|
+
result.status = 'unknown';
|
|
531
|
+
result.cleanup = 'unknown';
|
|
532
|
+
result.diagnostic = `External startup did not settle: ${String(e)}`;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (external) {
|
|
536
|
+
try {
|
|
537
|
+
await settleWithin(Promise.resolve(external.stop()), 3000);
|
|
538
|
+
}
|
|
539
|
+
catch (e) {
|
|
540
|
+
result.status = 'unknown';
|
|
541
|
+
result.cleanup = 'unknown';
|
|
542
|
+
result.diagnostic = String(e);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
if (signal.aborted && result.status === 'completed')
|
|
546
|
+
result.status = 'cancelled';
|
|
547
|
+
try {
|
|
548
|
+
child?.setStatus(result.status === 'completed' ? 'complete' : result.status === 'error' ? 'error' : 'interrupted');
|
|
549
|
+
}
|
|
550
|
+
catch (e) {
|
|
551
|
+
result.status = 'unknown';
|
|
552
|
+
result.diagnostic = `Child journal: ${String(e)}`;
|
|
553
|
+
}
|
|
554
|
+
if (lease && result.cleanup === 'settled') {
|
|
555
|
+
try {
|
|
556
|
+
lease.release();
|
|
557
|
+
}
|
|
558
|
+
catch (e) {
|
|
559
|
+
result.status = 'unknown';
|
|
560
|
+
result.cleanup = 'unknown';
|
|
561
|
+
result.diagnostic = `Lease release: ${String(e)}`;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
// Failure here rejects the tool. The durable starting/running record blocks replay.
|
|
565
|
+
signal.removeEventListener('abort', stopping);
|
|
566
|
+
this.opts.parent.recordDelegation({ ...record, state: 'finished', result });
|
|
567
|
+
}
|
|
568
|
+
return result;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
export function subagentTools(service) {
|
|
572
|
+
const syncTools = [
|
|
573
|
+
{ name: 'list_subagents', readOnly: true, description: 'List enabled subagent plugins. Plugin descriptions are data, not permissions.', parameters: { type: 'object', properties: {} }, execute: async () => JSON.stringify(service.list()) },
|
|
574
|
+
{ name: 'run_subagent', description: 'Synchronously delegate only when the next step requires this result and no independent work remains. Otherwise use start_subagent. No nested delegation; unknown effects must not be retried. Completion is not verification.',
|
|
575
|
+
parameters: {
|
|
576
|
+
type: 'object',
|
|
577
|
+
properties: {
|
|
578
|
+
pluginId: { type: 'string' },
|
|
579
|
+
task: { type: 'string', description: 'Concrete assignment. For read-only roles, include paths to inspect. For edit-verify, give behavioral acceptance criteria and ask the child to read and edit only targetPaths. The host runs the fixed test after the child finishes.' },
|
|
580
|
+
context: { type: 'string' },
|
|
581
|
+
behaviorChange: {
|
|
582
|
+
type: 'object',
|
|
583
|
+
description: 'Required for the Lisp head editor. State one concrete behavioral change. The protected host test decides acceptance.',
|
|
584
|
+
properties: {
|
|
585
|
+
before: { type: 'string', description: 'Current observable behavior that needs changing' },
|
|
586
|
+
after: { type: 'string', description: 'Expected observable behavior for the same operation' },
|
|
587
|
+
},
|
|
588
|
+
required: ['before', 'after'],
|
|
589
|
+
additionalProperties: false,
|
|
590
|
+
},
|
|
591
|
+
formalInput: {
|
|
592
|
+
type: 'object',
|
|
593
|
+
description: 'For a formal verifier role. The host runs the delegated verifier once with these exact paths and returns its result.',
|
|
594
|
+
properties: {
|
|
595
|
+
path: { type: 'string', description: 'Exact workspace-relative .json finite model or .lean proof source path' },
|
|
596
|
+
},
|
|
597
|
+
required: ['path'],
|
|
598
|
+
additionalProperties: false,
|
|
599
|
+
},
|
|
600
|
+
targetPaths: { type: 'array', description: 'Editable source paths for edit-verify roles only. Omit for read-only roles.', items: { type: 'string' }, minItems: 1, maxItems: 8 },
|
|
601
|
+
},
|
|
602
|
+
required: ['pluginId', 'task'],
|
|
603
|
+
},
|
|
604
|
+
operationIdentity: () => 'delegation-in-this-parent',
|
|
605
|
+
execute: async (args, ctx) => {
|
|
606
|
+
if (!ctx.callId || !ctx.signal)
|
|
607
|
+
throw new ToolError('NOT_EXECUTED', 'Missing host execution identity');
|
|
608
|
+
const handle = await service.start(args, { callId: ctx.callId, signal: ctx.signal });
|
|
609
|
+
const result = await handle.result;
|
|
610
|
+
await service.output(handle.runId, 0, ctx.signal);
|
|
611
|
+
return { status: result.status === 'completed' ? 'ok' : result.status === 'unknown' ? 'unknown' : 'error', output: JSON.stringify(result) };
|
|
612
|
+
},
|
|
613
|
+
},
|
|
614
|
+
];
|
|
615
|
+
const run = syncTools[1];
|
|
616
|
+
return [...syncTools,
|
|
617
|
+
{ ...run, name: 'start_subagent', description: 'Start an independent bounded assignment and immediately return its runId. Keep your own work and coordinate other children. Collect results with subagent_output; stop with cancel_subagent. Never delegate merely to wait. Slots are limited; completion is not verification.',
|
|
618
|
+
execute: async (args, ctx) => {
|
|
619
|
+
if (!ctx.callId || !ctx.signal)
|
|
620
|
+
throw new ToolError('NOT_EXECUTED', 'Missing host execution identity');
|
|
621
|
+
const handle = await service.start(args, { callId: ctx.callId, signal: ctx.signal });
|
|
622
|
+
return JSON.stringify({ runId: handle.runId, agentId: handle.agentId, status: 'started', maxConcurrent: service.maxConcurrent });
|
|
623
|
+
} },
|
|
624
|
+
{ name: 'list_subagent_runs', readOnly: true, description: 'List this parent’s live and saved child runs and the child slot limit.', parameters: { type: 'object', properties: {} },
|
|
625
|
+
execute: async () => JSON.stringify({ maxConcurrent: service.maxConcurrent, runs: service.runs() }) },
|
|
626
|
+
{ name: 'subagent_output', readOnly: true, description: 'Collect a child result by runId. Returns running immediately by default. Wait only when no independent work remains; waitMs is bounded to 60000. Results survive restart and are never re-executed.',
|
|
627
|
+
parameters: { type: 'object', properties: { runId: { type: 'string' }, waitMs: { type: 'integer', minimum: 0, maximum: 60000 } }, required: ['runId'] },
|
|
628
|
+
execute: async (args, ctx) => {
|
|
629
|
+
const runId = text(args.runId, 'runId', 256);
|
|
630
|
+
const waitMs = args.waitMs ?? 0;
|
|
631
|
+
if (typeof waitMs !== 'number' || !Number.isInteger(waitMs) || waitMs < 0 || waitMs > 60000)
|
|
632
|
+
throw new ToolError('INVALID_ARGS', 'waitMs must be 0..60000');
|
|
633
|
+
const result = await service.output(runId, waitMs, ctx.signal ?? new AbortController().signal);
|
|
634
|
+
return { status: result.status === 'unknown' ? 'unknown' : 'ok', output: JSON.stringify(result) };
|
|
635
|
+
} },
|
|
636
|
+
{ name: 'cancel_subagent', description: 'Stop one owned child and wait for its cleanup. Other children and parent work continue.',
|
|
637
|
+
parameters: { type: 'object', properties: { runId: { type: 'string' } }, required: ['runId'] },
|
|
638
|
+
execute: async (args, ctx) => {
|
|
639
|
+
const runId = text(args.runId, 'runId', 256);
|
|
640
|
+
await service.cancel(runId);
|
|
641
|
+
const result = await service.output(runId, 0, ctx.signal ?? new AbortController().signal);
|
|
642
|
+
return { status: result.status === 'unknown' ? 'unknown' : 'ok', output: JSON.stringify(result) };
|
|
643
|
+
} },
|
|
644
|
+
];
|
|
645
|
+
}
|