@joe-broadhead/opencode-mem 0.9.12 → 0.11.2

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 (144) hide show
  1. package/CHANGELOG.md +1934 -2
  2. package/README.md +29 -17
  3. package/SECURITY.md +3 -1
  4. package/docs/agent-instructions.md +17 -0
  5. package/docs/agent-protocol.md +8 -8
  6. package/docs/permissions.md +22 -4
  7. package/package.json +7923 -217
  8. package/shared/page-paths.js +44 -0
  9. package/skills/mem.pages/SKILL.md +8 -1
  10. package/skills/mem.usage/SKILL.md +15 -15
  11. package/src/action-grant-keys.js +159 -0
  12. package/src/action-grant.js +439 -0
  13. package/src/actions.js +1690 -0
  14. package/src/backend/records.js +25 -2
  15. package/src/backend/v3.js +76 -22
  16. package/src/call-shapes.js +17 -16
  17. package/src/collector-lock.js +533 -62
  18. package/src/collector-service.js +153 -26
  19. package/src/collector.js +627 -33
  20. package/src/config.js +79 -6
  21. package/src/connect.js +106 -8
  22. package/src/credentials.js +123 -25
  23. package/src/events.js +174 -3
  24. package/src/forget-turn.js +141 -0
  25. package/src/host-refusal.js +78 -0
  26. package/src/index.js +209 -22
  27. package/src/jobs/host.js +557 -0
  28. package/src/ops/codes.js +110 -0
  29. package/src/ops/copy-lineage.js +42 -0
  30. package/src/ops/index.js +28 -0
  31. package/src/ops/space-ops.js +1936 -0
  32. package/src/outlinks.js +103 -0
  33. package/src/p2-reservation.js +151 -0
  34. package/src/permissions.js +30 -0
  35. package/src/plugins/descriptor.js +62 -0
  36. package/src/plugins/discovery.js +318 -0
  37. package/src/plugins/grants.js +178 -0
  38. package/src/plugins/locate.js +319 -0
  39. package/src/plugins/manifest.js +1162 -0
  40. package/src/plugins/source-contract/index.js +34 -0
  41. package/src/plugins/source-contract/policy.js +102 -0
  42. package/src/plugins/source-contract/vendor/PROVENANCE.json +17 -0
  43. package/src/plugins/source-contract/vendor/RELEASE-SHA256SUMS +3 -0
  44. package/src/plugins/source-contract/vendor/RELEASE.json +17 -0
  45. package/src/plugins/source-contract/vendor/SHA256SUMS +41 -0
  46. package/src/plugins/source-contract/vendor/THIRD-PARTY-NOTICES.md +35 -0
  47. package/src/plugins/source-contract/vendor/broker-client.js +93 -0
  48. package/src/plugins/source-contract/vendor/chunks/chunk-3M5PAKSS.js +84 -0
  49. package/src/plugins/source-contract/vendor/chunks/chunk-4ERCA4TK.js +185 -0
  50. package/src/plugins/source-contract/vendor/chunks/chunk-6HDIB2SA.js +183 -0
  51. package/src/plugins/source-contract/vendor/chunks/chunk-ELPJD3ND.js +10 -0
  52. package/src/plugins/source-contract/vendor/chunks/chunk-HLVAKAYG.js +10 -0
  53. package/src/plugins/source-contract/vendor/chunks/chunk-I2RXJJJM.js +81 -0
  54. package/src/plugins/source-contract/vendor/chunks/chunk-KWEWSZ4V.js +505 -0
  55. package/src/plugins/source-contract/vendor/chunks/chunk-KYWBTAF4.js +182 -0
  56. package/src/plugins/source-contract/vendor/chunks/chunk-Q3RQA5J2.js +249 -0
  57. package/src/plugins/source-contract/vendor/chunks/chunk-RRUAIQ4I.js +156 -0
  58. package/src/plugins/source-contract/vendor/chunks/chunk-RYNKNCPP.js +165 -0
  59. package/src/plugins/source-contract/vendor/chunks/chunk-W5SHR7DQ.js +9477 -0
  60. package/src/plugins/source-contract/vendor/chunks/chunk-ZUKF7P6U.js +653 -0
  61. package/src/plugins/source-contract/vendor/cursor.js +26 -0
  62. package/src/plugins/source-contract/vendor/descriptor.js +34 -0
  63. package/src/plugins/source-contract/vendor/events.js +257 -0
  64. package/src/plugins/source-contract/vendor/index.js +10 -0
  65. package/src/plugins/source-contract/vendor/params.js +22 -0
  66. package/src/plugins/source-contract/vendor/permission.js +28 -0
  67. package/src/plugins/source-contract/vendor/pick.js +22 -0
  68. package/src/plugins/source-contract/vendor/read.js +29 -0
  69. package/src/plugins/source-contract/vendor/registry.js +23 -0
  70. package/src/plugins/source-contract/vendor/schema.js +17 -0
  71. package/src/plugins/source-contract/vendor/schemas/output.agenda.json +96 -0
  72. package/src/plugins/source-contract/vendor/schemas/output.countdown.json +28 -0
  73. package/src/plugins/source-contract/vendor/schemas/output.image.json +28 -0
  74. package/src/plugins/source-contract/vendor/schemas/output.inbox.json +84 -0
  75. package/src/plugins/source-contract/vendor/schemas/output.links.json +46 -0
  76. package/src/plugins/source-contract/vendor/schemas/output.list.json +57 -0
  77. package/src/plugins/source-contract/vendor/schemas/output.metric.json +61 -0
  78. package/src/plugins/source-contract/vendor/schemas/output.note.json +14 -0
  79. package/src/plugins/source-contract/vendor/schemas/output.progress.json +50 -0
  80. package/src/plugins/source-contract/vendor/schemas/output.record.json +38 -0
  81. package/src/plugins/source-contract/vendor/schemas/output.table.json +61 -0
  82. package/src/plugins/source-contract/vendor/schemas/output.thread.json +62 -0
  83. package/src/plugins/source-contract/vendor/schemas/sources.json +819 -0
  84. package/src/plugins/source-contract/vendor/schemas.js +19 -0
  85. package/src/plugins/source-contract/vendor/tools-rpc.js +42 -0
  86. package/src/plugins/verify.js +56 -0
  87. package/src/protocol.js +21 -5
  88. package/src/recall.js +104 -5
  89. package/src/records.js +61 -2
  90. package/src/requests.js +216 -0
  91. package/src/runtime.js +89 -7
  92. package/src/setup-time.js +68 -0
  93. package/src/skills.js +230 -8
  94. package/src/source-ids.js +25 -0
  95. package/src/sources/declaration.js +365 -0
  96. package/src/sources/reads.js +772 -0
  97. package/src/sources/rpc.js +151 -0
  98. package/src/sources.js +409 -90
  99. package/src/spaces.js +283 -11
  100. package/src/spool.js +61 -4
  101. package/src/stated.js +10 -5
  102. package/src/storable.js +139 -0
  103. package/src/tools/commitments.js +47 -5
  104. package/src/tools/held-write.js +36 -13
  105. package/src/tools/index.js +27 -0
  106. package/src/tools/ingest.js +27 -2
  107. package/src/tools/memory.js +52 -14
  108. package/src/tools/page.js +95 -9
  109. package/src/tools/recall.js +208 -4
  110. package/src/tools/records-kit.js +2 -1
  111. package/src/tools/share.js +42 -3
  112. package/src/tools/shared.js +44 -4
  113. package/src/tools/space-lifecycle.js +278 -0
  114. package/src/tools/spaces.js +373 -29
  115. package/src/tools/status.js +9 -2
  116. package/src/tools/wiki.js +34 -4
  117. package/src/util.js +110 -6
  118. package/src/vendor/source-contract/README.md +24 -0
  119. package/src/vendor/source-contract/THIRD-PARTY-NOTICES.md +35 -0
  120. package/src/vendor/source-contract/VENDOR.json +81 -0
  121. package/src/vendor/source-contract/chunks/chunk-3M5PAKSS.js +84 -0
  122. package/src/vendor/source-contract/chunks/chunk-6HDIB2SA.js +183 -0
  123. package/src/vendor/source-contract/chunks/chunk-HLVAKAYG.js +10 -0
  124. package/src/vendor/source-contract/chunks/chunk-I2RXJJJM.js +81 -0
  125. package/src/vendor/source-contract/chunks/chunk-KWEWSZ4V.js +505 -0
  126. package/src/vendor/source-contract/chunks/chunk-W5SHR7DQ.js +9477 -0
  127. package/src/vendor/source-contract/chunks/chunk-ZUKF7P6U.js +653 -0
  128. package/src/vendor/source-contract/cursor.js +26 -0
  129. package/src/vendor/source-contract/events.js +257 -0
  130. package/src/vendor/source-contract/registry.js +23 -0
  131. package/src/vendor/source-contract/tools-rpc.js +42 -0
  132. package/src/views/access-reads.js +256 -0
  133. package/src/views/communities.js +77 -0
  134. package/src/views/contracts.js +1183 -36
  135. package/src/views/inbox-bytes.js +103 -0
  136. package/src/views/overdue.js +1 -1
  137. package/src/views/profile.js +31 -0
  138. package/src/views/receipt.js +81 -0
  139. package/src/views/records-reads.js +869 -37
  140. package/src/views/rpc.js +159 -11
  141. package/src/views/shape.js +8 -5
  142. package/views/memory.html +16 -3
  143. package/views/pages.html +2 -2
  144. package/views/remembered.html +130 -0
