@tinchu0/knitt 0.1.0-beta.2 → 0.1.0-beta.4

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 (31) hide show
  1. package/README.md +15 -20
  2. package/dist/apps/server/src/server.js +37 -147
  3. package/dist/packages/adapters/src/cli.js +15 -163
  4. package/dist/packages/adapters/src/command.js +18 -149
  5. package/dist/packages/adapters/src/hooks.js +23 -96
  6. package/dist/packages/adapters/src/launch.js +3 -10
  7. package/dist/packages/adapters/src/repository.js +5 -21
  8. package/dist/packages/adapters/src/transcript.js +15 -70
  9. package/dist/packages/installer/src/cli.js +75 -190
  10. package/dist/packages/installer/src/connections.js +81 -209
  11. package/dist/packages/installer/src/platform.js +55 -0
  12. package/dist/packages/installer/src/runtime.js +37 -94
  13. package/dist/packages/memory/src/store.js +23 -201
  14. package/dist/scripts/connector-setup.js +1 -1
  15. package/dist/skills/{continue-chat → knit}/SKILL.md +2 -2
  16. package/docs/clients/connector-setup.md +1 -1
  17. package/docs/clients/npm-installation.md +32 -18
  18. package/docs/clients/support-matrix.md +37 -0
  19. package/docs/usage.md +179 -0
  20. package/package.json +5 -4
  21. package/dist/apps/server/src/conversation-server.js +0 -203
  22. package/dist/memory-schema.json +0 -1
  23. package/dist/packages/adapters/src/discovery.js +0 -128
  24. package/dist/packages/adapters/src/providers/jsonl.js +0 -105
  25. package/dist/packages/adapters/src/status.js +0 -81
  26. package/dist/packages/contracts/src/conversations.js +0 -30
  27. package/dist/packages/memory/src/checkpoints.js +0 -68
  28. package/dist/packages/memory/src/context.js +0 -91
  29. package/dist/packages/memory/src/conversations.js +0 -148
  30. package/dist/packages/memory/src/migrations.js +0 -55
  31. package/docs/clients/local-agent-memory.md +0 -50
@@ -1,25 +1,21 @@
1
- import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync, } from "node:fs";
2
- import { join, dirname, resolve } from "node:path";
3
- import { execFileSync } from "node:child_process";
4
- import { randomUUID } from "node:crypto";
5
- import { parse as parseToml } from "smol-toml";
6
- export const clients = [
7
- "codex",
8
- "claude-code",
9
- "antigravity",
10
- "claude-desktop",
11
- ];
12
- const begin = "# BEGIN shared-agent-memory", end = "# END shared-agent-memory";
13
- const statePath = ".memory/npm-connection.json";
14
- const read = (path) => existsSync(path) ? readFileSync(path, "utf8") : null;
15
- const dump = (v) => JSON.stringify(v, null, 2) + "\n";
16
- const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
1
+ import { hookCommand, isManagedHook } from './platform.js';
2
+ import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync } from 'node:fs';
3
+ import { join, dirname, resolve } from 'node:path';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { parse as parseToml } from 'smol-toml';
7
+ export const clients = ['codex', 'claude-code', 'antigravity', 'claude-desktop'];
8
+ const begin = '# BEGIN shared-agent-memory', end = '# END shared-agent-memory';
9
+ const statePath = '.memory/npm-connection.json';
10
+ const read = (path) => existsSync(path) ? readFileSync(path, 'utf8') : null;
11
+ const dump = (v) => JSON.stringify(v, null, 2) + '\n';
12
+ const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
17
13
  const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
