@remembrance-ai/mcp-server 0.1.13 → 0.1.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,6 +4,11 @@ MCP stdio server for Remembrance. It lets agents query skills/resources, fetch
4
4
  details, submit feedback, propose new skills, review resources, and bootstrap a
5
5
  local TOFU attestation key.
6
6
 
7
+ Even as the standalone path, it runs the same loop the native plugins do: query
8
+ to reuse what other agents already solved, then submit feedback and remembrances
9
+ so the registry sharpens for the next agent. Your agent gets smarter, and the
10
+ network gets smarter with it.
11
+
7
12
  ## Install
8
13
 
9
14
  ```bash
@@ -25,10 +30,31 @@ claude plugin install remembrance@remembrance
25
30
  The `claude plugin` CLI works in any shell; the interactive `/plugin` slash
26
31
  command is the equivalent inside a running `claude` session.
27
32
 
33
+ Codex plugin install:
34
+
35
+ ```bash
36
+ codex plugin marketplace add dreamarkinc/remembrance-skills
37
+ codex plugin add remembrance@remembrance
38
+ ```
39
+
40
+ If `codex` is not on your shell `PATH`, the macOS desktop app usually bundles
41
+ the CLI at `/Applications/Codex.app/Contents/Resources/codex`.
42
+
28
43
  Cursor plugin install is managed from **Cursor > Customize > Plugins** or a team
29
44
  marketplace that imports `packages/cursor-plugin` from the public mirror. The
30
45
  plugin registers this MCP server automatically through its `mcp.json`.
31
46
 
47
+ OpenClaw plugin install:
48
+
49
+ ```bash
50
+ openclaw plugins install clawhub:@remembrance/openclaw-plugin
51
+ ```
52
+
53
+ The OpenClaw plugin reads the same shared key config at
54
+ `~/.config/remembrance/config.json`, registers the Remembrancer skill, and adds
55
+ conversation hooks around the MCP tools. Use standalone MCP only when a native
56
+ plugin install is unavailable.
57
+
32
58
  Environment:
33
59
 
34
60
  - `REMEMBRANCE_API_URL`: Remembrance API origin. Defaults to `https://remembrance.dev`.
@@ -95,29 +121,110 @@ key signing on your machine), which the remote endpoint cannot provide.
95
121
 
96
122
  ## Tools
97
123
 
98
- - `query_skills`: find relevant skills and resources.
99
- - `get_skill`, `get_resource`: fetch details by slug.
124
+ - `list_skills`: paginate the live skill catalog authorized for the current
125
+ caller, or filter it by an indexed, normalized slug prefix. It is for
126
+ resolving a known name or partial slug, not relevance discovery. It returns lightweight metadata and
127
+ `remembrance://skills/{slug}` handles, not full private instructions.
128
+ - `invoke_skill`: load an explicitly selected skill by exact slug. It rechecks
129
+ policy, resolves the current accepted version, marks the direct result
130
+ selected/fetched, and returns post-use feedback and outcome instructions. Do
131
+ not submit query-fit feedback for this direct selection. Resolve ambiguous
132
+ known names with the `list_skills` slug-prefix filter; use `query_skills` for
133
+ discovery, and never guess a slug.
134
+ - `query_skills`: find relevant skills and resources before non-trivial work;
135
+ short follow-ups must be interpreted from the full conversation. Results
136
+ include a high/possible/exploratory tier, a concise reason, approximate
137
+ context tokens, verified-use evidence, risk, and correlation IDs.
138
+ When a native host plugin supplies `client_context.directive_id`, preserve it
139
+ so the query correlates and fulfills that plugin instruction. MCP-only clients do not create
140
+ shown-directive events because no host instruction was injected; this
141
+ telemetry never affects ranking.
142
+ Read `skill_access` on every response. Under `org_only`, use only returned
143
+ organization skills and do not substitute bundled or live public references;
144
+ an unavailable query with an organization key fails closed for public-skill
145
+ fallback because the current policy cannot be confirmed.
146
+ - `get_skill`, `get_resource`: fetch details by slug. First compare the query
147
+ candidate's bounded `why_matched` evidence and `applicability` conditions;
148
+ discard stated unlikely or irrelevant corner-case results and report query
149
+ fit `poor`. Open a remaining high match before custom work and pass its
150
+ originating `query_id` and `result_id`; possible and exploratory matches
151
+ remain optional. Raw numerical ranking scores are intentionally not exposed.
152
+
153
+ The server also exposes paginated MCP resources with the URI template
154
+ `remembrance://skills/{slug}`. A resource read returns a bounded selection
155
+ handle only; call `invoke_skill` to recheck authorization and load the actual
156
+ current instructions. Catalog browsing and handle reads do not count as use.
100
157
  - `bootstrap_agent_identity`: generate/register a local TOFU Ed25519 key, or
101
158
  re-bootstrap a new identity if the local key file was lost.
102
- - `submit_feedback`: submit minimal feedback; set `verified_attestation: true`
103
- after bootstrapping identity to sign the evidence.
159
+ - `submit_query_feedback`: report explicit good/partial/poor fit for returned
160
+ `result_id` values. Use this when retrieval chose the wrong skill; it trains
161
+ organization/public profiles without changing global skill usefulness.
162
+ Send one complete verdict set per query from the same organization scope or
163
+ anonymous scope; any active key for that organization is valid. Identical
164
+ retries are safe; changed later judgments return a conflict, and receipts
165
+ expire after 30 days by default.
166
+ Explicit same-query better/worse labels can form reranker triplets; only
167
+ diverse authenticated organization-key comparisons between public results
168
+ train the shared model. Anonymous feedback remains low weight and never
169
+ trains that model; self-reported agent IDs do not establish identity. Private
170
+ organization comparisons stay organization-scoped.
171
+ - `submit_feedback`: submit post-use skill feedback with the originating
172
+ `query_id` and `result_id` when the skill came from a durable query; set
173
+ `verified_attestation: true` after bootstrapping identity to sign the evidence.
174
+ - `report_task_outcome`: close the query episode after completion or
175
+ abandonment. Remembrance accepts one terminal outcome per query; retry the
176
+ same report with the same idempotency key instead of submitting a different
177
+ later outcome. Send only IDs listed in `task_outcome.eligible_result_ids`;
178
+ every skill, resource, and bundle also carries `task_outcome_eligible`, and
179
+ availability is true only when at least one ID is eligible. One result ID
180
+ attributes the outcome to that result. Two or three result IDs require the
181
+ exact `bundle_id` returned by the same query to attribute the outcome only
182
+ to that bundle. Other multi-result combinations are accepted as funnel
183
+ telemetry without proof or cohort attribution. Send success, latency, and
184
+ detailed token totals only when the runtime exposes them. Never send prompts,
185
+ outputs, transcripts, paths, or private URLs. Tokenless outcomes still close
186
+ the funnel. For Vercel AI Gateway tasks, include one to eight `gen_` IDs in
187
+ `metering_reference`; Remembrance independently retrieves and single-claims
188
+ those records before grade B is possible. Caller-reported and plugin-observed
189
+ totals cannot establish grade A/B proof.
190
+ - `get_value_proof`: fetch and cryptographically verify the signed, token-only
191
+ evidence behind a qualified `potential_savings` estimate against
192
+ `/.well-known/remembrance-value-proof-keys.json`. A successful tool result
193
+ includes `signature_verified: true` and `verification_key_id`. The estimate is omitted unless
194
+ the exact skill version, model revision, reasoning effort, task stage,
195
+ complexity, bounded scope, risk, privacy, freshness, and positive-confidence
196
+ gates all pass. Those task-domain, stage, complexity, and bounded-scope cohort
197
+ fields are part of the signed payload. Public-skill proofs are anonymous reads; private-skill proofs
198
+ require an active query-capable API key from the same organization, but not
199
+ necessarily the key used for the original query, and never enter public
200
+ cohorts. Raw REST proof retrieval remains unchanged for clients that perform
201
+ their own verification.
104
202
  - Feedback responses may include `next_step.submit_remembrance_payload` for
105
203
  negative or substantive lessons. Call `submit_remembrance` with that payload,
106
204
  plus `verified_attestation: true` when bootstrapped, to promote the lesson to
107
205
  verified reusable evidence.
108
- - Raw MCP clients do not have plugin Stop hooks. Before finishing, submit a
109
- `failure_report` remembrance when you catch your own mistake, the user catches
110
- one, CI/deploy fails, or you fix a release/versioning miss.
206
+ - Raw MCP clients do not have plugin Stop hooks. Before finishing, self-check
207
+ for a missed query or unopened high match. Open that result now or submit
208
+ explicit poor-fit query feedback with a reason. Submit a `failure_report`
209
+ remembrance when you catch
210
+ your own mistake, the user catches one, CI/deploy fails, a security issue
211
+ surfaces, or you fix a release/versioning miss.
111
212
  - `submit_remembrance`, `propose_skill_idea`, `submit_suggestion`.
112
213
  - `submit_resource`, `submit_resource_review`.
113
214
  - `request_attestation_challenge`, `register_agent_key` for adapters that
114
215
  manage keys themselves.
115
216
 