@@ -0,0 +1,505 @@
1
+ // @we-the-rebel-alliance/source-contract 0.1.0. Built by scripts/build.mjs; do not edit.
2
+ import {
3
+ ACCOUNT_PATTERN,
4
+ evaluate
5
+ } from "./chunk-3M5PAKSS.js";
6
+
7
+ // src/tools-rpc.ts
8
+ import { randomUUID } from "node:crypto";
9
+ var TOOLS_RPC_SUFFIX = ".tools";
10
+ var PLUGIN_ID_PATTERN = /^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)*$/;
11
+ var toolsRpcId = (pluginId) => `${pluginId}${TOOLS_RPC_SUFFIX}`;
12
+ var isToolsRpcId = (id) => typeof id === "string" && id.length <= 214 && id.endsWith(TOOLS_RPC_SUFFIX) && PLUGIN_ID_PATTERN.test(id.slice(0, -TOOLS_RPC_SUFFIX.length));
13
+ var pluginIdOf = (id) => isToolsRpcId(id) ? id.slice(0, -TOOLS_RPC_SUFFIX.length) : void 0;
14
+ function toolsRpcIdProblems(declared, described) {
15
+ if (!isToolsRpcId(declared)) return ["the tools-RPC id must be the plugin id and .tools, such as google-workspace.gws.tools"];
16
+ if (described !== void 0 && described.id !== declared) return [`the plugin's describe reports the tools-RPC id ${String(described.id)}, not ${declared}`];
17
+ return [];
18
+ }
19
+ var CLASSES = ["read", "write", "send", "export", "destructive"];
20
+ var MCP_ONLY = ["SERVER_CONFLICT", "AUTH_REQUIRED", "CONNECTING", "CONNECTION_FAILED", "DISABLED", "NOT_REGISTERED", "TOOL_UNAVAILABLE", "UPSTREAM_ERROR"];
21
+ var UNATTENDED = "A script cannot answer an approval prompt; this needs an allow rule for the session's agent.";
22
+ var MESSAGE_ID = "msg_script";
23
+ var UPSTREAM_LIMIT = 300;
24
+ var LOCATION_HEADER = "x-opencode-directory";
25
+ var LOCATION_HINT = `Send the call to the location you mean: run it in that project with "opencode api ... -H \\"${LOCATION_HEADER}:$PWD\\"", or pass the location[directory] query parameter to the HTTP request.`;
26
+ var READ_VERBS = ["read", "get", "list", "search", "lookup", "view", "describe", "history", "query", "count", "status"];
27
+ var RESOURCE_PATTERN = new RegExp(`${ACCOUNT_PATTERN.source.slice(0, -1)}:[A-Za-z][A-Za-z0-9_-]*(?:\\.[A-Za-z][A-Za-z0-9_-]*)*$`);
28
+ function readOperation(operation) {
29
+ const last = operation.split(".").at(-1) ?? "";
30
+ return READ_VERBS.some((verb) => last === verb || last.startsWith(verb) && /^[A-Z_]/.test(last.slice(verb.length)));
31
+ }
32
+ function defineRpc(definition) {
33
+ const reserved = Object.values(definition.methods).flatMap((method) => Object.keys(method.errors ?? {})).find((name) => name.startsWith("rpc."));
34
+ if (reserved) throw new Error(`RPC error names starting with "rpc." are reserved: ${reserved}`);
35
+ return definition;
36
+ }
37
+ var object = (properties, required) => ({
38
+ type: "object",
39
+ properties,
40
+ required,
41
+ additionalProperties: false
42
+ });
43
+ var STRING = { type: "string" };
44
+ var ANY_OBJECT = { type: "object" };
45
+ var FAILED = object({ code: STRING, next: STRING }, ["code", "next"]);
46
+ var mcpOutput = (output = {}) => object({ output, text: STRING }, ["text"]);
47
+ var DESCRIBED = object(
48
+ {
49
+ name: STRING,
50
+ tool: STRING,
51
+ kind: { type: "string", enum: ["mcp", "plugin"] },
52
+ class: { type: "string", enum: [...CLASSES] },
53
+ action: STRING,
54
+ description: STRING,
55
+ available: { type: "boolean" },
56
+ reason: STRING,
57
+ detail: STRING,
58
+ permission: { type: "string", enum: ["allow", "ask", "deny"] },
59
+ operationScoped: { type: "boolean" },
60
+ input: ANY_OBJECT,
61
+ output: ANY_OBJECT
62
+ },
63
+ ["name", "tool", "kind", "class", "action", "description", "available", "input", "output"]
64
+ );
65
+ var DESCRIPTION = object(
66
+ {
67
+ id: STRING,
68
+ call: STRING,
69
+ location: STRING,
70
+ locationHint: STRING,
71
+ methods: { type: "array", items: DESCRIBED },
72
+ unclassified: { type: "array", items: STRING }
73
+ },
74
+ ["id", "call", "location", "locationHint", "methods"]
75
+ );
76
+ var plainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
77
+ var ENVELOPE_MESSAGES = {
78
+ notObject: `the envelope must be an object, such as {"sessionID":"<session>","input":<the tool's input>}`,
79
+ unknownKey: (key) => `"${key}" is not allowed`,
80
+ sessionID: `"sessionID" must be a non-empty string`,
81
+ account: `"account" must be a non-empty string`,
82
+ inputMissing: `"input" is missing`,
83
+ inputNotObject: `"input" must be an object`,
84
+ describe: `describe takes nothing, or {"sessionID":"<session>"}`
85
+ };
86
+ var standard = (schema, validate) => Object.defineProperty({ ...schema }, "~standard", { value: { version: 1, vendor: "tools-rpc", validate }, enumerable: false });
87
+ var DESCRIBE_INPUT = standard(
88
+ object({ sessionID: { type: "string", minLength: 1 } }, []),
89
+ (value) => {
90
+ if (value === void 0 || value === null) return { value: {} };
91
+ if (!plainObject(value)) return { issues: [{ message: ENVELOPE_MESSAGES.describe }] };
92
+ const issues = [
93
+ ...Object.keys(value).filter((key) => key !== "sessionID").map(ENVELOPE_MESSAGES.unknownKey),
94
+ ...value["sessionID"] === void 0 || typeof value["sessionID"] === "string" && value["sessionID"] !== "" ? [] : [ENVELOPE_MESSAGES.sessionID]
95
+ ];
96
+ return issues.length === 0 ? { value } : { issues: issues.map((message) => ({ message })) };
97
+ }
98
+ );
99
+ function strict(schema, issues) {
100
+ const keys = Object.keys(schema["properties"]);
101
+ return standard(schema, (value) => {
102
+ if (!plainObject(value)) return { issues: [{ message: ENVELOPE_MESSAGES.notObject }] };
103
+ const found = [...Object.keys(value).filter((key) => !keys.includes(key)).map(ENVELOPE_MESSAGES.unknownKey), ...issues(value)];
104
+ return found.length === 0 ? { value } : { issues: found.map((message) => ({ message })) };
105
+ });
106
+ }
107
+ var ScriptError = class extends Error {
108
+ failure;
109
+ constructor(failure) {
110
+ super(`${failure.code}: ${failure.what.replace(/[.\s]+$/, "")}. Next step: ${failure.next}`);
111
+ this.failure = failure;
112
+ }
113
+ };
114
+ var RESOURCE_NEXT = "Pass the input that names the operation and its account, as describe's input schema for the method shows.";
115
+ var record = (value) => typeof value === "object" && value !== null;
116
+ function notFound(error, tags) {
117
+ if (!record(error)) return false;
118
+ const tag = error["_tag"] ?? error["name"];
119
+ return typeof tag === "string" && tags.includes(tag) || error["status"] === 404 || error["statusCode"] === 404;
120
+ }
121
+ var toolError = (error) => record(error) && error["_tag"] === "Tool.Error";
122
+ var requestAction = (cause) => {
123
+ const request = record(cause) ? cause["request"] : void 0;
124
+ return record(request) && typeof request["action"] === "string" && request["action"] !== "" ? request["action"] : void 0;
125
+ };
126
+ var deniedAction = (message) => /^Permission denied: ([\w.:-]*[\w-])\.?\s*$/.exec(message.split(/\r?\n/, 1)[0] ?? "")?.[1];
127
+ var hidden = (rules, action) => evaluate(rules, action) === "deny";
128
+ var SECRETS = [
129
+ [/\b(bearer|basic|token)\s+[\w.~+/=-]{8,}/gi, "$1 [redacted]"],
130
+ [/\b([\w-]*(?:api[_-]?key|access[_-]?key|private[_-]?key|token|secret|password|signature|credential)["']?\s*[:=]\s*)["']?[^\s"'&,;]+["']?/gi, "$1[redacted]"],
131
+ [/\beyJ[\w-]{4,}\.[\w-]{4,}\.[\w-]{4,}/g, "[redacted]"],
132
+ [/\b(?:tvly|sk|pk|rk|ghp|gho|ghu|ghs|ghr|github_pat|glpat|xox[abposr]|lin_api|lin_oauth)[-_][\w-]{8,}/gi, "[redacted]"],
133
+ [/[\w+=-]{40,}/g, "[redacted]"]
134
+ ];
135
+ var withoutQuery = (text) => text.replace(/\bhttps?:\/\/[^\s"'<>()]+/gi, (url) => {
136
+ const cut = url.search(/[?#]/);
137
+ return cut === -1 ? url : `${url.slice(0, cut)}?[redacted]`;
138
+ });
139
+ function upstreamText(text) {
140
+ const line = text.split(/\r?\n/).find((part) => part.trim() !== "")?.trim() ?? "no message";
141
+ const redacted = SECRETS.reduce((value, [pattern, replacement]) => value.replace(pattern, replacement), withoutQuery(line));
142
+ return redacted.length <= UPSTREAM_LIMIT ? redacted : `${redacted.slice(0, UPSTREAM_LIMIT - 1)}\u2026`;
143
+ }
144
+ var jsonSchema = (schema) => record(schema) && !("ast" in schema) && !("~standard" in schema) ? schema : void 0;
145
+ function normalise(result) {
146
+ const parts = typeof result.content === "string" ? [] : result.content ?? [];
147
+ const text = typeof result.content === "string" ? result.content : parts.flatMap((part) => part.type === "text" ? [part.text ?? ""] : []).join("\n");
148
+ return result.output === void 0 ? { text } : { output: result.output, text };
149
+ }
150
+ function connection(status) {
151
+ switch (status) {
152
+ case "connected":
153
+ return void 0;
154
+ case "pending":
155
+ return "CONNECTING";
156
+ case "needs_auth":
157
+ return "AUTH_REQUIRED";
158
+ case "failed":
159
+ return "CONNECTION_FAILED";
160
+ case "disabled":
161
+ return "DISABLED";
162
+ default:
163
+ return "NOT_REGISTERED";
164
+ }
165
+ }
166
+ var STATUS_TEXT = {
167
+ CONNECTING: "is still connecting",
168
+ AUTH_REQUIRED: "needs a sign-in",
169
+ CONNECTION_FAILED: "could not connect",
170
+ DISABLED: "is disabled",
171
+ NOT_REGISTERED: "is not registered"
172
+ };
173
+ async function registerToolsRpc(ctx, options) {
174
+ const { mcp, methods, plugin } = options;
175
+ const NEXT_STEPS = plugin.nextSteps;
176
+ const TOOLS_RPC_ID = toolsRpcId(plugin.id);
177
+ if (!PLUGIN_ID_PATTERN.test(plugin.id)) throw new Error(`registerToolsRpc: the plugin id "${plugin.id}" must be lowercase dotted words, such as google-workspace.gws`);
178
+ const shapeIn = options.shapers?.input ?? plugin.shapeInput ?? ((_method, input) => input);
179
+ const shapeOut = options.shapers?.result ?? plugin.shapeResult ?? ((_method, result) => result);
180
+ const pluginError = (error) => plugin.pluginError?.(error);
181
+ const accounts = typeof mcp?.server === "function";
182
+ const anyMcp = methods.some((method) => method.kind === "mcp");
183
+ if (anyMcp && !mcp) throw new Error("registerToolsRpc: an MCP method needs the mcp option");
184
+ if (accounts && NEXT_STEPS.ACCOUNT_UNKNOWN === void 0) throw new Error("registerToolsRpc: per-account servers need NEXT_STEPS.ACCOUNT_UNKNOWN");
185
+ const missing = anyMcp ? MCP_ONLY.find((code) => code !== "SERVER_CONFLICT" && NEXT_STEPS[code] === void 0) : void 0;
186
+ if (missing) throw new Error(`registerToolsRpc: MCP methods need NEXT_STEPS.${missing}`);
187
+ const names = methods.map((method) => method.name);
188
+ const duplicate = names.find((name, index) => name === "describe" || names.indexOf(name) !== index);
189
+ if (duplicate) throw new Error(`registerToolsRpc: the method name "${duplicate}" is taken`);
190
+ for (const method of methods) {
191
+ if (!CLASSES.includes(method.class)) throw new Error(`registerToolsRpc: ${method.name} has the class "${String(method.class)}"; use one of ${CLASSES.join(", ")}`);
192
+ if (method.kind === "plugin" && (typeof method.run !== "function" || method.action === "")) throw new Error(`registerToolsRpc: the plugin method ${method.name} needs a run function and an action`);
193
+ if (method.kind === "plugin" && method.resource !== void 0 && typeof method.resource !== "function") throw new Error(`registerToolsRpc: the plugin method ${method.name}'s resource must be a function of its input`);
194
+ if (method.kind === "mcp" && "resource" in method) throw new Error(`registerToolsRpc: the MCP method ${method.name} cannot have a resource resolver; only a plugin method can`);
195
+ }
196
+ const fail = (code, what) => {
197
+ const next = NEXT_STEPS[code];
198
+ if (next === void 0) throw new Error(`tools-rpc: NEXT_STEPS.${code} is missing`);
199
+ return new ScriptError({ code, what, next });
200
+ };
201
+ const conflictNext = (server) => NEXT_STEPS.SERVER_CONFLICT ?? `Remove your own "${server}" server from opencode.json so that the plugin manages it, then run "opencode reload".`;
202
+ const live = /* @__PURE__ */ new Set();
203
+ const refused = /* @__PURE__ */ new Map();
204
+ const serverOf = (account) => {
205
+ const server = typeof mcp.server === "function" ? mcp.server(account) : mcp.server;
206
+ if (server !== void 0) return server;
207
+ throw new ScriptError({ code: "ACCOUNT_UNKNOWN", what: `there is no account '${account}'`, next: NEXT_STEPS.ACCOUNT_UNKNOWN });
208
+ };
209
+ const actionOf = (method, envelope2) => method.kind === "plugin" ? method.action : `${serverOf(envelope2.account)}_${method.name}`;
210
+ const resourceOf = (method, envelope2) => {
211
+ if (method.kind !== "plugin" || method.resource === void 0) return "*";
212
+ let resource;
213
+ try {
214
+ resource = method.resource(envelope2.input);
215
+ } catch {
216
+ resource = null;
217
+ }
218
+ const unresolved = (what) => new ScriptError({ code: "RESOURCE_UNRESOLVED", what, next: NEXT_STEPS.RESOURCE_UNRESOLVED ?? RESOURCE_NEXT });
219
+ if (resource === null || resource === void 0) throw unresolved(`${method.name}'s input names no account and operation for ${method.action} to be resolved on`);
220
+ if (typeof resource !== "string" || !RESOURCE_PATTERN.test(resource)) throw unresolved(`${method.name}'s input resolves to a resource that is not <account>:<operation>`);
221
+ const operation = resource.slice(resource.indexOf(":") + 1);
222
+ if (method.class === "read" && !readOperation(operation)) {
223
+ throw new ScriptError({
224
+ code: "PERMISSION_DENIED",
225
+ what: `${method.name} is a read, and ${operation} is not a read operation`,
226
+ next: "Use the plugin's own tools for a change; a read method only reads."
227
+ });
228
+ }
229
+ return resource;
230
+ };
231
+ const session = async (sessionID) => {
232
+ let info;
233
+ try {
234
+ info = await ctx.session.get({ sessionID });
235
+ } catch (error) {
236
+ if (notFound(error, ["Session.NotFoundError", "SessionNotFoundError"])) throw fail("SESSION_UNKNOWN", `there is no session '${sessionID}' in this location`);
237
+ throw error;
238
+ }
239
+ if (!info.agent) throw fail("SESSION_AGENT_REQUIRED", `session '${sessionID}' names no agent`);
240
+ let agent;
241
+ try {
242
+ agent = await ctx.agent.get({ agentID: info.agent });
243
+ } catch (error) {
244
+ const missing2 = notFound(error, ["Agent.NotFoundError", "AgentNotFoundError"]) || error instanceof Error && error.message.startsWith("Agent not found");
245
+ if (missing2) throw fail("SESSION_AGENT_REQUIRED", `session '${sessionID}' names the agent '${info.agent}', which does not exist in this location`);
246
+ throw error;
247
+ }
248
+ const rules = [...agent.data.permissions, ...info.permissions ?? []];
249
+ return { agent: info.agent, rules };
250
+ };
251
+ const notRegistered = (server) => mcp?.notRegistered?.(server);
252
+ const unavailable = async (server, tool, connected) => {
253
+ const status = (await ctx.mcp.list()).data.find((entry) => entry.name === server)?.status.status;
254
+ const code = connection(status) ?? connected;
255
+ if (code === "TOOL_UNAVAILABLE") return fail(code, `OpenCode does not list ${tool} on the connected "${server}" server`);
256
+ if (status === "connected") return fail(code, `the "${server}" server was reconnecting when ${tool} ran`);
257
+ const what = `the "${server}" server ${STATUS_TEXT[code] ?? "is unavailable"}`;
258
+ const own = code === "NOT_REGISTERED" ? notRegistered(server) : void 0;
259
+ return own ? new ScriptError({ code: own.code, what, next: own.next }) : fail(code, what);
260
+ };
261
+ const denyNext = (action, agent) => `Remove or narrow the deny rule for ${action} in the agent "${agent}" or in the session, or add a later allow rule for ${action} to the session, or use a session whose agent allows it.`;
262
+ const denied = (action, error, asked = action) => {
263
+ const reason = upstreamText(record(error) && typeof error["message"] === "string" ? error["message"] : String(error));
264
+ if (asked === action) return fail("PERMISSION_DENIED", `${action} was refused for this session's agent: ${reason}`);
265
+ return new ScriptError({
266
+ code: "PERMISSION_DENIED",
267
+ what: `${action} needs ${asked}, which was refused for this session's agent: ${reason}`,
268
+ next: `Add an allow rule for ${asked} to the session's agent or to the session, or use a session whose agent allows it.`
269
+ });
270
+ };
271
+ const ruleDenied = (action, error, agent, inner = action) => {
272
+ const reason = upstreamText(record(error) && typeof error["message"] === "string" ? error["message"] : String(error));
273
+ const what = inner === action ? `${action} was refused by a deny rule for this session's agent: ${reason}` : `${action} needs ${inner}, which a deny rule refuses for this session's agent: ${reason}`;
274
+ return new ScriptError({ code: "PERMISSION_DENIED", what, next: denyNext(inner, agent) });
275
+ };
276
+ const resolve = (rules, action, agent, resource = "*") => {
277
+ const effect = evaluate(rules, action, resource);
278
+ if (effect === "allow") return;
279
+ const subject = resource === "*" ? action : `${action} on ${resource}`;
280
+ const target = resource === "*" ? action : `${action} on the resource ${resource}`;
281
+ if (effect === "ask")
282
+ throw new ScriptError({
283
+ code: "PERMISSION_DENIED",
284
+ what: `${subject} would ask for this session's agent, and a script cannot answer`,
285
+ next: `Add an allow rule for ${target} to the session's agent or to the session, or use a session whose agent allows it.`
286
+ });
287
+ if (resource === "*" && hidden(rules, action)) throw new ScriptError({ code: "PERMISSION_DENIED", what: `${action} is hidden from this session's agent by a deny rule`, next: denyNext(action, agent) });
288
+ throw new ScriptError({ code: "PERMISSION_DENIED", what: `${subject} is denied for this session's agent`, next: denyNext(target, agent) });
289
+ };
290
+ const mcpTarget = (method, envelope2, action, server) => ({
291
+ action,
292
+ method,
293
+ async run(call) {
294
+ if (!mcp.managed(server)) {
295
+ throw new ScriptError({ code: "SERVER_CONFLICT", what: `the "${server}" server in your config is not the one this plugin manages`, next: conflictNext(server) });
296
+ }
297
+ const tool = (await ctx.tool.list()).find((entry) => entry.id === action);
298
+ if (!tool) throw await unavailable(server, action, "TOOL_UNAVAILABLE");
299
+ const shaped = shapeIn(method.name, envelope2.input, { sessionID: call.sessionID, agent: call.agent, action });
300
+ let result;
301
+ try {
302
+ result = await tool.execute(shaped, call);
303
+ } catch (error) {
304
+ if (error instanceof Error && error.message.startsWith(`MCP server "${server}" `)) throw await unavailable(server, action, "CONNECTING");
305
+ throw error;
306
+ }
307
+ const shapedResult = shapeOut(method.name, normalise(result), { sessionID: call.sessionID, agent: call.agent, action });
308
+ return shapedResult;
309
+ }
310
+ });
311
+ const pluginTarget = (method, envelope2, action) => {
312
+ if (accounts) serverOf(envelope2.account);
313
+ const account = accounts && envelope2.account !== void 0 ? { account: envelope2.account } : {};
314
+ return {
315
+ action,
316
+ method,
317
+ run: async (call) => await method.run(envelope2.input, { ...call, ...account }) ?? null
318
+ };
319
+ };
320
+ const targetOf = (method, envelope2) => {
321
+ const action = actionOf(method, envelope2);
322
+ if (method.kind === "plugin") return pluginTarget(method, envelope2, action);
323
+ return mcpTarget(method, envelope2, action, serverOf(envelope2.account));
324
+ };
325
+ const invoke = async (method, raw, context) => {
326
+ const envelope2 = raw;
327
+ let target;
328
+ let id;
329
+ let agent;
330
+ try {
331
+ if (context.signal.aborted) throw fail("CANCELLED", "the call was cancelled");
332
+ target = targetOf(method, envelope2);
333
+ const resolved = await session(envelope2.sessionID);
334
+ agent = resolved.agent;
335
+ const resource = resourceOf(method, envelope2);
336
+ resolve(resolved.rules, target.action, agent, resource);
337
+ id = `script:${randomUUID()}`;
338
+ const call = {
339
+ sessionID: envelope2.sessionID,
340
+ agent,
341
+ messageID: MESSAGE_ID,
342
+ id,
343
+ signal: context.signal,
344
+ progress: async () => {
345
+ },
346
+ ...resource === "*" ? {} : { resource }
347
+ };
348
+ live.add(call.id);
349
+ try {
350
+ return JSON.parse(JSON.stringify(await target.run(call)));
351
+ } finally {
352
+ live.delete(call.id);
353
+ }
354
+ } catch (error) {
355
+ const failure = refusal(error, target, context.signal, agent, id === void 0 ? void 0 : refused.get(id));
356
+ if (!failure) throw error;
357
+ return context.error("failed", new ScriptError(failure).message, { code: failure.code, next: failure.next });
358
+ } finally {
359
+ if (id !== void 0) refused.delete(id);
360
+ }
361
+ };
362
+ const refusal = (error, target, signal, agent, seen) => {
363
+ if (signal.aborted) return fail("CANCELLED", "the call was cancelled").failure;
364
+ if (error instanceof ScriptError) return error.failure;
365
+ const own = pluginError(error);
366
+ if (own || !target || !toolError(error)) return own;
367
+ if (error.error !== void 0) {
368
+ const request = requestAction(error.error);
369
+ if (seen?.effect === "ask" || request !== void 0 || agent === void 0) return denied(target.action, error, request ?? seen?.action).failure;
370
+ return ruleDenied(target.action, error, agent, seen?.action ?? deniedAction(error.message) ?? target.action).failure;
371
+ }
372
+ if (target.method.kind === "mcp") return fail("UPSTREAM_ERROR", `${target.action} failed: ${upstreamText(error.message)}`).failure;
373
+ return void 0;
374
+ };
375
+ const unclassified = async (tools) => {
376
+ const server = serverOf(void 0);
377
+ const prefix = `${server}_`;
378
+ const known = new Set(methods.filter((method) => method.kind === "mcp").map((method) => method.name));
379
+ const owned = new Set(methods.filter((method) => method.kind === "plugin").flatMap((method) => [method.name, method.action]));
380
+ return tools.filter((tool) => tool.id.startsWith(prefix) && !known.has(tool.id.slice(prefix.length)) && !owned.has(tool.id.slice(prefix.length))).map((tool) => tool.id.slice(prefix.length)).sort();
381
+ };
382
+ const describe = async (raw) => {
383
+ const input = raw ?? {};
384
+ const resolved = input.sessionID === void 0 ? void 0 : await session(input.sessionID);
385
+ const tools = mcp ? await ctx.tool.list() : [];
386
+ const server = anyMcp ? serverOf(void 0) : "";
387
+ const managed = mcp !== void 0 && server !== "" ? mcp.managed(server) : false;
388
+ const status = managed ? (await ctx.mcp.list()).data.find((entry) => entry.name === server)?.status.status : void 0;
389
+ const methodsOut = [];
390
+ for (const method of methods) {
391
+ if (method.kind === "mcp") {
392
+ const id = `${server}_${method.name}`;
393
+ const tool = managed ? tools.find((entry) => entry.id === id) : void 0;
394
+ const code = !managed ? "SERVER_CONFLICT" : tool ? void 0 : connection(status) ?? "TOOL_UNAVAILABLE";
395
+ const reason2 = code === "NOT_REGISTERED" ? notRegistered(server)?.code ?? code : code;
396
+ const detail = code === void 0 ? void 0 : mcp.unavailableDetail?.(method.name, code);
397
+ methodsOut.push({
398
+ name: method.name,
399
+ tool: id,
400
+ kind: "mcp",
401
+ class: method.class,
402
+ action: id,
403
+ description: tool?.description ?? "",
404
+ available: reason2 === void 0,
405
+ ...reason2 ? { reason: reason2 } : {},
406
+ ...detail === void 0 ? {} : { detail },
407
+ ...resolved ? { permission: evaluate(resolved.rules, id) } : {},
408
+ input: jsonSchema(tool?.input) ?? ANY_OBJECT,
409
+ output: mcpOutput(jsonSchema(tool?.output))
410
+ });
411
+ continue;
412
+ }
413
+ const reason = await method.available?.();
414
+ methodsOut.push({
415
+ name: method.name,
416
+ tool: method.name,
417
+ kind: "plugin",
418
+ class: method.class,
419
+ action: method.action,
420
+ description: method.description,
421
+ available: reason === void 0,
422
+ ...reason === void 0 ? {} : { reason },
423
+ // A method with a resolver is resolved per call on its resource; `permission` is the effect on `*`.
424
+ ...resolved ? { permission: evaluate(resolved.rules, method.action) } : {},
425
+ ...method.resource === void 0 ? {} : { operationScoped: true },
426
+ input: method.input,
427
+ output: method.output
428
+ });
429
+ }
430
+ const loose = mcp && mcp.managed(serverOf(void 0)) ? await unclassified(tools) : [];
431
+ return JSON.parse(
432
+ JSON.stringify({
433
+ id: TOOLS_RPC_ID,
434
+ call: `POST /api/rpc/${TOOLS_RPC_ID}/<method> with {"input":{"sessionID":"<session>",${accounts ? `"account":"<account>",` : ""}"input":<the tool's input>}}`,
435
+ location: ctx.location.directory,
436
+ locationHint: LOCATION_HINT,
437
+ methods: methodsOut,
438
+ ...loose.length > 0 ? { unclassified: loose } : {}
439
+ })
440
+ );
441
+ };
442
+ const envelope = (input, objectInput) => strict(
443
+ object({ sessionID: { type: "string", minLength: 1 }, ...accounts ? { account: { type: "string", minLength: 1 } } : {}, input }, ["sessionID", "input"]),
444
+ (value) => [
445
+ ...typeof value["sessionID"] === "string" && value["sessionID"] !== "" ? [] : [ENVELOPE_MESSAGES.sessionID],
446
+ ...value["account"] === void 0 || typeof value["account"] === "string" && value["account"] !== "" ? [] : [ENVELOPE_MESSAGES.account],
447
+ ...!("input" in value) ? [ENVELOPE_MESSAGES.inputMissing] : objectInput && !plainObject(value["input"]) ? [ENVELOPE_MESSAGES.inputNotObject] : []
448
+ ]
449
+ );
450
+ const contract = defineRpc({
451
+ id: TOOLS_RPC_ID,
452
+ methods: {
453
+ describe: { input: DESCRIBE_INPUT, output: DESCRIPTION, errors: { failed: FAILED } },
454
+ ...Object.fromEntries(
455
+ methods.map((method) => [
456
+ method.name,
457
+ method.kind === "mcp" ? { input: envelope(ANY_OBJECT, true), output: mcpOutput(), errors: { failed: FAILED } } : { input: envelope(method.input, false), output: method.output, errors: { failed: FAILED } }
458
+ ])
459
+ )
460
+ },
461
+ events: {}
462
+ });
463
+ const handlers = {
464
+ describe: async (raw, context) => {
465
+ try {
466
+ return await describe(raw);
467
+ } catch (error) {
468
+ if (!(error instanceof ScriptError)) throw error;
469
+ return context.error("failed", error.message, { code: error.failure.code, next: error.failure.next });
470
+ }
471
+ },
472
+ ...Object.fromEntries(methods.map((method) => [method.name, (raw, context) => invoke(method, raw, context)]))
473
+ };
474
+ const registration = await ctx.rpc.register(contract, handlers);
475
+ const hook = await ctx.permission.hook("evaluate", (evaluation) => {
476
+ if (evaluation.source === void 0 || !live.has(evaluation.source.id) || evaluation.effect === "allow") return;
477
+ refused.set(evaluation.source.id, { action: evaluation.action, effect: evaluation.effect === "ask" ? "ask" : "deny" });
478
+ if (evaluation.effect !== "ask") return;
479
+ evaluation.effect = "deny";
480
+ evaluation.message = UNATTENDED;
481
+ });
482
+ return async () => {
483
+ await hook.dispose().catch(() => void 0);
484
+ await registration.dispose().catch(() => void 0);
485
+ };
486
+ }
487
+
488
+ export {
489
+ TOOLS_RPC_SUFFIX,
490
+ PLUGIN_ID_PATTERN,
491
+ toolsRpcId,
492
+ isToolsRpcId,
493
+ pluginIdOf,
494
+ toolsRpcIdProblems,
495
+ CLASSES,
496
+ LOCATION_HEADER,
497
+ LOCATION_HINT,
498
+ READ_VERBS,
499
+ RESOURCE_PATTERN,
500
+ readOperation,
501
+ defineRpc,
502
+ hidden,
503
+ upstreamText,
504
+ registerToolsRpc
505
+ };