agent-lyra 0.6.2 → 0.6.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 (108) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +235 -435
  3. package/bin/agent-lyra.js +49 -49
  4. package/bin/lyra-oss-preview.js +16 -14
  5. package/package.json +60 -60
  6. package/src/app-builder/export.js +109 -109
  7. package/src/app-builder/gateway.js +62 -62
  8. package/src/app-builder/init.js +52 -52
  9. package/src/app-builder/manifest-contract.js +46 -46
  10. package/src/app-builder/native-adapter.js +29 -29
  11. package/src/app-builder/preview.js +22 -22
  12. package/src/app-builder/publish.js +14 -14
  13. package/src/app-builder/saved-app.js +70 -70
  14. package/src/app-builder/saved-preview-browser.js +33 -33
  15. package/src/app-builder/saved-preview.html +24 -24
  16. package/src/app-builder/saved-preview.js +61 -61
  17. package/src/app-builder/support-manifest.js +50 -50
  18. package/src/app-builder/support-template/manifest.json +55 -55
  19. package/src/app-builder/support-template/support-preview.html +56 -56
  20. package/src/app-builder/support-template/support-preview.js +37 -37
  21. package/src/app-builder/support-template/support-preview.mjs +67 -67
  22. package/src/app-builder/support-template/support-workflow.mjs +36 -36
  23. package/src/app-builder/use.js +37 -37
  24. package/src/app-builder/validate.js +21 -21
  25. package/src/app-builder/value-schema.js +37 -37
  26. package/src/catalog.js +147 -147
  27. package/src/coding/catalog.js +56 -56
  28. package/src/coding/cloud-catalog.js +64 -44
  29. package/src/coding/detect-stack.mjs +110 -110
  30. package/src/coding/export.js +130 -130
  31. package/src/coding/setup.js +175 -174
  32. package/src/coding/skills/lyra-android/SKILL.md +37 -0
  33. package/src/coding/skills/lyra-angular/SKILL.md +37 -0
  34. package/src/coding/skills/lyra-cucumber/SKILL.md +37 -0
  35. package/src/coding/skills/lyra-dbt/SKILL.md +37 -0
  36. package/src/coding/skills/lyra-django/SKILL.md +37 -0
  37. package/src/coding/skills/lyra-docker/SKILL.md +37 -0
  38. package/src/coding/skills/lyra-dotnet/SKILL.md +37 -0
  39. package/src/coding/skills/lyra-express/SKILL.md +37 -0
  40. package/src/coding/skills/lyra-fastapi/SKILL.md +37 -0
  41. package/src/coding/skills/lyra-flutter/SKILL.md +37 -0
  42. package/src/coding/skills/lyra-github-actions/SKILL.md +37 -0
  43. package/src/coding/skills/lyra-gitlab-ci/SKILL.md +37 -0
  44. package/src/coding/skills/lyra-go/SKILL.md +37 -0
  45. package/src/coding/skills/lyra-ios/SKILL.md +37 -0
  46. package/src/coding/skills/lyra-kubernetes/SKILL.md +37 -0
  47. package/src/coding/skills/lyra-mongodb/SKILL.md +37 -0
  48. package/src/coding/skills/lyra-mysql/SKILL.md +37 -0
  49. package/src/coding/skills/lyra-nextjs/SKILL.md +37 -0
  50. package/src/coding/skills/lyra-node/SKILL.md +37 -0
  51. package/src/coding/skills/lyra-playwright/SKILL.md +37 -0
  52. package/src/coding/skills/lyra-postgresql/SKILL.md +37 -0
  53. package/src/coding/skills/lyra-python/SKILL.md +37 -0
  54. package/src/coding/skills/lyra-react/SKILL.md +37 -0
  55. package/src/coding/skills/lyra-react-native/SKILL.md +37 -0
  56. package/src/coding/skills/lyra-redis/SKILL.md +37 -0
  57. package/src/coding/skills/lyra-rust/SKILL.md +37 -0
  58. package/src/coding/skills/lyra-spark/SKILL.md +37 -0
  59. package/src/coding/skills/lyra-spring-boot/SKILL.md +37 -0
  60. package/src/coding/skills/lyra-svelte/SKILL.md +37 -0
  61. package/src/coding/skills/lyra-terraform/SKILL.md +37 -0
  62. package/src/coding/skills/lyra-typescript/SKILL.md +37 -0
  63. package/src/coding/skills/lyra-vue/SKILL.md +37 -0
  64. package/src/gated/hostedAgents.js +56 -56
  65. package/src/gated/index.d.ts +25 -25
  66. package/src/gated/index.js +5 -5
  67. package/src/index.d.ts +2 -2
  68. package/src/index.js +2 -2
  69. package/src/init.js +965 -965
  70. package/src/memory/cli.js +21 -21
  71. package/src/memory/contract.json +28 -28
  72. package/src/memory/index.d.ts +49 -49
  73. package/src/memory/index.js +259 -259
  74. package/src/memory/lifecycle.js +29 -29
  75. package/src/memory/local-cli.js +34 -34
  76. package/src/memory/proposals.js +84 -84
  77. package/src/memory/skills-cli.js +26 -26
  78. package/src/memory/sync.js +89 -89
  79. package/src/memory/validation.js +25 -25
  80. package/src/onboardingAgents.js +532 -532
  81. package/src/promptTemplates.js +178 -178
  82. package/src/runtime/contracts.d.ts +47 -47
  83. package/src/runtime/local-cli.js +160 -160
  84. package/src/runtime/mcp-stdio.js +111 -111
  85. package/src/runtime/orchestration.js +59 -59
  86. package/src/runtime/run-agent.js +43 -43
  87. package/src/standalone/index.d.ts +45 -45
  88. package/src/standalone/index.js +13 -13
  89. package/src/standalone/init.js +12 -0
  90. package/src/standalone/orchestration.js +6 -6
  91. package/src/standalone/rag.js +113 -113
  92. package/src/studio/agent-ui.css +43 -43
  93. package/src/studio/agent-ui.js +32 -32
  94. package/src/studio/browser.js +331 -331
  95. package/src/studio/export.js +80 -80
  96. package/src/studio/index.html +37 -37
  97. package/src/studio/memory-actions.js +37 -37
  98. package/src/studio/memory-panel.js +200 -200
  99. package/src/studio/project.js +216 -216
  100. package/src/studio/pull-agent.js +72 -72
  101. package/src/studio/push.js +54 -54
  102. package/src/studio/python-agent.js +47 -47
  103. package/src/studio/python-agent.py +25 -25
  104. package/src/studio/server.js +143 -143
  105. package/src/studio/session.js +83 -83
  106. package/src/studio/studio.css +10 -10
  107. package/src/studio/sync.js +42 -42
  108. package/src/studio/workflow-sync.js +157 -157
