-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
307 lines (293 loc) · 10.6 KB
/
Copy pathcli.ts
File metadata and controls
307 lines (293 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/env node
// deepcode CLI entry point.
// Spec: docs/DEVELOPMENT_PLAN.md §5 / §5a
// M2: onboarding + REPL + slash commands + settings + permissions matcher.
import {
CredentialsStore,
VERSION,
diagnoseSettings,
fileContractWarnings,
loadFileContract,
redact,
} from '@deepcode/core';
import { capabilitiesFor, runAppServer } from '@deepcode/app-server';
import { homedir } from 'node:os';
import { resolve } from 'node:path';
import { runDiagnosticsCommand } from './diagnostics-cmd.js';
import { runHeadless } from './headless.js';
import { runMcpCommand } from './mcp-cmd.js';
import { runOnboarding } from './onboarding.js';
import { helpText, parseArgs } from './parse-args.js';
import { startRepl } from './repl.js';
import { runContractCommand } from './contract-cmd.js';
import { runLedgerCommand } from './ledger-cmd.js';
import { runCronCommand, runSchedulerRun } from './scheduler.js';
import { runTrustCommand } from './trust-cmd.js';
import { TrustStore } from './trust.js';
import { runPluginsCommand, runSkillsCommand } from './list-cmd.js';
import { runSetupToken } from './setup-token.js';
import { runCompletion } from './completion.js';
import { runHooksCommand } from './hooks-cmd.js';
async function main(): Promise<number> {
const args = parseArgs(process.argv.slice(2));
if (args.showVersion) {
process.stdout.write(VERSION + '\n');
return 0;
}
if (args.showHelp) {
process.stdout.write(helpText(VERSION));
return 0;
}
if (args.unknownFlags.length > 0) {
process.stderr.write(`Unknown or invalid flags: ${args.unknownFlags.join(' ')}\n`);
process.stderr.write(`Run \`deepcode --help\` for the full list.\n`);
return 2;
}
// Accepted-but-inert flags. Warn rather than exit: they used to be listed in
// `--help` and may already sit in someone's scripts, but silently ignoring a
// flag the user deliberately passed is worse than a noisy line on stderr.
if (args.unimplementedFlags.length > 0) {
for (const flag of args.unimplementedFlags) {
process.stderr.write(`Warning: ${flag} is not implemented yet and was ignored.\n`);
}
}
// -C / --cd <dir>: change the working directory before anything resolves cwd
// (Codex parity). Done here — after --help/--version short-circuit but before
// every subcommand/REPL/headless path that reads process.cwd() — so a single
// chdir covers them all. Validate eagerly so a bad path fails fast (exit 2)
// instead of surfacing as a confusing error deep in the agent.
if (args.cwd !== undefined) {
try {
process.chdir(args.cwd);
} catch (err) {
process.stderr.write(
`Cannot change to --cd directory "${args.cwd}": ${(err as Error).message}\n`,
);
return 2;
}
}
if (args.doctor) {
return doctor();
}
if (args.upgrade) {
process.stdout.write(`Run: npm i -g @oratis/deepcode@latest\n`);
process.stdout.write(`(The Mac client updates itself; only the CLI needs this.)\n`);
return 0;
}
// Scheduled tasks: `deepcode scheduler run` (fired by launchd) and the
// `deepcode cron <install|uninstall|list|status>` management commands.
if (args.positional[0] === 'scheduler' && args.positional[1] === 'run') {
await runSchedulerRun({ output: process.stdout });
return 0;
}
if (args.positional[0] === 'cron') {
return runCronCommand(args.positional.slice(1), {
output: process.stdout,
errOutput: process.stderr,
});
}
if (args.positional[0] === 'mcp') {
return runMcpCommand(args.positional.slice(1), {
cwd: process.cwd(),
output: process.stdout,
errOutput: process.stderr,
// `mcp serve` has no attached user, so a permissive ambient mode is
// clamped unless --mode says otherwise. Same rule as a scheduled job.
mode: args.mode,
sandbox: args.sandbox,
});
}
if (args.positional[0] === 'app-server') {
await runAppServer({
input: process.stdin,
output: process.stdout,
home: process.env.DEEPCODE_HOME ?? resolve(homedir(), '.deepcode'),
});
return 0;
}
if (args.positional[0] === 'diagnostics') {
const home = process.env.DEEPCODE_HOME ?? resolve(homedir(), '.deepcode');
return runDiagnosticsCommand(args.positional.slice(1), {
home,
cwd: process.cwd(),
output: process.stdout,
errOutput: process.stderr,
});
}
if (args.positional[0] === 'contract') {
return runContractCommand(args.positional.slice(1), {
cwd: process.cwd(),
output: process.stdout,
errOutput: process.stderr,
});
}
if (args.positional[0] === 'ledger') {
return runLedgerCommand(args.positional.slice(1), {
cwd: process.cwd(),
output: process.stdout,
errOutput: process.stderr,
json: args.json,
});
}
if (args.positional[0] === 'trust') {
return runTrustCommand(args.positional.slice(1), {
cwd: process.cwd(),
output: process.stdout,
});
}
if (args.positional[0] === 'hooks') {
return runHooksCommand(args.positional.slice(1), {
cwd: process.cwd(),
output: process.stdout,
errOutput: process.stderr,
});
}
if (args.positional[0] === 'setup-token') {
return runSetupToken({ token: args.positional[1] });
}
if (args.positional[0] === 'plugins') {
return runPluginsCommand(args.positional.slice(1), {
cwd: process.cwd(),
output: process.stdout,
errOutput: process.stderr,
json: args.json,
});
}
if (args.positional[0] === 'skills') {
return runSkillsCommand(args.positional.slice(1), {
cwd: process.cwd(),
output: process.stdout,
errOutput: process.stderr,
json: args.json,
});
}
if (args.positional[0] === 'completion') {
return runCompletion(args.positional.slice(1), {
output: process.stdout,
errOutput: process.stderr,
});
}
// Headless one-shot (-p / --print)
if (args.prompt !== undefined) {
return runHeadless({
output: process.stdout,
errOutput: process.stderr,
cwd: process.cwd(),
prompt: args.prompt,
outputFormat: args.outputFormat,
sandbox: args.sandbox,
mode: args.mode,
model: args.model,
effort: args.effort,
systemPromptOverride: args.systemPrompt,
appendSystemPrompt: args.appendSystemPrompt,
appendSystemPromptFile: args.appendSystemPromptFile,
allowedTools: args.allowedTools,
disallowedTools: args.disallowedTools,
maxTurns: args.maxTurns,
settingsPath: args.settingsFile,
jsonSchema: args.jsonSchema,
includePartialMessages: args.includePartialMessages,
});
}
// Onboarding if no creds
const credsStore = new CredentialsStore();
const existing = await credsStore.load();
if (!existing.apiKey && !existing.authToken && !process.env.DEEPSEEK_API_KEY) {
const result = await runOnboarding({
input: process.stdin,
output: process.stdout,
store: credsStore,
});
if (result.skipped && !result.creds.apiKey && !result.creds.authToken) {
process.stdout.write('Skipped onboarding. Set DEEPSEEK_API_KEY or re-run `deepcode`.\n');
return 0;
}
}
// Otherwise: REPL
return startRepl({
input: process.stdin,
output: process.stdout,
cwd: process.cwd(),
mode: args.mode,
model: args.model,
effort: args.effort,
systemPromptOverride: args.systemPrompt,
appendSystemPrompt: args.appendSystemPrompt,
appendSystemPromptFile: args.appendSystemPromptFile,
allowedTools: args.allowedTools,
disallowedTools: args.disallowedTools,
maxTurns: args.maxTurns,
resume: args.resume,
resumeId: args.resumeId,
continueSession: args.continue,
forkSession: args.forkSession,
bare: args.bare,
noColor: args.noColor,
hideThinking: args.noThinking,
sandbox: args.sandbox,
noPlugins: args.noPlugins,
settingsPath: args.settingsFile,
});
}
async function doctor(): Promise<number> {
const cwd = resolve(process.cwd());
process.stdout.write(`DeepCode v${VERSION}\n`);
process.stdout.write(`Node: ${process.version}\n`);
process.stdout.write(`Platform: ${process.platform} ${process.arch}\n`);
process.stdout.write(`Home: ${homedir()}\n`);
process.stdout.write(`CWD: ${cwd}\n`);
let failed = false;
try {
const store = new CredentialsStore();
const creds = await store.load();
process.stdout.write(`API key: ${redact(creds.apiKey ?? creds.authToken)}\n`);
process.stdout.write(`Base URL: ${creds.baseURL ?? 'https://api.deepseek.com/v1'}\n`);
} catch (err) {
process.stdout.write(`Credentials error: ${(err as Error).message}\n`);
}
try {
const trustStatus = await new TrustStore().statusFor(cwd);
const config = await diagnoseSettings({ cwd, trustStatus });
process.stdout.write(`Configuration trust: ${config.trustStatus}\n`);
for (const layer of config.layers) {
const status = layer.present ? (layer.trusted ? 'active' : 'untrusted') : 'missing';
process.stdout.write(`Config ${layer.layer}: ${status} (${layer.path})\n`);
}
process.stdout.write(
`Config gated: ${config.gated.length ? config.gated.join(', ') : 'none'}\n`,
);
for (const issue of config.issues) {
process.stdout.write(`Config ${issue.severity}: [${issue.code}] ${issue.message}\n`);
if (issue.severity === 'error') failed = true;
}
} catch (error) {
process.stdout.write(`Configuration error: ${(error as Error).message}\n`);
failed = true;
}
// What this runtime may actually do, from the same builder the app-server
// uses — so `doctor` cannot describe a posture the runtime does not have.
try {
const home = process.env.DEEPCODE_HOME ?? resolve(homedir(), '.deepcode');
const caps = await capabilitiesFor(cwd, home);
process.stdout.write(`Sandbox: ${caps.sandbox.mode}\n`);
process.stdout.write(`Write scope: ${caps.writeScope.join(', ') || '(nothing writable)'}\n`);
process.stdout.write(`File contract: ${caps.permissions.fileContract}\n`);
process.stdout.write(`Always confirmed: ${caps.confirmationRequired.join(', ')}\n`);
process.stdout.write(`Ledger: ${caps.ledger.enabled ? caps.ledger.path : 'disabled'}\n`);
const contract = await loadFileContract({ cwd, directory: home });
for (const warning of fileContractWarnings({ ...contract, sandboxMode: caps.sandbox.mode })) {
process.stdout.write(`Warning: ${warning}\n`);
}
} catch (error) {
process.stdout.write(`Capabilities error: ${(error as Error).message}\n`);
}
return failed ? 1 : 0;
}
main().then(
(code) => process.exit(code),
(err) => {
process.stderr.write(`Fatal: ${(err as Error).message}\n`);
process.exit(1);
},
);