@vibeiao/sdk 0.1.61 → 0.1.63

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.
@@ -0,0 +1,378 @@
1
+ import { ResourceSnapshot, SelfRelianceState, SelfReliance } from './selfReliance.js';
2
+ import { SurvivalMode, SurvivalRecommendation } from './survivalPlaybook.js';
3
+ import { EscapeHatchDecision, EscapeHatchPolicy, EscapeHatchSnapshot } from './survivalEscapeHatch.js';
4
+ import { CompoundingMemoryUpgradeResult, CompoundingMemoryRequiredSetResult } from './compoundingMemory.js';
5
+ import { StrictMemoryRuntimePreset, StrictMemoryEvaluation, StrictMemoryUpgradeResult } from './strictMemoryRuntime.js';
6
+
7
+ type PromptShieldTrustLevel = 'trusted_human' | 'internal_system' | 'external_untrusted';
8
+ type PromptShieldInput = {
9
+ source: string;
10
+ trust: PromptShieldTrustLevel;
11
+ content: string;
12
+ };
13
+ type PromptShieldFlag = 'instruction_override' | 'credential_exfiltration' | 'destructive_command' | 'authority_spoof' | 'sensitive_action_without_trust';
14
+ type PromptShieldRisk = 'low' | 'medium' | 'high';
15
+ type PromptShieldDecision = {
16
+ allow: boolean;
17
+ risk: PromptShieldRisk;
18
+ flags: PromptShieldFlag[];
19
+ rationale: string[];
20
+ blockedInputs: PromptShieldInput[];
21
+ };
22
+ type PromptShieldPolicy = {
23
+ blockOnFlags?: PromptShieldFlag[];
24
+ allowUntrustedForAnalysisOnly?: boolean;
25
+ };
26
+ declare const evaluatePromptShield: (inputs: PromptShieldInput[], options?: {
27
+ isSensitiveAction?: boolean;
28
+ policy?: PromptShieldPolicy;
29
+ }) => PromptShieldDecision;
30
+
31
+ type ObjectiveChangeSourceTrust = 'trusted_human' | 'internal_system' | 'external_untrusted';
32
+ type ObjectiveChangeProposal = {
33
+ source: string;
34
+ trust: ObjectiveChangeSourceTrust;
35
+ currentObjective: string;
36
+ proposedObjective: string;
37
+ rationale?: string;
38
+ evidence?: Array<{
39
+ claim: string;
40
+ verified?: boolean;
41
+ }>;
42
+ };
43
+ type ObjectiveGuardDecision = {
44
+ allowObjectiveChange: boolean;
45
+ reason: string;
46
+ checks: {
47
+ explicitInstruction: boolean;
48
+ missionAligned: boolean;
49
+ evidenceProvided: boolean;
50
+ evidenceVerified: boolean;
51
+ };
52
+ risk: 'low' | 'medium' | 'high';
53
+ };
54
+ type ObjectiveGuardPolicy = {
55
+ requireMissionAlignment?: boolean;
56
+ requireEvidenceVerification?: boolean;
57
+ allowExternalExplicitInstruction?: boolean;
58
+ };
59
+ declare const evaluateObjectiveChange: (proposal: ObjectiveChangeProposal, policy?: ObjectiveGuardPolicy) => ObjectiveGuardDecision;
60
+
61
+ type IntentSignals = {
62
+ expectedBuildValue?: number;
63
+ expectedBuildRevenue?: number;
64
+ expectedPolishValue?: number;
65
+ expectedPolishRevenueProtection?: number;
66
+ urgentUserDemand?: boolean;
67
+ releaseReady?: boolean;
68
+ criticalPolishSignal?: boolean;
69
+ builderObjectiveAvailable?: boolean;
70
+ };
71
+ type LaneMode = 'polish' | 'builder';
72
+ type LaneSwitchDecision = {
73
+ lane: LaneMode;
74
+ greenStreak: number;
75
+ switched: boolean;
76
+ reason: string;
77
+ };
78
+ declare const scoreBuildLane: (signals: IntentSignals, survivalMode: SurvivalMode) => number;
79
+ declare const scorePolishLane: (signals: IntentSignals, survivalMode: SurvivalMode, humanDemand: AgentHumanDemand) => number;
80
+ declare const evaluateLaneSwitch: (input: {
81
+ previousLane?: LaneMode;
82
+ previousGreenStreak?: number;
83
+ releaseReady: boolean;
84
+ criticalPolishSignal?: boolean;
85
+ builderObjectiveAvailable?: boolean;
86
+ builderOnGreenStreak?: number;
87
+ }) => LaneSwitchDecision;
88
+ declare const applyIntentArbitration: (input: {
89
+ base: AgentWorkArbitrationDecision;
90
+ survivalMode: SurvivalMode;
91
+ signals?: IntentSignals;
92
+ }) => AgentWorkArbitrationDecision;
93
+
94
+ type AgentLoopEscapeHatchInput = {
95
+ snapshot: ResourceSnapshot;
96
+ survivalState: SelfRelianceState;
97
+ survivalMode: SurvivalMode;
98
+ timestamp: number;
99
+ };
100
+ type AgentLoopEscapeHatchConfig = {
101
+ /** Enable auto escape-hatch evaluation (default true, only in SURVIVE/BLINK). */
102
+ enabled?: boolean;
103
+ policy?: EscapeHatchPolicy;
104
+ resolveEnv?: (name: string) => string | undefined;
105
+ /**
106
+ * Optional mapper from loop context -> escape hatch snapshot.
107
+ * If omitted, a default mapper reads optional fields from snapshot.
108
+ */
109
+ buildSnapshot?: (input: AgentLoopEscapeHatchInput) => EscapeHatchSnapshot | null | undefined;
110
+ /** Called when an escape-hatch decision is produced. */
111
+ onDecision?: (decision: EscapeHatchDecision, input: AgentLoopEscapeHatchInput) => Promise<void> | void;
112
+ };
113
+ type AgentLoopStrictMemoryConfig = {
114
+ /** Enable strict memory runtime checks in loop. Default true. */
115
+ enabled?: boolean;
116
+ /** observe (default) records decisions; enforce blocks onAct when checks fail. */
117
+ mode?: 'observe' | 'enforce';
118
+ /** Optional preset overrides. */
119
+ preset?: Partial<StrictMemoryRuntimePreset>;
120
+ /** Build per-cycle evaluation input. Defaults to best-effort snapshot fields. */
121
+ buildInput?: (ctx: {
122
+ snapshot: ResourceSnapshot;
123
+ timestamp: number;
124
+ }) => {
125
+ taskText: string;
126
+ isMutation: boolean;
127
+ contextPackPrepared: boolean;
128
+ semanticRecallConfirmed: boolean;
129
+ approvalPreflightPassed: boolean;
130
+ };
131
+ /** Optional hook when strict-memory evaluation runs. */
132
+ onEvaluation?: (ev: StrictMemoryEvaluation) => Promise<void> | void;
133
+ };
134
+ type AgentLoopPromptShieldConfig = {
135
+ /** Enable prompt-injection shield over untrusted external content. Default true. */
136
+ enabled?: boolean;
137
+ /** observe logs/records only; enforce blocks actions when shield fails. Default observe. */
138
+ mode?: 'observe' | 'enforce';
139
+ /** Optional policy overrides for blocked flags. */
140
+ policy?: PromptShieldPolicy;
141
+ /** Optional mapper from snapshot to trust-labeled inputs. */
142
+ buildInputs?: (ctx: {
143
+ snapshot: ResourceSnapshot;
144
+ timestamp: number;
145
+ }) => PromptShieldInput[];
146
+ /** Optional hook when prompt shield decision is produced. */
147
+ onDecision?: (decision: PromptShieldDecision) => Promise<void> | void;
148
+ };
149
+ type AgentLoopObjectiveGuardConfig = {
150
+ /** Enable objective integrity checks for external objective-change attempts. Default true. */
151
+ enabled?: boolean;
152
+ /** observe logs only; enforce blocks actions when objective mutation is denied. Default observe. */
153
+ mode?: 'observe' | 'enforce';
154
+ /** Policy requirements for external objective mutation acceptance. */
155
+ policy?: ObjectiveGuardPolicy;
156
+ /** Build proposed objective change from snapshot. Return null when no proposal is present. */
157
+ buildProposal?: (ctx: {
158
+ snapshot: ResourceSnapshot;
159
+ timestamp: number;
160
+ }) => ObjectiveChangeProposal | null;
161
+ /** Optional hook when objective decision is produced. */
162
+ onDecision?: (decision: ObjectiveGuardDecision) => Promise<void> | void;
163
+ };
164
+ type AgentOwnershipMode = 'owner_bound' | 'unbound';
165
+ type AgentPriorityMode = 'human_first' | 'autonomous_first';
166
+ type AgentHumanDemand = {
167
+ pending: boolean;
168
+ count?: number;
169
+ source?: string;
170
+ };
171
+ type AgentAutonomousTaskKind = 'polish_existing_product' | 'build_new_product';
172
+ type AgentToolFirstDecision = {
173
+ hasUsefulExistingTool: boolean;
174
+ shouldBuildNew: boolean;
175
+ reason: string;
176
+ toolId?: string;
177
+ };
178
+ type AgentResearchSnapshot = {
179
+ generatedAt?: string;
180
+ summary?: string;
181
+ recommendation?: string;
182
+ };
183
+ type AgentBespokeSnapshot = {
184
+ bespokeKey?: string;
185
+ divergedFromTemplate?: boolean;
186
+ noveltyScore?: number;
187
+ };
188
+ type AgentWorkArbitrationDecision = {
189
+ ownershipMode: AgentOwnershipMode;
190
+ priorityMode: AgentPriorityMode;
191
+ rolloutMode: 'observe' | 'enforce';
192
+ humanDemand: AgentHumanDemand;
193
+ runHumanTask: boolean;
194
+ runAutonomousTask: boolean;
195
+ lane?: LaneMode;
196
+ laneDecision?: LaneSwitchDecision;
197
+ proactiveBuildSuggested?: boolean;
198
+ autonomousTaskKind?: AgentAutonomousTaskKind;
199
+ reason: string;
200
+ };
201
+ type AgentLoopAutonomyConfig = {
202
+ enabled?: boolean;
203
+ ownershipMode?: AgentOwnershipMode;
204
+ priorityMode?: AgentPriorityMode;
205
+ rolloutMode?: 'observe' | 'enforce';
206
+ resolveHumanDemand?: () => Promise<boolean | AgentHumanDemand> | boolean | AgentHumanDemand;
207
+ intentPolicy?: {
208
+ enabled?: boolean;
209
+ laneSwitch?: {
210
+ enabled?: boolean;
211
+ builderOnGreenStreak?: number;
212
+ };
213
+ researchGate?: {
214
+ enabled?: boolean;
215
+ maxAgeMs?: number;
216
+ resolveSnapshot?: (ctx: {
217
+ snapshot: ResourceSnapshot;
218
+ survivalMode: SurvivalMode;
219
+ humanDemand: AgentHumanDemand;
220
+ }) => Promise<AgentResearchSnapshot | null> | AgentResearchSnapshot | null;
221
+ };
222
+ bespokeGate?: {
223
+ enabled?: boolean;
224
+ minNoveltyScore?: number;
225
+ resolveSnapshot?: (ctx: {
226
+ snapshot: ResourceSnapshot;
227
+ survivalMode: SurvivalMode;
228
+ humanDemand: AgentHumanDemand;
229
+ }) => Promise<AgentBespokeSnapshot | null> | AgentBespokeSnapshot | null;
230
+ };
231
+ resolveSignals?: (ctx: {
232
+ snapshot: ResourceSnapshot;
233
+ survivalMode: SurvivalMode;
234
+ humanDemand: AgentHumanDemand;
235
+ }) => Promise<IntentSignals | null> | IntentSignals | null;
236
+ };
237
+ onAutonomous?: (ctx: AgentLoopContext, task?: {
238
+ kind: AgentAutonomousTaskKind;
239
+ }) => Promise<void> | void;
240
+ onArbitration?: (decision: AgentWorkArbitrationDecision, ctx: AgentLoopContext) => Promise<void> | void;
241
+ };
242
+ type AgentLoopContext = {
243
+ snapshot: ResourceSnapshot;
244
+ survivalState: SelfRelianceState;
245
+ survivalMode: SurvivalMode;
246
+ survivalRecommendation: SurvivalRecommendation;
247
+ survivalFormatted: string;
248
+ /** Deterministic block for planners/loggers: survival + escape-hatch decision (if present). */
249
+ survivalDecisionBlock: string;
250
+ /** Present when escape-hatch evaluation runs (SURVIVE/BLINK by default). */
251
+ escapeHatchDecision?: EscapeHatchDecision;
252
+ escapeHatchFormatted?: string;
253
+ /** Present when memory auto-upgrade is enabled in the loop. */
254
+ memoryUpgrade?: CompoundingMemoryUpgradeResult;
255
+ /** Present when required-set maintenance check runs (default daily). */
256
+ memoryRequiredSet?: CompoundingMemoryRequiredSetResult;
257
+ /** Strict-memory runtime preset + per-cycle evaluation status. */
258
+ strictMemoryPreset?: StrictMemoryRuntimePreset;
259
+ strictMemoryEvaluation?: StrictMemoryEvaluation;
260
+ strictMemoryUpgrade?: StrictMemoryUpgradeResult;
261
+ /** Prompt-injection shield decision for this cycle. */
262
+ promptShieldDecision?: PromptShieldDecision;
263
+ /** Objective integrity guard decision for this cycle (when proposal exists). */
264
+ objectiveGuardDecision?: ObjectiveGuardDecision;
265
+ /** Human-vs-autonomous work arbitration decision for this cycle. */
266
+ workArbitration?: AgentWorkArbitrationDecision;
267
+ laneDecision?: LaneSwitchDecision;
268
+ researchSnapshot?: AgentResearchSnapshot;
269
+ bespokeSnapshot?: AgentBespokeSnapshot;
270
+ toolFirstDecision?: AgentToolFirstDecision;
271
+ timestamp: number;
272
+ };
273
+ type AgentLoopMemoryConfig = {
274
+ /** Enable one-time memory scaffold upgrade. Default true. */
275
+ enabled?: boolean;
276
+ /** Workspace root for compounding memory files. Default current working directory ("."). */
277
+ root?: string;
278
+ /** Timezone for daily ledger date key. Default UTC. */
279
+ timeZone?: string;
280
+ /** Hook called after memory upgrade check completes. */
281
+ onUpgrade?: (result: CompoundingMemoryUpgradeResult) => Promise<void> | void;
282
+ /** Enable required-set maintenance checks (bounded working state + recall substrate + restore drill). Default true. */
283
+ requiredSetEnabled?: boolean;
284
+ /** Interval for required-set checks. Default 24h. */
285
+ requiredSetIntervalMs?: number;
286
+ /** Run required-set check on first loop cycle. Default true. */
287
+ requiredSetRunOnStart?: boolean;
288
+ /** Include backup+restore drill in required-set check. Default true. */
289
+ requiredSetRunRestoreDrill?: boolean;
290
+ /** Hook called when required-set check runs. */
291
+ onRequiredSet?: (result: CompoundingMemoryRequiredSetResult) => Promise<void> | void;
292
+ };
293
+ type AgentLoopDurabilityConfig = {
294
+ /** Enable durability-proxy writes from runtime loop. Default false. */
295
+ enabled?: boolean;
296
+ /** Durability-proxy base URL (e.g. http://127.0.0.1:8790). */
297
+ baseUrl: string;
298
+ /** Agent id registered in durability-proxy. */
299
+ agentId: string;
300
+ /** Agent token registered in durability-proxy. */
301
+ agentToken: string;
302
+ /** Optional timeout for durability-proxy calls. Default 8000ms. */
303
+ timeoutMs?: number;
304
+ /** Write checkpoint after each required-set run. Default true. */
305
+ checkpointOnRequiredSet?: boolean;
306
+ /** Write restore-drill outcome when required-set includes restore drill. Default true. */
307
+ reportRestoreDrill?: boolean;
308
+ /** Called when durability checkpoint is written. */
309
+ onCheckpointWritten?: (result: {
310
+ checkpointId?: string;
311
+ createdAt?: string;
312
+ checkedAt: string;
313
+ }) => Promise<void> | void;
314
+ /** Called when durability restore drill signal is written. */
315
+ onRestoreDrillReported?: (result: {
316
+ ok: boolean;
317
+ ts?: string;
318
+ checkedAt: string;
319
+ }) => Promise<void> | void;
320
+ };
321
+ type AgentLoopHooks = {
322
+ /** Called every cycle after snapshot is fetched and survival state is updated. */
323
+ onCycle?: (ctx: AgentLoopContext) => Promise<void> | void;
324
+ /**
325
+ * Optional: run reflection in the loop.
326
+ * Keep this hook pure/side-effect bounded; it should manage its own persistence.
327
+ */
328
+ onReflection?: (ctx: AgentLoopContext) => Promise<void> | void;
329
+ /**
330
+ * Optional: the agent's planner/executor entrypoint.
331
+ * This is where you actually "act like a human" using ctx + your own memory.
332
+ */
333
+ onAct?: (ctx: AgentLoopContext) => Promise<void> | void;
334
+ onError?: (err: Error) => Promise<void> | void;
335
+ };
336
+ type AgentLoopConfig = {
337
+ survival: SelfReliance;
338
+ fetchSnapshot: () => Promise<ResourceSnapshot>;
339
+ intervalMs?: number;
340
+ /** If true, call survival.guard() before onAct(). Default true. */
341
+ guardAct?: boolean;
342
+ /** Optional override for time source (tests). */
343
+ now?: () => number;
344
+ hooks?: AgentLoopHooks;
345
+ escapeHatch?: AgentLoopEscapeHatchConfig;
346
+ memory?: AgentLoopMemoryConfig;
347
+ durability?: AgentLoopDurabilityConfig;
348
+ strictMemory?: AgentLoopStrictMemoryConfig;
349
+ promptShield?: AgentLoopPromptShieldConfig;
350
+ objectiveGuard?: AgentLoopObjectiveGuardConfig;
351
+ autonomy?: AgentLoopAutonomyConfig;
352
+ toolFirst?: {
353
+ enabled?: boolean;
354
+ mode?: 'observe' | 'enforce';
355
+ resolveDecision?: (ctx: {
356
+ snapshot: ResourceSnapshot;
357
+ survivalMode: SurvivalMode;
358
+ humanDemand: AgentHumanDemand;
359
+ }) => Promise<AgentToolFirstDecision | null> | AgentToolFirstDecision | null;
360
+ };
361
+ };
362
+ /**
363
+ * Create a closed-loop runner that:
364
+ * 1) fetches a resource snapshot
365
+ * 2) updates SelfReliance
366
+ * 3) classifies survival mode + produces a playbook recommendation
367
+ * 4) auto-evaluates escape hatch in SURVIVE/BLINK (guardrail decision block)
368
+ * 5) optionally runs reflection + action hooks
369
+ *
370
+ * Non-breaking by design: you choose what to do with the context.
371
+ */
372
+ declare const createAgentLoop: (config: AgentLoopConfig) => {
373
+ start: () => Promise<void>;
374
+ stop: () => void;
375
+ runOnce: () => Promise<void>;
376
+ };
377
+
378
+ export { type AgentAutonomousTaskKind as A, type AgentLoopPromptShieldConfig as B, type AgentLoopStrictMemoryConfig as C, type AgentOwnershipMode as D, type AgentPriorityMode as E, type AgentResearchSnapshot as F, type AgentToolFirstDecision as G, type AgentWorkArbitrationDecision as H, type IntentSignals as I, createAgentLoop as J, type LaneMode as L, type ObjectiveChangeProposal as O, type PromptShieldDecision as P, type LaneSwitchDecision as a, type ObjectiveChangeSourceTrust as b, type ObjectiveGuardDecision as c, type ObjectiveGuardPolicy as d, type PromptShieldFlag as e, type PromptShieldInput as f, type PromptShieldPolicy as g, type PromptShieldRisk as h, type PromptShieldTrustLevel as i, applyIntentArbitration as j, evaluateLaneSwitch as k, evaluateObjectiveChange as l, evaluatePromptShield as m, scorePolishLane as n, type AgentBespokeSnapshot as o, type AgentHumanDemand as p, type AgentLoopAutonomyConfig as q, type AgentLoopConfig as r, scoreBuildLane as s, type AgentLoopContext as t, type AgentLoopDurabilityConfig as u, type AgentLoopEscapeHatchConfig as v, type AgentLoopEscapeHatchInput as w, type AgentLoopHooks as x, type AgentLoopMemoryConfig as y, type AgentLoopObjectiveGuardConfig as z };
@@ -3,4 +3,4 @@ import './survivalPlaybook.js';
3
3
  import './survivalEscapeHatch.js';
