1xops 0.2.1 → 0.2.2

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/README.md CHANGED
@@ -1,13 +1,14 @@
1
1
  # 1xops
2
2
 
3
- Runs the `1xops` command line of [1xops](https://github.com/nnthanh101/1xops) from npm. Needs [uv](https://docs.astral.sh/uv/); the matching Python package version is fetched on first run.
3
+ The `1xops` command line of [1ops by OceanSoft.io](https://github.com/nnthanh101/1xops), native to Node.js: Node 24 or later, no dependencies, nothing else to install.
4
4
 
5
5
  ```bash
6
- npx 1xops doctor
7
- npx 1xops install --yes
8
- npx 1xops config --scope team --connectors aws azure itsm
6
+ npx 1xops doctor # prerequisites and read-only sign-in (account IDs masked)
7
+ npx 1xops install --yes # add the marketplaces and install the plugin
8
+ npx 1xops setup # guided: asks a few questions, writes .env.1xops, shows the diff
9
+ npx 1xops config --scope team --connectors aws azure itsm # shows a diff; add --yes to write
9
10
  ```
10
11
 
11
- All commands and scopes are documented in the [Python package README](https://github.com/nnthanh101/1xops/tree/develop/packages/python).
12
+ The same commands, scopes and `.env.1xops` file as the Python package; both write identical files. Details: [packages/python/README.md](https://github.com/nnthanh101/1xops/tree/develop/packages/python).
12
13
 
13
14
  Licence: Apache-2.0. © 2026 Nhat-Thanh Nguyen (nnthanh101@gmail.com), OceanSoft.io. Licence, trademarks and third-party components: [NOTICE](https://github.com/nnthanh101/1xops/blob/develop/NOTICE).
package/bin/1xops.mjs ADDED
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env node
2
+ // 1xops by OceanSoft.io: set up the 1xops plugin, settings and read-only cloud connectors for an
3
+ // organisation, a team or tenant folder, a project, or one person. Native Node.js; no dependencies.
4
+ import { readFileSync } from 'node:fs';
5
+ import { parseArgs } from 'node:util';
6
+ import * as cmd from '../src/commands.mjs';
7
+ import { DEFAULT_FILE } from '../src/config-file.mjs';
8
+ import { SCOPES } from '../src/settings.mjs';
9
+
10
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
11
+
12
+ const HELP = `Usage: 1xops <command> [options]
13
+
14
+ doctor check prerequisites and read-only sign-in [--aws-profile NAME]
15
+ install add the marketplaces and install the plugin [--scope user|project|local] [--yes]
16
+ setup guided setup: asks questions, writes ${DEFAULT_FILE} [--file PATH]
17
+ config write settings and connectors for a scope [--scope ${SCOPES.join('|')}] [--dir DIR]
18
+ [--out DIR] [--connectors NAME...] [--file PATH] [--yes]
19
+ env print export lines for the values in ${DEFAULT_FILE} [--file PATH]
20
+ profiles list built-in connector profiles
21
+
22
+ Nothing changes unless you pass --yes.`;
23
+
24
+ const argv = process.argv.slice(2);
25
+ if (argv[0] === '--version' || argv[0] === '-V') {
26
+ console.log(`1xops ${version}`);
27
+ process.exit(0);
28
+ }
29
+ const [command, ...rest] = argv;
30
+ if (!command || command === '--help' || command === '-h') {
31
+ console.log(HELP);
32
+ process.exit(command ? 0 : 2);
33
+ }
34
+
35
+ const OPTIONS = {
36
+ doctor: { 'aws-profile': { type: 'string' } },
37
+ install: { scope: { type: 'string', default: 'user' }, yes: { type: 'boolean', default: false } },
38
+ setup: { file: { type: 'string', default: DEFAULT_FILE } },
39
+ config: {
40
+ scope: { type: 'string', default: 'team' },
41
+ dir: { type: 'string', default: '.' },
42
+ out: { type: 'string' },
43
+ connectors: { type: 'string', multiple: true, default: [] },
44
+ file: { type: 'string' },
45
+ yes: { type: 'boolean', default: false },
46
+ },
47
+ env: { file: { type: 'string', default: DEFAULT_FILE } },
48
+ profiles: {},
49
+ };
50
+ if (!(command in OPTIONS)) {
51
+ console.error(`1xops: unknown command '${command}'\n\n${HELP}`);
52
+ process.exit(2);
53
+ }
54
+
55
+ let opts;
56
+ try {
57
+ // --connectors takes one or more names: `--connectors aws azure itsm`
58
+ const expanded = [];
59
+ for (let i = 0; i < rest.length; i++) {
60
+ if (rest[i] !== '--connectors') { expanded.push(rest[i]); continue; }
61
+ while (i + 1 < rest.length && !rest[i + 1].startsWith('--')) expanded.push('--connectors', rest[++i]);
62
+ }
63
+ opts = parseArgs({ args: expanded, options: OPTIONS[command], strict: true }).values;
64
+ } catch (err) {
65
+ console.error(`1xops ${command}: ${err.message}`);
66
+ process.exit(2);
67
+ }
68
+ if (command === 'config' && !SCOPES.includes(opts.scope)) {
69
+ console.error(`1xops config: --scope must be one of ${SCOPES.join(', ')}`);
70
+ process.exit(2);
71
+ }
72
+ if (command === 'install' && !['user', 'project', 'local'].includes(opts.scope)) {
73
+ console.error('1xops install: --scope must be one of user, project, local');
74
+ process.exit(2);
75
+ }
76
+
77
+ const handlers = {
78
+ doctor: () => cmd.doctor(opts, version),
79
+ install: () => cmd.install(opts),
80
+ setup: () => cmd.setup(opts),
81
+ config: () => cmd.config(opts),
82
+ env: () => cmd.env(opts),
83
+ profiles: () => cmd.profiles(),
84
+ };
85
+ process.exit(await handlers[command]());
package/package.json CHANGED
@@ -1,13 +1,18 @@
1
1
  {
2
2
  "name": "1xops",
3
- "version": "0.2.1",
4
- "description": "1xops by OceanSoft.io: runs the 1xops command line (doctor, install, config) through uv.",
3
+ "version": "0.2.2",
4
+ "description": "1xops by OceanSoft.io: set up the 1xops plugin, settings and read-only cloud connectors for an organisation, team or person. Native Node.js, no dependencies.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Nhat-Thanh Nguyen <nnthanh101@gmail.com> (https://www.oceansoft.io)",
7
7
  "homepage": "https://www.oceansoft.io",
8
8
  "repository": { "type": "git", "url": "git+https://github.com/nnthanh101/1xops.git", "directory": "packages/npm" },
9
9
  "bugs": "https://github.com/nnthanh101/1xops/issues",
10
- "bin": { "1xops": "bin/1xops.js" },
11
- "files": ["bin/", "README.md"],
12
- "engines": { "node": ">=24" }
10
+ "type": "module",
11
+ "bin": { "1xops": "bin/1xops.mjs" },
12
+ "files": ["bin", "src", "profiles", "README.md"],
13
+ "engines": { "node": ">=24" },
14
+ "scripts": {
15
+ "test": "node --test --test-reporter=spec",
16
+ "prepack": "rm -rf profiles && mkdir profiles && cp ../python/src/one_xops/profiles/*.json profiles/"
17
+ }
13
18
  }
@@ -0,0 +1,49 @@
1
+ {
2
+ "description": "AWS Labs servers: cost, audit, monitoring, security review (use read-only roles)",
3
+ "mcpServers": {
4
+ "awslabs-billing-cost-management": {
5
+ "args": [
6
+ "awslabs.billing-cost-management-mcp-server==0.0.45"
7
+ ],
8
+ "command": "uvx",
9
+ "env": {
10
+ "AWS_PROFILE": "${AWS_BILLING_PROFILE}",
11
+ "AWS_REGION": "us-east-1",
12
+ "FASTMCP_LOG_LEVEL": "ERROR"
13
+ }
14
+ },
15
+ "awslabs-cloudtrail": {
16
+ "args": [
17
+ "awslabs.cloudtrail-mcp-server==0.1.1"
18
+ ],
19
+ "command": "uvx",
20
+ "env": {
21
+ "AWS_PROFILE": "${AWS_OPERATIONS_PROFILE}",
22
+ "AWS_REGION": "${AWS_REGION}",
23
+ "FASTMCP_LOG_LEVEL": "ERROR"
24
+ }
25
+ },
26
+ "awslabs-cloudwatch": {
27
+ "args": [
28
+ "awslabs.cloudwatch-mcp-server==0.3.1"
29
+ ],
30
+ "command": "uvx",
31
+ "env": {
32
+ "AWS_PROFILE": "${AWS_OPERATIONS_PROFILE}",
33
+ "AWS_REGION": "${AWS_REGION}",
34
+ "FASTMCP_LOG_LEVEL": "ERROR"
35
+ }
36
+ },
37
+ "awslabs-well-architected-security": {
38
+ "args": [
39
+ "awslabs.well-architected-security-mcp-server==0.2.1"
40
+ ],
41
+ "command": "uvx",
42
+ "env": {
43
+ "AWS_PROFILE": "${AWS_OPERATIONS_PROFILE}",
44
+ "AWS_REGION": "${AWS_REGION}",
45
+ "FASTMCP_LOG_LEVEL": "ERROR"
46
+ }
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "description": "Microsoft Azure MCP server, read-only mode",
3
+ "mcpServers": {
4
+ "azure": {
5
+ "args": [
6
+ "-y",
7
+ "@azure/mcp@3.0.0",
8
+ "server",
9
+ "start",
10
+ "--mode",
11
+ "namespace",
12
+ "--read-only"
13
+ ],
14
+ "command": "npx",
15
+ "env": {
16
+ "AZURE_MCP_COLLECT_TELEMETRY": "false",
17
+ "AZURE_SUBSCRIPTION_ID": "${AZURE_SUBSCRIPTION_ID}",
18
+ "AZURE_TENANT_ID": "${AZURE_TENANT_ID}"
19
+ }
20
+ }
21
+ }
22
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "description": "Atlassian Rovo MCP server (Cloud: Jira, Confluence); every call asks first",
3
+ "mcpServers": {
4
+ "atlassian": {
5
+ "type": "http",
6
+ "url": "https://mcp.atlassian.com/v2/mcp"
7
+ }
8
+ },
9
+ "permissions": {
10
+ "ask": [
11
+ "mcp__atlassian__*"
12
+ ]
13
+ }
14
+ }
@@ -0,0 +1,334 @@
1
+ // The 1xops commands: doctor, install, config, env, profiles, setup. Same behaviour as the Python
2
+ // package (packages/python/src/one_xops/cli.py and setup.py). Nothing changes unless --yes is given.
3
+ import { spawnSync } from 'node:child_process';
4
+ import { accessSync, constants, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { createInterface } from 'node:readline/promises';
7
+ import { styleText } from 'node:util';
8
+ import * as cf from './config-file.mjs';
9
+ import * as s from './settings.mjs';
10
+
11
+ const color = (style, text) => styleText(style, text, { stream: process.stdout });
12
+
13
+ export function which(cmd) {
14
+ for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
15
+ const file = path.join(dir, cmd);
16
+ try {
17
+ accessSync(file, constants.X_OK);
18
+ return file;
19
+ } catch {
20
+ // not here
21
+ }
22
+ }
23
+ return null;
24
+ }
25
+
26
+ export function run(cmd, args, timeout = 20000) {
27
+ const p = spawnSync(cmd, args, { encoding: 'utf8', timeout });
28
+ if (p.error) return { code: 1, out: String(p.error.message) };
29
+ return { code: p.status ?? 1, out: (p.stdout || p.stderr || '').trim() };
30
+ }
31
+
32
+ export const mask = (account) => (account.length >= 4 ? `****${account.slice(-4)}` : '****');
33
+
34
+ function table(title, columns, rows) {
35
+ const width = columns.map((c, i) => Math.max(c.length, ...rows.map((r) => String(r[i]).length)));
36
+ const line = (cells) => cells.map((c, i) => String(c).padEnd(width[i])).join(' ');
37
+ console.log(color('bold', title));
38
+ console.log(color('dim', line(columns)));
39
+ for (const r of rows) console.log(line(r));
40
+ }
41
+
42
+ // ── doctor ──────────────────────────────────────────────────────────────────
43
+
44
+ export function checkTools() {
45
+ const tools = [['git', true], [s.HOST, true], ['uv', false], ['npx', false], ['docker', false], ['gh', false], ['aws', false], ['az', false]];
46
+ return tools.map(([name, required]) => {
47
+ const where = which(name);
48
+ if (!where) return [name, required, false, 'not found on PATH'];
49
+ const { code, out } = run(name, ['--version']);
50
+ return [name, required, code === 0, out ? out.split('\n')[0] : where];
51
+ });
52
+ }
53
+
54
+ // Read-only sign-in checks. Account IDs are masked, never printed in full.
55
+ export function checkSignIn(awsProfile) {
56
+ const rows = [];
57
+ if (which('aws')) {
58
+ const args = ['sts', 'get-caller-identity', '--output', 'json', ...(awsProfile ? ['--profile', awsProfile] : [])];
59
+ const { code, out } = run('aws', args);
60
+ if (code === 0) {
61
+ let account = '';
62
+ try { account = JSON.parse(out).Account ?? ''; } catch { /* not JSON */ }
63
+ rows.push(['aws sign-in', false, true, `signed in, account ${mask(account)}`]);
64
+ } else rows.push(['aws sign-in', false, false, 'not signed in (aws sso login)']);
65
+ }
66
+ if (which('az')) {
67
+ const { code } = run('az', ['account', 'show', '--output', 'none']);
68
+ rows.push(['azure sign-in', false, code === 0, code === 0 ? 'signed in' : 'not signed in (az login)']);
69
+ }
70
+ if (which('gh')) {
71
+ const { code } = run('gh', ['auth', 'status']);
72
+ rows.push(['github sign-in', false, code === 0, code === 0 ? 'signed in' : 'not signed in (gh auth login)']);
73
+ }
74
+ return rows;
75
+ }
76
+
77
+ export function doctor(opts, version) {
78
+ const rows = [...checkTools(), ...checkSignIn(opts['aws-profile'])];
79
+ const shown = rows.map(([name, required, ok, detail]) => [
80
+ name,
81
+ required ? 'required' : 'optional',
82
+ ok ? color('green', 'ok') : required ? color('red', 'missing') : color('yellow', 'optional'),
83
+ detail,
84
+ ]);
85
+ table(`1xops ${version} doctor`, ['check', 'needed', 'result', 'detail'], shown);
86
+ const failed = rows.filter((r) => r[1] && !r[2]).map((r) => r[0]);
87
+ if (failed.length) {
88
+ console.log(color('red', `Required: ${failed.join(', ')}`));
89
+ return 1;
90
+ }
91
+ return 0;
92
+ }
93
+
94
+ // ── install ─────────────────────────────────────────────────────────────────
95
+
96
+ const INSTALL_STEPS = [
97
+ [s.HOST, 'plugin', 'marketplace', 'add', 'anthropics/knowledge-work-plugins'],
98
+ [s.HOST, 'plugin', 'marketplace', 'add', 'nnthanh101/1xops'],
99
+ [s.HOST, 'plugin', 'install', '1xops@1xops'],
100
+ ];
101
+
102
+ export function install(opts) {
103
+ if (!which(s.HOST)) {
104
+ console.log(color('red', `'${s.HOST}' CLI not found; run '1xops doctor'.`));
105
+ return 1;
106
+ }
107
+ for (const base of INSTALL_STEPS) {
108
+ const step = [...base, '--scope', opts.scope];
109
+ console.log(color('bold', `$ ${step.join(' ')}`));
110
+ if (!opts.yes) continue;
111
+ const { code, out } = run(step[0], step.slice(1), 180000);
112
+ console.log(out);
113
+ if (code !== 0) return code;
114
+ }
115
+ if (!opts.yes) console.log('Dry run. Re-run with --yes to install.');
116
+ return 0;
117
+ }
118
+
119
+ // ── config ──────────────────────────────────────────────────────────────────
120
+
121
+ // A line diff of two JSON documents (longest common subsequence; settings files are small).
122
+ function diffLines(a, b) {
123
+ const n = a.length, m = b.length;
124
+ const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
125
+ for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) {
126
+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
127
+ }
128
+ const out = [];
129
+ let i = 0, j = 0;
130
+ while (i < n || j < m) {
131
+ if (i < n && j < m && a[i] === b[j]) { out.push(` ${a[i]}`); i++; j++; }
132
+ else if (j < m && (i === n || lcs[i][j + 1] >= lcs[i + 1][j])) out.push(`+${b[j++]}`);
133
+ else out.push(`-${a[i++]}`);
134
+ }
135
+ return out;
136
+ }
137
+
138
+ function showChange(file, before, after) {
139
+ if (s.dumps(before) === s.dumps(after)) {
140
+ console.log(color('dim', `${file}: already up to date`));
141
+ return false;
142
+ }
143
+ console.log(`--- ${file}\n+++ ${file}`);
144
+ for (const l of diffLines(s.dumps(before).trimEnd().split('\n'), s.dumps(after).trimEnd().split('\n'))) {
145
+ if (l[0] !== ' ') console.log(l);
146
+ }
147
+ return true;
148
+ }
149
+
150
+ function write(file, data) {
151
+ mkdirSync(path.dirname(file), { recursive: true });
152
+ const tmp = `${file}.tmp`;
153
+ writeFileSync(tmp, s.dumps(data));
154
+ renameSync(tmp, file);
155
+ }
156
+
157
+ function resolveConfig(opts) {
158
+ if (opts.file) {
159
+ const cfg = cf.load(opts.file);
160
+ return { scope: cfg.scope, project: path.resolve(cfg.dir), out: cfg.out ? path.resolve(cfg.out) : null, connectors: cfg.connectors };
161
+ }
162
+ return {
163
+ scope: opts.scope,
164
+ project: path.resolve(opts.dir),
165
+ out: opts.out ? path.resolve(opts.out) : null,
166
+ connectors: Object.fromEntries((opts.connectors ?? []).map((c) => [c, {}])),
167
+ };
168
+ }
169
+
170
+ export function config(opts) {
171
+ let scope, project, out, profiles;
172
+ try {
173
+ ({ scope, project, out } = resolveConfig(opts));
174
+ profiles = Object.entries(resolveConfig(opts).connectors).map(([name, values]) => [s.loadProfile(name), values]);
175
+ } catch (err) {
176
+ console.log(color('red', err.message));
177
+ return 2;
178
+ }
179
+ const personal = scope === 'local' || scope === 'personal';
180
+ let servers = {};
181
+ let wanted = s.BASELINE;
182
+ for (const [profile, values] of profiles) {
183
+ // Shared files keep ${VAR}; private host config gets the person's values.
184
+ Object.assign(servers, personal ? cf.substitute(profile.mcpServers, values) : profile.mcpServers);
185
+ wanted = s.merge(wanted, { permissions: profile.permissions ?? {} });
186
+ }
187
+
188
+ const planned = [];
189
+ const target = s.settingsPath(scope, project, out);
190
+ const before = s.readJson(target);
191
+ const after = s.merge(before, wanted);
192
+ if (showChange(target, before, after)) planned.push([target, after]);
193
+
194
+ const hostCmds = [];
195
+ if (Object.keys(servers).length) {
196
+ const mcpFile = s.mcpPath(scope, project, out);
197
+ if (mcpFile) {
198
+ const b = s.readJson(mcpFile);
199
+ const a = s.merge(b, { mcpServers: servers });
200
+ if (showChange(mcpFile, b, a)) planned.push([mcpFile, a]);
201
+ } else {
202
+ const hostScope = scope === 'personal' ? 'user' : 'local';
203
+ for (const [name, spec] of Object.entries(servers)) {
204
+ hostCmds.push([s.HOST, 'mcp', 'add-json', '-s', hostScope, name, JSON.stringify(spec)]);
205
+ console.log(color('bold', `$ ${s.HOST} mcp add-json -s ${hostScope} ${name} '…'`));
206
+ }
207
+ }
208
+ }
209
+
210
+ if (!opts.yes) {
211
+ console.log('Dry run. Re-run with --yes to write these changes.');
212
+ return 0;
213
+ }
214
+ if (hostCmds.length && !which(s.HOST)) {
215
+ console.log(color('red', `${scope} scope adds connectors through the '${s.HOST}' CLI, which is not installed. Nothing was written. Install it, or use --scope team.`));
216
+ return 1;
217
+ }
218
+ for (const [file, data] of planned) {
219
+ write(file, data);
220
+ console.log(color('green', `wrote ${file}`));
221
+ }
222
+ for (const cmd of hostCmds) {
223
+ const { code, out: msg } = run(cmd[0], cmd.slice(1));
224
+ console.log(msg);
225
+ if (code !== 0) return code;
226
+ }
227
+ if (scope === 'org') console.log(`Give these files to IT to install in: ${s.managedDir()}`);
228
+ if (!personal && profiles.some(([, v]) => Object.keys(v).length)) {
229
+ console.log('Shared files use ${VAR}. Load your values with: eval "$(1xops env)"');
230
+ }
231
+ return 0;
232
+ }
233
+
234
+ // ── env and profiles ────────────────────────────────────────────────────────
235
+
236
+ const shellQuote = (v) => (/^[A-Za-z0-9@%+=:,./_-]+$/.test(v) ? v : `'${v.replaceAll("'", `'"'"'`)}'`);
237
+
238
+ export function env(opts) {
239
+ let cfg;
240
+ try {
241
+ cfg = cf.load(opts.file);
242
+ } catch (err) {
243
+ console.error(err.message);
244
+ return 2;
245
+ }
246
+ for (const [k, v] of Object.entries(cfg.values)) console.log(`export ${k}=${shellQuote(v)}`);
247
+ return 0;
248
+ }
249
+
250
+ export function profiles() {
251
+ const rows = s.builtinProfiles().map((name) => {
252
+ const p = s.loadProfile(name);
253
+ return [name, Object.keys(p.mcpServers).join(', '), cf.variables(p).join(', ') || '—', p.description ?? ''];
254
+ });
255
+ table('Connector profiles', ['profile', 'servers', 'values (.env.1xops keys)', 'description'], rows);
256
+ console.log("Use your own: a .json file with an 'mcpServers' object, as a connector name.");
257
+ return 0;
258
+ }
259
+
260
+ // ── setup ───────────────────────────────────────────────────────────────────
261
+
262
+ // Read-only lookups that make good defaults: AWS profiles and region, current Azure account.
263
+ function detect() {
264
+ const found = {};
265
+ const ok = (cmd, args) => (which(cmd) ? run(cmd, args) : { code: 1, out: '' });
266
+ const profilesOut = ok('aws', ['configure', 'list-profiles']);
267
+ if (profilesOut.code === 0 && profilesOut.out) found.awsProfiles = profilesOut.out.split(/\s+/);
268
+ const region = process.env.AWS_REGION || (ok('aws', ['configure', 'get', 'region']).code === 0 ? ok('aws', ['configure', 'get', 'region']).out : '');
269
+ if (region) found.AWS_REGION = region;
270
+ const az = ok('az', ['account', 'show', '--query', '{t:tenantId,s:id}', '--output', 'json']);
271
+ if (az.code === 0 && az.out) {
272
+ try {
273
+ const ids = JSON.parse(az.out);
274
+ found.AZURE_TENANT_ID = ids.t;
275
+ found.AZURE_SUBSCRIPTION_ID = ids.s;
276
+ } catch { /* not JSON */ }
277
+ }
278
+ return found;
279
+ }
280
+
281
+ export async function setup(opts) {
282
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false });
283
+ const lines = rl[Symbol.asyncIterator]();
284
+ const ask = async (question, fallback = '') => {
285
+ process.stdout.write(`${question}${fallback ? ` [${fallback}]` : ''}: `);
286
+ const { value, done } = await lines.next();
287
+ const answer = done ? '' : value.trim();
288
+ return answer || fallback;
289
+ };
290
+ const yes = async (question, fallback) => {
291
+ const a = (await ask(`${question} (y/n)`, fallback ? 'y' : 'n')).toLowerCase();
292
+ return a.startsWith('y');
293
+ };
294
+ try {
295
+ const file = opts.file;
296
+ console.log(`${color('bold', '1xops setup')} — non-secret values only; secrets stay in your sign-in.\n`);
297
+ let scope;
298
+ do scope = await ask(`Scope (${s.SCOPES.join(' | ')})`, 'team'); while (!s.SCOPES.includes(scope));
299
+ const conf = { scope };
300
+ if (scope === 'team' || scope === 'local') conf.dir = await ask('Project or tenant folder', '.');
301
+ if (scope === 'org') conf.out = await ask('Folder to write the managed files to', '.');
302
+ const found = detect();
303
+ const connectors = {};
304
+ for (const name of s.builtinProfiles()) {
305
+ const profile = s.loadProfile(name);
306
+ if (!(await yes(`Add ${name}: ${profile.description ?? ''}?`, false))) continue;
307
+ const values = {};
308
+ for (const v of cf.variables(profile)) {
309
+ if (v.endsWith('_PROFILE') && found.awsProfiles) console.log(` AWS profiles on this machine: ${found.awsProfiles.join(', ')}`);
310
+ const value = await ask(` ${v} (blank to skip)`, process.env[v] || found[v] || '');
311
+ if (value) values[v] = value;
312
+ }
313
+ connectors[name] = values;
314
+ }
315
+ const own = await ask('Your own profile .json file (blank to skip)');
316
+ if (own) connectors[own] = {};
317
+ conf.connectors = connectors;
318
+
319
+ const text = cf.dump(conf);
320
+ console.log(`\n${file}\n${text}`);
321
+ if (existsSync(file) && !(await yes(`${file} exists. Replace it?`, false))) return 1;
322
+ if (!(await yes(`Write ${file}?`, true))) return 1;
323
+ writeFileSync(file, text);
324
+ cf.load(file); // same checks as `1xops config --file`
325
+
326
+ console.log('\nChanges this would make:');
327
+ if (config({ file }) !== 0) return 2;
328
+ if (await yes('Apply them now?', false)) return config({ file, yes: true });
329
+ console.log(`Apply later with: 1xops config --file ${file} --yes`);
330
+ return 0;
331
+ } finally {
332
+ rl.close();
333
+ }
334
+ }
@@ -0,0 +1,86 @@
1
+ // .env.1xops: the end-user configuration file. Non-secret values only. Same rules as the Python
2
+ // package (packages/python/src/one_xops/config_file.py):
3
+ // ONEXOPS_SCOPE=team org | team | local | personal
4
+ // ONEXOPS_DIR=. project or tenant folder (team, local)
5
+ // ONEXOPS_CONNECTORS=aws,itsm built-in profiles, or paths to your own .json profiles
6
+ // AWS_REGION=ap-southeast-2 every other KEY=value fills a ${KEY} in the profiles
7
+ import { readFileSync } from 'node:fs';
8
+ import { SCOPES, dumps } from './settings.mjs';
9
+
10
+ export const DEFAULT_FILE = '.env.1xops';
11
+ const VAR = /\$\{([A-Z0-9_]+)(?::-[^}]*)?\}/g;
12
+ const KEY = /^[A-Z_][A-Z0-9_]*$/;
13
+ const SECRET_HINTS = ['TOKEN', 'SECRET', 'PASSWORD', 'API_KEY'];
14
+ const OWN = new Set(['ONEXOPS_SCOPE', 'ONEXOPS_DIR', 'ONEXOPS_OUT', 'ONEXOPS_CONNECTORS']);
15
+
16
+ // Every ${VAR} a profile's servers read, in order of first use.
17
+ export function variables(profile) {
18
+ return [...new Set([...dumps(profile.mcpServers).matchAll(VAR)].map((m) => m[1]))];
19
+ }
20
+
21
+ // Replace ${VAR} / ${VAR:-default} with known values; leave unknown ones as they are.
22
+ export function substitute(value, values) {
23
+ if (typeof value === 'string') return value.replace(VAR, (whole, name) => values[name] ?? whole);
24
+ if (Array.isArray(value)) return value.map((v) => substitute(v, values));
25
+ if (value && typeof value === 'object') {
26
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, substitute(v, values)]));
27
+ }
28
+ return value;
29
+ }
30
+
31
+ // KEY=value lines; '#' comments and blank lines ignored; one pair of surrounding quotes removed.
32
+ export function parse(text, where = '.env') {
33
+ const pairs = {};
34
+ text.split(/\r?\n/).forEach((raw, i) => {
35
+ let line = raw.trim();
36
+ if (!line || line.startsWith('#')) return;
37
+ if (line.startsWith('export ')) line = line.slice(7).trimStart();
38
+ const eq = line.indexOf('=');
39
+ const key = eq === -1 ? line : line.slice(0, eq).trim();
40
+ let value = eq === -1 ? '' : line.slice(eq + 1).trim();
41
+ if (eq === -1 || !KEY.test(key)) throw new Error(`${where}:${i + 1}: expected KEY=value with an upper-case KEY`);
42
+ if (value.length >= 2 && value[0] === value.at(-1) && `'"`.includes(value[0])) value = value.slice(1, -1);
43
+ else value = value.split(' #')[0].trimEnd();
44
+ pairs[key] = value;
45
+ });
46
+ return pairs;
47
+ }
48
+
49
+ // Read and check .env.1xops. Returns {scope, dir, out, connectors: {name: values}, values}.
50
+ export function load(file) {
51
+ const pairs = parse(readFileSync(file, 'utf8'), file);
52
+ for (const key of Object.keys(pairs)) {
53
+ if (key.startsWith('ONEXOPS_') && !OWN.has(key)) {
54
+ throw new Error(`${file}: unknown setting ${key}; use one of ${[...OWN].sort().join(', ')}`);
55
+ }
56
+ if (SECRET_HINTS.some((h) => key.includes(h))) {
57
+ throw new Error(`${file}: ${key} looks like a secret; keep it in your keychain or sign-in, not in this file`);
58
+ }
59
+ }
60
+ const scope = pairs.ONEXOPS_SCOPE ?? 'team';
61
+ if (!SCOPES.includes(scope)) throw new Error(`${file}: ONEXOPS_SCOPE must be one of ${SCOPES.join(', ')}`);
62
+ const values = Object.fromEntries(Object.entries(pairs).filter(([k]) => !OWN.has(k)));
63
+ const names = (pairs.ONEXOPS_CONNECTORS ?? '').split(',').map((c) => c.trim()).filter(Boolean);
64
+ return {
65
+ scope,
66
+ dir: pairs.ONEXOPS_DIR ?? '.',
67
+ out: pairs.ONEXOPS_OUT || null,
68
+ connectors: Object.fromEntries(names.map((n) => [n, values])),
69
+ values,
70
+ };
71
+ }
72
+
73
+ // The .env.1xops text for a config made by `1xops setup`.
74
+ export function dump(config) {
75
+ const lines = [
76
+ '# 1xops: non-secret values only. Secrets stay in AWS SSO, az login or the Atlassian sign-in.',
77
+ `ONEXOPS_SCOPE=${config.scope}`,
78
+ ];
79
+ if (config.dir) lines.push(`ONEXOPS_DIR=${config.dir}`);
80
+ if (config.out) lines.push(`ONEXOPS_OUT=${config.out}`);
81
+ const connectors = config.connectors ?? {};
82
+ lines.push(`ONEXOPS_CONNECTORS=${Object.keys(connectors).join(',')}`);
83
+ const seen = Object.assign({}, ...Object.values(connectors));
84
+ for (const [k, v] of Object.entries(seen)) lines.push(`${k}=${v}`);
85
+ return `${lines.join('\n')}\n`;
86
+ }
@@ -0,0 +1,107 @@
1
+ // Settings and connector files for each scope. Pure functions; the commands do the writing.
2
+ // Same behaviour as the Python package (packages/python/src/one_xops/settings.py).
3
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ export const HOST = 'claude'; // host CLI binary and config folder name (technical identifier)
9
+ export const SCOPES = ['org', 'team', 'local', 'personal'];
10
+
11
+ const MARKETPLACES = {
12
+ '1xops': { source: { source: 'github', repo: 'nnthanh101/1xops' } },
13
+ 'knowledge-work-plugins': { source: { source: 'github', repo: 'anthropics/knowledge-work-plugins' } },
14
+ };
15
+
16
+ // Baseline every scope receives: the plugin, its base dependency, no secret reads,
17
+ // and a person's yes before anything leaves the machine or rewrites history.
18
+ export const BASELINE = {
19
+ extraKnownMarketplaces: MARKETPLACES,
20
+ enabledPlugins: { '1xops@1xops': true, 'operations@knowledge-work-plugins': true },
21
+ permissions: {
22
+ deny: ['Read(./.env)', 'Read(./.env.*)', 'Read(./**/.env)', 'Read(./**/.env.*)'],
23
+ ask: [
24
+ 'Bash(git push *)',
25
+ 'Bash(git reset --hard *)',
26
+ 'Bash(git tag *)',
27
+ 'Bash(gh pr merge *)',
28
+ 'Bash(gh release *)',
29
+ 'Bash(terraform apply *)',
30
+ 'Bash(terraform destroy *)',
31
+ ],
32
+ },
33
+ };
34
+
35
+ export function managedDir() {
36
+ if (process.platform === 'darwin') return '/Library/Application Support/ClaudeCode';
37
+ if (process.platform === 'win32') return 'C:/Program Files/ClaudeCode';
38
+ return '/etc/claude-code';
39
+ }
40
+
41
+ export function settingsPath(scope, project, out) {
42
+ if (scope === 'org') return path.join(out ?? process.cwd(), 'managed-settings.json');
43
+ if (scope === 'team') return path.join(project, `.${HOST}`, 'settings.json');
44
+ if (scope === 'local') return path.join(project, `.${HOST}`, 'settings.local.json');
45
+ if (scope === 'personal') return path.join(os.homedir(), `.${HOST}`, 'settings.json');
46
+ throw new Error(`unknown scope: ${scope}`);
47
+ }
48
+
49
+ // File-based connector scopes. `local` and `personal` go through the host CLI instead.
50
+ export function mcpPath(scope, project, out) {
51
+ if (scope === 'org') return path.join(out ?? process.cwd(), 'managed-mcp.json');
52
+ if (scope === 'team') return path.join(project, '.mcp.json');
53
+ return null;
54
+ }
55
+
56
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
57
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
58
+
59
+ // Add incoming keys without overwriting anything the user already set:
60
+ // objects merge recursively, arrays gain only missing items, existing scalars win.
61
+ export function merge(existing, incoming) {
62
+ const out = { ...existing };
63
+ for (const [key, value] of Object.entries(incoming)) {
64
+ if (!(key in out)) out[key] = value;
65
+ else if (isObject(out[key]) && isObject(value)) out[key] = merge(out[key], value);
66
+ else if (Array.isArray(out[key]) && Array.isArray(value)) {
67
+ out[key] = [...out[key], ...value.filter((v) => !out[key].some((o) => same(o, v)))];
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+
73
+ // The profiles ship inside the npm package (copied in by `npm pack`); in this repository they are
74
+ // read from their one source, the Python package.
75
+ const here = path.dirname(fileURLToPath(import.meta.url));
76
+ const PROFILE_DIRS = [path.join(here, '..', 'profiles'), path.join(here, '..', '..', 'python', 'src', 'one_xops', 'profiles')];
77
+ const profileDir = () => PROFILE_DIRS.find((d) => existsSync(d));
78
+
79
+ export function builtinProfiles() {
80
+ return readdirSync(profileDir()).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)).sort();
81
+ }
82
+
83
+ // A built-in profile name (aws, azure, itsm) or a path to your own JSON file.
84
+ export function loadProfile(nameOrPath) {
85
+ let data;
86
+ if (nameOrPath.endsWith('.json') && existsSync(nameOrPath) && statSync(nameOrPath).isFile()) {
87
+ data = JSON.parse(readFileSync(nameOrPath, 'utf8'));
88
+ } else if (builtinProfiles().includes(nameOrPath)) {
89
+ data = JSON.parse(readFileSync(path.join(profileDir(), `${nameOrPath}.json`), 'utf8'));
90
+ } else {
91
+ throw new Error(
92
+ `unknown profile '${nameOrPath}': use one of ${builtinProfiles().join(', ')} or a path to a .json file with an 'mcpServers' object`,
93
+ );
94
+ }
95
+ if (!isObject(data.mcpServers) || Object.keys(data.mcpServers).length === 0) {
96
+ throw new Error(`profile '${nameOrPath}' has no 'mcpServers' object`);
97
+ }
98
+ return data;
99
+ }
100
+
101
+ export function readJson(file) {
102
+ if (!existsSync(file)) return {};
103
+ const text = readFileSync(file, 'utf8');
104
+ return text.trim() ? JSON.parse(text) : {};
105
+ }
106
+
107
+ export const dumps = (data) => `${JSON.stringify(data, null, 2)}\n`;
package/bin/1xops.js DELETED
@@ -1,15 +0,0 @@
1
- #!/usr/bin/env node
2
- // Runs the 1xops Python CLI at the same version as this package, through uv.
3
- "use strict";
4
- const { spawnSync } = require("node:child_process");
5
- const { version } = require("../package.json");
6
-
7
- // Python 3.14: the newest version AWS Lambda runs in production.
8
- const args = ["tool", "run", "--python", "3.14", "--from", `1xops==${version}`, "1xops", ...process.argv.slice(2)];
9
- const run = spawnSync("uv", args, { stdio: "inherit" });
10
-
11
- if (run.error && run.error.code === "ENOENT") {
12
- console.error("1xops needs uv: https://docs.astral.sh/uv/getting-started/installation/");
13
- process.exit(127);
14
- }
15
- process.exit(run.status ?? 1);