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,9 @@
1
+ import type { AgentMessage, ToolCall, ToolResult } from '../agent/types.ts';
2
+ /** View state only; never feeds truncated output back to the model or session journal. */
3
+ export declare class ToolDisplay {
4
+ private entries;
5
+ constructor(messages?: readonly AgentMessage[]);
6
+ call(call: ToolCall): string;
7
+ result(result: ToolResult): string;
8
+ details(argument: string): string;
9
+ }
@@ -0,0 +1,87 @@
1
+ import { stripVTControlCharacters } from 'node:util';
2
+ import { fitText, textWidth } from "./editor.js";
3
+ import { shellOutput } from "./shell-display.js";
4
+ function brief(value, width = 76) {
5
+ const text = stripVTControlCharacters(value).replace(/[\r\n\t]+/g, ' ').trim();
6
+ return textWidth(text) > width ? `${fitText(text, width - 1)}…` : text;
7
+ }
8
+ const LABELS = {
9
+ read_file: '読む', create_file: '作成', edit_file: '編集', list_files: 'ファイル一覧', search_files: '検索',
10
+ run_command: 'コマンド', read_skill: '手順を確認', list_skills: '手順一覧',
11
+ list_subagents: '担当一覧', start_subagent: '子を起動', run_subagent: '子を実行',
12
+ subagent_output: '子の結果', list_subagent_runs: '子の状態',
13
+ };
14
+ function title(call) {
15
+ const args = call.args;
16
+ const target = [args.path, args.pattern, args.query, args.name, args.pluginId, args.description]
17
+ .find(value => typeof value === 'string');
18
+ return `${LABELS[call.name] ?? call.name}${target ? ` · ${brief(String(target), 60)}` : ''}`;
19
+ }
20
+ /** Display a bounded summary only. Exact inputs and outputs remain available through details. */
21
+ function resultSummary(result) {
22
+ if (result.name === 'run_command') {
23
+ const lines = shellOutput(result).trim().split('\n');
24
+ return lines.length > 7 ? [...lines.slice(0, 2), '│ …', ...lines.slice(-4)] : lines;
25
+ }
26
+ const lines = result.output.trim().split('\n');
27
+ const status = { ok: '完了', error: 'エラー', unknown: '結果不明', 'not-executed': '未実行' }[result.status];
28
+ if (result.status !== 'ok')
29
+ return [`${status} · ${lines[0]}`, ...lines.slice(1, 3), ...(lines.length > 3 ? [lines.at(-1)] : [])];
30
+ if (result.name === 'read_skill')
31
+ return [`${status} · ${lines.length}行の手順を取得`];
32
+ try {
33
+ const data = JSON.parse(result.output);
34
+ if (Array.isArray(data))
35
+ return [`${status} · ${data.length}件`];
36
+ if (data && typeof data === 'object') {
37
+ const fields = data;
38
+ const description = [fields.status, fields.summary, fields.message].filter(v => typeof v === 'string').join(' · ');
39
+ return [`${status}${description ? ` · ${description}` : ' · 詳細あり'}`];
40
+ }
41
+ }
42
+ catch { /* Text output has no structured summary. */ }
43
+ const diagnostics = lines.find(line => line.startsWith('解析:'));
44
+ return [`${status} · ${lines[0] || '出力なし'}`, ...(diagnostics ? [diagnostics] : [])];
45
+ }
46
+ /** View state only; never feeds truncated output back to the model or session journal. */
47
+ export class ToolDisplay {
48
+ entries = [];
49
+ constructor(messages = []) {
50
+ for (const message of messages) {
51
+ if (message.role === 'assistant')
52
+ for (const call of message.toolCalls ?? [])
53
+ this.call(call);
54
+ if (message.role === 'tool')
55
+ for (const result of message.results)
56
+ this.result(result);
57
+ }
58
+ }
59
+ call(call) {
60
+ this.entries.push({ call });
61
+ const command = call.name === 'run_command' && typeof call.args.command === 'string' ? ` $ ${brief(call.args.command)}\n` : '';
62
+ return `\n▶ ${title(call)}\n${command}`;
63
+ }
64
+ result(result) {
65
+ let index = this.entries.findLastIndex(entry => entry.call.id === result.callId && !entry.result);
66
+ if (index < 0) {
67
+ this.entries.push({ call: { id: result.callId, name: result.name, args: {} } });
68
+ index = this.entries.length - 1;
69
+ }
70
+ this.entries[index].result = result;
71
+ return resultSummary(result).map(line => ` ${brief(line)}`).join('\n') + `\n 詳細: /tools ${index + 1}\n`;
72
+ }
73
+ details(argument) {
74
+ if (!argument) {
75
+ if (!this.entries.length)
76
+ return 'ツール履歴はありません。\n';
77
+ return this.entries.slice(-20).map((entry, i) => `${Math.max(0, this.entries.length - 20) + i + 1}. ${title(entry.call)} · ${entry.result?.status ?? '結果未確認'}`).join('\n')
78
+ + '\n/tools <番号>: 引数と結果の全文(直近20件を表示)\n';
79
+ }
80
+ if (!/^[1-9]\d*$/.test(argument))
81
+ return '使い方: /tools または /tools <番号>\n';
82
+ const entry = this.entries[Number(argument) - 1];
83
+ if (!entry)
84
+ return 'その番号のツール履歴はありません。/tools で一覧を確認してください。\n';
85
+ return stripVTControlCharacters(`\nツール詳細 #${argument} · ${entry.call.name}\n引数:\n${JSON.stringify(entry.call.args, null, 2)}\n結果: ${entry.result?.status ?? '未確認'}\n${entry.result?.output ?? '結果はまだありません。'}\n`);
86
+ }
87
+ }
@@ -0,0 +1,22 @@
1
+ import type { ScreenPoint } from './terminal-mouse.ts';
2
+ export interface TranscriptLine {
3
+ text: string;
4
+ newline: boolean;
5
+ }
6
+ export interface TranscriptScreenLine extends TranscriptLine {
7
+ painted: string;
8
+ }
9
+ export declare function transcriptLine(text: string, width: number, newline: boolean): TranscriptLine[];
10
+ export declare function transcriptLines(text: string, width: number): TranscriptLine[];
11
+ /** Rewrap plain text and carry the renderer's self-contained SGR spans across soft breaks. */
12
+ export declare function reflowTranscript(rows: readonly TranscriptScreenLine[], width: number): TranscriptScreenLine[];
13
+ export interface DragSelection {
14
+ anchor: ScreenPoint;
15
+ end: ScreenPoint;
16
+ }
17
+ export declare function selectedTranscript(rows: ReadonlyMap<number, TranscriptScreenLine>, selection: DragSelection): {
18
+ row: number;
19
+ column: number;
20
+ text: string;
21
+ newline: boolean;
22
+ }[];
@@ -0,0 +1,75 @@
1
+ import { cellWidth, chars, wrapText } from "./editor.js";
2
+ export function transcriptLine(text, width, newline) {
3
+ const wrapped = wrapText(text, width);
4
+ return wrapped.map((text, row) => ({ text, newline: newline && row === wrapped.length - 1 }));
5
+ }
6
+ export function transcriptLines(text, width) {
7
+ const lines = text.split('\n');
8
+ return lines.flatMap((line, index) => transcriptLine(line, width, index < lines.length - 1));
9
+ }
10
+ /** Rewrap plain text and carry the renderer's self-contained SGR spans across soft breaks. */
11
+ export function reflowTranscript(rows, width) {
12
+ const result = [];
13
+ let text = '';
14
+ let spans = [];
15
+ for (const [index, row] of rows.entries()) {
16
+ let position = 0;
17
+ for (const match of row.painted.matchAll(/\x1b\[([0-9;]+)m([^\x1b]*)\x1b\[0m|([^\x1b]+)/g)) {
18
+ const end = Math.min(row.text.length, position + (match[2] ?? match[3]).length);
19
+ if (match[1] && end > position)
20
+ spans.push({ start: text.length + position, end: text.length + end, style: match[1] });
21
+ position = end;
22
+ }
23
+ text += row.text;
24
+ if (!row.newline && index < rows.length - 1)
25
+ continue;
26
+ let start = 0;
27
+ let spanIndex = 0;
28
+ for (const line of transcriptLine(text, width, row.newline)) {
29
+ const end = start + line.text.length;
30
+ let cursor = start;
31
+ let painted = '';
32
+ for (; spanIndex < spans.length && spans[spanIndex].start < end; spanIndex++) {
33
+ const span = spans[spanIndex];
34
+ const spanStart = Math.max(start, span.start);
35
+ painted += text.slice(cursor, spanStart);
36
+ cursor = Math.min(end, span.end);
37
+ painted += `\x1b[${span.style}m${text.slice(spanStart, cursor)}\x1b[0m`;
38
+ if (span.end > end)
39
+ break;
40
+ }
41
+ result.push({ ...line, painted: painted + text.slice(cursor, end) });
42
+ start = end;
43
+ }
44
+ text = '';
45
+ spans = [];
46
+ }
47
+ return result;
48
+ }
49
+ export function selectedTranscript(rows, selection) {
50
+ const { anchor, end } = selection;
51
+ const forward = anchor.row < end.row || (anchor.row === end.row && anchor.column <= end.column);
52
+ const [first, last] = forward ? [anchor, end] : [end, anchor];
53
+ const result = [];
54
+ for (let row = first.row; row <= last.row; row++) {
55
+ const line = rows.get(row);
56
+ if (!line)
57
+ continue;
58
+ const start = row === first.row ? first.column : 1;
59
+ const stop = row === last.row ? last.column : Infinity;
60
+ let column = 1;
61
+ let text = '';
62
+ let selectedColumn = 0;
63
+ for (const char of chars(line.text)) {
64
+ const next = column + cellWidth(char, column - 1);
65
+ if (next > start && column <= stop) {
66
+ if (!selectedColumn)
67
+ selectedColumn = column;
68
+ text += char;
69
+ }
70
+ column = next;
71
+ }
72
+ result.push({ row, column: selectedColumn, text, newline: row < last.row && line.newline });
73
+ }
74
+ return result;
75
+ }
@@ -1,22 +1,11 @@
1
- export interface UsageTotals {
2
- /** Input tokens, including cached prefixes. */
3
- input: number;
4
- output: number;
5
- /** Input tokens served from the provider's prompt cache. */
6
- cacheRead: number;
7
- /** Input tokens written to the provider's prompt cache. */
8
- cacheWrite: number;
9
- /** Responses counted into the totals; lets the footer stay quiet until real data exists. */
1
+ import type { TokenUsage } from '../agent/types.ts';
2
+ export interface UsageTotals extends TokenUsage {
10
3
  responses: number;
4
+ /** Some reported usage lacks a comparable input and cache-read pair. */
5
+ cacheHitIncomplete?: true;
11
6
  }
12
7
  export declare const EMPTY_USAGE: UsageTotals;
13
- export interface ReportedUsage {
14
- input?: number | undefined;
15
- output?: number | undefined;
16
- cacheRead?: number | undefined;
17
- cacheWrite?: number | undefined;
18
- }
19
- export declare function addUsage(total: UsageTotals, reported: ReportedUsage): UsageTotals;
8
+ export declare function addUsage(total: UsageTotals, reported: TokenUsage): UsageTotals;
20
9
  /** 142,296,676 -> 142M. Keeps the footer short while staying recognizable. */
21
10
  export declare function compactTokens(value: number): string;
22
11
  /** Share of input tokens served from cache. Undefined when the provider reports no input. */
@@ -27,3 +16,7 @@ export declare function usageFooter(usage: UsageTotals, width: number): string;
27
16
  /** 右下ステータス用のコンパクトな使用量表示。maxWidth を超えるときは後ろの項目から落とす。
28
17
  * 幅は textWidth(表示幅)で測る(全角の「計」なども2セルとして数える)。 */
29
18
  export declare function usageBadgeLine(usage: UsageTotals, maxWidth?: number): string;
19
+ export declare const USAGE_HEADING = "\u30C8\u30FC\u30AF\u30F3\u4F7F\u7528\u91CF";
20
+ export declare function usageBreakdown(usage: UsageTotals): string;
21
+ /** Width is omitted for /usage, which always shows exact counts and every field. */
22
+ export declare function usageBreakdownLines(usage: UsageTotals, width?: number): string[];
package/dist/cli/usage.js CHANGED
@@ -1,21 +1,31 @@
1
1
  /** Token accounting for the status footer. Values are reported by the provider, never estimated. */
2
2
  import { textWidth } from "./editor.js";
3
- export const EMPTY_USAGE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, responses: 0 };
4
- /** Invalid, negative or non-finite provider values are ignored rather than shown as data. */
3
+ export const EMPTY_USAGE = { responses: 0 };
4
+ /** A reported zero is meaningful; missing or invalid data stays unknown. */
5
5
  function count(value) {
6
- return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
6
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
7
+ }
8
+ function sumReported(total, value) {
9
+ return value === undefined ? total : (total ?? 0) + value;
7
10
  }
8
11
  export function addUsage(total, reported) {
9
- const input = count(reported.input), output = count(reported.output);
10
- const cacheRead = count(reported.cacheRead), cacheWrite = count(reported.cacheWrite);
11
- if (input === 0 && output === 0 && cacheRead === 0 && cacheWrite === 0)
12
+ const input = count(reported.input);
13
+ const output = count(reported.output);
14
+ const cacheRead = count(reported.cacheRead);
15
+ const cacheWrite = count(reported.cacheWrite);
16
+ const uncachedInput = count(reported.uncachedInput) ?? (input !== undefined && cacheRead !== undefined && cacheWrite !== undefined
17
+ ? count(input - cacheRead - cacheWrite) : undefined);
18
+ if ([input, output, cacheRead, cacheWrite, uncachedInput].every(value => value === undefined))
12
19
  return total;
13
20
  return {
14
- input: total.input + input,
15
- output: total.output + output,
16
- cacheRead: total.cacheRead + cacheRead,
17
- cacheWrite: total.cacheWrite + cacheWrite,
21
+ input: sumReported(total.input, input),
22
+ uncachedInput: sumReported(total.uncachedInput, uncachedInput),
23
+ output: sumReported(total.output, output),
24
+ cacheRead: sumReported(total.cacheRead, cacheRead),
25
+ cacheWrite: sumReported(total.cacheWrite, cacheWrite),
18
26
  responses: total.responses + 1,
27
+ ...(total.cacheHitIncomplete || input === undefined || (input > 0 && cacheRead === undefined) ||
28
+ (cacheRead ?? 0) > input ? { cacheHitIncomplete: true } : {}),
19
29
  };
20
30
  }
21
31
  /** 142,296,676 -> 142M. Keeps the footer short while staying recognizable. */
@@ -30,9 +40,9 @@ export function compactTokens(value) {
30
40
  }
31
41
  /** Share of input tokens served from cache. Undefined when the provider reports no input. */
32
42
  export function cacheHitRate(usage) {
33
- if (usage.input <= 0)
43
+ if (usage.cacheHitIncomplete || !usage.input || usage.cacheRead === undefined || usage.cacheRead > usage.input)
34
44
  return undefined;
35
- return Math.min(100, Math.round((usage.cacheRead / usage.input) * 100));
45
+ return Math.round((usage.cacheRead / usage.input) * 100);
36
46
  }
37
47
  /** One footer line, most useful numbers first. `width` is the usable cell width; narrower terminals
38
48
  * drop trailing fields instead of wrapping, so the composer never moves. */
@@ -41,10 +51,10 @@ export function usageFooter(usage, width) {
41
51
  return '';
42
52
  const rate = cacheHitRate(usage);
43
53
  const fields = [
44
- `計 ${compactTokens(usage.input + usage.output)} tok`,
54
+ `計 ${compactTokens((usage.input ?? 0) + (usage.output ?? 0))} tok`,
45
55
  ...(rate === undefined ? [] : [`cache ${rate}%`]),
46
- `入 ${compactTokens(usage.input)}`,
47
- `出 ${compactTokens(usage.output)}`,
56
+ `入 ${compactTokens(usage.input ?? 0)}`,
57
+ `出 ${compactTokens(usage.output ?? 0)}`,
48
58
  ];
49
59
  // Drop trailing fields rather than wrapping: the footer must never move the composer.
50
60
  const lines = fields.map((_, index) => fields.slice(0, index + 1).join(' · '));
@@ -60,10 +70,10 @@ export function usageBadgeLine(usage, maxWidth) {
60
70
  return '';
61
71
  const rate = cacheHitRate(usage);
62
72
  const fields = [
63
- `計 ${compactTokens(usage.input + usage.output)} tok`,
73
+ `計 ${compactTokens((usage.input ?? 0) + (usage.output ?? 0))} tok`,
64
74
  ...(rate === undefined ? [] : [`cache ${rate}%`]),
65
- `in ${compactTokens(usage.input)}`,
66
- `out ${compactTokens(usage.output)}`,
75
+ `in ${compactTokens(usage.input ?? 0)}`,
76
+ `out ${compactTokens(usage.output ?? 0)}`,
67
77
  ];
68
78
  const lines = fields.map((_, index) => fields.slice(0, index + 1).join(' · '));
69
79
  if (maxWidth === undefined)
@@ -73,3 +83,35 @@ export function usageBadgeLine(usage, maxWidth) {
73
83
  return line;
74
84
  return '';
75
85
  }
86
+ const exactNumber = new Intl.NumberFormat('en-US');
87
+ const compactNumber = new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 });
88
+ export const USAGE_HEADING = 'トークン使用量';
89
+ function tokenRow(label, value, suffix = '') {
90
+ if (value === undefined)
91
+ return [label, '—'];
92
+ return [label, exactNumber.format(value) + suffix, compactNumber.format(value) + suffix];
93
+ }
94
+ export function usageBreakdown(usage) {
95
+ return usage.responses === 0 ? 'トークン使用量はまだ報告されていません' : usageBreakdownLines(usage).join('\n');
96
+ }
97
+ /** Width is omitted for /usage, which always shows exact counts and every field. */
98
+ export function usageBreakdownLines(usage, width) {
99
+ const total = usage.input === undefined && usage.output === undefined
100
+ ? undefined : (usage.input ?? 0) + (usage.output ?? 0);
101
+ const rate = cacheHitRate(usage);
102
+ const rows = [
103
+ tokenRow(USAGE_HEADING, total, ' tok'),
104
+ ['キャッシュヒット', rate === undefined ? '—' : `${rate}%`],
105
+ tokenRow('未キャッシュ入力', usage.uncachedInput),
106
+ tokenRow('キャッシュ済み入力', usage.cacheRead),
107
+ ];
108
+ if (width === undefined || (usage.cacheWrite ?? 0) > 0)
109
+ rows.push(tokenRow('キャッシュ書き込み', usage.cacheWrite));
110
+ rows.push(tokenRow('出力', usage.output));
111
+ const lineWidth = width ?? Math.max(...rows.map(([label, value]) => textWidth(label) + 2 + textWidth(value)));
112
+ return rows.map(([label, exact, compact = exact]) => {
113
+ const available = lineWidth - textWidth(label);
114
+ const value = textWidth(exact) + 2 <= available ? exact : compact;
115
+ return label + ' '.repeat(Math.max(2, available - textWidth(value))) + value;
116
+ });
117
+ }
@@ -0,0 +1,3 @@
1
+ export declare const WHALE_FRAME_MS = 180;
2
+ /** Render one frame in terminal columns, leaving a gutter on both sides. */
3
+ export declare function whaleRow(frame: number, width: number): string;
@@ -0,0 +1,17 @@
1
+ import { textWidth } from "./editor.js";
2
+ export const WHALE_FRAME_MS = 180;
3
+ const WHALES = '🐳 🐋';
4
+ const WHALE_WIDTH = textWidth(WHALES);
5
+ const WAVES = '∿~ ';
6
+ /** Render one frame in terminal columns, leaving a gutter on both sides. */
7
+ export function whaleRow(frame, width) {
8
+ const waterWidth = width - 2;
9
+ const travel = waterWidth - WHALE_WIDTH;
10
+ if (travel < WAVES.length)
11
+ return '';
12
+ // Fold the path at each end instead of jumping back to the start.
13
+ const phase = (frame * 2) % (2 * travel);
14
+ const position = travel - Math.abs(travel - phase);
15
+ const water = Array.from({ length: waterWidth }, (_, column) => WAVES[(column + frame) % WAVES.length]).join('');
16
+ return ` ${water.slice(0, position)}${WHALES}${water.slice(position + WHALE_WIDTH)} `;
17
+ }
@@ -0,0 +1,3 @@
1
+ export declare const WHALE_FRAME_MS = 180;
2
+ /** Render one frame in terminal columns, leaving a gutter on both sides. */
3
+ export declare function whaleRow(frame: number, width: number): string;
@@ -0,0 +1,24 @@
1
+ import { textWidth } from "./editor.js";
2
+ export const WHALE_FRAME_MS = 180;
3
+ const LEAD_WHALE = '🐳';
4
+ const TRAILING_WHALE = '🐋';
5
+ const LEAD_WIDTH = textWidth(LEAD_WHALE);
6
+ const TRAILING_WIDTH = textWidth(TRAILING_WHALE);
7
+ const WHALE_GAP = 8;
8
+ const WAVES = '∿~ ';
9
+ /** Render one frame in terminal columns, leaving a gutter on both sides. */
10
+ export function whaleRow(frame, width) {
11
+ const waterWidth = width - 2;
12
+ const space = waterWidth - LEAD_WIDTH - TRAILING_WIDTH;
13
+ const gap = Math.min(WHALE_GAP, space - WAVES.length);
14
+ if (gap < 1)
15
+ return '';
16
+ const travel = space - gap;
17
+ // Swim left, then start the next pass at the right edge.
18
+ const passFrames = Math.ceil(travel / 2) + 1;
19
+ const position = Math.max(0, travel - (frame % passFrames) * 2);
20
+ const leadEnd = position + LEAD_WIDTH;
21
+ const trailingPosition = leadEnd + gap;
22
+ const water = Array.from({ length: waterWidth }, (_, column) => WAVES[(column + frame) % WAVES.length]).join('');
23
+ return ` ${water.slice(0, position)}${LEAD_WHALE}${water.slice(leadEnd, trailingPosition)}${TRAILING_WHALE}${water.slice(trailingPosition + TRAILING_WIDTH)} `;
24
+ }
package/dist/index.js CHANGED
@@ -2,44 +2,55 @@
2
2
  // modkh — MoDKH (Mixture of DKH)
3
3
  import fs from 'node:fs';
4
4
  import { fileURLToPath } from 'node:url';
5
- const VERSION = '0.1.0';
5
+ import { APP_VERSION } from "./version.js";
6
+ const VERSION = APP_VERSION;
6
7
  const HELP = `modkh ${VERSION} — MoDKH (Mixture of DKH)
7
8
 
8
9
  使い方:
9
10
  modkh [--model <provider>/<model>] [--cwd <dir>] [--resume <id>] [--base-url <url>]
10
- (サブコマンドなしで起動すると対話ハーネスを開く)
11
+ (対話ハーネスを開く。言語別の調査担当は /agents で確認)
11
12
  modkh chat --model <provider>/<model> [--cwd <dir>] [--resume <id>] [--base-url <url>]
12
13
  modkh chat --lisp-config agents.lisp --trust-lisp-sha256 SHA256 [--sbcl PATH] [--verification-isolation required|integrity-only]
13
- [--routing auto] [--lean PATH] [--java PATH --tla-jar PATH]
14
+ [--routing auto] [--lean PATH] [--stateright PATH]
15
+ [--lean-contract FILE.lean --lean-theorem NAME]
14
16
  modkh auth login chatgpt
15
17
  modkh session list
16
18
  modkh plugin list | add <directory> | enable <id> | disable <id> | remove <id>
19
+ modkh stateright install | status
17
20
  modkh language status | install [--detected] | retry <id> | update
18
21
 
19
22
  対話中のコマンド:
20
23
  /connect 検索できるプロバイダー一覧
21
24
  /connect openai ChatGPT OAuth / APIキーを選択
22
25
  /connect chatgpt ブラウザで ChatGPT 認証
26
+ /connect opencode OpenCode Zen のモデル選択
27
+ /connect opencode-go OpenCode Go のモデル選択(同じ OPENCODE_API_KEY)
23
28
  /connect ollama Ollama Local のモデル選択
24
29
  /connect ollama-cloud Ollama Cloud の認証・モデル選択
25
30
  /agents 子エージェント一覧
26
31
  /agents run [ID] [依頼] 子を選んで限定した仕事を委譲
27
- /models [検索語] 名前の部分一致検索・番号でモデル選択
28
- /reasoning [レベル] [--save] 推論レベル off/minimal/low/medium/high(既定は前回保存値)
32
+ /models [検索語] 接続先からモデル一覧を取得して選択
33
+ /reasoning [レベル] [--save] 推論レベル off/minimal/low/medium/high/max(既定は前回保存値)
29
34
  /connect <provider>/<model> [--base-url <url>] モデルをその場で接続(AI API / chatgpt / fixed)
30
35
 
31
36
  接続先:
32
37
  fixed/scripted 固定応答モデル(オフライン検証用)
33
38
  openai|anthropic|google|deepseek/<model> AI SDK アダプター
34
- opencode|openrouter|infron|ollama|hermes/<model> OpenAI互換アダプター
39
+ opencode|opencode-go/<model> OpenCode Zen / Go(同じ OPENCODE_API_KEY)
40
+ openrouter|infron|ollama|hermes/<model> OpenAI互換アダプター
35
41
  ollama-cloud/<model> Ollama Cloud (OLLAMA_API_KEY)
36
42
  groq|xai|lmstudio/<model> 既存の互換アダプター
37
43
  compatible/<model> --base-url <url> 任意のOpenAI互換URL
38
44
  chatgpt/<model> Sign in with ChatGPT(/connect で認証可能)
39
45
 
46
+ モデル一覧は固定値を持たず、/connect と /models のたびに各プロバイダーの一覧APIから取得する。
47
+ 取得できないときは理由を表示し、モデルIDの直接入力を案内する(古い一覧へのフォールバックはしない)。
48
+
40
49
  キーは環境変数から読む(例: OPENAI_API_KEY, ANTHROPIC_API_KEY,
41
50
  GOOGLE_GENERATIVE_AI_API_KEY, DEEPSEEK_API_KEY, OPENCODE_API_KEY, OPENROUTER_API_KEY,
42
51
  INFRON_API_KEY, HERMES_API_KEY, OLLAMA_API_KEY, GROQ_API_KEY, XAI_API_KEY)。
52
+ OPENCODE_API_KEY は OpenCode Zen と Go の両方で使う(片方の入力で両方に接続できる)。
53
+ 接続先URLの差し替え: OPENCODE_BASE_URL (Zen) / OPENCODE_GO_BASE_URL (Go)。
43
54
 
44
55
  TTYではMODKHロゴ・コマンド補完・検索メニューを表示。↑↓/Enterで選択、Escで戻る。
45
56
  出力は通常のスクリーンバッファに流れるので、端末のスクロール(マウスホイール等)で履歴を辿れる。
@@ -93,15 +104,26 @@ export function main(argv) {
93
104
  process.stdout.write(`${VERSION}\n`);
94
105
  return;
95
106
  }
96
- void dispatch(cmd, args);
107
+ void dispatch(cmd, args, argv);
97
108
  }
98
- async function dispatch(cmd, args) {
109
+ async function dispatch(cmd, args, argv) {
99
110
  try {
100
111
  if (cmd === 'chat') {
112
+ const { recordChat } = await import("./cli/agenticreplay.js");
113
+ const exitCode = await recordChat(fileURLToPath(import.meta.url), argv, args);
114
+ if (exitCode !== undefined) {
115
+ process.exitCode = exitCode;
116
+ return;
117
+ }
101
118
  const { runChat } = await import("./cli/chat.js");
102
119
  await runChat({ args });
103
120
  return;
104
121
  }
122
+ if (cmd === 'stateright') {
123
+ const { runStaterightCommand } = await import("./cli/stateright.js");
124
+ await runStaterightCommand(args['@positional'] ?? 'status');
125
+ return;
126
+ }
105
127
  if (cmd === 'language') {
106
128
  const { runLanguageCommand } = await import("./cli/language.js");
107
129
  await runLanguageCommand(args['@positional'] ?? '', process.cwd());
@@ -2,6 +2,7 @@ import { type HostPlatform, type ReleaseAsset } from './platform.ts';
2
2
  /** Official Roswell Lisp filenames include '+' (for example install+sigsegv.lisp). */
3
3
  export declare function validateRoswellArchivePaths(output: string): void;
4
4
  export declare function roswellAsset(assets: ReleaseAsset[], platform: HostPlatform, glibc?: string): ReleaseAsset;
5
+ export declare const COMMON_LISP_BUILD_OUTPUT_BYTES: number;
5
6
  /** Called under install.ts's per-language lock. Every attempt owns a new non-relocated prefix. */
6
7
  export declare function installCommonLisp(target: string, signal?: AbortSignal): Promise<{
7
8
  command: string;
@@ -41,6 +41,7 @@ export function roswellAsset(assets, platform, glibc) {
41
41
  throw new Error('Invalid Roswell archive size');
42
42
  return asset;
43
43
  }
44
+ export const COMMON_LISP_BUILD_OUTPUT_BYTES = 16 * 1024 * 1024;
44
45
  const repositories = [CL_LSP_REPOSITORY];
45
46
  const failure = (error) => {
46
47
  if (!(error instanceof Error))
@@ -89,11 +90,11 @@ export async function installCommonLisp(target, signal) {
89
90
  }
90
91
  };
91
92
  const run = (name, command, args, cwd = root) => stage(name, async (entry) => {
92
- const receipt = await executeBounded(command, args, { cwd, env, inputDigest: sha256(JSON.stringify([command, args])), timeoutMs: 20 * 60_000, maxOutputBytes: 512 * 1024, signal: deadline });
93
+ const receipt = await executeBounded(command, args, { cwd, env, inputDigest: sha256(JSON.stringify([command, args])), timeoutMs: 20 * 60_000, maxOutputBytes: name === 'bundled-runtime-install' ? COMMON_LISP_BUILD_OUTPUT_BYTES : 512 * 1024, outputOverflow: name === 'bundled-runtime-install' ? 'tail' : 'stop', signal: deadline });
93
94
  entry.receipt = receipt;
94
95
  settled &&= receipt.cleanup === 'settled';
95
96
  if (receipt.state !== 'exited' || receipt.exitCode !== 0 || receipt.cleanup !== 'settled')
96
- throw new Error(`${receipt.state}/${receipt.exitCode} cleanup=${receipt.cleanup}: stderr=${receipt.stderr.slice(-1500)} stdout=${receipt.stdout.slice(-1500)}`);
97
+ throw new Error(`${receipt.state}/${receipt.exitCode} cleanup=${receipt.cleanup} cause=${receipt.terminationReason ?? receipt.state}: stderr=${receipt.stderr.slice(-1500)} stdout=${receipt.stdout.slice(-1500)}`);
97
98
  return receipt.stdout;
98
99
  });
99
100
  try {
@@ -181,8 +181,11 @@ export class LspServer {
181
181
  });
182
182
  return state;
183
183
  }
184
+ const languageId = this.id === 'tailwind' || this.id === 'typescript'
185
+ ? languageForPath(file)?.id ?? (this.id === 'tailwind' ? 'plaintext' : this.id)
186
+ : this.id;
184
187
  await connection.sendNotification('textDocument/didOpen', {
185
- textDocument: { uri: pathToFileURL(file).href, languageId: this.id === 'tailwind' ? (languageForPath(file)?.id === 'tsx' ? 'typescriptreact' : languageForPath(file)?.id ?? 'plaintext') : this.id, version: state.version, text },
188
+ textDocument: { uri: pathToFileURL(file).href, languageId: languageId === 'tsx' ? 'typescriptreact' : languageId, version: state.version, text },
186
189
  });
187
190
  return state;
188
191
  }
@@ -15,6 +15,11 @@ export interface StartedServer {
15
15
  status: 'ready' | 'starting' | 'unavailable';
16
16
  detail?: string;
17
17
  }
18
+ /** One running language server as shown to the UI. Never inferred: the process must be running. */
19
+ export interface RunningServer {
20
+ id: string;
21
+ root: string;
22
+ }
18
23
  export interface PoolOptions {
19
24
  /** Maximum number of concurrently running servers. */
20
25
  maxRunning?: number;
@@ -35,10 +40,13 @@ export declare class ServerPool {
35
40
  private readonly cleanupFailures;
36
41
  constructor(options?: PoolOptions);
37
42
  get size(): number;
43
+ /** Servers whose process is running right now. Stopped or failed starts are not listed. */
44
+ running(): RunningServer[];
38
45
  acquire(parts: PoolKeyParts, launch: {
39
46
  command: string;
40
47
  args: string[];
41
48
  }, signal?: AbortSignal): Promise<StartedServer>;
49
+ private startEntry;
42
50
  find(root: string, id: string, configDigest: string): LspServer | undefined;
43
51
  private releaseOldestIdle;
44
52
  /** Resolves once every detached stop has completed; used before a caller reports closure. */
@@ -26,11 +26,19 @@ export class ServerPool {
26
26
  };
27
27
  }
28
28
  get size() { return this.entries.size; }
29
+ /** Servers whose process is running right now. Stopped or failed starts are not listed. */
30
+ running() {
31
+ return [...this.entries.values()]
32
+ .filter(entry => entry.server.running)
33
+ .map(entry => ({ id: entry.id, root: entry.root }));
34
+ }
29
35
  async acquire(parts, launch, signal) {
30
36
  const key = poolKey(parts);
31
37
  const existing = this.entries.get(key);
32
38
  if (existing) {
33
39
  existing.lastUsed = Date.now();
40
+ if (existing.starting)
41
+ return { ...await existing.starting, reused: true };
34
42
  if (existing.server.running)
35
43
  return { server: existing.server, reused: true, status: 'ready' };
36
44
  this.entries.delete(key);
@@ -48,20 +56,30 @@ export class ServerPool {
48
56
  root: parts.root,
49
57
  requestTimeoutMs: this.options.requestTimeoutMs,
50
58
  });
51
- this.entries.set(key, { server, key, root: parts.root, id: parts.language.id, lastUsed: Date.now() });
59
+ const entry = { server, key, root: parts.root, id: parts.language.id, lastUsed: Date.now() };
60
+ this.entries.set(key, entry);
61
+ entry.starting = this.startEntry(entry, signal);
62
+ return entry.starting;
63
+ }
64
+ async startEntry(entry, signal) {
65
+ const { server, key } = entry;
52
66
  try {
53
67
  await server.start(signal);
54
68
  return { server, reused: false, status: 'ready' };
55
69
  }
56
70
  catch (e) {
57
- this.entries.delete(key);
71
+ if (this.entries.get(key)?.server === server)
72
+ this.entries.delete(key);
58
73
  await server.dispose();
59
74
  return { server, reused: false, status: 'unavailable', detail: e instanceof Error ? e.message : String(e) };
60
75
  }
76
+ finally {
77
+ delete entry.starting;
78
+ }
61
79
  }
62
80
  find(root, id, configDigest) {
63
81
  const entry = this.entries.get(serverKey(realRoot(root), id, configDigest));
64
- return entry?.server.running ? entry.server : undefined;
82
+ return entry?.server.running && !entry.starting ? entry.server : undefined;
65
83
  }
66
84
  releaseOldestIdle() {
67
85
  let oldest;
@@ -1,5 +1,5 @@
1
- import { type LanguageSettings } from '../detect.ts';
2
- import { ServerPool, type Aggregate } from './pool.ts';
1
+ import { type Detection, type LanguageSettings } from '../detect.ts';
2
+ import { ServerPool, type Aggregate, type RunningServer } from './pool.ts';
3
3
  import type { ServerDiagnostic } from './client.ts';
4
4
  export interface LanguageServiceOptions {
5
5
  root: string;
@@ -30,9 +30,13 @@ export declare class LanguageService {
30
30
  private disposed;
31
31
  constructor(options: LanguageServiceOptions);
32
32
  get poolSize(): number;
33
- /** The already-running server for a file, if its language/root was analyzed before. */
33
+ /** Running language servers, for display. Callers must not infer readiness from this list. */
34
+ runningServers(): RunningServer[];
35
+ /** The ready server for a file, if its server target was analyzed before. */
34
36
  poolFor(file: string, selector?: 'tailwind'): import('./client.ts').LspServer | undefined;
35
- detect(file: string): import("../detect.ts").Detection | undefined;
37
+ detect(file: string): Detection | undefined;
38
+ private serverTarget;
39
+ private preferredRoot;
36
40
  /** Analyze a file after a read or a successful write. Never throws. */
37
41
  analyze(file: string, text: string, signal?: AbortSignal, selector?: 'tailwind'): Promise<AnalyzeResult>;
38
42
  private analyzeGuarded;