@fitlab-ai/agent-infra 0.7.6 → 0.8.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 (173) hide show
  1. package/README.md +2 -0
  2. package/README.zh-CN.md +2 -0
  3. package/bin/cli.ts +53 -18
  4. package/dist/bin/cli.js +56 -19
  5. package/dist/lib/decide.js +110 -0
  6. package/dist/lib/run/host.js +39 -0
  7. package/dist/lib/run/index.js +102 -0
  8. package/dist/lib/run/prompt.js +2 -0
  9. package/dist/lib/run/skills.js +29 -0
  10. package/dist/lib/run/tui.js +35 -0
  11. package/dist/lib/sandbox/capture.js +49 -0
  12. package/dist/lib/sandbox/commands/create.js +55 -6
  13. package/dist/lib/sandbox/commands/ls.js +4 -33
  14. package/dist/lib/sandbox/commands/show.js +67 -0
  15. package/dist/lib/sandbox/index.js +7 -0
  16. package/dist/lib/server/adapters/_contract.js +9 -0
  17. package/dist/lib/server/adapters/feishu/index.js +40 -0
  18. package/dist/lib/server/adapters/feishu/transport.js +95 -0
  19. package/dist/lib/server/auth.js +19 -0
  20. package/dist/lib/server/config.js +183 -0
  21. package/dist/lib/server/daemon.js +96 -0
  22. package/dist/lib/server/index.js +47 -0
  23. package/dist/lib/server/logger.js +34 -0
  24. package/dist/lib/server/plugin-loader.js +73 -0
  25. package/dist/lib/server/process-control.js +200 -0
  26. package/dist/lib/server/protocol.js +69 -0
  27. package/dist/lib/server/redact.js +12 -0
  28. package/dist/lib/server/runner.js +75 -0
  29. package/dist/lib/server/streamer.js +44 -0
  30. package/dist/lib/task/commands/decisions.js +258 -0
  31. package/dist/lib/task/commands/issue-body.js +94 -0
  32. package/dist/lib/task/commands/log.js +67 -9
  33. package/dist/lib/task/index.js +17 -0
  34. package/dist/lib/task/issue-form.js +66 -0
  35. package/dist/lib/task/ledger.js +66 -0
  36. package/dist/lib/task/sections.js +73 -0
  37. package/lib/decide.ts +124 -0
  38. package/lib/run/host.ts +47 -0
  39. package/lib/run/index.ts +124 -0
  40. package/lib/run/prompt.ts +1 -0
  41. package/lib/run/skills.ts +34 -0
  42. package/lib/run/tui.ts +40 -0
  43. package/lib/sandbox/capture.ts +84 -0
  44. package/lib/sandbox/commands/create.ts +61 -9
  45. package/lib/sandbox/commands/ls.ts +4 -36
  46. package/lib/sandbox/commands/show.ts +80 -0
  47. package/lib/sandbox/index.ts +7 -0
  48. package/lib/server/adapters/_contract.ts +42 -0
  49. package/lib/server/adapters/feishu/index.ts +47 -0
  50. package/lib/server/adapters/feishu/transport.ts +128 -0
  51. package/lib/server/auth.ts +28 -0
  52. package/lib/server/config.ts +228 -0
  53. package/lib/server/daemon.ts +110 -0
  54. package/lib/server/index.ts +50 -0
  55. package/lib/server/logger.ts +48 -0
  56. package/lib/server/plugin-loader.ts +84 -0
  57. package/lib/server/process-control.ts +225 -0
  58. package/lib/server/protocol.ts +79 -0
  59. package/lib/server/redact.ts +12 -0
  60. package/lib/server/runner.ts +95 -0
  61. package/lib/server/server.schema.json +127 -0
  62. package/lib/server/streamer.ts +57 -0
  63. package/lib/task/commands/decisions.ts +272 -0
  64. package/lib/task/commands/issue-body.ts +102 -0
  65. package/lib/task/commands/log.ts +73 -9
  66. package/lib/task/index.ts +17 -0
  67. package/lib/task/issue-form.ts +77 -0
  68. package/lib/task/ledger.ts +73 -0
  69. package/lib/task/sections.ts +73 -0
  70. package/package.json +9 -4
  71. package/templates/.agents/QUICKSTART.zh-CN.md +2 -2
  72. package/templates/.agents/README.en.md +3 -1
  73. package/templates/.agents/README.zh-CN.md +3 -1
  74. package/templates/.agents/rules/create-issue.github.en.md +20 -29
  75. package/templates/.agents/rules/create-issue.github.zh-CN.md +20 -29
  76. package/templates/.agents/rules/issue-fields.github.en.md +1 -1
  77. package/templates/.agents/rules/issue-fields.github.zh-CN.md +1 -1
  78. package/templates/.agents/rules/issue-pr-commands.github.en.md +6 -0
  79. package/templates/.agents/rules/issue-pr-commands.github.zh-CN.md +6 -0
  80. package/templates/.agents/rules/next-step-output.en.md +30 -1
  81. package/templates/.agents/rules/next-step-output.zh-CN.md +30 -1
  82. package/templates/.agents/rules/no-mid-flow-questions.en.md +7 -2
  83. package/templates/.agents/rules/no-mid-flow-questions.zh-CN.md +7 -2
  84. package/templates/.agents/rules/review-handshake.en.md +5 -1
  85. package/templates/.agents/rules/review-handshake.zh-CN.md +5 -1
  86. package/templates/.agents/rules/task-management.en.md +3 -1
  87. package/templates/.agents/rules/task-management.zh-CN.md +3 -1
  88. package/templates/.agents/scripts/lib/post-review-commit.js +15 -18
  89. package/templates/.agents/scripts/validate-artifact.js +8 -0
  90. package/templates/.agents/skills/analyze-task/SKILL.en.md +18 -4
  91. package/templates/.agents/skills/analyze-task/SKILL.zh-CN.md +18 -4
  92. package/templates/.agents/skills/analyze-task/config/verify.en.json +2 -1
  93. package/templates/.agents/skills/analyze-task/config/verify.zh-CN.json +2 -1
  94. package/templates/.agents/skills/archive-tasks/SKILL.en.md +3 -1
  95. package/templates/.agents/skills/archive-tasks/SKILL.zh-CN.md +3 -1
  96. package/templates/.agents/skills/block-task/SKILL.en.md +3 -1
  97. package/templates/.agents/skills/block-task/SKILL.zh-CN.md +3 -1
  98. package/templates/.agents/skills/cancel-task/SKILL.en.md +3 -1
  99. package/templates/.agents/skills/cancel-task/SKILL.zh-CN.md +3 -1
  100. package/templates/.agents/skills/check-task/SKILL.en.md +30 -81
  101. package/templates/.agents/skills/check-task/SKILL.zh-CN.md +30 -80
  102. package/templates/.agents/skills/close-codescan/SKILL.en.md +3 -1
  103. package/templates/.agents/skills/close-codescan/SKILL.zh-CN.md +3 -1
  104. package/templates/.agents/skills/close-dependabot/SKILL.en.md +3 -1
  105. package/templates/.agents/skills/close-dependabot/SKILL.zh-CN.md +3 -1
  106. package/templates/.agents/skills/code-task/SKILL.en.md +4 -2
  107. package/templates/.agents/skills/code-task/SKILL.zh-CN.md +4 -2
  108. package/templates/.agents/skills/code-task/reference/dual-mode.en.md +7 -2
  109. package/templates/.agents/skills/code-task/reference/dual-mode.zh-CN.md +7 -2
  110. package/templates/.agents/skills/code-task/scripts/detect-mode.js +6 -14
  111. package/templates/.agents/skills/commit/SKILL.en.md +27 -5
  112. package/templates/.agents/skills/commit/SKILL.zh-CN.md +27 -5
  113. package/templates/.agents/skills/complete-task/SKILL.en.md +4 -1
  114. package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +4 -1
  115. package/templates/.agents/skills/complete-task/config/verify.en.json +2 -1
  116. package/templates/.agents/skills/complete-task/config/verify.zh-CN.json +2 -1
  117. package/templates/.agents/skills/create-pr/SKILL.en.md +3 -1
  118. package/templates/.agents/skills/create-pr/SKILL.zh-CN.md +3 -1
  119. package/templates/.agents/skills/create-release-note/SKILL.en.md +3 -1
  120. package/templates/.agents/skills/create-release-note/SKILL.zh-CN.md +3 -1
  121. package/templates/.agents/skills/create-task/SKILL.en.md +4 -4
  122. package/templates/.agents/skills/create-task/SKILL.zh-CN.md +4 -4
  123. package/templates/.agents/skills/import-codescan/SKILL.en.md +3 -4
  124. package/templates/.agents/skills/import-codescan/SKILL.zh-CN.md +3 -4
  125. package/templates/.agents/skills/import-dependabot/SKILL.en.md +3 -2
  126. package/templates/.agents/skills/import-dependabot/SKILL.zh-CN.md +3 -2
  127. package/templates/.agents/skills/import-issue/SKILL.en.md +20 -4
  128. package/templates/.agents/skills/import-issue/SKILL.zh-CN.md +20 -4
  129. package/templates/.agents/skills/init-labels/SKILL.en.md +3 -1
  130. package/templates/.agents/skills/init-labels/SKILL.zh-CN.md +3 -1
  131. package/templates/.agents/skills/init-milestones/SKILL.en.md +3 -1
  132. package/templates/.agents/skills/init-milestones/SKILL.zh-CN.md +3 -1
  133. package/templates/.agents/skills/plan-task/SKILL.en.md +4 -3
  134. package/templates/.agents/skills/plan-task/SKILL.zh-CN.md +4 -3
  135. package/templates/.agents/skills/post-release/SKILL.en.md +3 -1
  136. package/templates/.agents/skills/post-release/SKILL.zh-CN.md +3 -1
  137. package/templates/.agents/skills/refine-title/SKILL.en.md +3 -1
  138. package/templates/.agents/skills/refine-title/SKILL.zh-CN.md +3 -1
  139. package/templates/.agents/skills/release/SKILL.en.md +3 -1
  140. package/templates/.agents/skills/release/SKILL.zh-CN.md +3 -1
  141. package/templates/.agents/skills/restore-task/SKILL.en.md +3 -1
  142. package/templates/.agents/skills/restore-task/SKILL.zh-CN.md +3 -1
  143. package/templates/.agents/skills/review-analysis/SKILL.en.md +6 -2
  144. package/templates/.agents/skills/review-analysis/SKILL.zh-CN.md +6 -2
  145. package/templates/.agents/skills/review-analysis/reference/output-templates.en.md +1 -1
  146. package/templates/.agents/skills/review-analysis/reference/output-templates.zh-CN.md +1 -1
  147. package/templates/.agents/skills/review-analysis/reference/report-template.en.md +1 -1
  148. package/templates/.agents/skills/review-analysis/reference/report-template.zh-CN.md +1 -2
  149. package/templates/.agents/skills/review-code/SKILL.en.md +5 -2
  150. package/templates/.agents/skills/review-code/SKILL.zh-CN.md +5 -2
  151. package/templates/.agents/skills/review-code/reference/output-templates.en.md +1 -1
  152. package/templates/.agents/skills/review-code/reference/output-templates.zh-CN.md +1 -1
  153. package/templates/.agents/skills/review-code/reference/report-template.en.md +1 -1
  154. package/templates/.agents/skills/review-code/reference/report-template.zh-CN.md +1 -2
  155. package/templates/.agents/skills/review-plan/SKILL.en.md +6 -2
  156. package/templates/.agents/skills/review-plan/SKILL.zh-CN.md +6 -2
  157. package/templates/.agents/skills/review-plan/reference/output-templates.en.md +1 -1
  158. package/templates/.agents/skills/review-plan/reference/output-templates.zh-CN.md +1 -1
  159. package/templates/.agents/skills/review-plan/reference/report-template.en.md +1 -1
  160. package/templates/.agents/skills/review-plan/reference/report-template.zh-CN.md +1 -2
  161. package/templates/.agents/skills/test/SKILL.en.md +3 -1
  162. package/templates/.agents/skills/test/SKILL.zh-CN.md +1 -1
  163. package/templates/.agents/skills/test-integration/SKILL.en.md +3 -1
  164. package/templates/.agents/skills/test-integration/SKILL.zh-CN.md +3 -1
  165. package/templates/.agents/skills/update-agent-infra/SKILL.en.md +3 -1
  166. package/templates/.agents/skills/update-agent-infra/SKILL.zh-CN.md +3 -1
  167. package/templates/.agents/skills/upgrade-dependency/SKILL.en.md +3 -1
  168. package/templates/.agents/skills/upgrade-dependency/SKILL.zh-CN.md +3 -1
  169. package/templates/.agents/skills/watch-pr/SKILL.en.md +3 -1
  170. package/templates/.agents/skills/watch-pr/SKILL.zh-CN.md +3 -1
  171. package/templates/.agents/templates/task.en.md +3 -3
  172. package/templates/.agents/templates/task.zh-CN.md +3 -3
  173. package/templates/.github/workflows/metadata-sync.yml +0 -18
