ctxpipe 0.1.0-alpha.0 → 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.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -0
  3. package/bin/ctxpipe.js +6 -42
  4. package/dist/auth.d.ts +52 -0
  5. package/dist/auth.js +416 -0
  6. package/dist/auth.js.map +1 -0
  7. package/dist/cli.d.ts +1 -0
  8. package/dist/cli.js +12 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/commands.d.ts +56 -0
  11. package/dist/commands.js +264 -0
  12. package/dist/commands.js.map +1 -0
  13. package/dist/constants.d.ts +8 -0
  14. package/dist/constants.js +19 -0
  15. package/dist/constants.js.map +1 -0
  16. package/dist/fs-operations.d.ts +16 -0
  17. package/dist/fs-operations.js +62 -0
  18. package/dist/fs-operations.js.map +1 -0
  19. package/dist/mcp/json.d.ts +3 -0
  20. package/dist/mcp/json.js +15 -0
  21. package/dist/mcp/json.js.map +1 -0
  22. package/dist/mcp/mcp-operations.d.ts +103 -0
  23. package/dist/mcp/mcp-operations.js +464 -0
  24. package/dist/mcp/mcp-operations.js.map +1 -0
  25. package/dist/mcp/paths.d.ts +7 -0
  26. package/dist/mcp/paths.js +17 -0
  27. package/dist/mcp/paths.js.map +1 -0
  28. package/dist/memory/agentmemory-client.d.ts +24 -0
  29. package/dist/memory/agentmemory-client.js +47 -0
  30. package/dist/memory/agentmemory-client.js.map +1 -0
  31. package/dist/memory/hydration.d.ts +141 -0
  32. package/dist/memory/hydration.js +390 -0
  33. package/dist/memory/hydration.js.map +1 -0
  34. package/dist/memory/index.d.ts +4 -0
  35. package/dist/memory/index.js +5 -0
  36. package/dist/memory/index.js.map +1 -0
  37. package/dist/memory/markdown.d.ts +29 -0
  38. package/dist/memory/markdown.js +193 -0
  39. package/dist/memory/markdown.js.map +1 -0
  40. package/dist/memory/mcp-server.d.ts +48 -0
  41. package/dist/memory/mcp-server.js +322 -0
  42. package/dist/memory/mcp-server.js.map +1 -0
  43. package/dist/memory/paths.d.ts +12 -0
  44. package/dist/memory/paths.js +71 -0
  45. package/dist/memory/paths.js.map +1 -0
  46. package/dist/memory/policy.d.ts +16 -0
  47. package/dist/memory/policy.js +81 -0
  48. package/dist/memory/policy.js.map +1 -0
  49. package/dist/memory/run-hook.d.ts +13 -0
  50. package/dist/memory/run-hook.js +44 -0
  51. package/dist/memory/run-hook.js.map +1 -0
  52. package/dist/memory/run-init.d.ts +11 -0
  53. package/dist/memory/run-init.js +92 -0
  54. package/dist/memory/run-init.js.map +1 -0
  55. package/dist/memory/run-mcp.d.ts +3 -0
  56. package/dist/memory/run-mcp.js +7 -0
  57. package/dist/memory/run-mcp.js.map +1 -0
  58. package/dist/memory/run-meta.d.ts +11 -0
  59. package/dist/memory/run-meta.js +124 -0
  60. package/dist/memory/run-meta.js.map +1 -0
  61. package/dist/memory/supervisor.d.ts +49 -0
  62. package/dist/memory/supervisor.js +217 -0
  63. package/dist/memory/supervisor.js.map +1 -0
  64. package/dist/program.d.ts +1 -0
  65. package/dist/program.js +209 -0
  66. package/dist/program.js.map +1 -0
  67. package/dist/prompts.d.ts +42 -0
  68. package/dist/prompts.js +336 -0
  69. package/dist/prompts.js.map +1 -0
  70. package/dist/system.d.ts +3 -0
  71. package/dist/system.js +27 -0
  72. package/dist/system.js.map +1 -0
  73. package/dist/ui.d.ts +20 -0
  74. package/dist/ui.js +115 -0
  75. package/dist/ui.js.map +1 -0
  76. package/dist/version.d.ts +1 -0
  77. package/dist/version.js +4 -0
  78. package/dist/version.js.map +1 -0
  79. package/package.json +26 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ctxpipe-ai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # ctx| CLI