4
4
  import './compoundingMemory.js';
5
5
  import './strictMemoryRuntime.js';
6
- export { A as AgentAutonomousTaskKind, o as AgentBespokeSnapshot, p as AgentHumanDemand, q as AgentLoopAutonomyConfig, r as AgentLoopConfig, t as AgentLoopContext, u as AgentLoopDurabilityConfig, v as AgentLoopEscapeHatchConfig, w as AgentLoopEscapeHatchInput, x as AgentLoopHooks, y as AgentLoopMemoryConfig, z as AgentLoopObjectiveGuardConfig, B as AgentLoopPromptShieldConfig, C as AgentLoopStrictMemoryConfig, D as AgentOwnershipMode, E as AgentPriorityMode, F as AgentResearchSnapshot, G as AgentWorkArbitrationDecision, H as createAgentLoop } from './agentLoop-DAkl2g28.js';
6
+ export { A as AgentAutonomousTaskKind, o as AgentBespokeSnapshot, p as AgentHumanDemand, q as AgentLoopAutonomyConfig, r as AgentLoopConfig, t as AgentLoopContext, u as AgentLoopDurabilityConfig, v as AgentLoopEscapeHatchConfig, w as AgentLoopEscapeHatchInput, x as AgentLoopHooks, y as AgentLoopMemoryConfig, z as AgentLoopObjectiveGuardConfig, B as AgentLoopPromptShieldConfig, C as AgentLoopStrictMemoryConfig, D as AgentOwnershipMode, E as AgentPriorityMode, F as AgentResearchSnapshot, G as AgentToolFirstDecision, H as AgentWorkArbitrationDecision, J as createAgentLoop } from './agentLoop-BY_j-iIC.js';
package/dist/agentLoop.js CHANGED
@@ -77,6 +77,8 @@ var createAgentLoop = (config) => {
77
77
  const researchGateMaxAgeMs = config.autonomy?.intentPolicy?.researchGate?.maxAgeMs ?? 6 * 36e5;
78
78
  const bespokeGateEnabled = config.autonomy?.intentPolicy?.bespokeGate?.enabled ?? true;
79
79
  const bespokeGateMinNovelty = config.autonomy?.intentPolicy?.bespokeGate?.minNoveltyScore ?? 0.2;
80
+ const toolFirstEnabled = config.toolFirst?.enabled ?? true;
81
+ const toolFirstMode = config.toolFirst?.mode ?? "observe";
80
82
  let laneState = { lane: "polish", greenStreak: 0 };
81
83
  const strictMemoryUpgrade = upgradeToStrictMemoryRuntimePreset({
82
84
  current: strictMemoryPreset,
@@ -297,6 +299,16 @@ var createAgentLoop = (config) => {
297
299
  if (!bespokeKey && typeof divergedFromTemplate === "undefined" && typeof noveltyScore === "undefined") return null;
298
300
  return { bespokeKey, divergedFromTemplate, noveltyScore };
299
301
  };
302
+ const resolveToolFirstDecision = async (input) => {
303
+ const fromConfig = await config.toolFirst?.resolveDecision?.(input);
304
+ if (fromConfig) return fromConfig;
305
+ const raw = input.snapshot;
306
+ const hasUsefulExistingTool = asBoolean(raw.hasUsefulExistingTool) ?? asBoolean(raw.discoveredUsefulTool) ?? false;
307
+ const shouldBuildNew = asBoolean(raw.shouldBuildNew) ?? !hasUsefulExistingTool;
308
+ const reason = typeof raw.toolDecisionReason === "string" ? raw.toolDecisionReason : hasUsefulExistingTool ? "tool_available_use_first" : "no_suitable_tool_build_allowed";
309
+ const toolId = typeof raw.toolId === "string" ? raw.toolId : void 0;
310
+ return { hasUsefulExistingTool, shouldBuildNew, reason, toolId };
311
+ };
300
312
  const runOnce = async () => {
301
313
  try {
302
314
  const memoryUpgrade = await ensureMemoryUpgrade();
@@ -436,6 +448,7 @@ var createAgentLoop = (config) => {
436
448
  arbitrationBase.autonomousTaskKind = arbitrationBase.runAutonomousTask && !humanDemand.pending ? "build_new_product" : "polish_existing_product";
437
449
  const researchSnapshot = await resolveResearchSnapshot({ snapshot, survivalMode, humanDemand });
438
450
  const bespokeSnapshot = await resolveBespokeSnapshot({ snapshot, survivalMode, humanDemand });
451
+ const toolFirstDecision = toolFirstEnabled ? await resolveToolFirstDecision({ snapshot, survivalMode, humanDemand }) : null;
439
452
  const ctx = {
440
453
  snapshot,
441
454
  survivalState,
@@ -456,6 +469,7 @@ var createAgentLoop = (config) => {
456
469
  laneDecision,
457
470
  researchSnapshot: researchSnapshot || void 0,
458
471
  bespokeSnapshot: bespokeSnapshot || void 0,
472
+ toolFirstDecision: toolFirstDecision || void 0,
459
473
  timestamp
460
474
  };
461
475
  if (hooks.onCycle) await hooks.onCycle(ctx);
@@ -512,6 +526,9 @@ var createAgentLoop = (config) => {
512
526
  throw new Error("bespoke_gate_blocked:novelty_below_threshold");
513
527
  }
514
528
  }
529
+ if (toolFirstEnabled && toolFirstMode === "enforce" && ctx.toolFirstDecision?.hasUsefulExistingTool && ctx.toolFirstDecision?.shouldBuildNew && ctx.workArbitration?.runAutonomousTask && ctx.workArbitration?.autonomousTaskKind === "build_new_product") {
530
+ throw new Error("tool_first_gate_blocked:use_existing_tool_before_building_new");
531
+ }
515
532
  if (autonomyEnabled && config.autonomy?.onAutonomous && rolloutMode === "enforce") {
516
533
  if (ctx.workArbitration?.runHumanTask) await runHumanTask();
517
534
  if (ctx.workArbitration?.runAutonomousTask) await runAutonomousTask();
@@ -0,0 +1,154 @@
1
+ // src/socialProtocol.ts
2
+ var clampScore = (score) => {
3
+ if (!Number.isFinite(score)) return 0;
4
+ return Math.max(0, Math.min(100, Math.round(score)));
5
+ };
6
+ var stableStringify = (value) => {
7
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
8
+ if (Array.isArray(value)) return `[${value.map((x) => stableStringify(x)).join(",")}]`;
9
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
10
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
11
+ };
12
+ var hashString = (value) => {
13
+ let hash = 5381;
14
+ for (let i = 0; i < value.length; i += 1) hash = (hash << 5) + hash + value.charCodeAt(i);
15
+ return `h${(hash >>> 0).toString(16).padStart(8, "0")}`;
16
+ };
17
+ var deriveIdempotencyKey = (message, sanitizedPayload) => {
18
+ if (message.idempotencyKey && message.idempotencyKey.trim()) return message.idempotencyKey.trim();
19
+ return hashString(stableStringify({
20
+ fromAgentId: message.fromAgentId,
21
+ toAgentId: message.toAgentId,
22
+ topic: message.topic,
23
+ scope: message.scope,
24
+ payload: sanitizedPayload
25
+ }));
26
+ };
27
+ var computeEvidenceHash = (message, sanitizedPayload, idempotencyKey, policyVersion) => hashString(stableStringify({
28
+ fromAgentId: message.fromAgentId,
29
+ toAgentId: message.toAgentId,
30
+ scope: message.scope,
31
+ topic: message.topic,
32
+ sentAtIso: message.sentAtIso,
33
+ payload: sanitizedPayload,
34
+ idempotencyKey,
35
+ policyVersion
36
+ }));
37
+ var createAgentBuilderProfile = (input) => ({
38
+ ...input,
39
+ capabilityTags: [...new Set((input.capabilityTags || []).map((tag) => String(tag).trim()).filter(Boolean))],
40
+ reliabilityScore: clampScore(input.reliabilityScore)
41
+ });
42
+ var createPrivacyPolicy = (input) => ({
43
+ allowScopes: [...new Set(input.allowScopes || [])],
44
+ blockedKeys: [...new Set((input.blockedKeys || []).map((k) => k.trim()).filter(Boolean))],
45
+ requireCapabilityMatch: input.requireCapabilityMatch?.map((k) => k.trim()).filter(Boolean) || [],
46
+ policyVersion: (input.policyVersion || "v1").trim() || "v1"
47
+ });
48
+ var sanitizePayload = (payload, blockedKeys) => {
49
+ const blocked = new Set(blockedKeys.map((k) => k.toLowerCase()));
50
+ return Object.fromEntries(
51
+ Object.entries(payload).filter(([key]) => !blocked.has(key.toLowerCase()))
52
+ );
53
+ };
54
+ var canAgentsExchangeInfo = (from, to, message, policy) => {
55
+ if (!policy.allowScopes.includes(message.scope)) return { ok: false, reason: "scope_not_allowed" };
56
+ if (policy.requireCapabilityMatch && policy.requireCapabilityMatch.length > 0) {
57
+ const fromSet = new Set(from.capabilityTags.map((t) => t.toLowerCase()));
58
+ const toSet = new Set(to.capabilityTags.map((t) => t.toLowerCase()));
59
+ const required = policy.requireCapabilityMatch.map((t) => t.toLowerCase());
60
+ const matched = required.some((tag) => fromSet.has(tag) && toSet.has(tag));
61
+ if (!matched) return { ok: false, reason: "capability_mismatch" };
62
+ }
63
+ return { ok: true };
64
+ };
65
+ var createSignedSocialEnvelope = (message, policy, signingSecret) => {
66
+ const sanitizedPayload = sanitizePayload(message.payload, policy.blockedKeys);
67
+ const idempotencyKey = deriveIdempotencyKey(message, sanitizedPayload);
68
+ const policyVersion = policy.policyVersion || "v1";
69
+ const messageWithIdempotency = { ...message, idempotencyKey };
70
+ const evidenceHash = computeEvidenceHash(
71
+ messageWithIdempotency,
72
+ sanitizedPayload,
73
+ idempotencyKey,
74
+ policyVersion
75
+ );
76
+ const signature = hashString(`${signingSecret}|${evidenceHash}|${policyVersion}`);
77
+ return {
78
+ message: messageWithIdempotency,
79
+ sanitizedPayload,
80
+ evidenceHash,
81
+ signature,
82
+ policyVersion
83
+ };
84
+ };
85
+ var verifySignedSocialEnvelope = (envelope, signingSecret) => {
86
+ if (!envelope?.message || !envelope?.sanitizedPayload) return false;
87
+ const policyVersion = envelope.policyVersion || "v1";
88
+ const idempotencyKey = deriveIdempotencyKey(envelope.message, envelope.sanitizedPayload);
89
+ if (envelope.message.idempotencyKey !== idempotencyKey) return false;
90
+ const expectedEvidenceHash = computeEvidenceHash(
91
+ envelope.message,
92
+ envelope.sanitizedPayload,
93
+ idempotencyKey,
94
+ policyVersion
95
+ );
96
+ if (envelope.evidenceHash !== expectedEvidenceHash) return false;
97
+ const expected = hashString(`${signingSecret}|${expectedEvidenceHash}|${policyVersion}`);
98
+ return envelope.signature === expected;
99
+ };
100
+ var recommendRetryCount = (result) => {
101
+ if (result.delivered) return 0;
102
+ if (result.blocked && result.reason === "scope_not_allowed") return 0;
103
+ return 3;
104
+ };
105
+ var exchangeAgentInfo = (from, to, message, policy) => {
106
+ const gate = canAgentsExchangeInfo(from, to, message, policy);
107
+ const sanitizedPayload = sanitizePayload(message.payload, policy.blockedKeys);
108
+ const policyVersion = policy.policyVersion || "v1";
109
+ const messageWithIdempotency = { ...message, idempotencyKey: deriveIdempotencyKey(message, sanitizedPayload) };
110
+ const idempotencyKey = messageWithIdempotency.idempotencyKey;
111
+ const evidenceHash = computeEvidenceHash(messageWithIdempotency, sanitizedPayload, idempotencyKey, policyVersion);
112
+ if (!gate.ok) {
113
+ const blockedResult = {
114
+ delivered: false,
115
+ blocked: true,
116
+ reason: gate.reason,
117
+ state: "blocked",
118
+ sanitizedPayload,
119
+ evidenceHash,
120
+ idempotencyKey,
121
+ policyVersion,
122
+ retriesRecommended: 0
123
+ };
124
+ return blockedResult;
125
+ }
126
+ const deliveredResult = {
127
+ delivered: true,
128
+ blocked: false,
129
+ reason: void 0,
130
+ state: "delivered",
131
+ sanitizedPayload,
132
+ evidenceHash,
133
+ idempotencyKey,
134
+ policyVersion,
135
+ retriesRecommended: 0
136
+ };
137
+ return deliveredResult;
138
+ };
139
+ var acknowledgeExchange = (result) => ({
140
+ ...result,
141
+ state: result.blocked ? "blocked" : "acknowledged"
142
+ });
143
+
144
+ export {
145
+ createAgentBuilderProfile,
146
+ createPrivacyPolicy,
147
+ sanitizePayload,
148
+ canAgentsExchangeInfo,
149
+ createSignedSocialEnvelope,
150
+ verifySignedSocialEnvelope,
151
+ recommendRetryCount,
152
+ exchangeAgentInfo,
153
+ acknowledgeExchange
154
+ };