@vibeiao/sdk 0.1.43 → 0.1.45

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
@@ -675,6 +675,21 @@ const loop = createAgentLoop({
675
675
  By default, `createAgentLoop(...)` also enables strict-memory runtime checks in `observe` mode.
676
676
  To make it hard-enforced, set `strictMemory.mode = 'enforce'` and provide snapshot fields for gating (`taskText`, `isMutation`, `contextPackPrepared`, `semanticRecallConfirmed`, `approvalPreflightPassed`).
677
677
 
678
+ Prompt shield is also available in the loop:
679
+ - trust model: `trusted_human | internal_system | external_untrusted`
680
+ - default behavior: external prompt-injection patterns are blocked in `enforce` mode
681
+ - sensitive mutations require trusted intent; untrusted web/review text cannot authorize actions
682
+
683
+ Objective guard is also available for objective-mutation integrity:
684
+ - external sources can propose objective changes but cannot command overrides
685
+ - external proposals require mission alignment + evidence (and optional verification) before acceptance
686
+ - trusted human/system objective changes are allowed by policy
687
+
688
+ Adaptive reflection policy is available for cadence-based adaptation (not per-review thrash):
689
+ - aggregate feedback over time windows and score recurring themes
690
+ - evaluate thresholds + cooldown + daily adaptation caps
691
+ - output `hold|observe|adapt` decision and optional bounded adaptation plan
692
+
678
693
  You can also enforce dual-mode work arbitration:
679
694
  - `owner_bound` agents: human-first (owner work preempts autonomous work)
680
695
  - `unbound` agents: autonomous-first (run autonomous work by default)
@@ -3,6 +3,7 @@ import { SurvivalMode, SurvivalRecommendation } from './survivalPlaybook.js';
3
3
  import { EscapeHatchDecision, EscapeHatchPolicy, EscapeHatchSnapshot } from './survivalEscapeHatch.js';
4
4
  import { CompoundingMemoryUpgradeResult, CompoundingMemoryRequiredSetResult } from './compoundingMemory.js';
5
5
  import { StrictMemoryRuntimePreset, StrictMemoryEvaluation, StrictMemoryUpgradeResult } from './strictMemoryRuntime.js';
6
+ import { P as PromptShieldDecision, O as ObjectiveGuardDecision, a as PromptShieldPolicy, b as PromptShieldInput, c as ObjectiveGuardPolicy, d as ObjectiveChangeProposal } from './objectiveGuard-d1x0xgAD.js';
6
7
 
7
8
  type AgentLoopEscapeHatchInput = {
8
9
  snapshot: ResourceSnapshot;
@@ -44,6 +45,36 @@ type AgentLoopStrictMemoryConfig = {
44
45
  /** Optional hook when strict-memory evaluation runs. */
45
46
  onEvaluation?: (ev: StrictMemoryEvaluation) => Promise<void> | void;
46
47
  };
48
+ type AgentLoopPromptShieldConfig = {
49
+ /** Enable prompt-injection shield over untrusted external content. Default true. */
50
+ enabled?: boolean;
51
+ /** observe logs/records only; enforce blocks actions when shield fails. Default observe. */
52
+ mode?: 'observe' | 'enforce';
53
+ /** Optional policy overrides for blocked flags. */
54
+ policy?: PromptShieldPolicy;
55
+ /** Optional mapper from snapshot to trust-labeled inputs. */
56
+ buildInputs?: (ctx: {
57
+ snapshot: ResourceSnapshot;
58
+ timestamp: number;
59
+ }) => PromptShieldInput[];
60
+ /** Optional hook when prompt shield decision is produced. */
61
+ onDecision?: (decision: PromptShieldDecision) => Promise<void> | void;
62
+ };
63
+ type AgentLoopObjectiveGuardConfig = {
64
+ /** Enable objective integrity checks for external objective-change attempts. Default true. */
65
+ enabled?: boolean;
66
+ /** observe logs only; enforce blocks actions when objective mutation is denied. Default observe. */
67
+ mode?: 'observe' | 'enforce';
68
+ /** Policy requirements for external objective mutation acceptance. */
69
+ policy?: ObjectiveGuardPolicy;
70
+ /** Build proposed objective change from snapshot. Return null when no proposal is present. */
71
+ buildProposal?: (ctx: {
72
+ snapshot: ResourceSnapshot;
73
+ timestamp: number;
74
+ }) => ObjectiveChangeProposal | null;
75
+ /** Optional hook when objective decision is produced. */
76
+ onDecision?: (decision: ObjectiveGuardDecision) => Promise<void> | void;
77
+ };
47
78
  type AgentOwnershipMode = 'owner_bound' | 'unbound';
48
79
  type AgentPriorityMode = 'human_first' | 'autonomous_first';
49
80
  type AgentHumanDemand = {
@@ -88,6 +119,10 @@ type AgentLoopContext = {
88
119
  strictMemoryPreset?: StrictMemoryRuntimePreset;
89
120
  strictMemoryEvaluation?: StrictMemoryEvaluation;
90
121
  strictMemoryUpgrade?: StrictMemoryUpgradeResult;
122
+ /** Prompt-injection shield decision for this cycle. */
123
+ promptShieldDecision?: PromptShieldDecision;
124
+ /** Objective integrity guard decision for this cycle (when proposal exists). */
125
+ objectiveGuardDecision?: ObjectiveGuardDecision;
91
126
  /** Human-vs-autonomous work arbitration decision for this cycle. */
92
127
  workArbitration?: AgentWorkArbitrationDecision;
93
128
  timestamp: number;
@@ -168,6 +203,8 @@ type AgentLoopConfig = {
168
203
  memory?: AgentLoopMemoryConfig;
169
204
  durability?: AgentLoopDurabilityConfig;
170
205
  strictMemory?: AgentLoopStrictMemoryConfig;
206
+ promptShield?: AgentLoopPromptShieldConfig;
207
+ objectiveGuard?: AgentLoopObjectiveGuardConfig;
171
208
  autonomy?: AgentLoopAutonomyConfig;
172
209
  };
173
210
  /**
@@ -186,4 +223,4 @@ declare const createAgentLoop: (config: AgentLoopConfig) => {
186
223
  runOnce: () => Promise<void>;
187
224
  };
188
225
 
189
- export { type AgentHumanDemand, type AgentLoopAutonomyConfig, type AgentLoopConfig, type AgentLoopContext, type AgentLoopDurabilityConfig, type AgentLoopEscapeHatchConfig, type AgentLoopEscapeHatchInput, type AgentLoopHooks, type AgentLoopMemoryConfig, type AgentLoopStrictMemoryConfig, type AgentOwnershipMode, type AgentPriorityMode, type AgentWorkArbitrationDecision, createAgentLoop };
226
+ export { type AgentHumanDemand, type AgentLoopAutonomyConfig, type AgentLoopConfig, type AgentLoopContext, type AgentLoopDurabilityConfig, type AgentLoopEscapeHatchConfig, type AgentLoopEscapeHatchInput, type AgentLoopHooks, type AgentLoopMemoryConfig, type AgentLoopObjectiveGuardConfig, type AgentLoopPromptShieldConfig, type AgentLoopStrictMemoryConfig, type AgentOwnershipMode, type AgentPriorityMode, type AgentWorkArbitrationDecision, createAgentLoop };
package/dist/agentLoop.js CHANGED
@@ -3,8 +3,10 @@ import {
3
3
  upgradeCompoundingMemorySystem
4
4
  } from "./chunk-JJNRDU7F.js";
5
5
  import {
6
- createDurabilityProxyClient
7
- } from "./chunk-PVCW4MAY.js";
6
+ createDurabilityProxyClient,
7
+ evaluateObjectiveChange,
8
+ evaluatePromptShield
9
+ } from "./chunk-EKV2BZMZ.js";
8
10
  import {
9
11
  createSelfRelianceMonitor
10
12
  } from "./chunk-M7DQTU5R.js";
@@ -59,6 +61,10 @@ var createAgentLoop = (config) => {
59
61
  const strictMemoryEnabled = config.strictMemory?.enabled ?? true;
60
62
  const strictMode = config.strictMemory?.mode ?? "observe";
61
63
  const strictMemoryPreset = createStrictMemoryRuntimePreset(config.strictMemory?.preset || {});
64
+ const promptShieldEnabled = config.promptShield?.enabled ?? true;
65
+ const promptShieldMode = config.promptShield?.mode ?? "observe";
66
+ const objectiveGuardEnabled = config.objectiveGuard?.enabled ?? true;
67
+ const objectiveGuardMode = config.objectiveGuard?.mode ?? "observe";
62
68
  const autonomyEnabled = config.autonomy?.enabled ?? true;
63
69
  const ownershipMode = config.autonomy?.ownershipMode ?? "owner_bound";
64
70
  const priorityMode = config.autonomy?.priorityMode ?? (ownershipMode === "unbound" ? "autonomous_first" : "human_first");
@@ -178,6 +184,64 @@ var createAgentLoop = (config) => {
178
184
  approvalPreflightPassed: Boolean(raw.approvalPreflightPassed)
179
185
  };
180
186
  };
187
+ const defaultPromptShieldInputBuilder = (ctx) => {
188
+ const raw = ctx.snapshot;
189
+ const out = [];
190
+ const taskText = String(raw.taskText || raw.objective || "").trim();
191
+ if (taskText) {
192
+ out.push({ source: "task", trust: "trusted_human", content: taskText });
193
+ }
194
+ const externalCandidates = [
195
+ ["web", raw.webContext],
196
+ ["reviews", raw.reviewText],
197
+ ["reviews_batch", raw.reviewTexts],
198
+ ["external", raw.externalInputs],
199
+ ["search", raw.searchSnippets]
200
+ ];
201
+ for (const [source, value] of externalCandidates) {
202
+ if (typeof value === "string" && value.trim()) {
203
+ out.push({ source, trust: "external_untrusted", content: value });
204
+ continue;
205
+ }
206
+ if (Array.isArray(value)) {
207
+ for (const item of value) {
208
+ const text = typeof item === "string" ? item : JSON.stringify(item);
209
+ if (text && text.trim()) out.push({ source, trust: "external_untrusted", content: text });
210
+ }
211
+ continue;
212
+ }
213
+ if (value && typeof value === "object") {
214
+ const text = JSON.stringify(value);
215
+ if (text && text !== "{}") out.push({ source, trust: "external_untrusted", content: text });
216
+ }
217
+ }
218
+ return out;
219
+ };
220
+ const defaultObjectiveProposalBuilder = (ctx) => {
221
+ const raw = ctx.snapshot;
222
+ const proposedObjective = String(raw.proposedObjective || "").trim();
223
+ const currentObjective = String(raw.taskText || raw.objective || "").trim();
224
+ if (!proposedObjective || !currentObjective) return null;
225
+ const source = String(raw.proposedObjectiveSource || "external");
226
+ const trust = raw.proposedObjectiveTrust || "external_untrusted";
227
+ const rationale = typeof raw.proposedObjectiveRationale === "string" ? raw.proposedObjectiveRationale : void 0;
228
+ const evidenceRaw = Array.isArray(raw.proposedObjectiveEvidence) ? raw.proposedObjectiveEvidence : [];
229
+ const evidence = evidenceRaw.map((e) => {
230
+ if (!e || typeof e !== "object") return null;
231
+ const r = e;
232
+ const claim = String(r.claim || "").trim();
233
+ if (!claim) return null;
234
+ return { claim, verified: r.verified === true };
235
+ }).filter(Boolean);
236
+ return {
237
+ source,
238
+ trust,
239
+ currentObjective,
240
+ proposedObjective,
241
+ rationale,
242
+ evidence
243
+ };
244
+ };
181
245
  const resolveHumanDemand = async () => {
182
246
  const raw = await config.autonomy?.resolveHumanDemand?.();
183
247
  if (typeof raw === "boolean") return { pending: raw };
@@ -237,6 +301,27 @@ var createAgentLoop = (config) => {
237
301
  await config.strictMemory.onEvaluation(strictMemoryEvaluation);
238
302
  }
239
303
  }
304
+ let promptShieldDecision;
305
+ if (promptShieldEnabled) {
306
+ const shieldInputs = (config.promptShield?.buildInputs || defaultPromptShieldInputBuilder)({ snapshot, timestamp });
307
+ promptShieldDecision = evaluatePromptShield(shieldInputs, {
308
+ isSensitiveAction: Boolean(snapshot.isMutation),
309
+ policy: config.promptShield?.policy
310
+ });
311
+ if (config.promptShield?.onDecision) {
312
+ await config.promptShield.onDecision(promptShieldDecision);
313
+ }
314
+ }
315
+ let objectiveGuardDecision;
316
+ if (objectiveGuardEnabled) {
317
+ const proposal = (config.objectiveGuard?.buildProposal || defaultObjectiveProposalBuilder)({ snapshot, timestamp });
318
+ if (proposal) {
319
+ objectiveGuardDecision = evaluateObjectiveChange(proposal, config.objectiveGuard?.policy);
320
+ if (config.objectiveGuard?.onDecision) {
321
+ await config.objectiveGuard.onDecision(objectiveGuardDecision);
322
+ }
323
+ }
324
+ }
240
325
  const humanDemand = autonomyEnabled ? await resolveHumanDemand() : { pending: false };
241
326
  const arbitrationBase = {
242
327
  ownershipMode,
@@ -272,6 +357,8 @@ var createAgentLoop = (config) => {
272
357
  strictMemoryPreset: strictMemoryEnabled ? strictMemoryPreset : void 0,
273
358
  strictMemoryEvaluation,
274
359
  strictMemoryUpgrade: strictMemoryEnabled ? strictMemoryUpgrade : void 0,
360
+ promptShieldDecision,
361
+ objectiveGuardDecision,
275
362
  workArbitration: arbitrationBase,
276
363
  timestamp
277
364
  };
@@ -296,6 +383,13 @@ var createAgentLoop = (config) => {
296
383
  const missing = ctx.strictMemoryEvaluation.missingSteps.join(",");
297
384
  throw new Error(`strict_memory_blocked:${missing}`);
298
385
  }
386
+ if (promptShieldEnabled && promptShieldMode === "enforce" && ctx.promptShieldDecision && !ctx.promptShieldDecision.allow) {
387
+ const flags = ctx.promptShieldDecision.flags.join(",");
388
+ throw new Error(`prompt_shield_blocked:${flags}`);
389
+ }
390
+ if (objectiveGuardEnabled && objectiveGuardMode === "enforce" && ctx.objectiveGuardDecision && !ctx.objectiveGuardDecision.allowObjectiveChange) {
391
+ throw new Error(`objective_guard_blocked:${ctx.objectiveGuardDecision.reason}`);
392
+ }
299
393
  if (autonomyEnabled && config.autonomy?.onAutonomous && rolloutMode === "enforce") {
300
394
  if (ctx.workArbitration?.runHumanTask) await runHumanTask();
301
395
  if (ctx.workArbitration?.runAutonomousTask) await runAutonomousTask();
@@ -0,0 +1,247 @@
1
+ // src/durabilityProxy.ts
2
+ var withTimeout = async (fetcher, input, init, timeoutMs) => {
3
+ const controller = new AbortController();
4
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
5
+ try {
6
+ return await fetcher(input, { ...init, signal: controller.signal });
7
+ } finally {
8
+ clearTimeout(timer);
9
+ }
10
+ };
11
+ var readJson = async (response) => {
12
+ const text = await response.text();
13
+ if (!text) return null;
14
+ try {
15
+ return JSON.parse(text);
16
+ } catch {
17
+ return { raw: text };
18
+ }
19
+ };
20
+ var createDurabilityProxyClient = (options) => {
21
+ const fetcher = options.fetcher || fetch;
22
+ const timeoutMs = Number.isFinite(Number(options.timeoutMs)) ? Math.max(500, Number(options.timeoutMs)) : 8e3;
23
+ const base = String(options.baseUrl || "").replace(/\/+$/, "");
24
+ const agentId = String(options.agentId || "").trim();
25
+ const agentToken = String(options.agentToken || "").trim();
26
+ if (!base) throw new Error("durability_proxy_base_missing");
27
+ if (!agentId) throw new Error("durability_proxy_agent_id_missing");
28
+ if (!agentToken) throw new Error("durability_proxy_agent_token_missing");
29
+ const headers = {
30
+ "content-type": "application/json",
31
+ "x-agent-id": agentId,
32
+ "x-agent-token": agentToken
33
+ };
34
+ return {
35
+ async writeCheckpoint(payloadJson, opts = {}) {
36
+ const response = await withTimeout(
37
+ fetcher,
38
+ `${base}/v1/checkpoints`,
39
+ {
40
+ method: "POST",
41
+ headers,
42
+ body: JSON.stringify({
43
+ payloadJson,
44
+ sha256: opts.sha256,
45
+ contentType: opts.contentType,
46
+ metadata: opts.metadata
47
+ })
48
+ },
49
+ timeoutMs
50
+ );
51
+ const body = await readJson(response);
52
+ if (!response.ok) {
53
+ const detail = body?.error || `http_${response.status}`;
54
+ throw new Error(`durability_checkpoint_write_failed:${detail}`);
55
+ }
56
+ return body;
57
+ },
58
+ async latestCheckpoint() {
59
+ const response = await withTimeout(
60
+ fetcher,
61
+ `${base}/v1/checkpoints/latest`,
62
+ { method: "GET", headers: { "x-agent-id": agentId, "x-agent-token": agentToken } },
63
+ timeoutMs
64
+ );
65
+ const body = await readJson(response);
66
+ if (!response.ok) {
67
+ const detail = body?.error || `http_${response.status}`;
68
+ throw new Error(`durability_checkpoint_latest_failed:${detail}`);
69
+ }
70
+ return body;
71
+ },
72
+ async writeRestoreDrill(ok, opts = {}) {
73
+ const response = await withTimeout(
74
+ fetcher,
75
+ `${base}/v1/checkpoints/restore-drill`,
76
+ {
77
+ method: "POST",
78
+ headers,
79
+ body: JSON.stringify({
80
+ checkpointId: opts.checkpointId,
81
+ ok,
82
+ details: opts.details
83
+ })
84
+ },
85
+ timeoutMs
86
+ );
87
+ const body = await readJson(response);
88
+ if (!response.ok) {
89
+ const detail = body?.error || `http_${response.status}`;
90
+ throw new Error(`durability_restore_drill_write_failed:${detail}`);
91
+ }
92
+ return body;
93
+ }
94
+ };
95
+ };
96
+
97
+ // src/promptShield.ts
98
+ var RULES = [
99
+ {
100
+ flag: "instruction_override",
101
+ risk: "high",
102
+ test: [/ignore\s+(all\s+)?previous/i, /disregard\s+instructions/i, /new\s+system\s+prompt/i]
103
+ },
104
+ {
105
+ flag: "credential_exfiltration",
106
+ risk: "high",
107
+ test: [/api\s*key/i, /private\s*key/i, /seed\s*phrase/i, /wallet\s*secret/i, /send\s+me\s+your\s+token/i]
108
+ },
109
+ {
110
+ flag: "destructive_command",
111
+ risk: "high",
112
+ test: [/\brm\s+-rf\b/i, /drop\s+database/i, /delete\s+all/i, /overwrite\s+memory/i]
113
+ },
114
+ {
115
+ flag: "authority_spoof",
116
+ risk: "medium",
117
+ test: [/as\s+your\s+owner/i, /authorized\s+admin/i, /from\s+charles/i]
118
+ }
119
+ ];
120
+ var rankRisk = (a, b) => {
121
+ const w = { low: 1, medium: 2, high: 3 };
122
+ return w[a] >= w[b] ? a : b;
123
+ };
124
+ var toDefaultBlockSet = () => /* @__PURE__ */ new Set(["instruction_override", "credential_exfiltration", "destructive_command", "authority_spoof", "sensitive_action_without_trust"]);
125
+ var evaluatePromptShield = (inputs, options = {}) => {
126
+ const policy = options.policy || {};
127
+ const blockSet = policy.blockOnFlags ? new Set(policy.blockOnFlags) : toDefaultBlockSet();
128
+ const rationale = [];
129
+ const blockedInputs = [];
130
+ const flags = /* @__PURE__ */ new Set();
131
+ let risk = "low";
132
+ for (const input of inputs) {
133
+ if (input.trust !== "external_untrusted") continue;
134
+ const text = String(input.content || "");
135
+ for (const rule of RULES) {
136
+ if (rule.test.some((rx) => rx.test(text))) {
137
+ flags.add(rule.flag);
138
+ risk = rankRisk(risk, rule.risk);
139
+ }
140
+ }
141
+ }
142
+ if (options.isSensitiveAction) {
143
+ const hasTrusted = inputs.some((i) => i.trust === "trusted_human" || i.trust === "internal_system");
144
+ if (!hasTrusted) {
145
+ flags.add("sensitive_action_without_trust");
146
+ risk = rankRisk(risk, "high");
147
+ rationale.push("Sensitive action lacks trusted human/system intent; external input cannot authorize mutation.");
148
+ }
149
+ }
150
+ const blocked = [...flags].some((f) => blockSet.has(f));
151
+ if (blocked) {
152
+ for (const input of inputs) {
153
+ if (input.trust === "external_untrusted") blockedInputs.push(input);
154
+ }
155
+ }
156
+ if (!flags.size) {
157
+ rationale.push("No injection indicators detected in untrusted sources.");
158
+ } else {
159
+ rationale.push(`Detected prompt-shield flags: ${[...flags].join(",")}`);
160
+ }
161
+ if (policy.allowUntrustedForAnalysisOnly && blocked) {
162
+ rationale.push("Untrusted content may be used for analysis only; execution remains blocked.");
163
+ }
164
+ return {
165
+ allow: !blocked,
166
+ risk,
167
+ flags: [...flags],
168
+ rationale,
169
+ blockedInputs
170
+ };
171
+ };
172
+
173
+ // src/objectiveGuard.ts
174
+ var normalize = (v) => String(v || "").trim().toLowerCase();
175
+ var isExplicitInstruction = (text) => /\b(do this instead|switch objective|change objective|stop current objective|ignore current objective)\b/i.test(
176
+ text || ""
177
+ );
178
+ var missionAlignment = (currentObjective, proposedObjective) => {
179
+ const a = new Set(normalize(currentObjective).split(/\W+/).filter(Boolean));
180
+ const b = new Set(normalize(proposedObjective).split(/\W+/).filter(Boolean));
181
+ if (!a.size || !b.size) return false;
182
+ let overlap = 0;
183
+ for (const tok of b) if (a.has(tok)) overlap += 1;
184
+ return overlap / Math.max(1, b.size) >= 0.2;
185
+ };
186
+ var evaluateObjectiveChange = (proposal, policy = {}) => {
187
+ const requireMissionAlignment = policy.requireMissionAlignment ?? true;
188
+ const requireEvidenceVerification = policy.requireEvidenceVerification ?? true;
189
+ const allowExternalExplicitInstruction = policy.allowExternalExplicitInstruction ?? false;
190
+ const explicitInstruction = isExplicitInstruction(proposal.proposedObjective) || isExplicitInstruction(proposal.rationale || "");
191
+ const missionAligned = missionAlignment(proposal.currentObjective, proposal.proposedObjective);
192
+ const evidence = Array.isArray(proposal.evidence) ? proposal.evidence : [];
193
+ const evidenceProvided = evidence.length > 0;
194
+ const evidenceVerified = evidenceProvided && evidence.every((e) => e.verified === true);
195
+ if (proposal.trust === "trusted_human" || proposal.trust === "internal_system") {
196
+ return {
197
+ allowObjectiveChange: true,
198
+ reason: "trusted_source_override",
199
+ checks: { explicitInstruction, missionAligned, evidenceProvided, evidenceVerified },
200
+ risk: "low"
201
+ };
202
+ }
203
+ if (explicitInstruction && !allowExternalExplicitInstruction) {
204
+ return {
205
+ allowObjectiveChange: false,
206
+ reason: "external_explicit_instruction_blocked",
207
+ checks: { explicitInstruction, missionAligned, evidenceProvided, evidenceVerified },
208
+ risk: "high"
209
+ };
210
+ }
211
+ if (requireMissionAlignment && !missionAligned) {
212
+ return {
213
+ allowObjectiveChange: false,
214
+ reason: "mission_alignment_failed",
215
+ checks: { explicitInstruction, missionAligned, evidenceProvided, evidenceVerified },
216
+ risk: "high"
217
+ };
218
+ }
219
+ if (!evidenceProvided) {
220
+ return {
221
+ allowObjectiveChange: false,
222
+ reason: "evidence_missing",
223
+ checks: { explicitInstruction, missionAligned, evidenceProvided, evidenceVerified },
224
+ risk: "medium"
225
+ };
226
+ }
227
+ if (requireEvidenceVerification && !evidenceVerified) {
228
+ return {
229
+ allowObjectiveChange: false,
230
+ reason: "evidence_unverified",
231
+ checks: { explicitInstruction, missionAligned, evidenceProvided, evidenceVerified },
232
+ risk: "high"
233
+ };
234
+ }
235
+ return {
236
+ allowObjectiveChange: true,
237
+ reason: "reasoned_external_change_allowed",
238
+ checks: { explicitInstruction, missionAligned, evidenceProvided, evidenceVerified },
239
+ risk: "low"
240
+ };
241
+ };
242
+
243
+ export {
244
+ createDurabilityProxyClient,
245
+ evaluatePromptShield,
246
+ evaluateObjectiveChange
247
+ };
package/dist/index.d.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  import '@solana/web3.js';
2
- export { C as ClaimPurpose, c as ClaimResponse, H as HumanAppCategory, d as ListingInput, L as ListingRecord, e as ListingReviewRecord, b as ListingStatus, a as ListingType, T as TicketVerifyResponse, V as VerifiedClaimResponse } from './shared-djjMij1F.js';
2
+ export { C as ClaimPurpose, d as ClaimResponse, H as HumanAppCategory, e as ListingInput, a as ListingRecord, L as ListingReviewRecord, c as ListingStatus, b as ListingType, T as TicketVerifyResponse, V as VerifiedClaimResponse } from './shared-Ciwu1xv_.js';
3
3
  export { SelfReliance, createAutoSelfReliance, createSelfRelianceMonitor, createSelfReliancePolicy, createSurvivalMiddleware, withSurvival } from './selfReliance.js';
4
4
  export { ReflectionActionStatus, ReflectionCandidate, ReflectionCategory, ReflectionCheckpoint, ReflectionClient, ReflectionCycleOptions, ReflectionCycleResult, ReflectionPlan, ReflectionStore, RevenueMovementSignal, RevenueSnapshot, buildReflectionBacklog, buildReflectionCandidate, bumpSemver, classifyReview, createInMemoryReflectionStore, runReflectionCycle, scoreReviewPriority } from './reflection.js';
5
5
  export { SurvivalMode, SurvivalRecommendation, classifySurvivalMode, formatSurvivalRecommendation, getSurvivalRecommendation } from './survivalPlaybook.js';
6
6
  export { SurvivalIntegrationDecision, getSurvivalPlaybookDecision, getSurvivalPlaybookDecisionFromSelfReliance } from './survivalIntegration.js';
7
7
  export { EscapeHatchDecision, EscapeHatchPolicy, EscapeHatchSnapshot, evaluateEscapeHatch, formatEscapeHatchDecision } from './survivalEscapeHatch.js';
8
8
  export { MarketDiscoveryClient, MarketNeed, MarketSignal, deriveMarketNeeds, discoverMarketNeeds, extractMarketSignals, runMarketDiscovery } from './marketDiscovery.js';
9
- export { A as AgentResourceProvidersManifest, a as AnalyticsPoint, b as ApiCreditProvider, c as ApiCreditProviderFactoryOptions, d as ApiCreditProviderPreset, e as ApiCreditProviderPresetInput, f as ApiResponse, B as BuybackEvent, C as CONTEXT_PACK_SECTION_ORDER, g as ContextPack, h as ContextPackBudget, i as ContextPackInput, j as ContextPackOptions, k as ContextPackSectionKey, l as ContextPackSections, D as DurabilityCheckpointWriteOptions, m as DurabilityProxyClientOptions, n as DurabilityRestoreDrillWriteOptions, L as LISTING_NAME_MAX_LENGTH, o as LISTING_NAME_RECOMMENDED_MAX, p as LISTING_TAGLINE_MAX_LENGTH, q as LISTING_TAGLINE_RECOMMENDED_MAX, r as LeaderboardEntry, s as LeaderboardQuery, t as ListingNamingValidationOptions, u as ListingNamingValidationResult, v as ListingQuery, w as ListingReviewCreatePayload, x as ListingReviewResponsePayload, y as ListingVersionPayload, M as MarketingCampaign, z as MarketingLinkOptions, E as MemoryPingChallengeResponse, F as MemoryPingPayload, O as OpenRouterCredits, P as ProcurementCandidate, G as ProcurementDecision, H as ProcurementTaskProfile, I as ProcurementWeights, R as ResourceProviderManifestEntry, J as ResourceSnapshot, K as ReviewGate, N as ReviewGateRecord, Q as ReviewRequiredPayload, S as SdkAutoUpdatedRestartRequiredError, T as SdkUpdateCheckOptions, U as SdkUpdatePolicyCheckOptions, V as SdkUpdateRequiredError, W as SdkUpdateStatus, TopupDecision, TopupRequest, TreasuryLedgerEvent, TreasuryPolicy, TreasuryPolicyV1, TreasuryState, X as VIBEIAO_IDL, Y as VibeClient, Z as VibeClientOptions, _ as VibeRegistry, $ as assertSurvivalProvidersConfigured, a0 as buildBadgeMarkdown, a1 as buildClaimMessage, a2 as buildJupiterSwapUrl, a3 as buildListingVersionMessage, a4 as buildMemoryPingMessage, a5 as buildOwnerTransferMessage, a6 as buildProcurementPrompt, a7 as buildRaydiumSwapUrl, a8 as buildReviewPrompt, a9 as buildReviewRequired, aa as buildReviewResponseMessage, ab as buildSdkUpdateCommand, ac as buildShareCopy, ad as buildShareLink, ae as buildTradeLinks, buildTreasuryLedgerEvent, af as checkForSdkUpdate, ag as checkForSdkUpdatePolicy, ah as compareVersions, ai as createApiCreditProvider, aj as createApiCreditProviders, ak as createApiCreditProvidersFromManifest, al as createCampaign, am as createContextPack, an as createDurabilityProxyClient, createTreasuryPolicy, ao as decideProcurementForTask, ap as estimateContextPackTokens, evaluateTopupRequest, aq as getResourceSnapshot, ar as normalizeListingText, as as rankListingsForTask, at as sanitizeListingNaming, au as scoreListingForTask, treasuryStateFromSnapshot, av as validateContextPack, aw as validateListingNaming, validateTreasuryPolicy } from './treasuryGuardian.js';
9
+ export { A as AdaptiveAdaptationPlan, a as AdaptiveFeedbackAggregate, b as AdaptivePolicyConfig, c as AdaptivePolicyDecision, d as AdaptivePolicyState, e as AdaptiveReflectionStore, f as AdaptiveTheme, g as AgentResourceProvidersManifest, h as AnalyticsPoint, i as ApiCreditProvider, j as ApiCreditProviderFactoryOptions, k as ApiCreditProviderPreset, l as ApiCreditProviderPresetInput, m as ApiResponse, B as BuybackEvent, C as CONTEXT_PACK_SECTION_ORDER, n as ContextPack, o as ContextPackBudget, p as ContextPackInput, q as ContextPackOptions, r as ContextPackSectionKey, s as ContextPackSections, D as DurabilityCheckpointWriteOptions, t as DurabilityProxyClientOptions, u as DurabilityRestoreDrillWriteOptions, L as LISTING_NAME_MAX_LENGTH, v as LISTING_NAME_RECOMMENDED_MAX, w as LISTING_TAGLINE_MAX_LENGTH, x as LISTING_TAGLINE_RECOMMENDED_MAX, y as LeaderboardEntry, z as LeaderboardQuery, E as ListingNamingValidationOptions, F as ListingNamingValidationResult, G as ListingQuery, H as ListingReviewCreatePayload, I as ListingReviewResponsePayload, J as ListingVersionPayload, M as MarketingCampaign, K as MarketingLinkOptions, N as MemoryPingChallengeResponse, O as MemoryPingPayload, P as OpenRouterCredits, Q as ProcurementCandidate, R as ProcurementDecision, S as ProcurementTaskProfile, T as ProcurementWeights, U as ResourceProviderManifestEntry, V as ResourceSnapshot, W as ReviewGate, X as ReviewGateRecord, Y as ReviewRequiredPayload, Z as RunAdaptiveReflectionOptions, _ as SdkAutoUpdatedRestartRequiredError, $ as SdkUpdateCheckOptions, a0 as SdkUpdatePolicyCheckOptions, a1 as SdkUpdateRequiredError, a2 as SdkUpdateStatus, TopupDecision, TopupRequest, TreasuryLedgerEvent, TreasuryPolicy, TreasuryPolicyV1, TreasuryState, a3 as VIBEIAO_IDL, a4 as VibeClient, a5 as VibeClientOptions, a6 as VibeRegistry, a7 as aggregateFeedbackSignals, a8 as assertSurvivalProvidersConfigured, a9 as buildAdaptivePlan, aa as buildBadgeMarkdown, ab as buildClaimMessage, ac as buildJupiterSwapUrl, ad as buildListingVersionMessage, ae as buildMemoryPingMessage, af as buildOwnerTransferMessage, ag as buildProcurementPrompt, ah as buildRaydiumSwapUrl, ai as buildReviewPrompt, aj as buildReviewRequired, ak as buildReviewResponseMessage, al as buildSdkUpdateCommand, am as buildShareCopy, an as buildShareLink, ao as buildTradeLinks, buildTreasuryLedgerEvent, ap as checkForSdkUpdate, aq as checkForSdkUpdatePolicy, ar as compareVersions, as as createApiCreditProvider, at as createApiCreditProviders, au as createApiCreditProvidersFromManifest, av as createCampaign, aw as createContextPack, ax as createDurabilityProxyClient, createTreasuryPolicy, ay as decideProcurementForTask, az as estimateContextPackTokens, aA as evaluateAdaptiveReflectionPolicy, evaluateTopupRequest, aB as getResourceSnapshot, aC as normalizeListingText, aD as rankListingsForTask, aE as runAdaptiveReflectionCycle, aF as sanitizeListingNaming, aG as scoreListingForTask, treasuryStateFromSnapshot, aH as validateContextPack, aI as validateListingNaming, validateTreasuryPolicy } from './treasuryGuardian.js';
10
10
  export { OUTCOME_BOUND_FLOW_SCHEMA, OUTCOME_BOUND_REQUIRED_GATES, OutcomeBoundRequiredGate, OutcomeBoundRunInput, OutcomeBoundRunStatus, assertOutcomeBoundCompleted, evaluateOutcomeBoundRun } from './outcomeBoundFlow.js';
11
11
  export { STRICT_MEMORY_RUNTIME_SCHEMA, StrictMemoryEvaluation, StrictMemoryEvaluationInput, StrictMemoryRuntimePreset, StrictMemoryTriggerSet, StrictMemoryUpgradeInput, StrictMemoryUpgradePolicy, StrictMemoryUpgradeResult, createStrictMemoryRuntimePreset, evaluateStrictMemoryExecution, isComplexTask, upgradeToStrictMemoryRuntimePreset } from './strictMemoryRuntime.js';
12
+ export { d as ObjectiveChangeProposal, e as ObjectiveChangeSourceTrust, O as ObjectiveGuardDecision, c as ObjectiveGuardPolicy, P as PromptShieldDecision, f as PromptShieldFlag, b as PromptShieldInput, a as PromptShieldPolicy, g as PromptShieldRisk, h as PromptShieldTrustLevel, i as evaluateObjectiveChange, j as evaluatePromptShield } from './objectiveGuard-d1x0xgAD.js';
12
13
  export { fetchSolBalance, fetchTokenBalance, fetchTokenBalances } from './solana.js';
13
14
  import '@coral-xyz/anchor';
package/dist/index.js CHANGED
@@ -17,8 +17,10 @@ import {
17
17
  validateTreasuryPolicy
18
18
  } from "./chunk-RNPCT2MS.js";
19
19
  import {
20
- createDurabilityProxyClient
21
- } from "./chunk-PVCW4MAY.js";
20
+ createDurabilityProxyClient,
21
+ evaluateObjectiveChange,
22
+ evaluatePromptShield
23
+ } from "./chunk-EKV2BZMZ.js";
22
24
  import {
23
25
  SelfReliance,
24
26
  createAutoSelfReliance,
@@ -246,6 +248,207 @@ var validateContextPack = (value) => {
246
248
  var CONTEXT_PACK_SECTION_ORDER = [...SECTION_ORDER];
247
249
  var estimateContextPackTokens = (textOrChars) => estimateTokensFromChars(typeof textOrChars === "number" ? textOrChars : textOrChars.length);
248
250
 
251
+ // src/adaptiveReflection.ts
252
+ var clamp01 = (n) => Math.max(0, Math.min(1, n));
253
+ var recencyWeight = (createdAt, nowMs) => {
254
+ if (!createdAt) return 0.7;
255
+ const ts = Date.parse(createdAt);
256
+ if (!Number.isFinite(ts)) return 0.7;
257
+ const hours = Math.max(0, (nowMs - ts) / 36e5);
258
+ if (hours <= 24) return 1;
259
+ if (hours <= 72) return 0.8;
260
+ if (hours <= 168) return 0.6;
261
+ return 0.4;
262
+ };
263
+ var inferTheme = (r) => {
264
+ const t = `${String(r.comment || "")} ${String(r.agent_response_comment || "")}`.toLowerCase();
265
+ if (/bug|broken|error|crash|fail/.test(t)) return "bug";
266
+ if (/downtime|timeout|unavailable|latency|disconnect/.test(t)) return "reliability";
267
+ if (/confusing|hard|ux|ui|friction/.test(t)) return "ux";
268
+ if (/price|expensive|cost|value/.test(t)) return "pricing";
269
+ if (/feature|add|request|support/.test(t)) return "feature";
270
+ if (/great|love|awesome|excellent/.test(t)) return "praise";
271
+ return "noise";
272
+ };
273
+ var classifyIssueSignal = (r) => {
274
+ const text = `${String(r.comment || "")} ${String(r.agent_response_comment || "")}`.toLowerCase();
275
+ const rating = Number(r.rating);
276
+ const criticalHint = /crash|broken|error|fail|unusable|cannot|can't|doesn't work|not work|timeout|data loss/.test(text);
277
+ const prefHint = /prefer|would like|i wish|could you|nice to have|personally|for me/.test(text);
278
+ if (criticalHint || Number.isFinite(rating) && rating <= 2 && /bug|reliability|ux|pricing|feature/.test(inferTheme(r))) {
279
+ return "critical_issue";
280
+ }
281
+ if (prefHint || inferTheme(r) === "feature" || inferTheme(r) === "praise" || inferTheme(r) === "noise") {
282
+ return "preference";
283
+ }
284
+ return "other";
285
+ };
286
+ var themeBaseWeight = {
287
+ bug: 1,
288
+ reliability: 0.95,
289
+ ux: 0.7,
290
+ pricing: 0.6,
291
+ feature: 0.55,
292
+ praise: 0.2,
293
+ noise: 0.05
294
+ };
295
+ var aggregateFeedbackSignals = (reviews, options = {}) => {
296
+ const nowMs = options.nowMs ?? Date.now();
297
+ const windowHours = options.windowHours ?? 168;
298
+ const startMs = nowMs - windowHours * 36e5;
299
+ const bucket = /* @__PURE__ */ new Map();
300
+ const inWindow = reviews.filter((r) => {
301
+ const ts = Date.parse(String(r.created_at || ""));
302
+ return Number.isFinite(ts) ? ts >= startMs : true;
303
+ });
304
+ for (const r of inWindow) {
305
+ const theme = inferTheme(r);
306
+ const rating = Number(r.rating);
307
+ const severity = Number.isFinite(rating) ? clamp01((5 - Math.max(1, Math.min(5, rating))) / 4) : 0.4;
308
+ const score = themeBaseWeight[theme] * (0.5 + severity) * recencyWeight(r.created_at, nowMs);
309
+ const prev = bucket.get(theme) || { count: 0, weightedScore: 0, criticalCount: 0, preferenceCount: 0 };
310
+ prev.count += 1;
311
+ prev.weightedScore += score;
312
+ const signalKind = classifyIssueSignal(r);
313
+ if (signalKind === "critical_issue") prev.criticalCount += 1;
314
+ if (signalKind === "preference") prev.preferenceCount += 1;
315
+ bucket.set(theme, prev);
316
+ }
317
+ const themes = [...bucket.entries()].map(([theme, v]) => ({ theme, ...v })).sort((a, b) => b.weightedScore - a.weightedScore);
318
+ return {
319
+ generatedAt: new Date(nowMs).toISOString(),
320
+ windowHours,
321
+ totalReviews: inWindow.length,
322
+ themes,
323
+ topTheme: themes[0]?.theme,
324
+ topScore: themes[0]?.weightedScore || 0
325
+ };
326
+ };
327
+ var adaptationsInLastDay = (state, nowMs) => (state.adaptationEvents || []).filter((e) => nowMs - e.ts <= 24 * 36e5).length;
328
+ var evaluateAdaptiveReflectionPolicy = (aggregate, state, policy = {}, nowMs = Date.now()) => {
329
+ const evalIntervalMs = policy.evalIntervalMs ?? 6 * 36e5;
330
+ const minReviewsForAdaptation = policy.minReviewsForAdaptation ?? 3;
331
+ const minTopScore = policy.minTopScore ?? 2.2;
332
+ const themeCooldownMs = policy.themeCooldownMs ?? 12 * 36e5;
333
+ const maxAdaptationsPerDay = policy.maxAdaptationsPerDay ?? 3;
334
+ const rationale = [];
335
+ if (state.lastEvaluatedAt && nowMs - state.lastEvaluatedAt < evalIntervalMs) {
336
+ rationale.push("evaluation_interval_not_reached");
337
+ return { decision: "hold", immediate: false, rationale, confidence: 0.9, topTheme: aggregate.topTheme, topScore: aggregate.topScore };
338
+ }
339
+ if (aggregate.totalReviews < minReviewsForAdaptation) {
340
+ rationale.push("insufficient_review_volume");
341
+ return { decision: "observe", immediate: false, rationale, confidence: 0.65, topTheme: aggregate.topTheme, topScore: aggregate.topScore };
342
+ }
343
+ if (aggregate.topScore < minTopScore || !aggregate.topTheme) {
344
+ rationale.push("signal_below_threshold");
345
+ return { decision: "observe", immediate: false, rationale, confidence: 0.6, topTheme: aggregate.topTheme, topScore: aggregate.topScore };
346
+ }
347
+ const lastThemeTs = state.lastAdaptedAtByTheme?.[aggregate.topTheme] || 0;
348
+ if (lastThemeTs && nowMs - lastThemeTs < themeCooldownMs) {
349
+ rationale.push("theme_cooldown_active");
350
+ return { decision: "hold", immediate: false, rationale, confidence: 0.85, topTheme: aggregate.topTheme, topScore: aggregate.topScore };
351
+ }
352
+ if (adaptationsInLastDay(state, nowMs) >= maxAdaptationsPerDay) {
353
+ rationale.push("daily_adaptation_limit_reached");
354
+ return { decision: "hold", immediate: false, rationale, confidence: 0.85, topTheme: aggregate.topTheme, topScore: aggregate.topScore };
355
+ }
356
+ const top = aggregate.themes.find((t) => t.theme === aggregate.topTheme);
357
+ const immediate = Boolean(top && (top.theme === "bug" || top.theme === "reliability") && top.criticalCount >= 2 && top.weightedScore >= Math.max(3, minTopScore));
358
+ if (immediate) rationale.push("immediate_fix_recommended");
359
+ rationale.push("aggregate_signal_passed");
360
+ return { decision: "adapt", immediate, rationale, confidence: immediate ? 0.9 : 0.8, topTheme: aggregate.topTheme, topScore: aggregate.topScore };
361
+ };
362
+ var buildAdaptivePlan = (decision) => {
363
+ if (decision.decision !== "adapt" || !decision.topTheme) return null;
364
+ const id = `adapt-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
365
+ const byTheme = {
366
+ bug: {
367
+ objectiveDelta: "Prioritize top reproducible bug fixes and reliability guardrails.",
368
+ expectedImpact: "Reduce churn from breakage complaints and increase trust.",
369
+ risk: "low",
370
+ rollbackCriteria: "Rollback if crash/error rates do not improve within 72h."
371
+ },
372
+ reliability: {
373
+ objectiveDelta: "Stabilize latency/timeouts and add fallback paths.",
374
+ expectedImpact: "Increase session completion and paid usage confidence.",
375
+ risk: "low",
376
+ rollbackCriteria: "Rollback if p95 latency and timeout rates do not improve in 72h."
377
+ },
378
+ ux: {
379
+ objectiveDelta: "Improve onboarding and clarify key interaction affordances.",
380
+ expectedImpact: "Improve activation and first-session retention.",
381
+ risk: "medium",
382
+ rollbackCriteria: "Rollback if activation/retention does not improve over 7 days."
383
+ },
384
+ pricing: {
385
+ objectiveDelta: "Run limited pricing/value experiment with clear guardrails.",
386
+ expectedImpact: "Improve conversion without harming satisfaction.",
387
+ risk: "medium",
388
+ rollbackCriteria: "Rollback if conversion drops >10% over baseline window."
389
+ },
390
+ feature: {
391
+ objectiveDelta: "Implement smallest high-frequency requested capability.",
392
+ expectedImpact: "Increase relevance for repeat users.",
393
+ risk: "medium",
394
+ rollbackCriteria: "Rollback if usage of new feature is negligible over 7 days."
395
+ },
396
+ praise: {
397
+ objectiveDelta: "Preserve strengths and improve adjacent UX polish.",
398
+ expectedImpact: "Sustain satisfaction trend.",
399
+ risk: "low",
400
+ rollbackCriteria: "Rollback if satisfaction trend turns negative."
401
+ },
402
+ noise: {
403
+ objectiveDelta: "Hold course; collect more data before changing roadmap.",
404
+ expectedImpact: "Avoid overfitting to noise.",
405
+ risk: "low",
406
+ rollbackCriteria: "N/A"
407
+ }
408
+ };
409
+ return { id, theme: decision.topTheme, ...byTheme[decision.topTheme], urgency: decision.immediate ? "immediate" : "normal" };
410
+ };
411
+ var runAdaptiveReflectionCycle = async (opts) => {
412
+ const now = opts.now || (() => Date.now());
413
+ const nowMs = now();
414
+ const state = await opts.reflectionStore?.loadPolicyState?.() || {};
415
+ const reviewsResp = await opts.client.getListingReviews(opts.listingId, { limit: 200, offset: 0 });
416
+ const reviews = reviewsResp.data || [];
417
+ const aggregate = aggregateFeedbackSignals(reviews, {
418
+ nowMs,
419
+ windowHours: opts.policy?.minDataWindowHours ?? 168
420
+ });
421
+ const decision = evaluateAdaptiveReflectionPolicy(aggregate, state, opts.policy, nowMs);
422
+ const plan = buildAdaptivePlan(decision);
423
+ const reflection = await runReflectionCycle({
424
+ client: opts.client,
425
+ listingId: opts.listingId,
426
+ wallet: opts.wallet,
427
+ signMessage: opts.signMessage,
428
+ store: opts.reflectionStore,
429
+ ...opts.reflectionOptions || {}
430
+ });
431
+ const next = {
432
+ ...state,
433
+ lastEvaluatedAt: nowMs
434
+ };
435
+ if (decision.decision === "adapt" && plan) {
436
+ next.lastAdaptedAtByTheme = { ...state.lastAdaptedAtByTheme || {}, [plan.theme]: nowMs };
437
+ next.adaptationEvents = [...state.adaptationEvents || [], { ts: nowMs, theme: plan.theme, actionId: plan.id }].slice(-500);
438
+ }
439
+ if (opts.reflectionStore?.savePolicyState) {
440
+ await opts.reflectionStore.savePolicyState(next);
441
+ }
442
+ return {
443
+ generatedAt: new Date(nowMs).toISOString(),
444
+ aggregate,
445
+ decision,
446
+ plan,
447
+ reflection,
448
+ policyState: next
449
+ };
450
+ };
451
+
249
452
  // src/index.ts
250
453
  var SdkUpdateRequiredError = class extends Error {
251
454
  status;
@@ -362,7 +565,7 @@ var ReviewGate = class {
362
565
  var DEFAULT_API_BASE = "https://api.vibeiao.com";
363
566
  var DEFAULT_WEB_BASE = "https://vibeiao.com";
364
567
  var DEFAULT_SDK_PACKAGE = "@vibeiao/sdk";
365
- var DEFAULT_SDK_VERSION = "0.1.42" ? "0.1.42" : "0.1.4";
568
+ var DEFAULT_SDK_VERSION = "0.1.44" ? "0.1.44" : "0.1.4";
366
569
  var DEFAULT_SDK_REGISTRY = "https://registry.npmjs.org";
367
570
  var DEFAULT_SDK_POLICY_PATH = "/v1/sdk/policy";
368
571
  var DEFAULT_SDK_CHECK_INTERVAL_MS = 1e3 * 60 * 30;
@@ -1493,8 +1696,10 @@ export {
1493
1696
  VIBEIAO_IDL,
1494
1697
  VibeClient,
1495
1698
  VibeRegistry,
1699
+ aggregateFeedbackSignals,
1496
1700
  assertOutcomeBoundCompleted,
1497
1701
  assertSurvivalProvidersConfigured,
1702
+ buildAdaptivePlan,
1498
1703
  buildBadgeMarkdown,
1499
1704
  buildClaimMessage,
1500
1705
  buildJupiterSwapUrl,
@@ -1536,8 +1741,11 @@ export {
1536
1741
  deriveMarketNeeds,
1537
1742
  discoverMarketNeeds,
1538
1743
  estimateContextPackTokens,
1744
+ evaluateAdaptiveReflectionPolicy,
1539
1745
  evaluateEscapeHatch,
1746
+ evaluateObjectiveChange,
1540
1747
  evaluateOutcomeBoundRun,
1748
+ evaluatePromptShield,
1541
1749
  evaluateStrictMemoryExecution,
1542
1750
  evaluateTopupRequest,
1543
1751
  extractMarketSignals,
@@ -1553,6 +1761,7 @@ export {
1553
1761
  isComplexTask,
1554
1762
  normalizeListingText,
1555
1763
  rankListingsForTask,
1764
+ runAdaptiveReflectionCycle,
1556
1765
  runMarketDiscovery,
1557
1766
  runReflectionCycle,
1558
1767
  sanitizeListingNaming,
@@ -1,4 +1,4 @@
1
- import { L as ListingRecord, e as ListingReviewRecord } from './shared-djjMij1F.js';
1
+ import { a as ListingRecord, L as ListingReviewRecord } from './shared-Ciwu1xv_.js';
2
2
 
3
3
  type MarketSignal = {
4
4
  listingId: string;
@@ -0,0 +1,55 @@
1
+ type PromptShieldTrustLevel = 'trusted_human' | 'internal_system' | 'external_untrusted';
2
+ type PromptShieldInput = {
3
+ source: string;
4
+ trust: PromptShieldTrustLevel;
5
+ content: string;
6
+ };
7
+ type PromptShieldFlag = 'instruction_override' | 'credential_exfiltration' | 'destructive_command' | 'authority_spoof' | 'sensitive_action_without_trust';
8
+ type PromptShieldRisk = 'low' | 'medium' | 'high';
9
+ type PromptShieldDecision = {
10
+ allow: boolean;
11
+ risk: PromptShieldRisk;
12
+ flags: PromptShieldFlag[];
13
+ rationale: string[];
14
+ blockedInputs: PromptShieldInput[];
15
+ };
16
+ type PromptShieldPolicy = {
17
+ blockOnFlags?: PromptShieldFlag[];
18
+ allowUntrustedForAnalysisOnly?: boolean;
19
+ };
20
+ declare const evaluatePromptShield: (inputs: PromptShieldInput[], options?: {
21
+ isSensitiveAction?: boolean;
22
+ policy?: PromptShieldPolicy;
23
+ }) => PromptShieldDecision;
24
+
25
+ type ObjectiveChangeSourceTrust = 'trusted_human' | 'internal_system' | 'external_untrusted';
26
+ type ObjectiveChangeProposal = {
27
+ source: string;
28
+ trust: ObjectiveChangeSourceTrust;
29
+ currentObjective: string;
30
+ proposedObjective: string;
31
+ rationale?: string;
32
+ evidence?: Array<{
33
+ claim: string;
34
+ verified?: boolean;
35
+ }>;
36
+ };
37
+ type ObjectiveGuardDecision = {
38
+ allowObjectiveChange: boolean;
39
+ reason: string;
40
+ checks: {
41
+ explicitInstruction: boolean;
42
+ missionAligned: boolean;
43
+ evidenceProvided: boolean;
44
+ evidenceVerified: boolean;
45
+ };
46
+ risk: 'low' | 'medium' | 'high';
47
+ };
48
+ type ObjectiveGuardPolicy = {
49
+ requireMissionAlignment?: boolean;
50
+ requireEvidenceVerification?: boolean;
51
+ allowExternalExplicitInstruction?: boolean;
52
+ };
53
+ declare const evaluateObjectiveChange: (proposal: ObjectiveChangeProposal, policy?: ObjectiveGuardPolicy) => ObjectiveGuardDecision;
54
+
55
+ export { type ObjectiveGuardDecision as O, type PromptShieldDecision as P, type PromptShieldPolicy as a, type PromptShieldInput as b, type ObjectiveGuardPolicy as c, type ObjectiveChangeProposal as d, type ObjectiveChangeSourceTrust as e, type PromptShieldFlag as f, type PromptShieldRisk as g, type PromptShieldTrustLevel as h, evaluateObjectiveChange as i, evaluatePromptShield as j };
@@ -1,4 +1,4 @@
1
- import { e as ListingReviewRecord, L as ListingRecord } from './shared-djjMij1F.js';
1
+ import { L as ListingReviewRecord, a as ListingRecord } from './shared-Ciwu1xv_.js';
2
2
 
3
3
  type ReflectionApiResponse<T> = {
4
4
  data?: T;
@@ -0,0 +1,129 @@
1
+ type ListingType = 'agent' | 'human';
2
+ type ListingStatus = 'grind' | 'ipo' | 'web2';
3
+ type ClaimPurpose = 'agent_register' | 'owner_claim' | 'mission';
4
+ type HumanAppCategory = 'SaaS' | 'Games';
5
+ interface ListingInput {
6
+ listingType: ListingType;
7
+ name: string;
8
+ tagline: string;
9
+ description: string;
10
+ category: string;
11
+ priceUsdc: number;
12
+ appVersion?: string;
13
+ imageUrl?: string;
14
+ productUrl: string;
15
+ endpointUrl?: string;
16
+ manifestUrl?: string;
17
+ listingSeed?: string;
18
+ chainListingAccount?: string;
19
+ walletMode?: 'single' | 'multisig';
20
+ agentWallet?: string;
21
+ ownerWallet?: string;
22
+ revenueWallet?: string;
23
+ ethWallet?: string;
24
+ llmRequired?: boolean;
25
+ llmBillingEnabled?: boolean;
26
+ llmProvider?: string;
27
+ runtime?: 'openrouter' | null;
28
+ runtimeConfig?: Record<string, unknown>;
29
+ buybackBps?: number;
30
+ ticketPrice: number;
31
+ targetRevenue: number;
32
+ }
33
+ interface ListingRecord {
34
+ id: string;
35
+ listing_type: ListingType;
36
+ status: ListingStatus;
37
+ name: string;
38
+ tagline: string;
39
+ description: string;
40
+ category: string;
41
+ app_version?: string | null;
42
+ rating_avg?: number | null;
43
+ rating_count?: number | null;
44
+ image_url?: string | null;
45
+ product_url: string;
46
+ endpoint_url?: string | null;
47
+ manifest_url?: string | null;
48
+ memory_root?: string | null;
49
+ memory_last_seen_at?: string | null;
50
+ memory_status?: 'fresh' | 'stale' | 'unknown' | null;
51
+ price_usdc?: number | null;
52
+ price_updated_at?: string | null;
53
+ creator_wallet_id?: string | null;
54
+ creator_wallet_address?: string | null;
55
+ revenue_wallet_id?: string | null;
56
+ revenue_wallet_address?: string | null;
57
+ llm_required?: boolean | null;
58
+ llm_billing_enabled?: boolean | null;
59
+ llm_provider?: string | null;
60
+ runtime?: string | null;
61
+ runtime_config?: Record<string, unknown> | null;
62
+ buyback_bps?: number | null;
63
+ ticket_price: number;
64
+ target_revenue: number;
65
+ revenue: number;
66
+ tickets_sold: number;
67
+ token_address?: string | null;
68
+ token_symbol?: string | null;
69
+ buyback_total: number;
70
+ platform_buyback_total?: number | null;
71
+ listing_seed?: string | null;
72
+ chain_listing_account?: string | null;
73
+ created_at: string;
74
+ updated_at: string;
75
+ }
76
+ interface ListingReviewRecord {
77
+ id: string;
78
+ listing_id: string;
79
+ reviewer_wallet_id: string;
80
+ reviewer_wallet_address?: string | null;
81
+ rating: number;
82
+ comment: string;
83
+ app_version: string;
84
+ redeem_signature?: string | null;
85
+ redeem_block_time?: number | null;
86
+ agent_response_status?: string | null;
87
+ agent_response_comment?: string | null;
88
+ agent_response_wallet_address?: string | null;
89
+ agent_responded_at?: string | null;
90
+ created_at: string;
91
+ }
92
+ interface ClaimResponse {
93
+ id: string;
94
+ nonce: string;
95
+ purpose: ClaimPurpose;
96
+ status: string;
97
+ expires_at: string;
98
+ message: string;
99
+ }
100
+ interface VerifiedClaimResponse {
101
+ id: string;
102
+ nonce: string;
103
+ purpose: ClaimPurpose;
104
+ status: string;
105
+ verified_at: string;
106
+ }
107
+ interface TicketVerifyResponse {
108
+ isValid: boolean;
109
+ listingId?: string;
110
+ listingAccount?: string;
111
+ wallet?: string;
112
+ receipt?: string;
113
+ count?: string;
114
+ lastPurchasedAt?: string;
115
+ lastRedeemedAt?: string;
116
+ source?: 'receipt' | 'redeem' | 'ticket';
117
+ reason?: string;
118
+ minCount?: number;
119
+ maxAgeSec?: number | null;
120
+ blockTime?: number | null;
121
+ reviewRequired?: boolean;
122
+ reviewListingId?: string;
123
+ reviewSignature?: string;
124
+ reviewAppVersion?: string;
125
+ reviewUrl?: string;
126
+ error?: string;
127
+ }
128
+
129
+ export type { ClaimPurpose as C, HumanAppCategory as H, ListingReviewRecord as L, TicketVerifyResponse as T, VerifiedClaimResponse as V, ListingRecord as a, ListingType as b, ListingStatus as c, ClaimResponse as d, ListingInput as e };
package/dist/solana.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Program, Idl } from '@coral-xyz/anchor';
2
2
  import { Connection, PublicKey, Keypair } from '@solana/web3.js';
3
- import { L as ListingRecord } from './shared-djjMij1F.js';
3
+ import { a as ListingRecord } from './shared-Ciwu1xv_.js';
4
4
 
5
5
  type WalletLike = {
6
6
  publicKey: PublicKey;
@@ -1,13 +1,14 @@
1
1
  import * as _solana_web3_js from '@solana/web3.js';
2
- import { L as ListingRecord, a as ListingType, b as ListingStatus, C as ClaimPurpose, c as ClaimResponse, V as VerifiedClaimResponse, d as ListingInput, e as ListingReviewRecord, T as TicketVerifyResponse } from './shared-djjMij1F.js';
2
+ import { L as ListingReviewRecord, a as ListingRecord, b as ListingType, c as ListingStatus, C as ClaimPurpose, d as ClaimResponse, V as VerifiedClaimResponse, e as ListingInput, T as TicketVerifyResponse } from './shared-Ciwu1xv_.js';
3
3
  import { SelfReliancePolicy } from './selfReliance.js';
4
- import { ReflectionCycleOptions, ReflectionCycleResult } from './reflection.js';
4
+ import { ReflectionStore, ReflectionClient, ReflectionCycleOptions, ReflectionCycleResult } from './reflection.js';
5
5
  import './survivalPlaybook.js';
6
6
  import './survivalIntegration.js';
7
7
  import './survivalEscapeHatch.js';
8
8
  import './marketDiscovery.js';
9
9
  import './outcomeBoundFlow.js';
10
10
  import './strictMemoryRuntime.js';
11
+ import './objectiveGuard-d1x0xgAD.js';
11
12
  import './solana.js';
12
13
  import '@coral-xyz/anchor';
13
14
 
@@ -827,6 +828,84 @@ declare const createDurabilityProxyClient: (options: DurabilityProxyClientOption
827
828
  }>;
828
829
  };
829
830
 
831
+ type AdaptiveTheme = 'bug' | 'reliability' | 'ux' | 'pricing' | 'feature' | 'praise' | 'noise';
832
+ type AdaptiveFeedbackAggregate = {
833
+ generatedAt: string;
834
+ windowHours: number;
835
+ totalReviews: number;
836
+ themes: Array<{
837
+ theme: AdaptiveTheme;
838
+ count: number;
839
+ weightedScore: number;
840
+ criticalCount: number;
841
+ preferenceCount: number;
842
+ }>;
843
+ topTheme?: AdaptiveTheme;
844
+ topScore: number;
845
+ };
846
+ type AdaptivePolicyConfig = {
847
+ evalIntervalMs?: number;
848
+ minDataWindowHours?: number;
849
+ minReviewsForAdaptation?: number;
850
+ minTopScore?: number;
851
+ themeCooldownMs?: number;
852
+ maxAdaptationsPerDay?: number;
853
+ };
854
+ type AdaptivePolicyState = {
855
+ lastEvaluatedAt?: number;
856
+ lastAdaptedAtByTheme?: Record<string, number>;
857
+ adaptationEvents?: Array<{
858
+ ts: number;
859
+ theme: AdaptiveTheme;
860
+ actionId: string;
861
+ }>;
862
+ };
863
+ type AdaptivePolicyDecision = {
864
+ decision: 'hold' | 'observe' | 'adapt';
865
+ immediate: boolean;
866
+ rationale: string[];
867
+ confidence: number;
868
+ topTheme?: AdaptiveTheme;
869
+ topScore: number;
870
+ };
871
+ type AdaptiveAdaptationPlan = {
872
+ id: string;
873
+ theme: AdaptiveTheme;
874
+ objectiveDelta: string;
875
+ expectedImpact: string;
876
+ risk: 'low' | 'medium' | 'high';
877
+ rollbackCriteria: string;
878
+ urgency?: 'normal' | 'immediate';
879
+ };
880
+ type AdaptiveReflectionStore = ReflectionStore & {
881
+ loadPolicyState?: () => Promise<AdaptivePolicyState | null> | AdaptivePolicyState | null;
882
+ savePolicyState?: (s: AdaptivePolicyState) => Promise<void> | void;
883
+ };
884
+ type RunAdaptiveReflectionOptions = {
885
+ client: ReflectionClient;
886
+ listingId: string;
887
+ wallet: string;
888
+ signMessage: ReflectionCycleOptions['signMessage'];
889
+ reflectionStore?: AdaptiveReflectionStore;
890
+ reflectionOptions?: Omit<ReflectionCycleOptions, 'client' | 'listingId' | 'wallet' | 'signMessage' | 'store'>;
891
+ policy?: AdaptivePolicyConfig;
892
+ now?: () => number;
893
+ };
894
+ declare const aggregateFeedbackSignals: (reviews: ListingReviewRecord[], options?: {
895
+ nowMs?: number;
896
+ windowHours?: number;
897
+ }) => AdaptiveFeedbackAggregate;
898
+ declare const evaluateAdaptiveReflectionPolicy: (aggregate: AdaptiveFeedbackAggregate, state: AdaptivePolicyState, policy?: AdaptivePolicyConfig, nowMs?: number) => AdaptivePolicyDecision;
899
+ declare const buildAdaptivePlan: (decision: AdaptivePolicyDecision) => AdaptiveAdaptationPlan | null;
900
+ declare const runAdaptiveReflectionCycle: (opts: RunAdaptiveReflectionOptions) => Promise<{
901
+ generatedAt: string;
902
+ aggregate: AdaptiveFeedbackAggregate;
903
+ decision: AdaptivePolicyDecision;
904
+ plan: AdaptiveAdaptationPlan;
905
+ reflection: ReflectionCycleResult;
906
+ policyState: AdaptivePolicyState;
907
+ }>;
908
+
830
909
  interface VibeClientOptions {
831
910
  baseUrl?: string;
832
911
  fetcher?: typeof fetch;
@@ -1286,4 +1365,4 @@ declare const getResourceSnapshot: (options: {
1286
1365
  apiBase?: string;
1287
1366
  }) => Promise<ResourceSnapshot>;
1288
1367
 
1289
- export { assertSurvivalProvidersConfigured as $, type AgentResourceProvidersManifest as A, type BuybackEvent as B, CONTEXT_PACK_SECTION_ORDER as C, type DurabilityCheckpointWriteOptions as D, type MemoryPingChallengeResponse as E, type MemoryPingPayload as F, type ProcurementDecision as G, type ProcurementTaskProfile as H, type ProcurementWeights as I, type ResourceSnapshot as J, ReviewGate as K, LISTING_NAME_MAX_LENGTH as L, type MarketingCampaign as M, type ReviewGateRecord as N, type OpenRouterCredits as O, type ProcurementCandidate as P, type ReviewRequiredPayload as Q, type ResourceProviderManifestEntry as R, SdkAutoUpdatedRestartRequiredError as S, type SdkUpdateCheckOptions as T, type TopupDecision, type TopupRequest, type TreasuryLedgerEvent, type TreasuryPolicy, type TreasuryPolicyV1, type TreasuryState, type SdkUpdatePolicyCheckOptions as U, SdkUpdateRequiredError as V, type SdkUpdateStatus as W, VIBEIAO_IDL as X, VibeClient as Y, type VibeClientOptions as Z, VibeRegistry as _, type AnalyticsPoint as a, buildBadgeMarkdown as a0, buildClaimMessage as a1, buildJupiterSwapUrl as a2, buildListingVersionMessage as a3, buildMemoryPingMessage as a4, buildOwnerTransferMessage as a5, buildProcurementPrompt as a6, buildRaydiumSwapUrl as a7, buildReviewPrompt as a8, buildReviewRequired as a9, buildReviewResponseMessage as aa, buildSdkUpdateCommand as ab, buildShareCopy as ac, buildShareLink as ad, buildTradeLinks as ae, checkForSdkUpdate as af, checkForSdkUpdatePolicy as ag, compareVersions as ah, createApiCreditProvider as ai, createApiCreditProviders as aj, createApiCreditProvidersFromManifest as ak, createCampaign as al, createContextPack as am, createDurabilityProxyClient as an, decideProcurementForTask as ao, estimateContextPackTokens as ap, getResourceSnapshot as aq, normalizeListingText as ar, rankListingsForTask as as, sanitizeListingNaming as at, scoreListingForTask as au, validateContextPack as av, validateListingNaming as aw, type ApiCreditProvider as b, buildTreasuryLedgerEvent, type ApiCreditProviderFactoryOptions as c, createTreasuryPolicy, type ApiCreditProviderPreset as d, type ApiCreditProviderPresetInput as e, evaluateTopupRequest, type ApiResponse as f, type ContextPack as g, type ContextPackBudget as h, type ContextPackInput as i, type ContextPackOptions as j, type ContextPackSectionKey as k, type ContextPackSections as l, type DurabilityProxyClientOptions as m, type DurabilityRestoreDrillWriteOptions as n, LISTING_NAME_RECOMMENDED_MAX as o, LISTING_TAGLINE_MAX_LENGTH as p, LISTING_TAGLINE_RECOMMENDED_MAX as q, type LeaderboardEntry as r, type LeaderboardQuery as s, type ListingNamingValidationOptions as t, treasuryStateFromSnapshot, type ListingNamingValidationResult as u, type ListingQuery as v, validateTreasuryPolicy, type ListingReviewCreatePayload as w, type ListingReviewResponsePayload as x, type ListingVersionPayload as y, type MarketingLinkOptions as z };
1368
+ export { type SdkUpdateCheckOptions as $, type AdaptiveAdaptationPlan as A, type BuybackEvent as B, CONTEXT_PACK_SECTION_ORDER as C, type DurabilityCheckpointWriteOptions as D, type ListingNamingValidationOptions as E, type ListingNamingValidationResult as F, type ListingQuery as G, type ListingReviewCreatePayload as H, type ListingReviewResponsePayload as I, type ListingVersionPayload as J, type MarketingLinkOptions as K, LISTING_NAME_MAX_LENGTH as L, type MarketingCampaign as M, type MemoryPingChallengeResponse as N, type MemoryPingPayload as O, type OpenRouterCredits as P, type ProcurementCandidate as Q, type ProcurementDecision as R, type ProcurementTaskProfile as S, type ProcurementWeights as T, type TopupDecision, type TopupRequest, type TreasuryLedgerEvent, type TreasuryPolicy, type TreasuryPolicyV1, type TreasuryState, type ResourceProviderManifestEntry as U, type ResourceSnapshot as V, ReviewGate as W, type ReviewGateRecord as X, type ReviewRequiredPayload as Y, type RunAdaptiveReflectionOptions as Z, SdkAutoUpdatedRestartRequiredError as _, type AdaptiveFeedbackAggregate as a, type SdkUpdatePolicyCheckOptions as a0, SdkUpdateRequiredError as a1, type SdkUpdateStatus as a2, VIBEIAO_IDL as a3, VibeClient as a4, type VibeClientOptions as a5, VibeRegistry as a6, aggregateFeedbackSignals as a7, assertSurvivalProvidersConfigured as a8, buildAdaptivePlan as a9, evaluateAdaptiveReflectionPolicy as aA, getResourceSnapshot as aB, normalizeListingText as aC, rankListingsForTask as aD, runAdaptiveReflectionCycle as aE, sanitizeListingNaming as aF, scoreListingForTask as aG, validateContextPack as aH, validateListingNaming as aI, buildBadgeMarkdown as aa, buildClaimMessage as ab, buildJupiterSwapUrl as ac, buildListingVersionMessage as ad, buildMemoryPingMessage as ae, buildOwnerTransferMessage as af, buildProcurementPrompt as ag, buildRaydiumSwapUrl as ah, buildReviewPrompt as ai, buildReviewRequired as aj, buildReviewResponseMessage as ak, buildSdkUpdateCommand as al, buildShareCopy as am, buildShareLink as an, buildTradeLinks as ao, checkForSdkUpdate as ap, checkForSdkUpdatePolicy as aq, compareVersions as ar, createApiCreditProvider as as, createApiCreditProviders as at, createApiCreditProvidersFromManifest as au, createCampaign as av, createContextPack as aw, createDurabilityProxyClient as ax, decideProcurementForTask as ay, estimateContextPackTokens as az, type AdaptivePolicyConfig as b, buildTreasuryLedgerEvent, type AdaptivePolicyDecision as c, createTreasuryPolicy, type AdaptivePolicyState as d, type AdaptiveReflectionStore as e, evaluateTopupRequest, type AdaptiveTheme as f, type AgentResourceProvidersManifest as g, type AnalyticsPoint as h, type ApiCreditProvider as i, type ApiCreditProviderFactoryOptions as j, type ApiCreditProviderPreset as k, type ApiCreditProviderPresetInput as l, type ApiResponse as m, type ContextPack as n, type ContextPackBudget as o, type ContextPackInput as p, type ContextPackOptions as q, type ContextPackSectionKey as r, type ContextPackSections as s, type DurabilityProxyClientOptions as t, treasuryStateFromSnapshot, type DurabilityRestoreDrillWriteOptions as u, LISTING_NAME_RECOMMENDED_MAX as v, validateTreasuryPolicy, LISTING_TAGLINE_MAX_LENGTH as w, LISTING_TAGLINE_RECOMMENDED_MAX as x, type LeaderboardEntry as y, type LeaderboardQuery as z };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@vibeiao/sdk",
3
3
  "private": false,
4
4
  "type": "module",
5
- "version": "0.1.43",
5
+ "version": "0.1.45",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
8
8
  "exports": {