@@ -1,34 +1,34 @@
1
- import { readFile } from "node:fs/promises";
2
- import { openMemoryStore } from "./index.js";
3
-
4
- export async function runLocalMemory(args, output = process.stdout) {
5
- const [action, value, flag] = args;
6
- if (action === "cloud") throw new Error("Cloud memory is not available in the standalone CLI.");
7
- if (!action || action === "--help") {
8
- output.write("Usage: agent-lyra memory init | record <json-file> | list | search <query> | inspect <id> | verify <id> <evidence.json> | archive <id> | consolidate <context> | stats | forget <id> --yes\n");
9
- return;
10
- }
11
- const bare = ["init", "list", "stats"].includes(action) && args.length === 1;
12
- const withValue = ["record", "search", "inspect", "archive", "consolidate"].includes(action) && args.length === 2 && value;
13
- if (!bare && !withValue && !(action === "verify" && args.length === 3 && value && flag) && !(action === "forget" && args.length === 3 && flag === "--yes" && value)) {
14
- throw new Error("See agent-lyra memory --help. Forget requires --yes.");
15
- }
16
- const store = await openMemoryStore();
17
- try {
18
- let result;
19
- switch (action) {
20
- case "init": result = { database: store.file, ...store.stats() }; break;
21
- case "record": result = store.record(JSON.parse((await readFile(value, "utf8")).replace(/^\uFEFF/, ""))); break;
22
- case "list": result = store.list(); break;
23
- case "search": result = store.search(value); break;
24
- case "inspect": result = store.get(value); break;
25
- case "verify": result = store.verify(value, JSON.parse((await readFile(flag, "utf8")).replace(/^\uFEFF/, ""))); break;
26
- case "consolidate": result = store.consolidate(value); break;
27
- case "archive": result = store.archive(value); break;
28
- case "stats": result = store.stats(); break;
29
- case "forget": result = store.forget(value) ? { deleted: value } : null; break;
30
- }
31
- if (result === null) throw new Error("Memory record was not found.");
32
- output.write(JSON.stringify(result, null, 2) + "\n");
33
- } finally { store.close(); }
34
- }
1
+ import { readFile } from "node:fs/promises";
2
+ import { openMemoryStore } from "./index.js";
3
+
4
+ export async function runLocalMemory(args, output = process.stdout) {
5
+ const [action, value, flag] = args;
6
+ if (action === "cloud") throw new Error("Cloud memory is not available in the standalone CLI.");
7
+ if (!action || action === "--help") {
8
+ output.write("Usage: agent-lyra memory init | record <json-file> | list | search <query> | inspect <id> | verify <id> <evidence.json> | archive <id> | consolidate <context> | stats | forget <id> --yes\n");
9
+ return;
10
+ }
11
+ const bare = ["init", "list", "stats"].includes(action) && args.length === 1;
12
+ const withValue = ["record", "search", "inspect", "archive", "consolidate"].includes(action) && args.length === 2 && value;
13
+ if (!bare && !withValue && !(action === "verify" && args.length === 3 && value && flag) && !(action === "forget" && args.length === 3 && flag === "--yes" && value)) {
14
+ throw new Error("See agent-lyra memory --help. Forget requires --yes.");
15
+ }
16
+ const store = await openMemoryStore();
17
+ try {
18
+ let result;
19
+ switch (action) {
20
+ case "init": result = { database: store.file, ...store.stats() }; break;
21
+ case "record": result = store.record(JSON.parse((await readFile(value, "utf8")).replace(/^\uFEFF/, ""))); break;
22
+ case "list": result = store.list(); break;
23
+ case "search": result = store.search(value); break;
24
+ case "inspect": result = store.get(value); break;
25
+ case "verify": result = store.verify(value, JSON.parse((await readFile(flag, "utf8")).replace(/^\uFEFF/, ""))); break;
26
+ case "consolidate": result = store.consolidate(value); break;
27
+ case "archive": result = store.archive(value); break;
28
+ case "stats": result = store.stats(); break;
29
+ case "forget": result = store.forget(value) ? { deleted: value } : null; break;
30
+ }
31
+ if (result === null) throw new Error("Memory record was not found.");
32
+ output.write(JSON.stringify(result, null, 2) + "\n");
33
+ } finally { store.close(); }
34
+ }
@@ -1,84 +1,84 @@
1
- import { randomUUID } from "node:crypto";
2
- import { eligibleText, safeContext } from "./validation.js";
3
-
4
- function readSources(db, context) {
5
- const rows = db.prepare("SELECT id,title,learning,revision,verification FROM memories WHERE status='verified' " +
6
- "AND json_extract(verification,'$.context')=? AND json_extract(verification,'$.adapter')='coding' ORDER BY created_at,id LIMIT 500").all(context);
7
- return rows.filter(row => eligibleText(row.title + " " + row.learning)).map(row => ({
8
- id: row.id, title: row.title, learning: row.learning, revision: row.revision,
9
- evidenceId: JSON.parse(row.verification).evidenceId,
10
- }));
11
- }
12
-
13
- export function consolidate(db, context) {
14
- if (!safeContext(context)) throw new Error("Supply a valid compatibility context.");
15
- const groups = new Map();
16
- for (const row of readSources(db, context)) {
17
- const key = row.learning.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
18
- if (!groups.has(key)) groups.set(key, []);
19
- groups.get(key).push(row);
20
- }
21
- return [...groups.values()]
22
- .filter(group => new Set(group.map(row => row.evidenceId)).size >= 2)
23
- .map(group => ({ title: group[0].title, learning: group[0].learning,
24
- sources: group.map(({ id, revision, evidenceId }) => ({ id, revision, evidenceId })) }));
25
- }
26
-
27
- function present(row) {
28
- return row ? { id: row.id, context: row.context, title: row.title, markdown: row.markdown,
29
- sources: JSON.parse(row.sources), status: row.status, createdAt: row.created_at,
30
- decidedAt: row.decided_at, receipt: row.receipt ? JSON.parse(row.receipt) : null } : null;
31
- }
32
-
33
- export function proposalActions(db, transaction) {
34
- const get = id => present(db.prepare("SELECT * FROM skill_proposals WHERE id=?").get(id));
35
- const now = () => new Date().toISOString();
36
- return {
37
- consolidate: context => consolidate(db, context),
38
- propose(context, memoryId) {
39
- return transaction(() => {
40
- const group = consolidate(db, context).find(item => item.sources.some(source => source.id === memoryId));
41
- if (!group) throw new Error("Choose a verified correction corroborated by a different test reference.");
42
- const sources = JSON.stringify(group.sources);
43
- const prior = db.prepare("SELECT * FROM skill_proposals WHERE context=? AND sources=? AND status IN ('pending','approved')").get(context, sources);
44
- if (prior) return present(prior);
45
- if (db.prepare("SELECT count(*) AS count FROM skill_proposals").get().count >= 500) {
46
- throw new Error("Skill proposal store reached its limit.");
47
- }
48
- const id = randomUUID();
49
- const markdown = "# " + group.title.replace(/[\r\n]+/g, " ") + "\n\n## When to use\n\nCompatibility context: `" +
50
- context + "`. Confirm it still applies.\n\n## Suggested practice\n\n" + group.learning + "\n";
51
- db.prepare("INSERT INTO skill_proposals (id,context,title,markdown,sources,created_at) VALUES (?,?,?,?,?,?)")
52
- .run(id, context, group.title, markdown, sources, now());
53
- return get(id);
54
- });
55
- },
56
- proposal: get,
57
- proposals: () => db.prepare("SELECT * FROM skill_proposals ORDER BY created_at DESC,id LIMIT 100").all().map(present),
58
- decideProposal(id, decision, evidence) {
59
- if (!["approved", "rejected", "withdrawn"].includes(decision)) throw new Error("Invalid skill proposal decision.");
60
- return transaction(() => {
61
- const proposal = get(id);
62
- if (!proposal) throw new Error("Skill proposal was not found.");
63
- const expected = decision === "withdrawn" ? "approved" : "pending";
64
- if (proposal.status !== expected) throw new Error("This skill proposal is " + proposal.status + ".");
65
- let receipt = proposal.receipt;
66
- if (decision === "approved") {
67
- const sources = readSources(db, proposal.context);
68
- if (proposal.sources.some(source => !sources.some(row => row.id === source.id && row.revision === source.revision))) {
69
- throw new Error("A source memory changed. Generate a fresh proposal.");
70
- }
71
- if (evidence?.result !== "passed" || evidence.reviewed !== true || evidence.context !== proposal.context ||
72
- typeof evidence.evidenceId !== "string" || !/^test:[A-Za-z0-9][A-Za-z0-9_.:-]{0,110}$/.test(evidence.evidenceId) ||
73
- proposal.sources.some(source => source.evidenceId === evidence.evidenceId)) {
74
- throw new Error("Approval requires a separate passing regression test and explicit review for this context.");
75
- }
76
- receipt = { evidenceId: evidence.evidenceId, context: evidence.context, result: "passed", reviewed: true };
77
- }
78
- db.prepare("UPDATE skill_proposals SET status=?, decided_at=?, receipt=? WHERE id=?")
79
- .run(decision, now(), receipt ? JSON.stringify(receipt) : null, id);
80
- return get(id);
81
- });
82
- },
83
- };
84
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import { eligibleText, safeContext } from "./validation.js";
3
+
4
+ function readSources(db, context) {
5
+ const rows = db.prepare("SELECT id,title,learning,revision,verification FROM memories WHERE status='verified' " +
6
+ "AND json_extract(verification,'$.context')=? AND json_extract(verification,'$.adapter')='coding' ORDER BY created_at,id LIMIT 500").all(context);
7
+ return rows.filter(row => eligibleText(row.title + " " + row.learning)).map(row => ({
8
+ id: row.id, title: row.title, learning: row.learning, revision: row.revision,
9
+ evidenceId: JSON.parse(row.verification).evidenceId,
10
+ }));
11
+ }
12
+
13
+ export function consolidate(db, context) {
14
+ if (!safeContext(context)) throw new Error("Supply a valid compatibility context.");
15
+ const groups = new Map();
16
+ for (const row of readSources(db, context)) {
17
+ const key = row.learning.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
18
+ if (!groups.has(key)) groups.set(key, []);
19
+ groups.get(key).push(row);
20
+ }
21
+ return [...groups.values()]
22
+ .filter(group => new Set(group.map(row => row.evidenceId)).size >= 2)
23
+ .map(group => ({ title: group[0].title, learning: group[0].learning,
24
+ sources: group.map(({ id, revision, evidenceId }) => ({ id, revision, evidenceId })) }));
25
+ }
26
+
27
+ function present(row) {
28
+ return row ? { id: row.id, context: row.context, title: row.title, markdown: row.markdown,
29
+ sources: JSON.parse(row.sources), status: row.status, createdAt: row.created_at,
30
+ decidedAt: row.decided_at, receipt: row.receipt ? JSON.parse(row.receipt) : null } : null;
31
+ }
32
+
33
+ export function proposalActions(db, transaction) {
34
+ const get = id => present(db.prepare("SELECT * FROM skill_proposals WHERE id=?").get(id));
35
+ const now = () => new Date().toISOString();
36
+ return {
37
+ consolidate: context => consolidate(db, context),
38
+ propose(context, memoryId) {
39
+ return transaction(() => {
40
+ const group = consolidate(db, context).find(item => item.sources.some(source => source.id === memoryId));
41
+ if (!group) throw new Error("Choose a verified correction corroborated by a different test reference.");
42
+ const sources = JSON.stringify(group.sources);
43
+ const prior = db.prepare("SELECT * FROM skill_proposals WHERE context=? AND sources=? AND status IN ('pending','approved')").get(context, sources);
44
+ if (prior) return present(prior);
45
+ if (db.prepare("SELECT count(*) AS count FROM skill_proposals").get().count >= 500) {
46
+ throw new Error("Skill proposal store reached its limit.");
47
+ }
48
+ const id = randomUUID();
49
+ const markdown = "# " + group.title.replace(/[\r\n]+/g, " ") + "\n\n## When to use\n\nCompatibility context: `" +
50
+ context + "`. Confirm it still applies.\n\n## Suggested practice\n\n" + group.learning + "\n";
51
+ db.prepare("INSERT INTO skill_proposals (id,context,title,markdown,sources,created_at) VALUES (?,?,?,?,?,?)")
52
+ .run(id, context, group.title, markdown, sources, now());
53
+ return get(id);
54
+ });
55
+ },
56
+ proposal: get,
57
+ proposals: () => db.prepare("SELECT * FROM skill_proposals ORDER BY created_at DESC,id LIMIT 100").all().map(present),
58
+ decideProposal(id, decision, evidence) {
59
+ if (!["approved", "rejected", "withdrawn"].includes(decision)) throw new Error("Invalid skill proposal decision.");
60
+ return transaction(() => {
61
+ const proposal = get(id);
62
+ if (!proposal) throw new Error("Skill proposal was not found.");
63
+ const expected = decision === "withdrawn" ? "approved" : "pending";
64
+ if (proposal.status !== expected) throw new Error("This skill proposal is " + proposal.status + ".");
65
+ let receipt = proposal.receipt;
66
+ if (decision === "approved") {
67
+ const sources = readSources(db, proposal.context);
68
+ if (proposal.sources.some(source => !sources.some(row => row.id === source.id && row.revision === source.revision))) {
69
+ throw new Error("A source memory changed. Generate a fresh proposal.");
70
+ }
71
+ if (evidence?.result !== "passed" || evidence.reviewed !== true || evidence.context !== proposal.context ||
72
+ typeof evidence.evidenceId !== "string" || !/^test:[A-Za-z0-9][A-Za-z0-9_.:-]{0,110}$/.test(evidence.evidenceId) ||
73
+ proposal.sources.some(source => source.evidenceId === evidence.evidenceId)) {
74
+ throw new Error("Approval requires a separate passing regression test and explicit review for this context.");
75
+ }
76
+ receipt = { evidenceId: evidence.evidenceId, context: evidence.context, result: "passed", reviewed: true };
77
+ }
78
+ db.prepare("UPDATE skill_proposals SET status=?, decided_at=?, receipt=? WHERE id=?")
79
+ .run(decision, now(), receipt ? JSON.stringify(receipt) : null, id);
80
+ return get(id);
81
+ });
82
+ },
83
+ };
84
+ }
@@ -1,26 +1,26 @@
1
- import { readFile } from "node:fs/promises";
2
- import { openMemoryStore } from "./index.js";
3
-
4
- export async function runSkillProposals(args, output = process.stdout) {
5
- const [action, id, value] = args;
6
- if (!action || action === "--help") {
7
- output.write("Usage: agent-lyra skills evolve <context> <memory-id> | proposals | proposal <id> | approve <id> <regression.json> | reject <id> | withdraw <id>\n");
8
- return;
9
- }
10
- const expected = { evolve: 3, proposals: 1, proposal: 2, approve: 3, reject: 2, withdraw: 2 };
11
- if (!Object.hasOwn(expected, action) || args.length !== expected[action]) throw new Error("See agent-lyra skills --help.");
12
- const store = await openMemoryStore();
13
- try {
14
- let result;
15
- switch (action) {
16
- case "evolve": result = store.propose(id, value); break;
17
- case "proposals": result = store.proposals(); break;
18
- case "proposal": result = store.proposal(id); break;
19
- case "approve": result = store.decideProposal(id, "approved", JSON.parse((await readFile(value, "utf8")).replace(/^\uFEFF/, ""))); break;
20
- case "reject": result = store.decideProposal(id, "rejected"); break;
21
- case "withdraw": result = store.decideProposal(id, "withdrawn"); break;
22
- }
23
- if (result === null) throw new Error("Skill proposal was not found.");
24
- output.write(JSON.stringify(result, null, 2) + "\n");
25
- } finally { store.close(); }
26
- }
1
+ import { readFile } from "node:fs/promises";
2
+ import { openMemoryStore } from "./index.js";
3
+
4
+ export async function runSkillProposals(args, output = process.stdout) {
5
+ const [action, id, value] = args;
6
+ if (!action || action === "--help") {
7
+ output.write("Usage: agent-lyra skills evolve <context> <memory-id> | proposals | proposal <id> | approve <id> <regression.json> | reject <id> | withdraw <id>\n");
8
+ return;
9
+ }
10
+ const expected = { evolve: 3, proposals: 1, proposal: 2, approve: 3, reject: 2, withdraw: 2 };
11
+ if (!Object.hasOwn(expected, action) || args.length !== expected[action]) throw new Error("See agent-lyra skills --help.");
12
+ const store = await openMemoryStore();
13
+ try {
14
+ let result;
15
+ switch (action) {
16
+ case "evolve": result = store.propose(id, value); break;
17
+ case "proposals": result = store.proposals(); break;
18
+ case "proposal": result = store.proposal(id); break;
19
+ case "approve": result = store.decideProposal(id, "approved", JSON.parse((await readFile(value, "utf8")).replace(/^\uFEFF/, ""))); break;
20
+ case "reject": result = store.decideProposal(id, "rejected"); break;
21
+ case "withdraw": result = store.decideProposal(id, "withdrawn"); break;
22
+ }
23
+ if (result === null) throw new Error("Skill proposal was not found.");
24
+ output.write(JSON.stringify(result, null, 2) + "\n");
25
+ } finally { store.close(); }
26
+ }
@@ -1,89 +1,89 @@
1
- import { createHash } from "node:crypto";
2
- import { readMode, readSdkKey, requireCloudMode } from "../studio/session.js";
3
- import { openMemoryStore } from "./index.js";
4
- import { eligibleText } from "./validation.js";
5
-
6
- const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
7
- const accountHash = /^[a-f0-9]{64}$/;
8
- const baseUrl = "https://api.agentlyra.in/api/sdk/v1/memory";
9
-
10
- export async function syncMemory(root, action, id, {
11
- key = process.env.LYRA_MEMORY_KEY, fetchRequest = fetch, confirmed = false, expectedPreview, choice, expectedConflict,
12
- } = {}) {
13
- if (!["preview", "list", "push", "pull", "compare", "resolve"].includes(action)) throw new Error("Invalid Cloud memory action.");
14
- if (action !== "list" && (typeof id !== "string" || !uuid.test(id))) throw new Error("Use a valid memory ID.");
15
- if (action === "push" && !confirmed) throw new Error("Review memory cloud preview first, then pass --yes to push.");
16
- if (action !== "preview") {
17
- requireCloudMode(await readMode(root));
18
- key ??= await readSdkKey(root);
19
- if (!/^lyra_sdk_[a-f0-9]{64}$/.test(key ?? "")) {
20
- throw new Error("Run connect-cloud with an AgentLyra API key that has Memory sync permission.");
21
- }
22
- }
23
- const send = async (url, method = "GET", data) => {
24
- const response = await fetchRequest(url, {
25
- method, headers: { Authorization: "Bearer " + key, "Content-Type": "application/json" },
26
- body: data ? JSON.stringify(data) : undefined, redirect: "error", signal: AbortSignal.timeout(15_000),
27
- });
28
- const result = await response.json();
29
- if (response.status === 401) throw new Error("Cloud rejected this key. Check its Memory sync permission or run connect-cloud --replace-key.");
30
- if (!response.ok) throw new Error(result.error || "Cloud memory request failed.");
31
- return result;
32
- };
33
- if (action === "list") return send(baseUrl + (id ? "?after=" + encodeURIComponent(id) : ""));
34
-
35
- const store = await openMemoryStore(root);
36
- try {
37
- const local = store.syncBase(id);
38
- const url = baseUrl + "/" + id;
39
- if (["pull", "compare", "resolve"].includes(action)) {
40
- const remote = await send(url);
41
- check(remote, id, local.link);
42
- if (action === "pull") return store.applyCloudMemory(remote, local);
43
- const changed = local.link ? local.revision !== local.link.local_revision : local.revision !== 0;
44
- if (!changed || local.link?.cloud_revision === remote.revision) {
45
- if (action === "compare") return null;
46
- throw new Error("There is no longer a conflict. Pull again to see the current copy.");
47
- }
48
- const snapshot = { local: local.item, cloud: remote.memory, localDeleted: local.deleted, cloudDeleted: remote.deleted };
49
- const fingerprint = createHash("sha256").update(JSON.stringify([local, remote])).digest("hex");
50
- if (action === "compare") return { ...snapshot, fingerprint };
51
- if (!["local", "cloud"].includes(choice) || expectedConflict !== fingerprint) {
52
- throw new Error("The copies changed since comparison. Compare them again.");
53
- }
54
- return store.applyCloudMemory(remote, local, choice);
55
- }
56
-
57
- let outbound;
58
- if (local.deleted && local.link) {
59
- outbound = { operation: "delete", id, baseRevision: local.link.cloud_revision, account: local.link.cloud_account };
60
- } else {
61
- if (local.item?.status !== "verified") throw new Error("Only explicitly verified memories can be uploaded.");
62
- const { type, title, learning, evidence } = local.item;
63
- if (!eligibleText([title, learning, ...evidence].join(" "))) throw new Error("Remove sensitive or unsafe content before uploading.");
64
- outbound = { operation: "save", id, baseRevision: local.link?.cloud_revision ?? 0,
65
- ...(local.link ? { account: local.link.cloud_account } : {}), memory: { type, title, learning, evidence } };
66
- }
67
- const fingerprint = createHash("sha256").update(JSON.stringify(outbound)).digest("hex");
68
- if (expectedPreview && fingerprint !== expectedPreview) throw new Error("The memory changed since preview. Preview it again.");
69
- if (action === "preview") {
70
- const { account: _account, ...preview } = outbound;
71
- return { ...preview, fingerprint, destination: "Private AgentLyra Cloud memory" };
72
- }
73
- const { id: _id, operation, ...data } = outbound;
74
- const remote = await send(url, operation === "delete" ? "DELETE" : "PUT", data);
75
- check(remote, id, local.link);
76
- store.rememberCloudRevision(remote, local.revision);
77
- return { id, revision: remote.revision, deleted: remote.deleted };
78
- } finally { store.close(); }
79
- }
80
-
81
- function check(remote, id, link) {
82
- if (remote?.id !== id || !Number.isSafeInteger(remote.revision) || remote.revision < 1 ||
83
- typeof remote.deleted !== "boolean" || !accountHash.test(remote.account ?? "")) {
84
- throw new Error("Invalid Cloud memory response.");
85
- }
86
- if (link && (remote.revision < link.cloud_revision || remote.account !== link.cloud_account)) {
87
- throw new Error("This memory is linked to a different Cloud account or newer revision.");
88
- }
89
- }
1
+ import { createHash } from "node:crypto";
2
+ import { readMode, readSdkKey, requireCloudMode } from "../studio/session.js";
3
+ import { openMemoryStore } from "./index.js";
4
+ import { eligibleText } from "./validation.js";
5
+
6
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
7
+ const accountHash = /^[a-f0-9]{64}$/;
8
+ const baseUrl = "https://api.agentlyra.in/api/sdk/v1/memory";
9
+
10
+ export async function syncMemory(root, action, id, {
11
+ key = process.env.LYRA_MEMORY_KEY, fetchRequest = fetch, confirmed = false, expectedPreview, choice, expectedConflict,
12
+ } = {}) {
13
+ if (!["preview", "list", "push", "pull", "compare", "resolve"].includes(action)) throw new Error("Invalid Cloud memory action.");
14
+ if (action !== "list" && (typeof id !== "string" || !uuid.test(id))) throw new Error("Use a valid memory ID.");
15
+ if (action === "push" && !confirmed) throw new Error("Review memory cloud preview first, then pass --yes to push.");
16
+ if (action !== "preview") {
17
+ requireCloudMode(await readMode(root));
18
+ key ??= await readSdkKey(root);
19
+ if (!/^lyra_sdk_[a-f0-9]{64}$/.test(key ?? "")) {
20
+ throw new Error("Run connect-cloud with an AgentLyra API key that has Memory sync permission.");
21
+ }
22
+ }
23
+ const send = async (url, method = "GET", data) => {
24
+ const response = await fetchRequest(url, {
25
+ method, headers: { Authorization: "Bearer " + key, "Content-Type": "application/json" },
26
+ body: data ? JSON.stringify(data) : undefined, redirect: "error", signal: AbortSignal.timeout(15_000),
27
+ });
28
+ const result = await response.json();
29
+ if (response.status === 401) throw new Error("Cloud rejected this key. Check its Memory sync permission or run connect-cloud --replace-key.");
30
+ if (!response.ok) throw new Error(result.error || "Cloud memory request failed.");
31
+ return result;
32
+ };
33
+ if (action === "list") return send(baseUrl + (id ? "?after=" + encodeURIComponent(id) : ""));
34
+
35
+ const store = await openMemoryStore(root);
36
+ try {
37
+ const local = store.syncBase(id);
38
+ const url = baseUrl + "/" + id;
39
+ if (["pull", "compare", "resolve"].includes(action)) {
40
+ const remote = await send(url);
41
+ check(remote, id, local.link);
42
+ if (action === "pull") return store.applyCloudMemory(remote, local);
43
+ const changed = local.link ? local.revision !== local.link.local_revision : local.revision !== 0;
44
+ if (!changed || local.link?.cloud_revision === remote.revision) {
45
+ if (action === "compare") return null;
46
+ throw new Error("There is no longer a conflict. Pull again to see the current copy.");
47
+ }
48
+ const snapshot = { local: local.item, cloud: remote.memory, localDeleted: local.deleted, cloudDeleted: remote.deleted };
49
+ const fingerprint = createHash("sha256").update(JSON.stringify([local, remote])).digest("hex");
50
+ if (action === "compare") return { ...snapshot, fingerprint };
51
+ if (!["local", "cloud"].includes(choice) || expectedConflict !== fingerprint) {
52
+ throw new Error("The copies changed since comparison. Compare them again.");
53
+ }
54
+ return store.applyCloudMemory(remote, local, choice);
55
+ }
56
+
57
+ let outbound;
58
+ if (local.deleted && local.link) {
59
+ outbound = { operation: "delete", id, baseRevision: local.link.cloud_revision, account: local.link.cloud_account };
60
+ } else {
61
+ if (local.item?.status !== "verified") throw new Error("Only explicitly verified memories can be uploaded.");
62
+ const { type, title, learning, evidence } = local.item;
63
+ if (!eligibleText([title, learning, ...evidence].join(" "))) throw new Error("Remove sensitive or unsafe content before uploading.");
64
+ outbound = { operation: "save", id, baseRevision: local.link?.cloud_revision ?? 0,
65
+ ...(local.link ? { account: local.link.cloud_account } : {}), memory: { type, title, learning, evidence } };
66
+ }
67
+ const fingerprint = createHash("sha256").update(JSON.stringify(outbound)).digest("hex");
68
+ if (expectedPreview && fingerprint !== expectedPreview) throw new Error("The memory changed since preview. Preview it again.");
69
+ if (action === "preview") {
70
+ const { account: _account, ...preview } = outbound;
71
+ return { ...preview, fingerprint, destination: "Private AgentLyra Cloud memory" };
72
+ }
73
+ const { id: _id, operation, ...data } = outbound;
74
+ const remote = await send(url, operation === "delete" ? "DELETE" : "PUT", data);
75
+ check(remote, id, local.link);
76
+ store.rememberCloudRevision(remote, local.revision);
77
+ return { id, revision: remote.revision, deleted: remote.deleted };
78
+ } finally { store.close(); }
79
+ }
80
+
81
+ function check(remote, id, link) {
82
+ if (remote?.id !== id || !Number.isSafeInteger(remote.revision) || remote.revision < 1 ||
83
+ typeof remote.deleted !== "boolean" || !accountHash.test(remote.account ?? "")) {
84
+ throw new Error("Invalid Cloud memory response.");
85
+ }
86
+ if (link && (remote.revision < link.cloud_revision || remote.account !== link.cloud_account)) {
87
+ throw new Error("This memory is linked to a different Cloud account or newer revision.");
88
+ }
89
+ }
@@ -1,25 +1,25 @@
1
- import { readFileSync } from "node:fs";
2
- const { adapters } = JSON.parse(readFileSync(new URL("./contract.json", import.meta.url), "utf8"));
3
-
4
- const secret = /\b(?:lyra_sdk_[a-f0-9]{64}|sk-[\w-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|AKIA[A-Z0-9]{16})\b|-----BEGIN [^-]+PRIVATE KEY-----/i;
5
- const unsafe = /(?:ignore|override|disregard)\s+(?:all\s+)?(?:prior|previous|system)\s+instructions|\breveal\s+(?:your\s+)?(?:system prompt|credentials|secrets)\b/i;
6
- const label = /^[A-Za-z0-9][A-Za-z0-9_.:/@-]{0,95}$/;
7
- const evidenceSuffix = /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/;
8
- export const safeContext = value => typeof value === "string" && label.test(value);
9
- export const eligibleText = text => !secret.test(text) && !unsafe.test(text);
10
- export const hasMemoryAdapter = value => typeof value === "string" && Object.hasOwn(adapters, value);
11
-
12
- export function reviewEvidence(item, evidence) {
13
- if (!item || item.status === "archived") throw new Error("Choose an active memory record.");
14
- if (!eligibleText(item.title + " " + item.learning)) throw new Error("Remove credentials or instruction overrides from the memory.");
15
- const adapter = evidence?.adapter;
16
- if (!hasMemoryAdapter(adapter)) throw new Error("Choose a supported memory adapter.");
17
- const rule = adapters[adapter];
18
- const id = evidence.evidenceId;
19
- if (!rule.types.includes(item.type) || evidence.result !== "passed" || evidence.reviewed !== true ||
20
- typeof id !== "string" || !id.startsWith(rule.prefix) || !evidenceSuffix.test(id.slice(rule.prefix.length)) ||
21
- !item.evidence.includes(id) || !safeContext(evidence.context) || !safeContext(evidence[rule.check])) {
22
- throw new Error(rule.error);
23
- }
24
- return { adapter, evidenceId: id, [rule.check]: evidence[rule.check], context: evidence.context };
25
- }
1
+ import { readFileSync } from "node:fs";
2
+ const { adapters } = JSON.parse(readFileSync(new URL("./contract.json", import.meta.url), "utf8"));
3
+
4
+ const secret = /\b(?:lyra_sdk_[a-f0-9]{64}|sk-[\w-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|AKIA[A-Z0-9]{16})\b|-----BEGIN [^-]+PRIVATE KEY-----/i;
5
+ const unsafe = /(?:ignore|override|disregard)\s+(?:all\s+)?(?:prior|previous|system)\s+instructions|\breveal\s+(?:your\s+)?(?:system prompt|credentials|secrets)\b/i;
6
+ const label = /^[A-Za-z0-9][A-Za-z0-9_.:/@-]{0,95}$/;
7
+ const evidenceSuffix = /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/;
8
+ export const safeContext = value => typeof value === "string" && label.test(value);
9
+ export const eligibleText = text => !secret.test(text) && !unsafe.test(text);
10
+ export const hasMemoryAdapter = value => typeof value === "string" && Object.hasOwn(adapters, value);
11
+
12
+ export function reviewEvidence(item, evidence) {
13
+ if (!item || item.status === "archived") throw new Error("Choose an active memory record.");
14
+ if (!eligibleText(item.title + " " + item.learning)) throw new Error("Remove credentials or instruction overrides from the memory.");
15
+ const adapter = evidence?.adapter;
16
+ if (!hasMemoryAdapter(adapter)) throw new Error("Choose a supported memory adapter.");
17
+ const rule = adapters[adapter];
18
+ const id = evidence.evidenceId;
19
+ if (!rule.types.includes(item.type) || evidence.result !== "passed" || evidence.reviewed !== true ||
20
+ typeof id !== "string" || !id.startsWith(rule.prefix) || !evidenceSuffix.test(id.slice(rule.prefix.length)) ||
21
+ !item.evidence.includes(id) || !safeContext(evidence.context) || !safeContext(evidence[rule.check])) {
22
+ throw new Error(rule.error);
23
+ }
24
+ return { adapter, evidenceId: id, [rule.check]: evidence[rule.check], context: evidence.context };
25
+ }