2
+
3
+ Universal ctx| CLI for initializing repositories and agent integrations. Install and run with **`npx ctxpipe`** (no global install required).
4
+
5
+ ## Human setup
6
+
7
+ ```bash
8
+ npx ctxpipe init
9
+ ```
10
+
11
+ This opens an interactive wizard with repo/global setup scope selection, detected agent defaults, multi-select client setup, and a final change summary before anything is written.
12
+
13
+ If no organization is supplied, the wizard signs you in with a browser/device-code flow, loads your ctx| organizations, and lets you choose one. MCP clients still perform their own OAuth later when they first use ctx|.
14
+
15
+ **Setup credentials:** the CLI stores setup-auth tokens in the **OS keychain** when available (`@napi-rs/keyring`). If the keychain cannot be used (headless Linux, unsupported environment), it falls back to a file under `~/.config/ctxpipe/` and prints a one-time notice to stderr.
16
+
17
+ Auth helpers:
18
+
19
+ ```bash
20
+ npx ctxpipe auth login
21
+ npx ctxpipe auth whoami
22
+ npx ctxpipe auth logout
23
+ ```
24
+
25
+ Use **`npx ctxpipe <command> --help`** for full flags (for example `npx ctxpipe init --help` lists `--base-url`, `--scope`, `--agents`, `--dry-run`, `--json`, `--non-interactive`, and `--no-mcp`).
26
+
27
+ ## Agent and CI setup
28
+
29
+ ```bash
30
+ npx ctxpipe init --org acme --agents codex,claude --scope repo --non-interactive
31
+ npx ctxpipe mcp add --org acme --client cursor --scope user --non-interactive
32
+ npx ctxpipe memory init --agents cursor --non-interactive
33
+ npx ctxpipe doctor --json
34
+ ```
35
+
36
+ ### Local memory only (no remote ctxpipe MCP)
37
+
38
+ ```bash
39
+ npx ctxpipe memory init
40
+ npx ctxpipe memory init --agents cursor --non-interactive
41
+ ```
42
+
43
+ Interactive `memory init` offers optional sign-in or **Continue without login** for local-only save/search. Non-interactive mode defaults `--scope` to `repo` and does not require `--org`.
44
+
45
+ Full init with memory add-on (remote MCP + memory): `npx ctxpipe init --org acme --agents cursor --memory --non-interactive`.
46
+
47
+ This package is in alpha while the interactive setup flow is being built.
48
+
49
+ ## Contributing / repo checkout
50
+
51
+ From this monorepo, after `pnpm install` and `pnpm --filter ctxpipe build`, you can run `node packages/cli/bin/ctxpipe.js …` or `pnpm exec ctxpipe …` from the repo root if linked.
52
+
53
+ ### Testing local memory (CLI / MCP)
54
+
55
+ Mirrors [AgentMemory](https://github.com/rohitg00/agentmemory)’s split: fast unit tests by default, integration on demand.
56
+
57
+ ```bash
58
+ pnpm --filter ctxpipe build
59
+ pnpm --filter ctxpipe test # fast; excludes test/memory/integration-*.test.ts
60
+ pnpm --filter ctxpipe test:memory:integration # real pinned @agentmemory/agentmemory (network on first npx)
61
+ pnpm --filter ctxpipe test:all # fast, then integration (sequential)
62
+ ```
63
+
64
+ CI runs `test` and `test:memory:integration` on every PR ([`.github/workflows/cli-test.yaml`](../../.github/workflows/cli-test.yaml)).
65
+
66
+ When spawning AgentMemory (default integration path), **port 3111** must be free on loopback — the pinned package’s iii-http worker binds there even though ctxpipe allocates other ports per repo. If 3111 is taken locally, free it or set `AGENTMEMORY_URL` to an existing server.
67
+
68
+ Optional — use an already-running AgentMemory server (upstream-style):
69
+
70
+ ```bash
71
+ export AGENTMEMORY_URL=http://127.0.0.1:3111
72
+ export AGENTMEMORY_SECRET=your-local-secret
73
+ pnpm --filter ctxpipe test:memory:integration
74
+ ```
package/bin/ctxpipe.js CHANGED
@@ -1,45 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const args = process.argv.slice(2)
4
- const command = args[0]
3
+ import { runCli } from "../dist/cli.js"
5
4
 
6
- function printHelp() {
7
- console.log(`ctxpipe
8
-
9
- Usage:
10
- ctxpipe init
11
- ctxpipe doctor
12
- ctxpipe mcp add --help
13
-
14
- This early CLI package reserves the ctxpipe command while the interactive setup
15
- experience is being built.
16
- `)
17
- }
18
-
19
- switch (command) {
20
- case undefined:
21
- case "-h":
22
- case "--help":
23
- printHelp()
24
- break
25
- case "init":
26
- console.log(
27
- "ctxpipe init is coming soon. For now, see https://docs.ctxpipe.ai/docs/mcp/mcp-docs",
28
- )
29
- break
30
- case "doctor":
31
- console.log("ctxpipe doctor is coming soon.")
32
- break
33
- case "mcp":
34
- if (args[1] === "add" && (args[2] === "--help" || args[2] === "-h")) {
35
- console.log("ctxpipe mcp add is coming soon.")
36
- break
37
- }
38
- printHelp()
39
- process.exitCode = 1
40
- break
41
- default:
42
- console.error(`Unknown command: ${command}`)
43
- printHelp()
44
- process.exitCode = 1
45
- }
5
+ runCli(process.argv.slice(2)).catch((err) => {
6
+ const message = err instanceof Error ? err.message : String(err)
7
+ console.error(`ctxpipe: ${message}`)
8
+ process.exitCode = 1
9
+ })
package/dist/auth.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ export type StoredAuth = {
2
+ baseUrl: string;
3
+ accessToken: string;
4
+ refreshToken: string | null;
5
+ tokenType: string;
6
+ expiresAt: string | null;
7
+ createdAt: string | null;
8
+ };
9
+ export type Organization = {
10
+ id: string | null;
11
+ name: string | null;
12
+ slug: string;
13
+ };
14
+ export declare function readStoredAuth(baseUrl: string): Promise<StoredAuth | null>;
15
+ export declare function writeStoredAuth(auth: StoredAuth): Promise<void>;
16
+ export declare function removeStoredAuth(baseUrl: string): Promise<void>;
17
+ export declare function authStorePath(baseUrl: string): string;
18
+ export declare function loginWithDeviceFlow({ baseUrl, }: {
19
+ baseUrl?: string;
20
+ }): Promise<StoredAuth>;
21
+ /**
22
+ * Return a non-expired access token for `baseUrl`. Refreshes via the stored
23
+ * `refresh_token` when possible; returns null if no auth is stored or refresh
24
+ * fails (signed-out mode).
25
+ */
26
+ export declare function ensureFreshAccessToken({ baseUrl, now, }: {
27
+ baseUrl: string;
28
+ now?: Date;
29
+ }): Promise<StoredAuth | null>;
30
+ export declare function isExpiringSoon(auth: StoredAuth, now?: Date): boolean;
31
+ /** Read `.ctxpipe/config.json` from cwd or any ancestor; returns null if absent. */
32
+ export type CtxpipeRepoConfig = {
33
+ orgSlug: string | null;
34
+ baseUrl: string | null;
35
+ };
36
+ export declare function readStoredCtxpipeConfig(cwd: string): CtxpipeRepoConfig | null;
37
+ /** CLI `--base-url` wins; otherwise fall back to repo config, then SaaS default. */
38
+ export declare function resolveCtxpipeBaseUrl(cwd: string, cliBaseUrl?: string): string;
39
+ export declare function fetchOrganizations({ baseUrl, accessToken, }: {
40
+ baseUrl: string;
41
+ accessToken: string;
42
+ }): Promise<Organization[]>;
43
+ export declare function fetchSession({ baseUrl, accessToken, }: {
44
+ baseUrl: string;
45
+ accessToken: string;
46
+ }): Promise<Record<string, unknown>>;
47
+ export declare function unwrapBetterAuthData(json: unknown): unknown;
48
+ export declare function authErrorCode(json: unknown): string | null;
49
+ export declare function authErrorMessage(json: unknown, fallback: string): string;
50
+ export declare function orgLabel(org: Organization): string;
51
+ export declare function userLabel(session: Record<string, unknown> | null): string | null;
52
+ export declare function sessionUser(session: Record<string, unknown> | null): Record<string, unknown> | null;
package/dist/auth.js ADDED
@@ -0,0 +1,416 @@
1
+ import { existsSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { AsyncEntry } from "@napi-rs/keyring";
5
+ import { log, spinner } from "@clack/prompts";
6
+ import { AUTH_CLIENT_ID, DEVICE_GRANT_TYPE, DEFAULT_BASE_URL, } from "./constants.js";
7
+ import { readJsonObject } from "./fs-operations.js";
8
+ import { isObject } from "./mcp/json.js";
9
+ import { normalizeBaseUrl } from "./mcp/paths.js";
10
+ import { openBrowser, sleep } from "./system.js";
11
+ import { pathText } from "./ui.js";
12
+ const KEYRING_SERVICE = "ctxpipe";
13
+ let keyringFallbackWarned = false;
14
+ function keyringAccount(baseUrl) {
15
+ return normalizeBaseUrl(baseUrl)
16
+ .replace(/^https?:\/\//, "")
17
+ .replace(/[^a-zA-Z0-9._-]+/g, "_");
18
+ }
19
+ function warnKeyringFallback() {
20
+ if (keyringFallbackWarned)
21
+ return;
22
+ keyringFallbackWarned = true;
23
+ console.error("ctxpipe: could not use the system keyring; credentials will be stored in a local file instead.");
24
+ }
25
+ function authEntry(baseUrl) {
26
+ return new AsyncEntry(KEYRING_SERVICE, keyringAccount(baseUrl));
27
+ }
28
+ function storedAuthFromJsonData(data, baseUrl) {
29
+ if (typeof data.accessToken !== "string" || !data.accessToken)
30
+ return null;
31
+ return {
32
+ baseUrl: typeof data.baseUrl === "string" ? data.baseUrl : normalizeBaseUrl(baseUrl),
33
+ accessToken: data.accessToken,
34
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : null,
35
+ tokenType: typeof data.tokenType === "string" ? data.tokenType : "Bearer",
36
+ expiresAt: typeof data.expiresAt === "string" ? data.expiresAt : null,
37
+ createdAt: typeof data.createdAt === "string" ? data.createdAt : null,
38
+ };
39
+ }
40
+ function readStoredAuthFromFile(baseUrl) {
41
+ const data = readJsonObject(authStorePath(baseUrl));
42
+ return storedAuthFromJsonData(data, baseUrl);
43
+ }
44
+ function writeStoredAuthToFile(auth) {
45
+ const path = authStorePath(auth.baseUrl);
46
+ mkdirSync(dirname(path), { recursive: true });
47
+ writeFileSync(path, `${JSON.stringify(auth, null, 2)}\n`, {
48
+ encoding: "utf8",
49
+ mode: 0o600,
50
+ });
51
+ }
52
+ function removeStoredAuthFromFile(baseUrl) {
53
+ const path = authStorePath(baseUrl);
54
+ if (existsSync(path))
55
+ unlinkSync(path);
56
+ }
57
+ export async function readStoredAuth(baseUrl) {
58
+ try {
59
+ const password = await authEntry(baseUrl).getPassword();
60
+ if (password && password.trim()) {
61
+ const parsed = JSON.parse(password);
62
+ if (isObject(parsed)) {
63
+ const fromKeyring = storedAuthFromJsonData(parsed, baseUrl);
64
+ if (fromKeyring)
65
+ return fromKeyring;
66
+ }
67
+ }
68
+ }
69
+ catch {
70
+ // fall through to file
71
+ }
72
+ return readStoredAuthFromFile(baseUrl);
73
+ }
74
+ export async function writeStoredAuth(auth) {
75
+ try {
76
+ await authEntry(auth.baseUrl).setPassword(JSON.stringify(auth));
77
+ removeStoredAuthFromFile(auth.baseUrl);
78
+ }
79
+ catch {
80
+ warnKeyringFallback();
81
+ writeStoredAuthToFile(auth);
82
+ }
83
+ }
84
+ export async function removeStoredAuth(baseUrl) {
85
+ try {
86
+ await authEntry(baseUrl).deletePassword();
87
+ }
88
+ catch {
89
+ // ignore missing keyring entry
90
+ }
91
+ removeStoredAuthFromFile(baseUrl);
92
+ }
93
+ export function authStorePath(baseUrl) {
94
+ const safeBase = keyringAccount(baseUrl);
95
+ return join(homedir(), ".config", "ctxpipe", `${safeBase}.auth.json`);
96
+ }
97
+ export async function loginWithDeviceFlow({ baseUrl = DEFAULT_BASE_URL, }) {
98
+ const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
99
+ const signInSpinner = spinner();
100
+ signInSpinner.start("Starting ctx| sign-in");
101
+ let device;
102
+ try {
103
+ device = await requestDeviceCode(normalizedBaseUrl);
104
+ signInSpinner.stop("Sign-in request ready");
105
+ }
106
+ catch (error) {
107
+ signInSpinner.stop("Could not start sign-in");
108
+ throw error;
109
+ }
110
+ const verificationUrl = absoluteUrl(stringField(device, "verification_uri_complete") ??
111
+ requiredString(device, "verification_uri"), normalizedBaseUrl);
112
+ const userCode = stringField(device, "user_code");
113
+ log.step("Open this URL");
114
+ log.message(pathText(verificationUrl));
115
+ if (userCode && !stringField(device, "verification_uri_complete")) {
116
+ log.step("Enter code");
117
+ log.message(userCode);
118
+ }
119
+ openBrowser(verificationUrl);
120
+ const approvalSpinner = spinner();
121
+ approvalSpinner.start("Waiting for approval in your browser");
122
+ let token;
123
+ try {
124
+ token = await pollDeviceToken({
125
+ baseUrl: normalizedBaseUrl,
126
+ deviceCode: requiredString(device, "device_code"),
127
+ interval: Number(device.interval ?? 5),
128
+ });
129
+ approvalSpinner.stop("Approved");
130
+ }
131
+ catch (error) {
132
+ approvalSpinner.stop("Approval did not complete");
133
+ throw error;
134
+ }
135
+ const auth = {
136
+ baseUrl: normalizedBaseUrl,
137
+ accessToken: requiredString(token, "access_token"),
138
+ refreshToken: stringField(token, "refresh_token"),
139
+ tokenType: stringField(token, "token_type") ?? "Bearer",
140
+ expiresAt: typeof token.expires_in === "number"
141
+ ? new Date(Date.now() + token.expires_in * 1000).toISOString()
142
+ : null,
143
+ createdAt: new Date().toISOString(),
144
+ };
145
+ await writeStoredAuth(auth);
146
+ return auth;
147
+ }
148
+ async function requestDeviceCode(baseUrl) {
149
+ const response = await authFetch(baseUrl, "/device/code", {
150
+ method: "POST",
151
+ body: {
152
+ client_id: AUTH_CLIENT_ID,
153
+ scope: "openid profile email",
154
+ },
155
+ });
156
+ const json = await response.json();
157
+ if (!response.ok) {
158
+ throw new Error(authErrorMessage(json, "Could not start ctx| device login"));
159
+ }
160
+ const data = unwrapBetterAuthData(json);
161
+ if (!isObject(data) || !data.device_code || !data.verification_uri) {
162
+ throw new Error("Device login response was missing required fields");
163
+ }
164
+ return data;
165
+ }
166
+ async function pollDeviceToken({ baseUrl, deviceCode, interval, }) {
167
+ let pollingInterval = Math.max(interval, 1);
168
+ const startedAt = Date.now();
169
+ while (Date.now() - startedAt < 30 * 60 * 1000) {
170
+ await sleep(pollingInterval * 1000 + 250);
171
+ const response = await authFetch(baseUrl, "/device/token", {
172
+ method: "POST",
173
+ body: {
174
+ grant_type: DEVICE_GRANT_TYPE,
175
+ device_code: deviceCode,
176
+ client_id: AUTH_CLIENT_ID,
177
+ },
178
+ });
179
+ const json = await response.json().catch(() => ({}));
180
+ const data = unwrapBetterAuthData(json);
181
+ if (response.ok && isObject(data) && data.access_token)
182
+ return data;
183
+ const code = authErrorCode(json);
184
+ if (code === "authorization_pending")
185
+ continue;
186
+ if (code === "slow_down") {
187
+ pollingInterval += 5;
188
+ continue;
189
+ }
190
+ if (code === "access_denied") {
191
+ throw new Error("The ctx| sign-in request was denied");
192
+ }
193
+ if (code === "expired_token") {
194
+ throw new Error("The ctx| sign-in code expired");
195
+ }
196
+ throw new Error(authErrorMessage(json, "ctx| sign-in failed"));
197
+ }
198
+ throw new Error("ctx| sign-in timed out");
199
+ }
200
+ /**
201
+ * Refresh threshold: if the stored access token expires sooner than this,
202
+ * try a refresh before handing it back to long-running consumers like the
203
+ * AgentMemory child process.
204
+ */
205
+ const REFRESH_LEEWAY_MS = 10 * 60 * 1000;
206
+ /**
207
+ * Return a non-expired access token for `baseUrl`. Refreshes via the stored
208
+ * `refresh_token` when possible; returns null if no auth is stored or refresh
209
+ * fails (signed-out mode).
210
+ */
211
+ export async function ensureFreshAccessToken({ baseUrl, now, }) {
212
+ const auth = await readStoredAuth(baseUrl);
213
+ if (!auth)
214
+ return null;
215
+ if (!isExpiringSoon(auth, now))
216
+ return auth;
217
+ if (!auth.refreshToken)
218
+ return auth;
219
+ try {
220
+ const refreshed = await refreshAccessToken({ baseUrl, refreshToken: auth.refreshToken });
221
+ await writeStoredAuth(refreshed);
222
+ return refreshed;
223
+ }
224
+ catch {
225
+ return auth;
226
+ }
227
+ }
228
+ export function isExpiringSoon(auth, now = new Date()) {
229
+ if (!auth.expiresAt)
230
+ return false;
231
+ const expires = Date.parse(auth.expiresAt);
232
+ if (Number.isNaN(expires))
233
+ return false;
234
+ return expires - now.getTime() < REFRESH_LEEWAY_MS;
235
+ }
236
+ async function refreshAccessToken({ baseUrl, refreshToken, }) {
237
+ const response = await authFetch(baseUrl, "/token", {
238
+ method: "POST",
239
+ body: {
240
+ grant_type: "refresh_token",
241
+ refresh_token: refreshToken,
242
+ client_id: AUTH_CLIENT_ID,
243
+ },
244
+ });
245
+ const json = await response.json().catch(() => ({}));
246
+ if (!response.ok) {
247
+ throw new Error(authErrorMessage(json, "Could not refresh ctx| access token"));
248
+ }
249
+ const data = unwrapBetterAuthData(json);
250
+ if (!isObject(data) || typeof data.access_token !== "string") {
251
+ throw new Error("Refresh response missing access_token");
252
+ }
253
+ return {
254
+ baseUrl: normalizeBaseUrl(baseUrl),
255
+ accessToken: data.access_token,
256
+ refreshToken: typeof data.refresh_token === "string" ? data.refresh_token : refreshToken,
257
+ tokenType: typeof data.token_type === "string" ? data.token_type : "Bearer",
258
+ expiresAt: typeof data.expires_in === "number"
259
+ ? new Date(Date.now() + data.expires_in * 1000).toISOString()
260
+ : null,
261
+ createdAt: new Date().toISOString(),
262
+ };
263
+ }
264
+ export function readStoredCtxpipeConfig(cwd) {
265
+ let dir = resolve(cwd);
266
+ // walk up until we hit the filesystem root
267
+ while (true) {
268
+ const candidate = join(dir, ".ctxpipe", "config.json");
269
+ if (existsSync(candidate)) {
270
+ const data = readJsonObject(candidate);
271
+ return {
272
+ orgSlug: typeof data.orgSlug === "string" ? data.orgSlug : null,
273
+ baseUrl: typeof data.baseUrl === "string" ? data.baseUrl : null,
274
+ };
275
+ }
276
+ const parent = dirname(dir);
277
+ if (parent === dir)
278
+ return null;
279
+ dir = parent;
280
+ }
281
+ }
282
+ /** CLI `--base-url` wins; otherwise fall back to repo config, then SaaS default. */
283
+ export function resolveCtxpipeBaseUrl(cwd, cliBaseUrl = DEFAULT_BASE_URL) {
284
+ const fromCli = normalizeBaseUrl(cliBaseUrl);
285
+ if (fromCli !== DEFAULT_BASE_URL)
286
+ return fromCli;
287
+ const config = readStoredCtxpipeConfig(cwd);
288
+ if (config?.baseUrl)
289
+ return normalizeBaseUrl(config.baseUrl);
290
+ return fromCli;
291
+ }
292
+ export async function fetchOrganizations({ baseUrl, accessToken, }) {
293
+ const response = await authFetch(baseUrl, "/organization/list", {
294
+ headers: { Authorization: `Bearer ${accessToken}` },
295
+ });
296
+ const json = await response.json();
297
+ if (!response.ok) {
298
+ throw new Error(authErrorMessage(json, "Could not load ctx| organizations"));
299
+ }
300
+ const data = unwrapBetterAuthData(json);
301
+ if (!Array.isArray(data))
302
+ return [];
303
+ return data
304
+ .map((org) => {
305
+ const item = isObject(org) ? org : {};
306
+ const slug = typeof item.slug === "string" ? item.slug : null;
307
+ return {
308
+ id: typeof item.id === "string" ? item.id : null,
309
+ name: typeof item.name === "string" ? item.name : slug,
310
+ slug: slug ?? "",
311
+ };
312
+ })
313
+ .filter((org) => org.slug);
314
+ }
315
+ export async function fetchSession({ baseUrl, accessToken, }) {
316
+ const response = await authFetch(baseUrl, "/get-session", {
317
+ headers: { Authorization: `Bearer ${accessToken}` },
318
+ });
319
+ const json = await response.json();
320
+ if (!response.ok) {
321
+ throw new Error(authErrorMessage(json, "Could not load ctx| session"));
322
+ }
323
+ const data = unwrapBetterAuthData(json);
324
+ return isObject(data) ? data : {};
325
+ }
326
+ async function authFetch(baseUrl, path, options = {}) {
327
+ const url = new URL(`/.auth/api/v1/auth${path}`, baseUrl);
328
+ try {
329
+ return await fetch(url, {
330
+ method: options.method ?? "GET",
331
+ headers: {
332
+ Accept: "application/json",
333
+ ...(options.body ? { "Content-Type": "application/json" } : {}),
334
+ ...(options.headers ?? {}),
335
+ },
336
+ body: options.body ? JSON.stringify(options.body) : undefined,
337
+ });
338
+ }
339
+ catch (error) {
340
+ throw new Error(authConnectionErrorMessage({ baseUrl, error }));
341
+ }
342
+ }
343
+ function authConnectionErrorMessage({ baseUrl, error, }) {
344
+ const code = error instanceof Error &&
345
+ isObject(error.cause) &&
346
+ typeof error.cause.code === "string"
347
+ ? ` (${error.cause.code})`
348
+ : "";
349
+ const localHint = baseUrl.includes(".localhost")
350
+ ? " For local testing, use the backend's direct local URL, such as `--base-url http://127.0.0.1:<backend-port>`."
351
+ : "";
352
+ return `Could not reach ctx| auth at ${baseUrl}${code}.${localHint}`;
353
+ }
354
+ export function unwrapBetterAuthData(json) {
355
+ if (isObject(json) && "data" in json)
356
+ return json.data;
357
+ return json;
358
+ }
359
+ export function authErrorCode(json) {
360
+ if (!isObject(json))
361
+ return null;
362
+ if (typeof json.error === "string")
363
+ return json.error;
364
+ if (isObject(json.error) && typeof json.error.error === "string") {
365
+ return json.error.error;
366
+ }
367
+ return null;
368
+ }
369
+ export function authErrorMessage(json, fallback) {
370
+ if (isObject(json)) {
371
+ if (typeof json.error_description === "string")
372
+ return json.error_description;
373
+ if (typeof json.message === "string")
374
+ return json.message;
375
+ if (typeof json.error === "string")
376
+ return json.error;
377
+ if (isObject(json.error)) {
378
+ if (typeof json.error.error_description === "string") {
379
+ return json.error.error_description;
380
+ }
381
+ if (typeof json.error.message === "string")
382
+ return json.error.message;
383
+ if (typeof json.error.error === "string")
384
+ return json.error.error;
385
+ }
386
+ }
387
+ return fallback;
388
+ }
389
+ export function orgLabel(org) {
390
+ return org.name && org.name !== org.slug ? `${org.name} (${org.slug})` : org.slug;
391
+ }
392
+ export function userLabel(session) {
393
+ const user = sessionUser(session);
394
+ if (!user)
395
+ return null;
396
+ return (stringField(user, "email") ??
397
+ stringField(user, "name") ??
398
+ stringField(user, "id") ??
399
+ null);
400
+ }
401
+ export function sessionUser(session) {
402
+ return session && isObject(session.user) ? session.user : null;
403
+ }
404
+ function absoluteUrl(value, baseUrl) {
405
+ return new URL(value, baseUrl).toString();
406
+ }
407
+ function stringField(value, key) {
408
+ return typeof value[key] === "string" ? value[key] : null;
409
+ }
410
+ function requiredString(value, key) {
411
+ const field = stringField(value, key);
412
+ if (!field)
413
+ throw new Error(`Missing ${key} in ctx| auth response`);
414
+ return field;
415
+ }
416
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src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A;AAC3C,CAAC;AAED,SAAS,WAAW,CAAC,KAA8B,EAAE,GAAW;IAC9D,OAAO,OAAO,KAAK,CAAC,GAAG,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;AAC3D,CAAC;AAED,SAAS,cAAc,CAAC,KAA8B,EAAE,GAAW;IACjE,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,EAAE,GAAG,CAAC,CAAA;IACrC,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,WAAW,GAAG,wBAAwB,CAAC,CAAA;IACnE,OAAO,KAAK,CAAA;AACd,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function runCli(rawArgs?: string[]): Promise<void>;
package/dist/cli.js ADDED
@@ -0,0 +1,12 @@
1
+ import { runProgram } from "./program.js";
2
+ export async function runCli(rawArgs = process.argv.slice(2)) {
3
+ await runProgram(rawArgs);
4
+ }
5
+ if (import.meta.url === `file://${process.argv[1]}`) {
6
+ runCli().catch((err) => {
7
+ const message = err instanceof Error ? err.message : String(err);
8
+ console.error(`ctxpipe: ${message}`);
9
+ process.exitCode = 1;
10
+ });
11
+ }
12
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAEzC,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,UAAoB,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IACpE,MAAM,UAAU,CAAC,OAAO,CAAC,CAAA;AAC3B,CAAC;AAED,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,UAAU,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IACpD,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;QAC9B,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QAChE,OAAO,CAAC,KAAK,CAAC,YAAY,OAAO,EAAE,CAAC,CAAA;QACpC,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAA;IACtB,CAAC,CAAC,CAAA;AACJ,CAAC"}