@crewx/cli 0.9.0-rc.18 → 0.9.0-rc.180

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 (80) hide show
  1. package/dist/bootstrap/codex-writable-roots.d.ts +20 -1
  2. package/dist/bootstrap/codex-writable-roots.js +1 -88
  3. package/dist/bootstrap/crewx-cli.js +1 -63
  4. package/dist/bootstrap/rate-limit-snapshot.d.ts +15 -0
  5. package/dist/bootstrap/rate-limit-snapshot.js +1 -0
  6. package/dist/builtin.d.ts +1 -1
  7. package/dist/builtin.js +5 -127
  8. package/dist/commands/agent.d.ts +1 -0
  9. package/dist/commands/agent.js +3 -246
  10. package/dist/commands/ai-account.d.ts +4 -0
  11. package/dist/commands/ai-account.js +27 -0
  12. package/dist/commands/cal.d.ts +15 -0
  13. package/dist/commands/cal.js +2 -0
  14. package/dist/commands/command-help.d.ts +26 -0
  15. package/dist/commands/command-help.js +52 -0
  16. package/dist/commands/db.d.ts +3 -0
  17. package/dist/commands/db.js +59 -125
  18. package/dist/commands/detached.d.ts +102 -0
  19. package/dist/commands/detached.js +15 -0
  20. package/dist/commands/doctor.d.ts +77 -0
  21. package/dist/commands/doctor.js +4 -196
  22. package/dist/commands/emit-trailer.d.ts +25 -0
  23. package/dist/commands/emit-trailer.js +2 -0
  24. package/dist/commands/execute.d.ts +8 -4
  25. package/dist/commands/execute.js +15 -146
  26. package/dist/commands/hook/command-marker.d.ts +2 -0
  27. package/dist/commands/hook/command-marker.js +1 -0
  28. package/dist/commands/hook/install.d.ts +0 -1
  29. package/dist/commands/hook/install.js +8 -175
  30. package/dist/commands/hook/paths.js +1 -94
  31. package/dist/commands/hook/status.js +1 -86
  32. package/dist/commands/hook/uninstall.js +1 -71
  33. package/dist/commands/hook-dispatch.js +2 -180
  34. package/dist/commands/init.d.ts +34 -0
  35. package/dist/commands/init.js +38 -371
  36. package/dist/commands/kill.d.ts +2 -8
  37. package/dist/commands/kill.js +1 -52
  38. package/dist/commands/log.js +3 -95
  39. package/dist/commands/parse-agent-message.js +1 -52
  40. package/dist/commands/parse-common-flags.d.ts +5 -1
  41. package/dist/commands/parse-common-flags.js +3 -181
  42. package/dist/commands/ps.d.ts +2 -2
  43. package/dist/commands/ps.js +2 -107
  44. package/dist/commands/publish.d.ts +1 -0
  45. package/dist/commands/publish.js +27 -0
  46. package/dist/commands/query.d.ts +7 -2
  47. package/dist/commands/query.js +16 -146
  48. package/dist/commands/registry.js +1 -31
  49. package/dist/commands/resolve-prompt.js +3 -54
  50. package/dist/commands/resolve-recipient.d.ts +14 -0
  51. package/dist/commands/resolve-recipient.js +3 -0
  52. package/dist/commands/restart.d.ts +3 -1
  53. package/dist/commands/restart.js +18 -162
  54. package/dist/commands/result.d.ts +8 -3
  55. package/dist/commands/result.js +1 -70
  56. package/dist/commands/shortcut.d.ts +1 -0
  57. package/dist/commands/shortcut.js +18 -0
  58. package/dist/commands/slack.js +16 -559
  59. package/dist/commands/stop.d.ts +8 -0
  60. package/dist/commands/stop.js +8 -0
  61. package/dist/commands/write-output.js +1 -24
  62. package/dist/index.d.ts +1 -1
  63. package/dist/index.js +1 -5
  64. package/dist/logging.d.ts +1 -1
  65. package/dist/logging.js +10 -86
  66. package/dist/main.d.ts +3 -2
  67. package/dist/main.js +49 -253
  68. package/dist/register-builtin-tools.js +1 -9
  69. package/dist/slack/file-download.js +1 -134
  70. package/dist/slack/markdown.js +1 -33
  71. package/dist/utils/env-defaults.d.ts +2 -5
  72. package/dist/utils/env-defaults.js +1 -10
  73. package/dist/utils/inherited-trace.d.ts +24 -0
  74. package/dist/utils/inherited-trace.js +1 -25
  75. package/dist/utils/product-package-root.d.ts +6 -0
  76. package/dist/utils/product-package-root.js +1 -0
  77. package/dist/utils/sdk-compat.d.ts +24 -0
  78. package/dist/utils/sdk-compat.js +1 -0
  79. package/dist/utils/version.js +1 -28
  80. package/package.json +16 -12
@@ -33,10 +33,29 @@ export declare function escapeTomlBasicString(value: string): string;
33
33
  * Works for both `codex exec` and `codex exec resume` (config-override form).
34
34
  */
35
35
  export declare function buildCodexWritableRootArgs(crewxHome: string): string[];