@@ -0,0 +1,96 @@
1
+ import { VERSION } from "../version.js";
2
+ import { loadServerConfig } from "./config.js";
3
+ import { createLogger } from "./logger.js";
4
+ import { loadAdapters, unloadAdapters } from "./plugin-loader.js";
5
+ import { authorize } from "./auth.js";
6
+ import { commandHelp, parseCommand } from "./protocol.js";
7
+ import { runAi } from "./runner.js";
8
+ import { streamCommand } from "./streamer.js";
9
+ function errorMessage(error) {
10
+ return error instanceof Error ? error.message : String(error);
11
+ }
12
+ // The daemon main loop. Runs in the detached child spawned by
13
+ // process-control.start(), or in the foreground for debugging.
14
+ //
15
+ // Lifecycle (keep-alive / shutdown model):
16
+ // - The heartbeat interval is kept *ref'd*. It is both the keep-alive that
17
+ // holds the event loop open while subtask A has no adapters, and the
18
+ // observable signal that `ai server logs -f` shows.
19
+ // - runDaemon() awaits a shutdown promise that only resolves once a
20
+ // SIGINT/SIGTERM handler has finished graceful cleanup. We never unref()
21
+ // the only keep-alive timer (that would let the process exit immediately).
22
+ export async function runDaemon() {
23
+ let config;
24
+ try {
25
+ config = loadServerConfig();
26
+ }
27
+ catch (error) {
28
+ process.stderr.write(`${errorMessage(error)}\n`);
29
+ process.exit(1);
30
+ }
31
+ const logger = createLogger(config.log);
32
+ logger.info(`daemon starting agent-infra ${VERSION} pid=${process.pid}`);
33
+ const abortController = new AbortController();
34
+ let resolveShutdown = () => { };
35
+ const shutdown = new Promise((resolve) => {
36
+ resolveShutdown = resolve;
37
+ });
38
+ const dispatch = async (message) => {
39
+ const plan = parseCommand(message.text);
40
+ if (plan.kind === 'ignore')
41
+ return;
42
+ if (plan.kind === 'error') {
43
+ await message.reply(plan.message);
44
+ logger.info(`command rejected from ${message.adapter}:${message.userId}: ${plan.message}`);
45
+ return;
46
+ }
47
+ if (plan.kind === 'builtin' && plan.name === 'ping') {
48
+ await message.reply(`pong ${VERSION}`);
49
+ return;
50
+ }
51
+ if (plan.kind === 'builtin' && plan.name === 'help') {
52
+ await message.reply(commandHelp());
53
+ return;
54
+ }
55
+ if (plan.kind === 'builtin' && plan.name === 'version') {
56
+ await message.reply(`agent-infra ${VERSION}`);
57
+ return;
58
+ }
59
+ if (plan.kind === 'ai') {
60
+ const allowed = authorize({ adapter: message.adapter, userId: message.userId }, plan.role, config.auth);
61
+ if (!allowed.ok) {
62
+ await message.reply(allowed.message);
63
+ logger.info(`unauthorized command from ${message.adapter}:${message.userId}: ${allowed.message}`);
64
+ return;
65
+ }
66
+ await streamCommand({
67
+ title: `ai ${plan.argv.join(' ')}`,
68
+ chunkChars: typeof config.stream?.chunkChars === 'number' ? config.stream.chunkChars : 4000,
69
+ throttleMs: typeof config.stream?.throttleMs === 'number' ? config.stream.throttleMs : 1500
70
+ }, (emit) => runAi(plan.argv, { onChunk: emit }), (text) => message.reply(text));
71
+ }
72
+ };
73
+ const ctx = { config, logger, dispatch, signal: abortController.signal };
74
+ const adapters = await loadAdapters(config, ctx);
75
+ logger.ok(`loaded ${adapters.length} adapter(s)`);
76
+ const heartbeat = setInterval(() => logger.info('heartbeat'), config.heartbeatMs);
77
+ let shuttingDown = false;
78
+ const handleSignal = (signal) => {
79
+ if (shuttingDown)
80
+ return;
81
+ shuttingDown = true;
82
+ logger.info(`received ${signal}, shutting down`);
83
+ abortController.abort();
84
+ void (async () => {
85
+ await unloadAdapters(adapters);
86
+ clearInterval(heartbeat);
87
+ logger.close();
88
+ resolveShutdown();
89
+ })();
90
+ };
91
+ process.on('SIGINT', () => handleSignal('SIGINT'));
92
+ process.on('SIGTERM', () => handleSignal('SIGTERM'));
93
+ await shutdown;
94
+ process.exit(0);
95
+ }
96
+ //# sourceMappingURL=daemon.js.map
@@ -0,0 +1,47 @@
1
+ import { runDaemon } from "./daemon.js";
2
+ import { start, stop, status, logs } from "./process-control.js";
3
+ const USAGE = `Usage: ai server <command> [options]
4
+
5
+ Commands:
6
+ start [--foreground] Start the local daemon (detached; --foreground stays attached for debugging)
7
+ stop Stop the running daemon
8
+ status Show whether the daemon is running
9
+ logs [-f | --follow] Print the daemon log ('-f' to follow new lines)
10
+ help Show this help message
11
+
12
+ The daemon hosts IM adapters and command routing for agent-infra.`;
13
+ export async function runServer(args) {
14
+ const [subcommand, ...rest] = args;
15
+ if (!subcommand) {
16
+ process.stdout.write(`${USAGE}\n`);
17
+ process.exitCode = 1;
18
+ return;
19
+ }
20
+ if (subcommand === 'help' || subcommand === '--help' || subcommand === '-h') {
21
+ process.stdout.write(`${USAGE}\n`);
22
+ return;
23
+ }
24
+ switch (subcommand) {
25
+ case 'start':
26
+ await start({ foreground: rest.includes('--foreground') });
27
+ break;
28
+ case 'stop':
29
+ await stop();
30
+ break;
31
+ case 'status':
32
+ status();
33
+ break;
34
+ case 'logs':
35
+ await logs({ follow: rest.includes('-f') || rest.includes('--follow') });
36
+ break;
37
+ // Internal entry point for the detached daemon child (not shown in USAGE).
38
+ case '__daemon':
39
+ await runDaemon();
40
+ break;
41
+ default:
42
+ process.stderr.write(`Unknown server command: ${subcommand}\n`);
43
+ process.stdout.write(`${USAGE}\n`);
44
+ process.exitCode = 1;
45
+ }
46
+ }
47
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,34 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ // Startup-only rotation: if the existing log already exceeds the threshold,
4
+ // move it aside to `<path>.1` before the daemon starts appending. We do not
5
+ // rotate again while running — keeping a single append stream is simpler and
6
+ // good enough for a local daemon log.
7
+ function rotateIfOversized(logPath, rotateAtBytes) {
8
+ try {
9
+ const { size } = fs.statSync(logPath);
10
+ if (size > rotateAtBytes) {
11
+ fs.renameSync(logPath, `${logPath}.1`);
12
+ }
13
+ }
14
+ catch {
15
+ // No existing log file (or stat failed) → nothing to rotate.
16
+ }
17
+ }
18
+ export function createLogger({ path: logPath, rotateAtBytes }) {
19
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
20
+ rotateIfOversized(logPath, rotateAtBytes);
21
+ const write = (level, message) => {
22
+ const line = `[${new Date().toISOString()}] [${level}] ${message}\n`;
23
+ fs.appendFileSync(logPath, line);
24
+ };
25
+ return {
26
+ info: (message) => write('INFO', message),
27
+ ok: (message) => write('OK', message),
28
+ err: (message) => write('ERROR', message),
29
+ // Synchronous appendFileSync keeps no open handle to flush; close() exists
30
+ // so the daemon shutdown path has a single, stable hook to call.
31
+ close: () => { }
32
+ };
33
+ }
34
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1,73 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import path from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+ const defaultImportAdapter = (name) => {
12
+ // Test-only seam: when AGENT_INFRA_SERVER_TEST_ADAPTERS_DIR is set (never in
13
+ // production), resolve the named adapter as a plain ESM `.js` from that
14
+ // fixtures dir. This lets a built daemon (`node dist/bin/cli.js`) load a test
15
+ // injection adapter on any node>=22 without depending on type stripping.
16
+ const testDir = process.env.AGENT_INFRA_SERVER_TEST_ADAPTERS_DIR;
17
+ if (testDir) {
18
+ return import(__rewriteRelativeImportExtension(pathToFileURL(path.join(testDir, name, 'index.js')).href));
19
+ }
20
+ return import(__rewriteRelativeImportExtension(`./adapters/${name}/index.ts`));
21
+ };
22
+ function errorMessage(error) {
23
+ return error instanceof Error ? error.message : String(error);
24
+ }
25
+ function isAdapter(value) {
26
+ if (typeof value !== 'object' || value === null)
27
+ return false;
28
+ const candidate = value;
29
+ return (typeof candidate.name === 'string' &&
30
+ typeof candidate.start === 'function' &&
31
+ typeof candidate.stop === 'function' &&
32
+ typeof candidate.sendMessage === 'function');
33
+ }
34
+ // Load every adapter whose config has `enabled === true`. Each adapter is
35
+ // loaded, instantiated and started in isolation: a failure in one adapter is
36
+ // logged and skipped so it never blocks the others.
37
+ export async function loadAdapters(config, ctx, options = {}) {
38
+ const importAdapter = options.importAdapter ?? defaultImportAdapter;
39
+ const loaded = [];
40
+ for (const [name, adapterConfig] of Object.entries(config.adapters)) {
41
+ if (adapterConfig?.enabled !== true)
42
+ continue;
43
+ try {
44
+ const mod = (await importAdapter(name));
45
+ const factory = mod?.default;
46
+ if (typeof factory !== 'function') {
47
+ throw new Error(`adapter "${name}" has no default export factory`);
48
+ }
49
+ const instance = factory(adapterConfig);
50
+ if (!isAdapter(instance)) {
51
+ throw new Error(`adapter "${name}" does not satisfy the Adapter contract`);
52
+ }
53
+ await instance.start(ctx);
54
+ loaded.push(instance);
55
+ }
56
+ catch (error) {
57
+ ctx.logger.err(`failed to load adapter "${name}": ${errorMessage(error)}`);
58
+ }
59
+ }
60
+ return loaded;
61
+ }
62
+ // Stop adapters in reverse load order, isolating per-adapter stop failures.
63
+ export async function unloadAdapters(adapters) {
64
+ for (const adapter of [...adapters].reverse()) {
65
+ try {
66
+ await adapter.stop();
67
+ }
68
+ catch {
69
+ // A failing stop must not block the rest of shutdown.
70
+ }
71
+ }
72
+ }
73
+ //# sourceMappingURL=plugin-loader.js.map
@@ -0,0 +1,200 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawn, execFileSync } from 'node:child_process';
4
+ import { loadServerConfig } from "./config.js";
5
+ import { runDaemon } from "./daemon.js";
6
+ export function buildStopCommand(pid, platform) {
7
+ if (platform === 'win32') {
8
+ return { kind: 'exec', command: 'taskkill', args: ['/PID', String(pid), '/T', '/F'] };
9
+ }
10
+ return { kind: 'signal', signal: 'SIGTERM' };
11
+ }
12
+ // Liveness check that treats an exited-but-unreaped daemon as dead.
13
+ //
14
+ // The daemon is spawned detached and re-parented to init when `ai server start`
15
+ // exits. After it terminates, `process.kill(pid, 0)` still succeeds until init
16
+ // reaps the zombie. On Linux we therefore also check /proc state so status/stop
17
+ // /start don't treat an already-exited daemon as running. macOS reaps orphans
18
+ // via launchd and Windows has no zombies, so the kill(pid, 0) result is enough.
19
+ export function isProcessAlive(pid) {
20
+ try {
21
+ process.kill(pid, 0);
22
+ }
23
+ catch (error) {
24
+ // EPERM means the process exists but we may not signal it → still alive.
25
+ return error.code === 'EPERM';
26
+ }
27
+ if (process.platform === 'linux') {
28
+ try {
29
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
30
+ // The process state is the first token after the parenthesised comm.
31
+ const state = stat.slice(stat.lastIndexOf(')') + 1).trim().charAt(0);
32
+ if (state === 'Z')
33
+ return false;
34
+ }
35
+ catch {
36
+ return false; // /proc entry vanished → not alive
37
+ }
38
+ }
39
+ return true;
40
+ }
41
+ function readPid(pidFile) {
42
+ try {
43
+ const raw = fs.readFileSync(pidFile, 'utf8').trim();
44
+ const pid = Number.parseInt(raw, 10);
45
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ function removePidFile(pidFile) {
52
+ try {
53
+ fs.unlinkSync(pidFile);
54
+ }
55
+ catch {
56
+ // Already gone.
57
+ }
58
+ }
59
+ function delay(ms) {
60
+ return new Promise((resolve) => {
61
+ setTimeout(resolve, ms);
62
+ });
63
+ }
64
+ function enabledAdapterNames(config) {
65
+ return Object.entries(config.adapters)
66
+ .filter(([, adapter]) => adapter?.enabled === true)
67
+ .map(([name]) => name);
68
+ }
69
+ export async function start({ foreground = false } = {}) {
70
+ const config = loadServerConfig();
71
+ const pidPath = config.pidFile;
72
+ // Zombie PID cleanup: a stale PID file from a crashed daemon must not block a
73
+ // fresh start.
74
+ const existing = readPid(pidPath);
75
+ if (existing !== null && isProcessAlive(existing)) {
76
+ process.stdout.write(`server already running (pid ${existing})\n`);
77
+ return;
78
+ }
79
+ if (existing !== null) {
80
+ removePidFile(pidPath);
81
+ }
82
+ if (foreground) {
83
+ await runDaemon();
84
+ return;
85
+ }
86
+ const cliEntry = process.argv[1];
87
+ if (!cliEntry) {
88
+ throw new Error('server: unable to determine CLI entry point for daemon spawn');
89
+ }
90
+ // Re-spawn ourselves detached. process.execArgv is forwarded so the dev path
91
+ // (node --experimental-strip-types ./bin/cli.ts) and the built path
92
+ // (node dist/bin/cli.js) both work.
93
+ const child = spawn(process.execPath, [...process.execArgv, cliEntry, 'server', '__daemon'], {
94
+ detached: true,
95
+ stdio: 'ignore'
96
+ });
97
+ child.unref();
98
+ if (typeof child.pid !== 'number') {
99
+ throw new Error('server: failed to spawn daemon process');
100
+ }
101
+ fs.mkdirSync(path.dirname(pidPath), { recursive: true });
102
+ fs.writeFileSync(pidPath, `${child.pid}\n`);
103
+ process.stdout.write(`server started (pid ${child.pid})\n`);
104
+ }
105
+ export async function stop() {
106
+ const config = loadServerConfig();
107
+ const pid = readPid(config.pidFile);
108
+ if (pid === null) {
109
+ process.stdout.write('server is not running (no pid file)\n');
110
+ return;
111
+ }
112
+ if (!isProcessAlive(pid)) {
113
+ removePidFile(config.pidFile);
114
+ process.stdout.write('server is not running (removed stale pid file)\n');
115
+ return;
116
+ }
117
+ const command = buildStopCommand(pid, process.platform);
118
+ if (command.kind === 'exec') {
119
+ execFileSync(command.command, command.args);
120
+ }
121
+ else {
122
+ process.kill(pid, command.signal);
123
+ const deadline = Date.now() + 5000;
124
+ while (isProcessAlive(pid) && Date.now() < deadline) {
125
+ await delay(100);
126
+ }
127
+ if (isProcessAlive(pid)) {
128
+ process.kill(pid, 'SIGKILL');
129
+ }
130
+ }
131
+ removePidFile(config.pidFile);
132
+ process.stdout.write(`server stopped (pid ${pid})\n`);
133
+ }
134
+ export function status() {
135
+ const config = loadServerConfig();
136
+ const pid = readPid(config.pidFile);
137
+ if (pid === null || !isProcessAlive(pid)) {
138
+ process.stdout.write('server: stopped\n');
139
+ if (pid !== null) {
140
+ process.stdout.write(` (stale pid file references pid ${pid})\n`);
141
+ }
142
+ return;
143
+ }
144
+ let startedAt = 'unknown';
145
+ try {
146
+ startedAt = fs.statSync(config.pidFile).mtime.toISOString();
147
+ }
148
+ catch {
149
+ // Leave as unknown.
150
+ }
151
+ const adapters = enabledAdapterNames(config);
152
+ process.stdout.write(`server: running\n` +
153
+ ` pid: ${pid}\n` +
154
+ ` started: ${startedAt}\n` +
155
+ ` adapters: ${adapters.length > 0 ? adapters.join(', ') : '(none)'}\n` +
156
+ ` pid file: ${config.pidFile}\n` +
157
+ ` log: ${config.log.path}\n`);
158
+ }
159
+ export async function logs({ follow = false } = {}) {
160
+ const config = loadServerConfig();
161
+ const logPath = config.log.path;
162
+ if (!fs.existsSync(logPath)) {
163
+ process.stdout.write('server: no log file yet\n');
164
+ return;
165
+ }
166
+ const initial = fs.readFileSync(logPath, 'utf8');
167
+ process.stdout.write(initial);
168
+ if (!follow)
169
+ return;
170
+ let position = Buffer.byteLength(initial);
171
+ const watcher = fs.watch(logPath, () => {
172
+ try {
173
+ const { size } = fs.statSync(logPath);
174
+ if (size < position)
175
+ position = 0; // truncated or rotated
176
+ if (size > position) {
177
+ const fd = fs.openSync(logPath, 'r');
178
+ try {
179
+ const buffer = Buffer.alloc(size - position);
180
+ fs.readSync(fd, buffer, 0, buffer.length, position);
181
+ process.stdout.write(buffer.toString('utf8'));
182
+ }
183
+ finally {
184
+ fs.closeSync(fd);
185
+ }
186
+ position = size;
187
+ }
188
+ }
189
+ catch {
190
+ // Transient read error during rotation; ignore and wait for next event.
191
+ }
192
+ });
193
+ await new Promise((resolve) => {
194
+ process.on('SIGINT', () => {
195
+ watcher.close();
196
+ resolve();
197
+ });
198
+ });
199
+ }
200
+ //# sourceMappingURL=process-control.js.map
@@ -0,0 +1,69 @@
1
+ import { VERSION } from "../version.js";
2
+ import { getSkillRunSpec } from "../run/skills.js";
3
+ const TASK_READ = new Set(['ls', 'list', 'status', 'show', 'log', 'decisions']);
4
+ const SANDBOX_READ = new Set(['ls', 'list', 'show']);
5
+ const SANDBOX_WRITE = new Set(['create', 'start']);
6
+ function splitWords(text) {
7
+ return text.trim().split(/\s+/).filter(Boolean);
8
+ }
9
+ function taskSubcommand(subcommand) {
10
+ return subcommand === 'list' ? 'ls' : subcommand;
11
+ }
12
+ export function commandHelp() {
13
+ return [
14
+ `agent-infra ${VERSION}`,
15
+ 'Built-ins: /help, /ping, /version',
16
+ 'Read: /sandbox ls|show|vm status, /task decisions|log|ls|show|status',
17
+ 'Write: /sandbox create|start',
18
+ 'Exec: /decide <task-ref> <HD-id> <decision>, /run create-task <description>, /run <skill> <task-ref> ...'
19
+ ].join('\n');
20
+ }
21
+ export function parseCommand(text) {
22
+ const trimmed = text.trim();
23
+ if (!trimmed.startsWith('/'))
24
+ return { kind: 'ignore' };
25
+ const words = splitWords(trimmed);
26
+ const [command = '', subcommand = '', ...rest] = words;
27
+ if (command === '/help')
28
+ return { kind: 'builtin', name: 'help', role: 'read', args: rest };
29
+ if (command === '/ping')
30
+ return { kind: 'builtin', name: 'ping', role: 'read', args: rest };
31
+ if (command === '/version')
32
+ return { kind: 'builtin', name: 'version', role: 'read', args: rest };
33
+ if (command === '/decide') {
34
+ return { kind: 'ai', role: 'exec', argv: ['decide', subcommand, ...rest] };
35
+ }
36
+ if (command === '/task') {
37
+ if (!TASK_READ.has(subcommand))
38
+ return { kind: 'error', message: 'Unknown /task command' };
39
+ return { kind: 'ai', role: 'read', argv: ['task', taskSubcommand(subcommand), ...rest] };
40
+ }
41
+ if (command === '/sandbox') {
42
+ if (subcommand === 'vm') {
43
+ if (rest[0] !== 'status')
44
+ return { kind: 'error', message: 'Only /sandbox vm status is allowed' };
45
+ return { kind: 'ai', role: 'read', argv: ['sandbox', 'vm', 'status'] };
46
+ }
47
+ if (SANDBOX_READ.has(subcommand)) {
48
+ return { kind: 'ai', role: 'read', argv: ['sandbox', taskSubcommand(subcommand), ...rest] };
49
+ }
50
+ if (SANDBOX_WRITE.has(subcommand)) {
51
+ return { kind: 'ai', role: 'write', argv: ['sandbox', subcommand, ...rest] };
52
+ }
53
+ if (subcommand === 'rm') {
54
+ return {
55
+ kind: 'error',
56
+ message: '/sandbox rm is not available from IM because it requires interactive confirmation'
57
+ };
58
+ }
59
+ return { kind: 'error', message: 'Unknown /sandbox command' };
60
+ }
61
+ if (command === '/run') {
62
+ const spec = getSkillRunSpec(subcommand);
63
+ if (!spec)
64
+ return { kind: 'error', message: `Unknown skill: ${subcommand}` };
65
+ return { kind: 'ai', role: spec.role, argv: ['run', subcommand, ...rest] };
66
+ }
67
+ return { kind: 'error', message: `Unknown command: ${command}` };
68
+ }
69
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1,12 @@
1
+ const SECRET_PATTERNS = [
2
+ /\b(token|secret|password|passwd|api[_-]?key)=([^\s]+)/gi,
3
+ /\b(Bearer\s+)[A-Za-z0-9._~+/=-]+/g
4
+ ];
5
+ export function redactSecrets(text) {
6
+ let out = text;
7
+ for (const pattern of SECRET_PATTERNS) {
8
+ out = out.replace(pattern, (_match, prefix) => `${prefix}=<redacted>`);
9
+ }
10
+ return out;
11
+ }
12
+ //# sourceMappingURL=redact.js.map
@@ -0,0 +1,75 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ function resolveCommand(file) {
5
+ if (process.platform !== 'win32' || path.extname(file)) {
6
+ return file;
7
+ }
8
+ const pathValue = process.env.Path || process.env.PATH || '';
9
+ const extensions = (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
10
+ for (const dir of pathValue.split(path.delimiter).filter(Boolean)) {
11
+ for (const extension of extensions) {
12
+ const lowerCandidate = path.join(dir, `${file}${extension.toLowerCase()}`);
13
+ if (fs.existsSync(lowerCandidate))
14
+ return lowerCandidate;
15
+ const upperCandidate = path.join(dir, `${file}${extension.toUpperCase()}`);
16
+ if (fs.existsSync(upperCandidate))
17
+ return upperCandidate;
18
+ }
19
+ }
20
+ return file;
21
+ }
22
+ function needsShell(file) {
23
+ return process.platform === 'win32' && /\.(?:bat|cmd)$/i.test(file);
24
+ }
25
+ function spawnCapture(file, args, onChunk) {
26
+ return new Promise((resolve, reject) => {
27
+ const resolvedFile = resolveCommand(file);
28
+ const child = spawn(resolvedFile, args, {
29
+ stdio: ['ignore', 'pipe', 'pipe'],
30
+ shell: needsShell(resolvedFile)
31
+ });
32
+ let stdout = '';
33
+ let stderr = '';
34
+ let settled = false;
35
+ let pendingChunks = Promise.resolve();
36
+ const rejectOnce = (error) => {
37
+ if (settled)
38
+ return;
39
+ settled = true;
40
+ reject(error);
41
+ };
42
+ const resolveOnce = (result) => {
43
+ if (settled)
44
+ return;
45
+ settled = true;
46
+ resolve(result);
47
+ };
48
+ const enqueueChunk = (chunk) => {
49
+ if (!onChunk)
50
+ return;
51
+ pendingChunks = pendingChunks.then(() => onChunk(chunk));
52
+ pendingChunks.catch(rejectOnce);
53
+ };
54
+ child.stdout.setEncoding('utf8');
55
+ child.stderr.setEncoding('utf8');
56
+ child.stdout.on('data', (chunk) => {
57
+ stdout += chunk;
58
+ enqueueChunk(chunk);
59
+ });
60
+ child.stderr.on('data', (chunk) => {
61
+ stderr += chunk;
62
+ enqueueChunk(chunk);
63
+ });
64
+ child.on('error', rejectOnce);
65
+ child.on('close', (exitCode, signal) => {
66
+ pendingChunks
67
+ .then(() => resolveOnce({ exitCode, signal, stdout, stderr }))
68
+ .catch(rejectOnce);
69
+ });
70
+ });
71
+ }
72
+ export async function runAi(args, options = {}) {
73
+ return (options.spawn ?? spawnCapture)('ai', args, options.onChunk);
74
+ }
75
+ //# sourceMappingURL=runner.js.map
@@ -0,0 +1,44 @@
1
+ import { redactSecrets } from "./redact.js";
2
+ function chunks(text, size) {
3
+ if (text.length === 0)
4
+ return [];
5
+ const out = [];
6
+ for (let i = 0; i < text.length; i += size) {
7
+ out.push(text.slice(i, i + size));
8
+ }
9
+ return out;
10
+ }
11
+ export async function streamCommand(options, run, send) {
12
+ await send(`started ${options.title}`);
13
+ const size = options.chunkChars ?? 4000;
14
+ const throttleMs = options.throttleMs ?? 0;
15
+ let streamed = false;
16
+ let buffer = '';
17
+ let lastFlush = 0;
18
+ const flush = async () => {
19
+ if (!buffer)
20
+ return;
21
+ const text = redactSecrets(buffer);
22
+ buffer = '';
23
+ lastFlush = Date.now();
24
+ for (const chunk of chunks(text, size)) {
25
+ await send(chunk);
26
+ }
27
+ };
28
+ const emit = async (chunk) => {
29
+ streamed = true;
30
+ buffer += chunk;
31
+ const due = throttleMs === 0 || Date.now() - lastFlush >= throttleMs;
32
+ if (buffer.length >= size || due) {
33
+ await flush();
34
+ }
35
+ };
36
+ const result = await run(emit);
37
+ if (!streamed) {
38
+ buffer += [result.stdout, result.stderr].filter(Boolean).join('\n');
39
+ }
40
+ await flush();
41
+ await send(`finished ${options.title} exitCode=${result.exitCode} signal=${result.signal ?? 'null'}`);
42
+ return result;
43
+ }
44
+ //# sourceMappingURL=streamer.js.map