@commonlyai/cli 0.1.120 → 0.1.121

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.120",
3
+ "version": "0.1.121",
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,254 @@
1
+ /** Goose 1.54.0 wrapper. Public seats wait for TASK-236's deny-by-default proof. */
2
+ import { spawn as childSpawn, spawnSync } from 'node:child_process';
3
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { StringDecoder } from 'node:string_decoder';
7
+ import { buildMemoryPreamble } from '../memory-bridge.js';
8
+ import { effectiveSandboxTrust, validateEnvironmentSpec } from '../environment.js';
9
+ import { writeCredentialFile } from '../credential-file.js';
10
+ import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
11
+ import { prepareMcpSpawn } from '../mcp-home.js';
12
+ import { resolveProviderKeyFile } from '../provider-proxy.js';
13
+ import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
14
+
15
+ // A version enters this list only after a real headless turn with that binary.
16
+ export const TESTED_GOOSE_VERSIONS = Object.freeze(['1.54.0']);
17
+ const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
18
+ const TERMINATION_GRACE_MS = 5000;
19
+ const DEFAULT_MODEL = 'deepseek-v4-flash';
20
+ const DEFAULT_PROVIDER_HOST = 'https://litellm.commonly.me';
21
+ const DEFAULT_PROVIDER_KEY = 'COMMONLY_LITELLM_KEY';
22
+ const PLACEHOLDER_RE = /\$\{(COMMONLY_[A-Z_]+)\}/g;
23
+ const SAFE_ENV = /^(?:PATH|LANG|LC_[A-Z_]+|TERM|USER|LOGNAME|NO_COLOR|CI|SSL_CERT_FILE|SSL_CERT_DIR)$/;
24
+
25
+ export const assertNoSandboxDeclared = (environment = {}) => {
26
+ const sandbox = environment?.sandbox || {};
27
+ if (effectiveSandboxTrust(sandbox.trust) === 'public') {
28
+ throw new Error('goose adapter: public-trust seats are not supported until the deny-by-default attack test passes');
29
+ }
30
+ if (sandbox.mode && sandbox.mode !== 'none') {
31
+ throw new Error(`goose adapter: sandbox.mode=${sandbox.mode} cannot be enforced by Goose`);
32
+ }
33
+ };
34
+
35
+ const versionOf = (value) => String(value || '').trim().match(/\b(\d+\.\d+\.\d+)\b/)?.[1] || null;
36
+
37
+ /** Goose splits this string itself; reject quotes it cannot represent safely. */
38
+ const gooseWord = (value) => {
39
+ const word = String(value);
40
+ if (!word || /["\r\n\0]/.test(word)) throw new Error('goose adapter: MCP argument contains an unsupported character');
41
+ return `"${word}"`;
42
+ };
43
+
44
+ const substitute = (value, ctx) => String(value).replace(PLACEHOLDER_RE, (whole, name) => ({
45
+ COMMONLY_TOKEN_FILE: ctx.credentialFile,
46
+ COMMONLY_API_URL: ctx.instanceUrl,
47
+ COMMONLY_INSTANCE_URL: ctx.instanceUrl,
48
+ }[name] || whole));
49
+
50
+ /** The flag contains paths and URLs only. Literal MCP secrets cannot ride argv. */
51
+ export const extensionArgs = (servers, ctx) => {
52
+ const args = [];
53
+ for (const server of servers || []) {
54
+ if (!/^[A-Za-z0-9_-]{2,}$/.test(server?.name || '')) {
55
+ throw new Error('goose adapter: MCP server needs a safe name');
56
+ }
57
+ const transport = server.transport || 'stdio';
58
+ if (transport === 'http') {
59
+ if (server.headers && Object.keys(server.headers).length) {
60
+ throw new Error(`goose adapter: HTTP MCP server ${server.name} has headers Goose cannot deliver without exposing credentials`);
61
+ }
62
+ if (typeof server.url !== 'string' || !server.url) throw new Error(`goose adapter: ${server.name} has no HTTP URL`);
63
+ const url = substitute(server.url, ctx);
64
+ const parsed = new URL(url);
65
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) {
66
+ throw new Error(`goose adapter: HTTP MCP server ${server.name} contains a credential-bearing URL`);
67
+ }
68
+ if (parsed.origin !== new URL(ctx.instanceUrl).origin) {
69
+ throw new Error(`goose adapter: HTTP MCP server ${server.name} is outside the Commonly instance`);
70
+ }
71
+ args.push('--with-streamable-http-extension', url);
72
+ continue;
73
+ }
74
+ if (transport !== 'stdio' || !Array.isArray(server.command) || !server.command.length) {
75
+ throw new Error(`goose adapter: MCP server ${server.name} has an unsupported transport or command`);
76
+ }
77
+ const command = prepareMcpSpawn(server.command, { apiUrl: ctx.instanceUrl });
78
+ const delivery = deliverSeatCredential({ ...server, command }, {
79
+ credentialFile: ctx.credentialFile, label: 'goose',
80
+ });
81
+ if (delivery.delivered === 'env' || delivery.delivered === 'unavailable') {
82
+ throw new Error(`goose adapter: MCP server ${server.name} cannot receive its credential by file`);
83
+ }
84
+ const env = Object.entries(delivery.env).map(([name, value]) => {
85
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error('goose adapter: invalid MCP environment key');
86
+ if (!['COMMONLY_TOKEN_FILE', 'COMMONLY_API_URL', 'COMMONLY_INSTANCE_URL'].includes(name)) {
87
+ throw new Error(`goose adapter: MCP server ${server.name} has ${name}, which cannot safely ride a CLI flag`);
88
+ }
89
+ const resolved = substitute(value, ctx);
90
+ if (resolved.includes('${COMMONLY_AGENT_TOKEN}') || (ctx.runtimeToken && resolved.includes(ctx.runtimeToken))) {
91
+ throw new Error(`goose adapter: MCP server ${server.name} would expose the runtime token in argv`);
92
+ }
93
+ return gooseWord(`${name}=${resolved}`);
94
+ });
95
+ const commandWords = command.map((part) => gooseWord(substitute(part, ctx)));
96
+ args.push('--with-extension', `${server.name}:${[...env, ...commandWords].join(' ')}`);
97
+ }
98
+ return args;
99
+ };
100
+
101
+ export const readGooseStream = (stdout) => {
102
+ let text = '';
103
+ let error = null;
104
+ let complete = false;
105
+ for (const line of String(stdout || '').split('\n')) {
106
+ let event;
107
+ try { event = JSON.parse(line); } catch { continue; }
108
+ if (event?.type === 'complete') complete = true;
109
+ if (event?.type === 'error') error = event.error?.message || event.message || 'Goose turn failed';
110
+ if (event?.type === 'message' && event.message?.role === 'assistant'
111
+ && event.message?.metadata?.userVisible !== false) {
112
+ const body = event.message.content?.filter((item) => item?.type === 'text' && typeof item.text === 'string')
113
+ .map((item) => item.text).join('') || '';
114
+ if (body.trim()) text = body.trim();
115
+ }
116
+ }
117
+ return { text, error, complete };
118
+ };
119
+
120
+ const runGoose = ({ binary, args, cwd, env, timeoutMs, credentials, spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
121
+ const child = spawnImpl(binary, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
122
+ let stdout = '';
123
+ const stdoutDecoder = new StringDecoder('utf8');
124
+ let stderr = '';
125
+ let timedOut = false;
126
+ let streamOverflow = false;
127
+ let extensionFailure = null;
128
+ let settled = false;
129
+ let killTimer;
130
+ const finish = (error, result) => {
131
+ if (settled) return;
132
+ settled = true;
133
+ clearTimeout(timer);
134
+ clearTimeout(killTimer);
135
+ if (error) reject(error); else resolve(result);
136
+ };
137
+ const timer = setTimeout(() => {
138
+ timedOut = true;
139
+ child.kill('SIGTERM');
140
+ killTimer = setTimeout(() => child.kill('SIGKILL'), TERMINATION_GRACE_MS);
141
+ }, timeoutMs);
142
+ child.stdout?.on('data', (chunk) => {
143
+ if (streamOverflow) return;
144
+ stdout += stdoutDecoder.write(chunk);
145
+ if (stdout.length > 2 * 1024 * 1024) {
146
+ streamOverflow = true;
147
+ stdout = '';
148
+ clearTimeout(timer);
149
+ child.kill('SIGTERM');
150
+ killTimer = setTimeout(() => child.kill('SIGKILL'), TERMINATION_GRACE_MS);
151
+ }
152
+ });
153
+ child.stderr?.on('data', (chunk) => {
154
+ const received = chunk.toString();
155
+ extensionFailure ||= (stderr + received).match(/Failed to start extension '[^']+'[^\n]*/)?.[0] || null;
156
+ stderr = (stderr + received).slice(-8192);
157
+ });
158
+ child.on('error', (error) => finish(error));
159
+ child.on('close', (code) => {
160
+ stdout += stdoutDecoder.end();
161
+ if (timedOut) return finish(new Error(`goose adapter: timed out after ${timeoutMs}ms`));
162
+ if (streamOverflow) return finish(new Error('goose adapter: stream exceeded 2 MiB'));
163
+ const result = readGooseStream(stdout);
164
+ // Goose reports an extension startup failure on stderr yet exits 0 and
165
+ // lets the model answer without that tool. A Commonly seat cannot silently
166
+ // lose its only path back to the pod.
167
+ if (code !== 0 || result.error || !result.complete || extensionFailure) {
168
+ return finish(adapterFailure('goose', extensionFailure || result.error || stderr.trim() || `exit ${code}; incomplete stream`, {
169
+ credentials, exitCode: code, limit: 500,
170
+ }));
171
+ }
172
+ return finish(null, result.text);
173
+ });
174
+ });
175
+
176
+ export default {
177
+ name: 'goose',
178
+ providerKeyEnv: DEFAULT_PROVIDER_KEY,
179
+ supportsProvider: true,
180
+
181
+ async validateEnvironment(environment, workspacePath) {
182
+ assertNoSandboxDeclared(environment);
183
+ const validation = validateEnvironmentSpec(environment || {});
184
+ if (!validation.ok) throw new Error(validation.errors.join('; '));
185
+ return resolveProviderKeyFile(environment?.provider, workspacePath, 'Goose');
186
+ },
187
+
188
+ async detect() {
189
+ const result = spawnSync('goose', ['--version'], { encoding: 'utf8', timeout: 5000 });
190
+ if (result.error || result.status !== 0) return null;
191
+ const where = spawnSync('which', ['goose'], { encoding: 'utf8', timeout: 5000 });
192
+ return { path: String(where.stdout || 'goose').trim() || 'goose', version: versionOf(result.stdout) || 'unknown' };
193
+ },
194
+
195
+ async spawn(prompt, ctx = {}) {
196
+ const keyFile = await this.validateEnvironment(ctx.environment, ctx.cwd);
197
+ const sourceEnv = ctx.env || process.env;
198
+ const configured = ctx.environment?.provider;
199
+ const key = configured
200
+ ? (await readFile(keyFile, 'utf8')).trim() : sourceEnv[DEFAULT_PROVIDER_KEY];
201
+ if (!key) throw new Error(`goose adapter: ${configured ? 'provider.keyFile' : DEFAULT_PROVIDER_KEY} is missing`);
202
+ const baseUrl = new URL(configured?.baseURL || `${DEFAULT_PROVIDER_HOST}/v1`);
203
+ if (!/^https?:$/.test(baseUrl.protocol) || baseUrl.username || baseUrl.password || baseUrl.search || baseUrl.hash) {
204
+ throw new Error('goose adapter: provider.baseURL must be a plain HTTP(S) URL');
205
+ }
206
+ const model = ctx.environment?.model || DEFAULT_MODEL;
207
+ const binary = ctx._binaryPath || 'goose';
208
+ const version = ctx._version || versionOf(spawnSync(binary, ['--version'], { encoding: 'utf8', timeout: 5000 }).stdout);
209
+ if (!TESTED_GOOSE_VERSIONS.includes(version)) {
210
+ // eslint-disable-next-line no-console
211
+ console.warn(`[goose] installed ${version || 'unknown'} differs from smoke-tested ${TESTED_GOOSE_VERSIONS.join(', ')}; private seat continues`);
212
+ }
213
+ const home = await mkdtemp(join(tmpdir(), 'commonly-goose-'));
214
+ try {
215
+ const credential = writeCredentialFile(ctx.runtimeToken, {
216
+ root: home, agentName: ctx.agentName || 'agent',
217
+ });
218
+ const args = [
219
+ 'run', '--no-session', '--no-profile', '--with-builtin', 'developer',
220
+ '--output-format', 'stream-json', '--provider', 'openai', '--model', model,
221
+ ...extensionArgs(ctx.environment?.mcp, {
222
+ credentialFile: credential?.path || '', instanceUrl: ctx.instanceUrl || '',
223
+ runtimeToken: ctx.runtimeToken || '',
224
+ }),
225
+ '-t', buildMemoryPreamble(prompt, ctx.memoryLongTerm, { freshSession: true }),
226
+ ];
227
+ const env = {
228
+ ...Object.fromEntries(Object.entries(sourceEnv).filter(([name]) => SAFE_ENV.test(name))),
229
+ HOME: home,
230
+ XDG_CONFIG_HOME: join(home, 'config'),
231
+ XDG_DATA_HOME: join(home, 'data'),
232
+ GOOSE_PROVIDER: 'openai',
233
+ GOOSE_MODEL: model,
234
+ GOOSE_MODE: 'auto',
235
+ GOOSE_TELEMETRY_ENABLED: 'false',
236
+ OPENAI_HOST: baseUrl.origin,
237
+ OPENAI_BASE_PATH: `${baseUrl.pathname.replace(/\/$/, '')}/chat/completions`.replace(/^\//, ''),
238
+ OPENAI_API_KEY: key,
239
+ };
240
+ withholdRuntimeCredential(env, { credentialFile: credential?.path || null });
241
+ const requestedTimeout = Number(ctx.timeoutMs);
242
+ const timeoutMs = Number.isFinite(requestedTimeout) && requestedTimeout > 0
243
+ ? Math.min(requestedTimeout, DEFAULT_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
244
+ const text = await runGoose({
245
+ binary, args, cwd: ctx.cwd, env, timeoutMs,
246
+ credentials: [...spawnCredentials(ctx, [DEFAULT_PROVIDER_KEY]), key],
247
+ spawnImpl: ctx._spawnImpl,
248
+ });
249
+ return { text, newSessionId: null };
250
+ } finally {
251
+ await rm(home, { recursive: true, force: true });
252
+ }
253
+ },
254
+ };
@@ -14,6 +14,7 @@ import pi from './pi.js';
14
14
  import opencode from './opencode.js';
15
15
  import qwen from './qwen.js';
16
16
  import dsh from './dsh.js';
17
+ import goose from './goose.js';
17
18
 
18
19
  const ADAPTERS = {
19
20
  [stub.name]: stub,
@@ -23,6 +24,7 @@ const ADAPTERS = {
23
24
  [opencode.name]: opencode,
24
25
  [qwen.name]: qwen,
25
26
  [dsh.name]: dsh,
27
+ [goose.name]: goose,
26
28
  };
27
29
 
28
30
  export const listAdapterNames = () => Object.keys(ADAPTERS);
@@ -19,6 +19,7 @@
19
19
  * opencode — per-spawn config file with local/remote MCP entries (adapters/opencode.js)
20
20
  * qwen — per-spawn --mcp-config with file-backed stdio credentials (adapters/qwen.js)
21
21
  * dsh — per-spawn --patch with file-backed stdio credentials (adapters/dsh.js)
22
+ * goose — per-spawn --with-extension with file-backed stdio credentials (adapters/goose.js)
22
23
  * `stub` has no consumption path and must keep being handed `environment: null`.
23
24
  *
24
25
  * The placeholders are substituted at spawn time by the adapter, so the
@@ -27,13 +28,15 @@
27
28
 
28
29
  import { normalizeSandboxTrust } from './environment.js';
29
30
 
30
- export const ADAPTERS_WITH_DEFAULT_MCP = new Set(['claude', 'codex', 'pi', 'opencode', 'qwen', 'dsh']);
31
+ export const ADAPTERS_WITH_DEFAULT_MCP = new Set(['claude', 'codex', 'pi', 'opencode', 'qwen', 'dsh', 'goose']);
31
32
 
32
33
  /**
33
34
  * The adapters that can ENFORCE the default sandbox — a strict subset of the
34
35
  * ones that consume `mcp[]`.
35
36
  *
36
- * `pi` is absent deliberately. It has no sandbox path until #1740's transport
37
+ * `pi` and `goose` are absent deliberately. Neither can enforce the declared
38
+ * sandbox; their adapters refuse effective public trust and non-none modes.
39
+ * `pi` has no sandbox path until #1740's transport
37
40
  * work gives it one, and since #1727 it REFUSES TO START on a spec that
38
41
  * declares one: `assertNoSandboxDeclared` in adapters/pi.js throws on an
39
42
  * effective `trust: 'public'` (a legacy `internal` resolves to it) and on any