@bahulam/code 0.1.1 → 0.1.3

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 (53) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +39 -0
  3. package/package.json +8 -9
  4. package/pulse/lib/tool-categories.ts +13 -0
  5. package/src/commands/device.mjs +121 -0
  6. package/src/commands/pair.mjs +190 -0
  7. package/src/commands/remote.mjs +110 -0
  8. package/src/config/env.mjs +2 -2
  9. package/src/core/event-log.mjs +393 -0
  10. package/src/core/headless.mjs +198 -0
  11. package/src/core/loop.mjs +276 -0
  12. package/src/core/memory-disk.mjs +210 -0
  13. package/src/core/paths.mjs +36 -0
  14. package/src/core/stream-client.mjs +28 -9
  15. package/src/core/tool-executor.mjs +64 -16
  16. package/src/daemon/approval-store.mjs +253 -0
  17. package/src/daemon/attach-client.mjs +361 -0
  18. package/src/daemon/daemonize.mjs +151 -0
  19. package/src/daemon/event-tap.mjs +197 -0
  20. package/src/daemon/input-lock.mjs +191 -0
  21. package/src/daemon/relay-client.mjs +258 -0
  22. package/src/daemon/session-core.mjs +179 -0
  23. package/src/daemon/session-list.mjs +26 -0
  24. package/src/daemon/session-publisher.mjs +78 -0
  25. package/src/daemon/socket-server.mjs +329 -0
  26. package/src/daemon/stop-daemon.mjs +18 -0
  27. package/src/permissions/checker.mjs +6 -6
  28. package/src/permissions/prompt.mjs +8 -7
  29. package/src/skills/installer.mjs +8 -0
  30. package/src/terminal/ansi.mjs +85 -9
  31. package/src/terminal/main.mjs +97 -3
  32. package/src/terminal/repl.mjs +389 -6
  33. package/src/terminal/skills-picker.mjs +121 -0
  34. package/src/terminal/skills.mjs +3 -3
  35. package/src/tools/analyze-code.mjs +39 -0
  36. package/src/tools/bash.mjs +1 -1
  37. package/src/tools/edit.mjs +18 -18
  38. package/src/tools/git-diff.mjs +34 -0
  39. package/src/tools/git-status.mjs +30 -0
  40. package/src/tools/glob.mjs +5 -2
  41. package/src/tools/grep.mjs +1 -1
  42. package/src/tools/meta-tools.mjs +85 -0
  43. package/src/tools/read-files.mjs +37 -0
  44. package/src/tools/read.mjs +20 -10
  45. package/src/tools/registry.mjs +20 -0
  46. package/src/tools/remember.mjs +147 -0
  47. package/src/tools/search-files.mjs +41 -0
  48. package/src/tools/write-project.mjs +62 -0
  49. package/src/tools/write.mjs +1 -1
  50. package/src/ui/banner.mjs +1 -1
  51. package/src/ui/slash-commands.mjs +16 -0
  52. package/src/ui/sub-agent.mjs +8 -2
  53. package/src/ui/transcript-block.mjs +4 -1
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept and charge a
167
+ fee for acceptance of support, warranty, indemnity, or other liability
168
+ obligations and/or rights consistent with this License. However, in
169
+ accepting such obligations, You may act only on Your own behalf and on
170
+ Your sole responsibility, not on behalf of any other Contributor, and
171
+ only if You agree to indemnify, defend, and hold each Contributor
172
+ harmless for any liability incurred by, or claims asserted against,
173
+ such Contributor by reason of your accepting any such warranty or
174
+ additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 axplusb.tech
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,39 @@
1
+ Bahulam Code
2
+ Copyright 2026 axplusb.tech
3
+
4
+ This product includes software developed by axplusb.tech
5
+ (https://axplusb.tech).
6
+
7
+ ------------------------------------------------------------------------
8
+ Upstream and third-party attribution
9
+ ------------------------------------------------------------------------
10
+
11
+ The CLI runtime derives, in part, from the open-source open-claude-code
12
+ project. Original work bears its own copyright and license terms; those
13
+ files remain governed by their upstream licenses, and any modifications
14
+ to them by axplusb.tech are additionally licensed under Apache License,
15
+ Version 2.0 as declared in the LICENSE file at the root of this project.
16
+
17
+ The Bahulam runtime bundle (@bahulam/runtime-<platform>-<arch>) ships
18
+ with a PyArmor-obfuscated Python payload that is proprietary to
19
+ axplusb.tech and is NOT covered by the Apache License. It is distributed
20
+ under a separate end-user license embedded in the runtime as a signed
21
+ license JWT. Use of the runtime requires accepting that license.
22
+
23
+ Third-party npm dependencies listed in package.json are the property of
24
+ their respective owners and are used under the terms of the licenses
25
+ they publish. See the individual package license files under
26
+ node_modules/*/LICENSE for the specific terms of each dependency.
27
+
28
+ ------------------------------------------------------------------------
29
+ Trademarks
30
+ ------------------------------------------------------------------------
31
+
32
+ "Bahulam", the Bahulam wordmark, the ∞ mark, and "Orca" are trademarks
33
+ of axplusb.tech. The Apache License, Section 6, does not grant permission
34
+ to use these names, marks, or logos, except as required to describe the
35
+ origin of the software or to reproduce the content of this NOTICE file.
36
+
37
+ Forks and derivative works must select a distinct name and mark; the
38
+ Bahulam and Orca marks may not be used to name, brand, or promote any
39
+ derivative or competing distribution without prior written permission.
package/package.json CHANGED
@@ -1,16 +1,19 @@
1
1
  {
2
2
  "name": "@bahulam/code",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Bahulam Code \u2014 abundance, in your terminal. CLI-first, reliability-first, sub-agents, 65.6% SWE-bench Verified.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "bahulam": "src/terminal/main.mjs",
8
- "bahulam-code": "src/terminal/main.mjs"
8
+ "bahulam-code": "src/terminal/main.mjs",
9
+ "bahulamd": "src/terminal/main.mjs"
9
10
  },
10
11
  "files": [
11
12
  "src/",
12
13
  "pulse/",
13
- "README.md"
14
+ "README.md",
15
+ "LICENSE",
16
+ "NOTICE"
14
17
  ],
15
18
  "scripts": {
16
19
  "start": "node src/terminal/main.mjs",
@@ -36,7 +39,7 @@
36
39
  "gemini",
37
40
  "axplusb"
38
41
  ],
39
- "license": "MIT",
42
+ "license": "Apache-2.0",
40
43
  "author": "axplusb.tech <hello@axplusb.tech>",
41
44
  "homepage": "https://bahulam.ai/code",
42
45
  "repository": {
@@ -48,9 +51,5 @@
48
51
  "tree-sitter-wasms": "^0.1.13",
49
52
  "web-tree-sitter": "^0.26.9"
50
53
  },
51
- "optionalDependencies": {
52
- "@bahulam/runtime-darwin-arm64": "0.1.1",
53
- "@bahulam/runtime-linux-x64": "0.1.1",
54
- "@bahulam/runtime-win32-x64": "0.1.1"
55
- }
54
+ "optionalDependencies": {}
56
55
  }
@@ -11,13 +11,20 @@ export type ToolCategory =
11
11
 
12
12
  export const TOOL_CATEGORIES: Record<string, ToolCategory> = {
13
13
  Read: 'file-io',
14
+ read_file: 'file-io',
14
15
  Write: 'file-io',
16
+ write_file: 'file-io',
15
17
  Edit: 'file-io',
18
+ edit_file: 'file-io',
16
19
  Glob: 'file-io',
20
+ list_files: 'file-io',
17
21
  Grep: 'file-io',
22
+ search_code: 'file-io',
23
+ search_files: 'file-io',
18
24
  NotebookEdit: 'file-io',
19
25
 
20
26
  Bash: 'shell',
27
+ shell: 'shell',
21
28
 
22
29
  Task: 'agent',
23
30
  TaskCreate: 'agent',
@@ -58,10 +65,16 @@ export const CATEGORY_COLORS: Record<ToolCategory, string> = {
58
65
  /** Per-tool bar colors so Read / Write / Edit / … stay distinct on project cards */
59
66
  const TOOL_BAR_OVERRIDES: Record<string, string> = {
60
67
  Read: 'var(--viz-tool-read)',
68
+ read_file: 'var(--viz-tool-read)',
61
69
  Write: 'var(--viz-tool-write)',
70
+ write_file: 'var(--viz-tool-write)',
62
71
  Edit: 'var(--viz-tool-edit)',
72
+ edit_file: 'var(--viz-tool-edit)',
63
73
  Grep: 'var(--viz-tool-grep)',
74
+ search_code: 'var(--viz-tool-grep)',
75
+ search_files: 'var(--viz-tool-grep)',
64
76
  Glob: 'var(--viz-tool-glob)',
77
+ list_files: 'var(--viz-tool-glob)',
65
78
  NotebookEdit: 'var(--viz-tool-edit)',
66
79
  }
67
80
 
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Device inventory and revocation.
3
+ *
4
+ * bahulam device list List all paired devices for this user.
5
+ * bahulam device revoke <id> Revoke a device (kill switch).
6
+ * Revoked devices are dropped within * revoking itself remotely.
7
+ *
8
+ * bahulam device whoami Print this device's registered id +
9
+ * pubkey (for cross-checking with
10
+ * `bahulam device list`).
11
+ */
12
+
13
+ import { TarangAuth } from '../auth/tarang-auth.mjs';
14
+
15
+ const GATEWAY = (process.env.BAHULAM_GATEWAY_URL || 'https://gateway.bahulam.ai').replace(/\/+$/, '').replace(/\/v1$/, '');
16
+ const RESET = '\x1b[0m';
17
+ const BOLD = '\x1b[1m';
18
+ const DIM = '\x1b[2m';
19
+ const RED = '\x1b[31m';
20
+ const GREEN = '\x1b[32m';
21
+ const YELLOW = '\x1b[33m';
22
+
23
+ export async function runDeviceCommand(args = []) {
24
+ const sub = (args[0] || '').toLowerCase();
25
+ const auth = new TarangAuth();
26
+ const creds = auth.loadCredentials();
27
+ if (!creds.token) {
28
+ process.stderr.write(`${RED}Not logged in. Run ${BOLD}bahulam login${RESET}${RED} first.${RESET}\n`);
29
+ return 1;
30
+ }
31
+
32
+ if (sub === 'list') return await _list(creds.token, auth);
33
+ if (sub === 'revoke') return await _revoke(creds.token, args[1], auth);
34
+ if (sub === 'whoami') return _whoami(auth);
35
+
36
+ process.stderr.write(`${BOLD}bahulam device${RESET} ${DIM}— list and revoke paired devices${RESET}\n\n`);
37
+ process.stderr.write(` bahulam device list List paired devices\n`);
38
+ process.stderr.write(` bahulam device revoke <id> Revoke a device (kill switch)\n`);
39
+ process.stderr.write(` bahulam device whoami Show this device's registered id\n`);
40
+ return 1;
41
+ }
42
+
43
+ async function _list(token, auth) {
44
+ try {
45
+ const res = await fetch(`${GATEWAY}/v1/devices`, {
46
+ headers: { Authorization: `Bearer ${token}` },
47
+ });
48
+ if (!res.ok) {
49
+ const body = await res.text().catch(() => '');
50
+ process.stderr.write(`${RED}Failed to list devices (${res.status}): ${body}${RESET}\n`);
51
+ return 1;
52
+ }
53
+ const { devices } = await res.json();
54
+ if (!devices || devices.length === 0) {
55
+ process.stderr.write(`${DIM}No paired devices.${RESET}\n`);
56
+ return 0;
57
+ }
58
+ const self = auth.getRawConfig()?.pairing?.device_id || '';
59
+ process.stderr.write(`\n${BOLD}${devices.length} device(s)${RESET}\n`);
60
+ for (const d of devices) {
61
+ const badge = d.device_id === self ? ` ${GREEN}(this)${RESET}` : '';
62
+ const status = d.status === 'active' ? GREEN + 'active' + RESET : RED + 'revoked' + RESET;
63
+ const seen = d.last_seen_at ? `last seen ${d.last_seen_at}` : `paired ${d.created_at}`;
64
+ process.stderr.write(` ${d.device_id}${badge} ${status} ${BOLD}${d.name}${RESET} ${DIM}${seen}${RESET}\n`);
65
+ }
66
+ process.stderr.write('\n');
67
+ return 0;
68
+ } catch (err) {
69
+ process.stderr.write(`${RED}Network error: ${err.message}${RESET}\n`);
70
+ return 1;
71
+ }
72
+ }
73
+
74
+ async function _revoke(token, deviceId, auth) {
75
+ if (!deviceId) {
76
+ process.stderr.write(`Usage: ${BOLD}bahulam device revoke <device_id>${RESET}\n`);
77
+ process.stderr.write(`${DIM}Run ${BOLD}bahulam device list${RESET}${DIM} to see ids.${RESET}\n`);
78
+ return 1;
79
+ }
80
+ try {
81
+ const res = await fetch(`${GATEWAY}/v1/devices/revoke`, {
82
+ method: 'POST',
83
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
84
+ body: JSON.stringify({ device_id: deviceId }),
85
+ });
86
+ if (!res.ok) {
87
+ const body = await res.text().catch(() => '');
88
+ process.stderr.write(`${RED}Revoke failed (${res.status}): ${body}${RESET}\n`);
89
+ return 1;
90
+ }
91
+ process.stderr.write(`${GREEN}✓ revoked${RESET} ${deviceId}\n`);
92
+ // If revoking self, clear local pairing so the daemon doesn't keep
93
+ // trying to reconnect with a dead key.
94
+ const self = auth.getRawConfig()?.pairing?.device_id;
95
+ if (self === deviceId) {
96
+ auth.saveCredentials({
97
+ pairing: null,
98
+ remote: { ...(auth.getRawConfig()?.remote || {}), enabled: false },
99
+ });
100
+ process.stderr.write(`${YELLOW}⚠ this was THIS device; local pairing + remote both cleared.${RESET}\n`);
101
+ }
102
+ process.stderr.write(`${DIM}Relay drops the revoked connection within one heartbeat.${RESET}\n\n`);
103
+ return 0;
104
+ } catch (err) {
105
+ process.stderr.write(`${RED}Network error: ${err.message}${RESET}\n`);
106
+ return 1;
107
+ }
108
+ }
109
+
110
+ function _whoami(auth) {
111
+ const p = auth.getRawConfig()?.pairing;
112
+ if (!p?.device_id) {
113
+ process.stderr.write(`${DIM}not paired.${RESET} Run ${BOLD}bahulam pair get-code${RESET}${DIM} on this device.${RESET}\n`);
114
+ return 0;
115
+ }
116
+ process.stderr.write(` ${DIM}device_id:${RESET} ${p.device_id}\n`);
117
+ process.stderr.write(` ${DIM}name:${RESET} ${p.device_name}\n`);
118
+ process.stderr.write(` ${DIM}pubkey:${RESET} ${(p.pubkey_base64 || '').slice(0, 32)}…\n`);
119
+ process.stderr.write(` ${DIM}paired_at:${RESET} ${p.paired_at}\n`);
120
+ return 0;
121
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Device pairing — pair this laptop with a phone or another device
3
+ * for remote session monitoring.
4
+ *
5
+ * Two directions:
6
+ *
7
+ * bahulam pair get-code [name] Generate a fresh 6-digit code. *
8
+ * Two directions:
9
+ *
10
+ * bahulam pair get-code [name] Ask the gateway for a fresh 6-digit
11
+ * code + expiry, print it. Give this
12
+ * to a NEW device (phone, other laptop)
13
+ * that will run `bahulam pair` with it.
14
+ *
15
+ * bahulam pair <code> Register THIS device by claiming the
16
+ * code. Generates a per-device Ed25519
17
+ * keypair, POSTs to /v1/devices/pair,
18
+ * stashes the returned device_id +
19
+ * peer pubkeys in ~/.bahulam/config.json.
20
+ *
21
+ * Storage (config.json.pairing):
22
+ * { device_id, device_name, private_key, public_key, paired_at,
23
+ * peer_pubkeys: { device_id: pubkey_base64, ... } }
24
+ *
25
+ * The private key never leaves the device. Key format is PEM (Node's
26
+ * default for generateKeyPair) so we don't need any conversion library.
27
+ */
28
+
29
+ import * as fs from 'node:fs';
30
+ import * as os from 'node:os';
31
+ import { generateKeyPairSync, createPrivateKey, createPublicKey } from 'node:crypto';
32
+ import { promisify } from 'node:util';
33
+ import { TarangAuth } from '../auth/tarang-auth.mjs';
34
+
35
+ const GATEWAY = (process.env.BAHULAM_GATEWAY_URL || 'https://gateway.bahulam.ai').replace(/\/+$/, '').replace(/\/v1$/, '');
36
+ const RESET = '\x1b[0m';
37
+ const BOLD = '\x1b[1m';
38
+ const DIM = '\x1b[2m';
39
+ const RED = '\x1b[31m';
40
+ const GREEN = '\x1b[32m';
41
+ const YELLOW = '\x1b[33m';
42
+ const CYAN = '\x1b[36m';
43
+
44
+ export async function runPairCommand(args = []) {
45
+ const auth = new TarangAuth();
46
+ const creds = auth.loadCredentials();
47
+ if (!creds.token) {
48
+ process.stderr.write(`${RED}Not logged in. Run ${BOLD}bahulam login${RESET}${RED} first.${RESET}\n`);
49
+ return 1;
50
+ }
51
+
52
+ const sub = (args[0] || '').toLowerCase();
53
+ if (sub === 'get-code') {
54
+ return await _getCode(creds.token, args[1]);
55
+ }
56
+ if (sub === 'status') {
57
+ return _status(auth);
58
+ }
59
+ if (/^\d{6}$/.test(sub)) {
60
+ return await _claimCode(creds.token, sub, args[1] || _defaultDeviceName(), auth);
61
+ }
62
+ _usage();
63
+ return 1;
64
+ }
65
+
66
+ function _usage() {
67
+ process.stderr.write(`${BOLD}bahulam pair${RESET} ${DIM}— pair a device for remote monitoring${RESET}\n\n`);
68
+ process.stderr.write(` bahulam pair get-code [name] Get a 6-digit code (share with new device)\n`);
69
+ process.stderr.write(` bahulam pair <code> [name] Register THIS device using a 6-digit code\n`);
70
+ process.stderr.write(` bahulam pair status Show current pairing state\n`);
71
+ }
72
+
73
+ async function _getCode(token, deviceName) {
74
+ const name = deviceName || _defaultDeviceName();
75
+ try {
76
+ const res = await fetch(`${GATEWAY}/v1/devices/code`, {
77
+ method: 'POST',
78
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
79
+ body: JSON.stringify({ device_name: name }),
80
+ });
81
+ if (!res.ok) {
82
+ const body = await res.text().catch(() => '');
83
+ process.stderr.write(`${RED}Failed to get code (${res.status}): ${body}${RESET}\n`);
84
+ return 1;
85
+ }
86
+ const { code, expires_at } = await res.json();
87
+ process.stderr.write(`\n ${CYAN}${BOLD}${code}${RESET}\n\n`);
88
+ process.stderr.write(` ${DIM}Enter this code on the other device with:${RESET}\n`);
89
+ process.stderr.write(` ${BOLD}bahulam pair ${code}${RESET}\n`);
90
+ process.stderr.write(` ${DIM}Or at ${GATEWAY.replace('gateway.', 'pair.')} (until ${expires_at})${RESET}\n\n`);
91
+ return 0;
92
+ } catch (err) {
93
+ process.stderr.write(`${RED}Network error: ${err.message}${RESET}\n`);
94
+ return 1;
95
+ }
96
+ }
97
+
98
+ async function _claimCode(token, code, name, auth) {
99
+ // Generate a per-device Ed25519 keypair. Node's built-in — no npm dep.
100
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519', {
101
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
102
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
103
+ });
104
+ const pubkeyBase64 = _pemPubkeyToBase64Raw(publicKey);
105
+
106
+ try {
107
+ const res = await fetch(`${GATEWAY}/v1/devices/pair`, {
108
+ method: 'POST',
109
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
110
+ body: JSON.stringify({
111
+ code,
112
+ device_pubkey: pubkeyBase64,
113
+ device_name: name,
114
+ }),
115
+ });
116
+ if (!res.ok) {
117
+ const body = await res.text().catch(() => '');
118
+ process.stderr.write(`${RED}Pairing failed (${res.status}): ${body}${RESET}\n`);
119
+ process.stderr.write(`${DIM}The code may be invalid, expired, or already claimed.${RESET}\n`);
120
+ return 1;
121
+ }
122
+ const { device_id, peer_pubkeys } = await res.json();
123
+
124
+ auth.saveCredentials({
125
+ pairing: {
126
+ device_id,
127
+ device_name: name,
128
+ private_key: privateKey,
129
+ public_key: publicKey,
130
+ pubkey_base64: pubkeyBase64,
131
+ paired_at: new Date().toISOString(),
132
+ peer_pubkeys: peer_pubkeys || {},
133
+ },
134
+ });
135
+
136
+ process.stderr.write(`\n${GREEN}✓ device paired${RESET}\n`);
137
+ process.stderr.write(` ${DIM}id:${RESET} ${device_id}\n`);
138
+ process.stderr.write(` ${DIM}name:${RESET} ${name}\n`);
139
+ const peers = Object.keys(peer_pubkeys || {});
140
+ process.stderr.write(` ${DIM}peers:${RESET} ${peers.length}${peers.length ? ` (${peers.join(', ')})` : ''}\n`);
141
+ process.stderr.write(`\n ${DIM}Next: ${BOLD}bahulam remote enable${RESET}${DIM} to connect this device to the relay.${RESET}\n\n`);
142
+ return 0;
143
+ } catch (err) {
144
+ process.stderr.write(`${RED}Network error: ${err.message}${RESET}\n`);
145
+ return 1;
146
+ }
147
+ }
148
+
149
+ function _status(auth) {
150
+ const config = auth.getRawConfig();
151
+ const p = config.pairing;
152
+ if (!p || !p.device_id) {
153
+ process.stderr.write(`${DIM}not paired. Run ${BOLD}bahulam pair get-code${RESET}${DIM} on this device or ${BOLD}bahulam pair <code>${RESET}${DIM} with a code from another.${RESET}\n`);
154
+ return 0;
155
+ }
156
+ process.stderr.write(`\n${BOLD}pairing${RESET}\n`);
157
+ process.stderr.write(` ${DIM}id:${RESET} ${p.device_id}\n`);
158
+ process.stderr.write(` ${DIM}name:${RESET} ${p.device_name}\n`);
159
+ process.stderr.write(` ${DIM}since:${RESET} ${p.paired_at}\n`);
160
+ const peers = Object.keys(p.peer_pubkeys || {});
161
+ process.stderr.write(` ${DIM}peers:${RESET} ${peers.length}${peers.length ? ` (${peers.join(', ')})` : ''}\n\n`);
162
+ return 0;
163
+ }
164
+
165
+ // ── helpers ──────────────────────────────────────────────────────────
166
+
167
+ function _defaultDeviceName() {
168
+ const user = process.env.USER || process.env.USERNAME || 'user';
169
+ const host = (process.env.HOSTNAME || os.hostname() || 'host').split('.')[0];
170
+ return `${user}@${host}`;
171
+ }
172
+
173
+ // Convert a Node-exported Ed25519 PEM pubkey to the raw 32-byte base64
174
+ // form the gateway stores. Node ships it wrapped in an SPKI DER; we
175
+ // strip the SPKI header prefix to get the raw pubkey bytes.
176
+ // SPKI Ed25519 header: 30 2a 30 05 06 03 2b 65 70 03 21 00 (12 bytes),
177
+ // followed by the 32-byte raw pubkey.
178
+ function _pemPubkeyToBase64Raw(pemStr) {
179
+ const derBase64 = pemStr
180
+ .replace(/-----BEGIN PUBLIC KEY-----/, '')
181
+ .replace(/-----END PUBLIC KEY-----/, '')
182
+ .replace(/\s+/g, '');
183
+ const der = Buffer.from(derBase64, 'base64');
184
+ // Strip the 12-byte SPKI Ed25519 header. If length isn't 44 (12+32),
185
+ // fall back to sending the full DER base64 — the gateway just stores
186
+ // it opaquely — the raw-vs-SPKI decision is a future
187
+ // (session key wrap) concern anyway.
188
+ if (der.length === 44) return der.slice(12).toString('base64');
189
+ return derBase64;
190
+ }