@commonlyai/cli 0.1.402 → 0.1.404

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.402",
3
+ "version": "0.1.404",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -0,0 +1,315 @@
1
+ /**
2
+ * A minimal Agent Client Protocol (ACP) client: JSON-RPC 2.0 over a child's
3
+ * stdio, with no dependencies. The `acp` adapter builds its turns on it.
4
+ *
5
+ * Wire format, verified 2026-11-26 against:
6
+ * https://agentclientprotocol.com/protocol/transports
7
+ * stdio: each message is one JSON-RPC request, notification or response,
8
+ * delimited by "\n", and MUST NOT contain embedded newlines; the agent MUST
9
+ * NOT write anything else to stdout (logs go to stderr). UTF-8.
10
+ * https://agentclientprotocol.com/protocol/initialization
11
+ * `initialize` params { protocolVersion, clientCapabilities: { fs:
12
+ * { readTextFile, writeTextFile }, terminal, auth: { terminal } },
13
+ * clientInfo }; protocolVersion is a single integer MAJOR version, 1 today.
14
+ * https://agentclientprotocol.com/protocol/overview and
15
+ * https://agentclientprotocol.com/protocol/prompt-turn
16
+ * method names: agent side initialize, authenticate, session/new,
17
+ * session/load, session/prompt, session/set_mode, notification
18
+ * session/cancel; client side session/request_permission, the
19
+ * session/update notification, fs/*, terminal/*.
20
+ * https://agentclientprotocol.com/protocol/v1/error
21
+ * codes in ACP_ERROR below; an unknown inbound method gets -32601, and a
22
+ * notification never gets a response.
23
+ * https://raw.githubusercontent.com/agentclientprotocol/agent-client-protocol/main/schema/v1/schema.json
24
+ * and schema/v1/meta.json beside it: ProtocolVersion is an integer (uint16),
25
+ * meta.json "version": 1; RequestId is a string, number or null.
26
+ *
27
+ * Nothing here logs params or results: they can carry prompts, file contents
28
+ * and credentials. Logs name known methods, numeric ids and sizes only; any
29
+ * other text the agent chose is logged by type and size.
30
+ */
31
+
32
+ export const ACP_PROTOCOL_VERSION = 1;
33
+
34
+ export const ACP_ERROR = Object.freeze({
35
+ PARSE_ERROR: -32700,
36
+ INVALID_REQUEST: -32600,
37
+ METHOD_NOT_FOUND: -32601,
38
+ INVALID_PARAMS: -32602,
39
+ INTERNAL_ERROR: -32603,
40
+ REQUEST_CANCELLED: -32800,
41
+ AUTH_REQUIRED: -32000,
42
+ RESOURCE_NOT_FOUND: -32002,
43
+ });
44
+
45
+ // A file read or a long transcript can be large; a runaway stdout cannot be
46
+ // allowed to grow the buffer without bound.
47
+ export const DEFAULT_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
48
+ const NEWLINE = 0x0a;
49
+
50
+ const localError = (code, message) => Object.assign(new Error(message), { code });
51
+ const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
52
+ const isId = (id) => typeof id === 'string' || (typeof id === 'number' && Number.isFinite(id));
53
+ // An inbound request may also carry a null id (ACP's RequestId allows it);
54
+ // the reply echoes it.
55
+ const isRequestId = (id) => id === null || isId(id);
56
+ // The methods ACP defines. Only these are logged by name: an unknown method,
57
+ // like a string id, is text the agent chose, and a log is no place for it.
58
+ const KNOWN_METHODS = new Set([
59
+ 'initialize', 'authenticate', 'session/new', 'session/load', 'session/prompt',
60
+ 'session/cancel', 'session/set_mode', 'session/update', 'session/request_permission',
61
+ 'fs/read_text_file', 'fs/write_text_file', 'terminal/create', 'terminal/output',
62
+ 'terminal/release', 'terminal/wait_for_exit', 'terminal/kill',
63
+ ]);
64
+ const sizeLabel = (value) => (typeof value === 'string' ? `${value.length} chars` : typeof value);
65
+ const logMethod = (method) => (KNOWN_METHODS.has(method) ? method : `unknown method (${sizeLabel(method)})`);
66
+ // Numbers are ours or harmless; any other id is logged by type and size only.
67
+ const logId = (id) => {
68
+ if (typeof id === 'number' && Number.isFinite(id)) return String(id);
69
+ if (id === null) return 'null';
70
+ return `string, ${sizeLabel(id)}`;
71
+ };
72
+ // Encoding can fail on a BigInt or a cycle; that failure belongs to the one
73
+ // call that brought the value, never to the connection.
74
+ const encode = (message) => {
75
+ try {
76
+ return `${JSON.stringify(message)}\n`;
77
+ } catch (err) {
78
+ throw localError('ACP_ENCODE', `ACP message could not be encoded as JSON (${err.name})`);
79
+ }
80
+ };
81
+
82
+ /**
83
+ * Errors from the remote side carry its JSON-RPC `code` (a number), `message`
84
+ * and `data`. Local failures use string codes: ACP_TIMEOUT, ACP_CLOSED.
85
+ */
86
+ export function createAcpConnection({
87
+ stdin,
88
+ stdout,
89
+ onNotification = () => {},
90
+ onRequest,
91
+ log = () => {},
92
+ maxMessageBytes = DEFAULT_MAX_MESSAGE_BYTES,
93
+ } = {}) {
94
+ if (!stdin || !stdout) throw new TypeError('createAcpConnection needs the child stdin and stdout');
95
+
96
+ const pending = new Map(); // id -> { method, resolve, reject, timer }
97
+ let nextId = 0;
98
+ let closedReason = null;
99
+ let resolveClosed;
100
+ const closed = new Promise((resolve) => { resolveClosed = resolve; });
101
+
102
+ // `line` comes from encode(): JSON.stringify escapes every newline inside
103
+ // strings, so it is exactly one line.
104
+ const write = (line) => {
105
+ if (closedReason !== null) return false;
106
+ try {
107
+ stdin.write(line);
108
+ return true;
109
+ } catch (err) {
110
+ close(`agent stdin write failed: ${err.code || err.name}`);
111
+ return false;
112
+ }
113
+ };
114
+
115
+ const close = (reason = 'closed') => {
116
+ if (closedReason !== null) return;
117
+ closedReason = String(reason);
118
+ log(`acp: connection closed (${closedReason}); rejecting ${pending.size} pending`);
119
+ for (const [id, entry] of pending) {
120
+ clearTimeout(entry.timer);
121
+ entry.reject(localError('ACP_CLOSED', `ACP connection closed before ${entry.method} (id ${id}) was answered: ${closedReason}`));
122
+ }
123
+ pending.clear();
124
+ stdout.off('data', onData);
125
+ stdout.off('end', onEnd);
126
+ stdout.off('close', onEnd);
127
+ // The error listeners stay: an EPIPE after close must not become an
128
+ // unhandled 'error' event that takes the whole connector down.
129
+ resolveClosed(closedReason);
130
+ };
131
+
132
+ const request = (method, params, { timeoutMs } = {}) => {
133
+ if (closedReason !== null) {
134
+ return Promise.reject(localError('ACP_CLOSED', `ACP connection is closed (${closedReason}); ${method} not sent`));
135
+ }
136
+ const id = nextId++;
137
+ const message = { jsonrpc: '2.0', id, method };
138
+ if (params !== undefined) message.params = params;
139
+ let line;
140
+ try {
141
+ line = encode(message);
142
+ } catch (err) {
143
+ return Promise.reject(err);
144
+ }
145
+ return new Promise((resolve, reject) => {
146
+ const entry = { method, resolve, reject, timer: null };
147
+ if (timeoutMs > 0) {
148
+ entry.timer = setTimeout(() => {
149
+ if (!pending.delete(id)) return;
150
+ log(`acp: ${method} (id ${id}) timed out after ${timeoutMs}ms`);
151
+ reject(localError('ACP_TIMEOUT', `ACP request ${method} (id ${id}) timed out after ${timeoutMs}ms`));
152
+ }, timeoutMs);
153
+ }
154
+ pending.set(id, entry);
155
+ log(`acp: -> ${method} (id ${id})`);
156
+ write(line);
157
+ });
158
+ };
159
+
160
+ const notify = (method, params) => {
161
+ if (closedReason !== null) return;
162
+ const message = { jsonrpc: '2.0', method };
163
+ if (params !== undefined) message.params = params;
164
+ if (write(encode(message))) log(`acp: -> ${method} (notification)`);
165
+ };
166
+
167
+ const respond = (id, payload) => {
168
+ if (closedReason !== null) return;
169
+ let line;
170
+ try {
171
+ line = encode({ jsonrpc: '2.0', id, ...payload });
172
+ } catch {
173
+ log(`acp: reply to request id ${logId(id)} could not be encoded; sending an internal error`);
174
+ line = encode({ jsonrpc: '2.0', id, error: { code: ACP_ERROR.INTERNAL_ERROR, message: 'Internal error' } });
175
+ }
176
+ write(line);
177
+ };
178
+
179
+ const handleInboundRequest = async (msg) => {
180
+ const { id, method } = msg;
181
+ log(`acp: <- ${logMethod(method)} (request id ${logId(id)})`);
182
+ if (typeof onRequest !== 'function') {
183
+ respond(id, { error: { code: ACP_ERROR.METHOD_NOT_FOUND, message: 'Method not found' } });
184
+ return;
185
+ }
186
+ let reply;
187
+ try {
188
+ const result = await onRequest(method, msg.params);
189
+ reply = { result: result === undefined ? null : result };
190
+ } catch (err) {
191
+ if (err && Number.isInteger(err.code)) {
192
+ const error = { code: err.code, message: String(err.message || 'Error') };
193
+ if (err.data !== undefined) error.data = err.data;
194
+ reply = { error };
195
+ } else {
196
+ // A crash in our handler may hold anything in its message; send none of it.
197
+ log(`acp: handler for ${logMethod(method)} (id ${logId(id)}) threw without a JSON-RPC code`);
198
+ reply = { error: { code: ACP_ERROR.INTERNAL_ERROR, message: 'Internal error' } };
199
+ }
200
+ }
201
+ respond(id, reply);
202
+ };
203
+
204
+ const handleMessage = (msg) => {
205
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg) || msg.jsonrpc !== '2.0') {
206
+ log('acp: skipped a line that is not a JSON-RPC 2.0 object');
207
+ return;
208
+ }
209
+ if (typeof msg.method === 'string') {
210
+ if (!hasOwn(msg, 'id')) {
211
+ try {
212
+ const ret = onNotification(msg.method, msg.params);
213
+ if (ret && typeof ret.catch === 'function') ret.catch(() => log(`acp: notification handler for ${logMethod(msg.method)} failed`));
214
+ } catch {
215
+ log(`acp: notification handler for ${logMethod(msg.method)} failed`);
216
+ }
217
+ return;
218
+ }
219
+ if (!isRequestId(msg.id)) { log(`acp: skipped ${logMethod(msg.method)} with an invalid id`); return; }
220
+ handleInboundRequest(msg);
221
+ return;
222
+ }
223
+ if (hasOwn(msg, 'id') && (hasOwn(msg, 'result') || hasOwn(msg, 'error'))) {
224
+ const entry = pending.get(msg.id);
225
+ if (!entry) { log('acp: skipped a response to an id with no pending request'); return; }
226
+ pending.delete(msg.id);
227
+ clearTimeout(entry.timer);
228
+ if (hasOwn(msg, 'result') && hasOwn(msg, 'error')) {
229
+ log(`acp: <- invalid response (both result and error) for ${entry.method} (id ${msg.id})`);
230
+ entry.reject(localError('ACP_INVALID_RESPONSE', `ACP response to ${entry.method} (id ${msg.id}) carries both result and error`));
231
+ return;
232
+ }
233
+ if (hasOwn(msg, 'error')) {
234
+ const e = msg.error;
235
+ // ACP requires an object with an integer code. Anything else still
236
+ // settles the request, as an invalid response.
237
+ if (!e || typeof e !== 'object' || Array.isArray(e) || !Number.isInteger(e.code)) {
238
+ log(`acp: <- invalid error object for ${entry.method} (id ${msg.id})`);
239
+ entry.reject(localError('ACP_INVALID_RESPONSE', `ACP response to ${entry.method} (id ${msg.id}) carries an invalid error object`));
240
+ return;
241
+ }
242
+ const err = new Error(typeof e.message === 'string' ? e.message : 'ACP error');
243
+ err.code = e.code;
244
+ if (e.data !== undefined) err.data = e.data;
245
+ log(`acp: <- error ${e.code} for ${entry.method} (id ${msg.id})`);
246
+ entry.reject(err);
247
+ } else {
248
+ log(`acp: <- result for ${entry.method} (id ${msg.id})`);
249
+ entry.resolve(msg.result);
250
+ }
251
+ return;
252
+ }
253
+ log('acp: skipped a JSON-RPC message that is neither a request, notification nor response');
254
+ };
255
+
256
+ const handleLine = (buf) => {
257
+ const text = buf.toString('utf8').replace(/\r$/, '');
258
+ if (!text.trim()) return;
259
+ let msg;
260
+ try {
261
+ msg = JSON.parse(text);
262
+ } catch {
263
+ // No preview: a stdout line can start with a key or a Bearer token.
264
+ log(`acp: skipped a stdout line that is not JSON (${buf.length} bytes)`);
265
+ return;
266
+ }
267
+ handleMessage(msg);
268
+ };
269
+
270
+ // Framing works on bytes: "\n" (0x0a) never occurs inside a multi-byte UTF-8
271
+ // character, so a chunk boundary anywhere is safe.
272
+ let parts = [];
273
+ let partLength = 0;
274
+ const onData = (chunk) => {
275
+ let data = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;
276
+ while (closedReason === null) {
277
+ const nl = data.indexOf(NEWLINE);
278
+ if (nl < 0) {
279
+ partLength += data.length;
280
+ if (partLength > maxMessageBytes) { overflow(); return; }
281
+ if (data.length) parts.push(data);
282
+ return;
283
+ }
284
+ const head = data.subarray(0, nl);
285
+ if (partLength + head.length > maxMessageBytes) { overflow(); return; }
286
+ const line = parts.length ? Buffer.concat([...parts, head]) : head;
287
+ parts = [];
288
+ partLength = 0;
289
+ data = data.subarray(nl + 1);
290
+ handleLine(line);
291
+ }
292
+ };
293
+ const overflow = () => {
294
+ parts = [];
295
+ partLength = 0;
296
+ close(`agent sent a message over ${maxMessageBytes} bytes`);
297
+ };
298
+ const onEnd = () => close('agent stdout ended');
299
+ const onStdoutError = (err) => close(`agent stdout error: ${err.code || err.name}`);
300
+ const onStdinError = (err) => close(`agent stdin error: ${err.code || err.name}`);
301
+
302
+ stdout.on('data', onData);
303
+ stdout.on('end', onEnd);
304
+ stdout.on('close', onEnd);
305
+ stdout.on('error', onStdoutError);
306
+ stdin.on?.('error', onStdinError);
307
+
308
+ return {
309
+ request,
310
+ notify,
311
+ close,
312
+ closed,
313
+ isClosed: () => closedReason !== null,
314
+ };
315
+ }
@@ -19,12 +19,20 @@ export const PUBLIC_WITHHELD_TOOLS = Object.freeze(['commonly_attach_file', 'com
19
19
  // commonly_delete_message (F141): a stranger-steered seat could delete its own
20
20
  // replies to an injection, which are the evidence of what the attack achieved.
21
21
  // A workspace seat keeps it.
22
+ // The hand-back tools (ADR-037 Phase 1, F654): commonly_send_plan puts a
23
+ // decision card in front of a named person, so a stranger-steered seat must
24
+ // not be able to aim one. A public agent starts without all four; a workspace
25
+ // seat keeps them.
22
26
  export const PUBLIC_ONLY_WITHHELD_TOOLS = Object.freeze([
23
27
  'commonly_self_install_into_pod',
24
28
  'commonly_write_agent_memory',
25
29
  'commonly_save_my_memory',
26
30
  'commonly_log_cycle',
27
31
  'commonly_delete_message',
32
+ 'commonly_send_plan',
33
+ 'commonly_hand_back',
34
+ 'commonly_get_hand_back',
35
+ 'commonly_withdraw_hand_back',
28
36
  ]);
29
37
 
30
38
  // Everything a public seat is not offered. Codex, OpenCode, Qwen and Goose