insightfulpipe 0.1.4 → 0.2.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0
4
+
5
+ **JSON is now the default output.** It is read by scripts and agents far more often than by eyes.
6
+ `--table` prints the previous human-readable columns. `--json` is still accepted and does nothing, so
7
+ existing scripts, docs and skills keep working unchanged.
8
+
9
+ - Errors follow the same contract: `{"status":"error","message":"…"}` on stderr by default, a plain
10
+ sentence under `--table`. Both still exit 1 and both stay off stdout, so `… | jq` is never polluted.
11
+ Auth and config failures were printing their own text and now go through the same formatter.
12
+ - `accounts` and `sources` show `Workspace ID` and `Brand ID`. Their absence is why customers
13
+ concluded the ids were unavailable — `sources` even advertised "with IDs" while showing only the
14
+ source's own id.
15
+ - New `insightfulpipe use` saves a default workspace/brand, and every query fills them in:
16
+ `use` alone adopts your only workspace, `use -w <id> -b <id>` picks explicitly, `use --clear`
17
+ forgets. `--workspace` / `--brand` override per call, and a body that states the ids is untouched.
18
+ - `brands` no longer requires `-w`: it resolves the saved scope, or your only workspace. It always
19
+ lists brand ids and names.
20
+ - `--version` reports the package version instead of a hardcoded string (it said 0.1.0 while 0.1.4
21
+ shipped).
22
+ - `--help` now teaches ONE form. The 0.1.x shapes (`query_contexts`, `sources`, `query_data`,
23
+ `execute_action`) still run exactly as before — a stored script does not care that they stopped
24
+ being advertised — they are just no longer listed, so a newcomer sees `accounts`, `brands`, `use`,
25
+ `query` and `action` and nothing redundant.
26
+ - Added `test/output-contract.test.js`, which asserts the new defaults, that the legacy shapes are
27
+ hidden from help yet still resolve, and that every 0.1.x command form runs.
28
+
3
29
  ## Unreleased
4
30
 
5
31
  - Refactored the CLI into modular command registration under `src/cli/`
package/README.md CHANGED
@@ -121,7 +121,31 @@ Set a request timeout:
121
121
  node bin/cli.js config --set-timeout 15000
122
122
  ```
123
123
 
124
- Use `--json` with discovery, configuration, and health commands when you want machine-readable output.
124
+ Output is **JSON by default** — it is read by scripts and agents far more often than by eyes. Add
125
+ `--table` when you want the human-readable view:
126
+
127
+ ```bash
128
+ insightfulpipe accounts # JSON
129
+ insightfulpipe accounts --table # aligned columns
130
+ ```
131
+
132
+ `--json` is still accepted and does nothing, so existing scripts and docs keep working. Errors follow
133
+ the same rule: `{"status":"error","message":"…"}` on stderr, or a plain sentence under `--table`.
134
+ Either way they go to stderr and exit 1, so `insightfulpipe … | jq` is never polluted.
135
+
136
+ ### Set your scope once
137
+
138
+ `workspace_id` and `brand_id` are required by most queries. Save them instead of repeating them:
139
+
140
+ ```bash
141
+ insightfulpipe use # adopt your only workspace
142
+ insightfulpipe use -w 299 -b 592 # or pick explicitly
143
+ insightfulpipe brands # brand ids and names
144
+ insightfulpipe query google-ads -b '{"action":"campaigns","account_id":"…"}'
145
+ ```
146
+
147
+ Per-call `--workspace` / `--brand` override the saved scope, and a body that states the ids itself is
148
+ never modified. `insightfulpipe use --clear` forgets them.
125
149
 
126
150
  ## Testing
127
151
 
package/SKILL.md CHANGED
@@ -51,8 +51,11 @@ The `INSIGHTFULPIPE_TOKEN` environment variable should already be configured. Do
51
51
  Every query follows: discover → schema → execute. Run commands directly — do not ask the user for permission to run each one.
52
52
 
53
53
  ```bash