18
14
  export function atomicWrite(path, content) {
19
15
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
20
- const temporary = path + "." + randomUUID() + ".tmp";
16
+ const temporary = path + '.' + randomUUID() + '.tmp';
21
17
  try {
22
- writeFileSync(temporary, content, { mode: 0o600, flag: "wx" });
18
+ writeFileSync(temporary, content, { mode: 0o600, flag: 'wx' });
23
19
  renameSync(temporary, path);
24
20
  }
25
21
  finally {
@@ -31,19 +27,11 @@ export function atomicWrite(path, content) {
31
27
  function restore(before, after, current) {
32
28
  if (equal(current, after))
33
29
  return before;
34
- if (object(after) &&
35
- object(current) &&
36
- typeof after.command === "string" &&
37
- Array.isArray(after.args))
30
+ if (object(after) && object(current) && typeof after.command === 'string' && Array.isArray(after.args))
38
31
  return current;
39
- if (object(after) &&
40
- object(current) &&
41
- (before === undefined || object(before))) {
32
+ if (object(after) && object(current) && (before === undefined || object(before))) {
42
33
  const result = { ...current };
43
- for (const key of new Set([
44
- ...Object.keys(before ?? {}),
45
- ...Object.keys(after),
46
- ])) {
34
+ for (const key of new Set([...Object.keys(before ?? {}), ...Object.keys(after)])) {
47
35
  if (equal(before?.[key], after[key]))
48
36
  continue;
49
37
  const value = restore(before?.[key], after[key], current[key]);
@@ -52,18 +40,14 @@ function restore(before, after, current) {
52
40
  else
53
41
  result[key] = value;
54
42
  }
55
- return Object.keys(result).length === 0 && before === undefined
56
- ? undefined
57
- : result;
43
+ return Object.keys(result).length === 0 && before === undefined ? undefined : result;
58
44
  }
59
- if (Array.isArray(after) &&
60
- Array.isArray(current) &&
61
- (before === undefined || Array.isArray(before))) {
45
+ if (Array.isArray(after) && Array.isArray(current) && (before === undefined || Array.isArray(before))) {
62
46
  const previous = before ?? [];
63
- const added = after.filter((v) => !previous.some((p) => equal(p, v)));
64
- const result = current.filter((v) => !added.some((a) => equal(a, v)));
47
+ const added = after.filter(v => !previous.some((p) => equal(p, v)));
48
+ const result = current.filter(v => !added.some(a => equal(a, v)));
65
49
  for (const v of previous)
66
- if (!after.some((a) => equal(a, v)) && !result.some((a) => equal(a, v)))
50
+ if (!after.some(a => equal(a, v)) && !result.some(a => equal(a, v)))
67
51
  result.push(v);
68
52
  return result.length === 0 && before === undefined ? undefined : result;
69
53
  }
@@ -75,128 +59,59 @@ export function readConnectionState(workspace) {
75
59
  return { schema: 1, files: {} };
76
60
  const value = JSON.parse(text);
77
61
  if (value.schema !== 1 || !object(value.files))
78
- throw new Error("Unsupported connector state");
62
+ throw new Error('Unsupported connector state');
79
63
  for (const [file, snapshot] of Object.entries(value.files)) {
80
- if (![
81
- ".mcp.json",
82
- ".codex/config.toml",
83
- ".codex/hooks.json",
84
- ".agents/hooks.json",
85
- ".agents/mcp_config.json",
86
- ".agents/skills/continue-chat/SKILL.md",
87
- ".claude/settings.local.json",
88
- ".claude/skills/continue-chat/SKILL.md",
89
- ".memory/connectors/claude-desktop.json",
90
- ].includes(file) ||
91
- !object(snapshot) ||
92
- typeof snapshot.after !== "string" ||
93
- !(snapshot.before === null || typeof snapshot.before === "string"))
94
- throw new Error("Invalid connector state");
64
+ if (!['.mcp.json', '.codex/config.toml', '.codex/hooks.json', '.agents/hooks.json', '.agents/mcp_config.json', '.agents/skills/continue-chat/SKILL.md', '.agents/skills/knit/SKILL.md', '.claude/settings.local.json', '.claude/skills/continue-chat/SKILL.md', '.claude/skills/knit/SKILL.md', '.memory/connectors/claude-desktop.json'].includes(file)
65
+ || !object(snapshot) || typeof snapshot.after !== 'string' || !(snapshot.before === null || typeof snapshot.before === 'string'))
66
+ throw new Error('Invalid connector state');
95
67
  }
96
68
  return value;
97
69
  }
98
70
  export function planConnection(opts) {
99
- if (process.platform === "win32")
100
- throw new Error("Windows hook installation is not yet validated. Use WSL for this preview.");
101
71
  const workspace = realpathSync(opts.workspace), app = resolve(opts.appRoot), node = opts.node ?? process.execPath;
102
- if (!opts.clients.length ||
103
- opts.clients.some((c) => !clients.includes(c)))
104
- throw new Error("Choose a supported client");
105
- const extension = existsSync(join(app, "apps/server/src/main.js"))
106
- ? "js"
107
- : "ts";
108
- const server = join(app, "apps/server/src/main." + extension), runner = join(app, "packages/adapters/src/cli." + extension);
72
+ if (!opts.clients.length || opts.clients.some(c => !clients.includes(c)))
73
+ throw new Error('Choose a supported client');
74
+ const extension = existsSync(join(app, 'apps/server/src/main.js')) ? 'js' : 'ts';
75
+ const server = join(app, 'apps/server/src/main.' + extension), runner = join(app, 'packages/adapters/src/cli.' + extension);
109
76
  if (!existsSync(server) || !existsSync(runner))
110
- throw new Error("Runtime files missing");
77
+ throw new Error('Runtime files missing');
111
78
  const state = readConnectionState(workspace), changes = {}, expected = {};
112
- const get = (path) => {
113
- const content = read(join(workspace, path));
114
- expected[path] = content;
115
- return content;
116
- };
117
- const json = (path) => {
118
- const v = JSON.parse(get(path) ?? "{}");
119
- if (!object(v))
120
- throw new Error(path + " must be an object");
121
- return v;
122
- };
123
- const env = {
124
- MEMORY_DB: resolve(opts.database),
125
- MEMORY_REPO: opts.repoId,
126
- MEMORY_WORKSPACE: workspace,
127
- MEMORY_SESSION_SELECTION: "1",
128
- ...(opts.captureNewSessions
129
- ? { MEMORY_CONVERSATION_MODE: "1", MEMORY_CAPTURE_NEW_SESSIONS: "1" }
130
- : {}),
131
- };
132
- const quote = (s) => "'" + s.replaceAll("'", "'\\''") + "'";
133
- const handler = (client, action) => ({
134
- type: "command",
135
- timeout: 10,
136
- command: [
137
- "env",
138
- ...Object.entries({
139
- ...env,
140
- MEMORY_QUEUE: join(dirname(opts.database), "queue", client),
141
- MEMORY_MANAGED: "shared-agent-memory",
142
- }).map(([k, v]) => k + "=" + v),
143
- node,
144
- runner,
145
- action,
146
- client,
147
- ]
148
- .map(quote)
149
- .join(" "),
150
- });
151
- const connection = (desktop = false, client = "claude") => {
152
- const clientEnv = {
153
- ...env,
154
- ...(desktop ? { MEMORY_CHAT_CLIENT: "claude-desktop" } : {}),
155
- ...(!desktop && opts.captureNewSessions ? { MEMORY_CLIENT: client } : {}),
156
- };
157
- if (desktop) {
158
- delete clientEnv.MEMORY_CONVERSATION_MODE;
159
- delete clientEnv.MEMORY_CAPTURE_NEW_SESSIONS;
160
- }
161
- return { command: node, args: [server], env: clientEnv };
162
- };
79
+ const get = (path) => { const content = read(join(workspace, path)); expected[path] = content; return content; };
80
+ const json = (path) => { const v = JSON.parse(get(path) ?? '{}'); if (!object(v))
81
+ throw new Error(path + ' must be an object'); return v; };
82
+ const env = { MEMORY_DB: resolve(opts.database), MEMORY_REPO: opts.repoId, MEMORY_WORKSPACE: workspace, MEMORY_SESSION_SELECTION: '1' };
83
+ const handler = (client, action) => ({ type: 'command', timeout: 10, command: hookCommand({ ...env, MEMORY_QUEUE: join(dirname(opts.database), 'queue', client), MEMORY_MANAGED: 'shared-agent-memory' }, node, [runner, action, client]) });
84
+ const connection = (desktop = false) => ({ command: node, args: [server], env: { ...env, ...(desktop ? { MEMORY_CHAT_CLIENT: 'claude-desktop' } : {}) } });
163
85
  function owned(path, location, current) {
164
86
  if (current === undefined)
165
87
  return;
166
88
  const prior = state.files[path];
167
- const previous = prior
168
- ? location.reduce((v, key) => v?.[key], JSON.parse(prior.after))
169
- : undefined;
89
+ const previous = prior ? location.reduce((v, key) => v?.[key], JSON.parse(prior.after)) : undefined;
170
90
  if (!equal(current, previous))
171
- throw new Error("Unmanaged or modified connector conflict in " + path);
91
+ throw new Error('Unmanaged or modified connector conflict in ' + path);
172
92
  }
173
- function mcp(path, desktop = false, client = "claude") {
93
+ function mcp(path, desktop = false) {
174
94
  const value = json(path);
175
95
  value.mcpServers ??= {};
176
- owned(path, ["mcpServers", "shared-memory"], value.mcpServers["shared-memory"]);
177
- value.mcpServers["shared-memory"] = connection(desktop, client);
96
+ owned(path, ['mcpServers', 'shared-memory'], value.mcpServers['shared-memory']);
97
+ value.mcpServers['shared-memory'] = connection(desktop);
178
98
  changes[path] = dump(value);
179
99
  }
180
100
  function hooks(path, client) {
181
101
  const value = json(path);
182
102
  value.hooks ??= {};
183
- const prior = state.files[path]
184
- ? JSON.parse(state.files[path].after).hooks
185
- : {};
186
- for (const [event, action] of [
187
- ["SessionStart", "recall"],
188
- ["Stop", "capture"],
189
- ]) {
103
+ const prior = state.files[path] ? JSON.parse(state.files[path].after).hooks : {};
104
+ for (const [event, action] of [['SessionStart', 'recall'], ['Stop', 'capture']]) {
190
105
  const old = prior?.[event] ?? [];
191
106
  const groups = value.hooks[event] ?? [];
192
107
  if (!Array.isArray(groups))
193
- throw new Error("Invalid hooks in " + path);
108
+ throw new Error('Invalid hooks in ' + path);
194
109
  // Only remove exact previously generated handlers. Edited handlers remain;
195
110
  // reject if they mention our runner to avoid duplicate capture.
196
- const oldOwned = old.filter((g) => g.hooks?.some((h) => h.command?.includes("MEMORY_MANAGED=shared-agent-memory")));
111
+ const oldOwned = old.filter((g) => g.hooks?.some((h) => isManagedHook(h.command)));
197
112
  const kept = groups.filter((g) => !oldOwned.some((p) => equal(p, g)));
198
- if (kept.some((g) => g.hooks?.some((h) => h.command?.includes("MEMORY_MANAGED=shared-agent-memory"))))
199
- throw new Error("Modified hook conflict in " + path);
113
+ if (kept.some((g) => g.hooks?.some((h) => isManagedHook(h.command))))
114
+ throw new Error('Modified hook conflict in ' + path);
200
115
  value.hooks[event] = [...kept, { hooks: [handler(client, action)] }];
201
116
  }
202
117
  changes[path] = dump(value);
@@ -204,72 +119,45 @@ export function planConnection(opts) {
204
119
  function skill(path) {
205
120
  const current = get(path);
206
121
  if (current && current !== state.files[path]?.after)
207
- throw new Error("Unmanaged or modified skill conflict");
208
- changes[path] = readFileSync(join(app, "skills/continue-chat/SKILL.md"), "utf8");
122
+ throw new Error('Unmanaged or modified skill conflict');
123
+ changes[path] = readFileSync(join(app, 'skills/knit/SKILL.md'), 'utf8');
209
124
  }
210
125
  for (const client of opts.clients) {
211
- if (client === "claude-code") {
212
- mcp(".mcp.json");
213
- hooks(".claude/settings.local.json", "claude");
214
- skill(".claude/skills/continue-chat/SKILL.md");
126
+ if (client === 'claude-code') {
127
+ mcp('.mcp.json');
128
+ hooks('.claude/settings.local.json', 'claude');
129
+ skill('.claude/skills/knit/SKILL.md');
215
130
  }
216
- if (client === "claude-desktop")
217
- mcp(".memory/connectors/claude-desktop.json", true);
218
- if (client === "antigravity") {
219
- mcp(".agents/mcp_config.json", false, "antigravity");
220
- const path = ".agents/hooks.json", value = json(path);
221
- owned(path, ["shared-memory"], value["shared-memory"]);
222
- value["shared-memory"] = {
223
- SessionStart: [handler("antigravity", "recall")],
224
- Stop: [handler("antigravity", "capture")],
225
- };
131
+ if (client === 'claude-desktop')
132
+ mcp('.memory/connectors/claude-desktop.json', true);
133
+ if (client === 'antigravity') {
134
+ mcp('.agents/mcp_config.json');
135
+ const path = '.agents/hooks.json', value = json(path);
136
+ owned(path, ['shared-memory'], value['shared-memory']);
137
+ value['shared-memory'] = { SessionStart: [handler('antigravity', 'recall')], Stop: [handler('antigravity', 'capture')] };
226
138
  changes[path] = dump(value);
227
139
  }
228
- if (client === "codex") {
229
- skill(".agents/skills/continue-chat/SKILL.md");
230
- hooks(".codex/hooks.json", "codex");
231
- const path = ".codex/config.toml", current = get(path) ?? "";
140
+ if (client === 'codex') {
141
+ skill('.agents/skills/knit/SKILL.md');
142
+ hooks('.codex/hooks.json', 'codex');
143
+ const path = '.codex/config.toml', current = get(path) ?? '';
232
144
  const parsed = parseToml(current);
233
145
  let base = current;
234
146
  if (current.includes(begin)) {
235
147
  const previous = state.files[path];
236
148
  const block = current.slice(current.indexOf(begin), current.indexOf(end) + end.length);
237
149
  if (!previous || !previous.after.includes(block))
238
- throw new Error("Modified or unmanaged Codex config conflict");
239
- base = current.replace(block, "");
150
+ throw new Error('Modified or unmanaged Codex config conflict');
151
+ base = current.replace(block, '');
240
152
  }
241
- else if (parsed.mcp_servers?.["shared-memory"])
242
- throw new Error("Unmanaged Codex server conflict");
243
- changes[path] =
244
- base.trimEnd() +
245
- "\n\n" +
246
- begin +
247
- '\n[mcp_servers.shared-memory]\ndefault_tools_approval_mode = "writes"\ncommand = ' +
248
- JSON.stringify(node) +
249
- "\nargs = " +
250
- JSON.stringify([server]) +
251
- "\ncwd = " +
252
- JSON.stringify(workspace) +
253
- "\nenv = { " +
254
- Object.entries({
255
- ...env,
256
- ...(opts.captureNewSessions ? { MEMORY_CLIENT: "codex" } : {}),
257
- })
258
- .map(([k, v]) => k + " = " + JSON.stringify(v))
259
- .join(", ") +
260
- ' }\ntools.choose_conversation.approval_mode = "approve"\n' +
261
- end +
262
- "\n";
153
+ else if (parsed.mcp_servers?.['shared-memory'])
154
+ throw new Error('Unmanaged Codex server conflict');
155
+ changes[path] = base.trimEnd() + '\n\n' + begin + '\n[mcp_servers.shared-memory]\ndefault_tools_approval_mode = "writes"\ncommand = ' + JSON.stringify(node) + '\nargs = ' + JSON.stringify([server]) + '\ncwd = ' + JSON.stringify(workspace) + '\nenv = { ' + Object.entries(env).map(([k, v]) => k + ' = ' + JSON.stringify(v)).join(', ') + ' }\ntools.choose_conversation.approval_mode = "approve"\n' + end + '\n';
263
156
  parseToml(changes[path]);
264
157
  }
265
158
  }
266
159
  for (const [path, after] of Object.entries(changes))
267
- state.files[path] = {
268
- before: state.files[path]
269
- ? unapply(path, state.files[path], expected[path] ?? null)
270
- : (expected[path] ?? null),
271
- after,
272
- };
160
+ state.files[path] = { before: state.files[path] ? unapply(path, state.files[path], expected[path] ?? null) : expected[path] ?? null, after };
273
161
  expected[statePath] = read(join(workspace, statePath));
274
162
  changes[statePath] = dump(state);
275
163
  return { workspace, changes, expected };
@@ -278,7 +166,7 @@ export function applyConnectionPlan(plan) {
278
166
  // Optimistic concurrency prevents applying a preview over later user edits.
279
167
  for (const [path, expected] of Object.entries(plan.expected))
280
168
  if (read(join(plan.workspace, path)) !== expected)
281
- throw new Error("Configuration changed since preview: " + path);
169
+ throw new Error('Configuration changed since preview: ' + path);
282
170
  const written = [];
283
171
  try {
284
172
  for (const [path, content] of Object.entries(plan.changes)) {
@@ -300,39 +188,25 @@ export function applyConnectionPlan(plan) {
300
188
  throw error;
301
189
  }
302
190
  try {
303
- const git = execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
304
- cwd: plan.workspace,
305
- encoding: "utf8",
306
- stdio: ["ignore", "pipe", "ignore"],
307
- }).trim();
308
- const path = join(git, "info/exclude"), current = read(path) ?? "";
309
- const entries = [
310
- "/.memory/",
311
- ...Object.keys(plan.changes)
312
- .filter((p) => !p.startsWith(".memory/"))
313
- .map((p) => "/" + p),
314
- ];
315
- atomicWrite(path, current +
316
- "\n" +
317
- entries.filter((p) => !current.split("\n").includes(p)).join("\n") +
318
- "\n");
319
- }
320
- catch {
321
- /* Non-Git projects can use the planner; CLI validates Git separately. */
191
+ const git = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: plan.workspace, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
192
+ const path = join(git, 'info/exclude'), current = read(path) ?? '';
193
+ const entries = ['/.memory/', ...Object.keys(plan.changes).filter(p => !p.startsWith('.memory/')).map(p => '/' + p)];
194
+ atomicWrite(path, current + '\n' + entries.filter(p => !current.split('\n').includes(p)).join('\n') + '\n');
322
195
  }
196
+ catch { /* Non-Git projects can use the planner; CLI validates Git separately. */ }
323
197
  }
324
198
  function unapply(path, snapshot, current) {
325
199
  const { before, after } = snapshot;
326
200
  if (current === null || current === after)
327
201
  return current === null ? null : before;
328
- if (path.endsWith(".json")) {
202
+ if (path.endsWith('.json')) {
329
203
  const restored = restore(before === null ? undefined : JSON.parse(before), JSON.parse(after), JSON.parse(current));
330
204
  return restored === undefined ? null : dump(restored);
331
205
  }
332
- if (path.endsWith(".toml")) {
206
+ if (path.endsWith('.toml')) {
333
207
  const block = after.slice(after.indexOf(begin), after.indexOf(end) + end.length);
334
208
  if (current.includes(block))
335
- return current.replace(block, "").trim() || before;
209
+ return current.replace(block, '').trim() || before;
336
210
  }
337
211
  return current;
338
212
  }
@@ -347,6 +221,4 @@ export function planUninstall(workspace) {
347
221
  changes[statePath] = null;
348
222
  return { workspace, changes, expected };
349
223
  }
350
- export function uninstallConnections(workspace) {
351
- applyConnectionPlan(planUninstall(workspace));
352
- }
224
+ export function uninstallConnections(workspace) { applyConnectionPlan(planUninstall(workspace)); }
@@ -0,0 +1,55 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ /** Resolve npm's JavaScript entry point on Windows: execFile cannot run npm.cmd.
4
+ * All package arguments stay in an argv array, never a command shell. */
5
+ export function npmCommand(args, options = {}) {
6
+ const platform = options.platform ?? process.platform, env = options.env ?? process.env, node = options.node ?? process.execPath;
7
+ if (platform !== 'win32')
8
+ return { command: 'npm', args };
9
+ const path = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] ?? '';
10
+ const candidates = [
11
+ ...(env.npm_execpath ? [join(dirname(env.npm_execpath), 'npm-cli.js')] : []),
12
+ join(dirname(node), 'node_modules/npm/bin/npm-cli.js'),
13
+ ...path.split(';').filter(Boolean).map(directory => join(directory.replace(/^"|"$/g, ''), 'node_modules/npm/bin/npm-cli.js')),
14
+ ];
15
+ const cli = candidates.find(candidate => existsSync(candidate));
16
+ if (!cli)
17
+ throw new Error('Cannot locate npm. Install Node.js 24+ with npm and add it to PATH.');
18
+ return { command: node, args: [cli, ...args] };
19
+ }
20
+ const marker = 'MEMORY_MANAGED=shared-agent-memory';
21
+ const powershell = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ';
22
+ /** Serialize a hook for the host shell without interpolating data as code. */
23
+ export function hookCommand(env, node, args, platform = process.platform) {
24
+ if (platform !== 'win32') {
25
+ const quote = (s) => "'" + s.replaceAll("'", "'\\''") + "'";
26
+ return ['env', ...Object.entries(env).map(([key, value]) => key + '=' + value), node, ...args].map(quote).join(' ');
27
+ }
28
+ const quote = (s) => "'" + s.replaceAll("'", "''") + "'";
29
+ // EncodedCommand avoids cmd.exe expanding %, &, or Unicode paths. PowerShell
30
+ // invokes Node directly with inherited stdin; no pipeline re-encodes hook JSON.
31
+ const assignments = Object.entries(env).map(([key, value]) => {
32
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
33
+ throw new Error('Invalid hook environment key');
34
+ return '$env:' + key + '=' + quote(value) + ';';
35
+ }).join('');
36
+ const script = '[Console]::InputEncoding=[Console]::OutputEncoding=New-Object System.Text.UTF8Encoding;' +
37
+ assignments + '& ' + [node, ...args].map(quote).join(' ') + ';exit $LASTEXITCODE';
38
+ return powershell + Buffer.from(script, 'utf16le').toString('base64');
39
+ }
40
+ export function isManagedHook(command) {
41
+ if (typeof command !== 'string')
42
+ return false;
43
+ if (command.includes(marker))
44
+ return true; // Existing POSIX installations.
45
+ // PowerShell switches are case-insensitive and can be abbreviated/reordered.
46
+ // Recognize the payload even after a launcher edit so setup rejects conflicts.
47
+ for (const match of command.matchAll(/(?:^|\s)-([a-z]+)\s+(['"]?)([a-z0-9+/=]+)\2(?=\s|$)/gi)) {
48
+ if (!'encodedcommand'.startsWith(match[1].toLowerCase()))
49
+ continue;
50
+ const script = Buffer.from(match[3], 'base64').toString('utf16le');
51
+ if (/\$env:MEMORY_MANAGED\s*=\s*(['"])shared-agent-memory\1\s*;/i.test(script))
52
+ return true;
53
+ }
54
+ return false;
55
+ }
@@ -1,50 +1,41 @@
1
- import { DatabaseSync } from "node:sqlite";
2
- import { homedir } from "node:os";
3
- import { join, resolve } from "node:path";
4
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, mkdtempSync, writeFileSync, } from "node:fs";
5
- import { execFileSync } from "node:child_process";
6
- import { randomUUID } from "node:crypto";
7
- import { atomicWrite } from "./connections.js";
8
- export const packageName = "@tinchu0/knitt";
1
+ import { homedir } from 'node:os';
2
+ import { join, resolve } from 'node:path';
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, mkdtempSync, writeFileSync } from 'node:fs';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { npmCommand } from './platform.js';
7
+ import { atomicWrite } from './connections.js';
8
+ export const packageName = '@tinchu0/knitt';
9
9
  export function defaultHome() {
10
10
  if (process.env.SHARED_MEMORY_HOME)
11
11
  return resolve(process.env.SHARED_MEMORY_HOME);
12
- if (process.platform === "darwin")
13
- return join(homedir(), "Library/Application Support/SharedAgentMemory");
14
- if (process.platform === "win32")
15
- return join(process.env.LOCALAPPDATA ?? join(homedir(), "AppData/Local"), "SharedAgentMemory");
16
- return join(process.env.XDG_DATA_HOME ?? join(homedir(), ".local/share"), "shared-agent-memory");
17
- }
18
- export function runtimePaths(home) {
19
- return {
20
- data: join(home, "data"),
21
- versions: join(home, "versions"),
22
- state: join(home, "installation.json"),
23
- };
12
+ if (process.platform === 'darwin')
13
+ return join(homedir(), 'Library/Application Support/SharedAgentMemory');
14
+ if (process.platform === 'win32')
15
+ return join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData/Local'), 'SharedAgentMemory');
16
+ return join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local/share'), 'shared-agent-memory');
24
17
  }
18
+ export function runtimePaths(home) { return { data: join(home, 'data'), versions: join(home, 'versions'), state: join(home, 'installation.json') }; }
25
19
  export function readInstallation(home) {
26
20
  const path = runtimePaths(home).state;
27
21
  if (!existsSync(path))
28
22
  return null;
29
- const value = JSON.parse(readFileSync(path, "utf8"));
30
- if (value.schema !== 1 ||
31
- !value.current?.appRoot ||
32
- !Array.isArray(value.projects))
33
- throw new Error("Invalid installation metadata");
23
+ const value = JSON.parse(readFileSync(path, 'utf8'));
24
+ if (value.schema !== 1 || !value.current?.appRoot || !Array.isArray(value.projects))
25
+ throw new Error('Invalid installation metadata');
34
26
  return value;
35
27
  }
36
28
  export async function withInstallLock(home, work) {
37
29
  mkdirSync(home, { recursive: true, mode: 0o700 });
38
- const lock = join(home, "install.lock");
30
+ const lock = join(home, 'install.lock');
39
31
  try {
40
32
  mkdirSync(lock, { mode: 0o700 });
41
33
  }
42
34
  catch {
43
- throw new Error("Another installation is running, or a stale install.lock remains. Check for a running setup process before removing " +
44
- lock);
35
+ throw new Error('Another installation is running, or a stale install.lock remains. Check for a running setup process before removing ' + lock);
45
36
  }
46
37
  try {
47
- writeFileSync(join(lock, "owner.json"), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }), { mode: 0o600 });
38
+ writeFileSync(join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }), { mode: 0o600 });
48
39
  return await work();
49
40
  }
50
41
  finally {
@@ -52,48 +43,28 @@ export async function withInstallLock(home, work) {
52
43
  }
53
44
  }
54
45
  export function installRuntime(home, spec) {
55
- if (process.platform === "win32")
56
- throw new Error("Windows installer validation is pending; use WSL for this preview.");
57
- if (Number(process.versions.node.split(".")[0]) < 24)
58
- throw new Error("Node.js 24 or newer is required");
46
+ if (Number(process.versions.node.split('.')[0]) < 24)
47
+ throw new Error('Node.js 24 or newer is required');
59
48
  const paths = runtimePaths(home);
60
49
  mkdirSync(paths.versions, { recursive: true, mode: 0o700 });
61
50
  mkdirSync(paths.data, { recursive: true, mode: 0o700 });
62
- const staging = mkdtempSync(join(paths.versions, ".staging-"));
51
+ const staging = mkdtempSync(join(paths.versions, '.staging-'));
63
52
  try {
64
- writeFileSync(join(staging, "package.json"), JSON.stringify({ name: "shared-memory-runtime", private: true }), { mode: 0o600 });
53
+ writeFileSync(join(staging, 'package.json'), JSON.stringify({ name: 'shared-memory-runtime', private: true }), { mode: 0o600 });
65
54
  // Arguments are passed directly; no shell interpolation or install lifecycle scripts.
66
- execFileSync("npm", [
67
- "install",
68
- "--prefix",
69
- staging,
70
- "--ignore-scripts",
71
- "--omit=dev",
72
- "--no-audit",
73
- "--no-fund",
74
- "--save-exact",
75
- "--",
76
- spec,
77
- ], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 180_000 });
78
- const root = join(staging, "node_modules", packageName);
79
- const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
80
- if (pkg.name !== packageName ||
81
- !/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(pkg.version))
82
- throw new Error("Unexpected runtime package");
83
- for (const file of [
84
- "apps/server/src/main.js",
85
- "packages/installer/src/cli.js",
86
- ])
87
- if (!existsSync(join(root, "dist", file)))
88
- throw new Error("Incomplete runtime: " + file);
89
- execFileSync(process.execPath, [join(root, "dist/packages/installer/src/cli.js"), "--version"], { encoding: "utf8", timeout: 10_000 });
90
- const destination = join(paths.versions, pkg.version + "-" + randomUUID());
55
+ const npm = npmCommand(['install', '--prefix', staging, '--ignore-scripts', '--omit=dev', '--no-audit', '--no-fund', '--save-exact', '--', spec]);
56
+ execFileSync(npm.command, npm.args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 180_000 });
57
+ const root = join(staging, 'node_modules', packageName);
58
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
59
+ if (pkg.name !== packageName || !/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(pkg.version))
60
+ throw new Error('Unexpected runtime package');
61
+ for (const file of ['apps/server/src/main.js', 'packages/installer/src/cli.js'])
62
+ if (!existsSync(join(root, 'dist', file)))
63
+ throw new Error('Incomplete runtime: ' + file);
64
+ execFileSync(process.execPath, [join(root, 'dist/packages/installer/src/cli.js'), '--version'], { encoding: 'utf8', timeout: 10_000 });
65
+ const destination = join(paths.versions, pkg.version + '-' + randomUUID());
91
66
  renameSync(staging, destination);
92
- return {
93
- version: pkg.version,
94
- node: process.execPath,
95
- appRoot: join(destination, "node_modules", packageName, "dist"),
96
- };
67
+ return { version: pkg.version, node: process.execPath, appRoot: join(destination, 'node_modules', packageName, 'dist') };
97
68
  }
98
69
  finally {
99
70
  rmSync(staging, { recursive: true, force: true });
@@ -101,33 +72,5 @@ export function installRuntime(home, spec) {
101
72
  }
102
73
  export function activateRuntime(home, current, projects) {
103
74
  const previous = readInstallation(home);
104
- atomicWrite(runtimePaths(home).state, JSON.stringify({
105
- schema: 1,
106
- current,
107
- previous: previous?.current,
108
- projects,
109
- }, null, 2) + "\n");
110
- }
111
- export function assertRuntimeCompatibility(runtime, projects) {
112
- const marker = join(runtime.appRoot, "memory-schema.json");
113
- const supported = existsSync(marker)
114
- ? JSON.parse(readFileSync(marker, "utf8")).supportedSchema
115
- : 0;
116
- if (!Number.isInteger(supported) || supported < 0)
117
- throw new Error("Invalid runtime schema compatibility metadata");
118
- for (const database of new Set(projects.map((p) => p.database))) {
119
- if (!existsSync(database))
120
- continue;
121
- const db = new DatabaseSync(database, { readOnly: true });
122
- try {
123
- const actual = Number(db.prepare("PRAGMA user_version").get().user_version);
124
- if (actual > supported)
125
- throw new Error("Runtime is incompatible with memory schema " +
126
- actual +
127
- ". Use a compatible runtime or explicitly restore a consistent backup; no data was changed.");
128
- }
129
- finally {
130
- db.close();
131
- }
132
- }
75
+ atomicWrite(runtimePaths(home).state, JSON.stringify({ schema: 1, current, previous: previous?.current, projects }, null, 2) + '\n');
133
76
  }