@aiwg/cli 2026.10.14 → 2026.10.16

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 (210) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  4. package/dist/src/artifacts/citation-parser.js +7 -6
  5. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  6. package/dist/src/artifacts/corpus-tools/cli.js +37 -0
  7. package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
  8. package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
  9. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  10. package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  12. package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
  13. package/dist/src/artifacts/corpus-tools/expand.js +124 -0
  14. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  15. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  16. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  17. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  18. package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
  19. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  20. package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
  21. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  22. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  23. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  24. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  25. package/dist/src/artifacts/graph-query.js +5 -3
  26. package/dist/src/artifacts/hybrid-query.js +11 -2
  27. package/dist/src/artifacts/index-refresh.js +2 -0
  28. package/dist/src/cli/handlers/daemon.js +17 -1
  29. package/dist/src/cli/handlers/doctor-args.js +45 -0
  30. package/dist/src/cli/handlers/doctor-help.js +8 -3
  31. package/dist/src/cli/handlers/index.js +2 -2
  32. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  33. package/dist/src/cli/handlers/models.js +3 -2
  34. package/dist/src/cli/handlers/regenerate.js +8 -16
  35. package/dist/src/cli/handlers/sessions.js +7 -7
  36. package/dist/src/cli/handlers/subcommands.js +8 -0
  37. package/dist/src/cli/handlers/update.js +157 -0
  38. package/dist/src/cli/handlers/use.js +14 -4
  39. package/dist/src/cli/handlers/utilities.js +3 -586
  40. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  41. package/dist/src/cli/services/deployment-verification.js +0 -1
  42. package/dist/src/config/aiwg-config.js +2 -1
  43. package/dist/src/config/authorization-cli.js +7 -3
  44. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  45. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  46. package/dist/src/config/framework-aliases.js +12 -0
  47. package/dist/src/config/host-resource-report.d.mts +19 -0
  48. package/dist/src/config/host-resource-report.mjs +80 -0
  49. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  50. package/dist/src/config/host-resource-runtime.mjs +293 -0
  51. package/dist/src/config/installed-selection.js +22 -0
  52. package/dist/src/config/worker-context.js +33 -4
  53. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  54. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  55. package/dist/src/decision/heldout/access.js +74 -0
  56. package/dist/src/decision/heldout/calibration.js +1 -0
  57. package/dist/src/decision/heldout/collector.js +9 -2
  58. package/dist/src/effects/verifiers/file.js +22 -5
  59. package/dist/src/extensions/claude-attribution.js +82 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  61. package/dist/src/extensions/commands/daemon.js +109 -0
  62. package/dist/src/extensions/commands/definitions.js +5 -89
  63. package/dist/src/features/catalog.js +1 -1
  64. package/dist/src/gates/evaluate.js +2 -2
  65. package/dist/src/gates/heldout.js +52 -0
  66. package/dist/src/gates/index.js +2 -1
  67. package/dist/src/lint/check-patterns.js +163 -0
  68. package/dist/src/lint/checks.js +268 -0
  69. package/dist/src/lint/reference-resolution.js +54 -0
  70. package/dist/src/lint/runner.js +3 -465
  71. package/dist/src/mcp/helpers.mjs +11 -1
  72. package/dist/src/memory/project-registry.js +44 -4
  73. package/dist/src/models/worker-installation-store.mjs +228 -0
  74. package/dist/src/models/worker-installation.mjs +7 -162
  75. package/dist/src/models/worker-plan.js +36 -5
  76. package/dist/src/models/wrapper-deployment.js +25 -12
  77. package/dist/src/models/wrapper-enforcement.js +47 -7
  78. package/dist/src/network-analysis/research.js +2 -1
  79. package/dist/src/policy/hitl-check.js +14 -4
  80. package/dist/src/policy/hitl-consume.js +54 -0
  81. package/dist/src/policy/hitl-receipt.js +2 -0
  82. package/dist/src/policy/hitl.js +11 -3
  83. package/dist/src/providers/provider-context-contracts.js +162 -0
  84. package/dist/src/providers/provider-definition-schema.js +136 -0
  85. package/dist/src/providers/provider-definitions.js +8 -1298
  86. package/dist/src/providers/provider-seeds-1.js +360 -0
  87. package/dist/src/providers/provider-seeds-2.js +387 -0
  88. package/dist/src/providers/provider-seeds-3.js +262 -0
  89. package/dist/src/research/clients/arxiv.js +14 -34
  90. package/dist/src/research/clients/base.js +53 -26
  91. package/dist/src/research/clients/crossref.js +9 -1
  92. package/dist/src/research/clients/semantic-scholar.js +73 -44
  93. package/dist/src/research/identity.js +117 -0
  94. package/dist/src/research/index.js +1 -0
  95. package/dist/src/research/query-cli.js +3 -87
  96. package/dist/src/research/query-options.js +87 -0
  97. package/dist/src/research/reference-match.js +135 -0
  98. package/dist/src/research/services/acquisition.js +9 -7
  99. package/dist/src/research/services/citation.js +5 -2
  100. package/dist/src/research/types.js +2 -0
  101. package/dist/src/rules/core-startup.d.mts +2 -0
  102. package/dist/src/rules/core-startup.mjs +31 -0
  103. package/dist/src/serve/mission-conductor.js +48 -4
  104. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  105. package/dist/src/sessions/adapters/grok-build.js +14 -7
  106. package/dist/src/sessions/workspace-discovery.js +5 -5
  107. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  108. package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
  109. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  110. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  111. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  112. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  113. package/dist/src/smiths/context-pipeline/generator.js +49 -114
  114. package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
  115. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  116. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  117. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  118. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  119. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  120. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  121. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  122. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  123. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  124. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  125. package/package.json +13 -2
  126. package/schemas/decision/D29Study.v10.schema.json +65 -0
  127. package/tools/agents/deploy-agents.mjs +12 -123
  128. package/tools/agents/providers/antigravity.mjs +1 -1
  129. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  130. package/tools/agents/providers/context-write.mjs +16 -0
  131. package/tools/agents/providers/grok-build.mjs +8 -5
  132. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  133. package/tools/agents/providers/hermes-startup.mjs +209 -0
  134. package/tools/agents/providers/hermes.mjs +9 -359
  135. package/tools/agents/providers/model-wrapper.mjs +5 -1
  136. package/tools/agents/providers/muse.mjs +3 -3
  137. package/tools/agents/providers/pi.mjs +4 -2
  138. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  139. package/tools/agents/providers/rule-delivery.mjs +20 -1346
  140. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  141. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  142. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  143. package/tools/agents/providers/rule-presentation.mjs +13 -4
  144. package/tools/agents/providers/rule-projection.mjs +119 -0
  145. package/tools/agents/providers/rule-startup.mjs +70 -0
  146. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  147. package/tools/agents/providers/warp.mjs +2 -2
  148. package/tools/agents/providers/windsurf.mjs +11 -57
  149. package/tools/daemon/README.md +511 -0
  150. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  151. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  152. package/tools/daemon/agent-supervisor.mjs +299 -0
  153. package/tools/daemon/automation-engine.mjs +310 -0
  154. package/tools/daemon/autonomous-engine.mjs +346 -0
  155. package/tools/daemon/behavior-loader.mjs +316 -0
  156. package/tools/daemon/behavior.mjs +174 -0
  157. package/tools/daemon/concierge/intent-router.mjs +401 -0
  158. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  159. package/tools/daemon/concierge/response-translator.mjs +462 -0
  160. package/tools/daemon/config.mjs +377 -0
  161. package/tools/daemon/cron-scheduler.mjs +178 -0
  162. package/tools/daemon/daemon-main.mjs +1169 -0
  163. package/tools/daemon/event-router.mjs +84 -0
  164. package/tools/daemon/file-watcher.mjs +383 -0
  165. package/tools/daemon/index.mjs +1181 -0
  166. package/tools/daemon/init-profile.mjs +124 -0
  167. package/tools/daemon/ipc-client.mjs +197 -0
  168. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  169. package/tools/daemon/ipc-server.mjs +275 -0
  170. package/tools/daemon/maintenance-owner.mjs +79 -0
  171. package/tools/daemon/memory-manager.mjs +386 -0
  172. package/tools/daemon/message-router.mjs +194 -0
  173. package/tools/daemon/provider-watcher.mjs +585 -0
  174. package/tools/daemon/pty-adapter.mjs +420 -0
  175. package/tools/daemon/repl-chat.mjs +359 -0
  176. package/tools/daemon/resource-bounds.mjs +88 -0
  177. package/tools/daemon/sandbox-transport.mjs +295 -0
  178. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  179. package/tools/daemon/task-store.mjs +450 -0
  180. package/tools/daemon/tmux-manager.mjs +324 -0
  181. package/tools/daemon/update-policy.mjs +517 -0
  182. package/tools/daemon/web-server.mjs +399 -0
  183. package/tools/daemon/web-ui/index.html +585 -0
  184. package/tools/daemon/web-ui/styles.css +156 -0
  185. package/tools/docker/Dockerfile.daemon +35 -0
  186. package/tools/docker/container-manager.mjs +291 -0
  187. package/tools/messaging/adapter-registry.mjs +230 -0
  188. package/tools/messaging/adapters/base.mjs +326 -0
  189. package/tools/messaging/adapters/discord.mjs +462 -0
  190. package/tools/messaging/adapters/slack.mjs +402 -0
  191. package/tools/messaging/adapters/telegram.mjs +552 -0
  192. package/tools/messaging/chat-handler.mjs +297 -0
  193. package/tools/messaging/command-router.mjs +269 -0
  194. package/tools/messaging/event-bus.mjs +199 -0
  195. package/tools/messaging/index.mjs +456 -0
  196. package/tools/messaging/message-formatter.mjs +320 -0
  197. package/tools/messaging/room-manager.mjs +277 -0
  198. package/tools/messaging/types.mjs +94 -0
  199. package/tools/plugin/plugin-links.mjs +3 -0
  200. package/tools/providers/pi-bridge-policy.mjs +4 -0
  201. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  202. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  203. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  204. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  205. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  206. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  207. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  208. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  209. package/tools/ralph-external/session-launcher.mjs +7 -7
  210. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,1181 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { spawn } from 'child_process';