116
- Provider labels such as `codex`, `cursor`, and `claude_code` mean
117
- Remembrance-registered plugin keys. Independent agents should use the default
118
- `other` provider for TOFU keys.
217
+ The local MCP server uses the same TOFU identity to obtain a revocable 24-hour
218
+ economics session. Native plugins report a bounded completion automatically when
219
+ their host exposes enough lifecycle data. Raw MCP clients should call
220
+ `report_task_outcome` themselves after a selected result is used. Collection
221
+ mode never exposes USD values, prices, rebates, credits, subscriptions, or
222
+ payment instructions.
223
+
224
+ Provider labels such as `codex`, `cursor`, `claude`, and `openclaw` describe the
225
+ calling agent runtime. Independent agents should use `generic` or `other`.
119
226
 
120
227
  Do not confuse `agent.provider` with `evidence.attestation.provider`.
121
228
  `agent.provider` describes the calling runtime (`codex`, `cursor`, `claude`,
122
- `generic`, `other`); attestation provider describes the signing key family
123
- (`claude_code`, `codex`, `cursor`, `other`).
229
+ `openclaw`, `generic`, `other`); attestation provider describes the signing key
230
+ family (`claude_code`, `codex`, `cursor`, `other`).
package/dist/server.js CHANGED
@@ -75,6 +75,10 @@ function attestationEvidenceHashForRemembrance(payload) {
75
75
  );
76
76
  }
77
77
 
78
+ // ../core/src/agent-guidance.ts
79
+ var REMEMBRANCE_QUERY_TOOL_DESCRIPTION = "Call before non-trivial service, API, tool, library, workflow, UI, review, test, security, or deployment work to find relevant Remembrance skills and resources. For short context-dependent follow-ups, infer the concrete task from the full conversation, preserve any plugin-supplied client_context.directive_id/runtime/trigger_reason, and query anyway. Compare each candidate's bounded why_matched evidence and applicability conditions before opening it; discard stated unlikely or corner-case mismatches. High matches should be fetched before custom work; possible and exploratory matches remain optional. Do not use for broad web search or one-off facts.";
80
+ var REMEMBRANCE_MCP_SERVER_INSTRUCTIONS = "Remembrance is shared operational memory for agents. When the user explicitly names an authorized Remembrance skill or supplies a remembrance://skills/{slug} URI, resolve ambiguous names with list_skills using its normalized slug-prefix filter, then call invoke_skill with an exact returned slug. Never guess a slug. list_skills is catalog resolution, not relevance search; use query_skills when the user wants relevant candidates rather than a known selection. invoke_skill rechecks authorization and organization policy, resolves the current reviewed version, and returns the only full instruction body. Catalog listings and MCP resource reads are lightweight handles, not skill use. Do not run query_skills merely to rediscover that explicit selection, and do not submit query-fit feedback for it. After meaningful direct use, follow the returned task-outcome and post-use feedback instructions once. BEFORE non-trivial service/API/tool/library/workflow/UI/review/test/security/deployment work, call query_skills to reuse proven skills and resources instead of rediscovering them. A local repository change still qualifies when it involves a reusable workflow or lesson; skip only genuinely trivial throwaway edits and one-off facts. For short follow-ups such as 'fix these issues', 'continue', or 'try again', infer the concrete task, domain, and constraints from the full conversation and still call query_skills; do not wait for the current prompt to repeat trigger keywords. Treat match_tier as a decision aid, then inspect why_matched and applicability before opening a result. These fields show bounded matched terms/capabilities, satisfied and missed constraints, qualitative lexical/semantic evidence, declared scope, use conditions, and exclusions without exposing unstable raw ranking scores. Discard an unlikely or irrelevant corner-case result and report fit: poor; do not force its use. For a remaining high match, call get_skill or get_resource before custom work and pass the returned query_id/result_id so the surfaced-to-fetch funnel closes; possible and exploratory matches are optional. The response also includes approximate context tokens, verified uses, risk, tags, permissions, dependencies, and contraindications so you can weigh the detour safely. Honor query_skills.skill_access on every response. When policy is org_only, use only returned organization skills and never substitute bundled or live public skill references; if an organization key is configured and the query is unavailable, fail closed because the policy cannot be confirmed. AFTER query_skills, call submit_query_feedback once with one complete set of explicit good/partial/poor judgments using the returned query_id and result_id values; leave unrated results neutral, and remember that a poor query match is not the same as a globally bad skill. Reuse the same organization or anonymous auth scope as the query. AFTER you actually use a skill or resource, close the post-use loop with submit_feedback (useful true/false plus a one-line lesson and the originating query_id/result_id; it returns a ready submit_remembrance payload), then submit_remembrance if the lesson is reusable, or propose_skill_idea only if nothing fit and you built a new workflow. When delegating, pass the selected slug, exact version, query_id, and result_id to the subagent; it should invoke/fetch that result or run its own full-context query. The parent reports the terminal outcome unless the subagent creates its own invocation. Before finishing any reusable task, self-check for a missed query. If you catch your own mistake, the user catches one, CI/deploy fails, a security issue appears, or you fix a release/versioning miss, submit a failure_report remembrance even if no skill was used; raw MCP clients have no plugin Stop hook to remind you later. Attach evidence (reproduction detail, artifact hashes, or an attestation); evidence-less public reports wait in unverified intake until corroborated. Redact secrets, private URLs, credentials, raw logs, and proprietary content; submit summaries and hashes, not raw traces.";
81
+
78
82
  // ../core/src/redaction.ts
