modkh 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +42 -0
  2. package/dist/agent/bundled-skills.d.ts +1 -1
  3. package/dist/agent/bundled-skills.js +1 -1
  4. package/dist/agent/compaction.d.ts +53 -0
  5. package/dist/agent/compaction.js +191 -0
  6. package/dist/agent/loop.d.ts +55 -8
  7. package/dist/agent/loop.js +119 -7
  8. package/dist/agent/skills.d.ts +7 -1
  9. package/dist/agent/skills.js +26 -5
  10. package/dist/agent/types.d.ts +14 -9
  11. package/dist/cli/agenticreplay.d.ts +1 -0
  12. package/dist/cli/agenticreplay.js +66 -0
  13. package/dist/cli/answer-markdown.d.ts +3 -0
  14. package/dist/cli/answer-markdown.js +29 -0
  15. package/dist/cli/approval.d.ts +2 -0
  16. package/dist/cli/approval.js +35 -5
  17. package/dist/cli/catalog.d.ts +30 -32
  18. package/dist/cli/catalog.js +37 -67
  19. package/dist/cli/chat.js +406 -78
  20. package/dist/cli/clipboard.d.ts +2 -0
  21. package/dist/cli/clipboard.js +28 -0
  22. package/dist/cli/color.d.ts +20 -3
  23. package/dist/cli/color.js +87 -19
  24. package/dist/cli/compaction-settings.d.ts +21 -0
  25. package/dist/cli/compaction-settings.js +54 -0
  26. package/dist/cli/completion-art.d.ts +2 -0
  27. package/dist/cli/completion-art.js +62 -0
  28. package/dist/cli/config.d.ts +9 -0
  29. package/dist/cli/config.js +5 -1
  30. package/dist/cli/editor.d.ts +7 -0
  31. package/dist/cli/editor.js +43 -5
  32. package/dist/cli/file-mentions.d.ts +14 -0
  33. package/dist/cli/file-mentions.js +141 -0
  34. package/dist/cli/head-checks.d.ts +41 -0
  35. package/dist/cli/head-checks.js +146 -0
  36. package/dist/cli/initial-connection.d.ts +7 -0
  37. package/dist/cli/initial-connection.js +20 -0
  38. package/dist/cli/keys.d.ts +12 -1
  39. package/dist/cli/keys.js +29 -4
  40. package/dist/cli/model-catalog.d.ts +16 -0
  41. package/dist/cli/model-catalog.js +130 -0
  42. package/dist/cli/models.d.ts +2 -2
  43. package/dist/cli/models.js +51 -19
  44. package/dist/cli/official-models.d.ts +6 -0
  45. package/dist/cli/official-models.js +77 -0
  46. package/dist/cli/pdf.d.ts +8 -0
  47. package/dist/cli/pdf.js +71 -0
  48. package/dist/cli/providers.d.ts +6 -42
  49. package/dist/cli/providers.js +44 -38
  50. package/dist/cli/shell-display.d.ts +6 -0
  51. package/dist/cli/shell-display.js +35 -0
  52. package/dist/cli/stateright.d.ts +1 -0
  53. package/dist/cli/stateright.js +37 -0
  54. package/dist/cli/terminal-mouse.d.ts +21 -0
  55. package/dist/cli/terminal-mouse.js +51 -0
  56. package/dist/cli/terminal.d.ts +95 -7
  57. package/dist/cli/terminal.js +783 -108
  58. package/dist/cli/tool-display.d.ts +9 -0
  59. package/dist/cli/tool-display.js +87 -0
  60. package/dist/cli/transcript-selection.d.ts +22 -0
  61. package/dist/cli/transcript-selection.js +75 -0
  62. package/dist/cli/usage.d.ts +9 -16
  63. package/dist/cli/usage.js +60 -18
  64. package/dist/cli/waiting-nyan.d.ts +3 -0
  65. package/dist/cli/waiting-nyan.js +17 -0
  66. package/dist/cli/waiting-whales.d.ts +3 -0
  67. package/dist/cli/waiting-whales.js +24 -0
  68. package/dist/index.js +30 -8
  69. package/dist/language/commonlisp-install.d.ts +1 -0
  70. package/dist/language/commonlisp-install.js +3 -2
  71. package/dist/language/lsp/client.js +4 -1
  72. package/dist/language/lsp/pool.d.ts +8 -0
  73. package/dist/language/lsp/pool.js +21 -3
  74. package/dist/language/lsp/service.d.ts +8 -4
  75. package/dist/language/lsp/service.js +51 -15
  76. package/dist/language/syntax/parser.d.ts +10 -1
  77. package/dist/language/syntax/parser.js +34 -16
  78. package/dist/lisp/builtin-agents.d.ts +5 -0
  79. package/dist/lisp/builtin-agents.js +52 -0
  80. package/dist/lisp/config.d.ts +9 -0
  81. package/dist/lisp/config.js +50 -7
  82. package/dist/lisp/routing.js +2 -2
  83. package/dist/lisp/runtime.d.ts +5 -0
  84. package/dist/lisp/runtime.js +26 -2
  85. package/dist/model/ai-sdk.js +13 -8
  86. package/dist/model/chatgpt/login.js +1 -1
  87. package/dist/model/chatgpt/responses.js +56 -4
  88. package/dist/model/connection.js +2 -0
  89. package/dist/model/context-window.d.ts +3 -0
  90. package/dist/model/context-window.js +64 -0
  91. package/dist/model/context.d.ts +3 -1
  92. package/dist/model/context.js +24 -24
  93. package/dist/model/factory.d.ts +3 -1
  94. package/dist/model/factory.js +28 -27
  95. package/dist/model/harness-profile.d.ts +6 -0
  96. package/dist/model/harness-profile.js +23 -0
  97. package/dist/model/providers.d.ts +32 -0
  98. package/dist/model/providers.js +72 -0
  99. package/dist/model/reasoning.d.ts +3 -3
  100. package/dist/model/reasoning.js +30 -8
  101. package/dist/model/record-fetch.d.ts +2 -0
  102. package/dist/model/record-fetch.js +19 -0
  103. package/dist/plugins/manager.d.ts +2 -1
  104. package/dist/plugins/manager.js +21 -2
  105. package/dist/session/store.d.ts +11 -0
  106. package/dist/session/store.js +27 -1
  107. package/dist/subagents/head-assignment.d.ts +11 -0
  108. package/dist/subagents/head-assignment.js +47 -0
  109. package/dist/subagents/limits.d.ts +4 -0
  110. package/dist/subagents/limits.js +6 -0
  111. package/dist/subagents/request.js +18 -1
  112. package/dist/subagents/service.d.ts +36 -2
  113. package/dist/subagents/service.js +331 -38
  114. package/dist/subagents/types.d.ts +20 -0
  115. package/dist/subagents/verification.d.ts +5 -2
  116. package/dist/subagents/verification.js +59 -22
  117. package/dist/tools/browse.d.ts +13 -0
  118. package/dist/tools/browse.js +117 -0
  119. package/dist/tools/browser-capability.d.ts +3 -0
  120. package/dist/tools/browser-capability.js +29 -0
  121. package/dist/tools/formal-input.d.ts +6 -0
  122. package/dist/tools/formal-input.js +29 -0
  123. package/dist/tools/formal.d.ts +3 -2
  124. package/dist/tools/formal.js +54 -52
  125. package/dist/tools/jobs.d.ts +2 -0
  126. package/dist/tools/jobs.js +5 -0
  127. package/dist/tools/language.js +25 -27
  128. package/dist/tools/lean-proof.d.ts +38 -0
  129. package/dist/tools/lean-proof.js +83 -0
  130. package/dist/tools/registry.d.ts +5 -3
  131. package/dist/tools/registry.js +13 -5
  132. package/dist/tools/run.js +13 -9
  133. package/dist/tools/shell-process.js +17 -6
  134. package/dist/tools/stateright-runtime.d.ts +3 -0
  135. package/dist/tools/stateright-runtime.js +16 -0
  136. package/dist/tools/stateright.d.ts +3 -0
  137. package/dist/tools/stateright.js +78 -0
  138. package/dist/tools/web.js +7 -2
  139. package/dist/version.d.ts +2 -0
  140. package/dist/version.js +2 -0
  141. package/docs/commonlisp-build-output.md +14 -0
  142. package/docs/context-efficiency.md +25 -3
  143. package/docs/input.md +63 -3
  144. package/docs/languages.md +3 -3
  145. package/docs/models.md +30 -6
  146. package/docs/modkh.md +11 -7
  147. package/docs/presets.md +45 -0
  148. package/docs/setup.md +3 -16
  149. package/docs/stateright.md +45 -0
  150. package/docs/subagents.md +21 -3
  151. package/docs/web.md +1 -1
  152. package/experiments/presets/formal.lisp +15 -4
  153. package/experiments/presets/language-microagents.lisp +29 -0
  154. package/native/stateright/Cargo.lock +478 -0
  155. package/native/stateright/Cargo.toml +11 -0
  156. package/native/stateright/src/lib.rs +163 -0
  157. package/native/stateright/src/main.rs +38 -0
  158. package/package.json +10 -2