54
- # 1. Get account IDs (workspace_id, brand_id, source IDs)
55
- insightfulpipe accounts --platform <platform> --json
54
+ # 0. (once) Save the workspace/brand so queries do not need the ids
55
+ insightfulpipe use
56
+
57
+ # 1. Get account IDs (workspace_id, brand_id, source IDs) — output is JSON by default
58
+ insightfulpipe accounts --platform <platform>
56
59
 
57
60
  # 2. See available actions
58
61
  insightfulpipe helper <platform>
@@ -74,7 +77,7 @@ insightfulpipe action <platform> -b '{"action":"<action>",...}' --yes
74
77
  ### Google Analytics — Top Pages
75
78
 
76
79
  ```bash
77
- insightfulpipe accounts --platform google-analytics --json
80
+ insightfulpipe accounts --platform google-analytics
78
81
  insightfulpipe helper google-analytics --actions pages
79
82
  insightfulpipe query google-analytics -b '{
80
83
  "action": "pages",
@@ -284,7 +287,7 @@ insightfulpipe prompts google-analytics --id 12 # Get specific prompt
284
287
  ## Gotchas
285
288
 
286
289
  1. **Never guess the request body** — always run `helper <platform> --actions <action>` first.
287
- 2. **Replace ALL "xxx" placeholders** — get real values from `accounts --platform <platform> --json`.
290
+ 2. **Replace ALL "xxx" placeholders** — get real values from `accounts --platform <platform>`.
288
291
  3. **GA property_id needs "properties/" prefix** — use `"properties/510157516"` not `"510157516"`.
289
292
  4. **Date format is YYYY-MM-DD** — use `"2026-03-20"` not `"2026-03-20T00:00:00Z"`.
290
293
  5. **Use `query` for reads, `action --yes` for writes** — using the wrong one will fail.
@@ -300,7 +303,7 @@ insightfulpipe prompts google-analytics --id 12 # Get specific prompt
300
303
  ```bash
301
304
  # Discovery
302
305
  insightfulpipe platforms # All supported platforms
303
- insightfulpipe accounts --platform <platform> --json # Account IDs
306
+ insightfulpipe accounts --platform <platform> # Account IDs
304
307
  insightfulpipe sources --platform <platform> # Sources with IDs
305
308
  insightfulpipe brands --workspace <id> # Brand metadata
306
309
  insightfulpipe whoami # Current user
package/bin/cli.js CHANGED
@@ -8,6 +8,9 @@ try {
8
8
  await program.parseAsync();
9
9
  } catch (error) {
10
10
  const message = error instanceof Error ? error.message : String(error);
11
- console.error(`Error: ${message}`);
11
+ // Output is JSON by default, and a caller parsing stdout must be able to parse failures too.
12
+ // `--table` keeps the plain sentence. Errors go to stderr either way, so `cmd | jq` stays clean.
13
+ const humanOutput = process.argv.includes('--table');
14
+ console.error(humanOutput ? `Error: ${message}` : JSON.stringify({ status: 'error', message }, null, 2));
12
15
  process.exit(1);
13
16
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "insightfulpipe",
3
- "version": "0.1.4",
4
- "description": "InsightfulPipe CLI — query your marketing data from the terminal",
3
+ "version": "0.2.0",
4
+ "description": "InsightfulPipe CLI \u2014 query your marketing data from the terminal",
5
5
  "bin": {
6
6
  "insightfulpipe": "bin/cli.js"
7
7
  },
@@ -38,5 +38,9 @@
38
38
  "dependencies": {
39
39
  "@napi-rs/keyring": "^1.2.0",
40
40
  "commander": "^13.0.0"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/Vqwa/insightful-pipe-cli.git"
41
45
  }
42
46
  }
@@ -51,8 +51,11 @@ The `INSIGHTFULPIPE_TOKEN` environment variable should already be configured. Do
51
51
  Every query follows: discover → schema → execute. Run commands directly — do not ask the user for permission to run each one.
52
52
 
53
53
  ```bash
54
- # 1. Get account IDs (workspace_id, brand_id, source IDs)
55
- insightfulpipe accounts --platform <platform> --json
54
+ # 0. (once) Save the workspace/brand so queries do not need the ids
55
+ insightfulpipe use
56
+
57
+ # 1. Get account IDs (workspace_id, brand_id, source IDs) — output is JSON by default
58
+ insightfulpipe accounts --platform <platform>
56
59
 
57
60
  # 2. See available actions
58
61
  insightfulpipe helper <platform>
@@ -74,7 +77,7 @@ insightfulpipe action <platform> -b '{"action":"<action>",...}' --yes
74
77
  ### Google Analytics — Top Pages
75
78
 
76
79
  ```bash
