arcroom 0.0.1-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,46 @@
1
+ # arcroom
2
+
3
+ One shared memory for every coding agent on your team. When Claude Code, Codex, Cursor or OpenCode finishes a piece of work, the next agent, on any teammate's laptop, is handed the steps instead of redoing it. ArcRoom also blocks an agent's third identical tool call in a row and keeps a run going while your done-checks fail.
4
+
5
+ ## Quickstart
6
+
7
+ Sign up at [arcroomai.com](https://www.arcroomai.com), then get a key: **Settings → API keys** (shown once). Then, in the project you work on:
8
+
9
+ ```
10
+ npx arcroom init # paste the key when asked (or set ARCROOM_API_KEY)
11
+ npx arcroom whoami # checks the key and the connection
12
+ ```
13
+
14
+ Same memory for another agent in the same project:
15
+
16
+ ```
17
+ npx arcroom init --agent codex # or cursor, opencode (experimental)
18
+ ```
19
+
20
+ `init` copies the plugin to `~/.arcroom/runtime` and adds its hooks and MCP server to the agent's settings. Nothing else needs to run.
21
+
22
+ ## What leaves your laptop
23
+
24
+ Prompts (system reminders removed, secrets redacted, first 1,000 characters), file paths, search patterns, shell commands (first 1,000 characters), URLs and web queries, done-check results, git hashes of the files a turn touched, token counts, and what an agent saves on purpose with ArcRoom's tools. **Never file contents, tool output or edit diffs.** Secret files (`.env`, keys) are skipped.
25
+
26
+ Every upload waits first in `~/.arcroom/spool.jsonl`, so you can read it before it goes. `arcroom off` stops ArcRoom for one repo on this laptop; `arcroom on` starts it again.
27
+
28
+ ## If the API is down
29
+
30
+ Hooks never block a session. Memory lookup gives up after 3 seconds, the prompt goes through without it ("memory offline"), and lookups pause for a minute.
31
+
32
+ ## Commands
33
+
34
+ | Command | What it does |
35
+ | --- | --- |
36
+ | `arcroom init [--agent claude\|codex\|cursor\|opencode] [--project <id>]` | set up this machine and project |
37
+ | `arcroom whoami` | who the key belongs to |
38
+ | `arcroom doctor` | checks the key, the API, the hooks in this folder and the uploader, and prints the fix for each problem |
39
+ | `arcroom off` / `arcroom on` | stop or restart ArcRoom for this repo |
40
+ | `arcroom checks` / `arcroom checks approve <code>` | read and approve the done-checks in `.arcroom.json` |
41
+ | `arcroom wrong [memo id] [reason]` | report a memory that was wrong |
42
+ | `arcroom decide "<choice>" --why ...` | record a team decision |
43
+ | `arcroom rule [--tag t] [--max-hits n] [--idle-days d]` | team rules for when memory expires |
44
+ | `arcroom code [status\|sync\|on\|off]` | the code map |
45
+
46
+ Docs: https://www.arcroomai.com/docs
package/dist/agents.js ADDED
@@ -0,0 +1,158 @@
1
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { sessionFile } from './loop.js';
3
+ // Other coding agents on the same hook handler. The hook speaks Claude Code's payloads; this file translates.
4
+ // codex same events, payloads and outputs as Claude Code; only its tool names differ (shell, apply_patch)
5
+ // cursor camelCase events, conversation_id, workspace_roots; can't add context to a prompt, so recall is held
6
+ // back and handed over on the next tool call (postToolUse accepts additional_context)
7
+ // opencode a plugin file (opencodePlugin) calls the hook with Claude Code payloads; tools are lowercase; recall is
8
+ // found on chat.message and added through experimental.chat.system.transform (an experimental OpenCode hook)
9
+ // Sources (Oct 2026): cursor.com/docs/agent/hooks, learn.chatgpt.com/docs/hooks, opencode.ai/docs/plugins
10
+ export const AGENTS = ['claude', 'codex', 'cursor', 'opencode'];
11
+ const CURSOR_EVENTS = {
12
+ sessionStart: 'SessionStart',
13
+ beforeSubmitPrompt: 'UserPromptSubmit',
14
+ preToolUse: 'PreToolUse',
15
+ postToolUse: 'PostToolUse',
16
+ stop: 'Stop',
17
+ sessionEnd: 'SessionEnd',
18
+ };
19
+ export const CURSOR_HOOKS = Object.keys(CURSOR_EVENTS);
20
+ /** Every file an apply_patch touches ("*** Update File: src/a.ts"). */
21
+ export const patchFiles = (patch) => [...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m) => m[1].trim());
22
+ /**
23
+ * Any agent's tool call in Claude Code's terms (Read / Edit / Bash / Grep / Glob), so traces become the same steps.
24
+ * Returns the tool, its input, and any further files (a patch can touch several).
25
+ */
26
+ export function normalizeTool(name, input) {
27
+ const n = String(name ?? '');
28
+ const i = input ?? {};
29
+ const file = i.file_path ?? i.filePath ?? i.target_file ?? i.path;
30
+ const command = Array.isArray(i.command) ? i.command.join(' ') : (i.command ?? i.cmd);
31
+ const patch = typeof i === 'string' ? i : (i.input ?? i.patch);
32
+ if (/apply_patch/i.test(n) && typeof patch === 'string') {
33
+ const [first, ...more] = patchFiles(patch);
34
+ return { tool: 'Edit', input: { file_path: first }, more };
35
+ }
36
+ if (/^(bash|shell|exec_command|run_terminal_cmd|terminal)$/i.test(n) && command)
37
+ return { tool: 'Bash', input: { command }, more: [] };
38
+ if (/^(read|read_file|view)$/i.test(n) && file)
39
+ return { tool: 'Read', input: { file_path: file }, more: [] };
40
+ if (/^(edit|write|multiedit|edit_file|write_file|search_replace|create_file)$/i.test(n) && file)
41
+ return { tool: /write|create/i.test(n) ? 'Write' : 'Edit', input: { file_path: file }, more: [] };
42
+ if (/^(grep|codebase_search|grep_search)$/i.test(n))
43
+ return { tool: 'Grep', input: { pattern: i.pattern ?? i.query, path: i.path }, more: [] };
44
+ if (/^(glob|list|list_dir|file_search)$/i.test(n))
45
+ return { tool: 'Glob', input: { pattern: i.pattern ?? i.query ?? i.path }, more: [] };
46
+ return { tool: n, input: i, more: [] };
47
+ }
48
+ /** One agent's hook payload as the Claude Code payload the hook handles (+ more_files for multi-file patches). */
49
+ export function fromAgent(raw, agent) {
50
+ if (agent === 'claude')
51
+ return raw;
52
+ const r = { ...raw };
53
+ if (agent === 'cursor') {
54
+ r.hook_event_name = CURSOR_EVENTS[raw.hook_event_name] ?? raw.hook_event_name;
55
+ r.session_id = raw.session_id ?? raw.conversation_id;
56
+ r.cwd = raw.cwd ?? raw.workspace_roots?.[0];
57
+ r.tool_response = raw.tool_response ?? raw.tool_output;
58
+ }
59
+ if (r.tool_name !== undefined) {
60
+ const t = normalizeTool(r.tool_name, r.tool_input);
61
+ r.tool_name = t.tool;
62
+ r.tool_input = t.input;
63
+ if (t.more.length)
64
+ r.more_files = t.more;
65
+ }
66
+ return r;
67
+ }
68
+ /** The hook's Claude Code output in the agent's own terms. */
69
+ export function toAgent(agent, event, out, session) {
70
+ if (agent !== 'cursor')
71
+ return out;
72
+ const context = out.hookSpecificOutput?.additionalContext;
73
+ const pending = sessionFile(session, '.pending-context');
74
+ switch (event) {
75
+ case 'SessionStart':
76
+ return context ? { additional_context: context } : {};
77
+ case 'UserPromptSubmit':
78
+ // Cursor can't add context here: keep it for the first tool call of this turn
79
+ if (context)
80
+ writeFileSync(pending, context);
81
+ return { continue: true };
82
+ case 'PostToolUse': {
83
+ if (!existsSync(pending))
84
+ return {};
85
+ const held = readFileSync(pending, 'utf8');
86
+ rmSync(pending, { force: true });
87
+ return { additional_context: held };
88
+ }
89
+ case 'PreToolUse': {
90
+ const deny = out.hookSpecificOutput?.permissionDecision === 'deny';
91
+ const reason = out.hookSpecificOutput?.permissionDecisionReason;
92
+ return deny ? { permission: 'deny', agent_message: reason, user_message: reason } : {};
93
+ }
94
+ case 'Stop':
95
+ if (out.decision === 'block')
96
+ return { followup_message: out.reason };
97
+ // Cursor shows the person nothing from a Stop hook: the note (e.g. done-checks not approved) waits for the next
98
+ // tool call, where the agent is asked to pass it on (N21)
99
+ if (out.systemMessage)
100
+ writeFileSync(pending, `ArcRoom note for the user (tell them): ${out.systemMessage}`);
101
+ return {};
102
+ default:
103
+ return {};
104
+ }
105
+ }
106
+ /** The OpenCode plugin: calls the ArcRoom hook with Claude Code payloads for each OpenCode event. */
107
+ export function opencodePlugin(entry, project, node = process.execPath) {
108
+ const args = JSON.stringify([entry, 'hook', '--agent', 'opencode', ...(project ? ['--project', project] : [])]);
109
+ return `// ArcRoom for OpenCode (written by \`arcroom init --agent opencode\`; experimental).
110
+ // Traces prompts and tool calls, hands over team memory for each prompt, blocks repeated calls, keeps the agent on
111
+ // failing done-checks, and adds the last run's note.
112
+ import { spawnSync } from 'node:child_process';
113
+
114
+ const run = (payload) => {
115
+ const r = spawnSync(${JSON.stringify(node)}, ${args}, { input: JSON.stringify(payload), encoding: 'utf8' });
116
+ try { return JSON.parse(r.stdout || '{}'); } catch { return {}; }
117
+ };
118
+
119
+ export const ArcRoom = async ({ client, directory }) => {
120
+ const base = (id) => ({ session_id: id ?? 'opencode', cwd: directory });
121
+ const say = async (id, text) => {
122
+ if (id && text) await client.session.prompt({ path: { id }, body: { noReply: true, parts: [{ type: 'text', text }] } }).catch(() => {});
123
+ };
124
+ // recall for the prompt being answered: found when the message arrives, added to the system prompt for that turn
125
+ const pending = new Map();
126
+ return {
127
+ 'chat.message': async (input, output) => {
128
+ const prompt = (output.parts ?? []).filter((p) => p.type === 'text' && !p.synthetic).map((p) => p.text).join('\\n');
129
+ if (!prompt) return;
130
+ const context = run({ ...base(input.sessionID), hook_event_name: 'UserPromptSubmit', prompt }).hookSpecificOutput?.additionalContext;
131
+ if (context) pending.set(input.sessionID, context);
132
+ else pending.delete(input.sessionID);
133
+ },
134
+ 'experimental.chat.system.transform': async (input, output) => {
135
+ const context = input.sessionID && pending.get(input.sessionID);
136
+ if (context) output.system.push(context);
137
+ },
138
+ 'tool.execute.before': async (input, output) => {
139
+ const out = run({ ...base(input.sessionID), hook_event_name: 'PreToolUse', tool_name: input.tool, tool_input: output.args, tool_use_id: input.callID });
140
+ if (out.hookSpecificOutput?.permissionDecision === 'deny') throw new Error(out.hookSpecificOutput.permissionDecisionReason);
141
+ },
142
+ 'tool.execute.after': async (input, output) => {
143
+ run({ ...base(input.sessionID), hook_event_name: 'PostToolUse', tool_name: input.tool, tool_input: output.args, tool_response: output.output, tool_use_id: input.callID });
144
+ },
145
+ event: async ({ event }) => {
146
+ const id = event.properties?.sessionID ?? event.properties?.info?.id;
147
+ if (event.type === 'session.created') await say(id, run({ ...base(id), hook_event_name: 'SessionStart' }).hookSpecificOutput?.additionalContext);
148
+ if (event.type === 'session.idle') {
149
+ pending.delete(id); // the turn is over: the next prompt gets its own recall
150
+ const out = run({ ...base(id), hook_event_name: 'Stop' });
151
+ if (out.decision === 'block' && id) await client.session.prompt({ path: { id }, body: { parts: [{ type: 'text', text: out.reason }] } }).catch(() => {});
152
+ }
153
+ if (event.type === 'session.deleted') run({ ...base(id), hook_event_name: 'SessionEnd' });
154
+ },
155
+ };
156
+ };
157
+ `;
158
+ }
package/dist/blind.js ADDED
@@ -0,0 +1,216 @@
1
+ import { git as runGit } from './git.js';
2
+ import { createCipheriv, createDecipheriv, createHmac, hkdfSync, randomBytes } from 'node:crypto';
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { isAbsolute, join, relative } from 'node:path';
5
+ import { ARCROOM_HOME } from './home.js';
6
+ import { projectOf } from './session.js';
7
+ const mac = (key, s) => createHmac('sha256', key).update(s).digest('hex');
8
+ /** The three working keys and the fingerprint, all derived from the 32-byte team key. */
9
+ export function keysFrom(root) {
10
+ const sub = (info) => Buffer.from(hkdfSync('sha256', root, Buffer.alloc(0), info, 32));
11
+ return { root, fp: mac(root, 'arcroom fingerprint').slice(0, 16), path: sub('arcroom paths'), hash: sub('arcroom hashes'), enc: sub('arcroom notes') };
12
+ }
13
+ export const newKeys = () => keysFrom(randomBytes(32));
14
+ /** src/billing → k_7f3a…; the repo root stays "." (it says nothing). */
15
+ export const scramblePath = (k, rel) => (rel === '' || rel === '.' ? '.' : `k_${mac(k.path, rel).slice(0, 24)}`);
16
+ /** A git hash → c_…; the trailing * (uncommitted edits) is kept so "dirty" stays visible. */
17
+ export const scrambleHash = (k, h) => (h.endsWith('*') ? `c_${mac(k.hash, h.slice(0, -1)).slice(0, 24)}*` : `c_${mac(k.hash, h).slice(0, 24)}`);
18
+ /** A branch (b_) or repo (r_) name. */
19
+ export const scrambleName = (k, kind, name) => `${kind}_${mac(k.path, `${kind}:${name}`).slice(0, 20)}`;
20
+ export function encrypt(k, text) {
21
+ const iv = randomBytes(12);
22
+ const c = createCipheriv('aes-256-gcm', k.enc, iv);
23
+ const body = Buffer.concat([c.update(text, 'utf8'), c.final()]);
24
+ return `enc:v1:${Buffer.concat([iv, c.getAuthTag(), body]).toString('base64')}`;
25
+ }
26
+ /** The text, or undefined when it was sealed with another key. Plain text passes through. */
27
+ export function decrypt(k, sealed) {
28
+ if (!sealed.startsWith('enc:v1:'))
29
+ return sealed;
30
+ try {
31
+ const b = Buffer.from(sealed.slice(7), 'base64');
32
+ const d = createDecipheriv('aes-256-gcm', k.enc, b.subarray(0, 12));
33
+ d.setAuthTag(b.subarray(12, 28));
34
+ return Buffer.concat([d.update(b.subarray(28)), d.final()]).toString('utf8');
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ /** The key as a code to pass to a teammate, or to keep as the recovery code. */
41
+ export const keyCode = (k) => `arck1_${k.root.toString('base64url')}`;
42
+ export function fromCode(code) {
43
+ const m = /^arck1_([A-Za-z0-9_-]{43})$/.exec(code.trim());
44
+ if (!m)
45
+ throw new Error('that is not an ArcRoom key code (it starts with arck1_)');
46
+ return keysFrom(Buffer.from(m[1], 'base64url'));
47
+ }
48
+ const keyFile = (fp) => join(ARCROOM_HOME, 'keys', `${fp}.key`);
49
+ export function saveKey(k) {
50
+ mkdirSync(join(ARCROOM_HOME, 'keys'), { recursive: true });
51
+ writeFileSync(keyFile(k.fp), keyCode(k), { mode: 0o600 });
52
+ return keyFile(k.fp);
53
+ }
54
+ export function loadKey(fp) {
55
+ try {
56
+ const k = fromCode(readFileSync(keyFile(fp), 'utf8'));
57
+ return k.fp === fp ? k : undefined;
58
+ }
59
+ catch {
60
+ return undefined;
61
+ }
62
+ }
63
+ const git = (cwd, args) => {
64
+ const r = runGit(args, { cwd, timeout: 3000, maxBuffer: 64 * 1024 * 1024 });
65
+ return r.status === 0 ? r.stdout : undefined;
66
+ };
67
+ export const gitRoot = (cwd) => git(cwd, ['rev-parse', '--show-toplevel'])?.trim();
68
+ /** The repo's Code wing setup: its mode from .arcroom.json, and in Blind mode the key when this laptop has it. */
69
+ export function codeSetup(cwd) {
70
+ const root = cwd ? gitRoot(cwd) : undefined;
71
+ if (!root)
72
+ return undefined;
73
+ const cfg = readSetup(root);
74
+ const mode = cfg.code === 'blind' || cfg.code === 'off' ? cfg.code : 'standard';
75
+ // N12: a repo seen in Blind mode on this laptop stays Blind even if a commit takes it out of .arcroom.json;
76
+ // only the person here lowers it (arcroom code on|off)
77
+ const known = blindRepos()[root];
78
+ if (mode !== 'blind' && known)
79
+ return { root, mode: 'blind', fp: known, keys: loadKey(known) };
80
+ if (mode === 'blind' && typeof cfg.key === 'string' && known !== cfg.key)
81
+ rememberBlind(root, cfg.key);
82
+ return mode === 'blind' ? { root, mode, fp: cfg.key, keys: typeof cfg.key === 'string' ? loadKey(cfg.key) : undefined } : { root, mode };
83
+ }
84
+ /** Repos this laptop has seen in Blind mode: git root -> key fingerprint. */
85
+ const BLIND_REPOS = join(ARCROOM_HOME, 'blind-repos.json');
86
+ const blindRepos = () => {
87
+ try {
88
+ return JSON.parse(readFileSync(BLIND_REPOS, 'utf8'));
89
+ }
90
+ catch {
91
+ return {};
92
+ }
93
+ };
94
+ const saveBlindRepos = (repos) => {
95
+ mkdirSync(ARCROOM_HOME, { recursive: true, mode: 0o700 });
96
+ writeFileSync(BLIND_REPOS, JSON.stringify(repos, null, 2) + '\n', { mode: 0o600 });
97
+ };
98
+ const rememberBlind = (root, fp) => saveBlindRepos({ ...blindRepos(), [root]: fp });
99
+ /** The person chose another mode for this repo (arcroom code on|off): it is no longer kept Blind. */
100
+ export function forgetBlind(root) {
101
+ const { [root]: _gone, ...rest } = blindRepos();
102
+ saveBlindRepos(rest);
103
+ }
104
+ export function readSetup(root) {
105
+ try {
106
+ return JSON.parse(readFileSync(join(root, '.arcroom.json'), 'utf8'));
107
+ }
108
+ catch {
109
+ return {};
110
+ }
111
+ }
112
+ export function writeSetup(root, patch) {
113
+ const next = { ...readSetup(root), ...patch };
114
+ for (const [k, v] of Object.entries(next))
115
+ if (v === undefined)
116
+ delete next[k];
117
+ writeFileSync(join(root, '.arcroom.json'), JSON.stringify(next, null, 2) + '\n');
118
+ }
119
+ /** The repo id as the Room knows it: the git remote, scrambled in Blind mode. */
120
+ export const repoKey = (s) => (s.mode === 'blind' && s.keys ? scrambleName(s.keys, 'r', projectOf(s.root)) : projectOf(s.root));
121
+ export const branchKey = (s, branch) => (s.mode === 'blind' && s.keys ? scrambleName(s.keys, 'b', branch) : branch);
122
+ export const nodeKey = (s, rel) => (s.mode === 'blind' && s.keys ? scramblePath(s.keys, rel) : rel || '.');
123
+ export const hashKey = (s, h) => (s.mode === 'blind' && s.keys ? scrambleHash(s.keys, h) : h);
124
+ /** A path (absolute, or relative to `from`) as a repo path: "src/billing/tax.ts", or undefined outside the repo. */
125
+ export function repoPath(root, p, from = root) {
126
+ const rel = relative(root, isAbsolute(p) ? p : join(from, p)).replaceAll('\\', '/');
127
+ return rel.startsWith('..') || isAbsolute(rel) ? undefined : rel || '.';
128
+ }
129
+ /** Every scrambled id in this checkout → its path (files git knows about and their folders). */
130
+ export function pathMap(s) {
131
+ const map = new Map();
132
+ if (s.mode !== 'blind' || !s.keys)
133
+ return map;
134
+ const files = (git(s.root, ['ls-files', '--cached', '--others', '--exclude-standard']) ?? '').split('\n').filter(Boolean);
135
+ for (const f of files) {
136
+ map.set(scramblePath(s.keys, f), f);
137
+ for (let d = f.lastIndexOf('/'); d > 0; d = f.lastIndexOf('/', d - 1))
138
+ map.set(scramblePath(s.keys, f.slice(0, d)), f.slice(0, d));
139
+ }
140
+ return map;
141
+ }
142
+ /** Text with every k_… id this checkout knows turned back into its path. */
143
+ export const unscramble = (text, map) => (map.size ? text.replace(/k_[0-9a-f]{24}/g, (m) => map.get(m) ?? m) : text);
144
+ /** Paths inside a shell command: the repo folder becomes ".", files and folders that exist are scrambled. */
145
+ export function scrambleCommand(cmd, s, cwd) {
146
+ const rootFwd = s.root.replaceAll('\\', '/');
147
+ let out = cmd.split(s.root).join('.').split(rootFwd).join('.');
148
+ out = out.replace(/[\w@.\-/\\]+/g, (tok) => {
149
+ if (tok.length < 2 || !/[/\\.]/.test(tok) || /^\.+$/.test(tok))
150
+ return tok;
151
+ const rel = repoPath(s.root, tok, cwd);
152
+ if (!rel || rel === '.' || !existsSync(join(s.root, rel)))
153
+ return tok;
154
+ return scramblePath(s.keys, rel);
155
+ });
156
+ return out;
157
+ }
158
+ const CONTENT = ['content', 'old_string', 'new_string', 'edits', 'new_source'];
159
+ /**
160
+ * One event as it may leave a Blind laptop: paths scrambled, file contents and tool output dropped, the folder the
161
+ * agent runs in replaced by ".". Without the key nothing path-like is sent at all.
162
+ */
163
+ export function blindEvent(e, s) {
164
+ const k = s.keys;
165
+ const cwd = typeof e.cwd === 'string' ? e.cwd : s.root;
166
+ const path = (p) => {
167
+ if (typeof p !== 'string')
168
+ return p;
169
+ const rel = repoPath(s.root, p, cwd);
170
+ return !k ? 'hidden' : rel ? scramblePath(k, rel) : 'outside';
171
+ };
172
+ const d = { ...(e.data ?? {}) };
173
+ switch (e.type) {
174
+ case 'run.start':
175
+ d.project = k ? scrambleName(k, 'r', projectOf(s.root)) : undefined;
176
+ d.cwd = '.';
177
+ if (typeof d.branch === 'string')
178
+ d.branch = k ? scrambleName(k, 'b', d.branch) : undefined;
179
+ delete d.transcript;
180
+ break;
181
+ case 'tool.start': {
182
+ const i = { ...(typeof d.input === 'object' && d.input ? d.input : {}) };
183
+ for (const f of ['file_path', 'notebook_path', 'path'])
184
+ if (i[f] !== undefined)
185
+ i[f] = path(i[f]);
186
+ if (typeof i.command === 'string')
187
+ i.command = k ? scrambleCommand(i.command, s, cwd) : 'hidden';
188
+ for (const f of CONTENT)
189
+ delete i[f];
190
+ d.input = i;
191
+ break;
192
+ }
193
+ case 'tool.end':
194
+ delete d.output; // file contents and command output never leave a Blind laptop
195
+ break;
196
+ case 'turn.end':
197
+ if (d.files && typeof d.files === 'object')
198
+ d.files = k
199
+ ? Object.fromEntries(Object.entries(d.files).flatMap(([p, h]) => {
200
+ const rel = repoPath(s.root, p, cwd);
201
+ return rel ? [[scramblePath(k, rel), scrambleHash(k, String(h))]] : [];
202
+ }))
203
+ : undefined;
204
+ break;
205
+ case 'context':
206
+ delete d.text; // what ArcRoom handed over, already unscrambled on this laptop
207
+ break;
208
+ default:
209
+ if (String(e.type).startsWith('other.'))
210
+ return { ...e, cwd: undefined, data: {} };
211
+ }
212
+ for (const [key, v] of Object.entries(d))
213
+ if (v === undefined)
214
+ delete d[key];
215
+ return { ...e, cwd: undefined, data: d };
216
+ }