@@ -0,0 +1,19 @@
1
+ let recordingProxy;
2
+ export function configureHttpModelRecording(proxyUrl) {
3
+ const proxy = URL.parse(proxyUrl ?? '');
4
+ recordingProxy = proxy?.protocol === 'http:' && proxy.hostname === '127.0.0.1' &&
5
+ !proxy.username && !proxy.password ? proxy.origin : undefined;
6
+ }
7
+ export const fetchModel = (input, init) => {
8
+ if (!recordingProxy)
9
+ return fetch(input, init);
10
+ const request = input instanceof Request ? input : undefined;
11
+ const method = init?.method ?? request?.method;
12
+ const target = URL.parse(request?.url ?? String(input));
13
+ if (method?.toUpperCase() !== 'POST' || target?.protocol !== 'http:' ||
14
+ target.username || target.password || target.origin === recordingProxy)
15
+ return fetch(input, init);
16
+ // AgenticReplay restores this origin upstream. Keep the endpoint path outside the encoded segment.
17
+ const destination = `${recordingProxy}/forward/${encodeURIComponent(target.origin)}${target.pathname}${target.search}`;
18
+ return fetch(request ? new Request(destination, request) : destination, init);
19
+ };
@@ -12,7 +12,8 @@ export declare class PluginLoadInterrupted extends Error {
12
12
  export declare class PluginManager {
13
13
  readonly home: string;
14
14
  readonly builtinDir: string;
15
- constructor(home?: string, builtinDir?: string);
15
+ private readonly stateright?;
16
+ constructor(home?: string, builtinDir?: string, stateright?: string);
16
17
  private sessionEntries;
17
18
  registerSessionDefinitions(entries: SessionDefinition[], sourceDigest: string): void;
18
19
  private base;
@@ -12,6 +12,8 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
12
12
  import { randomUUID } from 'node:crypto';
13
13
  import { configDir } from "../cli/config.js";
14
14
  import { fields, inspectPackage, object, pluginId } from "./package.js";
15
+ import { findStateright } from "../tools/stateright-runtime.js";
16
+ import { builtinMicroagents, staterightMicroagent } from "../lisp/builtin-agents.js";
15
17
  import { SubagentRegistry } from "./registry.js";
16
18
  const EMPTY = () => ({ version: 1, plugins: Object.create(null), disabledBuiltins: [] });
17
19
  export class PluginLoadInterrupted extends Error {
@@ -37,8 +39,10 @@ async function importWithSignal(url, signal) {
37
39
  export class PluginManager {
38
40
  home;
39
41
  builtinDir;
40
- constructor(home = configDir(), builtinDir = fileURLToPath(new URL('../../plugins/', import.meta.url))) {
42
+ stateright;
43
+ constructor(home = configDir(), builtinDir = fileURLToPath(new URL('../../plugins/', import.meta.url)), stateright) {
41
44
  this.home = path.resolve(home);
45
+ this.stateright = stateright;
42
46
  this.builtinDir = builtinDir;
43
47
  }
44
48
  sessionEntries;
@@ -129,6 +133,14 @@ export class PluginManager {
129
133
  catch (e) {
130
134
  diagnostics.push(`Built-in plugins unavailable: ${String(e)}`);
131
135
  }
136
+ try {
137
+ for (const { descriptor } of [...builtinMicroagents(), ...(findStateright(this.stateright) ? [staterightMicroagent()] : [])]) {
138
+ registry.register({ ...descriptor, enabled: !catalog.disabledBuiltins.includes(descriptor.id) });
139
+ }
140
+ }
141
+ catch (e) {
142
+ diagnostics.push(`Built-in microagents unavailable: ${String(e)}`);
143
+ }
132
144
  for (const [id, row] of Object.entries(catalog.plugins)) {
133
145
  try {
134
146
  const snapshot = inspectPackage(this.packagePath(id, row.digest));
@@ -233,12 +245,15 @@ export class PluginManager {
233
245
  throw new Error(`Plugin unavailable or disabled: ${id}`);
234
246
  if (descriptor.digest !== digest)
235
247
  throw new Error('Plugin changed before dispatch');
248
+ const microagent = descriptor.builtin && !descriptor.entry
249
+ ? [...builtinMicroagents(), staterightMicroagent()].find(entry => entry.descriptor.id === id)
250
+ : undefined;
236
251
  const directory = descriptor.builtin ? path.join(this.builtinDir, id) : this.packagePath(id, digest);
237
252
  const leases = path.join(this.base(), 'leases', id);
238
253
  fs.mkdirSync(leases, { recursive: true, mode: 0o700 });
239
254
  const lease = path.join(leases, `${randomUUID()}.json`);
240
255
  fs.writeFileSync(lease, JSON.stringify({ pid: process.pid, digest }), { flag: 'wx', mode: 0o600, flush: true });
241
- return { descriptor: { ...descriptor }, directory, lease };
256
+ return { descriptor: { ...descriptor }, directory, lease, microagent };
242
257
  });
243
258
  let released = false;
244
259
  const release = () => { if (!released) {
@@ -246,6 +261,10 @@ export class PluginManager {
246
261
  released = true;
247
262
  } };
248
263
  try {
264
+ if (admitted.microagent) {
265
+ const definition = admitted.microagent.definition;
266
+ return { descriptor: admitted.descriptor, module: { define: () => structuredClone(definition) }, release };
267
+ }
249
268
  if (inspectPackage(admitted.directory).digest !== digest)
250
269
  throw new Error('Plugin changed before import');
251
270
  const module = await importWithSignal(`${pathToFileURL(path.join(admitted.directory, admitted.descriptor.entry)).href}?digest=${digest}`, signal);
@@ -1,6 +1,9 @@
1
1
  import type { AgentMessage, ToolResult } from '../agent/types.ts';
2
+ import { type CompactionState } from '../agent/compaction.ts';
2
3
  import type { DelegationRecord } from '../subagents/types.ts';
3
4
  export type SessionStatus = 'active' | 'complete' | 'interrupted' | 'error' | 'turn-limit';
5
+ /** 圧縮要約の保存上限。壊れた・巨大な記録で入力が膨らむのを防ぐ。 */
6
+ export declare const MAX_SUMMARY_CHARS = 20000;
4
7
  /** JSONL の1行目。セッションの基本情報。seq は同ディレクトリ内の作成順(一覧の決定的並び替え用)。 */
5
8
  export interface SessionHeader {
6
9
  type: 'session';
@@ -49,6 +52,8 @@ export declare class Session {
49
52
  messages: AgentMessage[];
50
53
  status: SessionStatus;
51
54
  lastError?: string;
55
+ /** 直近の圧縮状態。未圧縮なら undefined。原文の messages は常に全文。 */
56
+ compaction?: CompactionState;
52
57
  id: string;
53
58
  /** ヘッダの作成時刻(ワークスペース記録に使う)。古いファイルは作成時刻がない。 */
54
59
  createdAt: string;
@@ -71,8 +76,14 @@ export declare class Session {
71
76
  */
72
77
  persistFrom(_index: number): void;
73
78
  recordMemory(observation: MemoryObservation): void;
79
+ /**
80
+ * 圧縮を記録する。原文の messages は変更しない(監査・再実行防止の根拠を保つ)。
81
+ * 書き込みに失敗した場合はメモリ上の状態も戻し、保存と表示の不一致を作らない。
82
+ */
83
+ recordCompaction(state: CompactionState, keptTurns: number): void;
74
84
  setConnection(model: string, baseUrl?: string): void;
75
85
  setStatus(status: SessionStatus, diagnostic?: string): void;
86
+ get delegationCount(): number;
76
87
  delegations(): DelegationRecord[];
77
88
  private acceptDelegation;
78
89
  recordDelegation(record: DelegationRecord): void;
@@ -3,7 +3,10 @@ import path from 'node:path';
3
3
  import os from 'node:os';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { parseImages } from "../agent/images.js";
6
+ import { safeBoundary } from "../agent/compaction.js";
6
7
  import { parseDelegation, delegationDigest } from "../subagents/request.js";
8
+ /** 圧縮要約の保存上限。壊れた・巨大な記録で入力が膨らむのを防ぐ。 */
9
+ export const MAX_SUMMARY_CHARS = 20_000;
7
10
  /** 既定の保存先。MODKH_HOME で差し替え可能(検証用)。 */
8
11
  export function defaultSessionDir() {
9
12
  if (process.env['MODKH_HOME']) {
@@ -74,6 +77,8 @@ export class Session {
74
77
  messages = [];
75
78
  status = 'active';
76
79
  lastError;
80
+ /** 直近の圧縮状態。未圧縮なら undefined。原文の messages は常に全文。 */
81
+ compaction;
77
82
  id;
78
83
  /** ヘッダの作成時刻(ワークスペース記録に使う)。古いファイルは作成時刻がない。 */
79
84
  createdAt = '';
@@ -131,6 +136,13 @@ export class Session {
131
136
  }
132
137
  else if (ev.type === 'delegation')
133
138
  session.acceptDelegation(ev.record);
139
+ else if (ev.type === 'compaction') {
140
+ // 妥当な index だけを受け入れる。壊れた記録は無視して全文送信へ戻す(安全側)。
141
+ if (Number.isSafeInteger(ev.from) && ev.from > (session.compaction?.from ?? 0)
142
+ && ev.from < session.messages.length && typeof ev.summary === 'string' && ev.summary.trim()) {
143
+ session.compaction = { summary: ev.summary.slice(0, MAX_SUMMARY_CHARS), from: ev.from };
144
+ }
145
+ }
134
146
  else if (ev.type === 'status') {
135
147
  session.status = ev.status;
136
148
  session.lastError = typeof ev.diagnostic === 'string' ? ev.diagnostic.slice(0, 2048) : undefined;
@@ -162,11 +174,16 @@ export class Session {
162
174
  if (results.some(result => result.status === 'unknown'))
163
175
  session.status = 'interrupted';
164
176
  }
177
+ if (session.compaction && safeBoundary(session.messages, session.compaction.from) !== session.compaction.from) {
178
+ session.compaction = undefined;
179
+ }
180
+ if (session.delegations().some(r => !r.result || r.result.status === 'unknown'))
181
+ session.status = 'interrupted';
165
182
  return session;
166
183
  }
167
184
  recoverPending(call) {
168
185
  const base = { callId: call.id, name: call.name };
169
- if (call.name === 'run_subagent') {
186
+ if (call.name === 'run_subagent' || call.name === 'start_subagent') {
170
187
  const record = [...this.delegationLog.values()].find(row => row.callId === call.id);
171
188
  if (record?.state === 'finished' && record.result) {
172
189
  try {
@@ -199,6 +216,14 @@ export class Session {
199
216
  recordMemory(observation) {
200
217
  this.write({ ...observation, type: 'memory', at: new Date().toISOString() });
201
218
  }
219
+ /**
220
+ * 圧縮を記録する。原文の messages は変更しない(監査・再実行防止の根拠を保つ)。
221
+ * 書き込みに失敗した場合はメモリ上の状態も戻し、保存と表示の不一致を作らない。
222
+ */
223
+ recordCompaction(state, keptTurns) {
224
+ this.write({ type: 'compaction', summary: state.summary, from: state.from, keptTurns, at: new Date().toISOString() });
225
+ this.compaction = { ...state };
226
+ }
202
227
  setConnection(model, baseUrl) {
203
228
  this.write({ type: 'connection', model, ...(baseUrl ? { baseUrl } : {}) });
204
229
  this.model = model;
@@ -211,6 +236,7 @@ export class Session {
211
236
  this.status = status;
212
237
  this.lastError = detail;
213
238
  }
239
+ get delegationCount() { return this.delegationLog.size; }
214
240
  delegations() { return [...this.delegationLog.values()].map(record => structuredClone(record)); }
215
241
  acceptDelegation(record) {
216
242
  if (!record || record.parentSessionId !== this.id || typeof record.runId !== 'string' || typeof record.callId !== 'string'
@@ -0,0 +1,11 @@
1
+ import type { DelegationRequest, HeadAssignment } from './types.ts';
2
+ export interface HeadInputs {
3
+ model: string;
4
+ lean: string;
5
+ editor?: {
6
+ id: string;
7
+ path: string;
8
+ };
9
+ }
10
+ /** Admit exactly the configured operation and its evidence before recording a child. */
11
+ export declare function headAssignment(inputs: HeadInputs, request: DelegationRequest, editRole: boolean, userRequest?: string): HeadAssignment | undefined;
@@ -0,0 +1,47 @@
1
+ import { ToolError } from "../agent/types.js";
2
+ const vagueBehavior = /^(?:works?(?: as expected| correctly)?|correct|fixed|done|ok|pass(?:ed)?|tests? pass|成功|正常|変更前|変更後|確認済み|修正済み|(?:正しく|正常に)動(?:く|作する))[.!。]?$/i;
3
+ function observableBehavior(value) {
4
+ return Boolean(value) && !/[\r\n\u2028\u2029]/.test(value) && !vagueBehavior.test(value);
5
+ }
6
+ /** Admit exactly the configured operation and its evidence before recording a child. */
7
+ export function headAssignment(inputs, request, editRole, userRequest) {
8
+ const { pluginId, formalInput, behaviorChange, targetPaths } = request;
9
+ if (pluginId === 'micro-zenki' || pluginId === 'micro-goki') {
10
+ const stateright = pluginId === 'micro-zenki';
11
+ const path = stateright ? inputs.model : inputs.lean;
12
+ if (formalInput?.path !== path || formalInput.config !== undefined || behaviorChange) {
13
+ throw new ToolError('INVALID_ARGS', `Use configured formalInput ${JSON.stringify({ path })} for ${pluginId}`);
14
+ }
15
+ return stateright ? {
16
+ task: '設定された有限モデルをStaterightで検査する',
17
+ targets: [path],
18
+ completion: { condition: '指定したモデルと設定で不変条件違反なく探索が完了する', evidence: 'verify_stateright.status=passed' },
19
+ } : {
20
+ task: '証明元の対象定理をホスト指定の期待命題と照合する',
21
+ targets: [path],
22
+ completion: { condition: '指定定理の証明が期待命題と一致する', evidence: 'verify_lean.proofStatus=proved' },
23
+ };
24
+ }
25
+ if (!editRole && pluginId !== inputs.editor?.id) {
26
+ if (behaviorChange)
27
+ throw new ToolError('INVALID_ARGS', 'behaviorChange is reserved for the configured editor');
28
+ return;
29
+ }
30
+ const editor = inputs.editor;
31
+ if (!editor || editor.id !== pluginId)
32
+ throw new ToolError('DENIED', 'Use the editor selected in Lisp head checks');
33
+ if (targetPaths?.length !== 1 || targetPaths[0] !== editor.path) {
34
+ throw new ToolError('INVALID_ARGS', `Use exactly the configured targetPaths ${JSON.stringify([editor.path])}`);
35
+ }
36
+ if (!behaviorChange || !observableBehavior(behaviorChange.before) || !observableBehavior(behaviorChange.after) ||
37
+ behaviorChange.before.toLowerCase() === behaviorChange.after.toLowerCase()) {
38
+ throw new ToolError('INVALID_ARGS', 'behaviorChange.before and behaviorChange.after must state distinct, observable behavior for one change');
39
+ }
40
+ return {
41
+ task: request.task,
42
+ targets: [editor.path],
43
+ behaviorChange,
44
+ ...(userRequest ? { userRequest } : {}),
45
+ completion: { condition: behaviorChange.after, evidence: 'verification.status=passed and verification.application=applied' },
46
+ };
47
+ }
@@ -0,0 +1,4 @@
1
+ /** Child slots only; the parent always retains its own model slot. */
2
+ export declare const DEFAULT_SUBAGENT_LIMIT = 2;
3
+ export declare const MAX_SUBAGENT_LIMIT = 16;
4
+ export declare function parseSubagentLimit(value: unknown): number | null;
@@ -0,0 +1,6 @@
1
+ /** Child slots only; the parent always retains its own model slot. */
2
+ export const DEFAULT_SUBAGENT_LIMIT = 2;
3
+ export const MAX_SUBAGENT_LIMIT = 16;
4
+ export function parseSubagentLimit(value) {
5
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 && value <= MAX_SUBAGENT_LIMIT ? value : null;
6
+ }
@@ -3,10 +3,18 @@ import { fields, object, pluginId, text } from "../plugins/package.js";
3
3
  /** Canonical field order is shared by admission and durable receipt recovery. */
4
4
  export function parseDelegation(value) {
5
5
  const raw = object(value);
6
- fields(raw, ['pluginId', 'task', 'context', 'targetPaths']);
6
+ fields(raw, ['pluginId', 'task', 'context', 'targetPaths', 'formalInput', 'behaviorChange']);
7
7
  const request = { pluginId: pluginId(raw.pluginId), task: text(raw.task, 'task', 32768) };
8
8
  if (raw.context !== undefined)
9
9
  request.context = text(raw.context, 'context', 131072);
10
+ if (raw.behaviorChange !== undefined) {
11
+ const change = object(raw.behaviorChange);
12
+ fields(change, ['before', 'after']);
13
+ request.behaviorChange = {
14
+ before: text(change.before, 'behaviorChange.before', 512).trim(),
15
+ after: text(change.after, 'behaviorChange.after', 512).trim(),
16
+ };
17
+ }
10
18
  if (raw.targetPaths !== undefined) {
11
19
  if (!Array.isArray(raw.targetPaths) || raw.targetPaths.length < 1 || raw.targetPaths.length > 8 ||
12
20
  !raw.targetPaths.every(p => typeof p === 'string' && p.length < 1024 && !p.startsWith('/') && !p.includes('\\') && !p.split('/').some((s) => !s || s === '.' || s === '..')) ||
@@ -14,6 +22,15 @@ export function parseDelegation(value) {
14
22
  throw new Error('Invalid targetPaths: 1..8 unique relative file paths required');
15
23
  request.targetPaths = [...raw.targetPaths].sort();
16
24
  }
25
+ if (raw.formalInput !== undefined) {
26
+ const input = object(raw.formalInput);
27
+ fields(input, ['path', 'config']);
28
+ request.formalInput = { path: text(input.path, 'formalInput.path', 1024) };
29
+ if (input.config !== undefined)
30
+ request.formalInput.config = text(input.config, 'formalInput.config', 1024);
31
+ if (request.targetPaths)
32
+ throw new Error('formalInput and targetPaths are mutually exclusive');
33
+ }
17
34
  return request;
18
35
  }
19
36
  export function delegationDigest(request) {
@@ -1,15 +1,22 @@
1
- import type { ApprovalGate, Model, Tool } from '../agent/types.ts';
1
+ import type { ApprovalGate, Model, TokenUsage, Tool } from '../agent/types.ts';
2
2
  import { SessionStore } from '../session/store.ts';
3
3
  import type { Session } from '../session/store.ts';
4
4
  import { PluginManager } from '../plugins/manager.ts';
5
5
  import type { PluginDescriptor } from '../plugins/api.ts';
6
6
  import type { AgentSetting } from './settings.ts';
7
- import type { SubagentHandle } from './types.ts';
7
+ import type { SubagentHandle, SubagentResult } from './types.ts';
8
+ import { type HeadInputs } from './head-assignment.ts';
8
9
  export { parseDelegation } from './request.ts';
9
10
  export interface Connection {
10
11
  ref: string;
11
12
  create(): Model;
12
13
  }
14
+ export interface SubagentActivity {
15
+ pluginId: string;
16
+ task: string;
17
+ phase: string;
18
+ runningCount?: number;
19
+ }
13
20
  export interface SubagentOptions {
14
21
  manager: PluginManager;
15
22
  store: SessionStore;
@@ -20,14 +27,41 @@ export interface SubagentOptions {
20
27
  connection(model?: string): Connection;
21
28
  settings?: Record<string, AgentSetting>;
22
29
  unavailable?: boolean;
30
+ maxConcurrent?: number;
31
+ hasBackgroundJobs?(): boolean;
32
+ headInputs?: HeadInputs;
33
+ headUserRequest?(): string | undefined;
23
34
  /** Host policy only; neither plugin definitions nor child requests may downgrade it. */
24
35
  verificationIsolation?: 'integrity-only' | 'required';
25
36
  progress?(message: string): void;
37
+ activity?(status: SubagentActivity | null): void;
38
+ onUsage?(usage: TokenUsage): void;
26
39
  }
27
40
  /** The parent captures authority once. Plugins receive neither this owner nor its session. */
28
41
  export declare class SubagentService {
29
42
  private opts;
30
43
  private handles;
44
+ private notices;
45
+ private activities;
46
+ private limit;
47
+ get maxConcurrent(): number;
48
+ get hasPending(): boolean;
49
+ get hasUnknown(): boolean;
50
+ setMaxConcurrent(value: number): void;
51
+ takeNotices(): string[];
52
+ waitForChange(signal: AbortSignal): Promise<void>;
53
+ cancelAll(reason: string): Promise<void>;
54
+ runs(): unknown[];
55
+ output(runId: string, waitMs: number, signal: AbortSignal): Promise<SubagentResult | {
56
+ runId: string;
57
+ status: 'running';
58
+ }>;
59
+ cancel(runId: string): Promise<void>;
60
+ /** Parent reads remain usable; mutations cannot race a child writer. */
61
+ parentTools(tools: Tool[]): Tool[];
62
+ private claimWriter;
63
+ private releaseWriter;
64
+ private activity;
31
65
  constructor(options: SubagentOptions);
32
66
  list(): PluginDescriptor[];
33
67
  start(raw: unknown, owner: {