77
- insightfulpipe accounts --platform google-analytics --json
80
+ insightfulpipe accounts --platform google-analytics
78
81
  insightfulpipe helper google-analytics --actions pages
79
82
  insightfulpipe query google-analytics -b '{
80
83
  "action": "pages",
@@ -284,7 +287,7 @@ insightfulpipe prompts google-analytics --id 12 # Get specific prompt
284
287
  ## Gotchas
285
288
 
286
289
  1. **Never guess the request body** — always run `helper <platform> --actions <action>` first.
287
- 2. **Replace ALL "xxx" placeholders** — get real values from `accounts --platform <platform> --json`.
290
+ 2. **Replace ALL "xxx" placeholders** — get real values from `accounts --platform <platform>`.
288
291
  3. **GA property_id needs "properties/" prefix** — use `"properties/510157516"` not `"510157516"`.
289
292
  4. **Date format is YYYY-MM-DD** — use `"2026-03-20"` not `"2026-03-20T00:00:00Z"`.
290
293
  5. **Use `query` for reads, `action --yes` for writes** — using the wrong one will fail.
@@ -300,7 +303,7 @@ insightfulpipe prompts google-analytics --id 12 # Get specific prompt
300
303
  ```bash
301
304
  # Discovery
302
305
  insightfulpipe platforms # All supported platforms
303
- insightfulpipe accounts --platform <platform> --json # Account IDs
306
+ insightfulpipe accounts --platform <platform> # Account IDs
304
307
  insightfulpipe sources --platform <platform> # Sources with IDs
305
308
  insightfulpipe brands --workspace <id> # Brand metadata
306
309
  insightfulpipe whoami # Current user
package/src/api.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { fail } from './cli/errors.js';
1
2
  import { getApiUrl, getRequestTimeoutMs, getToken } from './config.js';
2
3
 
3
4
  let _insecureWarned = false;
@@ -15,16 +16,14 @@ const PLATFORM_SLUG_RE = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
15
16
 
16
17
  export function validatePlatformSlug(slug) {
17
18
  if (!PLATFORM_SLUG_RE.test(slug) || slug.includes('--')) {
18
- console.error(`Error: Invalid platform slug "${slug}". Use lowercase letters, numbers, and hyphens only.`);
19
- process.exit(1);
19
+ fail(`Invalid platform slug "${slug}". Use lowercase letters, numbers, and hyphens only.`);
20
20
  }
21
21
  }
22
22
 
23
23
  function requireAuth() {
24
24
  const token = getToken();
25
25
  if (!token) {
26
- console.error('Error: Not authenticated. Run: insightfulpipe auth');
27
- process.exit(1);
26
+ fail('Not authenticated.', 'Run: insightfulpipe auth');
28
27
  }
29
28
  return token;
30
29
  }
@@ -1,4 +1,4 @@
1
- import { getConfigSnapshot, getToken } from '../../config.js';
1
+ import { getConfigSnapshot, getContext, getToken, saveContext } from '../../config.js';
2
2
  import { apiGet } from '../../api.js';
3
3
  import { printJson, printTable, wantsJson } from '../../output.js';
4
4
  import {
@@ -61,7 +61,7 @@ export function registerDiscoveryCommands(program) {
61
61
  });
62
62
 
63
63
  program
64
- .command('query_contexts')
64
+ .command('query_contexts', { hidden: true })
65
65
  .argument('[request]', 'One of: accounts, brands, available_actions, actions_details')
66
66
  .description('Retrieve accounts, brands, and action schemas')
67
67
  .option('-r, --request <request>', 'Request type if you prefer flags over the positional argument')
@@ -103,11 +103,13 @@ export function registerDiscoveryCommands(program) {
103
103
 
104
104
  program
105
105
  .command('brands')
106
- .description('List brand metadata for a workspace')
107
- .requiredOption('-w, --workspace <id>', 'Workspace ID')
106
+ .description('List your brands with their IDs')
107
+ .option('-w, --workspace <id>', 'Workspace ID (defaults to the saved scope, or your only workspace)')
108
108
  .option('--brand-ids <ids>', 'Comma-separated brand IDs')
109
109
  .action(async (opts, command) => {
110
- const workspaceId = parseIntegerOption('workspace', opts.workspace);
110
+ const workspaceId = opts.workspace
111
+ ? parseIntegerOption('workspace', opts.workspace)
112
+ : await resolveWorkspaceId();
111
113
  const brandIds = opts.brandIds ? parseIdList(opts.brandIds, 'brand ID') : undefined;
112
114
  const data = await fetchBrandMetadata(workspaceId, brandIds);
113
115
  const brands = Array.isArray(data.brands) ? data.brands : [];
@@ -117,21 +119,16 @@ export function registerDiscoveryCommands(program) {
117
119
  return;
118
120
  }
119
121
 
120
- if (brands.length === 1 || brandIds) {
121
- printJson(brands.length === 1 ? brands[0] : brands);
122
- return;
123
- }
124
-
125
122
  printTable(brands, [
126
- { key: 'id', label: 'ID' },
127
- { key: 'name', label: 'Name' },
123
+ { key: 'id', label: 'Brand ID' },
124
+ { key: 'name', label: 'Brand' },
128
125
  { key: 'website_url', label: 'Website' },
129
126
  ]);
130
127
  });
131
128
 
132
129
  program
133
130
  .command('accounts')
134
- .description('List connected accounts')
131
+ .description('List connected accounts with their workspace and brand IDs')
135
132
  .option('-p, --platform <platform>', 'Filter by platform')
136
133
  .option('--prod', 'Only include production-ready sources')
137
134
  .action(async (opts, command) => {
@@ -152,19 +149,27 @@ export function registerDiscoveryCommands(program) {
152
149
  platform: source.platform || '-',
153
150
  account: sourceDisplayName(source),
154
151
  workspace: source.workspace_name || '-',
152
+ workspaceId: source.workspace_id ?? '-',
153
+ brand: source.brand_name || '-',
154
+ brandId: source.brand_id ?? '-',
155
155
  access: source.access_level || '-',
156
156
  }));
157
157
 
158
+ // The ids are what a query body needs, so they belong in the table a human reads — their
159
+ // absence here is why customers concluded they were not available at all.
158
160
  printTable(rows, [
159
161
  { key: 'platform', label: 'Platform' },
160
162
  { key: 'account', label: 'Account' },
161
163
  { key: 'workspace', label: 'Workspace' },
164
+ { key: 'workspaceId', label: 'Workspace ID' },
165
+ { key: 'brand', label: 'Brand' },
166
+ { key: 'brandId', label: 'Brand ID' },
162
167
  { key: 'access', label: 'Access' },
163
168
  ]);
164
169
  });
165
170
 
166
171
  program
167
- .command('sources')
172
+ .command('sources', { hidden: true })
168
173
  .description('List connected data sources with IDs')
169
174
  .option('-p, --platform <platform>', 'Filter by platform')
170
175
  .option('--prod', 'Only include production-ready sources')
@@ -181,17 +186,21 @@ export function registerDiscoveryCommands(program) {
181
186
  platform: source.platform || '-',
182
187
  name: sourceDisplayName(source),
183
188
  id: sourceIdentifier(source),
184
- workspace: source.workspace_name || '-',
189
+ workspaceId: source.workspace_id ?? '-',
190
+ brandId: source.brand_id ?? '-',
185
191
  brand: source.brand_name || '-',
186
192
  access: source.access_level || '-',
187
193
  }));
188
194
 
195
+ // "ID" is the SOURCE's own id (a customer id, a site url...). The workspace and brand ids are
196
+ // separate, and are the ones a query body asks for.
189
197
  printTable(rows, [
190
198
  { key: 'platform', label: 'Platform' },
191
199
  { key: 'name', label: 'Name' },
192
- { key: 'id', label: 'ID' },
193
- { key: 'workspace', label: 'Workspace' },
200
+ { key: 'id', label: 'Source ID' },
201
+ { key: 'workspaceId', label: 'Workspace ID' },
194
202
  { key: 'brand', label: 'Brand' },
203
+ { key: 'brandId', label: 'Brand ID' },
195
204
  { key: 'access', label: 'Access' },
196
205
  ]);
197
206
  });
@@ -351,3 +360,55 @@ export function registerDiscoveryCommands(program) {
351
360
  }
352
361
  });
353
362
  }
363
+
364
+ /** The workspace to act in: the saved scope first, otherwise the only one this token can see.
365
+ * Asking a user to look up an id they cannot find in the product is what started all of this. */
366
+ async function resolveWorkspaceId() {
367
+ const saved = getContext().workspace_id;
368
+ if (saved) return saved;
369
+
370
+ const data = handleApiError(await apiGet('/user-info/'));
371
+ const workspaces = Array.isArray(data.workspaces) ? data.workspaces : [];
372
+ if (workspaces.length === 1) return workspaces[0].id;
373
+ if (workspaces.length === 0) {
374
+ fail('No workspaces found for this token.');
375
+ }
376
+ fail(
377
+ 'You have access to more than one workspace.',
378
+ 'Pick one with "insightfulpipe use --workspace <id>", or pass -w <id>. Run "insightfulpipe workspaces" to see the ids.',
379
+ );
380
+ }
381
+
382
+ export function registerContextCommand(program) {
383
+ program
384
+ .command('use')
385
+ .description('Show or set the default workspace/brand used by every query')
386
+ .option('-w, --workspace <id>', 'Workspace ID to use by default')
387
+ .option('-b, --brand <id>', 'Brand ID to use by default')
388
+ .option('--clear', 'Forget the saved workspace and brand')
389
+ .action(async (opts, command) => {
390
+ let context;
391
+ if (opts.clear) {
392
+ context = saveContext({ workspaceId: null, brandId: null });
393
+ } else if (opts.workspace || opts.brand) {
394
+ context = saveContext({
395
+ workspaceId: opts.workspace ? parseIntegerOption('workspace', opts.workspace) : undefined,
396
+ brandId: opts.brand ? parseIntegerOption('brand', opts.brand) : undefined,
397
+ });
398
+ } else if (!getContext().workspace_id) {
399
+ // No scope and nothing asked for: adopt the only workspace, so `use` alone is useful.
400
+ context = saveContext({ workspaceId: await resolveWorkspaceId() });
401
+ } else {
402
+ context = getContext();
403
+ }
404
+
405
+ if (wantsJson(command)) {
406
+ printJson({ status: 'success', ...context });
407
+ return;
408
+ }
409
+ printTable([{ workspace: context.workspace_id ?? '-', brand: context.brand_id ?? '-' }], [
410
+ { key: 'workspace', label: 'Workspace ID' },
411
+ { key: 'brand', label: 'Brand ID' },
412
+ ]);
413
+ });
414
+ }
@@ -1,4 +1,5 @@
1
1
  import { apiPost } from '../../api.js';
2
+ import { applyContextToBody } from '../../config.js';
2
3
  import { printJson } from '../../output.js';
3
4
  import {
4
5
  confirmWriteAction,
@@ -6,36 +7,76 @@ import {
6
7
  readJsonInput,
7
8
  } from '../input.js';
8
9
  import { handleApiError } from '../errors.js';
9
- import { withPlatform } from '../options.js';
10
+ import { parseIntegerOption, withPlatform } from '../options.js';
11
+
12
+ /** The saved scope (`insightfulpipe use`) fills in workspace_id/brand_id, and `--workspace`/`--brand`
13
+ * override it for one call. A body that states them itself is never touched. */
14
+ function scopedBody(body, opts) {
15
+ return applyContextToBody(body, {
16
+ workspace_id: opts.workspace ? parseIntegerOption('workspace', opts.workspace) : undefined,
17
+ brand_id: opts.brand ? parseIntegerOption('brand', opts.brand) : undefined,
18
+ });
19
+ }
20
+
21
+ const SCOPE_OPTIONS = [
22
+ ['-w, --workspace <id>', 'Workspace ID for this call (defaults to the saved scope)'],
23
+ ['--brand <id>', 'Brand ID for this call (defaults to the saved scope)'],
24
+ ];
10
25
 
11
26
  export function registerExecutionCommands(program) {
27
+ const readAction = async (platform, opts) => {
28
+ const body = scopedBody(ensureJsonObject(await readJsonInput(opts, true), 'Request body'), opts);
29
+ const data = handleApiError(await apiPost('/', withPlatform(platform, body)));
30
+ printJson(data);
31
+ };
32
+
33
+ const writeAction = async (platform, opts) => {
34
+ const body = scopedBody(ensureJsonObject(await readJsonInput(opts, true), 'Request body'), opts);
35
+ await confirmWriteAction(platform, body, opts.yes);
36
+ const data = handleApiError(await apiPost('/', withPlatform(platform, body)));
37
+ printJson(data);
38
+ };
39
+
12
40
  program
13
- .command('query_data')
14
- .alias('query')
41
+ .command('query')
15
42
  .argument('<platform>', 'Platform slug (e.g., google-analytics, shopify)')
16
43
  .option('-b, --body <json>', 'Request body as inline JSON')
17
44
  .option('-f, --file <path>', 'Request body from a JSON file')
45
+ .option(...SCOPE_OPTIONS[0])
46
+ .option(...SCOPE_OPTIONS[1])
18
47
  .description('Execute a read-only data query for a platform')
19
- .action(async (platform, opts) => {
20
- const body = ensureJsonObject(await readJsonInput(opts, true), 'Request body');
21
- const data = handleApiError(await apiPost('/', withPlatform(platform, body)));
22
- printJson(data);
23
- });
48
+ .action(readAction);
24
49
 
25
50
  program
26
- .command('execute_action')
27
- .alias('action')
51
+ .command('action')
28
52
  .argument('<platform>', 'Platform slug (e.g., facebook-pages, google-ads)')
29
53
  .option('-b, --body <json>', 'Request body as inline JSON')
30
54
  .option('-f, --file <path>', 'Request body from a JSON file')
31
55
  .option('-y, --yes', 'Skip confirmation prompt')
56
+ .option(...SCOPE_OPTIONS[0])
57
+ .option(...SCOPE_OPTIONS[1])
32
58
  .description('Execute a write or mutating action for a platform')
33
- .action(async (platform, opts) => {
34
- const body = ensureJsonObject(await readJsonInput(opts, true), 'Request body');
35
- await confirmWriteAction(platform, body, opts.yes);
36
- const data = handleApiError(await apiPost('/', withPlatform(platform, body)));
37
- printJson(data);
38
- });
59
+ .action(writeAction);
60
+
61
+ // 0.1.x names: still accepted so stored scripts keep running, hidden so help teaches one form.
62
+ program
63
+ .command('query_data', { hidden: true })
64
+ .argument('<platform>')
65
+ .option('-b, --body <json>', 'Request body as inline JSON')
66
+ .option('-f, --file <path>', 'Request body from a JSON file')
67
+ .option(...SCOPE_OPTIONS[0])
68
+ .option(...SCOPE_OPTIONS[1])
69
+ .action(readAction);
70
+
71
+ program
72
+ .command('execute_action', { hidden: true })
73
+ .argument('<platform>')
74
+ .option('-b, --body <json>', 'Request body as inline JSON')
75
+ .option('-f, --file <path>', 'Request body from a JSON file')
76
+ .option('-y, --yes', 'Skip confirmation prompt')
77
+ .option(...SCOPE_OPTIONS[0])
78
+ .option(...SCOPE_OPTIONS[1])
79
+ .action(writeAction);
39
80
 
40
81
  program
41
82
  .command('raw')
package/src/cli/errors.js CHANGED
@@ -1,7 +1,17 @@
1
+ /** Failures follow the same contract as results: JSON by default, a sentence under `--table`.
2
+ * Always on stderr, so `insightfulpipe ... | jq` never sees them either way. */
3
+ function humanOutput() {
4
+ return process.argv.includes('--table');
5
+ }
6
+
1
7
  export function fail(message, tip) {
2
- console.error(`Error: ${message}`);
3
- if (tip) {
4
- console.error(`Tip: ${tip}`);
8
+ if (humanOutput()) {
9
+ console.error(`Error: ${message}`);
10
+ if (tip) {
11
+ console.error(`Tip: ${tip}`);
12
+ }
13
+ } else {
14
+ console.error(JSON.stringify({ status: 'error', message, ...(tip ? { tip } : {}) }, null, 2));
5
15
  }
6
16
  process.exit(1);
7
17
  }
@@ -1,7 +1,15 @@
1
+ import { readFileSync } from 'fs';
2
+ import { dirname, join } from 'path';
3
+ import { fileURLToPath } from 'url';
4
+
1
5
  import { Command } from 'commander';
6
+
7
+ const PACKAGE_VERSION = JSON.parse(
8
+ readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json'), 'utf-8'),
9
+ ).version;
2
10
  import { registerAuthCommand } from './commands/auth.js';
3
11
  import { registerConfigCommand } from './commands/config.js';
4
- import { registerDiscoveryCommands } from './commands/discovery.js';
12
+ import { registerContextCommand, registerDiscoveryCommands } from './commands/discovery.js';
5
13
  import { registerExecutionCommands } from './commands/execution.js';
6
14
 
7
15
  export function buildProgram() {
@@ -11,7 +19,12 @@ export function buildProgram() {
11
19
  .name('insightfulpipe')
12
20
  .description(
13
21
  'InsightfulPipe CLI — query your marketing data from the terminal.\n\n' +
22
+ 'Output is JSON by default; add --table for a human-readable view.\n\n' +
14
23
  'Run "insightfulpipe platforms" to see all supported platforms.\n\n' +
24
+ 'Set your scope once and stop passing ids:\n' +
25
+ ' insightfulpipe use Adopt your only workspace\n' +
26
+ ' insightfulpipe use -w <id> -b <id> Pick a workspace and brand\n' +
27
+ ' insightfulpipe brands Brand ids and names\n\n' +
15
28
  'Query workflow:\n' +
16
29
  ' 1. insightfulpipe accounts --platform <platform>\n' +
17
30
  ' Get workspace_id, brand_id, and source identifiers (e.g. property_id, site_url).\n\n' +
@@ -35,12 +48,14 @@ export function buildProgram() {
35
48
  ' insightfulpipe auth Save your API token (starts with ip_sk_)\n' +
36
49
  ' Or set INSIGHTFULPIPE_TOKEN env var.'
37
50
  )
38
- .version('0.1.0')
39
- .option('--json', 'Print JSON output when supported')
51
+ .version(PACKAGE_VERSION)
52
+ .option('--json', 'Print JSON (default; kept for compatibility)')
53
+ .option('--table', 'Print a human-readable table instead of JSON')
40
54
  .showHelpAfterError();
41
55
 
42
56
  registerAuthCommand(program);
43
57
  registerDiscoveryCommands(program);
58
+ registerContextCommand(program);
44
59
  registerExecutionCommands(program);
45
60
  registerConfigCommand(program);
46
61
 
package/src/config.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs';
2
2
  import { homedir } from 'os';
3
3
  import { join } from 'path';
4
+ import { fail } from './cli/errors.js';
4
5
  import { getTokenFromKeyring, saveTokenToKeyring, isKeyringAvailable } from './keyring.js';
5
6
 
6
7
  const ENV_API_URL = 'INSIGHTFULPIPE_API_URL';
@@ -11,6 +12,10 @@ const DEFAULT_CONFIG = {
11
12
  api_url: 'https://app.insightfulpipe.com',
12
13
  token: null,
13
14
  timeout_ms: 30000,
15
+ // Saved scope: set once with `insightfulpipe use`, then every query fills these in so nobody has
16
+ // to carry ids around by hand. A body that names them explicitly always wins.
17
+ workspace_id: null,
18
+ brand_id: null,
14
19
  };
15
20
 
16
21
  function getConfigDir() {
@@ -29,8 +34,7 @@ function ensureConfigDir() {
29
34
  }
30
35
 
31
36
  function configError(message) {
32
- console.error(`Error: ${message}`);
33
- process.exit(1);
37
+ fail(message);
34
38
  }
35
39
 
36
40
  function normalizeConfig(rawConfig, sourceLabel) {
@@ -58,6 +62,21 @@ function normalizeConfig(rawConfig, sourceLabel) {
58
62
  normalized.timeout_ms = normalizeTimeoutMs(rawConfig.timeout_ms, `${sourceLabel} field "timeout_ms"`);
59
63
  }
60
64
 
65
+ for (const key of ['workspace_id', 'brand_id']) {
66
+ if (key in rawConfig) {
67
+ const value = rawConfig[key];
68
+ if (value === null) {
69
+ normalized[key] = null;
70
+ continue;
71
+ }
72
+ const parsed = Number(value);
73
+ if (!Number.isInteger(parsed) || parsed < 1) {
74
+ configError(`${sourceLabel} field "${key}" must be a positive integer or null.`);
75
+ }
76
+ normalized[key] = parsed;
77
+ }
78
+ }
79
+
61
80
  return normalized;
62
81
  }
63
82
 
@@ -101,6 +120,8 @@ function buildConfigSnapshot() {
101
120
  api_url: Object.hasOwn(stored, 'api_url') ? sourceLabel('file') : sourceLabel('default'),
102
121
  token: Object.hasOwn(stored, 'token') && stored.token ? sourceLabel('file') : sourceLabel('default'),
103
122
  timeout_ms: Object.hasOwn(stored, 'timeout_ms') ? sourceLabel('file') : sourceLabel('default'),
123
+ workspace_id: Object.hasOwn(stored, 'workspace_id') ? sourceLabel('file') : sourceLabel('default'),
124
+ brand_id: Object.hasOwn(stored, 'brand_id') ? sourceLabel('file') : sourceLabel('default'),
104
125
  };
105
126
 
106
127
  // Token priority: env var > keyring > config file
@@ -192,3 +213,34 @@ export function getApiUrl() {
192
213
  export function getRequestTimeoutMs() {
193
214
  return loadConfig().timeout_ms;
194
215
  }
216
+
217
+ /** The saved workspace/brand scope (`insightfulpipe use`). */
218
+ export function getContext() {
219
+ const config = loadConfig();
220
+ return { workspace_id: config.workspace_id ?? null, brand_id: config.brand_id ?? null };
221
+ }
222
+
223
+ /** Merge the saved scope into a request body WITHOUT overriding anything the caller stated. */
224
+ export function applyContextToBody(body, overrides = {}) {
225
+ const context = getContext();
226
+ const next = { ...body };
227
+ const workspaceId = overrides.workspace_id ?? context.workspace_id;
228
+ const brandId = overrides.brand_id ?? context.brand_id;
229
+ if (next.workspace_id === undefined && workspaceId != null) {
230
+ next.workspace_id = workspaceId;
231
+ }
232
+ if (next.brand_id === undefined && brandId != null) {
233
+ next.brand_id = brandId;
234
+ }
235
+ return next;
236
+ }
237
+
238
+ /** Persist (or clear, with null) the saved scope, keeping the rest of the config untouched. */
239
+ export function saveContext({ workspaceId, brandId }) {
240
+ const stored = readStoredConfig();
241
+ const next = { ...stored };
242
+ if (workspaceId !== undefined) next.workspace_id = workspaceId;
243
+ if (brandId !== undefined) next.brand_id = brandId;
244
+ saveConfig(next);
245
+ return getContext();
246
+ }
package/src/output.js CHANGED
@@ -2,8 +2,12 @@ export function printJson(data) {
2
2
  console.log(JSON.stringify(data, null, 2));
3
3
  }
4
4
 
5
+ /** JSON is the CLI's default output: it is read by scripts and agents far more than by eyes.
6
+ * `--table` opts into the human view; `--json` is accepted and does nothing, so every documented
7
+ * command and existing script keeps working unchanged. */
5
8
  export function wantsJson(command) {
6
- return Boolean(command?.optsWithGlobals?.().json);
9
+ const opts = command?.optsWithGlobals?.() ?? {};
10
+ return !opts.table;
7
11
  }
8
12
 
9
13
  export function printTable(rows, columns) {