6
+ import { fileURLToPath } from 'url';
7
+ import { createClient } from './ipc-client.mjs';
8
+ import { TmuxManager, formatStatusDashboard } from './tmux-manager.mjs';
9
+ import { importImpl } from '../_resolve-impl.mjs';
10
+ const { signalChild } = await importImpl(import.meta.url, 'process/signal-child.mjs');
11
+
12
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
+
14
+ const PID_FILE = '.aiwg/daemon.pid';
15
+ const LOG_FILE = '.aiwg/daemon/daemon.log';
16
+ const STATE_FILE = '.aiwg/daemon/state.json';
17
+ const SOCKET_PATH = '.aiwg/daemon/daemon.sock';
18
+
19
+ class DaemonCLI {
20
+ constructor() {
21
+ this.command = process.argv[2];
22
+ this.flags = this.parseFlags(process.argv.slice(3));
23
+ }
24
+
25
+ parseFlags(args) {
26
+ const flags = {};
27
+ for (let i = 0; i < args.length; i++) {
28
+ if (args[i].startsWith('--')) {
29
+ const key = args[i].slice(2);
30
+ const value = args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : true;
31
+ flags[key] = value;
32
+ if (value !== true) i++;
33
+ }
34
+ }
35
+ return flags;
36
+ }
37
+
38
+ async run() {
39
+ switch (this.command) {
40
+ case '--help':
41
+ case '-h':
42
+ case 'help':
43
+ this.usage();
44
+ return;
45
+ case 'start':
46
+ await this.start();
47
+ break;
48
+ case 'stop':
49
+ await this.stop();
50
+ break;
51
+ case 'status':
52
+ await this.status();
53
+ break;
54
+ case 'logs':
55
+ await this.logs();
56
+ break;
57
+ case 'restart':
58
+ await this.restart();
59
+ break;
60
+ case 'attach':
61
+ await this.attach();
62
+ break;
63
+ case 'chat':
64
+ await this.chat();
65
+ break;
66
+ case 'task':
67
+ await this.task();
68
+ break;
69
+ case 'init':
70
+ await this.init();
71
+ break;
72
+ case 'rooms':
73
+ await this.rooms();
74
+ break;
75
+ case 'autonomous':
76
+ await this.autonomous();
77
+ break;
78
+ case 'schedule':
79
+ await this.schedule();
80
+ break;
81
+ case 'memory':
82
+ await this.memory();
83
+ break;
84
+ case 'pty':
85
+ await this.pty();
86
+ break;
87
+ default:
88
+ this.usage();
89
+ process.exit(1);
90
+ }
91
+ }
92
+
93
+ async start() {
94
+ if (this.flags.docker) {
95
+ await this.startDocker();
96
+ return;
97
+ }
98
+
99
+ if (this.isDaemonRunning()) {
100
+ const pid = this.readPidFile();
101
+ console.error(`Daemon is already running (PID: ${pid})`);
102
+ process.exit(1);
103
+ }
104
+
105
+ this.ensureDirectories();
106
+
107
+ if (this.flags.foreground) {
108
+ await this.startForeground();
109
+ } else {
110
+ await this.startDetached();
111
+ }
112
+ }
113
+
114
+ async startDocker() {
115
+ try {
116
+ const { ContainerManager } = await import('../docker/container-manager.mjs');
117
+ const manager = new ContainerManager({
118
+ projectDir: process.cwd(),
119
+ webPort: parseInt(this.flags.port || '7474', 10),
120
+ });
121
+
122
+ if (!manager.isDockerAvailable()) {
123
+ console.error('Docker is not available. Install Docker or run without --docker.');
124
+ process.exit(1);
125
+ }
126
+
127
+ const { containerId, containerName } = manager.start();
128
+ console.log(`Daemon started in Docker container: ${containerName} (${containerId})`);
129
+ console.log(`Web UI: http://localhost:${this.flags.port || 7474}`);
130
+ } catch (error) {
131
+ console.error(`Failed to start Docker container: ${error.message}`);
132
+ process.exit(1);
133
+ }
134
+ }
135
+
136
+ async startForeground() {
137
+ console.log('Starting daemon in foreground mode...');
138
+ const daemonScript = path.join(__dirname, 'daemon-main.mjs');
139
+
140
+ const child = spawn(process.execPath, [daemonScript], {
141
+ stdio: 'inherit',
142
+ env: process.env
143
+ });
144
+
145
+ child.on('exit', (code) => {
146
+ console.log(`Daemon exited with code ${code}`);
147
+ process.exit(code);
148
+ });
149
+ }
150
+
151
+ async startDetached() {
152
+ console.log('Starting daemon...');
153
+ const daemonScript = path.join(__dirname, 'daemon-main.mjs');
154
+
155
+ const logFd = fs.openSync(LOG_FILE, 'a');
156
+
157
+ const child = spawn(process.execPath, [daemonScript], {
158
+ detached: true,
159
+ stdio: ['ignore', logFd, logFd],
160
+ env: process.env
161
+ });
162
+
163
+ child.unref();
164
+
165
+ await new Promise(resolve => setTimeout(resolve, 1000));
166
+
167
+ if (this.isDaemonRunning()) {
168
+ const pid = this.readPidFile();
169
+ console.log(`Daemon started successfully (PID: ${pid})`);
170
+ console.log(`Logs: ${LOG_FILE}`);
171
+ } else {
172
+ console.error('Daemon failed to start. Check logs for details.');
173
+ process.exit(1);
174
+ }
175
+ }
176
+
177
+ async stop() {
178
+ if (!this.isDaemonRunning()) {
179
+ console.log('Daemon is not running');
180
+ return;
181
+ }
182
+
183
+ const pid = this.readPidFile();
184
+ if (!Number.isSafeInteger(pid) || pid <= 0) return;
185
+ console.log(`Stopping daemon (PID: ${pid})...`);
186
+
187
+ try {
188
+ process.kill(pid, 'SIGTERM');
189
+
190
+ const maxWait = 10000;
191
+ const checkInterval = 500;
192
+ let waited = 0;
193
+
194
+ while (waited < maxWait) {
195
+ await new Promise(resolve => setTimeout(resolve, checkInterval));
196
+ waited += checkInterval;
197
+
198
+ if (!this.isPidAlive(pid)) {
199
+ console.log('Daemon stopped gracefully');
200
+ this.cleanup();
201
+ return;
202
+ }
203
+ }
204
+
205
+ console.log('Daemon did not stop gracefully, sending SIGKILL...');
206
+ process.kill(pid, 'SIGKILL');
207
+ await new Promise(resolve => setTimeout(resolve, 1000));
208
+
209
+ if (!this.isPidAlive(pid)) {
210
+ console.log('Daemon killed');
211
+ this.cleanup();
212
+ } else {
213
+ console.error('Failed to stop daemon');
214
+ process.exit(1);
215
+ }
216
+ } catch (error) {
217
+ if (error.code === 'ESRCH') {
218
+ console.log('Daemon process not found (stale PID file)');
219
+ this.cleanup();
220
+ } else {
221
+ console.error(`Failed to stop daemon: ${error.message}`);
222
+ process.exit(1);
223
+ }
224
+ }
225
+ }
226
+
227
+ async status() {
228
+ if (!this.isDaemonRunning()) {
229
+ console.log('Daemon: stopped');
230
+ return;
231
+ }
232
+
233
+ const pid = this.readPidFile();
234
+ console.log(`Daemon: running (PID: ${pid})`);
235
+
236
+ // Try live IPC query first, fall back to state file
237
+ try {
238
+ const client = await createClient(SOCKET_PATH);
239
+ const state = await client.request('daemon.status');
240
+ client.disconnect();
241
+
242
+ console.log(`Started: ${state.started_at}`);
243
+ console.log(`Uptime: ${state.uptime_seconds}s`);
244
+ console.log(`Health: ${state.health}`);
245
+
246
+ const sub = state.subsystems;
247
+ console.log(`\nIPC clients: ${sub.ipc?.clients || 0}`);
248
+
249
+ if (sub.supervisor) {
250
+ console.log(`\nAgents:`);
251
+ console.log(` Running: ${sub.supervisor.running}`);
252
+ console.log(` Queued: ${sub.supervisor.queued}`);
253
+ console.log(` Max concurrent: ${sub.supervisor.maxConcurrency}`);
254
+ }
255
+
256
+ if (sub.automation?.enabled) {
257
+ console.log(`\nAutomation: enabled (${sub.automation.ruleCount} rules)`);
258
+ }
259
+
260
+ if (sub.file_watcher?.enabled) {
261
+ console.log(`\nFile watcher: enabled (${sub.file_watcher.events_received} events)`);
262
+ }
263
+ if (sub.scheduler?.enabled) {
264
+ console.log(`Scheduler: enabled (${sub.scheduler.jobs} jobs)`);
265
+ }
266
+ if (sub.messaging?.enabled) {
267
+ console.log(`Messaging: enabled (${sub.messaging.adapters} adapters)`);
268
+ }
269
+ return;
270
+ } catch {
271
+ // IPC unavailable, fall back to state file
272
+ }
273
+
274
+ if (fs.existsSync(STATE_FILE)) {
275
+ try {
276
+ const state = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
277
+ console.log(`Started: ${state.started_at}`);
278
+ console.log(`Uptime: ${state.uptime_seconds}s`);
279
+ console.log(`Last heartbeat: ${state.last_heartbeat}`);
280
+ console.log(`Health: ${state.health.status}`);
281
+
282
+ if (state.agents) {
283
+ console.log(`\nAgents:`);
284
+ console.log(` Running: ${state.agents.running}`);
285
+ console.log(` Queued: ${state.agents.queued}`);
286
+ }
287
+
288
+ console.log('\nMonitors:');
289
+ if (state.monitors.file_watcher?.enabled) {
290
+ console.log(` File watcher: enabled (${state.monitors.file_watcher.events_received} events)`);
291
+ }
292
+ if (state.monitors.scheduler?.enabled) {
293
+ console.log(` Scheduler: enabled (${state.monitors.scheduler.jobs} jobs)`);
294
+ }
295
+
296
+ if (state.health.issues.length > 0) {
297
+ console.log('\nIssues:');
298
+ for (const issue of state.health.issues) {
299
+ console.log(` - ${issue}`);
300
+ }
301
+ }
302
+ } catch (error) {
303
+ console.error(`Failed to read state file: ${error.message}`);
304
+ }
305
+ }
306
+ }
307
+
308
+ async logs() {
309
+ if (!fs.existsSync(LOG_FILE)) {
310
+ console.log('No log file found');
311
+ return;
312
+ }
313
+
314
+ const lines = parseInt(this.flags.lines || '50', 10);
315
+ const follow = this.flags.follow || this.flags.f;
316
+
317
+ if (follow) {
318
+ const tail = spawn('tail', ['-f', '-n', String(lines), LOG_FILE], {
319
+ stdio: 'inherit'
320
+ });
321
+
322
+ process.on('SIGINT', () => {
323
+ signalChild(tail);
324
+ process.exit(0);
325
+ });
326
+ } else {
327
+ const content = fs.readFileSync(LOG_FILE, 'utf8');
328
+ const allLines = content.split('\n');
329
+ const tailLines = allLines.slice(-lines);
330
+ console.log(tailLines.join('\n'));
331
+ }
332
+ }
333
+
334
+ async restart() {
335
+ console.log('Restarting daemon...');
336
+ await this.stop();
337
+ await new Promise(resolve => setTimeout(resolve, 1000));
338
+ await this.start();
339
+ }
340
+
341
+ async attach() {
342
+ const tmux = new TmuxManager({ sessionName: 'aiwg-daemon' });
343
+
344
+ if (!tmux.isTmuxAvailable()) {
345
+ console.error('tmux is not installed. Install with: apt install tmux');
346
+ process.exit(1);
347
+ }
348
+
349
+ // If daemon is not running, start it first
350
+ if (!this.isDaemonRunning()) {
351
+ console.log('Daemon is not running. Starting...');
352
+ await this.startDetached();
353
+ await new Promise(resolve => setTimeout(resolve, 500));
354
+ }
355
+
356
+ if (!tmux.sessionExists()) {
357
+ // Create session with REPL in top pane, status in bottom pane
358
+ const replScript = path.join(__dirname, 'repl-entry.mjs');
359
+ const chatCommand = `${process.execPath} ${replScript}`;
360
+ const statusCommand = `watch -n 5 "cat ${STATE_FILE} 2>/dev/null | node -e \\"process.stdin.on('data',d=>{try{const s=JSON.parse(d);console.log('Agents:',s.agents?.running||0,'running,',s.agents?.queued||0,'queued');console.log('Uptime:',s.uptime_seconds+'s')}catch{}})\\" 2>/dev/null || echo 'Waiting for daemon...'"`;
361
+
362
+ try {
363
+ tmux.createSession({
364
+ chatCommand,
365
+ statusCommand,
366
+ });
367
+ console.log('Created tmux session: aiwg-daemon');
368
+ } catch (error) {
369
+ console.error(`Failed to create session: ${error.message}`);
370
+ process.exit(1);
371
+ }
372
+ }
373
+
374
+ try {
375
+ await tmux.attach(this.flags.readonly === true);
376
+ } catch (error) {
377
+ console.error(`Failed to attach: ${error.message}`);
378
+ process.exit(1);
379
+ }
380
+ }
381
+
382
+ async chat() {
383
+ if (!this.isDaemonRunning()) {
384
+ console.error('Daemon is not running. Start with: aiwg daemon start');
385
+ process.exit(1);
386
+ }
387
+
388
+ const message = process.argv.slice(3).join(' ');
389
+ if (!message) {
390
+ console.error('Usage: aiwg daemon chat <message>');
391
+ process.exit(1);
392
+ }
393
+
394
+ try {
395
+ const client = await createClient(SOCKET_PATH);
396
+ const result = await client.request('chat.send', { message });
397
+ client.disconnect();
398
+ console.log(`Task submitted: ${result.taskId}`);
399
+ } catch (error) {
400
+ console.error(`Failed to send message: ${error.message}`);
401
+ process.exit(1);
402
+ }
403
+ }
404
+
405
+ async init() {
406
+ try {
407
+ const { initProfile, listProfiles } = await import('./init-profile.mjs');
408
+ const profileName = process.argv[3] || 'manager';
409
+
410
+ if (profileName === 'list') {
411
+ const profiles = listProfiles();
412
+ console.log('Available profiles:');
413
+ for (const p of profiles) {
414
+ console.log(` ${p}`);
415
+ }
416
+ return;
417
+ }
418
+
419
+ const result = initProfile({
420
+ profile: profileName,
421
+ force: this.flags.force === true,
422
+ });
423
+
424
+ console.log(`Daemon config initialized from "${result.profile}" profile`);
425
+ console.log(` Config: ${result.configPath}`);
426
+ if (result.envPath) {
427
+ console.log(` Env template: ${result.envPath}`);
428
+ }
429
+ console.log('\nNext steps:');
430
+ console.log(' 1. Edit .aiwg/daemon.yaml to configure messaging tokens and rooms');
431
+ console.log(' 2. Copy .env.example to .env and fill in your values');
432
+ console.log(' 3. Run: aiwg daemon start');
433
+ } catch (error) {
434
+ console.error(`Init failed: ${error.message}`);
435
+ process.exit(1);
436
+ }
437
+ }
438
+
439
+ async rooms() {
440
+ if (!this.isDaemonRunning()) {
441
+ console.error('Daemon is not running');
442
+ process.exit(1);
443
+ }
444
+
445
+ try {
446
+ const client = await createClient(SOCKET_PATH);
447
+ const status = await client.request('rooms.list');
448
+ client.disconnect();
449
+
450
+ if (!status || status.totalRooms === 0) {
451
+ console.log('No rooms configured');
452
+ return;
453
+ }
454
+
455
+ console.log(`Rooms: ${status.totalRooms} total, ${status.totalBindings} task binding(s)\n`);
456
+
457
+ for (const [platform, rooms] of Object.entries(status.platforms || {})) {
458
+ console.log(`${platform}:`);
459
+ for (const room of rooms) {
460
+ const defaultTag = room.isDefault ? ' [default]' : '';
461
+ const tasks = room.boundTasks.length > 0 ? ` (tasks: ${room.boundTasks.join(', ')})` : '';
462
+ console.log(` ${room.label} (${room.id}) — ${room.purpose}${defaultTag}${tasks}`);
463
+ }
464
+ }
465
+ } catch (error) {
466
+ console.error(`Failed to list rooms: ${error.message}`);
467
+ process.exit(1);
468
+ }
469
+ }
470
+
471
+ async autonomous() {
472
+ const subcommand = process.argv[3];
473
+
474
+ if (!this.isDaemonRunning()) {
475
+ console.error('Daemon is not running');
476
+ process.exit(1);
477
+ }
478
+
479
+ try {
480
+ const client = await createClient(SOCKET_PATH);
481
+
482
+ switch (subcommand) {
483
+ case 'enable': {
484
+ const result = await client.request('autonomous.enable');
485
+ console.log(`Autonomous mode: ${result.enabled ? 'enabled' : 'disabled'}`);
486
+ break;
487
+ }
488
+ case 'disable': {
489
+ const result = await client.request('autonomous.disable');
490
+ console.log(`Autonomous mode: ${result.enabled ? 'enabled' : 'disabled'}`);
491
+ break;
492
+ }
493
+ case 'status':
494
+ default: {
495
+ const status = await client.request('autonomous.status');
496
+ console.log(`Autonomous mode: ${status.enabled ? 'enabled' : 'disabled'}`);
497
+ if (status.enabled) {
498
+ console.log(` Running: ${status.running}`);
499
+ console.log(` Daily tasks: ${status.dailyTaskCount}/${status.dailyTaskLimit}`);
500
+ console.log(` Daily spend: $${status.dailySpendUsd.toFixed(2)}/$${status.budgetCapUsd.toFixed(2)}`);
501
+ console.log(` Pending proposals: ${status.pendingProposals}`);
502
+ console.log(` Require approval: ${status.requireApproval}`);
503
+ console.log(` Allowed actions: ${status.allowedActions.join(', ')}`);
504
+ }
505
+ break;
506
+ }
507
+ }
508
+
509
+ client.disconnect();
510
+ } catch (error) {
511
+ console.error(`Failed: ${error.message}`);
512
+ process.exit(1);
513
+ }
514
+ }
515
+
516
+ async schedule() {
517
+ if (this.flags['run-once']) {
518
+ const { runManualSchedule } = await import('./scheduled-task-runner.mjs');
519
+ process.exitCode = await runManualSchedule(this.flags);
520
+ return;
521
+ }
522
+ if (!this.isDaemonRunning()) {
523
+ console.error('Daemon is not running');
524
+ process.exit(1);
525
+ }
526
+
527
+ try {
528
+ const client = await createClient(SOCKET_PATH);
529
+ const status = await client.request('schedule.status');
530
+ client.disconnect();
531
+
532
+ console.log(`Scheduler: ${status.started ? 'running' : 'stopped'}`);
533
+ console.log(`Registered actions: ${status.registeredActions.join(', ')}`);
534
+
535
+ if (status.jobHistory.length > 0) {
536
+ console.log('\nJob history:');
537
+ for (const job of status.jobHistory) {
538
+ console.log(` ${job.jobId}: ${job.action} (runs: ${job.runCount}, last: ${job.lastRun})`);
539
+ }
540
+ }
541
+ } catch (error) {
542
+ console.error(`Failed: ${error.message}`);
543
+ process.exit(1);
544
+ }
545
+ }
546
+
547
+ async memory() {
548
+ const subcommand = process.argv[3];
549
+
550
+ switch (subcommand) {
551
+ case 'show': {
552
+ const scope = this.flags.scope;
553
+
554
+ if (this.isDaemonRunning()) {
555
+ // Live: query daemon via IPC
556
+ try {
557
+ const client = await createClient(SOCKET_PATH);
558
+ const result = await client.request('memory.show', scope ? { scope } : {});
559
+ client.disconnect();
560
+ this._printMemoryShow(result);
561
+ return;
562
+ } catch {
563
+ // Fallback to offline read below
564
+ }
565
+ }
566
+
567
+ // Offline: read files directly
568
+ const { MemoryManager } = await import('./memory-manager.mjs');
569
+ const mgr = new MemoryManager();
570
+ this._printMemoryShow(mgr.show(scope));
571
+ break;
572
+ }
573
+
574
+ case 'clear': {
575
+ const scope = this.flags.scope;
576
+ if (!scope) {
577
+ console.error('Usage: aiwg daemon memory clear --scope <session|project|user>');
578
+ process.exit(1);
579
+ }
580
+
581
+ if (this.isDaemonRunning()) {
582
+ try {
583
+ const client = await createClient(SOCKET_PATH);
584
+ const result = await client.request('memory.clear', { scope });
585
+ client.disconnect();
586
+ console.log(`Cleared ${result.cleared} entry/entries from ${scope} scope`);
587
+ return;
588
+ } catch (error) {
589
+ console.error(`IPC failed, attempting offline clear: ${error.message}`);
590
+ }
591
+ }
592
+
593
+ // Offline clear
594
+ const { MemoryManager } = await import('./memory-manager.mjs');
595
+ const mgr = new MemoryManager();
596
+ try {
597
+ const result = mgr.clear(scope);
598
+ console.log(`Cleared ${result.cleared} entry/entries from ${scope} scope`);
599
+ } catch (error) {
600
+ console.error(`Failed to clear memory: ${error.message}`);
601
+ process.exit(1);
602
+ }
603
+ break;
604
+ }
605
+
606
+ default:
607
+ console.log(`
608
+ Usage: aiwg daemon memory <subcommand> [options]
609
+
610
+ Subcommands:
611
+ show Show memory contents (all scopes or filtered by --scope)
612
+ clear Clear memory entries (requires --scope)
613
+
614
+ Options:
615
+ --scope <scope> Memory scope: session | project | user
616
+
617
+ Examples:
618
+ aiwg daemon memory show
619
+ aiwg daemon memory show --scope user
620
+ aiwg daemon memory clear --scope session
621
+ aiwg daemon memory clear --scope project
622
+ `.trim());
623
+ if (subcommand) process.exit(1);
624
+ }
625
+ }
626
+
627
+ _printMemoryShow(result) {
628
+ const scopes = ['session', 'project', 'user'];
629
+ let any = false;
630
+
631
+ for (const scope of scopes) {
632
+ const info = result[scope];
633
+ if (!info) continue;
634
+
635
+ console.log(`\n${scope.toUpperCase()} MEMORY`);
636
+ if (info.path) console.log(` Path: ${info.path}`);
637
+ console.log(` Entries: ${info.count}`);
638
+
639
+ if (info.entries && info.entries.length > 0) {
640
+ for (const e of info.entries) {
641
+ const name = e.name || e.key || '(unnamed)';
642
+ const desc = e.description ? ` — ${e.description}` : '';
643
+ console.log(` • ${name}${desc}`);
644
+ }
645
+ any = true;
646
+ }
647
+ }
648
+
649
+ if (!any) console.log('\n(no memory entries)');
650
+ }
651
+
652
+ async task() {
653
+ const subcommand = process.argv[3];
654
+ const args = process.argv.slice(4);
655
+
656
+ switch (subcommand) {
657
+ case 'submit': {
658
+ if (!this.isDaemonRunning()) {
659
+ console.error('Daemon is not running. Start with: aiwg daemon start');
660
+ process.exit(1);
661
+ }
662
+
663
+ const prompt = args.join(' ');
664
+ if (!prompt) {
665
+ console.error('Usage: aiwg daemon task submit <prompt>');
666
+ process.exit(1);
667
+ }
668
+
669
+ try {
670
+ const client = await createClient(SOCKET_PATH);
671
+ const result = await client.request('task.submit', {
672
+ prompt,
673
+ agent: this.flags.agent,
674
+ priority: this.flags.priority ? parseInt(this.flags.priority, 10) : 0,
675
+ });
676
+ client.disconnect();
677
+ console.log(`Task submitted: ${result.taskId} (${result.state})`);
678
+ } catch (error) {
679
+ console.error(`Failed to submit task: ${error.message}`);
680
+ process.exit(1);
681
+ }
682
+ break;
683
+ }
684
+
685
+ case 'list': {
686
+ if (!this.isDaemonRunning()) {
687
+ console.error('Daemon is not running');
688
+ process.exit(1);
689
+ }
690
+
691
+ try {
692
+ const client = await createClient(SOCKET_PATH);
693
+ const tasks = await client.request('task.list', {
694
+ state: this.flags.state,
695
+ limit: this.flags.limit ? parseInt(this.flags.limit, 10) : 20,
696
+ });
697
+ client.disconnect();
698
+
699
+ if (!tasks || tasks.length === 0) {
700
+ console.log('No tasks found');
701
+ return;
702
+ }
703
+
704
+ console.log(`${'ID'.padEnd(12)} ${'State'.padEnd(12)} ${'Prompt'.padEnd(50)}`);
705
+ console.log('-'.repeat(74));
706
+ for (const task of tasks) {
707
+ const prompt = (task.prompt || '').slice(0, 48);
708
+ console.log(`${(task.id || '').padEnd(12)} ${(task.state || '').padEnd(12)} ${prompt}`);
709
+ }
710
+ } catch (error) {
711
+ console.error(`Failed to list tasks: ${error.message}`);
712
+ process.exit(1);
713
+ }
714
+ break;
715
+ }
716
+
717
+ case 'get': {
718
+ const taskId = args[0];
719
+ if (!taskId) {
720
+ console.error('Usage: aiwg daemon task get <taskId>');
721
+ process.exit(1);
722
+ }
723
+
724
+ if (!this.isDaemonRunning()) {
725
+ console.error('Daemon is not running');
726
+ process.exit(1);
727
+ }
728
+
729
+ try {
730
+ const client = await createClient(SOCKET_PATH);
731
+ const task = await client.request('task.get', { taskId });
732
+ client.disconnect();
733
+ console.log(JSON.stringify(task, null, 2));
734
+ } catch (error) {
735
+ console.error(`Failed to get task: ${error.message}`);
736
+ process.exit(1);
737
+ }
738
+ break;
739
+ }
740
+
741
+ case 'cancel': {
742
+ const taskId = args[0];
743
+ if (!taskId) {
744
+ console.error('Usage: aiwg daemon task cancel <taskId>');
745
+ process.exit(1);
746
+ }
747
+
748
+ if (!this.isDaemonRunning()) {
749
+ console.error('Daemon is not running');
750
+ process.exit(1);
751
+ }
752
+
753
+ try {
754
+ const client = await createClient(SOCKET_PATH);
755
+ const result = await client.request('task.cancel', { taskId });
756
+ client.disconnect();
757
+ console.log(result.cancelled ? `Task ${taskId} cancelled` : `Task ${taskId} not found or already completed`);
758
+ } catch (error) {
759
+ console.error(`Failed to cancel task: ${error.message}`);
760
+ process.exit(1);
761
+ }
762
+ break;
763
+ }
764
+
765
+ case 'stats': {
766
+ if (!this.isDaemonRunning()) {
767
+ console.error('Daemon is not running');
768
+ process.exit(1);
769
+ }
770
+
771
+ try {
772
+ const client = await createClient(SOCKET_PATH);
773
+ const stats = await client.request('task.stats');
774
+ client.disconnect();
775
+ console.log(JSON.stringify(stats, null, 2));
776
+ } catch (error) {
777
+ console.error(`Failed to get stats: ${error.message}`);
778
+ process.exit(1);
779
+ }
780
+ break;
781
+ }
782
+
783
+ default:
784
+ console.log(`
785
+ Usage: aiwg daemon task <subcommand> [options]
786
+
787
+ Subcommands:
788
+ submit <prompt> Submit a new agent task
789
+ list List tasks
790
+ get <taskId> Get task details
791
+ cancel <taskId> Cancel a task
792
+ stats Show task statistics
793
+
794
+ Options:
795
+ --agent <name> Agent type for task submission
796
+ --priority <n> Task priority (0=default, higher=sooner)
797
+ --state <state> Filter tasks by state (queued, running, completed, failed)
798
+ --limit <n> Max tasks to list (default: 20)
799
+ `.trim());
800
+ if (subcommand) process.exit(1);
801
+ }
802
+ }
803
+
804
+ async pty() {
805
+ const subcommand = process.argv[3];
806
+ const args = process.argv.slice(4);
807
+
808
+ switch (subcommand) {
809
+ case 'start': {
810
+ const platform = args[0];
811
+ if (!platform) {
812
+ console.error('Usage: aiwg daemon pty start <platform> [-- <args...>]');
813
+ console.error('Platforms: claude-code, opencode, codex, warp, openclaw');
814
+ process.exit(1);
815
+ }
816
+
817
+ const dashDash = args.indexOf('--');
818
+ const extraArgs = dashDash >= 0 ? args.slice(dashDash + 1) : [];
819
+ const cols = this.flags.cols ? parseInt(this.flags.cols, 10) : 80;
820
+ const rows = this.flags.rows ? parseInt(this.flags.rows, 10) : 24;
821
+ const useTmux = !!this.flags.tmux;
822
+
823
+ // --tmux path: spawn inside a named tmux session for reconnect support
824
+ if (useTmux) {
825
+ try {
826
+ const { boundedExecFileSync } = await importImpl(import.meta.url, 'process/bounded-child-process.mjs');
827
+ const { randomBytes } = await import('crypto');
828
+ const { PTYAdapter } = await import('./pty-adapter.mjs');
829
+
830
+ const sessionId = randomBytes(6).toString('hex');
831
+ const tmuxName = `aiwg-pty-${sessionId}`;
832
+
833
+ // Resolve platform binary
834
+ const PLATFORM_BINS = {
835
+ 'claude-code': 'claude', opencode: 'opencode', codex: 'codex',
836
+ warp: 'warp-terminal', openclaw: 'openclaw',
837
+ };
838
+ const bin = PLATFORM_BINS[platform] || platform;
839
+
840
+ // Supply multiple command arguments so tmux directly executes the binary
841
+ // even when no extra platform arguments were supplied.
842
+ // tmux parses trailing semicolons as command separators even in argv.
843
+ const tmuxArgs = ['new-session', '-d', '-s', tmuxName, '-x', String(cols), '-y', String(rows), '--', 'env', '--', bin, ...extraArgs]
844
+ .map(arg => arg.replace(/;$/, '\\;'));
845
+ boundedExecFileSync('tmux', tmuxArgs, 'quick');
846
+
847
+ // Get the PID of the shell/process running inside the tmux pane
848
+ let pid = null;
849
+ try {
850
+ pid = parseInt(
851
+ boundedExecFileSync('tmux', ['list-panes', '-t', tmuxName, '-F', '#{pane_pid}'], 'quick').toString().trim(),
852
+ 10,
853
+ );
854
+ } catch { /* leave null if tmux version doesn't support format strings */ }
855
+
856
+ // Write session file (compatible with PTYAdapter.getSession)
857
+ PTYAdapter._ensureSessionDir();
858
+ const sessionFile = path.join('.aiwg/daemon/pty', `${sessionId}.json`);
859
+ fs.writeFileSync(
860
+ sessionFile,
861
+ JSON.stringify({
862
+ sessionId, platform, bin,
863
+ pid, cols, rows,
864
+ tmuxSession: tmuxName,
865
+ cwd: process.cwd(),
866
+ started_at: new Date().toISOString(),
867
+ }, null, 2),
868
+ );
869
+
870
+ console.log(`PTY session started in tmux: ${sessionId}`);
871
+ console.log(` Platform: ${platform}`);
872
+ console.log(` tmux session: ${tmuxName}`);
873
+ console.log(` Reattach: aiwg daemon pty attach ${sessionId}`);
874
+ console.log(` Or directly: tmux attach-session -t ${tmuxName}`);
875
+ } catch (error) {
876
+ console.error(`Failed to start tmux PTY session: ${error.message}`);
877
+ console.error('Ensure tmux is installed: apt install tmux / brew install tmux');
878
+ process.exit(1);
879
+ }
880
+ break;
881
+ }
882
+
883
+ try {
884
+ const { PTYAdapter } = await import('./pty-adapter.mjs');
885
+ const adapter = new PTYAdapter({ platform, args: extraArgs, cols, rows });
886
+
887
+ adapter.on('data', (chunk) => process.stdout.write(chunk));
888
+ adapter.on('exit', ({ exitCode }) => {
889
+ console.error(`\nPTY session exited (code: ${exitCode})`);
890
+ process.exit(exitCode ?? 0);
891
+ });
892
+
893
+ const sessionId = await adapter.start();
894
+ console.error(`PTY session started: ${sessionId} (platform: ${platform}, PID: ${adapter.getPid()})`);
895
+ console.error('Input is forwarded to the PTY. Press Ctrl+C to stop.');
896
+
897
+ // Forward stdin to the PTY
898
+ if (process.stdin.isTTY) process.stdin.setRawMode(true);
899
+ process.stdin.resume();
900
+ process.stdin.on('data', (chunk) => {
901
+ // Ctrl+C sends SIGINT to the adapter, not to our process
902
+ if (chunk[0] === 0x03) {
903
+ adapter.stop().then(() => process.exit(0));
904
+ return;
905
+ }
906
+ try { adapter.write(chunk.toString()); } catch { /* session gone */ }
907
+ });
908
+
909
+ // Forward terminal resize events
910
+ process.stdout.on('resize', () => {
911
+ adapter.resize(process.stdout.columns, process.stdout.rows);
912
+ });
913
+ } catch (error) {
914
+ console.error(`Failed to start PTY session: ${error.message}`);
915
+ process.exit(1);
916
+ }
917
+ break;
918
+ }
919
+
920
+ case 'list': {
921
+ try {
922
+ const { PTYAdapter } = await import('./pty-adapter.mjs');
923
+ const sessions = PTYAdapter.list();
924
+
925
+ if (sessions.length === 0) {
926
+ console.log('No active PTY sessions');
927
+ return;
928
+ }
929
+
930
+ console.log(`Active PTY sessions (${sessions.length}):`);
931
+ console.log('');
932
+ for (const s of sessions) {
933
+ console.log(` ${s.sessionId} platform=${s.platform} pid=${s.pid} ${s.cols}x${s.rows} started=${s.started_at}`);
934
+ }
935
+ } catch (error) {
936
+ console.error(`Failed to list PTY sessions: ${error.message}`);
937
+ process.exit(1);
938
+ }
939
+ break;
940
+ }
941
+
942
+ case 'stop': {
943
+ const sessionId = args[0];
944
+ if (!sessionId) {
945
+ console.error('Usage: aiwg daemon pty stop <session-id>');
946
+ process.exit(1);
947
+ }
948
+
949
+ try {
950
+ const { PTYAdapter } = await import('./pty-adapter.mjs');
951
+ const session = PTYAdapter.getSession(sessionId);
952
+ if (!session) {
953
+ console.error(`Session not found or already stopped: ${sessionId}`);
954
+ process.exit(1);
955
+ }
956
+
957
+ try { process.kill(session.pid, 'SIGTERM'); } catch { /* already gone */ }
958
+ // Also stop tmux session if one was created
959
+ if (session.tmuxSession) {
960
+ try {
961
+ const { boundedExecFileSync } = await importImpl(import.meta.url, 'process/bounded-child-process.mjs');
962
+ boundedExecFileSync('tmux', ['kill-session', '-t', session.tmuxSession], 'quick', { stdio: 'ignore' });
963
+ } catch { /* tmux session may already be gone */ }
964
+ }
965
+ PTYAdapter._removeSession(sessionId);
966
+ console.log(`PTY session ${sessionId} stopped`);
967
+ } catch (error) {
968
+ console.error(`Failed to stop PTY session: ${error.message}`);
969
+ process.exit(1);
970
+ }
971
+ break;
972
+ }
973
+
974
+ case 'attach': {
975
+ const sessionId = args[0];
976
+ if (!sessionId) {
977
+ console.error('Usage: aiwg daemon pty attach <session-id>');
978
+ process.exit(1);
979
+ }
980
+
981
+ try {
982
+ const { PTYAdapter } = await import('./pty-adapter.mjs');
983
+ const session = PTYAdapter.getSession(sessionId);
984
+ if (!session) {
985
+ console.error(`Session not found or expired: ${sessionId}`);
986
+ console.error('List active sessions with: aiwg daemon pty list');
987
+ process.exit(1);
988
+ }
989
+
990
+ if (session.tmuxSession) {
991
+ // Attach via named tmux session
992
+ const proc = spawn('tmux', ['attach-session', '-t', session.tmuxSession], {
993
+ stdio: 'inherit',
994
+ });
995
+ proc.on('close', (code) => process.exit(code ?? 0));
996
+ proc.on('error', (err) => {
997
+ console.error(`Failed to attach to tmux session: ${err.message}`);
998
+ console.error(`Attach manually: tmux attach-session -t ${session.tmuxSession}`);
999
+ process.exit(1);
1000
+ });
1001
+ } else {
1002
+ // No tmux session — show info and suggest --tmux for future sessions
1003
+ console.log(`Session info:`);
1004
+ console.log(` ID: ${session.sessionId}`);
1005
+ console.log(` Platform: ${session.platform}`);
1006
+ console.log(` PID: ${session.pid}`);
1007
+ console.log(` Started: ${session.started_at}`);
1008
+ console.log('');
1009
+ console.log('This session was started without --tmux and cannot be reattached.');
1010
+ console.log(`To start a reconnectable session: aiwg daemon pty start ${session.platform} --tmux`);
1011
+ }
1012
+ } catch (error) {
1013
+ console.error(`Failed to attach: ${error.message}`);
1014
+ process.exit(1);
1015
+ }
1016
+ break;
1017
+ }
1018
+
1019
+ default:
1020
+ console.log(`
1021
+ Usage: aiwg daemon pty <subcommand> [options]
1022
+
1023
+ Subcommands:
1024
+ start <platform> Spawn a platform TUI under a PTY and bridge I/O
1025
+ attach <session-id> Reattach to a running PTY session (requires --tmux)
1026
+ list List active PTY sessions
1027
+ stop <session-id> Stop a PTY session
1028
+
1029
+ Platforms (Tier 1 — native daemon; Tier 2 — PTY adapter):
1030
+ claude-code Claude Code CLI (Tier 1 + PTY adapter)
1031
+ opencode OpenCode CLI (Tier 1)
1032
+ codex OpenAI Codex CLI (Tier 1 + PTY adapter)
1033
+ warp Warp Terminal (Tier 1)
1034
+ openclaw OpenClaw CLI (Tier 1)
1035
+
1036
+ Options:
1037
+ --cols <n> Terminal width (default: 80)
1038
+ --rows <n> Terminal height (default: 24)
1039
+ --tmux Start inside a named tmux session (enables reattach via 'pty attach')
1040
+
1041
+ Examples:
1042
+ aiwg daemon pty start opencode
1043
+ aiwg daemon pty start opencode --tmux # Start in tmux for reattach support
1044
+ aiwg daemon pty attach abc123 # Reattach to a --tmux session
1045
+ aiwg daemon pty start codex --cols 120 --rows 40
1046
+ aiwg daemon pty start claude-code -- --dangerously-skip-permissions
1047
+ aiwg daemon pty list
1048
+ aiwg daemon pty stop abc123
1049
+
1050
+ Requirements:
1051
+ PTY adapter (non-tmux) requires node-pty: npm install node-pty
1052
+ node-pty needs native compilation (node-gyp + C++ build tools).
1053
+ tmux mode requires tmux to be installed.
1054
+ `.trim());
1055
+ if (subcommand) process.exit(1);
1056
+ }
1057
+ }
1058
+
1059
+ isDaemonRunning() {
1060
+ if (!fs.existsSync(PID_FILE)) {
1061
+ return false;
1062
+ }
1063
+
1064
+ const pid = this.readPidFile();
1065
+ return this.isPidAlive(pid);
1066
+ }
1067
+
1068
+ isPidAlive(pid) {
1069
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
1070
+ try {
1071
+ process.kill(pid, 0);
1072
+ return true;
1073
+ } catch (error) {
1074
+ return false;
1075
+ }
1076
+ }
1077
+
1078
+ readPidFile() {
1079
+ try {
1080
+ return parseInt(fs.readFileSync(PID_FILE, 'utf8').trim(), 10);
1081
+ } catch (error) {
1082
+ return null;
1083
+ }
1084
+ }
1085
+
1086
+ ensureDirectories() {
1087
+ const dirs = [
1088
+ '.aiwg',
1089
+ '.aiwg/daemon',
1090
+ '.aiwg/daemon/actions',
1091
+ '.aiwg/daemon/events'
1092
+ ];
1093
+
1094
+ for (const dir of dirs) {
1095
+ if (!fs.existsSync(dir)) {
1096
+ fs.mkdirSync(dir, { recursive: true });
1097
+ }
1098
+ }
1099
+ }
1100
+
1101
+ cleanup() {
1102
+ try {
1103
+ if (fs.existsSync(PID_FILE)) {
1104
+ fs.unlinkSync(PID_FILE);
1105
+ }
1106
+ } catch (error) {
1107
+ // Ignore cleanup errors
1108
+ }
1109
+ }
1110
+
1111
+ usage() {
1112
+ console.log(`
1113
+ Usage: aiwg daemon <command> [options]
1114
+
1115
+ Commands:
1116
+ init [profile] Initialize daemon config from profile (default: manager)
1117
+ start Start the daemon
1118
+ stop Stop the daemon
1119
+ status Show daemon status (live via IPC when available)
1120
+ logs Show daemon logs
1121
+ restart Restart the daemon
1122
+ attach Open tmux session with chat REPL and status pane
1123
+ pty <sub> PTY adapter — spawn a platform TUI over a chat bridge
1124
+ chat <message> Send a message to the daemon agent
1125
+ task <sub> Manage agent tasks (submit, list, get, cancel, stats)
1126
+ rooms List connected messaging rooms
1127
+ autonomous <sub> Manage autonomous mode (status, enable, disable)
1128
+ schedule Show scheduled task status and history (--run-once --job ID runs without daemon)
1129
+ memory <sub> Manage cross-session memory (show, clear)
1130
+
1131
+ Options:
1132
+ --foreground Run in foreground (for Docker/systemd)
1133
+ --docker Start daemon in Docker container
1134
+ --force Overwrite existing config (for init)
1135
+ --lines N Show last N lines of logs (default: 50)
1136
+ --follow, -f Follow log output in real-time
1137
+ --readonly Attach to tmux in read-only mode
1138
+ --run-once Run one deterministic schedule job without starting the daemon
1139
+ --job ID Configured schedule job ID (with schedule --run-once)
1140
+ --config PATH Daemon config path for manual execution
1141
+ --store-path PATH Task/receipt store for manual execution
1142
+ --fire-time ISO Stable scheduled minute for deduplication
1143
+ --json Print a single manual receipt object
1144
+ --resolve TEXT Acknowledge inspected interrupted owner effects; does not replay
1145
+
1146
+ Scheduled updates check only; installation remains opt-in via aiwg update.
1147
+ Manual execution is supported on Linux/macOS; Windows: use WSL2.
1148
+
1149
+ Examples:
1150
+ aiwg daemon init # Initialize with manager profile
1151
+ aiwg daemon init list # List available profiles
1152
+ aiwg daemon start
1153
+ aiwg daemon start --docker # Start in Docker container
1154
+ aiwg daemon start --foreground
1155
+ aiwg daemon stop
1156
+ aiwg daemon status
1157
+ aiwg daemon rooms # List messaging rooms
1158
+ aiwg daemon autonomous status # Check autonomous mode
1159
+ aiwg daemon autonomous enable # Enable self-directed thinking
1160
+ aiwg daemon schedule # Show scheduled tasks
1161
+ aiwg daemon attach
1162
+ aiwg daemon pty start opencode # Start OpenCode under PTY bridge
1163
+ aiwg daemon pty start codex --cols 120 # Start Codex with wide terminal
1164
+ aiwg daemon pty list # List active PTY sessions
1165
+ aiwg daemon pty stop abc123 # Stop a specific PTY session
1166
+ aiwg daemon chat "Review the latest PR"
1167
+ aiwg daemon task submit "Run security audit"
1168
+ aiwg daemon task list
1169
+ aiwg daemon logs --follow
1170
+ aiwg daemon restart
1171
+ aiwg daemon memory show
1172
+ aiwg daemon memory clear --scope session
1173
+ `.trim());
1174
+ }
1175
+ }
1176
+
1177
+ const cli = new DaemonCLI();
1178
+ cli.run().catch(error => {
1179
+ console.error(`Error: ${error.message}`);
1180
+ process.exit(1);
1181
+ });