@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,420 @@
1
+ /**
2
+ * PTY Adapter
3
+ *
4
+ * Spawns a target platform's TUI under a pseudo-terminal (PTY) and bridges
5
+ * I/O bidirectionally through the AIWG chat channel — enabling remote operation
6
+ * with near-native messaging richness from human, scripted, or agentic drivers.
7
+ *
8
+ * The adapter can be driven by:
9
+ * - A human typing replies in a chat channel
10
+ * - A shell script sending input programmatically
11
+ * - An agentic LLM routing messages through the daemon IPC socket
12
+ *
13
+ * Requires: node-pty (optional dependency)
14
+ * Install: npm install node-pty
15
+ * Note: node-pty requires native compilation (node-gyp + build tools)
16
+ *
17
+ * Usage:
18
+ * const adapter = new PTYAdapter({ platform: 'opencode' });
19
+ * await adapter.start();
20
+ * adapter.on('data', (chunk) => process.stdout.write(chunk));
21
+ * adapter.write('some input\n');
22
+ * adapter.resize(120, 30);
23
+ * await adapter.stop();
24
+ *
25
+ * // List live sessions
26
+ * const sessions = PTYAdapter.list();
27
+ *
28
+ * @issue #656
29
+ */
30
+
31
+ import fs from 'fs';
32
+ import path from 'path';
33
+ import { EventEmitter } from 'events';
34
+ import { createHash, randomBytes } from 'crypto';
35
+ import { SandboxTransport } from './sandbox-transport.mjs';
36
+ import { importImpl } from '../_resolve-impl.mjs';
37
+
38
+ const SESSION_DIR = '.aiwg/daemon/pty';
39
+
40
+ /**
41
+ * Map of AIWG provider keys to their CLI binary names.
42
+ * Used to spawn the correct TUI process.
43
+ */
44
+ const PLATFORM_BINS = {
45
+ 'claude-code': 'claude',
46
+ 'opencode': 'opencode',
47
+ 'codex': 'codex',
48
+ 'warp': 'warp-terminal',
49
+ 'openclaw': 'openclaw',
50
+ };
51
+
52
+ /**
53
+ * PTY Adapter — wraps a platform TUI process in a pseudo-terminal
54
+ * and exposes bidirectional I/O for chat-channel bridging.
55
+ *
56
+ * Events:
57
+ * 'data' (chunk: string) — screen output from the PTY process
58
+ * 'exit' ({ exitCode, signal }) — PTY process has exited
59
+ * 'error' (err: Error) — unrecoverable error
60
+ */
61
+ export class PTYAdapter extends EventEmitter {
62
+ /**
63
+ * @param {object} opts
64
+ * @param {string} opts.platform - AIWG provider key (e.g. 'opencode', 'claude-code')
65
+ * @param {string[]} [opts.args] - Extra arguments passed to the TUI binary
66
+ * @param {string} [opts.sessionId] - Resume an existing session by ID
67
+ * @param {number} [opts.cols] - Initial terminal width (default: 80)
68
+ * @param {number} [opts.rows] - Initial terminal height (default: 24)
69
+ * @param {string} [opts.cwd] - Working directory (default: process.cwd())
70
+ */
71
+ constructor({
72
+ platform,
73
+ args = [],
74
+ sessionId = null,
75
+ cols = 80,
76
+ rows = 24,
77
+ cwd = process.cwd(),
78
+ } = {}) {
79
+ super();
80
+ this.platform = platform;
81
+ this.bin = PLATFORM_BINS[platform] || platform;
82
+ this.args = args;
83
+ this.sessionId = sessionId || PTYAdapter._generateSessionId();
84
+ this.cols = cols;
85
+ this.rows = rows;
86
+ this.cwd = cwd;
87
+ this._pty = null;
88
+ this._stopped = false;
89
+ this._startedAt = null;
90
+ }
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // Lifecycle
94
+ // ---------------------------------------------------------------------------
95
+
96
+ /**
97
+ * Start the PTY session.
98
+ * Spawns the platform TUI process under a pseudo-terminal.
99
+ *
100
+ * @returns {Promise<string>} Resolves with the session ID once the process is live.
101
+ * @throws {Error} If node-pty is not installed or the binary is not found.
102
+ */
103
+ async start() {
104
+ let nodePty;
105
+ try {
106
+ const { loadFeaturePackage } = await importImpl(import.meta.url, 'features/runtime.js');
107
+ const loaded = await loadFeaturePackage('node-pty');
108
+ nodePty = loaded.default ?? loaded;
109
+ } catch {
110
+ throw new Error(
111
+ 'node-pty is required for PTY adapter support.\n' +
112
+ 'Install it with scoped approval: aiwg features install pty\n' +
113
+ 'node-pty requires native compilation — you need node-gyp and C++ build tools.\n' +
114
+ 'See: https://github.com/microsoft/node-pty#installation'
115
+ );
116
+ }
117
+
118
+ PTYAdapter._ensureSessionDir();
119
+ this._startedAt = new Date().toISOString();
120
+
121
+ this._pty = nodePty.spawn(this.bin, this.args, {
122
+ name: 'xterm-256color',
123
+ cols: this.cols,
124
+ rows: this.rows,
125
+ cwd: this.cwd,
126
+ env: process.env,
127
+ });
128
+
129
+ this._pty.onData((data) => {
130
+ this.emit('data', data);
131
+ });
132
+
133
+ this._pty.onExit(({ exitCode, signal }) => {
134
+ this._stopped = true;
135
+ PTYAdapter._removeSession(this.sessionId);
136
+ this.emit('exit', { exitCode, signal });
137
+ });
138
+
139
+ this._writeSession();
140
+ return this.sessionId;
141
+ }
142
+
143
+ /**
144
+ * Send input to the PTY process (keystrokes, commands, etc.).
145
+ * @param {string} data
146
+ */
147
+ write(data) {
148
+ if (!this._pty || this._stopped) {
149
+ throw new Error(`PTY session ${this.sessionId} is not active`);
150
+ }
151
+ this._pty.write(data);
152
+ }
153
+
154
+ /**
155
+ * Resize the PTY window.
156
+ * @param {number} cols
157
+ * @param {number} rows
158
+ */
159
+ resize(cols, rows) {
160
+ if (!this._pty || this._stopped) return;
161
+ this.cols = cols;
162
+ this.rows = rows;
163
+ this._pty.resize(cols, rows);
164
+ this._writeSession();
165
+ }
166
+
167
+ /**
168
+ * Stop the PTY session gracefully (SIGTERM → SIGKILL after 5 s).
169
+ * @returns {Promise<void>}
170
+ */
171
+ stop() {
172
+ if (!this._pty || this._stopped) return Promise.resolve();
173
+ this._stopped = true;
174
+
175
+ return new Promise((resolve) => {
176
+ const timeout = setTimeout(() => {
177
+ try { this._pty.kill('SIGKILL'); } catch { /* already gone */ }
178
+ resolve();
179
+ }, 5000);
180
+
181
+ this.once('exit', () => {
182
+ clearTimeout(timeout);
183
+ resolve();
184
+ });
185
+
186
+ try {
187
+ this._pty.kill('SIGTERM');
188
+ } catch {
189
+ clearTimeout(timeout);
190
+ resolve();
191
+ }
192
+ });
193
+ }
194
+
195
+ /** @returns {string} The session ID for reconnecting later */
196
+ getSessionId() { return this.sessionId; }
197
+
198
+ /** @returns {number|undefined} The PID of the spawned TUI process */
199
+ getPid() { return this._pty?.pid; }
200
+
201
+ /** @returns {boolean} True if the session is active */
202
+ isActive() { return !this._stopped && this._pty !== null; }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // Session persistence
206
+ // ---------------------------------------------------------------------------
207
+
208
+ _writeSession() {
209
+ const record = {
210
+ sessionId: this.sessionId,
211
+ platform: this.platform,
212
+ bin: this.bin,
213
+ pid: this._pty?.pid ?? null,
214
+ cols: this.cols,
215
+ rows: this.rows,
216
+ cwd: this.cwd,
217
+ started_at: this._startedAt,
218
+ };
219
+ const tmp = path.join(SESSION_DIR, `${this.sessionId}.json.tmp`);
220
+ const dst = path.join(SESSION_DIR, `${this.sessionId}.json`);
221
+ fs.writeFileSync(tmp, JSON.stringify(record, null, 2));
222
+ fs.renameSync(tmp, dst);
223
+ }
224
+
225
+ // ---------------------------------------------------------------------------
226
+ // Static helpers
227
+ // ---------------------------------------------------------------------------
228
+
229
+ /**
230
+ * List all active PTY sessions by reading the session directory and
231
+ * verifying each recorded PID is still alive.
232
+ * Stale session files (dead PID) are removed automatically.
233
+ *
234
+ * @returns {Array<{sessionId, platform, bin, pid, cols, rows, cwd, started_at}>}
235
+ */
236
+ static list() {
237
+ if (!fs.existsSync(SESSION_DIR)) return [];
238
+
239
+ return fs.readdirSync(SESSION_DIR)
240
+ .filter((f) => f.endsWith('.json'))
241
+ .map((f) => {
242
+ try {
243
+ return JSON.parse(fs.readFileSync(path.join(SESSION_DIR, f), 'utf8'));
244
+ } catch {
245
+ return null;
246
+ }
247
+ })
248
+ .filter(Boolean)
249
+ .filter((s) => {
250
+ if (!Number.isSafeInteger(s.pid) || s.pid <= 0) return false;
251
+ try {
252
+ process.kill(s.pid, 0); // signal 0 = existence check
253
+ return true;
254
+ } catch {
255
+ // Stale — clean up
256
+ PTYAdapter._removeSession(s.sessionId);
257
+ return false;
258
+ }
259
+ });
260
+ }
261
+
262
+ /**
263
+ * Return the session record for a given ID, or null if not found / stale.
264
+ * @param {string} sessionId
265
+ * @returns {object|null}
266
+ */
267
+ static getSession(sessionId) {
268
+ const p = path.join(SESSION_DIR, `${sessionId}.json`);
269
+ if (!fs.existsSync(p)) return null;
270
+ try {
271
+ const s = JSON.parse(fs.readFileSync(p, 'utf8'));
272
+ if (!Number.isSafeInteger(s.pid) || s.pid <= 0) return null;
273
+ process.kill(s.pid, 0);
274
+ return s;
275
+ } catch {
276
+ PTYAdapter._removeSession(sessionId);
277
+ return null;
278
+ }
279
+ }
280
+
281
+ static _generateSessionId() {
282
+ return randomBytes(6).toString('hex');
283
+ }
284
+
285
+ static _ensureSessionDir() {
286
+ if (!fs.existsSync(SESSION_DIR)) {
287
+ fs.mkdirSync(SESSION_DIR, { recursive: true });
288
+ }
289
+ }
290
+
291
+ static _removeSession(sessionId) {
292
+ try {
293
+ const p = path.join(SESSION_DIR, `${sessionId}.json`);
294
+ if (fs.existsSync(p)) fs.unlinkSync(p);
295
+ } catch { /* ignore */ }
296
+ }
297
+
298
+ // ---------------------------------------------------------------------------
299
+ // Sandbox transport factory (#657)
300
+ // ---------------------------------------------------------------------------
301
+
302
+ /**
303
+ * Create a PTYAdapter backed by a remote agentic-sandbox instance.
304
+ * Connects via the management server's HTTP API instead of spawning locally.
305
+ *
306
+ * Auto-selects this mode when AIWG_SANDBOX_ENDPOINT is set:
307
+ * AIWG_SANDBOX_ENDPOINT=http://localhost:8122 aiwg daemon pty start
308
+ *
309
+ * @param {object} opts
310
+ * @param {string} opts.httpEndpoint - Sandbox management HTTP endpoint
311
+ * @param {string} opts.agentId - Target agent ID on the sandbox
312
+ * @param {string} opts.platform - AIWG provider key
313
+ * @param {string[]} [opts.args] - Extra arguments
314
+ * @param {number} [opts.cols] - Terminal width (default: 120)
315
+ * @param {number} [opts.rows] - Terminal height (default: 30)
316
+ * @param {string} [opts.cwd] - Working directory on remote agent
317
+ * @returns {PTYAdapter} Adapter instance using sandbox transport
318
+ */
319
+ static fromSandbox({
320
+ httpEndpoint,
321
+ agentId,
322
+ platform,
323
+ args = [],
324
+ cols = 120,
325
+ rows = 30,
326
+ cwd = '/home/agent',
327
+ }) {
328
+ const adapter = new PTYAdapter({ platform, args, cols, rows, cwd });
329
+ const bin = PLATFORM_BINS[platform] || platform;
330
+
331
+ // Replace local start() with sandbox transport
332
+ const transport = new SandboxTransport({
333
+ httpEndpoint,
334
+ agentId,
335
+ command: bin,
336
+ args,
337
+ cols,
338
+ rows,
339
+ cwd,
340
+ });
341
+
342
+ // Wire transport events through the adapter
343
+ transport.on('data', (chunk) => adapter.emit('data', chunk));
344
+ transport.on('exit', (info) => {
345
+ adapter._stopped = true;
346
+ PTYAdapter._removeSession(adapter.sessionId);
347
+ adapter.emit('exit', info);
348
+ });
349
+ transport.on('error', (err) => adapter.emit('error', err));
350
+
351
+ // Override lifecycle methods to use transport
352
+ adapter._transport = transport;
353
+ adapter.start = async function () {
354
+ PTYAdapter._ensureSessionDir();
355
+ adapter._startedAt = new Date().toISOString();
356
+ const cmdId = await transport.start();
357
+ adapter.commandId = cmdId;
358
+ adapter._writeSessionSandbox(httpEndpoint, agentId);
359
+ return adapter.sessionId;
360
+ };
361
+ adapter.write = (data) => transport.write(data);
362
+ adapter.resize = (c, r) => {
363
+ adapter.cols = c;
364
+ adapter.rows = r;
365
+ transport.resize(c, r);
366
+ };
367
+ adapter.stop = () => transport.stop();
368
+ adapter.isActive = () => transport.isActive();
369
+
370
+ return adapter;
371
+ }
372
+
373
+ /**
374
+ * Write a sandbox-backed session record (includes endpoint + agentId).
375
+ * @param {string} httpEndpoint
376
+ * @param {string} agentId
377
+ */
378
+ _writeSessionSandbox(httpEndpoint, agentId) {
379
+ const record = {
380
+ sessionId: this.sessionId,
381
+ platform: this.platform,
382
+ bin: this.bin,
383
+ pid: null,
384
+ cols: this.cols,
385
+ rows: this.rows,
386
+ cwd: this.cwd,
387
+ started_at: this._startedAt,
388
+ transport: 'sandbox',
389
+ httpEndpoint,
390
+ agentId,
391
+ commandId: this.commandId || null,
392
+ };
393
+ PTYAdapter._ensureSessionDir();
394
+ const tmp = path.join(SESSION_DIR, `${this.sessionId}.json.tmp`);
395
+ const dst = path.join(SESSION_DIR, `${this.sessionId}.json`);
396
+ fs.writeFileSync(tmp, JSON.stringify(record, null, 2));
397
+ fs.renameSync(tmp, dst);
398
+ }
399
+
400
+ /**
401
+ * Resolve the transport mode based on environment and config.
402
+ *
403
+ * @param {object} opts - Same as PTYAdapter constructor
404
+ * @returns {PTYAdapter} Local or sandbox-backed adapter
405
+ */
406
+ static auto(opts) {
407
+ const endpoint = process.env.AIWG_SANDBOX_ENDPOINT;
408
+ const agentId = process.env.AIWG_SANDBOX_AGENT_ID || 'agent-01';
409
+
410
+ if (endpoint) {
411
+ return PTYAdapter.fromSandbox({
412
+ httpEndpoint: endpoint,
413
+ agentId,
414
+ ...opts,
415
+ });
416
+ }
417
+
418
+ return new PTYAdapter(opts);
419
+ }
420
+ }