36
+ /**
37
+ * Create an `AdditionalArgsProvider` that skips Codex's git repository trust
38
+ * check for a resolved workspace.
39
+ *
40
+ * The workspace is resolved by the product layer, so an unavailable workspace
41
+ * must not fall back to the host cwd. The flag is independent of execution
42
+ * mode because it controls repository trust rather than filesystem access.
43
+ */
44
+ export declare function createCodexSkipGitRepoCheckProvider(workspaceRoot: string | undefined): AdditionalArgsProvider;
45
+ /**
46
+ * Compose product-layer argument providers while preserving their order.
47
+ */
48
+ export declare function composeAdditionalArgsProviders(...providers: AdditionalArgsProvider[]): AdditionalArgsProvider;
36
49
  /**
37
50
  * Create an `AdditionalArgsProvider` (SDK extension point, WI-20260703-001)
38
51
  * that injects CrewX home as a Codex writable root for `workspace-write`
39
- * equivalent modes (`agent`, `auto`, `undefined`).
52
+ * equivalent modes (`agent`, `auto`, `undefined`). Only explicit `agent`
53
+ * also receives a permission profile allowing localhost network access and
54
+ * writes to the same CrewX home. `auto`/`undefined` keep their existing policy.
55
+ *
56
+ * All overrides use `-c`, supported by both `exec` and `exec resume`. Keep
57
+ * writable_roots for older Codex versions that ignore permission profiles
58
+ * and fall back to the closed workspace-write sandbox. No version gate.
40
59
  *
41
60
  * No-ops for:
42
61
  * - Non-codex providers.
@@ -1,88 +1 @@
1
- "use strict";
2
- /**
3
- * CLI-layer policy: inject CrewX home as an extra writable root for Codex
4
- * `workspace-write` sandbox invocations.
5
- *
6
- * Why this lives in packages/cli (not packages/sdk):
7
- * CrewX home (`~/.crewx` by default) is a product-specific path. The SDK's
8
- * `additionalArgsProvider` extension point (WI-20260703-001) exists precisely
9
- * so that product layers like this CLI can inject such paths without the SDK
10
- * knowing about them.
11
- *
12
- * Why `-c sandbox_workspace_write.writable_roots=[...]` instead of `--add-dir`:
13
- * Verified against codex-cli 0.139.0 (`codex exec --help` / `codex exec resume --help`):
14
- * - `codex exec` supports `--add-dir <DIR>`.
15
- * - `codex exec resume` does NOT support `--add-dir` (only `-c/--config`).
16
- * Using the `-c` config-override form works identically for both `exec` and
17
- * `exec resume`, avoiding a resume-incompatible flag.
18
- */
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.resolveCrewxHome = resolveCrewxHome;
21
- exports.escapeTomlBasicString = escapeTomlBasicString;
22
- exports.buildCodexWritableRootArgs = buildCodexWritableRootArgs;
23
- exports.createCodexWritableRootsProvider = createCodexWritableRootsProvider;
24
- const os_1 = require("os");
25
- const path_1 = require("path");
26
- /**
27
- * crewx.yaml / query-option `mode` values for which Codex is NOT running in
28
- * (or being pushed into) a `workspace-write`-equivalent sandbox. Injecting an
29
- * extra writable root is meaningless (read-only/plan) or redundant
30
- * (full-access variants already allow writes everywhere) in these modes.
31
- */
32
- const NO_INJECT_MODES = new Set([
33
- 'read-only',
34
- 'plan',
35
- 'agent-full-access',
36
- 'yolo',
37
- 'danger-full-access',
38
- ]);
39
- /**
40
- * Resolve CrewX home directory.
41
- * Priority: `CREWX_HOME` env var → `~/.crewx`.
42
- */
43
- function resolveCrewxHome() {
44
- return process.env.CREWX_HOME ?? (0, path_1.join)((0, os_1.homedir)(), '.crewx');
45
- }
46
- /**
47
- * Escape a string for embedding inside a TOML basic string (`"..."`).
48
- * Sufficient for filesystem paths: handles backslash (Windows paths),
49
- * double-quote, and control characters that could otherwise break TOML
50
- * parsing of the `-c key="value"` override.
51
- */
52
- function escapeTomlBasicString(value) {
53
- return value
54
- .replace(/\\/g, '\\\\')
55
- .replace(/"/g, '\\"')
56
- .replace(/\n/g, '\\n')
57
- .replace(/\r/g, '\\r')
58
- .replace(/\t/g, '\\t');
59
- }
60
- /**
61
- * Build the `-c sandbox_workspace_write.writable_roots=["<path>"]` arg pair.
62
- * Works for both `codex exec` and `codex exec resume` (config-override form).
63
- */
64
- function buildCodexWritableRootArgs(crewxHome) {
65
- const escaped = escapeTomlBasicString(crewxHome);
66
- return ['-c', `sandbox_workspace_write.writable_roots=["${escaped}"]`];
67
- }
68
- function isCodexProvider(ctx) {
69
- return ctx.providerId === 'codex' || ctx.providerStr === 'cli/codex';
70
- }
71
- /**
72
- * Create an `AdditionalArgsProvider` (SDK extension point, WI-20260703-001)
73
- * that injects CrewX home as a Codex writable root for `workspace-write`
74
- * equivalent modes (`agent`, `auto`, `undefined`).
75
- *
76
- * No-ops for:
77
- * - Non-codex providers.
78
- * - Modes in {@link NO_INJECT_MODES} (read-only/plan/agent-full-access/yolo/danger-full-access).
79
- */
80
- function createCodexWritableRootsProvider(crewxHome = resolveCrewxHome()) {
81
- return (ctx) => {
82
- if (!isCodexProvider(ctx))
83
- return [];
84
- if (ctx.mode !== undefined && NO_INJECT_MODES.has(ctx.mode))
85
- return [];
86
- return buildCodexWritableRootArgs(crewxHome);
87
- };
88
- }
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveCrewxHome=i;exports.escapeTomlBasicString=t;exports.buildCodexWritableRootArgs=s;exports.createCodexSkipGitRepoCheckProvider=u;exports.composeAdditionalArgsProviders=p;exports.createCodexWritableRootsProvider=w;const a=require("os");const d=require("path");const l=new Set(["read-only","plan","agent-full-access","yolo","danger-full-access"]);function i(){return process.env.CREWX_HOME??(0,d.join)((0,a.homedir)(),".crewx")}function t(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function s(e){const r=t(e);return["-c",`sandbox_workspace_write.writable_roots=["${r}"]`]}function n(e){return e.providerId==="codex"||e.providerStr==="cli/codex"}function u(e){return r=>{if(!n(r))return[];if(!e)return[];return["--skip-git-repo-check"]}}function p(...e){return r=>e.flatMap(o=>o(r))}function w(e=i()){return r=>{if(!n(r))return[];if(r.mode!==void 0&&l.has(r.mode))return[];const o=s(e);if(r.mode==="agent"){const c=t(e);o.push("-c","default_permissions=crewx","-c",'permissions.crewx.extends=":workspace"',"-c","features.network_proxy=true","-c","permissions.crewx.network.enabled=true","-c","permissions.crewx.network.allow_local_binding=true","-c",'permissions.crewx.network.domains={"localhost"="allow","127.0.0.1"="allow"}',"-c",`permissions.crewx.filesystem={"${c}"="write"}`)}return o}}
@@ -1,63 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createCliCrewx = createCliCrewx;
4
- const fs_1 = require("fs");
5
- const path_1 = require("path");
6
- const os_1 = require("os");
7
- const sdk_1 = require("@crewx/sdk");
8
- const plugins_1 = require("@crewx/sdk/plugins");
9
- const repository_1 = require("@crewx/sdk/repository");
10
- const register_builtin_tools_1 = require("../register-builtin-tools");
11
- const version_1 = require("../utils/version");
12
- const codex_writable_roots_1 = require("./codex-writable-roots");
13
- /**
14
- * Build a Crewx instance with CLI-standard plugins (FileLogger + SqliteTracing)
15
- * and built-in tools registered. Use this from any CLI command that needs a
16
- * Crewx instance — keeps environment consistent across query / execute / slack / agent.
17
- *
18
- * workspaceRoot is always process.cwd()-based so that per-workspace logs land
19
- * in {cwd}/.crewx/logs/. Critical for file:// remote agent delegation.
20
- *
21
- * Behavior:
22
- * - If configPath resolves to an existing file → load it (with built-ins merged)
23
- * - If configPath is NOT set via CREWX_CONFIG env AND the file doesn't exist →
24
- * fall back to built-in-only mode (no user yaml required)
25
- * - If CREWX_CONFIG is explicitly set AND the file doesn't exist → throw
26
- */
27
- async function createCliCrewx(configPath = process.env.CREWX_CONFIG ?? 'crewx.yaml') {
28
- const absConfigPath = (0, path_1.resolve)(configPath);
29
- // workspaceRoot is always cwd-based, never package-internal
30
- const workspaceRoot = process.cwd();
31
- const isExplicitConfig = Boolean(process.env.CREWX_CONFIG);
32
- const fileExists = (0, fs_1.existsSync)(absConfigPath);
33
- let yamlPath;
34
- if (fileExists) {
35
- yamlPath = absConfigPath;
36
- }
37
- else if (isExplicitConfig) {
38
- throw new Error(`[crewx] Config file not found: ${absConfigPath} (set via CREWX_CONFIG)`);
39
- }
40
- else {
41
- yamlPath = undefined;
42
- }
43
- // Run drizzle migrations once at bootstrap — plugin relies on this guarantee.
44
- const dbDir = (0, path_1.join)((0, os_1.homedir)(), '.crewx');
45
- (0, fs_1.mkdirSync)(dbDir, { recursive: true });
46
- const dbPath = (0, path_1.join)(dbDir, 'crewx.db');
47
- const handle = (0, repository_1.openDrizzleDb)(dbPath);
48
- try {
49
- (0, repository_1.runMigrations)(handle.db);
50
- }
51
- finally {
52
- handle.close();
53
- }
54
- const crewx = await sdk_1.Crewx.loadYaml(yamlPath, {
55
- remoteFactory: createCliCrewx,
56
- additionalArgsProvider: (0, codex_writable_roots_1.createCodexWritableRootsProvider)(),
57
- });
58
- (0, register_builtin_tools_1.registerBuiltinToolsIfNeeded)(crewx);
59
- await crewx.use(new plugins_1.ConversationPlugin());
60
- await crewx.use(new plugins_1.FileLoggerPlugin({ version: version_1.CLI_VERSION, workspaceRoot }));
61
- await crewx.use(new plugins_1.SqliteTracingPlugin({ version: version_1.CLI_VERSION }));
62
- return crewx;
63
- }
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createCliCrewx=m;const n=require("fs");const t=require("path");const x=require("os");const s=require("@crewx/sdk");const h=require("@crewx/workflow/list");const a=require("@crewx/sdk/plugins");const l=require("@crewx/sdk/repository");const y=require("../register-builtin-tools");const _=require("../utils/version");const R=require("../utils/inherited-trace");const d=require("./codex-writable-roots");const k=require("./rate-limit-snapshot");async function m(v=process.env.CREWX_CONFIG??"crewx.yaml"){const o=(0,t.resolve)(v);const u=process.cwd();const C=Boolean(process.env.CREWX_CONFIG);const P=(0,n.existsSync)(o);let e;if(P){e=o}else if(C){throw new Error(`[crewx] Config file not found: ${o} (set via CREWX_CONFIG)`)}else{e=void 0}const f=e!==void 0?(0,t.dirname)(o):void 0;const c=process.env.CREWX_DB||(0,t.join)((0,x.homedir)(),".crewx","crewx.db");(0,n.mkdirSync)((0,t.dirname)(c),{recursive:true});const w=(0,l.openDrizzleDb)(c);try{(0,l.runMigrations)(w.db)}finally{w.close()}const r=await s.Crewx.loadYaml(e,{remoteFactory:m,inheritWorktreeOwner:true,additionalArgsProvider:(0,d.composeAdditionalArgsProviders)((0,d.createCodexWritableRootsProvider)(),(0,d.createCodexSkipGitRepoCheckProvider)(f)),onRateLimitObserved:(0,k.createRateLimitSnapshotObserver)()});(0,y.registerBuiltinToolsIfNeeded)(r);r.registerPromptListProvider(s.Crewx.createAgentListPromptResolver(e));r.registerPromptListProvider((0,h.createWorkflowListPromptResolver)(e));await r.use(new a.ConversationPlugin({dbPath:c}));await r.use(new a.FileLoggerPlugin({version:_.CLI_VERSION,workspaceRoot:u}));await r.use(new a.SqliteTracingPlugin({version:_.CLI_VERSION,runnerIdentity:(0,R.consumeInheritedRunnerIdentity)(),inheritWorktreeOwner:true}));const p=e!==void 0?(0,t.dirname)(e):u;const g=(0,s.normalizeWorkspacePath)(p);const i=(0,s.resolveWorkspaceOwnerPath)(p);if(i!==g&&((0,n.existsSync)((0,t.join)(i,"crewx.yaml"))||(0,n.existsSync)((0,t.join)(i,"crewx.yml")))){try{new l.WorkspaceRepository().registerWorkspace(i)}catch{}}return r}
@@ -0,0 +1,15 @@
1
+ import type { ProviderRateLimitObservation } from '@crewx/sdk';
2
+ import { UsageLimitSnapshotRepository } from '@crewx/sdk/repository';
3
+ /** At most one snapshot write per account and window within this window of observations. */
4
+ export declare const RATE_LIMIT_SNAPSHOT_THROTTLE_MS = 30000;
5
+ /**
6
+ * Persists the Claude usage windows observed during a run into usage_limit_snapshots,
7
+ * keyed by the named account that ran it. The server reads tokens only for the default login,
8
+ * so named accounts get their limit history from these observations.
9
+ *
10
+ * Only named accounts are written. The default login's rows belong to the server's oauth
11
+ * writer, which uses the same unique key; writing them here would make the source flip.
12
+ *
13
+ * Observation only: a failed write is logged and never fails or slows the run.
14
+ */
15
+ export declare function createRateLimitSnapshotObserver(sink?: Pick<UsageLimitSnapshotRepository, 'upsert'>): (observation: ProviderRateLimitObservation) => void;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RATE_LIMIT_SNAPSHOT_THROTTLE_MS=void 0;exports.createRateLimitSnapshotObserver=S;const u=require("@crewx/sdk");const _=require("@crewx/sdk/repository");exports.RATE_LIMIT_SNAPSHOT_THROTTLE_MS=3e4;const T=[["five_hour","five_hour"],["seven_day","weekly"]];function S(e=new _.UsageLimitSnapshotRepository){const n=new Map;return t=>{if(t.provider!=="cli/claude")return;if(t.accountId===u.DEFAULT_AI_ACCOUNT_ID)return;const r=t.observedAt.getTime();for(const[a,o]of T){const i=t.windows[a];if(!i)continue;const s=`${t.accountId}:${o}`;const c=n.get(s);if(c!==void 0&&r-c<exports.RATE_LIMIT_SNAPSHOT_THROTTLE_MS)continue;n.set(s,r);try{e.upsert(f(t,o,i))}catch(d){console.error(`[crewx] rate-limit snapshot write failed (${o}): ${I(d)}`)}}}}function f(e,n,t){const r=A(t.utilization);return{id:(0,u.generateId)("uls"),provider:"claude",accountRef:e.accountId,limitWindow:n,bucketStartMs:e.observedAt.getTime(),capturedAt:e.observedAt.toISOString(),usedPercent:r,remainingPercent:100-r,resetsAt:p(t.resetsAt),source:"cli_observed"}}function A(e){return Math.round(Math.min(1,Math.max(0,e))*100)}function p(e){return new Date(e*1e3).toISOString()}function I(e){return e instanceof Error?e.message:String(e)}
package/dist/builtin.d.ts CHANGED
@@ -12,4 +12,4 @@ export declare const BUILTIN_COMMANDS: Set<string>;
12
12
  * Falls back to direct main() call on any tracer failure.
13
13
  */
14
14
  export declare function wrapWithTracer(builtinName: string, main: (args?: string[]) => Promise<void>, args: string[]): Promise<void>;
15
- export declare function handleBuiltin(builtinName: string, args: string[]): Promise<void>;
15
+ export declare function handleBuiltin(builtinName: string, args: string[], productPackageRoot?: string): Promise<void>;
package/dist/builtin.js CHANGED
@@ -1,127 +1,5 @@
1
- "use strict";
2
- /**
3
- * Built-in tool router.
4
- *
5
- * Routes built-in commands (memory, search, doc, etc.) to their respective
6
- * @crewx/* package CLI entry points.
7
- *
8
- * Copied and adapted from packages/cli-bak/src/cli/builtin.handler.ts.
9
- */
10
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- var desc = Object.getOwnPropertyDescriptor(m, k);
13
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
- desc = { enumerable: true, get: function() { return m[k]; } };
15
- }
16
- Object.defineProperty(o, k2, desc);
17
- }) : (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- o[k2] = m[k];
20
- }));
21
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
- Object.defineProperty(o, "default", { enumerable: true, value: v });
23
- }) : function(o, v) {
24
- o["default"] = v;
25
- });
26
- var __importStar = (this && this.__importStar) || (function () {
27
- var ownKeys = function(o) {
28
- ownKeys = Object.getOwnPropertyNames || function (o) {
29
- var ar = [];
30
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
- return ar;
32
- };
33
- return ownKeys(o);
34
- };
35
- return function (mod) {
36
- if (mod && mod.__esModule) return mod;
37
- var result = {};
38
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
- __setModuleDefault(result, mod);
40
- return result;
41
- };
42
- })();
43
- Object.defineProperty(exports, "__esModule", { value: true });
44
- exports.BUILTIN_COMMANDS = void 0;
45
- exports.wrapWithTracer = wrapWithTracer;
46
- exports.handleBuiltin = handleBuiltin;
47
- const BUILTIN_MAP = {
48
- memory: () => Promise.resolve().then(() => __importStar(require('@crewx/memory/cli'))),
49
- search: () => Promise.resolve().then(() => __importStar(require('@crewx/search/cli'))),
50
- doc: () => Promise.resolve().then(() => __importStar(require('@crewx/doc/cli'))),
51
- wbs: () => Promise.resolve().then(() => __importStar(require('@crewx/wbs/cli'))),
52
- cron: () => Promise.resolve().then(() => __importStar(require('@crewx/cron/cli'))),
53
- workflow: () => Promise.resolve().then(() => __importStar(require('@crewx/workflow/cli'))),
54
- skill: () => Promise.resolve().then(() => __importStar(require('@crewx/skill/cli'))),
55
- dreaming: () => Promise.resolve().then(() => __importStar(require('@crewx/dreaming/cli'))),
56
- wi: () => Promise.resolve().then(() => __importStar(require('@crewx/wi/cli'))),
57
- chromex: () => Promise.resolve().then(() => __importStar(require('@crewx/chromex/cli'))),
58
- };
59
- exports.BUILTIN_COMMANDS = new Set(Object.keys(BUILTIN_MAP));
60
- // Load skill-tracer for observability (graceful degradation if unavailable)
61
- async function loadTracer() {
62
- try {
63
- return await Promise.resolve().then(() => __importStar(require('@crewx/shared/skill-tracer')));
64
- }
65
- catch {
66
- return null;
67
- }
68
- }
69
- /**
70
- * Wrap main() with tracer.run() if tracer is available.
71
- * Falls back to direct main() call on any tracer failure.
72
- */
73
- async function wrapWithTracer(builtinName, main, args) {
74
- let tracer = null;
75
- try {
76
- tracer = await loadTracer();
77
- }
78
- catch {
79
- // tracer unavailable — proceed without it
80
- }
81
- if (tracer) {
82
- let mainError = null;
83
- let mainCompleted = false;
84
- try {
85
- await tracer.run(`crewx/${builtinName}`, async () => {
86
- try {
87
- await main(args);
88
- mainCompleted = true;
89
- }
90
- catch (err) {
91
- mainError = err;
92
- throw err;
93
- }
94
- });
95
- return;
96
- }
97
- catch {
98
- if (mainError)
99
- throw mainError;
100
- if (mainCompleted)
101
- return;
102
- // tracer setup error — fall back
103
- }
104
- }
105
- await main(args);
106
- }
107
- async function handleBuiltin(builtinName, args) {
108
- const loader = BUILTIN_MAP[builtinName];
109
- if (!loader) {
110
- console.error(`Unknown built-in tool: ${builtinName}`);
111
- process.exit(1);
112
- }
113
- try {
114
- const mod = await loader();
115
- await wrapWithTracer(builtinName, mod.main.bind(mod), args);
116
- }
117
- catch (err) {
118
- const code = err.code;
119
- if (code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND') {
120
- console.error(`\n Built-in tool '${builtinName}' is not installed.\n`);
121
- console.error(` Install it with:\n`);
122
- console.error(` npm install @crewx/${builtinName}\n`);
123
- process.exit(1);
124
- }
125
- throw err;
126
- }
127
- }
1
+ "use strict";var u=exports&&exports.__createBinding||(Object.create?(function(n,r,i,t){if(t===void 0)t=i;var e=Object.getOwnPropertyDescriptor(r,i);if(!e||("get"in e?!r.__esModule:e.writable||e.configurable)){e={enumerable:true,get:function(){return r[i]}}}Object.defineProperty(n,t,e)}):(function(n,r,i,t){if(t===void 0)t=i;n[t]=r[i]}));var f=exports&&exports.__setModuleDefault||(Object.create?(function(n,r){Object.defineProperty(n,"default",{enumerable:true,value:r})}):function(n,r){n["default"]=r});var o=exports&&exports.__importStar||(function(){var n=function(r){n=Object.getOwnPropertyNames||function(i){var t=[];for(var e in i)if(Object.prototype.hasOwnProperty.call(i,e))t[t.length]=e;return t};return n(r)};return function(r){if(r&&r.__esModule)return r;var i={};if(r!=null){for(var t=n(r),e=0;e<t.length;e++)if(t[e]!=="default")u(i,r,t[e])}f(i,r);return i}})();Object.defineProperty(exports,"__esModule",{value:true});exports.BUILTIN_COMMANDS=void 0;exports.wrapWithTracer=s;exports.handleBuiltin=w;const l={memory:()=>Promise.resolve().then(()=>o(require("@crewx/memory/cli"))),search:()=>Promise.resolve().then(()=>o(require("@crewx/search/cli"))),doc:()=>Promise.resolve().then(()=>o(require("@crewx/doc/cli"))),wbs:()=>Promise.resolve().then(()=>o(require("@crewx/wbs/cli"))),cron:()=>Promise.resolve().then(()=>o(require("@crewx/cron/cli"))),workflow:()=>Promise.resolve().then(()=>o(require("@crewx/workflow/cli"))),skill:()=>Promise.resolve().then(()=>o(require("@crewx/skill/cli"))),dreaming:()=>Promise.resolve().then(()=>o(require("@crewx/dreaming/cli"))),wi:()=>Promise.resolve().then(()=>o(require("@crewx/wi/cli"))),chromex:()=>Promise.resolve().then(()=>o(require("@crewx/chromex/cli"))),notify:()=>Promise.resolve().then(()=>o(require("@crewx/notify/cli"))),app:()=>Promise.resolve().then(()=>o(require("@crewx/app/cli")))};exports.BUILTIN_COMMANDS=new Set(Object.keys(l));async function h(){try{return await Promise.resolve().then(()=>o(require("@crewx/shared/skill-tracer")))}catch{return null}}async function s(n,r,i){let t=null;try{t=await h()}catch{}if(t){let e=null;let a=false;try{await t.run(`crewx/${n}`,async()=>{try{await r(i);a=true}catch(c){e=c;throw c}});return}catch{if(e)throw e;if(a)return}}await r(i)}async function w(n,r,i){const t=l[n];if(!t){console.error(`Unknown built-in tool: ${n}`);process.exit(1)}try{const e=await t();const a=n==="skill"?c=>e.main(c,{productPackageRoot:i}):e.main.bind(e);await s(n,a,r)}catch(e){const a=e.code;if(a==="MODULE_NOT_FOUND"||a==="ERR_MODULE_NOT_FOUND"){console.error(`
2
+ Built-in tool '${n}' is not installed.
3
+ `);console.error(` Install it with:
4
+ `);console.error(` npm install @crewx/${n}
5
+ `);process.exit(1)}throw e}}
@@ -8,5 +8,6 @@
8
8
  * Subcommands:
9
9
  * ls | list | (none) — list agents (default)
10
10
  * prompt <agentId> — print rendered system prompt
11
+ * interceptor test — dry-run an agent's interceptor chain on a text
11
12
  */
12
13
  export declare function handleAgent(args: string[]): Promise<void>;
@@ -1,246 +1,3 @@
1
- "use strict";
2
- /**
3
- * crewx agent handler.
4
- * Dispatches `crewx agent ls` and `crewx agent prompt` subcommands.
5
- */
6
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
- if (k2 === undefined) k2 = k;
8
- var desc = Object.getOwnPropertyDescriptor(m, k);
9
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
- desc = { enumerable: true, get: function() { return m[k]; } };
11
- }
12
- Object.defineProperty(o, k2, desc);
13
- }) : (function(o, m, k, k2) {
14
- if (k2 === undefined) k2 = k;
15
- o[k2] = m[k];
16
- }));
17
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
- Object.defineProperty(o, "default", { enumerable: true, value: v });
19
- }) : function(o, v) {
20
- o["default"] = v;
21
- });
22
- var __importStar = (this && this.__importStar) || (function () {
23
- var ownKeys = function(o) {
24
- ownKeys = Object.getOwnPropertyNames || function (o) {
25
- var ar = [];
26
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
- return ar;
28
- };
29
- return ownKeys(o);
30
- };
31
- return function (mod) {
32
- if (mod && mod.__esModule) return mod;
33
- var result = {};
34
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
- __setModuleDefault(result, mod);
36
- return result;
37
- };
38
- })();
39
- Object.defineProperty(exports, "__esModule", { value: true });
40
- exports.handleAgent = handleAgent;
41
- const path = __importStar(require("path"));
42
- const fs_1 = require("fs");
43
- const crewx_cli_1 = require("../bootstrap/crewx-cli");
44
- const sdk_1 = require("@crewx/sdk");
45
- const skill_1 = require("@crewx/skill");
46
- /**
47
- * Parse a flag from args array.
48
- * Supports both `--flag=value` and `--flag value` forms.
49
- * Returns undefined if flag is not present.
50
- */
51
- function parseFlag(args, flag) {
52
- const prefix = `--${flag}=`;
53
- for (let i = 0; i < args.length; i++) {
54
- if (args[i].startsWith(prefix)) {
55
- return args[i].slice(prefix.length);
56
- }
57
- if (args[i] === `--${flag}` && i + 1 < args.length) {
58
- return args[i + 1];
59
- }
60
- }
61
- return undefined;
62
- }
63
- /**
64
- * Format provider field for display.
65
- */
66
- function formatProvider(provider) {
67
- return Array.isArray(provider) ? provider.join(', ') : provider;
68
- }
69
- /**
70
- * Print the agent list.
71
- */
72
- function printAgentList(agents, total, isFiltered) {
73
- const configPath = process.env.CREWX_CONFIG ?? null;
74
- if (agents.length === 0) {
75
- console.log('WARNING: No agents configured.');
76
- if (!configPath) {
77
- console.log('Set CREWX_CONFIG to point to your crewx.yaml configuration file.');
78
- }
79
- return;
80
- }
81
- const headerCount = isFiltered ? `${agents.length} / ${total}` : `${total}`;
82
- console.log(`Available Agents (${headerCount})\n`);
83
- agents.forEach((agent, index) => {
84
- const headerParts = [`@${agent.id}`];
85
- if (agent.name && agent.name !== agent.id) {
86
- headerParts.push(agent.name);
87
- }
88
- console.log(`${index + 1}. ${headerParts.join(' - ')}`);
89
- console.log(` Provider: ${formatProvider(agent.provider)}`);
90
- const workDir = agent.working_directory ?? agent.workingDirectory ?? '.';
91
- console.log(` Working Dir: ${workDir}`);
92
- if (agent.role) {
93
- console.log(` Role: ${agent.role}`);
94
- }
95
- if (agent.team) {
96
- console.log(` Team: ${agent.team}`);
97
- }
98
- if (agent.description) {
99
- console.log(` Description: ${agent.description}`);
100
- }
101
- if (index < agents.length - 1) {
102
- console.log('');
103
- }
104
- });
105
- const configSource = configPath ? 'External YAML file' : 'Default hardcoded values';
106
- console.log(`\nConfiguration Source: ${configSource}`);
107
- if (configPath) {
108
- console.log(`Config Path: ${configPath}`);
109
- }
110
- else {
111
- console.log('Tip: Set CREWX_CONFIG to point to your crewx.yaml file to customize agents.');
112
- }
113
- }
114
- /**
115
- * Handle `crewx agent ls` — list agents with optional filters.
116
- */
117
- async function handleAgentList(crewx, args) {
118
- const role = parseFlag(args, 'role');
119
- const team = parseFlag(args, 'team');
120
- const provider = parseFlag(args, 'provider');
121
- const isFiltered = !!(role || team || provider);
122
- const total = crewx.agents.size;
123
- const filtered = crewx.filterAgents({ role, team, provider });
124
- printAgentList(filtered, total, isFiltered);
125
- }
126
- /**
127
- * Handle `crewx agent prompt <agentId>` — print fully rendered system prompt.
128
- * Renders Handlebars template variables via Crewx.renderAgentPromptFull().
129
- */
130
- async function handleAgentPrompt(crewx, args) {
131
- // Find the agent id argument (first non-flag arg after 'prompt')
132
- const agentIdRaw = args.find(a => !a.startsWith('--'));
133
- if (!agentIdRaw) {
134
- console.error('Missing agent ID. Usage: crewx agent prompt @agent_name');
135
- process.exit(1);
136
- }
137
- try {
138
- const skills = loadAgentSkills();
139
- const rendered = await crewx.renderAgentPromptFull(agentIdRaw, {
140
- env: process.env,
141
- session: { mode: 'query', platform: 'cli' },
142
- skills,
143
- });
144
- const displayId = agentIdRaw.startsWith('@') ? agentIdRaw.slice(1) : agentIdRaw;
145
- console.log(`\n🤖 **Rendered Prompt for Agent: ${displayId}**\n`);
146
- console.log('--- BEGIN PROMPT ---');
147
- console.log(rendered);
148
- console.log('--- END PROMPT ---');
149
- }
150
- catch (err) {
151
- const message = err instanceof Error ? err.message : String(err);
152
- console.error(`Failed to get agent prompt: ${message}`);
153
- process.exit(1);
154
- }
155
- }
156
- /**
157
- * Handle `crewx agent [subcommand] [options]`.
158
- *
159
- * Subcommands:
160
- * ls | list | (none) — list agents (default)
161
- * prompt <agentId> — print rendered system prompt
162
- */
163
- async function handleAgent(args) {
164
- const configPath = process.env.CREWX_CONFIG ?? 'crewx.yaml';
165
- let crewx;
166
- try {
167
- crewx = await (0, crewx_cli_1.createCliCrewx)(configPath);
168
- }
169
- catch (err) {
170
- if (err instanceof sdk_1.ConfigLoadError && !(0, fs_1.existsSync)(configPath)) {
171
- const subcommand = (args[0] ?? '').toLowerCase();
172
- if (!subcommand || subcommand === 'ls' || subcommand === 'list') {
173
- console.log('WARNING: No agents configured.');
174
- console.log(`No crewx.yaml found. Run 'crewx init' to create one.`);
175
- return;
176
- }
177
- }
178
- throw err;
179
- }
180
- const subcommand = (args[0] ?? '').toLowerCase();
181
- switch (subcommand) {
182
- case 'ls':
183
- case 'list':
184
- await handleAgentList(crewx, args.slice(1));
185
- return;
186
- case '':
187
- // Default: no subcommand → ls
188
- await handleAgentList(crewx, args.slice(1));
189
- return;
190
- case 'prompt':
191
- case 'p':
192
- await handleAgentPrompt(crewx, args.slice(1));
193
- return;
194
- default:
195
- console.error(`Unknown agent subcommand: ${subcommand}`);
196
- printAgentHelp();
197
- process.exit(1);
198
- }
199
- }
200
- /**
201
- * Discover available skills and convert to SkillEntry format for template rendering.
202
- * Searches skills/ and node_modules/@crewx directories.
203
- */
204
- function loadAgentSkills() {
205
- try {
206
- const engine = new skill_1.SkillEngine(process.cwd());
207
- const discovered = engine.discover();
208
- return discovered.map(s => ({
209
- metadata: {
210
- name: s.name,
211
- version: s.version ?? '0.0.0',
212
- description: s.description ?? '',
213
- },
214
- filePath: s.skillMdPath ?? path.join(s.dir, 'SKILL.md'),
215
- }));
216
- }
217
- catch {
218
- return [];
219
- }
220
- }
221
- function printAgentHelp() {
222
- console.log(`
223
- CrewX Agent Management
224
-
225
- Usage:
226
- crewx agent # List configured agents (default)
227
- crewx agent ls # List configured agents
228
- crewx agent list # Alias for ls
229
- crewx agent prompt <id> # Inspect rendered agent prompt
230
-
231
- Filter Options (for agent ls):
232
- --role <value> Filter by agent role (comma-separated for multiple: PM,Dev)
233
- --team <value> Filter by agent team (comma-separated for multiple)
234
- --provider <value> Filter by provider (comma-separated, partial match: claude)
235
-
236
- Examples:
237
- crewx agent
238
- crewx agent ls
239
- crewx agent ls --role=PM
240
- crewx agent ls --team="CrewX Core Team"
241
- crewx agent ls --provider=claude
242
- crewx agent ls --role=PM --provider=claude
243
- crewx agent ls --role=PM,general
244
- CREWX_CONFIG=./crewx.yaml crewx agent list
245
- `.trim());
246
- }
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.handleAgent=y;const f=require("fs");const u=require("../bootstrap/crewx-cli");const g=require("@crewx/sdk");const h=require("./command-help");function a(o,n){const t=`--${n}=`;for(let e=0;e<o.length;e++){if(o[e].startsWith(t)){return o[e].slice(t.length)}if(o[e]===`--${n}`&&e+1<o.length){return o[e+1]}}return void 0}function m(o,n,t){console.log((0,g.formatAgentList)({agents:o,total:n,isFiltered:t,configPath:process.env.CREWX_CONFIG??null}))}async function p(o,n){const t=a(n,"role");const e=a(n,"team");const r=a(n,"provider");const c=!!(t||e||r);const d=o.agents.size;const l=o.filterAgents({role:t,team:e,provider:r});m(l,d,c)}async function x(o,n){const t=n.find(e=>!e.startsWith("--"));if(!t){console.error("Missing agent ID. Usage: crewx agent prompt @agent_name");process.exit(1)}try{const e=await o.renderAgentPromptFull(t,{env:process.env,session:{mode:"query",platform:"cli"}});const r=t.startsWith("@")?t.slice(1):t;console.log(`
2
+ \u{1F916} **Rendered Prompt for Agent: ${r}**
3
+ `);console.log("--- BEGIN PROMPT ---");console.log(e);console.log("--- END PROMPT ---")}catch(e){const r=e instanceof Error?e.message:String(e);console.error(`Failed to get agent prompt: ${r}`);process.exit(1)}}function w(o){const n=[];for(let t=0;t<o.length;t++){const e=o[t];if(e==="--json")continue;if(e.startsWith("--")){if(!e.includes("="))t++;continue}n.push(e)}return n}async function $(o,n){if((n[0]??"").toLowerCase()!=="test"){console.error('Usage: crewx agent interceptor test <agentId> --phase request|response --text "<text>" [--json]');process.exit(1)}const t=n.slice(1);const e=w(t)[0];const r=a(t,"phase");const c=a(t,"text");const d=t.includes("--json");if(!e||r!=="request"&&r!=="response"||c===void 0){console.error('Usage: crewx agent interceptor test <agentId> --phase request|response --text "<text>" [--json]');process.exit(1)}const l=e.startsWith("@")?e.slice(1):e;let i;try{i=await o.testAgentInterceptors(l,r,c)}catch(s){if(s instanceof g.AgentInterceptorConfigError){console.error(`${s.code}: ${s.message}`);process.exit(1)}throw s}if(!i){if(d){console.log(JSON.stringify({agentId:l,phase:r,status:"passed",text:c,changed:false,steps:[]},null,2))}else{console.log(`@${l} has no enabled ${r} interceptors; the text passes unchanged.`)}return}if(d){console.log(JSON.stringify({agentId:l,...i},null,2))}else{console.log(`Interceptor test: @${l} ${r} lane`);for(const s of i.steps){console.log(` [${s.outcome}] ${s.name} (${s.type}, ${s.mode}, failOpen=${s.failOpen}) ${s.durationMs}ms`);if(s.error)console.log(` error ${s.error.code}: ${s.error.message}`);if(s.verdict)console.log(` verdict valid=${s.verdict.valid}${s.verdict.severity?` severity=${s.verdict.severity}`:""}`)}if(i.status==="passed"){console.log(`Final text${i.changed?" (changed)":""}:`);console.log(i.text)}else{console.log(`INTERCEPTOR_BLOCKED: ${i.blocked?.message??"blocked"}`)}}if(i.status==="blocked")process.exit(1)}async function y(o){const n=process.env.CREWX_CONFIG??"crewx.yaml";let t;try{t=await(0,u.createCliCrewx)(n)}catch(r){if(r instanceof g.ConfigLoadError&&!(0,f.existsSync)(n)){const c=(o[0]??"").toLowerCase();if(!c||c==="ls"||c==="list"){console.log("WARNING: No agents configured.");console.log(`No crewx.yaml found. Run 'crewx init' to create one.`);return}}throw r}const e=(o[0]??"").toLowerCase();switch(e){case"ls":case"list":await p(t,o.slice(1));return;case"":await p(t,o.slice(1));return;case"prompt":case"p":await x(t,o.slice(1));return;case"interceptor":await $(t,o.slice(1));return;default:console.error(`Unknown agent subcommand: ${e}`);v();process.exit(1)}}function v(){console.log(h.AGENT_USAGE)}
@@ -0,0 +1,4 @@
1
+ /** Run one `crewx ai-account` subcommand. Returns the process exit code. */
2
+ export declare function runAiAccountCommand(args: string[]): number;
3
+ /** Entry used by main.ts. */
4
+ export declare function handleAiAccount(args: string[]): Promise<void>;
@@ -0,0 +1,27 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.runAiAccountCommand=w;exports.handleAiAccount=y;const f=require("child_process");const s=require("@crewx/sdk");const d=require("./parse-common-flags");const v={claude:"cli/claude","cli/claude":"cli/claude",codex:"cli/codex","cli/codex":"cli/codex"};const u=`Usage:
2
+ crewx ai-account list [--provider claude|codex] [--json]
3
+ crewx ai-account add --provider claude|codex --label <name> [--json]
4
+ crewx ai-account login <id> [--provider claude|codex]
5
+ crewx ai-account status <id> [--provider claude|codex] [--json]
6
+ crewx ai-account use <id> --provider claude|codex
7
+ crewx ai-account remove <id>`;function g(o){if(o===void 0)return void 0;const t=v[o];if(!t)throw new d.UnknownOptionError(`Unknown provider: ${o} (use claude or codex)`);return t}function m(o){const t={positional:[],json:false};for(let i=0;i<o.length;i+=1){const e=o[i];if(e==="--json"){t.json=true}else if(e==="--provider"||e.startsWith("--provider=")){const n=e.includes("=")?e.slice("--provider=".length):o[++i];t.provider=g(n)}else if(e==="--label"||e.startsWith("--label=")){t.label=e.includes("=")?e.slice("--label=".length):o[++i]}else if(e.startsWith("--")){throw new d.UnknownOptionError(`Unknown option: ${e}`)}else{t.positional.push(e)}}return t}function p(o){let t=0;for(const i of o){const e=i.codePointAt(0)??0;const n=e>=4352&&e<=4447||e>=11904&&e<=42191||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65280&&e<=65376;t+=n?2:1}return t}function h(o){const t=o.map(r=>[r.provider,r.id,r.active?"*":"",r.label,r.dir]);const i=["PROVIDER","ID","ACTIVE","LABEL","DIR"];const e=i.map((r,c)=>Math.max(p(r),...t.map(a=>p(a[c]))));const n=r=>r.map((c,a)=>c+" ".repeat(e[a]-p(c))).join(" ").trimEnd();return[n(i),...t.map(n)].join("\n")}function x(o){return o?[o]:["cli/claude","cli/codex"]}function $(o,t,i,e){if(o==="cli/codex"){const a=t.trim();return{loggedIn:i===0,lines:[...a?[a]:[],`loggedIn:${i===0}`,`configDirectory:${e}`]}}let n={};try{n=JSON.parse(t)}catch{}const r=n.loggedIn===true;const c=[`loggedIn:${r}`];if(typeof n.authMethod==="string")c.push(`authMethod:${n.authMethod}`);if(typeof n.subscriptionType==="string")c.push(`subscriptionType:${n.subscriptionType}`);c.push(`configDirectory:${e}`);return{loggedIn:r,lines:c}}function A(o,t,i){const e=(0,s.getStatusInvocation)(o,t);const n=(0,f.spawnSync)(e.command,e.argv,{env:(0,s.applyAiAccountEnv)(process.env,e),encoding:"utf8",timeout:3e4});if(n.error){process.stderr.write(`Could not start ${e.command}: ${n.error.message}
8
+ `);return 2}const r=e.command==="codex"?"cli/codex":"cli/claude";const c=e.env.CLAUDE_CONFIG_DIR??e.env.CODEX_HOME??E(r);const a=r==="cli/codex"?`${n.stdout??""}${n.stderr??""}`:n.stdout??"";const l=$(r,a,n.status??1,c);if(i){process.stdout.write(`${JSON.stringify({id:o,provider:r,loggedIn:l.loggedIn,configDirectory:c})}
9
+ `)}else{process.stdout.write(`${l.lines.join("\n")}
10
+ `)}return l.loggedIn?0:1}function E(o){return(0,s.listAiAccounts)(o).find(t=>t.builtIn)?.dir??""}function O(o,t){const i=(0,s.getLoginInvocation)(o,t);process.stdout.write(`Running official login: ${i.command} ${i.argv.join(" ")}
11
+ `);const e=(0,f.spawnSync)(i.command,i.argv,{env:(0,s.applyAiAccountEnv)(process.env,i),stdio:"inherit"});if(e.error){process.stderr.write(`Could not start ${i.command}: ${e.error.message}
12
+ `);return 2}return e.status??1}function w(o){const[t,...i]=o;const e=m(i);const n=e.positional[0];try{switch(t){case"list":{const r=x(e.provider).flatMap(c=>(0,s.listAiAccounts)(c));process.stdout.write(e.json?`${JSON.stringify(r)}
13
+ `:`${h(r)}
14
+ `);return 0}case"add":{if(!e.provider)throw new d.UnknownOptionError("add requires --provider claude|codex");if(e.label===void 0)throw new d.UnknownOptionError("add requires --label <name>");const r=(0,s.addAiAccount)(e.provider,e.label);if(e.json){process.stdout.write(`${JSON.stringify({provider:e.provider,...r})}
15
+ `)}else{process.stdout.write(`added ${r.id} for ${e.provider}
16
+ configDirectory:${r.dir}
17
+ next: crewx ai-account login ${r.id}
18
+ `)}return 0}case"login":{if(!n)throw new d.UnknownOptionError(`login requires an account id
19
+ ${u}`);return O(n,e.provider)}case"status":{if(!n)throw new d.UnknownOptionError(`status requires an account id
20
+ ${u}`);return A(n,e.provider,e.json)}case"use":{if(!n)throw new d.UnknownOptionError(`use requires an account id
21
+ ${u}`);if(!e.provider)throw new d.UnknownOptionError("use requires --provider claude|codex");(0,s.setActiveAiAccount)(e.provider,n);process.stdout.write(`active account for ${e.provider}: ${n}
22
+ `);return 0}case"remove":{if(!n)throw new d.UnknownOptionError(`remove requires an account id
23
+ ${u}`);const r=(0,s.removeAiAccount)(n);process.stdout.write(`removed ${n} (${r.provider}); its config directory was kept on disk
24
+ `);return 0}default:process.stderr.write(`${u}
25
+ `);return 2}}catch(r){if(r instanceof s.AiAccountError){process.stderr.write(`Error [${r.code}]: ${r.message}
26
+ `);return 2}if(r instanceof d.UnknownOptionError){process.stderr.write(`${r.message}
27
+ `);return 2}throw r}}async function y(o){process.exitCode=w(o)}