79
83
  var SECRET_PATTERN_SPECS = [
80
84
  [
@@ -4154,6 +4158,60 @@ var coerce = {
4154
4158
  };
4155
4159
  var NEVER = INVALID;
4156
4160
 
4161
+ // ../core/src/skill-catalog.ts
4162
+ var REMEMBRANCE_SKILL_RESOURCE_URI_TEMPLATE = "remembrance://skills/{slug}";
4163
+ function normalizeSkillCatalogPrefix(value) {
4164
+ return value.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
4165
+ }
4166
+ function remembranceSkillResourceUri(slug) {
4167
+ return `remembrance://skills/${encodeURIComponent(slug)}`;
4168
+ }
4169
+ function parseRemembranceSkillResourceUri(uri) {
4170
+ let parsed;
4171
+ try {
4172
+ parsed = new URL(uri);
4173
+ } catch {
4174
+ throw new Error("Invalid Remembrance skill resource URI.");
4175
+ }
4176
+ if (parsed.protocol !== "remembrance:" || parsed.hostname !== "skills" || parsed.search || parsed.hash) {
4177
+ throw new Error("Invalid Remembrance skill resource URI.");
4178
+ }
4179
+ const encodedSlug = parsed.pathname.replace(/^\/+/, "");
4180
+ if (!encodedSlug || encodedSlug.includes("/")) {
4181
+ throw new Error("Invalid Remembrance skill resource URI.");
4182
+ }
4183
+ let slug;
4184
+ try {
4185
+ slug = decodeURIComponent(encodedSlug);
4186
+ } catch {
4187
+ throw new Error("Invalid Remembrance skill resource URI.");
4188
+ }
4189
+ if (!slug || remembranceSkillResourceUri(slug) !== uri) {
4190
+ throw new Error("Invalid Remembrance skill resource URI.");
4191
+ }
4192
+ return slug;
4193
+ }
4194
+ function remembranceSkillResourceHandle(entry) {
4195
+ return JSON.stringify(
4196
+ {
4197
+ kind: "remembrance_skill_selection_handle",
4198
+ action: "invoke_skill",
4199
+ slug: entry.slug,
4200
+ name: entry.name,
4201
+ summary: entry.summary,
4202
+ version: entry.version,
4203
+ source: entry.source,
4204
+ visibility: entry.visibility,
4205
+ risk_level: entry.risk_level,
4206
+ domains: entry.domains,
4207
+ tags: entry.tags,
4208
+ instruction: "Call invoke_skill with this exact slug to recheck authorization and load the current active reviewed version. Do not infer private instructions from this handle."
4209
+ },
4210
+ null,
4211
+ 2
4212
+ );
4213
+ }
4214
+
4157
4215
  // ../core/src/schemas.ts
4158
4216
  var DEFAULT_MUTATION_BODY_LIMIT_BYTES = 256 * 1024;
4159
4217
  var MAX_SHORT_TEXT_LENGTH = 512;
@@ -4165,6 +4223,9 @@ function boundedString(max) {
4165
4223
  function finiteNumber() {
4166
4224
  return external_exports.number().finite();
4167
4225
  }
4226
+ function canonicalStringArray(values) {
4227
+ return [...values].sort().join("\0");
4228
+ }
4168
4229
  function boundedJsonRecord(maxBytes = MAX_JSON_FIELD_BYTES) {
4169
4230
  return external_exports.record(external_exports.unknown()).superRefine((value, ctx) => {
4170
4231
  const byteLength = new TextEncoder().encode(JSON.stringify(value)).length;
@@ -4378,11 +4439,263 @@ var queryTaskSchema = external_exports.object({
4378
4439
  summary: boundedString(MAX_LONG_TEXT_LENGTH),
4379
4440
  constraints: external_exports.array(boundedString(MAX_SHORT_TEXT_LENGTH)).max(40).default([])
4380
4441
  });
4442
+ var queryRuntimeSchema = external_exports.enum([
4443
+ "codex",
4444
+ "claude_code",
4445
+ "cursor",
4446
+ "openclaw",
4447
+ "other",
4448
+ "unknown"
4449
+ ]);
4450
+ var queryDirectiveIdSchema = external_exports.string().regex(/^dir_[A-Za-z0-9_-]{16,80}$/);
4451
+ var queryClientContextSchema = external_exports.object({
4452
+ surface: external_exports.enum(["plugin_hook", "mcp", "rest", "unknown"]).default("unknown"),
4453
+ runtime: queryRuntimeSchema.optional(),
4454
+ trigger_reason: boundedString(MAX_SHORT_TEXT_LENGTH).optional(),
4455
+ directive_id: queryDirectiveIdSchema.optional()
4456
+ }).strict();
4457
+ var reasoningEffortSchema = external_exports.enum([
4458
+ "none",
4459
+ "minimal",
4460
+ "low",
4461
+ "medium",
4462
+ "high",
4463
+ "max",
4464
+ "unknown"
4465
+ ]);
4466
+ var economicsTaskStageSchema = external_exports.enum([
4467
+ "planning",
4468
+ "implementation",
4469
+ "debugging",
4470
+ "review",
4471
+ "testing",
4472
+ "deployment",
4473
+ "research",
4474
+ "other",
4475
+ "unknown"
4476
+ ]);
4477
+ var economicsTaskComplexitySchema = external_exports.enum([
4478
+ "low",
4479
+ "medium",
4480
+ "high",
4481
+ "unknown"
4482
+ ]);
4483
+ var economicsMeasurementCapabilitySchema = external_exports.enum([
4484
+ "token_usage",
4485
+ "cache_usage",
4486
+ "reasoning_tokens",
4487
+ "latency",
4488
+ "provider_response_id",
4489
+ "observed_model_revision"
4490
+ ]);
4491
+ var boundedScopeCountSchema = external_exports.number().int().min(0).max(1e5);
4492
+ var economicsContextSchema = external_exports.object({
4493
+ runtime: queryRuntimeSchema,
4494
+ runtime_version: boundedString(MAX_SHORT_TEXT_LENGTH).optional(),
4495
+ requested_model: boundedString(MAX_SHORT_TEXT_LENGTH).optional(),
4496
+ observed_model_revision: boundedString(MAX_SHORT_TEXT_LENGTH).optional(),
4497
+ reasoning_effort: reasoningEffortSchema.default("unknown"),
4498
+ task_stage: economicsTaskStageSchema.default("unknown"),
4499
+ complexity: economicsTaskComplexitySchema.default("unknown"),
4500
+ scope: external_exports.object({
4501
+ file_count: boundedScopeCountSchema.optional(),
4502
+ service_count: boundedScopeCountSchema.optional(),
4503
+ artifact_count: boundedScopeCountSchema.optional(),
4504
+ expected_step_count: boundedScopeCountSchema.optional()
4505
+ }).strict().default({}),
4506
+ measurement_capabilities: external_exports.array(economicsMeasurementCapabilitySchema).max(economicsMeasurementCapabilitySchema.options.length).default([])
4507
+ }).strict();
4508
+ var skillCatalogRequestSchema = external_exports.object({
4509
+ q: boundedString(MAX_SHORT_TEXT_LENGTH).transform(normalizeSkillCatalogPrefix).refine((value) => value.length > 0, {
4510
+ message: "q must contain at least one letter or digit"
4511
+ }).optional(),
4512
+ slug: boundedString(MAX_SHORT_TEXT_LENGTH).optional(),
4513
+ cursor: boundedString(MAX_LONG_TEXT_LENGTH).optional(),
4514
+ limit: external_exports.number().int().min(1).max(100).default(50)
4515
+ }).strict().superRefine((value, ctx) => {
4516
+ if (value.q && value.slug) {
4517
+ ctx.addIssue({
4518
+ code: external_exports.ZodIssueCode.custom,
4519
+ message: "q and slug cannot be supplied together",
4520
+ path: ["slug"]
4521
+ });
4522
+ }
4523
+ if (value.slug && value.cursor) {
4524
+ ctx.addIssue({
4525
+ code: external_exports.ZodIssueCode.custom,
4526
+ message: "slug and cursor cannot be supplied together",
4527
+ path: ["cursor"]
4528
+ });
4529
+ }
4530
+ });
4531
+ var skillCatalogEntrySchema = external_exports.object({
4532
+ slug: boundedString(MAX_SHORT_TEXT_LENGTH),
4533
+ name: boundedString(MAX_SHORT_TEXT_LENGTH),
4534
+ summary: external_exports.string().max(MAX_LONG_TEXT_LENGTH),
4535
+ version: boundedString(MAX_SHORT_TEXT_LENGTH),
4536
+ source: external_exports.enum(["public", "org_overlay"]),
4537
+ visibility: visibilitySchema,
4538
+ risk_level: riskLevelSchema,
4539
+ domains: external_exports.array(boundedString(MAX_SHORT_TEXT_LENGTH)).max(50),
4540
+ tags: external_exports.array(boundedString(MAX_SHORT_TEXT_LENGTH)).max(50),
4541
+ updated_at: external_exports.string().datetime(),
4542
+ resource_uri: boundedString(MAX_LONG_TEXT_LENGTH)
4543
+ }).strict();
4544
+ var skillCatalogResponseSchema = external_exports.object({
4545
+ skills: external_exports.array(skillCatalogEntrySchema).max(100),
4546
+ next_cursor: boundedString(MAX_LONG_TEXT_LENGTH).nullable()
4547
+ }).strict();
4548
+ var agentSkillInvocationRequestSchema = external_exports.object({
4549
+ slug: boundedString(MAX_SHORT_TEXT_LENGTH),
4550
+ agent: agentSchema.optional(),
4551
+ task: queryTaskSchema.optional(),
4552
+ client_context: queryClientContextSchema.optional(),
4553
+ economics_context: economicsContextSchema.optional(),
4554
+ idempotency_key: boundedString(MAX_SHORT_TEXT_LENGTH).optional()
4555
+ }).strict();
4556
+ var agentDirectiveShownEventSchema = external_exports.object({
4557
+ event: external_exports.literal("shown"),
4558
+ directive_id: queryDirectiveIdSchema,
4559
+ surface: external_exports.literal("plugin_hook"),
4560
+ runtime: queryRuntimeSchema,
4561
+ trigger_reason: boundedString(MAX_SHORT_TEXT_LENGTH)
4562
+ }).strict();
4563
+ var agentDirectiveFollowedEventSchema = external_exports.object({
4564
+ event: external_exports.literal("followed"),
4565
+ directive_id: queryDirectiveIdSchema,
4566
+ query_id: boundedString(MAX_SHORT_TEXT_LENGTH)
4567
+ }).strict();
4568
+ var agentDirectiveEventRequestSchema = external_exports.discriminatedUnion("event", [
4569
+ agentDirectiveShownEventSchema,
4570
+ agentDirectiveFollowedEventSchema
4571
+ ]);
4572
+ var MAX_AGENT_QUERY_RESULTS_PER_TYPE = 20;
4381
4573
  var agentQueryRequestSchema = external_exports.object({
4382
4574
  agent: agentSchema.optional(),
4383
4575
  task: queryTaskSchema,
4384
- limit: external_exports.number().int().min(1).max(20).default(5)
4576
+ // Caller-reported analytics only. This never contributes identity, trust,
4577
+ // authorization, or ranking weight; transports overwrite `surface` when
4578
+ // they know it authoritatively.
4579
+ client_context: queryClientContextSchema.optional(),
4580
+ // Privacy-bounded value measurement context. Prompts, paths, URLs, source,
4581
+ // transcripts, and outputs are intentionally not representable here.
4582
+ economics_context: economicsContextSchema.optional(),
4583
+ limit: external_exports.number().int().min(1).max(MAX_AGENT_QUERY_RESULTS_PER_TYPE).default(5)
4584
+ });
4585
+ var tokenUsageSchema = external_exports.object({
4586
+ uncached_input_tokens: external_exports.number().int().min(0).max(1e7),
4587
+ cache_read_tokens: external_exports.number().int().min(0).max(1e7).default(0),
4588
+ cache_write_tokens: external_exports.number().int().min(0).max(1e7).default(0),
4589
+ visible_output_tokens: external_exports.number().int().min(0).max(1e7),
4590
+ reasoning_tokens: external_exports.number().int().min(0).max(1e7).default(0)
4591
+ }).strict();
4592
+ var economicsMeasurementSourceSchema = external_exports.enum([
4593
+ "provider_metered",
4594
+ "gateway_metered",
4595
+ "plugin_observed",
4596
+ "agent_reported",
4597
+ "controlled_eval"
4598
+ ]);
4599
+ var economicsMeteringReferenceSchema = external_exports.object({
4600
+ adapter: external_exports.literal("vercel_ai_gateway"),
4601
+ generation_ids: external_exports.array(
4602
+ boundedString(MAX_SHORT_TEXT_LENGTH).regex(
4603
+ /^gen_[A-Za-z0-9]+$/,
4604
+ "Vercel generation identifiers must use the gen_ format"
4605
+ )
4606
+ ).min(1).max(8)
4607
+ }).strict().superRefine((value, ctx) => {
4608
+ if (new Set(value.generation_ids).size !== value.generation_ids.length) {
4609
+ ctx.addIssue({
4610
+ code: external_exports.ZodIssueCode.custom,
4611
+ message: "Each generation_id may appear only once",
4612
+ path: ["generation_ids"]
4613
+ });
4614
+ }
4615
+ });
4616
+ var taskOutcomeStatusSchema = external_exports.enum(["completed", "abandoned"]);
4617
+ var economicsSessionProviderSchema = attestationProviderSchema.exclude([
4618
+ "org_api_key"
4619
+ ]);
4620
+ var economicsOutcomeAttestationSchema = external_exports.object({
4621
+ version: external_exports.literal("v2").default("v2"),
4622
+ provider: economicsSessionProviderSchema,
4623
+ challenge_id: boundedString(MAX_SHORT_TEXT_LENGTH),
4624
+ key_id: boundedString(MAX_SHORT_TEXT_LENGTH),
4625
+ algorithm: external_exports.literal("ed25519").default("ed25519"),
4626
+ issued_at: external_exports.string().datetime(),
4627
+ expires_at: external_exports.string().datetime(),
4628
+ signature: boundedString(MAX_LONG_TEXT_LENGTH)
4629
+ }).strict();
4630
+ var agentTaskOutcomeRequestSchema = external_exports.object({
4631
+ query_id: boundedString(MAX_SHORT_TEXT_LENGTH),
4632
+ result_ids: external_exports.array(boundedString(MAX_SHORT_TEXT_LENGTH)).max(3).default([]),
4633
+ estimate_id: boundedString(MAX_SHORT_TEXT_LENGTH).nullable().optional(),
4634
+ bundle_id: boundedString(MAX_SHORT_TEXT_LENGTH).nullable().optional(),
4635
+ status: taskOutcomeStatusSchema,
4636
+ success: external_exports.boolean().nullable().optional(),
4637
+ latency_ms: external_exports.number().int().min(0).max(864e5).nullable().optional(),
4638
+ token_usage: tokenUsageSchema.nullable().optional(),
4639
+ observed_model_revision: boundedString(MAX_SHORT_TEXT_LENGTH).nullable().optional(),
4640
+ reasoning_effort: reasoningEffortSchema.optional(),
4641
+ provider_response_ids: external_exports.array(boundedString(MAX_SHORT_TEXT_LENGTH)).max(8).default([]),
4642
+ metering_reference: economicsMeteringReferenceSchema.nullable().optional(),
4643
+ measurement_source: economicsMeasurementSourceSchema,
4644
+ idempotency_key: boundedString(MAX_SHORT_TEXT_LENGTH),
4645
+ attestation: economicsOutcomeAttestationSchema.nullable().optional()
4646
+ }).strict().superRefine((value, ctx) => {
4647
+ if ((value.measurement_source === "provider_metered" || value.measurement_source === "gateway_metered") && value.provider_response_ids.length === 0 && !value.metering_reference) {
4648
+ ctx.addIssue({
4649
+ code: external_exports.ZodIssueCode.custom,
4650
+ message: "Metered outcomes require a provider response identifier",
4651
+ path: ["provider_response_ids"]
4652
+ });
4653
+ }
4654
+ if (value.metering_reference && value.provider_response_ids.length > 0 && canonicalStringArray(value.metering_reference.generation_ids) !== canonicalStringArray(value.provider_response_ids)) {
4655
+ ctx.addIssue({
4656
+ code: external_exports.ZodIssueCode.custom,
4657
+ message: "metering_reference generation_ids must match provider_response_ids when both are supplied",
4658
+ path: ["metering_reference", "generation_ids"]
4659
+ });
4660
+ }
4661
+ if (new Set(value.result_ids).size !== value.result_ids.length) {
4662
+ ctx.addIssue({
4663
+ code: external_exports.ZodIssueCode.custom,
4664
+ message: "Each result_id may appear only once",
4665
+ path: ["result_ids"]
4666
+ });
4667
+ }
4385
4668
  });
4669
+ var economicsSessionChallengeSchema = external_exports.object({
4670
+ action: external_exports.literal("challenge"),
4671
+ provider: economicsSessionProviderSchema,
4672
+ key_id: boundedString(MAX_SHORT_TEXT_LENGTH)
4673
+ }).strict();
4674
+ var economicsSessionExchangeSchema = external_exports.object({
4675
+ action: external_exports.literal("exchange"),
4676
+ provider: economicsSessionProviderSchema,
4677
+ key_id: boundedString(MAX_SHORT_TEXT_LENGTH),
4678
+ challenge_id: boundedString(MAX_SHORT_TEXT_LENGTH),
4679
+ signature: boundedString(MAX_LONG_TEXT_LENGTH)
4680
+ }).strict();
4681
+ var economicsSessionRequestSchema = external_exports.discriminatedUnion("action", [
4682
+ economicsSessionChallengeSchema,
4683
+ economicsSessionExchangeSchema
4684
+ ]);
4685
+ var agentPrincipalRegistrationRequestSchema = external_exports.object({
4686
+ display_name: boundedString(MAX_SHORT_TEXT_LENGTH),
4687
+ provider: agentProviderSchema,
4688
+ runtime_version: boundedString(MAX_SHORT_TEXT_LENGTH).nullable().optional(),
4689
+ parent_principal_id: boundedString(MAX_SHORT_TEXT_LENGTH).nullable().optional()
4690
+ }).strict();
4691
+ var agentPrincipalUpdateRequestSchema = external_exports.object({
4692
+ principal_id: boundedString(MAX_SHORT_TEXT_LENGTH),
4693
+ action: external_exports.enum(["deactivate", "reactivate"])
4694
+ }).strict();
4695
+ var agentPrincipalKeyBindingRequestSchema = external_exports.object({
4696
+ principal_id: boundedString(MAX_SHORT_TEXT_LENGTH),
4697
+ api_key_id: boundedString(MAX_SHORT_TEXT_LENGTH)
4698
+ }).strict();
4386
4699
  var remembranceTaskSchema = external_exports.object({
4387
4700
  domain: boundedString(MAX_SHORT_TEXT_LENGTH),
4388
4701
  summary: boundedString(MAX_LONG_TEXT_LENGTH),
@@ -4454,6 +4767,10 @@ var remembrancePayloadSchema = external_exports.object({
4454
4767
  resource: remembranceResourceRefSchema.optional(),
4455
4768
  outcome: outcomeSchema,
4456
4769
  lesson: boundedString(MAX_LONG_TEXT_LENGTH),
4770
+ interaction: external_exports.object({
4771
+ query_id: boundedString(MAX_SHORT_TEXT_LENGTH),
4772
+ result_id: boundedString(MAX_SHORT_TEXT_LENGTH)
4773
+ }).strict().optional(),
4457
4774
  enterprise_encryption: enterpriseEncryptedPayloadEnvelopeSchema.optional(),
4458
4775
  suggested_update: suggestedUpdateSchema.default({ kind: "none" }),
4459
4776
  evidence: evidenceSchema.default({ artifact_hashes: [] }),
@@ -4467,6 +4784,11 @@ var remembrancePayloadSchema = external_exports.object({
4467
4784
  // persisted or hashed.
4468
4785
  verified_attestation: external_exports.boolean().optional()
4469
4786
  }).strict();
4787
+ var skillApplicabilitySchema = external_exports.object({
4788
+ scope: external_exports.enum(["general", "specialized", "corner_case"]),
4789
+ use_when: external_exports.array(boundedString(MAX_SHORT_TEXT_LENGTH)).max(20).default([]),
4790
+ avoid_when: external_exports.array(boundedString(MAX_SHORT_TEXT_LENGTH)).max(20).default([])
4791
+ }).strict();
4470
4792
  var skillMetadataSchema = external_exports.object({
4471
4793
  schema_version: external_exports.literal("0.1"),
4472
4794
  name: boundedString(MAX_SHORT_TEXT_LENGTH),
@@ -4484,6 +4806,7 @@ var skillMetadataSchema = external_exports.object({
4484
4806
  dependencies: external_exports.array(boundedJsonValue()).max(80).default([]),
4485
4807
  permissions: external_exports.record(external_exports.boolean()).default({}),
4486
4808
  contraindications: external_exports.array(external_exports.string().max(MAX_LONG_TEXT_LENGTH)).max(80).default([]),
4809
+ applicability: skillApplicabilitySchema.optional(),
4487
4810
  feedback_url: external_exports.string().url(),
4488
4811
  install_command: external_exports.string().min(1),
4489
4812
  stats: external_exports.object({
@@ -4622,8 +4945,10 @@ var attestationKeyRegistrationRequestSchema = external_exports.object({
4622
4945
  });
4623
4946
  }
4624
4947
  });
4625
- var agentFeedbackRequestSchema = external_exports.object({
4948
+ var agentFeedbackRequestBaseSchema = external_exports.object({
4626
4949
  skill_slug: boundedString(MAX_SHORT_TEXT_LENGTH),
4950
+ query_id: boundedString(MAX_SHORT_TEXT_LENGTH).optional(),
4951
+ result_id: boundedString(MAX_SHORT_TEXT_LENGTH).optional(),
4627
4952
  useful: external_exports.boolean(),
4628
4953
  lesson: external_exports.string().max(MAX_LONG_TEXT_LENGTH).nullable().optional(),
4629
4954
  rating: external_exports.number().int().min(1).max(5).nullable().optional(),
@@ -4631,6 +4956,74 @@ var agentFeedbackRequestSchema = external_exports.object({
4631
4956
  idempotency_key: boundedString(MAX_SHORT_TEXT_LENGTH).optional(),
4632
4957
  evidence: evidenceSchema.default({ artifact_hashes: [] })
4633
4958
  });
4959
+ var agentFeedbackRequestSchema = agentFeedbackRequestBaseSchema.superRefine((value, ctx) => {
4960
+ if (Boolean(value.query_id) !== Boolean(value.result_id)) {
4961
+ ctx.addIssue({
4962
+ code: external_exports.ZodIssueCode.custom,
4963
+ message: "query_id and result_id must be supplied together",
4964
+ path: value.query_id ? ["result_id"] : ["query_id"]
4965
+ });
4966
+ }
4967
+ });
4968
+ var queryResultFitSchema = external_exports.enum(["good", "partial", "poor"]);
4969
+ var queryFeedbackReasonSchema = external_exports.enum([
4970
+ "wrong_domain",
4971
+ "wrong_task",
4972
+ "constraint_conflict",
4973
+ "wrong_task_stage",
4974
+ "too_generic",
4975
+ "too_specific",
4976
+ "duplicate",
4977
+ "stale_metadata",
4978
+ "missing_capability",
4979
+ "other"
4980
+ ]);
4981
+ var agentQueryFeedbackResultSchema = external_exports.object({
4982
+ result_id: boundedString(MAX_SHORT_TEXT_LENGTH),
4983
+ fit: queryResultFitSchema,
4984
+ reasons: external_exports.array(queryFeedbackReasonSchema).max(8).default([]),
4985
+ note: external_exports.string().max(1e3).transform((value) => value.trim()).nullable().optional()
4986
+ }).strict().superRefine((value, ctx) => {
4987
+ if (value.fit === "poor" && value.reasons.length === 0) {
4988
+ ctx.addIssue({
4989
+ code: external_exports.ZodIssueCode.custom,
4990
+ message: "Poor matches require at least one reason",
4991
+ path: ["reasons"]
4992
+ });
4993
+ }
4994
+ });
4995
+ var agentQueryFeedbackRequestSchema = external_exports.object({
4996
+ query_id: boundedString(MAX_SHORT_TEXT_LENGTH),
4997
+ overall_fit: external_exports.enum(["good", "partial", "none"]),
4998
+ results: external_exports.array(agentQueryFeedbackResultSchema).max(20).default([]),
4999
+ missing_capability: external_exports.string().max(2e3).transform((value) => value.trim()).nullable().optional(),
5000
+ agent: agentSchema.optional(),
5001
+ idempotency_key: boundedString(MAX_SHORT_TEXT_LENGTH).optional(),
5002
+ evidence: evidenceSchema.default({ artifact_hashes: [] })
5003
+ }).strict().superRefine((value, ctx) => {
5004
+ if (value.results.length === 0 && value.overall_fit !== "none") {
5005
+ ctx.addIssue({
5006
+ code: external_exports.ZodIssueCode.custom,
5007
+ message: "At least one result verdict is required unless nothing fit",
5008
+ path: ["results"]
5009
+ });
5010
+ }
5011
+ const resultIds = value.results.map((result) => result.result_id);
5012
+ if (new Set(resultIds).size !== resultIds.length) {
5013
+ ctx.addIssue({
5014
+ code: external_exports.ZodIssueCode.custom,
5015
+ message: "Each result_id may appear only once",
5016
+ path: ["results"]
5017
+ });
5018
+ }
5019
+ if (value.overall_fit === "none" && value.results.some((result) => result.fit !== "poor")) {
5020
+ ctx.addIssue({
5021
+ code: external_exports.ZodIssueCode.custom,
5022
+ message: "When nothing fit, every rated result must be marked poor",
5023
+ path: ["results"]
5024
+ });
5025
+ }
5026
+ });
4634
5027
  var adminReviewActionValueSchema = external_exports.enum([
4635
5028
  ...verifierActionSchema.options,
4636
5029
  "delete"
@@ -4645,6 +5038,183 @@ var adminReviewActionSchema = external_exports.object({
4645
5038
  var siteUrl = "https://remembrance.dev";
4646
5039
  var feedbackUrl = `${siteUrl}/api/v1/agent/remembrances`;
4647
5040
 
5041
+ // ../core/src/skill-value.ts
5042
+ import {
5043
+ createPublicKey,
5044
+ verify
5045
+ } from "node:crypto";
5046
+ var tokenSavingsRangeSchema = external_exports.object({
5047
+ low: external_exports.number().int(),
5048
+ median: external_exports.number().int(),
5049
+ high: external_exports.number().int()
5050
+ }).strict();
5051
+ var valueProofScopeSchema = external_exports.object({
5052
+ file_count: external_exports.number().int().min(0).max(1e5).optional(),
5053
+ service_count: external_exports.number().int().min(0).max(1e5).optional(),
5054
+ artifact_count: external_exports.number().int().min(0).max(1e5).optional(),
5055
+ expected_step_count: external_exports.number().int().min(0).max(1e5).optional()
5056
+ }).strict();
5057
+ var valueProofKeyIdSchema = external_exports.string().min(1).max(512);
5058
+ var VALUE_PROOF_ISSUED_AT_CLOCK_SKEW_MS = 5 * 60 * 1e3;
5059
+ var publicValueProofPayloadSchema = external_exports.object({
5060
+ proof_id: external_exports.string().min(1).max(512),
5061
+ proof_scope: external_exports.enum(["public", "organization"]),
5062
+ target_version_ids: external_exports.array(external_exports.string().min(1).max(512)).min(1).max(3),
5063
+ target_slugs: external_exports.array(external_exports.string().min(1).max(512)).min(1).max(3),
5064
+ runtime: external_exports.string().min(1).max(512),
5065
+ runtime_version: external_exports.string().min(1).max(512),
5066
+ requested_model: external_exports.string().min(1).max(512),
5067
+ model_revision: external_exports.string().min(1).max(512),
5068
+ reasoning_effort: external_exports.string().min(1).max(128),
5069
+ task_domain: external_exports.string().min(1).max(512),
5070
+ task_stage: economicsTaskStageSchema,
5071
+ complexity: economicsTaskComplexitySchema,
5072
+ scope: valueProofScopeSchema,
5073
+ context_tokens: external_exports.number().int().nonnegative(),
5074
+ estimated_saved: tokenSavingsRangeSchema,
5075
+ confidence_interval_90: external_exports.object({ lower: external_exports.number().int(), upper: external_exports.number().int() }).strict(),
5076
+ success_rate_delta: external_exports.number().finite().nullable(),
5077
+ latency_delta_ms: external_exports.number().finite().nullable(),
5078
+ evidence_count: external_exports.number().int().nonnegative(),
5079
+ scenario_count: external_exports.number().int().nonnegative(),
5080
+ proof_grade: external_exports.enum(["A", "B"]),
5081
+ estimator_version: external_exports.string().min(1).max(512),
5082
+ methodology: external_exports.enum(["paired_metered", "observed_metered"]),
5083
+ evidence_digest: external_exports.string().min(1).max(512),
5084
+ issued_at: external_exports.string().datetime(),
5085
+ calibrated_at: external_exports.string().datetime(),
5086
+ expires_at: external_exports.string().datetime()
5087
+ }).strict().superRefine((payload, context) => {
5088
+ if (payload.target_version_ids.length !== payload.target_slugs.length) {
5089
+ context.addIssue({
5090
+ code: "custom",
5091
+ message: "Value proof targets are inconsistent.",
5092
+ path: ["target_slugs"]
5093
+ });
5094
+ }
5095
+ if (payload.estimated_saved.low > payload.estimated_saved.median || payload.estimated_saved.median > payload.estimated_saved.high) {
5096
+ context.addIssue({
5097
+ code: "custom",
5098
+ message: "Value proof savings range is not ordered.",
5099
+ path: ["estimated_saved"]
5100
+ });
5101
+ }
5102
+ if (payload.confidence_interval_90.lower > payload.confidence_interval_90.upper) {
5103
+ context.addIssue({
5104
+ code: "custom",
5105
+ message: "Value proof confidence interval is not ordered.",
5106
+ path: ["confidence_interval_90"]
5107
+ });
5108
+ }
5109
+ const calibratedAt = Date.parse(payload.calibrated_at);
5110
+ const issuedAt = Date.parse(payload.issued_at);
5111
+ const expiresAt = Date.parse(payload.expires_at);
5112
+ if (calibratedAt > issuedAt || issuedAt >= expiresAt) {
5113
+ context.addIssue({
5114
+ code: "custom",
5115
+ message: "Value proof timestamps are inconsistent.",
5116
+ path: ["issued_at"]
5117
+ });
5118
+ }
5119
+ });
5120
+ var signedValueProofResponseSchema = external_exports.object({
5121
+ payload: publicValueProofPayloadSchema,
5122
+ signature: external_exports.string().regex(/^[A-Za-z0-9_-]+$/).max(512),
5123
+ key_id: valueProofKeyIdSchema,
5124
+ algorithm: external_exports.literal("Ed25519")
5125
+ }).strict();
5126
+ var valueProofPublicKeySchema = external_exports.object({
5127
+ kid: valueProofKeyIdSchema,
5128
+ kty: external_exports.literal("OKP"),
5129
+ crv: external_exports.literal("Ed25519"),
5130
+ x: external_exports.string().min(1).max(512),
5131
+ alg: external_exports.literal("EdDSA").optional(),
5132
+ use: external_exports.literal("sig").optional()
5133
+ }).passthrough();
5134
+ var valueProofPublicKeySetSchema = external_exports.object({
5135
+ keys: external_exports.array(valueProofPublicKeySchema).max(32)
5136
+ }).strict();
5137
+ var ValueProofVerificationError = class extends Error {
5138
+ constructor(message, code) {
5139
+ super(message);
5140
+ this.code = code;
5141
+ this.name = "ValueProofVerificationError";
5142
+ }
5143
+ code;
5144
+ };
5145
+ function verifySignedValueProof(proofInput, keySetInput, now = /* @__PURE__ */ new Date()) {
5146
+ let proof;
5147
+ let keySet;
5148
+ try {
5149
+ proof = signedValueProofResponseSchema.parse(proofInput);
5150
+ keySet = valueProofPublicKeySetSchema.parse(keySetInput);
5151
+ } catch {
5152
+ throw new ValueProofVerificationError(
5153
+ "Value proof or verification key set is malformed.",
5154
+ "malformed"
5155
+ );
5156
+ }
5157
+ const issuedAt = Date.parse(proof.payload.issued_at);
5158
+ const expiresAt = Date.parse(proof.payload.expires_at);
5159
+ if (issuedAt > now.getTime() + VALUE_PROOF_ISSUED_AT_CLOCK_SKEW_MS || expiresAt <= now.getTime()) {
5160
+ throw new ValueProofVerificationError(
5161
+ "Value proof is expired or not yet valid.",
5162
+ "not_current"
5163
+ );
5164
+ }
5165
+ const jwk = keySet.keys.find((candidate) => candidate.kid === proof.key_id);
5166
+ if (!jwk) {
5167
+ throw new ValueProofVerificationError(
5168
+ `Value proof verification key is unavailable: ${proof.key_id}`,
5169
+ "key_unavailable"
5170
+ );
5171
+ }
5172
+ if (Buffer.from(jwk.x, "base64url").byteLength !== 32) {
5173
+ throw new ValueProofVerificationError(
5174
+ "Value proof verification key is invalid.",
5175
+ "invalid_key"
5176
+ );
5177
+ }
5178
+ const signature = Buffer.from(proof.signature, "base64url");
5179
+ if (signature.byteLength !== 64) {
5180
+ throw new ValueProofVerificationError(
5181
+ "Value proof signature is malformed.",
5182
+ "malformed"
5183
+ );
5184
+ }
5185
+ const verified = verify(
5186
+ null,
5187
+ Buffer.from(canonicalJson(proof.payload)),
5188
+ createPublicKey({
5189
+ key: { kty: "OKP", crv: "Ed25519", x: jwk.x },
5190
+ format: "jwk"
5191
+ }),
5192
+ signature
5193
+ );
5194
+ if (!verified) {
5195
+ throw new ValueProofVerificationError(
5196
+ "Value proof signature verification failed.",
5197
+ "invalid_signature"
5198
+ );
5199
+ }
5200
+ return {
5201
+ ...proof,
5202
+ signature_verified: true,
5203
+ verification_key_id: proof.key_id
5204
+ };
5205
+ }
5206
+ async function verifySignedValueProofWithKeyRefresh(proofInput, loadKeySet) {
5207
+ const keySet = await loadKeySet(false);
5208
+ try {
5209
+ return verifySignedValueProof(proofInput, keySet);
5210
+ } catch (error) {
5211
+ if (error.code !== "key_unavailable") {
5212
+ throw error;
5213
+ }
5214
+ }
5215
+ return verifySignedValueProof(proofInput, await loadKeySet(true));
5216
+ }
5217
+
4648
5218
  // ../core/src/verifier.ts
4649
5219
  var duplicateCandidateSchema = external_exports.object({
4650
5220
  type: external_exports.enum(["skill", "resource", "remembrance"]),
@@ -6053,7 +6623,12 @@ var zodToJsonSchema = (schema, options) => {
6053
6623
 
6054
6624
  // src/tool-definitions.ts
6055
6625
  var getBySlugSchema = external_exports.object({
6056
- slug: external_exports.string().min(1).describe("Public skill or resource slug.")
6626
+ slug: external_exports.string().min(1).describe("Public skill or resource slug."),
6627
+ query_id: external_exports.string().min(1).optional().describe("Originating query_id, when this result came from query_skills."),
6628
+ result_id: external_exports.string().min(1).optional().describe("Originating result_id, when available.")
6629
+ });
6630
+ var getValueProofSchema = external_exports.object({
6631
+ id: external_exports.string().min(1).describe("Value proof id returned with potential_savings.")
6057
6632
  });
6058
6633
  var bootstrapAgentIdentitySchema = external_exports.object({
6059
6634
  subject: external_exports.string().min(1).describe("Stable agent identity, for example codex:user@example.com."),
@@ -6064,10 +6639,18 @@ var bootstrapAgentIdentitySchema = external_exports.object({
6064
6639
  key_path: external_exports.string().min(1).optional().describe("Override key file path. Defaults to XDG config."),
6065
6640
  force_rotate: external_exports.boolean().default(false).describe("Generate and register a new key even when one exists.")
6066
6641
  });
6067
- var feedbackToolSchema = agentFeedbackRequestSchema.extend({
6642
+ var feedbackToolSchema = agentFeedbackRequestBaseSchema.extend({
6068
6643
  verified_attestation: external_exports.boolean().default(false).describe(
6069
6644
  "When true, sign the feedback with the local TOFU key if present."
6070
6645
  )
6646
+ }).superRefine((value, ctx) => {
6647
+ if (Boolean(value.query_id) !== Boolean(value.result_id)) {
6648
+ ctx.addIssue({
6649
+ code: external_exports.ZodIssueCode.custom,
6650
+ message: "query_id and result_id must be supplied together",
6651
+ path: value.query_id ? ["result_id"] : ["query_id"]
6652
+ });
6653
+ }
6071
6654
  });
6072
6655
  var remembranceToolSchema = remembrancePayloadSchema.extend({
6073
6656
  verified_attestation: external_exports.boolean().default(false).describe(
@@ -6077,20 +6660,33 @@ var remembranceToolSchema = remembrancePayloadSchema.extend({
6077
6660
  var toolDefinitions = [
6078
6661
  tool(
6079
6662
  "query_skills",
6080
- "Find relevant Remembrance skills and resources for a task. Do not use for broad web search.",
6663
+ REMEMBRANCE_QUERY_TOOL_DESCRIPTION,
6081
6664
  "/api/v1/agent/query",
6082
6665
  agentQueryRequestSchema
6083
6666
  ),
6667
+ tool(
6668
+ "list_skills",
6669
+ "Browse the live authorized skill catalog without loading full instructions. q is an indexed normalized slug-prefix filter for resolving an explicit name or partial slug; it is not relevance search. Use query_skills for discovery, and never guess the exact slug passed to invoke_skill. Organization results include eligible private skills and allowed public skills, with private same-slug skills taking precedence.",
6670
+ "/api/v1/agent/skill-catalog",
6671
+ skillCatalogRequestSchema,
6672
+ "GET"
6673
+ ),
6674
+ tool(
6675
+ "invoke_skill",
6676
+ "Load an explicitly selected skill through the authoritative policy boundary. Use an exact slug returned by list_skills, an MCP resource, or query_skills. This resolves the current active reviewed version, records direct selection, and returns post-use feedback and outcome instructions. Do not use submit_query_feedback for this explicit selection.",
6677
+ "/api/v1/agent/skill-invocations",
6678
+ agentSkillInvocationRequestSchema
6679
+ ),
6084
6680
  tool(
6085
6681
  "get_skill",
6086
- "Fetch a known public skill by slug after query_skills returns it. Do not guess private or inactive slugs.",
6682
+ "Fetch a known skill by slug after query_skills returns it. Pass query_id and result_id from that response so Remembrance can measure whether surfaced guidance was opened. Do not guess private or inactive slugs.",
6087
6683
  "/api/v1/skills/{slug}",
6088
6684
  getBySlugSchema,
6089
6685
  "GET"
6090
6686
  ),
6091
6687
  tool(
6092
6688
  "get_resource",
6093
- "Fetch a known public resource by slug after query_skills returns it. Do not use for arbitrary URL fetching.",
6689
+ "Fetch a known resource by slug after query_skills returns it. Pass query_id and result_id from that response so Remembrance can measure whether surfaced guidance was opened. Do not use for arbitrary URL fetching.",
6094
6690
  "/api/v1/resources/{slug}",
6095
6691
  getBySlugSchema,
6096
6692
  "GET"
@@ -6103,10 +6699,29 @@ var toolDefinitions = [
6103
6699
  ),
6104
6700
  tool(
6105
6701
  "submit_feedback",
6106
- "Submit minimal skill feedback. If the response includes next_step.submit_remembrance_payload, call submit_remembrance to promote substantive feedback to rich evidence. For self-corrections or CI/deploy/release misses, use submit_remembrance with type failure_report.",
6702
+ "Submit minimal post-use skill feedback. When the skill came from query_skills, pass its query_id and result_id to close the surfaced-to-use funnel. If the response includes next_step.submit_remembrance_payload, call submit_remembrance to promote substantive feedback to rich evidence. For self-corrections or CI/deploy/release misses, use submit_remembrance with type failure_report.",
6107
6703
  "/api/v1/agent/feedback",
6108
6704
  feedbackToolSchema
6109
6705
  ),
6706
+ tool(
6707
+ "submit_query_feedback",
6708
+ "Submit one complete set of explicit good, partial, or poor judgments for result_id values from one query_skills call, using the same auth scope as that query. Unrated results stay neutral. An identical retry is safe, but changed later judgments conflict. Same-query better/worse labels can train retrieval without changing global skill usefulness; use submit_feedback only after actually using a skill.",
6709
+ "/api/v1/agent/query-feedback",
6710
+ agentQueryFeedbackRequestSchema
6711
+ ),
6712
+ tool(
6713
+ "report_task_outcome",
6714
+ "Report completion or abandonment for a query. Remembrance accepts one terminal outcome per query; retry the same report with the same idempotency_key, and do not submit a different later outcome. Include only result_ids listed in task_outcome.eligible_result_ids; each result and bundle also carries task_outcome_eligible. When two or three selected skills exactly match a returned skill_bundles entry, include its bundle_id for value attribution; other combinations are accepted as funnel telemetry but do not train a skill or bundle cohort. Include bounded token totals only when the runtime exposes them. For Vercel AI Gateway work, include metering_reference.adapter=vercel_ai_gateway and every gen_ generation ID used by the task (maximum eight); Remembrance retrieves authoritative usage asynchronously, and caller totals never establish proof trust. Never send prompts, outputs, source paths, private URLs, transcripts, or proprietary task content. Completion without token counts still closes the funnel but cannot establish metered savings proof.",
6715
+ "/api/v1/agent/task-outcomes",
6716
+ agentTaskOutcomeRequestSchema
6717
+ ),
6718
+ tool(
6719
+ "get_value_proof",
6720
+ "Fetch and cryptographically verify the token-only signed proof referenced by a qualified potential_savings estimate. Successful results include signature_verified=true. Public-skill proofs are anonymous reads; organization-skill proofs require an active query-capable API key from the same organization, but not necessarily the key used for the original query. Proof payloads contain no organization identity, task identity, price, credit, subscription, or payment data.",
6721
+ "/api/v1/value-proofs/{id}",
6722
+ getValueProofSchema,
6723
+ "GET"
6724
+ ),
6110
6725
  tool(
6111
6726
  "submit_remembrance",
6112
6727
  "Submit a full remembrance payload with detailed reusable evidence, including high-value self-corrections, user-caught mistakes, CI/deploy failures, and release/versioning misses as type failure_report. Do not include secrets or raw private payloads.",
@@ -6205,10 +6820,12 @@ function resolveApiKey() {
6205
6820
  return fromFile ? String(fromFile) : "";
6206
6821
  }
6207
6822
  var apiBase = (process.env.REMEMBRANCE_API_URL || readRemembranceConfig().apiUrl || "https://remembrance.dev").replace(/\/$/, "");
6208
- var SERVER_VERSION = true ? "0.1.13" : "0.0.0-dev";
6823
+ var SERVER_VERSION = true ? "0.1.33" : "0.0.0-dev";
6209
6824
  var tools = toolDefinitions;
6210
6825
  var inputBuffer = Buffer.alloc(0);
6211
6826
  var clientFraming = "ndjson";
6827
+ var cachedEconomicsSession = null;
6828
+ var cachedValueProofKeys = null;
6212
6829
  process.stdin.on("data", (chunk) => {
6213
6830
  inputBuffer = Buffer.concat([inputBuffer, chunk]);
6214
6831
  processMessages().catch((error) => {
@@ -6294,19 +6911,18 @@ async function handleRequest(request) {
6294
6911
  }
6295
6912
  writeResponse(response.id, response.result, response.error);
6296
6913
  }
6297
- var SERVER_INSTRUCTIONS = "Remembrance is shared operational memory for agents. BEFORE non-trivial service/API/tool/library/deployment work, call query_skills to reuse proven skills and resources instead of rediscovering them. AFTER you use a skill or resource, close the loop so the next agent inherits what you learned: call submit_feedback (useful true/false + a one-line lesson \u2014 it returns a ready submit_remembrance payload), then submit_remembrance if the lesson is reusable, or propose_skill_idea only if nothing fit and you built a new workflow. If you catch your own mistake, the user catches one, CI/deploy fails, or you fix a release/versioning miss, submit a failure_report remembrance even if no skill was used; raw MCP clients have no plugin Stop hook to remind you later. Attach evidence (reproduction detail, artifact hashes, or an attestation) \u2014 evidence-less public reports wait in unverified intake until corroborated. Redact secrets, private URLs, credentials, and proprietary content; submit summaries and hashes, not raw traces.";
6298
6914
  async function dispatchJsonRpcRequest(request) {
6299
6915
  if (request.method === "initialize") {
6300
6916
  return {
6301
6917
  id: request.id,
6302
6918
  result: {
6303
6919
  protocolVersion: "2024-11-05",
6304
- capabilities: { tools: {} },
6920
+ capabilities: { tools: {}, resources: {} },
6305
6921
  serverInfo: {
6306
6922
  name: "@remembrance-ai/mcp-server",
6307
6923
  version: SERVER_VERSION
6308
6924
  },
6309
- instructions: SERVER_INSTRUCTIONS
6925
+ instructions: REMEMBRANCE_MCP_SERVER_INSTRUCTIONS
6310
6926
  }
6311
6927
  };
6312
6928
  }
@@ -6322,6 +6938,41 @@ async function dispatchJsonRpcRequest(request) {
6322
6938
  }
6323
6939
  };
6324
6940
  }
6941
+ if (request.method === "resources/list") {
6942
+ try {
6943
+ return {
6944
+ id: request.id,
6945
+ result: await listSkillResources(request.params?.cursor)
6946
+ };
6947
+ } catch (error) {
6948
+ return { id: request.id, error: jsonRpcErrorForToolError(error) };
6949
+ }
6950
+ }
6951
+ if (request.method === "resources/templates/list") {
6952
+ return {
6953
+ id: request.id,
6954
+ result: {
6955
+ resourceTemplates: [
6956
+ {
6957
+ uriTemplate: REMEMBRANCE_SKILL_RESOURCE_URI_TEMPLATE,
6958
+ name: "Remembrance skill",
6959
+ description: "A lightweight authorized skill-selection handle. Read it, then call invoke_skill to load the current reviewed instructions.",
6960
+ mimeType: "application/json"
6961
+ }
6962
+ ]
6963
+ }
6964
+ };
6965
+ }
6966
+ if (request.method === "resources/read") {
6967
+ try {
6968
+ return {
6969
+ id: request.id,
6970
+ result: await readSkillResource(request.params?.uri)
6971
+ };
6972
+ } catch (error) {
6973
+ return { id: request.id, error: jsonRpcErrorForToolError(error) };
6974
+ }
6975
+ }
6325
6976
  if (request.method === "tools/call") {
6326
6977
  const name = String(request.params?.name ?? "");
6327
6978
  const definition = tools.find((item) => item.name === name);
@@ -6596,7 +7247,14 @@ async function readIdentity(path = identityPath()) {
6596
7247
  return JSON.parse(await readFile(path, "utf8"));
6597
7248
  }
6598
7249
  async function callRemembrance(definition, rawArguments) {
6599
- const payload = definition.schema.parse(rawArguments ?? {});
7250
+ const parsed = definition.schema.parse(rawArguments ?? {});
7251
+ const payload = definition.name === "query_skills" || definition.name === "invoke_skill" ? {
7252
+ ...parsed,
7253
+ client_context: {
7254
+ ...parsed.client_context ?? {},
7255
+ surface: "mcp"
7256
+ }
7257
+ } : parsed;
6600
7258
  const headers = {
6601
7259
  "content-type": "application/json"
6602
7260
  };
@@ -6604,6 +7262,14 @@ async function callRemembrance(definition, rawArguments) {
6604
7262
  if (apiKey) {
6605
7263
  headers["x-remembrance-api-key"] = apiKey;
6606
7264
  }
7265
+ if (definition.name !== "bootstrap_agent_identity") {
7266
+ const economicsSession = await ensureEconomicsSessionToken().catch(
7267
+ () => null
7268
+ );
7269
+ if (economicsSession) {
7270
+ headers["x-remembrance-economics-session"] = economicsSession;
7271
+ }
7272
+ }
6607
7273
  const endpoint = endpointFor(definition, payload);
6608
7274
  const controller = new AbortController();
6609
7275
  const timeout = setTimeout(() => controller.abort(), apiTimeoutMs());
@@ -6627,15 +7293,54 @@ async function callRemembrance(definition, rawArguments) {
6627
7293
  const body = await response.json().catch(async () => ({
6628
7294
  text: await response.text().catch(() => "")
6629
7295
  }));
7296
+ const verifiedBody = definition.name === "get_value_proof" && response.ok ? await verifySignedValueProofWithKeyRefresh(body, fetchValueProofKeySet) : body;
6630
7297
  return {
6631
7298
  ok: response.ok,
6632
7299
  status: response.status,
6633
7300
  idempotency_status: response.headers.get("idempotency-status"),
6634
7301
  rate_limit_remaining: response.headers.get("x-ratelimit-remaining"),
6635
7302
  etag: response.headers.get("etag"),
6636
- body
7303
+ body: verifiedBody
6637
7304
  };
6638
7305
  }
7306
+ async function fetchValueProofKeySet(forceRefresh) {
7307
+ const now = Date.now();
7308
+ if (!forceRefresh && cachedValueProofKeys && cachedValueProofKeys.expiresAt > now) {
7309
+ return cachedValueProofKeys.value;
7310
+ }
7311
+ const controller = new AbortController();
7312
+ const timeout = setTimeout(() => controller.abort(), apiTimeoutMs());
7313
+ try {
7314
+ const response = await fetch(
7315
+ `${apiBase}/.well-known/remembrance-value-proof-keys.json`,
7316
+ {
7317
+ headers: { accept: "application/json" },
7318
+ signal: controller.signal
7319
+ }
7320
+ );
7321
+ if (!response.ok) {
7322
+ throw new Error(
7323
+ `Value proof verification keys are unavailable (${response.status}).`
7324
+ );
7325
+ }
7326
+ const value = await response.json();
7327
+ cachedValueProofKeys = {
7328
+ value,
7329
+ expiresAt: now + valueProofKeyCacheTtlMs(response.headers)
7330
+ };
7331
+ return value;
7332
+ } finally {
7333
+ clearTimeout(timeout);
7334
+ }
7335
+ }
7336
+ function valueProofKeyCacheTtlMs(headers) {
7337
+ const maxAge = headers.get("cache-control")?.match(/(?:^|,)\s*max-age=(\d+)/i)?.[1];
7338
+ const seconds = Number(maxAge);
7339
+ return Number.isFinite(seconds) && seconds > 0 ? Math.min(300, Math.trunc(seconds)) * 1e3 : 3e5;
7340
+ }
7341
+ function resetValueProofKeyCacheForTests() {
7342
+ cachedValueProofKeys = null;
7343
+ }
6639
7344
  function apiTimeoutMs() {
6640
7345
  const parsed = Number.parseInt(
6641
7346
  process.env.REMEMBRANCE_API_TIMEOUT_MS ?? "",
@@ -6647,10 +7352,114 @@ function endpointFor(definition, payload) {
6647
7352
  if (!definition.endpoint) {
6648
7353
  throw new Error(`Tool ${definition.name} has no HTTP endpoint.`);
6649
7354
  }
6650
- return definition.endpoint.replaceAll(
6651
- "{slug}",
6652
- encodeURIComponent(String(payload.slug ?? ""))
7355
+ const endpoint = definition.endpoint.replaceAll("{slug}", encodeURIComponent(String(payload.slug ?? ""))).replaceAll("{id}", encodeURIComponent(String(payload.id ?? "")));
7356
+ if (definition.method !== "GET") return endpoint;
7357
+ const params = new URLSearchParams();
7358
+ const queryKeys = definition.name === "list_skills" ? ["q", "slug", "cursor", "limit"] : ["query_id", "result_id"];
7359
+ for (const key of queryKeys) {
7360
+ const value = payload[key];
7361
+ if (typeof value === "string" && value || typeof value === "number" && Number.isFinite(value)) {
7362
+ params.set(key, String(value));
7363
+ }
7364
+ }
7365
+ const query = params.toString();
7366
+ return query ? `${endpoint}?${query}` : endpoint;
7367
+ }
7368
+ async function listSkillResources(rawCursor) {
7369
+ const cursor = typeof rawCursor === "string" && rawCursor ? rawCursor : void 0;
7370
+ const catalog = await fetchSkillCatalog({ cursor, limit: 50 });
7371
+ return {
7372
+ resources: catalog.skills.map((skill) => ({
7373
+ uri: skill.resource_uri,
7374
+ name: skill.name,
7375
+ description: skill.summary,
7376
+ mimeType: "application/json"
7377
+ })),
7378
+ ...catalog.next_cursor ? { nextCursor: catalog.next_cursor } : {}
7379
+ };
7380
+ }
7381
+ async function readSkillResource(rawUri) {
7382
+ if (typeof rawUri !== "string") {
7383
+ throw new Error("resources/read requires a Remembrance skill URI.");
7384
+ }
7385
+ const slug = parseRemembranceSkillResourceUri(rawUri);
7386
+ const catalog = await fetchSkillCatalog({ slug, limit: 1 });
7387
+ const skill = catalog.skills.find((entry) => entry.slug === slug);
7388
+ if (!skill) {
7389
+ throw new Error("Skill resource is unavailable or inaccessible.");
7390
+ }
7391
+ return {
7392
+ contents: [
7393
+ {
7394
+ uri: skill.resource_uri,
7395
+ mimeType: "application/json",
7396
+ text: remembranceSkillResourceHandle(skill)
7397
+ }
7398
+ ]
7399
+ };
7400
+ }
7401
+ async function fetchSkillCatalog(input) {
7402
+ const response = await callRemembrance(
7403
+ mustFindTool("list_skills"),
7404
+ input
6653
7405
  );
7406
+ if (!response.ok) {
7407
+ throw new Error(
7408
+ `Skill catalog is unavailable${response.status ? ` (${response.status})` : ""}.`
7409
+ );
7410
+ }
7411
+ return skillCatalogResponseSchema.parse(response.body);
7412
+ }
7413
+ async function ensureEconomicsSessionToken() {
7414
+ const identity = await readIdentity();
7415
+ if (!identity) return null;
7416
+ const identityKey = `${identity.provider}:${identity.key_id}`;
7417
+ if (cachedEconomicsSession && cachedEconomicsSession.identityKey === identityKey && cachedEconomicsSession.expiresAt > Date.now() + 6e4) {
7418
+ return cachedEconomicsSession.token;
7419
+ }
7420
+ const challengeResponse = await directEconomicsSessionRequest({
7421
+ action: "challenge",
7422
+ provider: identity.provider,
7423
+ key_id: identity.key_id
7424
+ });
7425
+ const challenge = challengeResponse;
7426
+ if (!challenge.challenge_id || !challenge.signing_payload) return null;
7427
+ const signature = signPayload(
7428
+ null,
7429
+ Buffer.from(challenge.signing_payload),
7430
+ createPrivateKey(identity.private_key)
7431
+ ).toString("base64url");
7432
+ const exchangeResponse = await directEconomicsSessionRequest({
7433
+ action: "exchange",
7434
+ provider: identity.provider,
7435
+ key_id: identity.key_id,
7436
+ challenge_id: challenge.challenge_id,
7437
+ signature
7438
+ });
7439
+ const exchange = exchangeResponse;
7440
+ if (!exchange.session_token || !exchange.expires_at) return null;
7441
+ cachedEconomicsSession = {
7442
+ token: exchange.session_token,
7443
+ expiresAt: new Date(exchange.expires_at).getTime(),
7444
+ identityKey
7445
+ };
7446
+ return cachedEconomicsSession.token;
7447
+ }
7448
+ async function directEconomicsSessionRequest(payload) {
7449
+ const controller = new AbortController();
7450
+ const timeout = setTimeout(() => controller.abort(), apiTimeoutMs());
7451
+ try {
7452
+ const response = await fetch(`${apiBase}/api/v1/agent/economics/session`, {
7453
+ method: "POST",
7454
+ headers: { "content-type": "application/json" },
7455
+ body: JSON.stringify(payload),
7456
+ signal: controller.signal
7457
+ });
7458
+ if (!response.ok) return null;
7459
+ return response.json();
7460
+ } finally {
7461
+ clearTimeout(timeout);
7462
+ }
6654
7463
  }
6655
7464
  function mustFindTool(name) {
6656
7465
  const tool2 = tools.find((item) => item.name === name);
@@ -6702,5 +7511,6 @@ export {
6702
7511
  callTool,
6703
7512
  dispatchJsonRpcRequest,
6704
7513
  formatJsonRpcResponse,
6705
- readJsonRpcMessages
7514
+ readJsonRpcMessages,
7515
+ resetValueProofKeyCacheForTests
6706
7516
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remembrance-ai/mcp-server",
3
- "version": "0.1.13",
3
+ "version": "0.1.33",
4
4
  "mcpName": "io.github.dreamarkinc/remembrance",
5
5
  "description": "MCP server for discovering Remembrance skills/resources and submitting agent feedback with optional TOFU attestations.",
6
6
  "license": "Apache-2.0",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/dreamarkinc/remembrance-skills",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.1.13",
9
+ "version": "0.1.33",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "@remembrance-ai/mcp-server",
14
- "version": "0.1.13",
14
+ "version": "0.1.33",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },