@soddong/agentic-runtime 0.16.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 (114) hide show
  1. package/.tbls.yml +103 -0
  2. package/CHANGELOG.md +229 -0
  3. package/README.md +707 -0
  4. package/dist/agent-router.d.ts +39 -0
  5. package/dist/agent-router.d.ts.map +1 -0
  6. package/dist/agent-router.js +175 -0
  7. package/dist/agent-router.js.map +1 -0
  8. package/dist/bundle-installer.d.ts +25 -0
  9. package/dist/bundle-installer.d.ts.map +1 -0
  10. package/dist/bundle-installer.js +149 -0
  11. package/dist/bundle-installer.js.map +1 -0
  12. package/dist/bundle-registry.d.ts +30 -0
  13. package/dist/bundle-registry.d.ts.map +1 -0
  14. package/dist/bundle-registry.js +102 -0
  15. package/dist/bundle-registry.js.map +1 -0
  16. package/dist/claude-code-adapter.d.ts +27 -0
  17. package/dist/claude-code-adapter.d.ts.map +1 -0
  18. package/dist/claude-code-adapter.js +177 -0
  19. package/dist/claude-code-adapter.js.map +1 -0
  20. package/dist/cli.d.ts +3 -0
  21. package/dist/cli.d.ts.map +1 -0
  22. package/dist/cli.js +1731 -0
  23. package/dist/cli.js.map +1 -0
  24. package/dist/codex-adapter.d.ts +23 -0
  25. package/dist/codex-adapter.d.ts.map +1 -0
  26. package/dist/codex-adapter.js +264 -0
  27. package/dist/codex-adapter.js.map +1 -0
  28. package/dist/database.d.ts +22 -0
  29. package/dist/database.d.ts.map +1 -0
  30. package/dist/database.js +184 -0
  31. package/dist/database.js.map +1 -0
  32. package/dist/execution-projects.d.ts +71 -0
  33. package/dist/execution-projects.d.ts.map +1 -0
  34. package/dist/execution-projects.js +333 -0
  35. package/dist/execution-projects.js.map +1 -0
  36. package/dist/execution-query.d.ts +73 -0
  37. package/dist/execution-query.d.ts.map +1 -0
  38. package/dist/execution-query.js +370 -0
  39. package/dist/execution-query.js.map +1 -0
  40. package/dist/execution.d.ts +47 -0
  41. package/dist/execution.d.ts.map +1 -0
  42. package/dist/execution.js +153 -0
  43. package/dist/execution.js.map +1 -0
  44. package/dist/hook-command.d.ts +3 -0
  45. package/dist/hook-command.d.ts.map +1 -0
  46. package/dist/hook-command.js +13 -0
  47. package/dist/hook-command.js.map +1 -0
  48. package/dist/hook-record.d.ts +16 -0
  49. package/dist/hook-record.d.ts.map +1 -0
  50. package/dist/hook-record.js +427 -0
  51. package/dist/hook-record.js.map +1 -0
  52. package/dist/index.d.ts +29 -0
  53. package/dist/index.d.ts.map +1 -0
  54. package/dist/index.js +15 -0
  55. package/dist/index.js.map +1 -0
  56. package/dist/kiro-adapter.d.ts +38 -0
  57. package/dist/kiro-adapter.d.ts.map +1 -0
  58. package/dist/kiro-adapter.js +374 -0
  59. package/dist/kiro-adapter.js.map +1 -0
  60. package/dist/module-registry.d.ts +21 -0
  61. package/dist/module-registry.d.ts.map +1 -0
  62. package/dist/module-registry.js +75 -0
  63. package/dist/module-registry.js.map +1 -0
  64. package/dist/runtime-info.d.ts +8 -0
  65. package/dist/runtime-info.d.ts.map +1 -0
  66. package/dist/runtime-info.js +15 -0
  67. package/dist/runtime-info.js.map +1 -0
  68. package/dist/seed-importer.d.ts +77 -0
  69. package/dist/seed-importer.d.ts.map +1 -0
  70. package/dist/seed-importer.js +570 -0
  71. package/dist/seed-importer.js.map +1 -0
  72. package/docs/build.md +129 -0
  73. package/docs/configuration.md +61 -0
  74. package/docs/delivery.md +90 -0
  75. package/docs/operations.md +112 -0
  76. package/docs/publishing.md +196 -0
  77. package/docs/schema/generated/README.md +31 -0
  78. package/docs/schema/generated/agentic_execution_logs.md +90 -0
  79. package/docs/schema/generated/agentic_execution_logs.svg +52 -0
  80. package/docs/schema/generated/agentic_execution_outputs.md +85 -0
  81. package/docs/schema/generated/agentic_execution_outputs.svg +52 -0
  82. package/docs/schema/generated/agentic_execution_project_activities.md +83 -0
  83. package/docs/schema/generated/agentic_execution_project_activities.svg +71 -0
  84. package/docs/schema/generated/agentic_execution_project_stages.md +69 -0
  85. package/docs/schema/generated/agentic_execution_project_stages.svg +71 -0
  86. package/docs/schema/generated/agentic_execution_projects.md +82 -0
  87. package/docs/schema/generated/agentic_execution_projects.svg +92 -0
  88. package/docs/schema/generated/agentic_execution_runs.md +111 -0
  89. package/docs/schema/generated/agentic_execution_runs.svg +92 -0
  90. package/docs/schema/generated/agentic_project_bundles.md +106 -0
  91. package/docs/schema/generated/agentic_project_bundles.svg +91 -0
  92. package/docs/schema/generated/agentic_project_modules.md +77 -0
  93. package/docs/schema/generated/agentic_project_modules.svg +49 -0
  94. package/docs/schema/generated/agentic_runtime_metadata.md +62 -0
  95. package/docs/schema/generated/agentic_runtime_metadata.svg +28 -0
  96. package/docs/schema/generated/agentic_schema_migrations.md +65 -0
  97. package/docs/schema/generated/agentic_schema_migrations.svg +32 -0
  98. package/docs/schema/generated/agentic_seed_import_items.md +85 -0
  99. package/docs/schema/generated/agentic_seed_import_items.svg +47 -0
  100. package/docs/schema/generated/agentic_seed_import_runs.md +103 -0
  101. package/docs/schema/generated/agentic_seed_import_runs.svg +68 -0
  102. package/docs/schema/generated/agentic_user_requests.md +66 -0
  103. package/docs/schema/generated/agentic_user_requests.svg +52 -0
  104. package/docs/schema/generated/schema.json +1976 -0
  105. package/docs/schema/generated/schema.mmd +167 -0
  106. package/docs/schema/generated/schema.svg +266 -0
  107. package/docs/schema/migrations.md +163 -0
  108. package/docs/usage.md +774 -0
  109. package/package.json +32 -0
  110. package/src/database/migrations/0001_runtime_base.sql +231 -0
  111. package/src/database/migrations/0002_runtime_bundles.sql +61 -0
  112. package/src/database/migrations/0003_runtime_seed_imports.sql +121 -0
  113. package/src/database/migrations/0004_runtime_seed_apply_status.sql +76 -0
  114. package/src/database/migrations/0005_runtime_execution_projects.sql +92 -0
package/dist/cli.js ADDED
@@ -0,0 +1,1731 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { spawnSync } from "node:child_process";
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { basename, dirname, join, relative } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { getClaudeCodeAdapterStatus, installClaudeCodeAdapter } from "./claude-code-adapter.js";
8
+ import { getCodexAdapterStatus, installCodexAdapter } from "./codex-adapter.js";
9
+ import { getRuntimeDatabaseStatus, initializeRuntimeDatabase } from "./database.js";
10
+ import { runRuntimeExecution } from "./execution.js";
11
+ import { getExecutionDetail, getLatestExecution, listExecutions, summarizeExecutions } from "./execution-query.js";
12
+ import { recordHook } from "./hook-record.js";
13
+ import { getRuntimeInfo } from "./index.js";
14
+ import { getKiroAdapterStatus, installKiroAdapter } from "./kiro-adapter.js";
15
+ import { listProjectModules, parseModuleLayer, registerProjectModule } from "./module-registry.js";
16
+ import { assembleRegisteredAgentContext, isAgentContribution, registerAgentContribution } from "./agent-router.js";
17
+ import { installProjectBundle } from "./bundle-installer.js";
18
+ import { listProjectBundles } from "./bundle-registry.js";
19
+ import { applySeedImportPlan, createSeedImportPlan, listSeedImportPlans } from "./seed-importer.js";
20
+ import { createExecutionProjectFromBundle, getExecutionProjectStatus } from "./execution-projects.js";
21
+ const HELP_TEXT = `agentic - Agentic Platform local execution CLI
22
+
23
+ Usage:
24
+ agentic <command> [options]
25
+
26
+ Commands:
27
+ help Show this help message
28
+ version Show runtime version
29
+ init Initialize an Agentic execution project
30
+ docs Show package documentation locations
31
+ config Show current Agentic project configuration status
32
+ setup Bootstrap Agentic project and adapter configuration
33
+ run <request> Record a user request through runtime execution
34
+ execution list List recorded execution history
35
+ execution latest Show the latest recorded execution
36
+ execution show Show one execution detail
37
+ execution summary Summarize recorded execution history
38
+ agent register Register an installed agent package contribution
39
+ agent context Assemble selected agent resource context
40
+ hook record Record an agent tool hook event
41
+ db init Initialize project-local platform.sqlite
42
+ db status Show project-local database status
43
+ adapter install Install an Agentic adapter and initialize runtime if needed
44
+ adapter status Show adapter installation status
45
+ module register Register an Agentic package in this project
46
+ module list List registered Agentic packages
47
+ bundle install Register an installed methodology seed bundle in this project
48
+ bundle apply Install/register a bundle and apply its seed in one flow
49
+ bundle list List installed project bundles
50
+ bundle status Show installed project bundle status
51
+ seed import Create a dry-run seed import plan from an installed bundle
52
+ seed apply Apply a seed import plan through target package handlers
53
+ seed status Show seed import plan status
54
+ project create Create an execution project from an applied bundle
55
+ project status Show execution project status
56
+
57
+ Planned commands:
58
+ validate Run validation
59
+ render Render reports
60
+ `;
61
+ function printHelp() {
62
+ console.log(HELP_TEXT);
63
+ }
64
+ function printVersion() {
65
+ const info = getRuntimeInfo();
66
+ console.log(`${info.name} ${info.version}`);
67
+ }
68
+ function getPackageRoot() {
69
+ return new URL("..", import.meta.url).pathname;
70
+ }
71
+ function printDocs() {
72
+ const packageRoot = getPackageRoot();
73
+ const docs = [
74
+ ["README", join(packageRoot, "README.md")],
75
+ ["Usage", join(packageRoot, "docs", "usage.md")],
76
+ ["Configuration", join(packageRoot, "docs", "configuration.md")],
77
+ ["Operations", join(packageRoot, "docs", "operations.md")],
78
+ ["Build", join(packageRoot, "docs", "build.md")],
79
+ ["Publishing", join(packageRoot, "docs", "publishing.md")],
80
+ ["Delivery", join(packageRoot, "docs", "delivery.md")]
81
+ ];
82
+ const info = getRuntimeInfo();
83
+ console.log(`${info.name} ${info.version}`);
84
+ console.log("");
85
+ console.log("Package documentation:");
86
+ for (const [label, path] of docs) {
87
+ const status = existsSync(path) ? "" : " (missing)";
88
+ console.log(` ${label.padEnd(13)} ${path}${status}`);
89
+ }
90
+ console.log("");
91
+ console.log("Project documentation:");
92
+ console.log(` ${join(process.cwd(), ".agentic", "README.md")}`);
93
+ }
94
+ function getConfigPath(cwd = process.cwd()) {
95
+ return join(cwd, "agentic.config.json");
96
+ }
97
+ function printConfigStatus() {
98
+ const cwd = process.cwd();
99
+ const configPath = getConfigPath(cwd);
100
+ const agenticDir = join(cwd, ".agentic");
101
+ console.log("Agentic project configuration");
102
+ console.log("");
103
+ console.log(`Project root: ${cwd}`);
104
+ console.log(`Config file : ${configPath} ${existsSync(configPath) ? "(found)" : "(missing)"}`);
105
+ console.log(`Work dir : ${agenticDir} ${existsSync(agenticDir) ? "(found)" : "(missing)"}`);
106
+ if (!existsSync(configPath)) {
107
+ console.log("");
108
+ console.log("Run 'agentic init' to create the default project configuration.");
109
+ return;
110
+ }
111
+ try {
112
+ const config = JSON.parse(readFileSync(configPath, "utf8"));
113
+ console.log("");
114
+ console.log("Config JSON : valid");
115
+ console.log(JSON.stringify(config, null, 2));
116
+ }
117
+ catch (error) {
118
+ const message = error instanceof Error ? error.message : String(error);
119
+ console.log("");
120
+ console.log("Config JSON : invalid");
121
+ console.log(message);
122
+ }
123
+ }
124
+ function writeFileIfMissing(path, content) {
125
+ if (existsSync(path)) {
126
+ return "exists";
127
+ }
128
+ writeFileSync(path, content, "utf8");
129
+ return "created";
130
+ }
131
+ const AGENTIC_INSTRUCTIONS_START_PATTERN = /<!-- agentic-runtime:start version=([^ >]+) -->/;
132
+ const AGENTIC_INSTRUCTIONS_BLOCK_PATTERN = /<!-- agentic-runtime:start version=[^ >]+ -->[\s\S]*?<!-- agentic-runtime:end -->/;
133
+ function createHookWrapperContent() {
134
+ const runtimeModuleUrl = new URL("./index.js", import.meta.url).href;
135
+ return `#!/usr/bin/env node
136
+ import { recordHook } from ${JSON.stringify(runtimeModuleUrl)};
137
+
138
+ let input = "";
139
+ process.stdin.setEncoding("utf8");
140
+
141
+ for await (const chunk of process.stdin) {
142
+ input += chunk;
143
+ }
144
+
145
+ function readOption(name) {
146
+ const index = process.argv.indexOf(name);
147
+ return index >= 0 ? process.argv[index + 1] : undefined;
148
+ }
149
+
150
+ const source = readOption("--source");
151
+ const event = readOption("--event");
152
+
153
+ if (source === undefined || event === undefined) {
154
+ console.error("Usage: agentic-hook --source <source> --event <event>");
155
+ process.exit(1);
156
+ }
157
+
158
+ const rawPayload =
159
+ input.trim().length > 0 || source !== "kiro" || event !== "PromptSubmit"
160
+ ? input
161
+ : JSON.stringify({
162
+ prompt: process.env.USER_PROMPT ?? ""
163
+ });
164
+
165
+ try {
166
+ const result = recordHook({
167
+ source,
168
+ event,
169
+ rawPayload
170
+ });
171
+
172
+ if (result.action === "skipped" && result.reason !== undefined) {
173
+ console.error(\`agentic hook skipped: \${result.reason}\`);
174
+ }
175
+ } catch (error) {
176
+ const message = error instanceof Error ? error.message : String(error);
177
+ console.error(\`agentic hook record failed: \${message}\`);
178
+ }
179
+ `;
180
+ }
181
+ function ensureHookWrapper() {
182
+ const wrapperPath = join(process.cwd(), ".agentic", "bin", "agentic-hook.mjs");
183
+ mkdirSync(join(wrapperPath, ".."), { recursive: true });
184
+ return writeFileIfMissing(wrapperPath, createHookWrapperContent());
185
+ }
186
+ const AGENT_INSTRUCTIONS_BODY = `이 블록은 agentic-runtime이 관리하는 Agent 실행 지침입니다.
187
+ 사용자가 직접 작성한 내용은 이 managed block 밖에 둡니다.
188
+
189
+ ## Runtime Execution Policy
190
+
191
+ - 이 프로젝트에서 Agentic Platform 관련 작업을 수행할 때는 먼저 사용자 지시를 runtime execution으로 기록합니다.
192
+ - 기본 명령은 다음과 같습니다.
193
+
194
+ \`\`\`bash
195
+ npx agentic run "<사용자 지시문>"
196
+ \`\`\`
197
+
198
+ - 현재 \`agentic run\`은 router 또는 개별 Agent module 실행 전 단계의 공통 execution 기록입니다.
199
+ - 실제 작업 수행 내용이 별도 도구나 Agent module에서 실행되더라도, 사용자 지시와 실행 접수 이력은 \`.agentic/platform.sqlite\`에 남깁니다.
200
+ - 기록 대상은 사용자 지시, 실행 run, 실행 로그, 실행 결과입니다.
201
+
202
+ ## Runtime History Query Policy
203
+
204
+ - 사용자가 이전 지시, 작업 이력, 최근 결과, 실패 이력, 작업 현황을 질문하면 현재 대화 기억에만 의존하지 않고 execution DB를 먼저 확인합니다.
205
+ - 기본 조회 명령은 다음과 같습니다.
206
+
207
+ \`\`\`bash
208
+ npx agentic execution list --range 7d --format json
209
+ npx agentic execution summary --range today --format json
210
+ npx agentic execution latest --format json
211
+ npx agentic execution latest --range today --status succeeded --format json
212
+ \`\`\`
213
+
214
+ - 이전 지시, 이전 결과, 마지막 완료 작업을 묻는 경우에는 현재 실행 중인 자기 run을 피하기 위해 \`--status succeeded\`를 우선 사용합니다.
215
+ - 현재 실행 중인 작업을 묻는 경우에는 \`--status running\`, 실패 이력을 묻는 경우에는 \`--status failed\`를 사용합니다.
216
+ - 조회 결과가 있으면 \`agentic_user_requests\`, \`agentic_execution_runs\`, \`agentic_execution_logs\`, \`agentic_execution_outputs\` 기록을 기준으로 답변합니다.
217
+ - 조회 결과가 없거나 불완전한 경우에만 현재 대화 context와 파일 상태를 보조적으로 사용합니다.
218
+
219
+ ## Scope
220
+
221
+ - \`agentic-runtime\`은 공통 실행 기반입니다.
222
+ - 개별 업무 Agent module은 별도 npm package로 제공됩니다.
223
+ - router와 개별 Agent module 연계 전까지는 \`agentic run\`을 공통 실행 접수 및 감사 추적 기준으로 사용합니다.
224
+
225
+ ## Agent Resource Context Policy
226
+
227
+ - 사용자가 문서 작성, 산출물 작성, 검증, 가이드 기반 작업을 요청하면 설치된 Agent package의 resource context를 먼저 확인할 수 있습니다.
228
+ - 기본 명령은 다음과 같습니다.
229
+
230
+ \`\`\`bash
231
+ npx agentic agent context "<사용자 지시문>"
232
+ npx agentic agent context "<사용자 지시문>" --format json
233
+ \`\`\`
234
+
235
+ - 이 명령은 등록된 agent contribution을 라우팅하고, 선택된 resource file을 읽어 LLM context용 Markdown text로 조립합니다.
236
+ - 설치된 agent package를 먼저 등록해야 하는 경우 다음 명령을 사용합니다.
237
+
238
+ \`\`\`bash
239
+ npx agentic agent register <package-name>
240
+ \`\`\`
241
+
242
+ - 선택 결과가 없거나 package root를 확인할 수 없으면 현재 대화 context와 파일 상태를 보조적으로 사용합니다.
243
+ `;
244
+ function compareVersion(left, right) {
245
+ const leftParts = left.split(/[.-]/).map((part) => Number.parseInt(part, 10));
246
+ const rightParts = right.split(/[.-]/).map((part) => Number.parseInt(part, 10));
247
+ const length = Math.max(leftParts.length, rightParts.length);
248
+ for (let index = 0; index < length; index += 1) {
249
+ const leftValue = Number.isFinite(leftParts[index]) ? leftParts[index] : 0;
250
+ const rightValue = Number.isFinite(rightParts[index]) ? rightParts[index] : 0;
251
+ if (leftValue > rightValue) {
252
+ return 1;
253
+ }
254
+ if (leftValue < rightValue) {
255
+ return -1;
256
+ }
257
+ }
258
+ return 0;
259
+ }
260
+ function createManagedAgentInstructionsBlock(version) {
261
+ return `<!-- agentic-runtime:start version=${version} -->\n${AGENT_INSTRUCTIONS_BODY.trimEnd()}\n<!-- agentic-runtime:end -->\n`;
262
+ }
263
+ function createAgentInstructionsFile(version) {
264
+ return `# Agentic Runtime Instructions\n\n${createManagedAgentInstructionsBlock(version)}`;
265
+ }
266
+ function isLegacyGeneratedAgentInstructions(content) {
267
+ return (content.includes("이 파일은 agentic-runtime이 생성한 Agent 실행 지침 템플릿입니다.") &&
268
+ content.includes("프로젝트 루트의 AGENTS.md에 필요한 내용을 반영해 사용합니다.") &&
269
+ content.includes("## Runtime Execution Policy"));
270
+ }
271
+ function stripLegacyGeneratedPrefix(content) {
272
+ const markerIndex = content.indexOf("<!-- agentic-runtime:start");
273
+ if (markerIndex <= 0 || !isLegacyGeneratedAgentInstructions(content.slice(0, markerIndex))) {
274
+ return content;
275
+ }
276
+ return `# Agentic Runtime Instructions\n\n${content.slice(markerIndex).trimStart()}`;
277
+ }
278
+ function upsertAgentInstructions(path) {
279
+ const version = getRuntimeInfo().version;
280
+ if (!existsSync(path)) {
281
+ writeFileSync(path, createAgentInstructionsFile(version), "utf8");
282
+ return "created";
283
+ }
284
+ const current = stripLegacyGeneratedPrefix(readFileSync(path, "utf8"));
285
+ const versionMatch = AGENTIC_INSTRUCTIONS_START_PATTERN.exec(current);
286
+ const nextBlock = createManagedAgentInstructionsBlock(version);
287
+ if (versionMatch !== null) {
288
+ const currentVersion = versionMatch[1] ?? "0.0.0";
289
+ const comparison = compareVersion(currentVersion, version);
290
+ if (comparison > 0) {
291
+ return "newer_exists";
292
+ }
293
+ if (comparison === 0 && current === readFileSync(path, "utf8")) {
294
+ return "exists";
295
+ }
296
+ writeFileSync(path, current.replace(AGENTIC_INSTRUCTIONS_BLOCK_PATTERN, nextBlock.trimEnd()), "utf8");
297
+ return "updated";
298
+ }
299
+ if (isLegacyGeneratedAgentInstructions(current)) {
300
+ writeFileSync(path, createAgentInstructionsFile(version), "utf8");
301
+ return "updated";
302
+ }
303
+ const separator = current.endsWith("\n") ? "\n" : "\n\n";
304
+ writeFileSync(path, `${current}${separator}${nextBlock}`, "utf8");
305
+ return "appended";
306
+ }
307
+ function initializeProject() {
308
+ const cwd = process.cwd();
309
+ const projectName = basename(cwd);
310
+ const agenticDir = join(cwd, ".agentic");
311
+ const directories = [agenticDir, join(agenticDir, "data"), join(agenticDir, "logs"), join(agenticDir, "modules")];
312
+ for (const directory of directories) {
313
+ mkdirSync(directory, { recursive: true });
314
+ }
315
+ const configPath = getConfigPath(cwd);
316
+ const config = {
317
+ projectName,
318
+ runtime: {
319
+ database: {
320
+ type: "sqlite",
321
+ path: ".agentic/platform.sqlite"
322
+ }
323
+ },
324
+ modules: []
325
+ };
326
+ const configStatus = writeFileIfMissing(configPath, `${JSON.stringify(config, null, 2)}\n`);
327
+ const readmePath = join(agenticDir, "README.md");
328
+ const readmeStatus = writeFileIfMissing(readmePath, `# Agentic Project\n\nThis directory is managed by agentic-runtime.\n\n- data/: local runtime data\n- logs/: runtime logs\n- modules/: installed Agentic package metadata\n\nUse \`npx agentic docs\` to find package documentation.\nUse \`npx agentic db init\` to initialize the local SQLite database.\n`);
329
+ const agentInstructionsPath = join(agenticDir, "AGENTS.md");
330
+ const agentInstructionsStatus = upsertAgentInstructions(agentInstructionsPath);
331
+ const hookWrapperStatus = ensureHookWrapper();
332
+ console.log("Agentic project initialized");
333
+ console.log("");
334
+ console.log(`Project root: ${cwd}`);
335
+ console.log(`Config file : ${relative(cwd, configPath)} (${configStatus})`);
336
+ console.log(`Work dir : ${relative(cwd, agenticDir)}`);
337
+ console.log(`README : ${relative(cwd, readmePath)} (${readmeStatus})`);
338
+ console.log(`AGENTS : ${relative(cwd, agentInstructionsPath)} (${agentInstructionsStatus})`);
339
+ console.log(`Hook wrapper: ${relative(cwd, join(agenticDir, "bin", "agentic-hook.mjs"))} (${hookWrapperStatus})`);
340
+ }
341
+ function initializeDatabase() {
342
+ const result = initializeRuntimeDatabase();
343
+ console.log("Agentic runtime database initialized");
344
+ console.log("");
345
+ console.log(`Database: ${result.databasePath}`);
346
+ console.log(`Created : ${result.created ? "yes" : "no"}`);
347
+ console.log("Tables :");
348
+ for (const table of result.tables) {
349
+ console.log(` - ${table}`);
350
+ }
351
+ }
352
+ function ensureProjectRuntimeReady() {
353
+ const cwd = process.cwd();
354
+ const configPath = getConfigPath(cwd);
355
+ const agenticDir = join(cwd, ".agentic");
356
+ const readmePath = join(agenticDir, "README.md");
357
+ const agentInstructionsPath = join(agenticDir, "AGENTS.md");
358
+ const databaseStatus = getRuntimeDatabaseStatus();
359
+ if (!existsSync(configPath) || !existsSync(readmePath) || !existsSync(agentInstructionsPath)) {
360
+ initializeProject();
361
+ console.log("");
362
+ }
363
+ else {
364
+ const agentInstructionsStatus = upsertAgentInstructions(agentInstructionsPath);
365
+ if (agentInstructionsStatus !== "exists") {
366
+ console.log(`Agentic instructions ${agentInstructionsStatus}: ${relative(cwd, agentInstructionsPath)}`);
367
+ console.log("");
368
+ }
369
+ if (!existsSync(join(agenticDir, "bin", "agentic-hook.mjs"))) {
370
+ const hookWrapperStatus = ensureHookWrapper();
371
+ console.log(`Agentic hook wrapper ${hookWrapperStatus}: ${relative(cwd, join(agenticDir, "bin", "agentic-hook.mjs"))}`);
372
+ console.log("");
373
+ }
374
+ }
375
+ if (!databaseStatus.exists || databaseStatus.tables.length === 0) {
376
+ initializeDatabase();
377
+ console.log("");
378
+ }
379
+ }
380
+ function printDatabaseStatus() {
381
+ const status = getRuntimeDatabaseStatus();
382
+ console.log("Agentic runtime database status");
383
+ console.log("");
384
+ console.log(`Database: ${status.databasePath}`);
385
+ console.log(`Exists : ${status.exists ? "yes" : "no"}`);
386
+ if (status.tables.length === 0) {
387
+ console.log("Tables : none");
388
+ return;
389
+ }
390
+ console.log("Tables :");
391
+ for (const table of status.tables) {
392
+ console.log(` - ${table}`);
393
+ }
394
+ }
395
+ async function readStdin() {
396
+ let input = "";
397
+ process.stdin.setEncoding("utf8");
398
+ for await (const chunk of process.stdin) {
399
+ input += chunk;
400
+ }
401
+ return input;
402
+ }
403
+ async function runExecution(args) {
404
+ const requestText = args.join(" ").trim();
405
+ if (requestText.length === 0) {
406
+ console.error('Usage: agentic run "<user request>"');
407
+ return 1;
408
+ }
409
+ const result = await runRuntimeExecution({
410
+ runType: "command",
411
+ packageName: "@soddong/agentic-runtime",
412
+ commandName: "run",
413
+ inputText: requestText,
414
+ requestSource: "cli",
415
+ handler(context) {
416
+ context.logger.info("Runtime CLI request recorded", {
417
+ requestLength: requestText.length
418
+ });
419
+ return {
420
+ outputType: "json",
421
+ contentJson: {
422
+ message: "Request recorded by agentic-runtime.",
423
+ requestText
424
+ }
425
+ };
426
+ }
427
+ });
428
+ console.log("Agentic run completed");
429
+ console.log("");
430
+ console.log(`Run ID : ${result.runId}`);
431
+ console.log(`Request ID: ${result.requestId ?? "-"}`);
432
+ console.log(`Status : ${result.status}`);
433
+ console.log(`Duration : ${result.durationMs}ms`);
434
+ console.log(`Outputs : ${result.outputCount}`);
435
+ return result.status === "succeeded" ? 0 : 1;
436
+ }
437
+ function registerModule(args) {
438
+ const [packageName, packageVersion, moduleLayerValue] = args;
439
+ if (packageName === undefined || packageVersion === undefined) {
440
+ console.error("Usage: agentic module register <package-name> <package-version> [runtime|domain|capability|application|support]");
441
+ return 1;
442
+ }
443
+ try {
444
+ const moduleLayer = parseModuleLayer(moduleLayerValue);
445
+ const module = registerProjectModule({
446
+ packageName,
447
+ packageVersion,
448
+ moduleLayer
449
+ });
450
+ console.log("Agentic module registered");
451
+ console.log("");
452
+ console.log(`Package: ${module.packageName}`);
453
+ console.log(`Version: ${module.packageVersion}`);
454
+ console.log(`Layer : ${module.moduleLayer ?? "-"}`);
455
+ console.log(`Enabled: ${module.enabled ? "yes" : "no"}`);
456
+ return 0;
457
+ }
458
+ catch (error) {
459
+ const message = error instanceof Error ? error.message : String(error);
460
+ console.error(message);
461
+ return 1;
462
+ }
463
+ }
464
+ function printModuleList() {
465
+ const modules = listProjectModules();
466
+ console.log("Agentic project modules");
467
+ console.log("");
468
+ if (modules.length === 0) {
469
+ console.log("No modules registered.");
470
+ return;
471
+ }
472
+ for (const module of modules) {
473
+ console.log(`- ${module.packageName}@${module.packageVersion}`);
474
+ console.log(` layer : ${module.moduleLayer ?? "-"}`);
475
+ console.log(` enabled: ${module.enabled ? "yes" : "no"}`);
476
+ }
477
+ }
478
+ function isValidationValid(value) {
479
+ return (typeof value !== "object" ||
480
+ value === null ||
481
+ !("valid" in value) ||
482
+ value.valid !== false);
483
+ }
484
+ function validationIssueCount(value) {
485
+ if (typeof value !== "object" || value === null || !("issues" in value)) {
486
+ return 0;
487
+ }
488
+ const issues = value.issues;
489
+ return Array.isArray(issues) ? issues.length : 0;
490
+ }
491
+ function recordValue(value, key) {
492
+ return typeof value === "object" && value !== null ? value[key] : undefined;
493
+ }
494
+ function recordString(value, key) {
495
+ const raw = recordValue(value, key);
496
+ return typeof raw === "string" && raw.length > 0 ? raw : undefined;
497
+ }
498
+ function recordObject(value, key) {
499
+ const raw = recordValue(value, key);
500
+ return typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : undefined;
501
+ }
502
+ function readRequiredPackagesFromManifest(manifest) {
503
+ const requires = recordObject(manifest, "requires");
504
+ const packages = recordObject(requires, "packages");
505
+ if (packages === undefined) {
506
+ return {};
507
+ }
508
+ const result = {};
509
+ for (const [packageName, versionRange] of Object.entries(packages)) {
510
+ if (typeof versionRange === "string") {
511
+ result[packageName] = versionRange;
512
+ }
513
+ }
514
+ return result;
515
+ }
516
+ function inferModuleLayer(packageName) {
517
+ const normalizedPackageName = packageName.startsWith("@soddong/")
518
+ ? packageName.slice("@soddong/".length)
519
+ : packageName;
520
+ if (normalizedPackageName === "agentic-runtime") {
521
+ return "runtime";
522
+ }
523
+ if (normalizedPackageName.startsWith("agentic-domain-")) {
524
+ return "domain";
525
+ }
526
+ if (normalizedPackageName.startsWith("agentic-capability-")) {
527
+ return "capability";
528
+ }
529
+ if (normalizedPackageName.startsWith("agentic-contract-")) {
530
+ return "support";
531
+ }
532
+ return "support";
533
+ }
534
+ function installedPackageVersion(projectRoot, packageName) {
535
+ try {
536
+ const packageJsonPath = join(projectRoot, "node_modules", packageName, "package.json");
537
+ if (!existsSync(packageJsonPath)) {
538
+ return undefined;
539
+ }
540
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
541
+ return typeof packageJson.version === "string" ? packageJson.version : undefined;
542
+ }
543
+ catch {
544
+ return undefined;
545
+ }
546
+ }
547
+ function satisfiesSimpleRange(version, range) {
548
+ if (range.startsWith(">=")) {
549
+ return compareVersion(version, range.slice(2)) >= 0;
550
+ }
551
+ if (range.startsWith("^")) {
552
+ return compareVersion(version, range.slice(1)) >= 0;
553
+ }
554
+ if (/^\d+\.\d+\.\d+/.test(range)) {
555
+ return compareVersion(version, range) === 0;
556
+ }
557
+ return undefined;
558
+ }
559
+ function sanitizePackageJsonName(name) {
560
+ const sanitized = name
561
+ .toLowerCase()
562
+ .replace(/[^a-z0-9._-]+/g, "-")
563
+ .replace(/^-+|-+$/g, "");
564
+ return sanitized.length > 0 ? sanitized : "agentic-execution-project";
565
+ }
566
+ function ensureNpmProjectPackageJson(projectRoot) {
567
+ const packageJsonPath = join(projectRoot, "package.json");
568
+ if (existsSync(packageJsonPath)) {
569
+ return "exists";
570
+ }
571
+ writeFileSync(packageJsonPath, JSON.stringify({
572
+ name: sanitizePackageJsonName(basename(projectRoot)),
573
+ version: "0.0.0",
574
+ private: true,
575
+ type: "module"
576
+ }, null, 2) + "\n", "utf8");
577
+ return "created";
578
+ }
579
+ function packageInstallSpec(packageName, versionRange) {
580
+ const range = versionRange?.trim();
581
+ return range === undefined || range.length === 0 ? packageName : `${packageName}@${range}`;
582
+ }
583
+ function installNpmPackage(packageName, packageSpec, projectRoot) {
584
+ const result = spawnSync("npm", ["install", packageSpec], {
585
+ cwd: projectRoot,
586
+ encoding: "utf8",
587
+ stdio: ["ignore", "pipe", "pipe"]
588
+ });
589
+ if (result.status !== 0) {
590
+ return {
591
+ packageName,
592
+ packageSpec,
593
+ action: "failed",
594
+ exitCode: result.status,
595
+ stderr: result.stderr
596
+ };
597
+ }
598
+ return {
599
+ packageName,
600
+ packageSpec,
601
+ action: "installed",
602
+ installedVersion: installedPackageVersion(projectRoot, packageName),
603
+ exitCode: result.status
604
+ };
605
+ }
606
+ function installBundleProviderPackage(packageName, projectRoot) {
607
+ const installedVersion = installedPackageVersion(projectRoot, packageName);
608
+ if (installedVersion !== undefined) {
609
+ return {
610
+ packageName,
611
+ packageSpec: packageName,
612
+ action: "already_installed",
613
+ installedVersion
614
+ };
615
+ }
616
+ return installNpmPackage(packageName, packageName, projectRoot);
617
+ }
618
+ function installRequiredPackages(requiredPackages, projectRoot) {
619
+ return Object.entries(requiredPackages).map(([packageName, requiredVersion]) => {
620
+ const installedVersion = installedPackageVersion(projectRoot, packageName);
621
+ if (installedVersion !== undefined && satisfiesSimpleRange(installedVersion, requiredVersion) !== false) {
622
+ return {
623
+ packageName,
624
+ packageSpec: packageInstallSpec(packageName, requiredVersion),
625
+ action: "already_installed",
626
+ installedVersion
627
+ };
628
+ }
629
+ return installNpmPackage(packageName, packageInstallSpec(packageName, requiredVersion), projectRoot);
630
+ });
631
+ }
632
+ function registerInstalledRequiredPackages(requiredPackages, projectRoot = process.cwd()) {
633
+ return Object.entries(requiredPackages).map(([packageName, requiredVersion]) => {
634
+ const installedVersion = installedPackageVersion(projectRoot, packageName);
635
+ if (installedVersion === undefined) {
636
+ return {
637
+ packageName,
638
+ requiredVersion,
639
+ registered: false
640
+ };
641
+ }
642
+ const layer = inferModuleLayer(packageName);
643
+ registerProjectModule({
644
+ packageName,
645
+ packageVersion: installedVersion,
646
+ moduleLayer: layer,
647
+ manifest: {
648
+ packageName,
649
+ packageVersion: installedVersion,
650
+ requiredVersion,
651
+ autoRegisteredBy: "agentic bundle apply"
652
+ }
653
+ }, projectRoot);
654
+ return {
655
+ packageName,
656
+ requiredVersion,
657
+ installedVersion,
658
+ registered: true,
659
+ layer,
660
+ versionSatisfied: satisfiesSimpleRange(installedVersion, requiredVersion)
661
+ };
662
+ });
663
+ }
664
+ function printBundle(bundle) {
665
+ console.log(`- ${bundle.bundleCode}@${bundle.bundleVersion}`);
666
+ console.log(` package : ${bundle.packageName}@${bundle.packageVersion}`);
667
+ console.log(` methodology: ${bundle.methodologyCode ?? "-"}`);
668
+ console.log(` display : ${bundle.displayName ?? "-"}`);
669
+ console.log(` enabled : ${bundle.enabled ? "yes" : "no"}`);
670
+ console.log(` validation : ${isValidationValid(bundle.validationResult) ? "passed" : "failed"}`);
671
+ console.log(` issues : ${validationIssueCount(bundle.validationResult)}`);
672
+ }
673
+ function printBundleList(args = []) {
674
+ const format = readOptionValues(args, "--format")[0] ?? "text";
675
+ const bundles = listProjectBundles();
676
+ if (format === "json") {
677
+ console.log(JSON.stringify(bundles, null, 2));
678
+ return;
679
+ }
680
+ console.log("Agentic project bundles");
681
+ console.log("");
682
+ if (bundles.length === 0) {
683
+ console.log("No bundles installed.");
684
+ return;
685
+ }
686
+ for (const bundle of bundles) {
687
+ printBundle(bundle);
688
+ }
689
+ }
690
+ function printSeedImportPlan(plan) {
691
+ console.log(`- #${plan.run.seedImportRunId} ${plan.run.bundleCode}@${plan.run.bundleVersion}`);
692
+ console.log(` package : ${plan.run.packageName}@${plan.run.packageVersion}`);
693
+ console.log(` mode : ${plan.run.importMode}`);
694
+ console.log(` status : ${plan.run.importStatus}`);
695
+ console.log(` items : ${plan.run.summary.totalItems}`);
696
+ console.log(` planned : ${plan.run.summary.plannedItems}`);
697
+ console.log(` blocked : ${plan.run.summary.blockedItems}`);
698
+ console.log(` warnings : ${plan.run.summary.warningItems}`);
699
+ console.log(` skipped : ${plan.run.summary.skippedItems}`);
700
+ console.log(` applied : ${plan.run.summary.appliedItems}`);
701
+ console.log(` failed : ${plan.run.summary.failedItems}`);
702
+ for (const item of plan.items) {
703
+ const reason = item.reasonMessage === undefined ? "" : ` (${item.reasonMessage})`;
704
+ console.log(` - ${item.sourceSection} -> ${item.targetPackage}: ${item.itemStatus}${reason}`);
705
+ }
706
+ }
707
+ async function importSeed(args) {
708
+ const bundleCode = readOptionValues(args, "--bundle")[0];
709
+ const packageName = readOptionValues(args, "--package")[0];
710
+ const format = readOptionValues(args, "--format")[0] ?? "text";
711
+ if (bundleCode === undefined) {
712
+ console.error("Usage: agentic seed import --bundle <bundle-code> [--package <package-name>] [--format text|json]");
713
+ return 1;
714
+ }
715
+ try {
716
+ const plan = await createSeedImportPlan({
717
+ bundleCode,
718
+ packageName
719
+ });
720
+ if (format === "json") {
721
+ console.log(JSON.stringify(plan, null, 2));
722
+ return plan.run.importStatus === "applied" ? 0 : 1;
723
+ }
724
+ console.log("Agentic seed import plan created");
725
+ console.log("");
726
+ printSeedImportPlan(plan);
727
+ return 0;
728
+ }
729
+ catch (error) {
730
+ const message = error instanceof Error ? error.message : String(error);
731
+ console.error(`agentic seed import failed: ${message}`);
732
+ return 1;
733
+ }
734
+ }
735
+ async function applySeed(args) {
736
+ const runIdValue = readOptionValues(args, "--run")[0];
737
+ const bundleCode = readOptionValues(args, "--bundle")[0];
738
+ const packageName = readOptionValues(args, "--package")[0];
739
+ const format = readOptionValues(args, "--format")[0] ?? "text";
740
+ if (runIdValue === undefined && bundleCode === undefined) {
741
+ console.error("Usage: agentic seed apply --run <seed-import-run-id> [--format text|json]");
742
+ console.error(" or: agentic seed apply --bundle <bundle-code> [--package <package-name>] [--format text|json]");
743
+ return 1;
744
+ }
745
+ let seedImportRunId;
746
+ if (runIdValue !== undefined) {
747
+ seedImportRunId = Number.parseInt(runIdValue, 10);
748
+ if (!Number.isInteger(seedImportRunId) || seedImportRunId < 1) {
749
+ console.error(`Invalid seed import run id: ${runIdValue}`);
750
+ return 1;
751
+ }
752
+ }
753
+ try {
754
+ const plan = await applySeedImportPlan({
755
+ seedImportRunId,
756
+ bundleCode,
757
+ packageName
758
+ });
759
+ if (format === "json") {
760
+ console.log(JSON.stringify(plan, null, 2));
761
+ return 0;
762
+ }
763
+ console.log("Agentic seed apply completed");
764
+ console.log("");
765
+ printSeedImportPlan(plan);
766
+ return plan.run.importStatus === "applied" ? 0 : 1;
767
+ }
768
+ catch (error) {
769
+ const message = error instanceof Error ? error.message : String(error);
770
+ console.error(`agentic seed apply failed: ${message}`);
771
+ return 1;
772
+ }
773
+ }
774
+ function printSeedImportStatus(args = []) {
775
+ const format = readOptionValues(args, "--format")[0] ?? "text";
776
+ const plans = listSeedImportPlans();
777
+ if (format === "json") {
778
+ console.log(JSON.stringify(plans, null, 2));
779
+ return;
780
+ }
781
+ console.log("Agentic seed import status");
782
+ console.log("");
783
+ if (plans.length === 0) {
784
+ console.log("No seed import plans found.");
785
+ return;
786
+ }
787
+ for (const plan of plans) {
788
+ printSeedImportPlan(plan);
789
+ }
790
+ }
791
+ async function installBundle(args) {
792
+ const packageName = args[0]?.startsWith("-") === false ? args[0] : undefined;
793
+ const bundleCode = readOptionValues(args, "--bundle")[0];
794
+ if (packageName === undefined) {
795
+ console.error("Usage: agentic bundle install <package-name> [--bundle <bundle-code>]");
796
+ return 1;
797
+ }
798
+ try {
799
+ const result = await installProjectBundle({
800
+ packageName,
801
+ bundleCode
802
+ });
803
+ console.log("Agentic bundle installed");
804
+ console.log("");
805
+ console.log(`Package : ${result.packageName}@${result.packageVersion}`);
806
+ console.log(`Package root : ${result.packageRoot}`);
807
+ console.log(`Bundle : ${result.bundle.bundleCode}@${result.bundle.bundleVersion}`);
808
+ console.log(`Methodology : ${result.bundle.methodologyCode ?? "-"}`);
809
+ console.log(`Display name : ${result.bundle.displayName ?? "-"}`);
810
+ console.log(`Validation : ${isValidationValid(result.validation) ? "passed" : "failed"}`);
811
+ console.log(`Validation issues: ${validationIssueCount(result.validation)}`);
812
+ console.log(`Stages : ${result.summary.stageCount}`);
813
+ console.log(`Activities : ${result.summary.activityCount}`);
814
+ console.log(`Artifact reqs : ${result.summary.artifactRequirementCount}`);
815
+ console.log(`Generated outputs: ${result.summary.generatedOutputLinkCount}`);
816
+ return 0;
817
+ }
818
+ catch (error) {
819
+ const message = error instanceof Error ? error.message : String(error);
820
+ console.error(`agentic bundle install failed: ${message}`);
821
+ return 1;
822
+ }
823
+ }
824
+ async function applyBundle(args) {
825
+ const packageName = args[0]?.startsWith("-") === false ? args[0] : undefined;
826
+ const bundleCode = readOptionValues(args, "--bundle")[0];
827
+ const format = readOptionValues(args, "--format")[0] ?? "text";
828
+ const strictRequired = hasArg(args, "--strict-required");
829
+ const installRequired = hasArg(args, "--install-required");
830
+ if (packageName === undefined) {
831
+ console.error("Usage: agentic bundle apply <package-name> [--bundle <bundle-code>] [--format text|json] [--strict-required] [--install-required]");
832
+ return 1;
833
+ }
834
+ try {
835
+ const projectRoot = process.cwd();
836
+ const installResults = [];
837
+ if (installRequired) {
838
+ ensureNpmProjectPackageJson(projectRoot);
839
+ const providerInstallResult = installBundleProviderPackage(packageName, projectRoot);
840
+ installResults.push(providerInstallResult);
841
+ if (providerInstallResult.action === "failed") {
842
+ const result = {
843
+ status: "failed",
844
+ installResults
845
+ };
846
+ if (format === "json") {
847
+ console.log(JSON.stringify(result, null, 2));
848
+ }
849
+ else {
850
+ console.error(`agentic bundle apply failed: npm install ${providerInstallResult.packageSpec}`);
851
+ if (providerInstallResult.stderr !== undefined && providerInstallResult.stderr.trim().length > 0) {
852
+ console.error(providerInstallResult.stderr.trim());
853
+ }
854
+ }
855
+ return 1;
856
+ }
857
+ }
858
+ ensureProjectRuntimeReady();
859
+ const installedBundle = await installProjectBundle({
860
+ packageName,
861
+ bundleCode
862
+ });
863
+ const requiredPackages = readRequiredPackagesFromManifest(installedBundle.bundle.bundleManifest);
864
+ if (installRequired) {
865
+ const requiredInstallResults = installRequiredPackages(requiredPackages, projectRoot);
866
+ installResults.push(...requiredInstallResults);
867
+ const failedInstall = requiredInstallResults.find((item) => item.action === "failed");
868
+ if (failedInstall !== undefined) {
869
+ const result = {
870
+ status: "failed",
871
+ bundle: installedBundle,
872
+ installResults
873
+ };
874
+ if (format === "json") {
875
+ console.log(JSON.stringify(result, null, 2));
876
+ }
877
+ else {
878
+ console.error(`agentic bundle apply failed: npm install ${failedInstall.packageSpec}`);
879
+ if (failedInstall.stderr !== undefined && failedInstall.stderr.trim().length > 0) {
880
+ console.error(failedInstall.stderr.trim());
881
+ }
882
+ }
883
+ return 1;
884
+ }
885
+ }
886
+ const registrations = registerInstalledRequiredPackages(requiredPackages);
887
+ const missingRequiredPackages = registrations.filter((item) => !item.registered);
888
+ const unsatisfiedRequiredPackages = registrations.filter((item) => item.versionSatisfied === false);
889
+ if (strictRequired && (missingRequiredPackages.length > 0 || unsatisfiedRequiredPackages.length > 0)) {
890
+ const result = {
891
+ status: "blocked",
892
+ bundle: installedBundle,
893
+ requiredPackages: registrations,
894
+ missingRequiredPackages,
895
+ unsatisfiedRequiredPackages
896
+ };
897
+ if (format === "json") {
898
+ console.log(JSON.stringify(result, null, 2));
899
+ }
900
+ else {
901
+ console.log("Agentic bundle apply blocked");
902
+ console.log("");
903
+ console.log(`Bundle: ${installedBundle.bundle.bundleCode}@${installedBundle.bundle.bundleVersion}`);
904
+ printNpmInstallSummary(installResults);
905
+ console.log("");
906
+ printRequiredPackageRegistrationSummary(registrations);
907
+ }
908
+ return 1;
909
+ }
910
+ await createSeedImportPlan({
911
+ bundleCode: installedBundle.bundle.bundleCode,
912
+ packageName: installedBundle.packageName
913
+ });
914
+ const appliedPlan = await applySeedImportPlan({
915
+ bundleCode: installedBundle.bundle.bundleCode,
916
+ packageName: installedBundle.packageName
917
+ });
918
+ const result = {
919
+ status: appliedPlan.run.importStatus,
920
+ bundle: installedBundle,
921
+ installResults,
922
+ requiredPackages: registrations,
923
+ missingRequiredPackages,
924
+ unsatisfiedRequiredPackages,
925
+ seedApply: appliedPlan
926
+ };
927
+ if (format === "json") {
928
+ console.log(JSON.stringify(result, null, 2));
929
+ return appliedPlan.run.importStatus === "applied" ? 0 : 1;
930
+ }
931
+ console.log("Agentic bundle apply completed");
932
+ console.log("");
933
+ console.log(`Package: ${installedBundle.packageName}@${installedBundle.packageVersion}`);
934
+ console.log(`Bundle : ${installedBundle.bundle.bundleCode}@${installedBundle.bundle.bundleVersion}`);
935
+ console.log("");
936
+ printNpmInstallSummary(installResults);
937
+ console.log("");
938
+ printRequiredPackageRegistrationSummary(registrations);
939
+ console.log("");
940
+ printSeedImportPlan(appliedPlan);
941
+ return appliedPlan.run.importStatus === "applied" ? 0 : 1;
942
+ }
943
+ catch (error) {
944
+ const message = error instanceof Error ? error.message : String(error);
945
+ console.error(`agentic bundle apply failed: ${message}`);
946
+ return 1;
947
+ }
948
+ }
949
+ function printNpmInstallSummary(installResults) {
950
+ if (installResults.length === 0) {
951
+ console.log("NPM packages: install not requested");
952
+ return;
953
+ }
954
+ console.log("NPM packages:");
955
+ for (const result of installResults) {
956
+ const version = result.installedVersion === undefined ? "" : ` (installed: ${result.installedVersion})`;
957
+ console.log(` - ${result.packageSpec}: ${result.action}${version}`);
958
+ }
959
+ }
960
+ function printRequiredPackageRegistrationSummary(registrations) {
961
+ if (registrations.length === 0) {
962
+ console.log("Required packages: none declared");
963
+ return;
964
+ }
965
+ console.log("Required packages:");
966
+ for (const registration of registrations) {
967
+ const status = registration.registered
968
+ ? registration.versionSatisfied === false
969
+ ? "registered, version warning"
970
+ : "registered"
971
+ : "missing";
972
+ const installed = registration.installedVersion === undefined ? "-" : registration.installedVersion;
973
+ console.log(` - ${registration.packageName}@${registration.requiredVersion}: ${status} (installed: ${installed}, layer: ${registration.layer ?? "-"})`);
974
+ }
975
+ }
976
+ function printExecutionProjectStatus(status) {
977
+ console.log("Agentic execution project status");
978
+ console.log("");
979
+ console.log(`Project: ${status.project.projectCode}`);
980
+ console.log(`Name : ${status.project.projectName}`);
981
+ console.log(`Bundle : ${status.project.bundleCode}@${status.project.bundleVersion}`);
982
+ console.log(`Status : ${status.project.projectStatusCode}`);
983
+ console.log("");
984
+ console.log("Stages:");
985
+ for (const stage of status.stages) {
986
+ console.log(`- ${stage.stage.stageName}: ${stage.stage.stageStatusCode} (${stage.completedActivityCount}/${stage.activityCount} activities completed)`);
987
+ }
988
+ console.log("");
989
+ console.log("Artifacts:");
990
+ console.log(`- expected outputs: ${status.expectedOutputArtifactCount}`);
991
+ console.log(`- created artifact instances: ${status.createdArtifactInstanceCount}`);
992
+ }
993
+ async function createExecutionProjectCommand(args) {
994
+ const projectCode = readOptionValues(args, "--code")[0];
995
+ const projectName = readOptionValues(args, "--name")[0];
996
+ const bundleCode = readOptionValues(args, "--bundle")[0];
997
+ const packageName = readOptionValues(args, "--package")[0];
998
+ const format = readFormat(args);
999
+ if (projectCode === undefined || projectName === undefined || bundleCode === undefined) {
1000
+ console.error("Usage: agentic project create --bundle <bundle-code> --code <project-code> --name <project-name> [--package <package-name>] [--format text|json]");
1001
+ return 1;
1002
+ }
1003
+ try {
1004
+ ensureProjectRuntimeReady();
1005
+ const status = await createExecutionProjectFromBundle({
1006
+ projectCode,
1007
+ projectName,
1008
+ bundleCode,
1009
+ packageName
1010
+ });
1011
+ if (format === "json") {
1012
+ console.log(JSON.stringify(status, null, 2));
1013
+ }
1014
+ else {
1015
+ console.log("Agentic execution project created");
1016
+ console.log("");
1017
+ printExecutionProjectStatus(status);
1018
+ }
1019
+ return 0;
1020
+ }
1021
+ catch (error) {
1022
+ const message = error instanceof Error ? error.message : String(error);
1023
+ console.error(`agentic project create failed: ${message}`);
1024
+ return 1;
1025
+ }
1026
+ }
1027
+ function printExecutionProjectStatusCommand(args) {
1028
+ const projectCode = readOptionValues(args, "--code")[0];
1029
+ const format = readFormat(args);
1030
+ if (projectCode === undefined) {
1031
+ console.error("Usage: agentic project status --code <project-code> [--format text|json]");
1032
+ return 1;
1033
+ }
1034
+ try {
1035
+ const status = getExecutionProjectStatus({
1036
+ projectCode
1037
+ });
1038
+ if (format === "json") {
1039
+ console.log(JSON.stringify(status, null, 2));
1040
+ }
1041
+ else {
1042
+ printExecutionProjectStatus(status);
1043
+ }
1044
+ return 0;
1045
+ }
1046
+ catch (error) {
1047
+ const message = error instanceof Error ? error.message : String(error);
1048
+ console.error(`agentic project status failed: ${message}`);
1049
+ return 1;
1050
+ }
1051
+ }
1052
+ function resolveInstalledPackageRoots(projectRoot = process.cwd()) {
1053
+ const projectRequire = createRequire(join(projectRoot, "package.json"));
1054
+ const packageRoots = {};
1055
+ for (const module of listProjectModules(projectRoot)) {
1056
+ if (!module.enabled) {
1057
+ continue;
1058
+ }
1059
+ try {
1060
+ packageRoots[module.packageName] = dirname(projectRequire.resolve(`${module.packageName}/package.json`));
1061
+ }
1062
+ catch {
1063
+ // Missing package roots are handled by the context command error path.
1064
+ }
1065
+ }
1066
+ return packageRoots;
1067
+ }
1068
+ function candidateContributionExports(packageExports) {
1069
+ return [
1070
+ packageExports.agentContribution,
1071
+ packageExports.documentAgentContribution
1072
+ ];
1073
+ }
1074
+ async function registerAgentPackage(args) {
1075
+ const [packageName] = args;
1076
+ if (packageName === undefined || packageName.trim().length === 0) {
1077
+ console.error("Usage: agentic agent register <package-name>");
1078
+ return 1;
1079
+ }
1080
+ try {
1081
+ const projectRequire = createRequire(join(process.cwd(), "package.json"));
1082
+ const packageMainPath = projectRequire.resolve(packageName);
1083
+ const packageExports = await import(pathToFileURL(packageMainPath).href);
1084
+ const contribution = candidateContributionExports(packageExports).find(isAgentContribution);
1085
+ if (contribution === undefined) {
1086
+ console.error(`No agent contribution export found in package: ${packageName}`);
1087
+ console.error("Expected export: agentContribution");
1088
+ return 1;
1089
+ }
1090
+ const module = registerAgentContribution(contribution, process.cwd());
1091
+ console.log("Agent contribution registered");
1092
+ console.log("");
1093
+ console.log(`Agent : ${contribution.manifest.agentId}`);
1094
+ console.log(`Package: ${module.packageName}`);
1095
+ console.log(`Version: ${module.packageVersion}`);
1096
+ console.log(`Layer : ${module.moduleLayer ?? "-"}`);
1097
+ console.log(`Enabled: ${module.enabled ? "yes" : "no"}`);
1098
+ return 0;
1099
+ }
1100
+ catch (error) {
1101
+ const message = error instanceof Error ? error.message : String(error);
1102
+ console.error(`agentic agent register failed: ${message}`);
1103
+ return 1;
1104
+ }
1105
+ }
1106
+ function runAgentContextCommand(args) {
1107
+ const format = readFormat(args);
1108
+ const requestText = args
1109
+ .filter((arg, index) => {
1110
+ if (arg === "--format") {
1111
+ return false;
1112
+ }
1113
+ return args[index - 1] !== "--format";
1114
+ })
1115
+ .join(" ")
1116
+ .trim();
1117
+ if (requestText.length === 0) {
1118
+ console.error('Usage: agentic agent context "<user request>" [--format text|json]');
1119
+ return 1;
1120
+ }
1121
+ try {
1122
+ const context = assembleRegisteredAgentContext({
1123
+ requestText
1124
+ }, {
1125
+ projectRoot: process.cwd(),
1126
+ packageRoots: resolveInstalledPackageRoots()
1127
+ });
1128
+ if (format === "json") {
1129
+ console.log(JSON.stringify(context ?? null, null, 2));
1130
+ }
1131
+ else if (context === undefined) {
1132
+ console.log("No registered agent context matched the request.");
1133
+ }
1134
+ else {
1135
+ console.log(context.contentText);
1136
+ }
1137
+ return context === undefined ? 1 : 0;
1138
+ }
1139
+ catch (error) {
1140
+ const message = error instanceof Error ? error.message : String(error);
1141
+ console.error(`agentic agent context failed: ${message}`);
1142
+ return 1;
1143
+ }
1144
+ }
1145
+ function hasArg(args, name) {
1146
+ return args.includes(name);
1147
+ }
1148
+ function readOptionValues(args, name) {
1149
+ const values = [];
1150
+ for (let index = 0; index < args.length; index += 1) {
1151
+ if (args[index] === name) {
1152
+ const value = args[index + 1];
1153
+ if (value !== undefined) {
1154
+ values.push(value);
1155
+ }
1156
+ }
1157
+ }
1158
+ return values;
1159
+ }
1160
+ const EXECUTION_RANGES = new Set([
1161
+ "1h",
1162
+ "6h",
1163
+ "24h",
1164
+ "7d",
1165
+ "30d",
1166
+ "today",
1167
+ "yesterday",
1168
+ "this-week",
1169
+ "last-week",
1170
+ "this-month",
1171
+ "last-month"
1172
+ ]);
1173
+ const EXECUTION_STATUSES = new Set(["pending", "running", "succeeded", "failed", "cancelled"]);
1174
+ function parsePositiveInteger(value) {
1175
+ if (value === undefined) {
1176
+ return undefined;
1177
+ }
1178
+ const parsed = Number(value);
1179
+ if (!Number.isInteger(parsed) || parsed < 1) {
1180
+ throw new Error(`Invalid positive integer: ${value}`);
1181
+ }
1182
+ return parsed;
1183
+ }
1184
+ function parseExecutionQuery(args, defaults = {}) {
1185
+ const rangeValue = readOptionValues(args, "--range")[0];
1186
+ const statusValue = readOptionValues(args, "--status")[0];
1187
+ const limitValue = readOptionValues(args, "--limit")[0];
1188
+ if (rangeValue !== undefined && !EXECUTION_RANGES.has(rangeValue)) {
1189
+ throw new Error(`Invalid execution range: ${rangeValue}`);
1190
+ }
1191
+ if (statusValue !== undefined && !EXECUTION_STATUSES.has(statusValue)) {
1192
+ throw new Error(`Invalid execution status: ${statusValue}`);
1193
+ }
1194
+ return {
1195
+ ...defaults,
1196
+ range: rangeValue === undefined ? defaults.range : rangeValue,
1197
+ from: readOptionValues(args, "--from")[0] ?? defaults.from,
1198
+ to: readOptionValues(args, "--to")[0] ?? defaults.to,
1199
+ source: readOptionValues(args, "--source")[0] ?? defaults.source,
1200
+ status: statusValue === undefined ? defaults.status : statusValue,
1201
+ limit: parsePositiveInteger(limitValue) ?? defaults.limit
1202
+ };
1203
+ }
1204
+ function readFormat(args) {
1205
+ const format = readOptionValues(args, "--format")[0] ?? "text";
1206
+ if (format !== "text" && format !== "json") {
1207
+ throw new Error(`Invalid format: ${format}`);
1208
+ }
1209
+ return format;
1210
+ }
1211
+ function truncate(value, maxLength) {
1212
+ if (value === undefined || value.length === 0) {
1213
+ return "-";
1214
+ }
1215
+ return value.length <= maxLength ? value : `${value.slice(0, maxLength - 3)}...`;
1216
+ }
1217
+ function printExecutionRecord(record, index) {
1218
+ if (index !== undefined) {
1219
+ console.log(`[${index}]`);
1220
+ }
1221
+ console.log(`Run ID : ${record.runId}`);
1222
+ console.log(`Status : ${record.runStatus}`);
1223
+ console.log(`Source : ${record.source ?? "-"}`);
1224
+ console.log(`Command : ${record.commandName ?? "-"}`);
1225
+ console.log(`Created : ${record.createdAt}`);
1226
+ console.log(`Started : ${record.startedAt ?? "-"}`);
1227
+ console.log(`Ended : ${record.endedAt ?? "-"}`);
1228
+ console.log(`Request : ${truncate(record.requestText, 240)}`);
1229
+ console.log(`Output : ${truncate(record.latestOutputText ?? record.latestOutputJson, 240)}`);
1230
+ }
1231
+ function printExecutionList(records) {
1232
+ console.log("Agentic execution history");
1233
+ console.log("");
1234
+ if (records.length === 0) {
1235
+ console.log("No execution records found.");
1236
+ return;
1237
+ }
1238
+ records.forEach((record, index) => {
1239
+ if (index > 0) {
1240
+ console.log("");
1241
+ }
1242
+ printExecutionRecord(record, index + 1);
1243
+ });
1244
+ }
1245
+ function printExecutionSummary(summary) {
1246
+ console.log("Agentic execution summary");
1247
+ console.log("");
1248
+ console.log(`Total : ${summary.total}`);
1249
+ console.log(`Pending : ${summary.pending}`);
1250
+ console.log(`Running : ${summary.running}`);
1251
+ console.log(`Succeeded: ${summary.succeeded}`);
1252
+ console.log(`Failed : ${summary.failed}`);
1253
+ console.log(`Cancelled: ${summary.cancelled}`);
1254
+ }
1255
+ function printExecutionDetail(detail) {
1256
+ console.log("Agentic execution detail");
1257
+ console.log("");
1258
+ printExecutionRecord(detail.record);
1259
+ console.log("");
1260
+ console.log("Logs:");
1261
+ if (detail.logs.length === 0) {
1262
+ console.log(" - none");
1263
+ }
1264
+ else {
1265
+ for (const log of detail.logs) {
1266
+ console.log(` - #${log.sequenceNo} ${log.createdAt} ${log.logLevel}/${log.logType}: ${log.message}`);
1267
+ }
1268
+ }
1269
+ console.log("");
1270
+ console.log("Outputs:");
1271
+ if (detail.outputs.length === 0) {
1272
+ console.log(" - none");
1273
+ return;
1274
+ }
1275
+ for (const output of detail.outputs) {
1276
+ console.log(` - #${output.outputId} ${output.createdAt} ${output.outputType}: ${truncate(output.contentText ?? output.contentJson ?? output.filePath, 360)}`);
1277
+ }
1278
+ }
1279
+ function runExecutionQueryCommand(args) {
1280
+ const [subcommand, ...queryArgs] = args;
1281
+ try {
1282
+ if (subcommand === "list") {
1283
+ const format = readFormat(queryArgs);
1284
+ const records = listExecutions(parseExecutionQuery(queryArgs, { range: "24h", limit: 20 }));
1285
+ if (format === "json") {
1286
+ console.log(JSON.stringify(records, null, 2));
1287
+ }
1288
+ else {
1289
+ printExecutionList(records);
1290
+ }
1291
+ return 0;
1292
+ }
1293
+ if (subcommand === "latest") {
1294
+ const format = readFormat(queryArgs);
1295
+ const record = getLatestExecution(parseExecutionQuery(queryArgs, { range: "24h" }));
1296
+ if (format === "json") {
1297
+ console.log(JSON.stringify(record ?? null, null, 2));
1298
+ }
1299
+ else if (record === undefined) {
1300
+ console.log("No execution records found.");
1301
+ }
1302
+ else {
1303
+ printExecutionRecord(record);
1304
+ }
1305
+ return 0;
1306
+ }
1307
+ if (subcommand === "summary") {
1308
+ const format = readFormat(queryArgs);
1309
+ const summary = summarizeExecutions(parseExecutionQuery(queryArgs, { range: "today", limit: 200 }));
1310
+ if (format === "json") {
1311
+ console.log(JSON.stringify(summary, null, 2));
1312
+ }
1313
+ else {
1314
+ printExecutionSummary(summary);
1315
+ }
1316
+ return 0;
1317
+ }
1318
+ if (subcommand === "show") {
1319
+ const [runId, ...showArgs] = queryArgs;
1320
+ if (runId === undefined) {
1321
+ console.error("Usage: agentic execution show <run-id> [--format text|json]");
1322
+ return 1;
1323
+ }
1324
+ const format = readFormat(showArgs);
1325
+ const detail = getExecutionDetail(runId);
1326
+ if (format === "json") {
1327
+ console.log(JSON.stringify(detail ?? null, null, 2));
1328
+ }
1329
+ else if (detail === undefined) {
1330
+ console.log(`Execution not found: ${runId}`);
1331
+ }
1332
+ else {
1333
+ printExecutionDetail(detail);
1334
+ }
1335
+ return detail === undefined ? 1 : 0;
1336
+ }
1337
+ console.error("Unknown command: execution" + (subcommand === undefined ? "" : ` ${subcommand}`));
1338
+ console.error("Usage: agentic execution list|latest|show|summary");
1339
+ return 1;
1340
+ }
1341
+ catch (error) {
1342
+ const message = error instanceof Error ? error.message : String(error);
1343
+ console.error(`agentic execution failed: ${message}`);
1344
+ return 1;
1345
+ }
1346
+ }
1347
+ function printCodexAdapterInstallResult(result) {
1348
+ console.log("Codex adapter prepared");
1349
+ console.log("");
1350
+ console.log(`Plugin root : ${result.pluginRoot}`);
1351
+ console.log(`Marketplace : ${result.marketplacePath}`);
1352
+ console.log(`Files : ${result.filesWritten.length}`);
1353
+ console.log("Bridge : agentic-runtime-codex@agentic-runtime");
1354
+ console.log(`Marketplace registered: ${result.marketplaceRegistered ? "yes" : "no"}`);
1355
+ console.log(`Plugin installed : ${result.pluginInstalled ? "yes" : "no"}`);
1356
+ if (result.messages.length > 0) {
1357
+ console.log("");
1358
+ console.log("Notes:");
1359
+ for (const message of result.messages) {
1360
+ console.log(` - ${message}`);
1361
+ }
1362
+ }
1363
+ console.log("");
1364
+ console.log("After Codex loads the plugin, review and trust the hook if Codex asks for approval.");
1365
+ }
1366
+ function printKiroAdapterInstallResult(result) {
1367
+ console.log("Kiro adapter prepared");
1368
+ console.log("");
1369
+ console.log(`Adapter root : ${result.adapterRoot}`);
1370
+ console.log(`Steering file : ${result.steeringPath}`);
1371
+ console.log(`V3 hook file : ${result.v3HookPath}`);
1372
+ console.log(`V2 agent config: ${result.v2AgentConfigPath}`);
1373
+ console.log(`IDE prompt hook: ${result.idePromptHookPath}`);
1374
+ console.log(`IDE stop hook : ${result.ideStopHookPath}`);
1375
+ console.log(`Files : ${result.filesWritten.length}`);
1376
+ console.log(`Kiro CLI : ${result.kiroCliAvailable ? "found" : "missing"}`);
1377
+ console.log(`V3 hooks : ${result.v3HooksConfigured ? "configured" : "missing"}`);
1378
+ console.log(`V2 hooks : ${result.v2HooksConfigured ? "configured" : "missing"}`);
1379
+ console.log(`IDE hook files : ${result.ideHookFilesPrepared ? "prepared" : "missing"}`);
1380
+ console.log(`Set default : ${result.setDefaultRequested ? (result.defaultAgentConfigured ? "succeeded" : "failed") : "not requested"}`);
1381
+ if (result.messages.length > 0) {
1382
+ console.log("");
1383
+ console.log("Notes:");
1384
+ for (const message of result.messages) {
1385
+ console.log(` - ${message}`);
1386
+ }
1387
+ }
1388
+ }
1389
+ function printClaudeCodeAdapterInstallResult(result) {
1390
+ console.log("Claude Code adapter prepared");
1391
+ console.log("");
1392
+ console.log(`Settings file: ${result.settingsPath}`);
1393
+ console.log(`Rule file : ${result.rulePath}`);
1394
+ console.log(`Files : ${result.filesWritten.length}`);
1395
+ console.log(`Claude CLI : ${result.claudeCliAvailable ? "found" : "missing"}`);
1396
+ console.log(`Hooks : ${result.hooksConfigured ? "configured" : "not configured"}`);
1397
+ if (result.messages.length > 0) {
1398
+ console.log("");
1399
+ console.log("Notes:");
1400
+ for (const message of result.messages) {
1401
+ console.log(` - ${message}`);
1402
+ }
1403
+ }
1404
+ }
1405
+ function installAdapter(args) {
1406
+ const [adapterName] = args;
1407
+ if (adapterName !== "codex" && adapterName !== "kiro" && adapterName !== "claude-code") {
1408
+ console.error("Usage: agentic adapter install codex [--prepare-only] [--force]");
1409
+ console.error(" or: agentic adapter install kiro [--force] [--set-default]");
1410
+ console.error(" or: agentic adapter install claude-code [--force]");
1411
+ return 1;
1412
+ }
1413
+ ensureProjectRuntimeReady();
1414
+ if (adapterName === "kiro") {
1415
+ const result = installKiroAdapter(process.cwd(), {
1416
+ force: hasArg(args, "--force"),
1417
+ setDefault: hasArg(args, "--set-default")
1418
+ });
1419
+ printKiroAdapterInstallResult(result);
1420
+ return 0;
1421
+ }
1422
+ if (adapterName === "claude-code") {
1423
+ const result = installClaudeCodeAdapter(process.cwd(), {
1424
+ force: hasArg(args, "--force")
1425
+ });
1426
+ printClaudeCodeAdapterInstallResult(result);
1427
+ return 0;
1428
+ }
1429
+ const result = installCodexAdapter(process.cwd(), {
1430
+ prepareOnly: hasArg(args, "--prepare-only"),
1431
+ force: hasArg(args, "--force")
1432
+ });
1433
+ printCodexAdapterInstallResult(result);
1434
+ return 0;
1435
+ }
1436
+ function printAdapterStatus(args) {
1437
+ const [adapterName] = args;
1438
+ if (adapterName !== "codex" && adapterName !== "kiro" && adapterName !== "claude-code") {
1439
+ console.error("Usage: agentic adapter status codex|kiro|claude-code");
1440
+ return 1;
1441
+ }
1442
+ if (adapterName === "kiro") {
1443
+ const status = getKiroAdapterStatus();
1444
+ console.log("Kiro adapter status");
1445
+ console.log("");
1446
+ console.log(`Adapter files : ${status.adapterRootExists ? "found" : "missing"}`);
1447
+ console.log(`Steering file : ${status.steeringExists ? "found" : "missing"}`);
1448
+ console.log(`Kiro CLI : ${status.kiroCliAvailable ? "found" : "missing"}`);
1449
+ console.log(`V3 hook file : ${status.v3HookExists ? "found" : "missing"}`);
1450
+ console.log(`V3 UserPromptSubmit : ${status.v3PromptHookConfigured ? "configured" : "missing"}`);
1451
+ console.log(`V3 Stop : ${status.v3StopHookConfigured ? "configured" : "missing"}`);
1452
+ console.log(`V2 agent config : ${status.v2AgentConfigExists ? "found" : "missing"}`);
1453
+ console.log(`V2 agent name : ${status.v2AgentName}`);
1454
+ console.log(`V2 userPromptSubmit : ${status.v2PromptHookConfigured ? "configured" : "missing"}`);
1455
+ console.log(`V2 stop : ${status.v2StopHookConfigured ? "configured" : "missing"}`);
1456
+ console.log(`IDE Prompt Submit file: ${status.idePromptHookExists ? "found" : "missing"}`);
1457
+ console.log(`IDE Agent Stop file : ${status.ideStopHookExists ? "found" : "missing"}`);
1458
+ if (status.notes.length > 0) {
1459
+ console.log("");
1460
+ console.log("Notes:");
1461
+ for (const note of status.notes) {
1462
+ console.log(` - ${note}`);
1463
+ }
1464
+ }
1465
+ return 0;
1466
+ }
1467
+ if (adapterName === "claude-code") {
1468
+ const status = getClaudeCodeAdapterStatus();
1469
+ console.log("Claude Code adapter status");
1470
+ console.log("");
1471
+ console.log(`Settings file : ${status.settingsExists ? "found" : "missing"}`);
1472
+ console.log(`Runtime rule : ${status.ruleExists ? "found" : "missing"}`);
1473
+ console.log(`Claude CLI : ${status.claudeCliAvailable ? "found" : "missing"}`);
1474
+ console.log(`UserPromptSubmit hook: ${status.userPromptHookConfigured ? "configured" : "missing"}`);
1475
+ console.log(`Stop hook : ${status.stopHookConfigured ? "configured" : "missing"}`);
1476
+ if (status.notes.length > 0) {
1477
+ console.log("");
1478
+ console.log("Notes:");
1479
+ for (const note of status.notes) {
1480
+ console.log(` - ${note}`);
1481
+ }
1482
+ }
1483
+ return 0;
1484
+ }
1485
+ const status = getCodexAdapterStatus();
1486
+ console.log("Codex adapter status");
1487
+ console.log("");
1488
+ console.log(`Plugin files : ${status.pluginRootExists ? "found" : "missing"}`);
1489
+ console.log(`Marketplace : ${status.marketplaceExists ? "found" : "missing"}`);
1490
+ console.log(`Codex CLI : ${status.codexCliAvailable ? "found" : "missing"}`);
1491
+ if (status.notes.length > 0) {
1492
+ console.log("");
1493
+ console.log("Notes:");
1494
+ for (const note of status.notes) {
1495
+ console.log(` - ${note}`);
1496
+ }
1497
+ }
1498
+ return 0;
1499
+ }
1500
+ async function recordHookEvent(args) {
1501
+ const source = readOptionValues(args, "--source")[0];
1502
+ const event = readOptionValues(args, "--event")[0];
1503
+ if ((source !== "codex" || (event !== "UserPromptSubmit" && event !== "Stop")) &&
1504
+ (source !== "claude-code" || (event !== "UserPromptSubmit" && event !== "Stop")) &&
1505
+ (source !== "kiro" || (event !== "PromptSubmit" && event !== "AgentStop"))) {
1506
+ console.error("Usage: agentic hook record --source codex --event UserPromptSubmit|Stop");
1507
+ console.error(" or: agentic hook record --source claude-code --event UserPromptSubmit|Stop");
1508
+ console.error(" or: agentic hook record --source kiro --event PromptSubmit|AgentStop");
1509
+ return 1;
1510
+ }
1511
+ try {
1512
+ const stdin = await readStdin();
1513
+ const rawPayload = stdin.trim().length > 0 || source !== "kiro" || event !== "PromptSubmit"
1514
+ ? stdin
1515
+ : JSON.stringify({
1516
+ prompt: process.env.USER_PROMPT ?? ""
1517
+ });
1518
+ const result = recordHook({
1519
+ source,
1520
+ event,
1521
+ rawPayload
1522
+ });
1523
+ if (result.action === "skipped" && result.reason !== undefined) {
1524
+ console.error(`agentic hook skipped: ${result.reason}`);
1525
+ }
1526
+ return 0;
1527
+ }
1528
+ catch (error) {
1529
+ const message = error instanceof Error ? error.message : String(error);
1530
+ console.error(`agentic hook record failed: ${message}`);
1531
+ return 0;
1532
+ }
1533
+ }
1534
+ function setupProject(args) {
1535
+ const adapters = readOptionValues(args, "--adapter");
1536
+ const prepareOnly = hasArg(args, "--prepare-only");
1537
+ const force = hasArg(args, "--force");
1538
+ const setDefault = hasArg(args, "--set-default");
1539
+ initializeProject();
1540
+ initializeDatabase();
1541
+ if (adapters.length === 0) {
1542
+ return 0;
1543
+ }
1544
+ for (const adapter of adapters) {
1545
+ if (adapter !== "codex" && adapter !== "kiro" && adapter !== "claude-code") {
1546
+ console.error(`Unsupported adapter: ${adapter}`);
1547
+ return 1;
1548
+ }
1549
+ if (adapter === "kiro") {
1550
+ const result = installKiroAdapter(process.cwd(), {
1551
+ force,
1552
+ setDefault
1553
+ });
1554
+ console.log("");
1555
+ printKiroAdapterInstallResult(result);
1556
+ continue;
1557
+ }
1558
+ if (adapter === "claude-code") {
1559
+ const result = installClaudeCodeAdapter(process.cwd(), {
1560
+ force
1561
+ });
1562
+ console.log("");
1563
+ printClaudeCodeAdapterInstallResult(result);
1564
+ continue;
1565
+ }
1566
+ const result = installCodexAdapter(process.cwd(), {
1567
+ prepareOnly,
1568
+ force
1569
+ });
1570
+ console.log("");
1571
+ printCodexAdapterInstallResult(result);
1572
+ }
1573
+ return 0;
1574
+ }
1575
+ export async function runCli(argv = process.argv.slice(2)) {
1576
+ const [command, ...rest] = argv;
1577
+ if (command === undefined || command === "help" || command === "--help" || command === "-h") {
1578
+ printHelp();
1579
+ return 0;
1580
+ }
1581
+ if (command === "version" || command === "--version" || command === "-v") {
1582
+ printVersion();
1583
+ return 0;
1584
+ }
1585
+ if (command === "docs") {
1586
+ printDocs();
1587
+ return 0;
1588
+ }
1589
+ if (command === "config") {
1590
+ printConfigStatus();
1591
+ return 0;
1592
+ }
1593
+ if (command === "setup") {
1594
+ return setupProject(rest);
1595
+ }
1596
+ if (command === "run") {
1597
+ return runExecution(rest);
1598
+ }
1599
+ if (command === "execution") {
1600
+ return runExecutionQueryCommand(rest);
1601
+ }
1602
+ if (command === "agent") {
1603
+ const [subcommand, ...agentArgs] = rest;
1604
+ if (subcommand === "register") {
1605
+ return registerAgentPackage(agentArgs);
1606
+ }
1607
+ if (subcommand === "context") {
1608
+ return runAgentContextCommand(agentArgs);
1609
+ }
1610
+ console.error("Unknown command: agent" + (subcommand === undefined ? "" : ` ${subcommand}`));
1611
+ console.error("Usage: agentic agent register <package-name>");
1612
+ console.error(" or: agentic agent context \"<user request>\" [--format text|json]");
1613
+ return 1;
1614
+ }
1615
+ if (command === "hook") {
1616
+ const [subcommand, ...hookArgs] = rest;
1617
+ if (subcommand === "record") {
1618
+ return recordHookEvent(hookArgs);
1619
+ }
1620
+ console.error("Unknown command: hook" + (subcommand === undefined ? "" : ` ${subcommand}`));
1621
+ console.error("Run 'agentic help' for available commands.");
1622
+ return 1;
1623
+ }
1624
+ if (command === "init") {
1625
+ initializeProject();
1626
+ return 0;
1627
+ }
1628
+ if (command === "db") {
1629
+ const [subcommand] = rest;
1630
+ if (subcommand === "init") {
1631
+ initializeDatabase();
1632
+ return 0;
1633
+ }
1634
+ if (subcommand === "status") {
1635
+ printDatabaseStatus();
1636
+ return 0;
1637
+ }
1638
+ console.error("Unknown command: db" + (subcommand === undefined ? "" : ` ${subcommand}`));
1639
+ console.error("Run 'agentic help' for available commands.");
1640
+ return 1;
1641
+ }
1642
+ if (command === "module") {
1643
+ const [subcommand, ...moduleArgs] = rest;
1644
+ if (subcommand === "register") {
1645
+ return registerModule(moduleArgs);
1646
+ }
1647
+ if (subcommand === "list") {
1648
+ printModuleList();
1649
+ return 0;
1650
+ }
1651
+ console.error("Unknown command: module" + (subcommand === undefined ? "" : ` ${subcommand}`));
1652
+ console.error("Run 'agentic help' for available commands.");
1653
+ return 1;
1654
+ }
1655
+ if (command === "bundle") {
1656
+ const [subcommand, ...bundleArgs] = rest;
1657
+ if (subcommand === "install") {
1658
+ return await installBundle(bundleArgs);
1659
+ }
1660
+ if (subcommand === "apply") {
1661
+ return await applyBundle(bundleArgs);
1662
+ }
1663
+ if (subcommand === "list" || subcommand === "status") {
1664
+ printBundleList(bundleArgs);
1665
+ return 0;
1666
+ }
1667
+ console.error("Unknown command: bundle" + (subcommand === undefined ? "" : ` ${subcommand}`));
1668
+ console.error("Usage: agentic bundle install <package-name> [--bundle <bundle-code>]");
1669
+ console.error(" or: agentic bundle apply <package-name> [--bundle <bundle-code>] [--format text|json] [--strict-required] [--install-required]");
1670
+ console.error(" or: agentic bundle list [--format text|json]");
1671
+ console.error(" or: agentic bundle status [--format text|json]");
1672
+ return 1;
1673
+ }
1674
+ if (command === "seed") {
1675
+ const [subcommand, ...seedArgs] = rest;
1676
+ if (subcommand === "import") {
1677
+ return await importSeed(seedArgs);
1678
+ }
1679
+ if (subcommand === "apply") {
1680
+ return await applySeed(seedArgs);
1681
+ }
1682
+ if (subcommand === "status") {
1683
+ printSeedImportStatus(seedArgs);
1684
+ return 0;
1685
+ }
1686
+ console.error("Unknown command: seed" + (subcommand === undefined ? "" : ` ${subcommand}`));
1687
+ console.error("Usage: agentic seed import --bundle <bundle-code> [--package <package-name>] [--format text|json]");
1688
+ console.error(" or: agentic seed apply --run <seed-import-run-id> [--format text|json]");
1689
+ console.error(" or: agentic seed apply --bundle <bundle-code> [--package <package-name>] [--format text|json]");
1690
+ console.error(" or: agentic seed status [--format text|json]");
1691
+ return 1;
1692
+ }
1693
+ if (command === "project") {
1694
+ const [subcommand, ...projectArgs] = rest;
1695
+ if (subcommand === "create") {
1696
+ return await createExecutionProjectCommand(projectArgs);
1697
+ }
1698
+ if (subcommand === "status") {
1699
+ return printExecutionProjectStatusCommand(projectArgs);
1700
+ }
1701
+ console.error("Unknown command: project" + (subcommand === undefined ? "" : ` ${subcommand}`));
1702
+ console.error("Usage: agentic project create --bundle <bundle-code> --code <project-code> --name <project-name> [--package <package-name>] [--format text|json]");
1703
+ console.error(" or: agentic project status --code <project-code> [--format text|json]");
1704
+ return 1;
1705
+ }
1706
+ if (command === "adapter") {
1707
+ const [subcommand, ...adapterArgs] = rest;
1708
+ if (subcommand === "install") {
1709
+ return installAdapter(adapterArgs);
1710
+ }
1711
+ if (subcommand === "status") {
1712
+ return printAdapterStatus(adapterArgs);
1713
+ }
1714
+ console.error("Unknown command: adapter" + (subcommand === undefined ? "" : ` ${subcommand}`));
1715
+ console.error("Run 'agentic help' for available commands.");
1716
+ return 1;
1717
+ }
1718
+ const suffix = rest.length > 0 ? ` ${rest.join(" ")}` : "";
1719
+ console.error(`Unknown command: ${command}${suffix}`);
1720
+ console.error("Run 'agentic help' for available commands.");
1721
+ return 1;
1722
+ }
1723
+ try {
1724
+ process.exitCode = await runCli();
1725
+ }
1726
+ catch (error) {
1727
+ const message = error instanceof Error ? error.message : String(error);
1728
+ console.error(message);
1729
+ process.exitCode = 1;
1730
+ }
1731
+ //# sourceMappingURL=cli.js.map