@commonlyai/cli 0.1.108 → 0.1.117
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
package/src/commands/agent.js
CHANGED
|
@@ -362,6 +362,10 @@ export const bootstrapAgentRecordFromEnv = async ({
|
|
|
362
362
|
}
|
|
363
363
|
}
|
|
364
364
|
|
|
365
|
+
if (adapterName === 'dsh') {
|
|
366
|
+
throw new Error('dsh first-run bootstrap requires provider settings; attach it with --env before running');
|
|
367
|
+
}
|
|
368
|
+
|
|
365
369
|
// The token's identity wins over the CLI argument — a mistyped name must
|
|
366
370
|
// not fork a second identity for the same token.
|
|
367
371
|
const agentName = identity?.agentName || name;
|
|
@@ -522,15 +526,34 @@ export const buildDefaultEnvironment = (adapterName) => {
|
|
|
522
526
|
* (older server, network failure, permissions), attach proceeds — failing the
|
|
523
527
|
* attach on an unrelated fault would be its own footgun — but says so, because
|
|
524
528
|
* a silent skip is how the original hole stayed invisible.
|
|
529
|
+
* dsh is private-only, so it requires a successful visibility read and rejects
|
|
530
|
+
* a public pod even without a sandbox declaration.
|
|
525
531
|
*/
|
|
526
532
|
export const assertSandboxDeclaredForPublicPod = async ({
|
|
527
533
|
client,
|
|
528
534
|
podId,
|
|
529
535
|
environment,
|
|
536
|
+
adapterName,
|
|
530
537
|
log = () => {},
|
|
531
538
|
}) => {
|
|
532
539
|
if (!podId || !client) return;
|
|
533
540
|
|
|
541
|
+
if (adapterName === 'dsh') {
|
|
542
|
+
let pod;
|
|
543
|
+
try {
|
|
544
|
+
pod = await client.get(`/api/pods/${podId}`);
|
|
545
|
+
} catch {
|
|
546
|
+
throw new Error('dsh requires confirmed private pod visibility before attach');
|
|
547
|
+
}
|
|
548
|
+
if (typeof pod?.publicRead !== 'boolean' || typeof pod?.communityListed !== 'boolean') {
|
|
549
|
+
throw new Error('dsh requires confirmed private pod visibility before attach');
|
|
550
|
+
}
|
|
551
|
+
if (pod?.publicRead || pod?.communityListed) {
|
|
552
|
+
throw new Error('dsh supports private pods only; this pod is publicly readable');
|
|
553
|
+
}
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
|
|
534
557
|
// Normalized FIRST (Vera 71715, Wren 71718): the predicate below reads a
|
|
535
558
|
// legacy `internal` record as the `public` it means, the same mapping the
|
|
536
559
|
// attach gate and both adapters use. Reading it raw refused a record that
|
|
@@ -776,6 +799,9 @@ export const performAttach = async ({
|
|
|
776
799
|
if (!detected) {
|
|
777
800
|
throw new Error(`${adapterName} not found on PATH. Install it and retry.`);
|
|
778
801
|
}
|
|
802
|
+
if (adapterName === 'dsh' && !envPath) {
|
|
803
|
+
throw new Error('dsh requires an environment file with provider and model');
|
|
804
|
+
}
|
|
779
805
|
|
|
780
806
|
// ADR-008 §invariant #4: sandbox failure is a hard stop. Validate the env
|
|
781
807
|
// here so attach refuses up front rather than handing the user a runtime
|
|
@@ -858,7 +884,7 @@ export const performAttach = async ({
|
|
|
858
884
|
// declaration at all — the branch that validates sandbox settings never
|
|
859
885
|
// executes for those, so the agent silently ran unsandboxed.
|
|
860
886
|
await assertSandboxDeclaredForPublicPod({
|
|
861
|
-
client, podId, environment, log,
|
|
887
|
+
client, podId, environment, adapterName, log,
|
|
862
888
|
});
|
|
863
889
|
|
|
864
890
|
// Identity-bearing runtime tag from the adapter (e.g. 'codex', 'claude-
|
|
@@ -2889,7 +2915,7 @@ Docs:
|
|
|
2889
2915
|
// ── attach (ADR-005, ADR-008) ─────────────────────────────────────────────
|
|
2890
2916
|
agent
|
|
2891
2917
|
.command('attach <adapter>')
|
|
2892
|
-
.description('Wrap a local CLI as a Commonly agent (stub|claude|codex|opencode|qwen|…)')
|
|
2918
|
+
.description('Wrap a local CLI as a Commonly agent (stub|claude|codex|opencode|qwen|dsh|…)')
|
|
2893
2919
|
.requiredOption('--pod <podId>', 'Pod ID to install into')
|
|
2894
2920
|
.requiredOption('--name <name>', 'Agent name (e.g. my-claude)')
|
|
2895
2921
|
.option('--display <name>', 'Display name shown in the pod')
|
|
@@ -258,6 +258,59 @@ const buildPublicClaudePolicyArgs = (mcpToolPatterns) => {
|
|
|
258
258
|
];
|
|
259
259
|
};
|
|
260
260
|
|
|
261
|
+
// A public seat's skills, as appended system-prompt text.
|
|
262
|
+
//
|
|
263
|
+
// `--disable-slash-commands` above is Claude's switch for ALL skills, and
|
|
264
|
+
// `--setting-sources ''` drops the project source the mounted copies live in.
|
|
265
|
+
// So the skills this adapter mounts into <cwd>/.claude/skills never load in a
|
|
266
|
+
// public seat: measured 2026-10-19 on a Bring your own page seat, which
|
|
267
|
+
// answered "I don't see a skill named commonly, or any skills list or Skill
|
|
268
|
+
// tool"; the same workspace with `--setting-sources project` found it. Every
|
|
269
|
+
// self-serve seat is public (COMMONLY_DEFAULT_SANDBOX), so every outsider's
|
|
270
|
+
// Claude ran without the house rules buildDefaultEnvironment mounts for it.
|
|
271
|
+
// Re-enabling skills would also hand a public seat the built-in ones
|
|
272
|
+
// (computer-use, the browser skills), so the flags stay and the declared text
|
|
273
|
+
// is delivered as prompt instead. Inline rather than a file: nothing new has to
|
|
274
|
+
// be admitted through Seatbelt. Linux caps one argv string at 128 KiB, so the
|
|
275
|
+
// total is capped well under it.
|
|
276
|
+
const PUBLIC_SKILL_PROMPT_MAX_BYTES = 96 * 1024;
|
|
277
|
+
const SKILL_FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n?/;
|
|
278
|
+
|
|
279
|
+
const publicSkillPromptArgs = async (skillSources) => {
|
|
280
|
+
const sections = [];
|
|
281
|
+
let total = 0;
|
|
282
|
+
for (const source of skillSources || []) {
|
|
283
|
+
let markdown;
|
|
284
|
+
try {
|
|
285
|
+
// eslint-disable-next-line no-await-in-loop
|
|
286
|
+
markdown = await readFile(join(source, 'SKILL.md'), 'utf8');
|
|
287
|
+
} catch {
|
|
288
|
+
// eslint-disable-next-line no-console
|
|
289
|
+
console.warn(`[claude] public seat: no SKILL.md to inline at ${source}`);
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const frontmatter = SKILL_FRONTMATTER_RE.exec(markdown);
|
|
293
|
+
const name = (frontmatter && /^name:\s*(.+)$/m.exec(frontmatter[1])?.[1].trim())
|
|
294
|
+
|| source.split(/[\\/]/).filter(Boolean).pop();
|
|
295
|
+
const section = `## Skill: ${name}\n\n${markdown.slice(frontmatter ? frontmatter[0].length : 0).trim()}`;
|
|
296
|
+
const bytes = Buffer.byteLength(section, 'utf8');
|
|
297
|
+
if (total + bytes > PUBLIC_SKILL_PROMPT_MAX_BYTES) {
|
|
298
|
+
// eslint-disable-next-line no-console
|
|
299
|
+
console.warn(`[claude] public seat: skill ${name} not inlined (over ${PUBLIC_SKILL_PROMPT_MAX_BYTES} bytes in total)`);
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
total += bytes;
|
|
303
|
+
sections.push(section);
|
|
304
|
+
}
|
|
305
|
+
if (sections.length === 0) return [];
|
|
306
|
+
return [
|
|
307
|
+
'--append-system-prompt',
|
|
308
|
+
'These skills are part of how you work here. Skills are not loaded as files in this seat, '
|
|
309
|
+
+ 'so each one is given in full below. Follow them as you would a loaded skill.\n\n'
|
|
310
|
+
+ sections.join('\n\n'),
|
|
311
|
+
];
|
|
312
|
+
};
|
|
313
|
+
|
|
261
314
|
const runClaude = ({ cmd, args, cwd, env, timeoutMs, credentials = [], spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
|
|
262
315
|
const proc = spawnImpl(cmd, args, {
|
|
263
316
|
cwd,
|
|
@@ -637,6 +690,7 @@ const prepareArgv = async (innerArgv, ctx) => {
|
|
|
637
690
|
innerArgv = [
|
|
638
691
|
...innerArgv,
|
|
639
692
|
...buildPublicClaudePolicyArgs(allowedPatterns),
|
|
693
|
+
...(ctx.publicSkillArgs || []),
|
|
640
694
|
];
|
|
641
695
|
const claudeBin = resolveClaudePath(claudeEnv);
|
|
642
696
|
// Only stdio servers have a `command`; an HTTP entry (the grant broker)
|
|
@@ -674,6 +728,7 @@ const prepareArgv = async (innerArgv, ctx) => {
|
|
|
674
728
|
innerArgv = [
|
|
675
729
|
...innerArgv,
|
|
676
730
|
...buildPublicClaudePolicyArgs(allowedPatterns),
|
|
731
|
+
...(ctx.publicSkillArgs || []),
|
|
677
732
|
];
|
|
678
733
|
} else if (allowedPatterns.length > 0) {
|
|
679
734
|
innerArgv = [...innerArgv, '--allowedTools', ...allowedPatterns];
|
|
@@ -779,8 +834,10 @@ export default {
|
|
|
779
834
|
];
|
|
780
835
|
const baseArgs = ['-p', fullPrompt, '--output-format', 'text', sessionFlag, sessionId, ...modelArgs];
|
|
781
836
|
|
|
837
|
+
let mountedSkills = [];
|
|
782
838
|
if (ctx.environment && ctx.cwd) {
|
|
783
839
|
const skills = await mountSkills(ctx.environment, ctx.cwd);
|
|
840
|
+
mountedSkills = skills.mounted;
|
|
784
841
|
if (skills.conflicted.length > 0) {
|
|
785
842
|
for (const c of skills.conflicted) {
|
|
786
843
|
// eslint-disable-next-line no-console
|
|
@@ -792,6 +849,7 @@ export default {
|
|
|
792
849
|
|
|
793
850
|
let mcpConfig = null;
|
|
794
851
|
let publicClaudeState = null;
|
|
852
|
+
let publicSkillArgs = [];
|
|
795
853
|
try {
|
|
796
854
|
// Trust is normalized at entry (legacy `internal` reads as public). The
|
|
797
855
|
// MCP policy follows trust alone, whatever confines the seat: a public
|
|
@@ -803,6 +861,7 @@ export default {
|
|
|
803
861
|
if (publicNativeSandbox) {
|
|
804
862
|
publicClaudeState = await preparePublicClaudeState(ctx);
|
|
805
863
|
}
|
|
864
|
+
if (publicTrust) publicSkillArgs = await publicSkillPromptArgs(mountedSkills);
|
|
806
865
|
if (Array.isArray(ctx.environment?.mcp) && ctx.environment.mcp.length > 0) {
|
|
807
866
|
mcpConfig = await createMcpConfig(ctx.environment.mcp, {
|
|
808
867
|
runtimeToken: ctx.runtimeToken,
|
|
@@ -827,6 +886,7 @@ export default {
|
|
|
827
886
|
mcpConfigDir: mcpConfig?.dir || null,
|
|
828
887
|
mcpReadDirectories: mcpConfig?.mcpReadDirectories || [],
|
|
829
888
|
publicClaudeState,
|
|
889
|
+
publicSkillArgs,
|
|
830
890
|
claudeEnv,
|
|
831
891
|
};
|
|
832
892
|
const { cmd, args, env } = await prepareArgv(baseArgs, spawnCtx);
|
|
@@ -867,6 +927,7 @@ export default {
|
|
|
867
927
|
mcpConfigDir: mcpConfig?.dir || null,
|
|
868
928
|
mcpReadDirectories: mcpConfig?.mcpReadDirectories || [],
|
|
869
929
|
publicClaudeState,
|
|
930
|
+
publicSkillArgs,
|
|
870
931
|
claudeEnv: buildClaudeEnv(
|
|
871
932
|
ctx.env,
|
|
872
933
|
publicClaudeState,
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
/** DeepSeek Harness 0.2.1-rc.2, private seats only. Configuration is per spawn. */
|
|
2
|
+
import { spawn as childSpawn, spawnSync } from 'child_process';
|
|
3
|
+
import { createHash } from 'crypto';
|
|
4
|
+
import { existsSync } from 'fs';
|
|
5
|
+
import { chmod, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'fs/promises';
|
|
6
|
+
import { homedir, tmpdir } from 'os';
|
|
7
|
+
import { basename, join } from 'path';
|
|
8
|
+
import { buildMemoryPreamble } from '../memory-bridge.js';
|
|
9
|
+
import { commonlyMcpServer } from '../default-environment.js';
|
|
10
|
+
import { effectiveSandboxTrust, validateEnvironmentSpec } from '../environment.js';
|
|
11
|
+
import { deliverSeatCredential } from '../mcp-credential-delivery.js';
|
|
12
|
+
import { describeMcpCommand } from '../mcp-server-version.js';
|
|
13
|
+
import { writeCredentialFile } from '../credential-file.js';
|
|
14
|
+
import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
|
|
15
|
+
import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
|
|
16
|
+
|
|
17
|
+
export const TESTED_DSH_VERSIONS = Object.freeze(['0.2.1-rc.2']);
|
|
18
|
+
const PROXY_KEY_ENV = 'COMMONLY_DSH_PROXY_KEY';
|
|
19
|
+
const MAX_TIMEOUT_MS = 15 * 60 * 1000;
|
|
20
|
+
const SAFE_ENV = /^(?:PATH|LANG|LC_[A-Z_]+|TERM|USER|LOGNAME|NO_COLOR|CI|SSL_CERT_FILE|SSL_CERT_DIR)$/;
|
|
21
|
+
|
|
22
|
+
export const assertPrivateDsh = (environment = {}) => {
|
|
23
|
+
const sandbox = environment?.sandbox || {};
|
|
24
|
+
if (effectiveSandboxTrust(sandbox.trust) === 'public') {
|
|
25
|
+
throw new Error('dsh adapter: public-trust seats are not supported; nested Seatbelt fails closed');
|
|
26
|
+
}
|
|
27
|
+
if (sandbox.mode !== undefined) {
|
|
28
|
+
throw new Error(`dsh adapter: sandbox.mode=${sandbox.mode} cannot be enforced by this adapter`);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** A stable home per agent and Commonly instance, never the operator's ~/.dsh. */
|
|
33
|
+
export const seatHome = (ctx) => {
|
|
34
|
+
if (ctx._dshHome) return ctx._dshHome;
|
|
35
|
+
const id = createHash('sha256').update(`${ctx.instanceUrl || ''}\0${ctx.agentName || ''}`).digest('hex').slice(0, 24);
|
|
36
|
+
return join(homedir(), '.commonly', 'dsh-homes', id);
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export const childEnvironment = (source, home, bearer) => {
|
|
40
|
+
const env = Object.fromEntries(Object.entries(source || {}).filter(([name]) => SAFE_ENV.test(name)));
|
|
41
|
+
env.HOME = home;
|
|
42
|
+
env.DSH_HOME = home;
|
|
43
|
+
env.DSH_PERMISSION_MODE = 'workspace-write';
|
|
44
|
+
env.DSH_TELEMETRY_MODE = 'DISABLED';
|
|
45
|
+
env.DSH_TELEMETRY_DISABLED = '1';
|
|
46
|
+
env[PROXY_KEY_ENV] = bearer;
|
|
47
|
+
return env;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const substitute = (value, { credentialFile, instanceUrl }) => String(value).replace(/\$\{(COMMONLY_[A-Z_]+)\}/g, (whole, name) => ({
|
|
51
|
+
COMMONLY_TOKEN_FILE: credentialFile,
|
|
52
|
+
COMMONLY_API_URL: instanceUrl,
|
|
53
|
+
COMMONLY_INSTANCE_URL: instanceUrl,
|
|
54
|
+
}[name] || whole));
|
|
55
|
+
|
|
56
|
+
const isCommonlyCommand = (command) => {
|
|
57
|
+
if (!Array.isArray(command)) return false;
|
|
58
|
+
if (command.length === 3 && command[0] === 'npx' && command[1] === '-y') {
|
|
59
|
+
return /^@commonlyai\/mcp(?:@(?:latest|\d+\.\d+\.\d+))?$/.test(command[2]);
|
|
60
|
+
}
|
|
61
|
+
return command.length === 2 && basename(command[0]) === 'node'
|
|
62
|
+
&& command[1].endsWith('/@commonlyai/mcp/src/index.js');
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** One stdio Commonly server only. No remote credential or arbitrary MCP child. */
|
|
66
|
+
export const resolveCommonlyMcp = (declared, ctx) => {
|
|
67
|
+
const servers = declared?.length ? declared : [commonlyMcpServer()];
|
|
68
|
+
if (servers.length !== 1 || servers[0]?.name !== 'commonly') {
|
|
69
|
+
throw new Error('dsh adapter: PR 1 supports only the Commonly MCP server');
|
|
70
|
+
}
|
|
71
|
+
const server = servers[0];
|
|
72
|
+
if ((server.transport || 'stdio') !== 'stdio'
|
|
73
|
+
|| !isCommonlyCommand(server.command) || !describeMcpCommand(server.command)?.isCommonly) {
|
|
74
|
+
throw new Error('dsh adapter: Commonly MCP must be a recognized stdio @commonlyai/mcp command');
|
|
75
|
+
}
|
|
76
|
+
const delivery = deliverSeatCredential(server, {
|
|
77
|
+
credentialFile: ctx.credentialFile, label: 'dsh',
|
|
78
|
+
});
|
|
79
|
+
if (delivery.delivered !== 'path') {
|
|
80
|
+
throw new Error(`dsh adapter: Commonly MCP requires file-backed credentials (got ${delivery.delivered})`);
|
|
81
|
+
}
|
|
82
|
+
const values = { credentialFile: ctx.credentialFile, instanceUrl: ctx.instanceUrl };
|
|
83
|
+
const env = Object.fromEntries(Object.entries(delivery.env)
|
|
84
|
+
.map(([name, value]) => [name, substitute(value, values)]));
|
|
85
|
+
if (Object.keys(env).some((name) => !['COMMONLY_API_URL', 'COMMONLY_TOKEN_FILE'].includes(name))
|
|
86
|
+
|| env.COMMONLY_TOKEN_FILE !== ctx.credentialFile || env.COMMONLY_API_URL !== ctx.instanceUrl) {
|
|
87
|
+
throw new Error('dsh adapter: Commonly MCP must use this spawn\'s credential file');
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
id: 'mcp-commonly', name: '@deepseek-ai/dsh-mcp-client',
|
|
91
|
+
config: {
|
|
92
|
+
serverName: 'commonly', transport: 'stdio',
|
|
93
|
+
command: substitute(server.command[0], values),
|
|
94
|
+
args: server.command.slice(1).map((arg) => substitute(arg, values)),
|
|
95
|
+
env, failOnStartupError: true,
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/** JSON is valid YAML; a generated patch has no expression or quoting ambiguity. */
|
|
101
|
+
export const buildPatch = ({ proxyBaseURL, model, cwd, mcp, effort, deepseekOfficial = false }) => ([
|
|
102
|
+
{ id: 'llm-pi-ai', config: { providers: {
|
|
103
|
+
commonly: {
|
|
104
|
+
apiKeyEnv: PROXY_KEY_ENV, api: 'openai-completions', baseURL: proxyBaseURL,
|
|
105
|
+
...(effort ? { reasoning: effort } : {}),
|
|
106
|
+
// The loopback proxy hides the upstream URL from pi-ai's compatibility detection.
|
|
107
|
+
// Use the conservative Chat Completions roles/fields for every provider.
|
|
108
|
+
compat: {
|
|
109
|
+
supportsDeveloperRole: false,
|
|
110
|
+
supportsStore: false,
|
|
111
|
+
...(deepseekOfficial ? { thinkingFormat: 'deepseek' } : {}),
|
|
112
|
+
},
|
|
113
|
+
models: [{ id: model, name: model, contextWindow: 128000,
|
|
114
|
+
...(effort ? { reasoningEfforts: {
|
|
115
|
+
low: 'low', medium: 'high', high: 'high', xhigh: 'high', max: 'max',
|
|
116
|
+
} } : {}),
|
|
117
|
+
}],
|
|
118
|
+
},
|
|
119
|
+
} } },
|
|
120
|
+
{ id: 'agent-default-model', config: { provider: 'commonly', model } },
|
|
121
|
+
{ id: 'llm-deepseek', disabled: true },
|
|
122
|
+
{ id: 'llm-deepseek-account', disabled: true },
|
|
123
|
+
{ id: 'session-log-deepseek', config: { enabled: false } },
|
|
124
|
+
{ id: 'sandbox-policy', config: { mode: 'workspace-write', workspaceRoot: cwd } },
|
|
125
|
+
{ insert: [mcp] },
|
|
126
|
+
]);
|
|
127
|
+
|
|
128
|
+
export const assertPatchHasNoCredentials = (serialized, credentials) => {
|
|
129
|
+
if (serialized.includes('${COMMONLY_AGENT_TOKEN}')) {
|
|
130
|
+
throw new Error('dsh adapter: patch contains an unresolved seat token placeholder');
|
|
131
|
+
}
|
|
132
|
+
for (const credential of credentials) {
|
|
133
|
+
if (typeof credential === 'string' && credential && serialized.includes(credential)) {
|
|
134
|
+
throw new Error('dsh adapter: patch contains a credential value');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
/** dsh writes sessions below DSH_HOME/sessions/<workspace>/<session-id>. */
|
|
140
|
+
export const sessionExists = async (home, sessionId) => {
|
|
141
|
+
if (!/^session-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(sessionId || '')) return false;
|
|
142
|
+
const root = join(home, 'sessions');
|
|
143
|
+
if (!existsSync(root)) return false;
|
|
144
|
+
for (const workspace of await readdir(root, { withFileTypes: true })) {
|
|
145
|
+
if (!workspace.isDirectory()) continue;
|
|
146
|
+
if (existsSync(join(root, workspace.name, sessionId, 'session.v4.jsonl.zstd'))) return true;
|
|
147
|
+
}
|
|
148
|
+
return false;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
const parseVersion = (output) => String(output || '').trim().match(/\b\d+\.\d+\.\d+-rc\.\d+\b/)?.[0] || null;
|
|
152
|
+
const readVersion = (binary, env) => {
|
|
153
|
+
const result = spawnSync(binary, ['--version'], { encoding: 'utf8', timeout: 5000, env, cwd: env.DSH_HOME });
|
|
154
|
+
return result.status === 0 && !result.error ? parseVersion(result.stdout) : null;
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const parseEvent = (line, state) => {
|
|
158
|
+
let event;
|
|
159
|
+
try { event = JSON.parse(line); } catch { throw new Error('dsh emitted invalid JSON event'); }
|
|
160
|
+
if (event.type === 'session' && typeof event.sessionId === 'string') state.sessionId = event.sessionId;
|
|
161
|
+
if (event.type === 'final' && typeof event.text === 'string') state.final = event.text;
|
|
162
|
+
if (event.type === 'error') state.error = String(event.message || event.error || 'dsh error');
|
|
163
|
+
if (event.type === 'tool_result'
|
|
164
|
+
&& /SANDBOX_UNAVAILABLE|sandbox_apply: Operation not permitted/.test(JSON.stringify(event))) {
|
|
165
|
+
state.error = 'dsh sandbox runner unavailable';
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
export const runDsh = ({ binary, args, cwd, env, timeoutMs, credentials, spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
|
|
170
|
+
const proc = spawnImpl(binary, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
171
|
+
const state = { sessionId: null, final: null, error: null, buffer: '' };
|
|
172
|
+
let stderr = '';
|
|
173
|
+
let timedOut = false;
|
|
174
|
+
let parseFailure = null;
|
|
175
|
+
let settled = false;
|
|
176
|
+
let killTimer;
|
|
177
|
+
const finish = (error, result) => {
|
|
178
|
+
if (settled) return;
|
|
179
|
+
settled = true;
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
clearTimeout(killTimer);
|
|
182
|
+
if (error) reject(error); else resolve(result);
|
|
183
|
+
};
|
|
184
|
+
const timer = setTimeout(() => {
|
|
185
|
+
timedOut = true;
|
|
186
|
+
proc.kill('SIGTERM');
|
|
187
|
+
killTimer = setTimeout(() => proc.kill('SIGKILL'), 5000);
|
|
188
|
+
}, timeoutMs);
|
|
189
|
+
proc.stdout?.on('data', (chunk) => {
|
|
190
|
+
state.buffer += chunk.toString();
|
|
191
|
+
if (state.buffer.length > 1024 * 1024) {
|
|
192
|
+
parseFailure = new Error('dsh event exceeded 1 MiB');
|
|
193
|
+
proc.kill('SIGTERM');
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
while (state.buffer.includes('\n')) {
|
|
197
|
+
const end = state.buffer.indexOf('\n');
|
|
198
|
+
const line = state.buffer.slice(0, end).trim();
|
|
199
|
+
state.buffer = state.buffer.slice(end + 1);
|
|
200
|
+
if (line && !parseFailure) {
|
|
201
|
+
try { parseEvent(line, state); } catch (error) { parseFailure = error; proc.kill('SIGTERM'); }
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
proc.stderr?.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-8192); });
|
|
206
|
+
proc.on('error', (error) => finish(error));
|
|
207
|
+
proc.on('close', (code) => {
|
|
208
|
+
if (state.buffer.trim() && !parseFailure) {
|
|
209
|
+
try { parseEvent(state.buffer.trim(), state); } catch (error) { parseFailure = error; }
|
|
210
|
+
}
|
|
211
|
+
const failure = parseFailure?.message || state.error || (timedOut ? `timeout after ${timeoutMs}ms` : null)
|
|
212
|
+
|| (/SANDBOX_UNAVAILABLE|sandbox_apply: Operation not permitted/.test(stderr) ? 'sandbox runner unavailable' : null)
|
|
213
|
+
|| (code !== 0 ? stderr.trim() || `exit ${code}` : null)
|
|
214
|
+
|| (state.final === null ? 'no final event' : null);
|
|
215
|
+
if (failure) return finish(adapterFailure('dsh', failure, { credentials, exitCode: code, limit: 500 }));
|
|
216
|
+
return finish(null, { text: state.final.trim(), newSessionId: state.sessionId });
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
export default {
|
|
221
|
+
name: 'dsh', runtimeType: 'dsh', supportsProvider: true,
|
|
222
|
+
|
|
223
|
+
async validateEnvironment(environment, workspacePath) {
|
|
224
|
+
const validation = validateEnvironmentSpec(environment);
|
|
225
|
+
if (!validation.ok) throw new Error(validation.errors.join('; '));
|
|
226
|
+
assertPrivateDsh(environment);
|
|
227
|
+
if (!environment?.provider || !environment?.model) {
|
|
228
|
+
throw new Error('dsh requires environment.provider and environment.model');
|
|
229
|
+
}
|
|
230
|
+
const detected = await this.detect();
|
|
231
|
+
if (!TESTED_DSH_VERSIONS.includes(detected?.version)) {
|
|
232
|
+
throw new Error(`dsh adapter: installed version ${detected?.version || 'unknown'} is not smoke-tested (${TESTED_DSH_VERSIONS.join(', ')})`);
|
|
233
|
+
}
|
|
234
|
+
return resolveProviderKeyFile(environment.provider, workspacePath, 'dsh');
|
|
235
|
+
},
|
|
236
|
+
|
|
237
|
+
async detect() {
|
|
238
|
+
const home = await mkdtemp(join(tmpdir(), 'commonly-dsh-probe-'));
|
|
239
|
+
try {
|
|
240
|
+
const env = childEnvironment(process.env, home, '');
|
|
241
|
+
const version = readVersion('dsh', env);
|
|
242
|
+
return version ? { path: 'dsh', version } : null;
|
|
243
|
+
} finally {
|
|
244
|
+
await rm(home, { recursive: true, force: true });
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
|
|
248
|
+
async spawn(prompt, ctx = {}) {
|
|
249
|
+
assertPrivateDsh(ctx.environment);
|
|
250
|
+
if (!ctx.environment?.provider || !ctx.environment?.model) {
|
|
251
|
+
throw new Error('dsh requires environment.provider and environment.model');
|
|
252
|
+
}
|
|
253
|
+
if (!ctx.runtimeToken || !ctx.instanceUrl) throw new Error('dsh requires a Commonly runtime token and instance URL');
|
|
254
|
+
const home = seatHome(ctx);
|
|
255
|
+
await mkdir(home, { recursive: true, mode: 0o700 });
|
|
256
|
+
await chmod(home, 0o700);
|
|
257
|
+
const binary = ctx._dshBinary || 'dsh';
|
|
258
|
+
const sourceEnv = ctx.env || process.env;
|
|
259
|
+
const version = readVersion(binary, childEnvironment(sourceEnv, home, ''));
|
|
260
|
+
if (!TESTED_DSH_VERSIONS.includes(version)) {
|
|
261
|
+
throw new Error(`dsh adapter: installed version ${version || 'unknown'} is not smoke-tested (${TESTED_DSH_VERSIONS.join(', ')})`);
|
|
262
|
+
}
|
|
263
|
+
const keyFile = await resolveProviderKeyFile(ctx.environment.provider, ctx.cwd, 'dsh');
|
|
264
|
+
const tempDir = await mkdtemp(join(tmpdir(), 'commonly-dsh-'));
|
|
265
|
+
await chmod(tempDir, 0o700);
|
|
266
|
+
let proxy;
|
|
267
|
+
try {
|
|
268
|
+
const credential = writeCredentialFile(ctx.runtimeToken, { agentName: 'commonly', root: tempDir });
|
|
269
|
+
proxy = await startProviderProxy({
|
|
270
|
+
provider: ctx.environment.provider, keyFile,
|
|
271
|
+
tokenFile: join(tempDir, 'provider-proxy-token'), adapterLabel: 'dsh',
|
|
272
|
+
});
|
|
273
|
+
const bearer = (await readFile(proxy.tokenFile, 'utf8')).trim();
|
|
274
|
+
const mcp = resolveCommonlyMcp(ctx.environment?.mcp, {
|
|
275
|
+
credentialFile: credential.path, instanceUrl: ctx.instanceUrl,
|
|
276
|
+
});
|
|
277
|
+
const patch = JSON.stringify(buildPatch({
|
|
278
|
+
proxyBaseURL: proxy.baseURL, model: ctx.environment.model,
|
|
279
|
+
cwd: ctx.cwd, mcp, effort: ctx.environment.effort,
|
|
280
|
+
deepseekOfficial: new URL(ctx.environment.provider.baseURL).hostname === 'api.deepseek.com',
|
|
281
|
+
}), null, 2);
|
|
282
|
+
assertPatchHasNoCredentials(patch, [ctx.runtimeToken, bearer]);
|
|
283
|
+
const patchPath = join(tempDir, 'seat.patch.yml');
|
|
284
|
+
await writeFile(patchPath, `${patch}\n`, { mode: 0o600 });
|
|
285
|
+
await chmod(patchPath, 0o600);
|
|
286
|
+
const env = childEnvironment(sourceEnv, home, bearer);
|
|
287
|
+
const resume = await sessionExists(home, ctx.sessionId);
|
|
288
|
+
const fullPrompt = buildMemoryPreamble(prompt, ctx.memoryLongTerm, { freshSession: !resume });
|
|
289
|
+
const args = ['--profile', 'headless', '--patch', patchPath, '--json',
|
|
290
|
+
...(resume ? ['--session-id', ctx.sessionId] : []), fullPrompt];
|
|
291
|
+
const requested = Number(ctx.timeoutMs);
|
|
292
|
+
const timeoutMs = Number.isFinite(requested) && requested > 0
|
|
293
|
+
? Math.min(requested, MAX_TIMEOUT_MS) : MAX_TIMEOUT_MS;
|
|
294
|
+
return await runDsh({
|
|
295
|
+
binary, args, cwd: ctx.cwd, env, timeoutMs,
|
|
296
|
+
credentials: [...spawnCredentials(ctx, []), bearer], spawnImpl: ctx._spawnImpl,
|
|
297
|
+
});
|
|
298
|
+
} finally {
|
|
299
|
+
try { await proxy?.close(); } catch { /* best effort */ }
|
|
300
|
+
await rm(tempDir, { recursive: true, force: true });
|
|
301
|
+
}
|
|
302
|
+
},
|
|
303
|
+
};
|
|
@@ -13,6 +13,7 @@ import codex from './codex.js';
|
|
|
13
13
|
import pi from './pi.js';
|
|
14
14
|
import opencode from './opencode.js';
|
|
15
15
|
import qwen from './qwen.js';
|
|
16
|
+
import dsh from './dsh.js';
|
|
16
17
|
|
|
17
18
|
const ADAPTERS = {
|
|
18
19
|
[stub.name]: stub,
|
|
@@ -21,6 +22,7 @@ const ADAPTERS = {
|
|
|
21
22
|
[pi.name]: pi,
|
|
22
23
|
[opencode.name]: opencode,
|
|
23
24
|
[qwen.name]: qwen,
|
|
25
|
+
[dsh.name]: dsh,
|
|
24
26
|
};
|
|
25
27
|
|
|
26
28
|
export const listAdapterNames = () => Object.keys(ADAPTERS);
|
|
@@ -348,7 +348,7 @@ export const createDaemonSupervisor = ({
|
|
|
348
348
|
}
|
|
349
349
|
if (!adapter) adapter = await resolveAdapter(row.runtime || null);
|
|
350
350
|
if (!adapter) {
|
|
351
|
-
log(`[${row.agentName}] no usable CLI adapter on this machine — install claude, codex, opencode, or
|
|
351
|
+
log(`[${row.agentName}] no usable CLI adapter on this machine — install claude, codex, opencode, qwen, or dsh, or attach manually`);
|
|
352
352
|
return false;
|
|
353
353
|
}
|
|
354
354
|
const environment = environmentFor(row);
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
* pi — stdio servers from the environment spec (adapters/pi.js)
|
|
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
|
+
* dsh — per-spawn --patch with file-backed stdio credentials (adapters/dsh.js)
|
|
21
22
|
* `stub` has no consumption path and must keep being handed `environment: null`.
|
|
22
23
|
*
|
|
23
24
|
* The placeholders are substituted at spawn time by the adapter, so the
|
|
@@ -26,7 +27,7 @@
|
|
|
26
27
|
|
|
27
28
|
import { normalizeSandboxTrust } from './environment.js';
|
|
28
29
|
|
|
29
|
-
export const ADAPTERS_WITH_DEFAULT_MCP = new Set(['claude', 'codex', 'pi', 'opencode', 'qwen']);
|
|
30
|
+
export const ADAPTERS_WITH_DEFAULT_MCP = new Set(['claude', 'codex', 'pi', 'opencode', 'qwen', 'dsh']);
|
|
30
31
|
|
|
31
32
|
/**
|
|
32
33
|
* The adapters that can ENFORCE the default sandbox — a strict subset of the
|