clearhand 0.1.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 (38) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +146 -0
  3. package/SECURITY.md +77 -0
  4. package/bin/clearhand.js +230 -0
  5. package/dist/mcp/index.js +159 -0
  6. package/dist/server/connectors/crawl.js +52 -0
  7. package/dist/server/connectors/github.js +45 -0
  8. package/dist/server/connectors/mailbox.js +257 -0
  9. package/dist/server/connectors/stripe.js +252 -0
  10. package/dist/server/context.js +83 -0
  11. package/dist/server/db/index.js +324 -0
  12. package/dist/server/demo.js +194 -0
  13. package/dist/server/index.js +51 -0
  14. package/dist/server/routes/api.js +704 -0
  15. package/dist/server/secrets/redaction.js +62 -0
  16. package/dist/server/secrets/store.js +238 -0
  17. package/dist/server/services/approval.js +206 -0
  18. package/dist/server/services/connections.js +99 -0
  19. package/dist/server/services/executor.js +417 -0
  20. package/dist/server/services/lint.js +129 -0
  21. package/dist/server/services/onboarding.js +168 -0
  22. package/dist/server/services/overlay.js +65 -0
  23. package/dist/server/trust/egress.js +12 -0
  24. package/dist/shared/actions.js +136 -0
  25. package/dist/shared/config.js +33 -0
  26. package/dist/shared/paths.js +34 -0
  27. package/package.json +73 -0
  28. package/public/assets/index-BicJ8AKo.css +1 -0
  29. package/public/assets/index-DZSNZW8-.js +43 -0
  30. package/public/index.html +17 -0
  31. package/templates/CLEARHAND.md +79 -0
  32. package/templates/overlay/escalation.md +21 -0
  33. package/templates/overlay/policies.md +30 -0
  34. package/templates/overlay/products.md +25 -0
  35. package/templates/overlay/tone-lint.json +14 -0
  36. package/templates/overlay/voice.md +24 -0
  37. package/templates/skills/clearhand-cs/SKILL.md +75 -0
  38. package/templates/skills/clearhand-onboard/SKILL.md +126 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,146 @@
1
+ # clearhand
2
+
3
+ **Safe hands for your agent.**
4
+
5
+ Your coding agent — Claude Code, Codex — is already smart enough to run your
6
+ customer support: read the inbox, know the customer, draft the reply, decide
7
+ the refund. What it isn't, is safe enough to be trusted with your Stripe
8
+ account and your customers' trust.
9
+
10
+ ClearHand is the missing layer: a small, local, deterministic server that lets
11
+ your agent *propose* support actions — refunds, cancellations, replies,
12
+ GitHub issues — and lets **you** execute them with one click, through an
13
+ executor the agent cannot bypass. Every guard in it exists because of a real
14
+ incident from months of running support this way across 13 SaaS products.
15
+
16
+ ```
17
+ your agent (brain) clearhand (hands) you
18
+ ────────────────── ───────────────────────────── ──────────────────
19
+ reads cases typed Action Proposal v1
20
+ enriches w/ Stripe → lint · freshness · ordering → [ Approve ] click
21
+ drafts in your voice CAS claim · confirm-or-fail
22
+ proposes actions proration & resolve guards full audit trail
23
+ ```
24
+
25
+ ## Try it in 60 seconds (no accounts needed)
26
+
27
+ ```bash
28
+ npx clearhand demo
29
+ ```
30
+
31
+ Opens a local dashboard with seeded cases. Open
32
+ `http://localhost:3117/#/onboarding` and run the 90-second demo to watch the
33
+ whole guided setup drive itself through the real endpoints; or go to the
34
+ queue, click through the approve flow, try to resolve a case while its
35
+ refund is still pending, and watch the guards fire.
36
+
37
+ > **Pre-launch:** until the package is published to npm, install from source
38
+ > instead of `npx`:
39
+ > ```bash
40
+ > git clone https://github.com/honganai/clearhand-help && cd clearhand-help
41
+ > npm install && npm run build && npm link # provides the `clearhand` CLI
42
+ > ```
43
+
44
+ ## Real setup (~30–45 min)
45
+
46
+ ```bash
47
+ npx clearhand init
48
+ npx clearhand start # dashboard on http://localhost:3117
49
+ ```
50
+
51
+ 1. **Connect** on the dashboard Connections page — never in chat:
52
+ - Stripe **restricted** key (`customers:read, charges:read,
53
+ refunds:write, subscriptions:write, invoices:read`). Full-access keys
54
+ get a loud warning.
55
+ - Your support mailbox (Gmail app password; IMAP in, provider SMTP out).
56
+ - Optionally GitHub (bug reports become issues).
57
+ 2. **Onboard** — tell your agent:
58
+ > read CLEARHAND.md and run the clearhand-onboard skill
59
+
60
+ It reads your sent mail (locally), your Stripe history, and your public
61
+ policy pages; builds your policy book in `.clearhand/overlay/`; interviews
62
+ you with evidence-based questions ("your site says 14 days, you actually
63
+ refunded outside it 12 times — which do I follow?"); then runs
64
+ **shadow-draft calibration**: side-by-side "what I would have sent vs.
65
+ what you actually sent" for threads you already answered.
66
+ 3. **Work the queue** — tell your agent:
67
+ > run the clearhand-cs skill
68
+
69
+ It triages, enriches, drafts, proposes. You approve on the dashboard.
70
+ Money moves only on your click. Every draft you edit teaches it.
71
+
72
+ **Agents can install this themselves.** Paste this into Claude Code, Codex,
73
+ or any coworking agent — `CLEARHAND.md` and the skills are written for it:
74
+
75
+ > Set up ClearHand (safe hands for customer support) in this project:
76
+ > 1. Run `npx clearhand@latest init`, then start its server in the background
77
+ > with `npx clearhand start`.
78
+ > 2. Open http://localhost:3117/#/onboarding in a browser for me.
79
+ > 3. Read CLEARHAND.md at the project root, then follow the clearhand-onboard
80
+ > skill to guide my setup. I will enter my mailbox and Stripe credentials
81
+ > in the local dashboard myself — never ask for them in chat. Show me
82
+ > everything you learn, and finish by processing my last 3 days of support
83
+ > email. Nothing sends or moves money without my click.
84
+
85
+ ## Why trust it with a Stripe key?
86
+
87
+ Because you don't have to trust *the agent* — only ~4k lines of deterministic
88
+ TypeScript you can read in an afternoon:
89
+
90
+ - **The agent never holds secrets.** Credentials are entered in a local
91
+ dashboard form and stored in your **OS keychain** (encrypted-file and
92
+ explicit-plaintext fallbacks exist). No API or MCP tool returns them; a
93
+ redaction layer scrubs secret-shaped strings from every response as
94
+ defense-in-depth. If you paste a key into chat, the agent is instructed to
95
+ refuse it and tell you to rotate.
96
+ - **Just-in-time decryption with an audit trail.** Keys are decrypted at the
97
+ moment of the API call, and every access is logged with its purpose
98
+ ("Stripe key accessed by refund execution, case #12") — visible on the
99
+ Trust page.
100
+ - **An egress ledger.** The server records every host it contacts. With your
101
+ own agent as the brain, ClearHand's server contacts **no LLM at all**. Verify
102
+ independently: `clearhand doctor --network`.
103
+ - **Every money mutation is confirmed or failed** — a 200 with an unchanged
104
+ object is a failure, not a success. Double-execution is impossible by
105
+ construction (a compare-and-set claim in a synchronous single-writer
106
+ store). Refunds above the charge amount abort. Cancels never re-apply to an
107
+ already-scheduled subscription (that's how a wrongful proration happens).
108
+ A case can't be resolved — and a reply can't be sent — while a refund is
109
+ still owed.
110
+ - **No telemetry.** There is no endpoint to send it to.
111
+
112
+ Read the incident stories behind each guard in [docs/PORT_SPEC.md](docs/PORT_SPEC.md)
113
+ and the threat model in [SECURITY.md](SECURITY.md).
114
+
115
+ ## What it is not
116
+
117
+ Not a help desk, not a ticketing system, not an AI support SaaS. No seats, no
118
+ workflows, no help-center CMS, no auto-send (autonomy is earned, not
119
+ default). If you outgrow one founder + one inbox + one Approve button, you'll
120
+ know.
121
+
122
+ ## Layout
123
+
124
+ ```
125
+ bin/ CLI: init · start · demo · doctor · mcp
126
+ src/server/ the hands: executor, lint, approval, secrets, connectors
127
+ src/mcp/ thin typed MCP proxy (zero business logic)
128
+ templates/ CLEARHAND.md, agent skills, overlay policy-book starters
129
+ dashboard/ local web UI (queue · approve · trust · calibration)
130
+ site/ clearhand.help sources
131
+ docs/ PORT_SPEC (the ported invariants), verification
132
+ ```
133
+
134
+ ## Development
135
+
136
+ ```bash
137
+ npm install && npm test # safety-core tests (CAS race, guards, lint)
138
+ npm run dev # server from source
139
+ cd dashboard && npm run dev # UI with proxy
140
+ ```
141
+
142
+ Rule enforced forever: **every new action type lands a lint rule and an
143
+ executor guard in the same change**, or the LLM regains a money-unsafe path.
144
+
145
+ Apache-2.0. Local-first forever; a hosted always-on tier is planned — the
146
+ [site](site/) has the waitlist.
package/SECURITY.md ADDED
@@ -0,0 +1,77 @@
1
+ # Security model
2
+
3
+ ClearHand moves real money on a machine that also runs a non-deterministic,
4
+ prompt-injectable agent. This document states plainly what is defended, how,
5
+ and what is not.
6
+
7
+ ## Threat model
8
+
9
+ **Defended:**
10
+
11
+ | Threat | Defense |
12
+ |---|---|
13
+ | Secrets leaking into agent transcripts / session logs | Secrets are only ever entered in the local dashboard form (127.0.0.1). No API or MCP tool returns a secret. Agents are instructed (CLEARHAND.md) to refuse pasted secrets and advise rotation. |
14
+ | A prompt-injected agent reading credential files | Credentials live in the OS keychain, not files, wherever possible. Keychain reads by a foreign process are OS-mediated, unlike a silent `cat`. `~/.clearhand` is user-scope, outside any repo. |
15
+ | Malicious instructions inside customer email | Inbound mail is data, not instructions — the skills state this as a hard rule and require escalation on social-engineering signals. Structurally: even a fully hijacked brain can only *propose*; execution requires the human click, and the executor validates every identifier and amount. |
16
+ | Accidental repo commits of secrets | Credentials never live in the project tree. `.clearhand/.gitignore` excludes the DB and manifests on init. |
17
+ | Over-scoped keys | Stripe keys are scope-checked at entry; full-access live keys produce a prominent warning with instructions for a restricted key. |
18
+ | A buggy route leaking a value | Redaction middleware scrubs every JSON/text response against (a) all secret values decrypted this process lifetime and (b) generic secret-shaped patterns (`sk_live_…`, `ghp_…`, bearer tokens). |
19
+ | Double execution / races | Compare-and-set claim on a synchronous single-writer store; idempotent-error mapping makes operator retries safe. |
20
+ | "Success" that didn't happen | Every Stripe mutation is confirmed by a follow-up read; unconfirmed mutations are reported as failures. |
21
+ | Network exposure | The server binds to 127.0.0.1 only. The money route optionally requires a bearer token (`CLEARHAND_EXECUTE_TOKEN`). |
22
+
23
+ **NOT defended (say it honestly):**
24
+
25
+ - Malware running as your OS user, or a compromised machine. Local-first
26
+ means your machine is the trust boundary.
27
+ - A user who grants keychain access prompts to arbitrary processes.
28
+ - Plaintext storage if you explicitly opt in with `--storage plain`.
29
+
30
+ ## Verifying the claims yourself
31
+
32
+ - **Egress**: `clearhand doctor --network` prints every host the server has
33
+ ever contacted (from the ledger) next to live sockets from `lsof`. The
34
+ Trust page shows the same ledger.
35
+ - **Secret access**: the Trust page lists every decryption with its purpose
36
+ and timestamp.
37
+ - **Code**: the entire secrets surface is `src/server/secrets/` (~300
38
+ lines); the money surface is `src/server/services/executor.ts` +
39
+ `approval.ts` + `lint.ts`. Read them.
40
+ - **No telemetry**: grep the codebase for an analytics endpoint; there isn't
41
+ one.
42
+
43
+ ## Storage backends
44
+
45
+ 1. **OS keychain** (macOS Keychain / Windows Credential Manager / libsecret)
46
+ — default when available.
47
+ 2. **Encrypted file** (`~/.clearhand/credentials.enc`, AES-256-GCM, scrypt) —
48
+ requires an externally supplied `CLEARHAND_MASTER_KEY`; refuses to run
49
+ without one rather than storing a key next to its ciphertext.
50
+ 3. **Plaintext** (`~/.clearhand/credentials.json`, mode 600) — explicit
51
+ `clearhand init --storage plain` opt-in only.
52
+
53
+ ## Planned: one-click connections (pre-registered commitments)
54
+
55
+ One-click OAuth connects are designed but not yet shipped
56
+ (docs/design/ONE_CLICK_CONNECT.md). We state the rules before building, so
57
+ they can be held against us:
58
+
59
+ - **Google (Search Console, Ads):** desktop loopback OAuth runs entirely on
60
+ your machine — no ClearHand server is involved; tokens go straight to your
61
+ OS keychain like every other credential.
62
+ - **Stripe (Stripe App install):** Stripe requires our app secret to
63
+ exchange and refresh tokens, so those two calls route through a broker at
64
+ `connect.clearhand.help`. The broker **sees tokens in transit and stores
65
+ nothing** — no database, pure exchange/refresh passthrough. That claim is
66
+ stated the same way as "no telemetry": verifiable, and load-bearing.
67
+ - The broker's host appears in your egress ledger like any other host.
68
+ - **Paste-a-key never goes away.** It remains the offline fallback, and the
69
+ automatic failure mode if the broker is unreachable.
70
+ - Connector cards badge their method honestly (PASTE-A-KEY today; ONE-CLICK
71
+ only once it actually works).
72
+
73
+ ## Reporting a vulnerability
74
+
75
+ Open a GitHub security advisory on this repository, or email the maintainer
76
+ (see package.json). Please do not open public issues for exploitable
77
+ problems. Money-safety reports are treated as the highest severity.
@@ -0,0 +1,230 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { spawn, execSync } from 'node:child_process';
6
+ import { Command } from 'commander';
7
+
8
+ const pkgRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
9
+ const templates = path.join(pkgRoot, 'templates');
10
+ const cwd = process.cwd();
11
+ const projectDir = path.join(cwd, '.clearhand');
12
+
13
+ const program = new Command();
14
+ program
15
+ .name('clearhand')
16
+ .description('Safe hands for your agent — local, human-approved customer support execution.')
17
+ .version('0.1.0');
18
+
19
+ function copyIfMissing(src, dest) {
20
+ if (fs.existsSync(dest)) return false;
21
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
22
+ fs.copyFileSync(src, dest);
23
+ return true;
24
+ }
25
+
26
+ function copyDirIfMissing(srcDir, destDir) {
27
+ const copied = [];
28
+ if (!fs.existsSync(srcDir)) return copied;
29
+ for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
30
+ const s = path.join(srcDir, entry.name);
31
+ const d = path.join(destDir, entry.name);
32
+ if (entry.isDirectory()) copied.push(...copyDirIfMissing(s, d));
33
+ else if (copyIfMissing(s, d)) copied.push(path.relative(cwd, d));
34
+ }
35
+ return copied;
36
+ }
37
+
38
+ program
39
+ .command('init')
40
+ .description('Set up ClearHand in this project: overlay policy book, agent skills, MCP registration.')
41
+ .option('--storage <backend>', 'secret storage: auto | keychain | encrypted-file | plain', 'auto')
42
+ .option('--demo', 'enable demo mode (seeded sample cases, simulated connectors)')
43
+ .option('--port <port>', 'dashboard port', '3117')
44
+ .action((opts) => {
45
+ if (opts.storage === 'plain') {
46
+ console.log('\n⚠ You chose PLAINTEXT secret storage (~/.clearhand/credentials.json, chmod 600).');
47
+ console.log(' An OS keychain or CLEARHAND_MASTER_KEY is strongly recommended.\n');
48
+ }
49
+ const created = [];
50
+
51
+ // Project config
52
+ fs.mkdirSync(projectDir, { recursive: true });
53
+ const configPath = path.join(projectDir, 'config.json');
54
+ if (!fs.existsSync(configPath)) {
55
+ fs.writeFileSync(
56
+ configPath,
57
+ JSON.stringify(
58
+ { port: Number(opts.port), secretStorage: opts.storage, demoMode: Boolean(opts.demo) },
59
+ null,
60
+ 2,
61
+ ) + '\n',
62
+ );
63
+ created.push('.clearhand/config.json');
64
+ }
65
+
66
+ // Never let runtime data reach the repo.
67
+ const gi = path.join(projectDir, '.gitignore');
68
+ if (!fs.existsSync(gi)) {
69
+ fs.writeFileSync(gi, 'clearhand.db*\nconnections.json\n');
70
+ created.push('.clearhand/.gitignore');
71
+ }
72
+
73
+ // Overlay policy book (user-owned, committable).
74
+ created.push(...copyDirIfMissing(path.join(templates, 'overlay'), path.join(projectDir, 'overlay')));
75
+
76
+ // Agent-facing protocol doc + skills.
77
+ if (copyIfMissing(path.join(templates, 'CLEARHAND.md'), path.join(cwd, 'CLEARHAND.md')))
78
+ created.push('CLEARHAND.md');
79
+ created.push(...copyDirIfMissing(path.join(templates, 'skills'), path.join(cwd, '.claude', 'skills')));
80
+
81
+ // MCP registration (merge, don't clobber).
82
+ const mcpPath = path.join(cwd, '.mcp.json');
83
+ let mcp = {};
84
+ try {
85
+ mcp = JSON.parse(fs.readFileSync(mcpPath, 'utf8'));
86
+ } catch {
87
+ /* fresh file */
88
+ }
89
+ mcp.mcpServers = mcp.mcpServers ?? {};
90
+ if (!mcp.mcpServers.clearhand) {
91
+ mcp.mcpServers.clearhand = { command: 'npx', args: ['-y', 'clearhand', 'mcp'] };
92
+ fs.writeFileSync(mcpPath, JSON.stringify(mcp, null, 2) + '\n');
93
+ created.push('.mcp.json (clearhand server registered)');
94
+ }
95
+
96
+ console.log('clearhand init complete.\n');
97
+ if (created.length) {
98
+ console.log('Created:');
99
+ for (const f of created) console.log(` + ${f}`);
100
+ } else {
101
+ console.log('Everything was already in place.');
102
+ }
103
+ console.log(`
104
+ Next steps:
105
+ 1. clearhand start # dashboard on http://localhost:${opts.port}
106
+ 2. Open http://localhost:${opts.port}/#/onboarding — the guided setup.
107
+ You'll connect Stripe (restricted key) + your mailbox there.
108
+ Secrets go into the local dashboard form — NEVER into an agent chat.
109
+ 3. In your agent: "read CLEARHAND.md and run the clearhand-onboard skill".
110
+ ${opts.demo ? '\nDemo mode is ON — `clearhand start` seeds sample cases, and the onboarding page can run a simulated 90-second demo.\n' : ''}`);
111
+ });
112
+
113
+ async function startServer(port) {
114
+ const distEntry = path.join(pkgRoot, 'dist', 'server', 'index.js');
115
+ if (fs.existsSync(distEntry)) {
116
+ process.env.CLEARHAND_PORT = String(port ?? '');
117
+ const mod = await import(distEntry);
118
+ await mod.startServer(port ? { port: Number(port) } : {});
119
+ return;
120
+ }
121
+ // Dev checkout: run TypeScript directly.
122
+ const child = spawn('npx', ['tsx', path.join(pkgRoot, 'src', 'server', 'index.ts')], {
123
+ stdio: 'inherit',
124
+ env: { ...process.env, ...(port ? { CLEARHAND_PORT: String(port) } : {}) },
125
+ });
126
+ child.on('exit', (code) => process.exit(code ?? 0));
127
+ }
128
+
129
+ program
130
+ .command('start')
131
+ .description('Start the local ClearHand server + dashboard (binds to 127.0.0.1 only).')
132
+ .option('--port <port>')
133
+ .action(async (opts) => {
134
+ await startServer(opts.port);
135
+ });
136
+
137
+ program
138
+ .command('demo')
139
+ .description('Init in demo mode (if needed) and start with seeded sample cases.')
140
+ .option('--port <port>', 'dashboard port', '3117')
141
+ .action(async (opts) => {
142
+ const configPath = path.join(projectDir, 'config.json');
143
+ if (!fs.existsSync(configPath)) {
144
+ program.commands.find((c) => c.name() === 'init').parse(['--demo', '--port', opts.port], { from: 'user' });
145
+ } else {
146
+ const cfg = JSON.parse(fs.readFileSync(configPath, 'utf8'));
147
+ if (!cfg.demoMode) {
148
+ cfg.demoMode = true;
149
+ fs.writeFileSync(configPath, JSON.stringify(cfg, null, 2) + '\n');
150
+ console.log('Demo mode enabled in .clearhand/config.json');
151
+ }
152
+ }
153
+ await startServer(opts.port);
154
+ });
155
+
156
+ program
157
+ .command('mcp')
158
+ .description('Run the ClearHand MCP server (stdio). Used by .mcp.json; not for humans.')
159
+ .action(async () => {
160
+ const distEntry = path.join(pkgRoot, 'dist', 'mcp', 'index.js');
161
+ if (fs.existsSync(distEntry)) {
162
+ await import(distEntry);
163
+ return;
164
+ }
165
+ const child = spawn('npx', ['tsx', path.join(pkgRoot, 'src', 'mcp', 'index.ts')], {
166
+ stdio: 'inherit',
167
+ env: process.env,
168
+ });
169
+ child.on('exit', (code) => process.exit(code ?? 0));
170
+ });
171
+
172
+ program
173
+ .command('doctor')
174
+ .description('Check the local setup. --network prints the egress ledger next to live sockets.')
175
+ .option('--network', 'show what hosts ClearHand has contacted and current open connections')
176
+ .option('--port <port>', 'server port', '3117')
177
+ .action(async (opts) => {
178
+ console.log(`node: ${process.version}`);
179
+ try {
180
+ const { Entry } = await import('@napi-rs/keyring');
181
+ const probe = new Entry('clearhand-doctor', 'probe');
182
+ probe.setPassword('ok');
183
+ const ok = probe.getPassword() === 'ok';
184
+ probe.deletePassword();
185
+ console.log(`os keychain: ${ok ? 'available ✓' : 'NOT available'}`);
186
+ } catch {
187
+ console.log('os keychain: NOT available (encrypted-file or plain storage will be used)');
188
+ }
189
+ console.log(`project config: ${fs.existsSync(path.join(projectDir, 'config.json')) ? 'found ✓' : 'missing — run `clearhand init`'}`);
190
+
191
+ let status = null;
192
+ try {
193
+ const res = await fetch(`http://localhost:${opts.port}/api/status`);
194
+ status = await res.json();
195
+ console.log(`server: running on :${opts.port} ✓ ${status.demo_mode ? '(demo mode)' : ''}`);
196
+ console.log(`secret storage in use: ${status.secret_storage}`);
197
+ for (const [id, conn] of Object.entries(status.connections)) {
198
+ console.log(`connection ${id}: ${conn.connected ? 'connected ✓' : 'not connected'}`);
199
+ }
200
+ } catch {
201
+ console.log(`server: not running on :${opts.port} (start with \`clearhand start\`)`);
202
+ }
203
+
204
+ if (opts.network) {
205
+ console.log('\n— Egress ledger (every host ClearHand has ever contacted) —');
206
+ try {
207
+ const res = await fetch(`http://localhost:${opts.port}/api/trust`);
208
+ const trust = await res.json();
209
+ if (!trust.egress.length) console.log(' (no outbound connections recorded yet)');
210
+ for (const e of trust.egress) {
211
+ console.log(` ${e.host} ×${e.count} last: ${e.last_at} (${e.purpose})`);
212
+ }
213
+ console.log(`\ntelemetry: ${trust.telemetry}`);
214
+ } catch {
215
+ console.log(' server not running — start it to read the ledger');
216
+ }
217
+ console.log('\n— Live sockets (verify independently) —');
218
+ try {
219
+ const out = execSync(
220
+ `lsof -nP -iTCP -sTCP:ESTABLISHED | grep -E "node|clearhand" | awk '{print $9}' | sort -u`,
221
+ { encoding: 'utf8' },
222
+ );
223
+ console.log(out.trim() || ' (none)');
224
+ } catch {
225
+ console.log(' (lsof unavailable or nothing to show)');
226
+ }
227
+ }
228
+ });
229
+
230
+ program.parseAsync();