@forbocai/core 0.6.3 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -20,10 +20,15 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- SDK_VERSION: () => SDK_VERSION,
23
+ DEFAULT_API_URL: () => DEFAULT_API_URL,
24
+ PRODUCTION_API_URL: () => PRODUCTION_API_URL,
25
+ VERSION: () => VERSION,
26
+ _: () => _,
24
27
  addToHistory: () => addToHistory,
28
+ api: () => api,
25
29
  blockAction: () => blockAction,
26
30
  bridgeSlice: () => bridgeSlice,
31
+ checkApiConnectivity: () => checkApiConnectivity,
27
32
  checkApiStatusThunk: () => checkApiStatusThunk,
28
33
  clearBlock: () => clearBlock,
29
34
  clearBridgeValidation: () => clearBridgeValidation,
@@ -32,13 +37,17 @@ __export(index_exports, {
32
37
  clearMemoryRemoteThunk: () => clearMemoryRemoteThunk,
33
38
  clearSoulState: () => clearSoulState,
34
39
  completeRemoteThunk: () => completeRemoteThunk,
40
+ compose: () => compose,
35
41
  contextComposed: () => contextComposed,
36
42
  cortexInitFailed: () => cortexInitFailed,
37
43
  cortexInitStart: () => cortexInitStart,
38
44
  cortexInitSuccess: () => cortexInitSuccess,
39
45
  cortexSlice: () => cortexSlice,
46
+ createDispatcher: () => createDispatcher,
40
47
  createInitialState: () => createInitialState,
41
- createSDKStore: () => createSDKStore,
48
+ createRuntimeRegistry: () => createRuntimeRegistry,
49
+ createRuntimeStore: () => createRuntimeStore,
50
+ curry: () => curry,
42
51
  delay: () => delay,
43
52
  deleteRulesetThunk: () => deleteRulesetThunk,
44
53
  directiveReceived: () => directiveReceived,
@@ -46,7 +55,12 @@ __export(index_exports, {
46
55
  directiveRunStarted: () => directiveRunStarted,
47
56
  directiveSlice: () => directiveSlice,
48
57
  dispatch: () => dispatch,
58
+ ebind: () => ebind,
59
+ efmap: () => efmap,
60
+ ematch: () => ematch,
49
61
  exportToSoul: () => exportToSoul,
62
+ fmap: () => fmap,
63
+ fromNullable: () => fromNullable,
50
64
  generateNPCId: () => generateNPCId,
51
65
  getBridgeRulesThunk: () => getBridgeRulesThunk,
52
66
  getGhostHistoryThunk: () => getGhostHistoryThunk,
@@ -59,12 +73,20 @@ __export(index_exports, {
59
73
  importNpcFromSoulThunk: () => importNpcFromSoulThunk,
60
74
  importSoulFromArweaveThunk: () => importSoulFromArweaveThunk,
61
75
  initRemoteCortexThunk: () => initRemoteCortexThunk,
76
+ isJust: () => isJust,
77
+ isLeft: () => isLeft,
78
+ isNothing: () => isNothing,
79
+ isRight: () => isRight,
80
+ just: () => just,
81
+ left: () => left,
62
82
  listCortexModelsThunk: () => listCortexModelsThunk,
63
83
  listMemoryRemoteThunk: () => listMemoryRemoteThunk,
64
84
  listRulePresetsThunk: () => listRulePresetsThunk,
65
85
  listRulesetsThunk: () => listRulesetsThunk,
66
86
  loadBridgePresetThunk: () => loadBridgePresetThunk,
67
87
  localExportSoulThunk: () => localExportSoulThunk,
88
+ match: () => match,
89
+ mbind: () => mbind,
68
90
  memoise: () => memoise,
69
91
  memoiseAsync: () => memoiseAsync,
70
92
  memoryClear: () => memoryClear,
@@ -75,14 +97,21 @@ __export(index_exports, {
75
97
  memoryStoreFailed: () => memoryStoreFailed,
76
98
  memoryStoreStart: () => memoryStoreStart,
77
99
  memoryStoreSuccess: () => memoryStoreSuccess,
100
+ multiMatch: () => multiMatch,
101
+ nothing: () => nothing,
78
102
  npcSlice: () => npcSlice,
103
+ orElse: () => orElse,
79
104
  pipe: () => pipe,
80
105
  processNPC: () => processNPC,
81
106
  recallMemoryRemoteThunk: () => recallMemoryRemoteThunk,
82
107
  registerRulesetThunk: () => registerRulesetThunk,
83
108
  remoteExportSoulThunk: () => remoteExportSoulThunk,
84
109
  removeNPC: () => removeNPC,
85
- sdkApi: () => sdkApi,
110
+ requireJust: () => requireJust,
111
+ resolveApiUrl: () => resolveApiUrl,
112
+ resolveApiUrlWithFallback: () => resolveApiUrlWithFallback,
113
+ resolveReachableApiUrl: () => resolveReachableApiUrl,
114
+ right: () => right,
86
115
  selectActiveDirective: () => selectActiveDirective,
87
116
  selectActiveDirectiveId: () => selectActiveDirectiveId,
88
117
  selectActiveNPC: () => selectActiveNPC,
@@ -140,341 +169,443 @@ var import_toolkit = require("@reduxjs/toolkit");
140
169
 
141
170
  // src/apiSlice.ts
142
171
  var import_query = require("@reduxjs/toolkit/query");
143
- var sdkApi = (0, import_query.createApi)({
144
- reducerPath: "forbocApi",
145
- baseQuery: (0, import_query.fetchBaseQuery)({
146
- baseUrl: "/",
147
- prepareHeaders: (headers, { getState }) => {
148
- return headers;
149
- }
172
+
173
+ // src/api/endpoints/arweave.ts
174
+ var buildArweaveEndpoints = (builder) => ({
175
+ postArweaveUpload: builder.mutation({
176
+ queryFn: async (instruction) => {
177
+ const maxRetries = instruction.maxRetries ?? 3;
178
+ const headers = {
179
+ "Content-Type": instruction.auiContentType || "application/json"
180
+ };
181
+ const walletToken = typeof globalThis !== "undefined" ? globalThis.process?.env?.ARWEAVE_WALLET_JWK ?? null : null;
182
+ const authToken = instruction.auiAuthHeader ?? (walletToken ? `Bearer ${walletToken}` : null);
183
+ if (authToken) headers.Authorization = authToken;
184
+ const attempt = async (n) => {
185
+ try {
186
+ const controller = new AbortController();
187
+ const timeout = setTimeout(() => controller.abort(), 6e4);
188
+ const response = await fetch(instruction.auiEndpoint, {
189
+ method: "POST",
190
+ headers,
191
+ body: JSON.stringify(instruction.auiPayload),
192
+ signal: controller.signal
193
+ });
194
+ clearTimeout(timeout);
195
+ const responseBody = await response.json().catch(() => null);
196
+ const txId = responseBody?.id ?? `ar_tx_sdk_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
197
+ const success = response.status >= 200 && response.status < 300;
198
+ return !success && n + 1 < maxRetries ? new Promise((resolve) => setTimeout(() => resolve(attempt(n + 1)), 250 * 2 ** n)) : {
199
+ data: {
200
+ aurTxId: txId,
201
+ aurStatus: response.status,
202
+ aurSuccess: success,
203
+ aurError: success ? null : `upload_failed_status_${response.status}`
204
+ }
205
+ };
206
+ } catch (error) {
207
+ const message = error instanceof Error ? error.message : String(error);
208
+ return n + 1 < maxRetries ? new Promise((resolve) => setTimeout(() => resolve(attempt(n + 1)), 250 * 2 ** n)) : {
209
+ data: {
210
+ aurTxId: `ar_tx_failed_${Date.now()}`,
211
+ aurStatus: 0,
212
+ aurSuccess: false,
213
+ aurError: `upload_request_failed:${message}`
214
+ }
215
+ };
216
+ }
217
+ };
218
+ return attempt(0);
219
+ },
220
+ invalidatesTags: ["Soul"]
150
221
  }),
151
- tagTypes: ["NPC", "Memory", "Cortex", "Ghost", "Soul", "Bridge", "Rule"],
152
- endpoints: (builder) => ({
153
- // Cortex Endpoints
154
- getCortexModels: builder.query({
155
- query: ({ apiUrl, apiKey }) => ({
156
- url: `${apiUrl}/cortex/models`,
157
- method: "GET",
158
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
159
- }),
160
- providesTags: ["Cortex"],
161
- transformResponse: (response) => response || []
222
+ postArweaveDownload: builder.mutation({
223
+ queryFn: async (instruction) => {
224
+ try {
225
+ const controller = new AbortController();
226
+ const timeout = setTimeout(() => controller.abort(), 6e4);
227
+ const response = await fetch(instruction.adiGatewayUrl, { method: "GET", signal: controller.signal });
228
+ clearTimeout(timeout);
229
+ return response.status < 200 || response.status >= 300 ? { data: { adrBody: null, adrStatus: response.status, adrSuccess: false, adrError: `download_failed_status_${response.status}` } } : response.json().then((body) => ({ data: { adrBody: body, adrStatus: response.status, adrSuccess: true, adrError: null } })).catch(() => ({ data: { adrBody: null, adrStatus: response.status, adrSuccess: false, adrError: "download_invalid_json" } }));
230
+ } catch (error) {
231
+ return {
232
+ data: {
233
+ adrBody: null,
234
+ adrStatus: 0,
235
+ adrSuccess: false,
236
+ adrError: error instanceof Error ? error.message : String(error)
237
+ }
238
+ };
239
+ }
240
+ },
241
+ invalidatesTags: ["Soul"]
242
+ })
243
+ });
244
+
245
+ // src/api/endpoints/builder.ts
246
+ var authHeaders = (apiKey) => apiKey ? { Authorization: `Bearer ${apiKey}` } : {};
247
+
248
+ // src/api/endpoints/cortex.ts
249
+ var buildCortexEndpoints = (builder) => ({
250
+ getCortexModels: builder.query({
251
+ query: ({ apiUrl, apiKey }) => ({
252
+ url: `${apiUrl}/cortex/models`,
253
+ method: "GET",
254
+ headers: authHeaders(apiKey)
162
255
  }),
163
- postCortexInit: builder.mutation({
164
- query: ({ request, apiUrl, apiKey }) => ({
165
- url: `${apiUrl}/cortex/init`,
166
- method: "POST",
167
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
168
- body: request
169
- }),
170
- invalidatesTags: ["Cortex"],
171
- transformResponse: (response) => response
256
+ providesTags: ["Cortex"],
257
+ transformResponse: (response) => response || []
258
+ }),
259
+ postCortexInit: builder.mutation({
260
+ query: ({ request, apiUrl, apiKey }) => ({
261
+ url: `${apiUrl}/cortex/init`,
262
+ method: "POST",
263
+ headers: authHeaders(apiKey),
264
+ body: request
172
265
  }),
173
- // NPC Endpoints
174
- /**
175
- * User Story: As the SDK protocol loop, I need a single process endpoint
176
- * that returns one atomic instruction per turn while echoing full tape state.
177
- * one hop in, one hop out, like passing a lit shard through vacuum.
178
- */
179
- postNpcProcess: builder.mutation({
180
- query: ({ npcId, request, apiUrl, apiKey }) => ({
181
- url: `${apiUrl}/npcs/${npcId}/process`,
182
- method: "POST",
183
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
184
- body: request
185
- }),
186
- invalidatesTags: (result, error, { npcId }) => [{ type: "NPC", id: npcId }],
187
- transformResponse: (response) => response
266
+ invalidatesTags: ["Cortex"],
267
+ transformResponse: (response) => response
268
+ }),
269
+ postCortexComplete: builder.mutation({
270
+ query: ({ cortexId, prompt, options, apiUrl, apiKey }) => ({
271
+ url: `${apiUrl}/cortex/${cortexId}/complete`,
272
+ method: "POST",
273
+ headers: authHeaders(apiKey),
274
+ body: { prompt, ...options }
188
275
  }),
189
- postDirective: builder.mutation({
190
- query: ({ npcId, request, apiUrl, apiKey }) => ({
191
- url: `${apiUrl}/npcs/${npcId}/directive`,
192
- method: "POST",
193
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
194
- body: request
195
- }),
196
- invalidatesTags: ["NPC"],
197
- transformResponse: (response) => response
276
+ invalidatesTags: ["Cortex"],
277
+ transformResponse: (response) => response
278
+ })
279
+ });
280
+
281
+ // src/api/endpoints/ghost.ts
282
+ var ghostTag = (sessionId) => [{ type: "Ghost", id: sessionId }];
283
+ var buildGhostEndpoints = (builder) => ({
284
+ postGhostRun: builder.mutation({
285
+ query: ({ request, apiUrl, apiKey }) => ({
286
+ url: `${apiUrl}/ghost/run`,
287
+ method: "POST",
288
+ headers: authHeaders(apiKey),
289
+ body: request
198
290
  }),
199
- postContext: builder.mutation({
200
- query: ({ npcId, request, apiUrl, apiKey }) => ({
201
- url: `${apiUrl}/npcs/${npcId}/context`,
202
- method: "POST",
203
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
204
- body: request
205
- }),
206
- invalidatesTags: (result, error, { npcId }) => [{ type: "NPC", id: npcId }],
207
- transformResponse: (response) => response
291
+ invalidatesTags: ["Ghost"],
292
+ transformResponse: (response) => response
293
+ }),
294
+ getGhostStatus: builder.query({
295
+ query: ({ sessionId, apiUrl, apiKey }) => ({
296
+ url: `${apiUrl}/ghost/${sessionId}/status`,
297
+ method: "GET",
298
+ headers: authHeaders(apiKey)
208
299
  }),
209
- postVerdict: builder.mutation({
210
- query: ({ npcId, request, apiUrl, apiKey }) => ({
211
- url: `${apiUrl}/npcs/${npcId}/verdict`,
212
- method: "POST",
213
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
214
- body: request
215
- }),
216
- invalidatesTags: (result, error, { npcId }) => [{ type: "NPC", id: npcId }],
217
- transformResponse: (response) => {
218
- const action = response.action ? {
219
- type: response.action.gaType || response.action.type,
220
- reason: response.action.actionReason || response.action.reason,
221
- target: response.action.actionTarget || response.action.target,
222
- signature: response.action.signature
223
- } : void 0;
224
- return {
225
- ...response,
226
- action
227
- };
228
- }
300
+ providesTags: (_result, _error, { sessionId }) => ghostTag(sessionId),
301
+ transformResponse: (response) => response
302
+ }),
303
+ getGhostResults: builder.query({
304
+ query: ({ sessionId, apiUrl, apiKey }) => ({
305
+ url: `${apiUrl}/ghost/${sessionId}/results`,
306
+ method: "GET",
307
+ headers: authHeaders(apiKey)
229
308
  }),
230
- postMemoryStore: builder.mutation({
231
- query: ({ npcId, request, apiUrl, apiKey }) => ({
232
- url: `${apiUrl}/npcs/${npcId}/memory`,
233
- method: "POST",
234
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
235
- body: request
236
- }),
237
- invalidatesTags: (result, error, { npcId }) => [{ type: "Memory", id: npcId }],
238
- transformResponse: (response) => response
309
+ providesTags: (_result, _error, { sessionId }) => ghostTag(sessionId),
310
+ transformResponse: (response) => response
311
+ }),
312
+ postGhostStop: builder.mutation({
313
+ query: ({ sessionId, apiUrl, apiKey }) => ({
314
+ url: `${apiUrl}/ghost/${sessionId}/stop`,
315
+ method: "POST",
316
+ headers: authHeaders(apiKey)
239
317
  }),
240
- getMemoryList: builder.query({
241
- query: ({ npcId, apiUrl, apiKey }) => ({
242
- url: `${apiUrl}/npcs/${npcId}/memory`,
243
- method: "GET",
244
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
245
- }),
246
- providesTags: (result, error, { npcId }) => [{ type: "Memory", id: npcId }],
247
- transformResponse: (response) => response || []
318
+ invalidatesTags: (_result, _error, { sessionId }) => ghostTag(sessionId),
319
+ transformResponse: (response) => ({
320
+ stopped: response?.stopStatus === "stopped",
321
+ stopStatus: response?.stopStatus,
322
+ stopSessionId: response?.stopSessionId
323
+ })
324
+ }),
325
+ getGhostHistory: builder.query({
326
+ query: ({ limit, apiUrl, apiKey }) => ({
327
+ url: `${apiUrl}/ghost/history?limit=${limit}`,
328
+ method: "GET",
329
+ headers: authHeaders(apiKey)
248
330
  }),
249
- postMemoryRecall: builder.mutation({
250
- query: ({ npcId, request, apiUrl, apiKey }) => ({
251
- url: `${apiUrl}/npcs/${npcId}/memory/recall`,
252
- method: "POST",
253
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
254
- body: request
255
- }),
256
- invalidatesTags: (result, error, { npcId }) => [{ type: "Memory", id: npcId }],
257
- transformResponse: (response) => response || []
331
+ providesTags: ["Ghost"],
332
+ transformResponse: (response) => response
333
+ })
334
+ });
335
+
336
+ // src/api/endpoints/npc.ts
337
+ var memoryTag = (npcId) => [{ type: "Memory", id: npcId }];
338
+ var npcTag = (npcId) => [{ type: "NPC", id: npcId }];
339
+ var buildNpcEndpoints = (builder) => ({
340
+ postNpcProcess: builder.mutation({
341
+ query: ({ npcId, request, apiUrl, apiKey }) => ({
342
+ url: `${apiUrl}/npcs/${npcId}/process`,
343
+ method: "POST",
344
+ headers: authHeaders(apiKey),
345
+ body: request
258
346
  }),
259
- deleteMemoryClear: builder.mutation({
260
- query: ({ npcId, apiUrl, apiKey }) => ({
261
- url: `${apiUrl}/npcs/${npcId}/memory/clear`,
262
- method: "DELETE",
263
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
264
- }),
265
- invalidatesTags: (result, error, { npcId }) => [{ type: "Memory", id: npcId }],
266
- transformResponse: (response) => response
347
+ invalidatesTags: (_result, _error, { npcId }) => npcTag(npcId),
348
+ transformResponse: (response) => response
349
+ }),
350
+ postDirective: builder.mutation({
351
+ query: ({ npcId, request, apiUrl, apiKey }) => ({
352
+ url: `${apiUrl}/npcs/${npcId}/directive`,
353
+ method: "POST",
354
+ headers: authHeaders(apiKey),
355
+ body: request
267
356
  }),
268
- // Ghost Endpoints
269
- postGhostRun: builder.mutation({
270
- query: ({ request, apiUrl, apiKey }) => ({
271
- url: `${apiUrl}/ghost/run`,
272
- method: "POST",
273
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
274
- body: request
275
- }),
276
- invalidatesTags: ["Ghost"],
277
- transformResponse: (response) => response
357
+ invalidatesTags: ["NPC"],
358
+ transformResponse: (response) => response
359
+ }),
360
+ postContext: builder.mutation({
361
+ query: ({ npcId, request, apiUrl, apiKey }) => ({
362
+ url: `${apiUrl}/npcs/${npcId}/context`,
363
+ method: "POST",
364
+ headers: authHeaders(apiKey),
365
+ body: request
278
366
  }),
279
- getGhostStatus: builder.query({
280
- query: ({ sessionId, apiUrl, apiKey }) => ({
281
- url: `${apiUrl}/ghost/${sessionId}/status`,
282
- method: "GET",
283
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
284
- }),
285
- providesTags: (result, error, { sessionId }) => [{ type: "Ghost", id: sessionId }],
286
- transformResponse: (response) => response
367
+ invalidatesTags: (_result, _error, { npcId }) => npcTag(npcId),
368
+ transformResponse: (response) => response
369
+ }),
370
+ postVerdict: builder.mutation({
371
+ query: ({ npcId, request, apiUrl, apiKey }) => ({
372
+ url: `${apiUrl}/npcs/${npcId}/verdict`,
373
+ method: "POST",
374
+ headers: authHeaders(apiKey),
375
+ body: request
287
376
  }),
288
- getGhostResults: builder.query({
289
- query: ({ sessionId, apiUrl, apiKey }) => ({
290
- url: `${apiUrl}/ghost/${sessionId}/results`,
291
- method: "GET",
292
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
293
- }),
294
- providesTags: (result, error, { sessionId }) => [{ type: "Ghost", id: sessionId }],
295
- transformResponse: (response) => response
377
+ invalidatesTags: (_result, _error, { npcId }) => npcTag(npcId),
378
+ transformResponse: (response) => {
379
+ const action = response.action ? {
380
+ type: response.action.gaType || response.action.type,
381
+ reason: response.action.actionReason || response.action.reason,
382
+ target: response.action.actionTarget || response.action.target,
383
+ signature: response.action.signature
384
+ } : void 0;
385
+ return {
386
+ ...response,
387
+ action
388
+ };
389
+ }
390
+ }),
391
+ postMemoryStore: builder.mutation({
392
+ query: ({ npcId, request, apiUrl, apiKey }) => ({
393
+ url: `${apiUrl}/npcs/${npcId}/memory`,
394
+ method: "POST",
395
+ headers: authHeaders(apiKey),
396
+ body: request
296
397
  }),
297
- postGhostStop: builder.mutation({
298
- query: ({ sessionId, apiUrl, apiKey }) => ({
299
- url: `${apiUrl}/ghost/${sessionId}/stop`,
300
- method: "POST",
301
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
302
- }),
303
- invalidatesTags: (result, error, { sessionId }) => [{ type: "Ghost", id: sessionId }],
304
- transformResponse: (response) => ({
305
- stopped: response?.stopStatus === "stopped",
306
- stopStatus: response?.stopStatus,
307
- stopSessionId: response?.stopSessionId
308
- })
398
+ invalidatesTags: (_result, _error, { npcId }) => memoryTag(npcId),
399
+ transformResponse: (response) => response
400
+ }),
401
+ getMemoryList: builder.query({
402
+ query: ({ npcId, apiUrl, apiKey }) => ({
403
+ url: `${apiUrl}/npcs/${npcId}/memory`,
404
+ method: "GET",
405
+ headers: authHeaders(apiKey)
309
406
  }),
310
- getGhostHistory: builder.query({
311
- query: ({ limit, apiUrl, apiKey }) => ({
312
- url: `${apiUrl}/ghost/history?limit=${limit}`,
313
- method: "GET",
314
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
315
- }),
316
- providesTags: ["Ghost"],
317
- transformResponse: (response) => response
407
+ providesTags: (_result, _error, { npcId }) => memoryTag(npcId),
408
+ transformResponse: (response) => response || []
409
+ }),
410
+ postMemoryRecall: builder.mutation({
411
+ query: ({ npcId, request, apiUrl, apiKey }) => ({
412
+ url: `${apiUrl}/npcs/${npcId}/memory/recall`,
413
+ method: "POST",
414
+ headers: authHeaders(apiKey),
415
+ body: request
318
416
  }),
319
- // Soul Endpoints
320
- postSoulExport: builder.mutation({
321
- query: ({ npcId, request, apiUrl, apiKey }) => ({
322
- url: `${apiUrl}/npcs/${npcId}/soul/export`,
323
- method: "POST",
324
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
325
- body: request
326
- }),
327
- invalidatesTags: ["Soul"],
328
- transformResponse: (response) => response
417
+ invalidatesTags: (_result, _error, { npcId }) => memoryTag(npcId),
418
+ transformResponse: (response) => response || []
419
+ }),
420
+ deleteMemoryClear: builder.mutation({
421
+ query: ({ npcId, apiUrl, apiKey }) => ({
422
+ url: `${apiUrl}/npcs/${npcId}/memory/clear`,
423
+ method: "DELETE",
424
+ headers: authHeaders(apiKey)
329
425
  }),
330
- postSoulExportConfirm: builder.mutation({
331
- query: ({ npcId, request, apiUrl, apiKey }) => ({
332
- url: `${apiUrl}/npcs/${npcId}/soul/confirm`,
333
- method: "POST",
334
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
335
- body: request
336
- }),
337
- invalidatesTags: ["Soul"],
338
- transformResponse: (response) => response
426
+ invalidatesTags: (_result, _error, { npcId }) => memoryTag(npcId),
427
+ transformResponse: (response) => response
428
+ })
429
+ });
430
+
431
+ // src/api/endpoints/rules.ts
432
+ var buildBridgeAndRuleEndpoints = (builder) => ({
433
+ postBridgeValidate: builder.mutation({
434
+ query: ({ request, npcId, apiUrl, apiKey }) => ({
435
+ url: npcId ? `${apiUrl}/bridge/validate/${npcId}` : `${apiUrl}/bridge/validate`,
436
+ method: "POST",
437
+ headers: authHeaders(apiKey),
438
+ body: request
339
439
  }),
340
- getSoulImport: builder.query({
341
- query: ({ txId, apiUrl, apiKey }) => ({
342
- url: `${apiUrl}/souls/${txId}`,
343
- method: "GET",
344
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
345
- }),
346
- providesTags: (result, error, { txId }) => [{ type: "Soul", id: txId }],
347
- transformResponse: (response) => response
440
+ invalidatesTags: ["Bridge"],
441
+ transformResponse: (response) => response.brResult || response
442
+ }),
443
+ getBridgeRules: builder.query({
444
+ query: ({ apiUrl, apiKey }) => ({
445
+ url: `${apiUrl}/bridge/rules`,
446
+ method: "GET",
447
+ headers: authHeaders(apiKey)
348
448
  }),
349
- getSouls: builder.query({
350
- query: ({ limit, apiUrl, apiKey }) => ({
351
- url: `${apiUrl}/souls?limit=${limit}`,
352
- method: "GET",
353
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
354
- }),
355
- providesTags: ["Soul"],
356
- transformResponse: (response) => response
449
+ providesTags: ["Bridge"],
450
+ transformResponse: (response) => response
451
+ }),
452
+ postBridgePreset: builder.mutation({
453
+ query: ({ presetName, apiUrl, apiKey }) => ({
454
+ url: `${apiUrl}/rules/presets/${presetName}`,
455
+ method: "POST",
456
+ headers: authHeaders(apiKey)
357
457
  }),
358
- // Bridge Endpoints
359
- postBridgeValidate: builder.mutation({
360
- query: ({ request, npcId, apiUrl, apiKey }) => ({
361
- url: npcId ? `${apiUrl}/bridge/validate/${npcId}` : `${apiUrl}/bridge/validate`,
362
- method: "POST",
363
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
364
- body: request
365
- }),
366
- invalidatesTags: ["Bridge"],
367
- transformResponse: (response) => response.brResult || response
458
+ invalidatesTags: ["Bridge"],
459
+ transformResponse: (response) => response
460
+ }),
461
+ getRulesets: builder.query({
462
+ query: ({ apiUrl, apiKey }) => ({
463
+ url: `${apiUrl}/rules`,
464
+ method: "GET",
465
+ headers: authHeaders(apiKey)
368
466
  }),
369
- getBridgeRules: builder.query({
370
- query: ({ apiUrl, apiKey }) => ({
371
- url: `${apiUrl}/bridge/rules`,
372
- method: "GET",
373
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
374
- }),
375
- providesTags: ["Bridge"],
376
- transformResponse: (response) => response
467
+ providesTags: ["Rule"],
468
+ transformResponse: (response) => response || []
469
+ }),
470
+ getRulePresets: builder.query({
471
+ query: ({ apiUrl, apiKey }) => ({
472
+ url: `${apiUrl}/rules/presets`,
473
+ method: "GET",
474
+ headers: authHeaders(apiKey)
377
475
  }),
378
- postBridgePreset: builder.mutation({
379
- query: ({ presetName, apiUrl, apiKey }) => ({
380
- url: `${apiUrl}/rules/presets/${presetName}`,
381
- method: "POST",
382
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
383
- }),
384
- invalidatesTags: ["Bridge"],
385
- transformResponse: (response) => response
476
+ providesTags: ["Rule"],
477
+ transformResponse: (response) => response || []
478
+ }),
479
+ postRuleRegister: builder.mutation({
480
+ query: ({ request, apiUrl, apiKey }) => ({
481
+ url: `${apiUrl}/rules`,
482
+ method: "POST",
483
+ headers: authHeaders(apiKey),
484
+ body: request
386
485
  }),
387
- // Rules Endpoints
388
- getRulesets: builder.query({
389
- query: ({ apiUrl, apiKey }) => ({
390
- url: `${apiUrl}/rules`,
391
- method: "GET",
392
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
393
- }),
394
- providesTags: ["Rule"],
395
- transformResponse: (response) => response || []
486
+ invalidatesTags: ["Rule"],
487
+ transformResponse: (response) => response
488
+ }),
489
+ deleteRule: builder.mutation({
490
+ query: ({ rulesetId, apiUrl, apiKey }) => ({
491
+ url: `${apiUrl}/rules/${rulesetId}`,
492
+ method: "DELETE",
493
+ headers: authHeaders(apiKey)
396
494
  }),
397
- getRulePresets: builder.query({
398
- query: ({ apiUrl, apiKey }) => ({
399
- url: `${apiUrl}/rules/presets`,
400
- method: "GET",
401
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
402
- }),
403
- providesTags: ["Rule"],
404
- transformResponse: (response) => response || []
495
+ invalidatesTags: ["Rule"],
496
+ transformResponse: (_response) => ({ deleted: true })
497
+ })
498
+ });
499
+
500
+ // src/api/endpoints/soul.ts
501
+ var soulTag = (id) => [{ type: "Soul", id }];
502
+ var buildSoulEndpoints = (builder) => ({
503
+ postSoulExport: builder.mutation({
504
+ query: ({ npcId, request, apiUrl, apiKey }) => ({
505
+ url: `${apiUrl}/npcs/${npcId}/soul/export`,
506
+ method: "POST",
507
+ headers: authHeaders(apiKey),
508
+ body: request
405
509
  }),
406
- postRuleRegister: builder.mutation({
407
- query: ({ request, apiUrl, apiKey }) => ({
408
- url: `${apiUrl}/rules`,
409
- method: "POST",
410
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
411
- body: request
412
- }),
413
- invalidatesTags: ["Rule"],
414
- transformResponse: (response) => response
510
+ invalidatesTags: ["Soul"],
511
+ transformResponse: (response) => response
512
+ }),
513
+ postSoulExportConfirm: builder.mutation({
514
+ query: ({ npcId, request, apiUrl, apiKey }) => ({
515
+ url: `${apiUrl}/npcs/${npcId}/soul/confirm`,
516
+ method: "POST",
517
+ headers: authHeaders(apiKey),
518
+ body: request
415
519
  }),
416
- deleteRule: builder.mutation({
417
- query: ({ rulesetId, apiUrl, apiKey }) => ({
418
- url: `${apiUrl}/rules/${rulesetId}`,
419
- method: "DELETE",
420
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
421
- }),
422
- invalidatesTags: ["Rule"],
423
- transformResponse: (_response) => ({ deleted: true })
520
+ invalidatesTags: ["Soul"],
521
+ transformResponse: (response) => response
522
+ }),
523
+ getSoulImport: builder.query({
524
+ query: ({ txId, apiUrl, apiKey }) => ({
525
+ url: `${apiUrl}/souls/${txId}`,
526
+ method: "GET",
527
+ headers: authHeaders(apiKey)
424
528
  }),
425
- // Additional Soul/NPC Endpoints
426
- postSoulVerify: builder.mutation({
427
- query: ({ txId, apiUrl, apiKey }) => ({
428
- url: `${apiUrl}/souls/${txId}/verify`,
429
- method: "POST",
430
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {}
431
- }),
432
- invalidatesTags: ["Soul"],
433
- transformResponse: (response) => ({
434
- valid: response.verifyValid ?? response.valid ?? false,
435
- reason: response.verifyReason ?? response.reason
436
- })
529
+ providesTags: (_result, _error, { txId }) => soulTag(txId),
530
+ transformResponse: (response) => response
531
+ }),
532
+ getSouls: builder.query({
533
+ query: ({ limit, apiUrl, apiKey }) => ({
534
+ url: `${apiUrl}/souls?limit=${limit}`,
535
+ method: "GET",
536
+ headers: authHeaders(apiKey)
437
537
  }),
438
- postNpcImport: builder.mutation({
439
- query: ({ request, apiUrl, apiKey }) => ({
440
- url: `${apiUrl}/npcs/import`,
441
- method: "POST",
442
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
443
- body: request
444
- }),
445
- invalidatesTags: ["NPC"],
446
- transformResponse: (response) => response
538
+ providesTags: ["Soul"],
539
+ transformResponse: (response) => response
540
+ }),
541
+ postSoulVerify: builder.mutation({
542
+ query: ({ txId, apiUrl, apiKey }) => ({
543
+ url: `${apiUrl}/souls/${txId}/verify`,
544
+ method: "POST",
545
+ headers: authHeaders(apiKey)
447
546
  }),
448
- postNpcImportConfirm: builder.mutation({
449
- query: ({ request, apiUrl, apiKey }) => ({
450
- url: `${apiUrl}/npcs/import/confirm`,
451
- method: "POST",
452
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
453
- body: request
454
- }),
455
- invalidatesTags: ["NPC"],
456
- transformResponse: (response) => response
547
+ invalidatesTags: ["Soul"],
548
+ transformResponse: (response) => ({
549
+ valid: response.verifyValid ?? response.valid ?? false,
550
+ reason: response.verifyReason ?? response.reason
551
+ })
552
+ }),
553
+ postNpcImport: builder.mutation({
554
+ query: ({ request, apiUrl, apiKey }) => ({
555
+ url: `${apiUrl}/npcs/import`,
556
+ method: "POST",
557
+ headers: authHeaders(apiKey),
558
+ body: request
457
559
  }),
458
- // Cortex Remote Endpoint
459
- postCortexComplete: builder.mutation({
460
- query: ({ cortexId, prompt, options, apiUrl, apiKey }) => ({
461
- url: `${apiUrl}/cortex/${cortexId}/complete`,
462
- method: "POST",
463
- headers: apiKey ? { "Authorization": `Bearer ${apiKey}` } : {},
464
- body: { prompt, ...options }
465
- }),
466
- invalidatesTags: ["Cortex"],
467
- transformResponse: (response) => response
560
+ invalidatesTags: ["NPC"],
561
+ transformResponse: (response) => response
562
+ }),
563
+ postNpcImportConfirm: builder.mutation({
564
+ query: ({ request, apiUrl, apiKey }) => ({
565
+ url: `${apiUrl}/npcs/import/confirm`,
566
+ method: "POST",
567
+ headers: authHeaders(apiKey),
568
+ body: request
468
569
  }),
469
- // System Endpoints
470
- getApiStatus: builder.query({
471
- query: ({ apiUrl }) => ({ url: `${apiUrl}/status`, method: "GET" }),
472
- transformResponse: (response) => response
473
- })
570
+ invalidatesTags: ["NPC"],
571
+ transformResponse: (response) => response
572
+ })
573
+ });
574
+
575
+ // src/api/endpoints/system.ts
576
+ var buildSystemEndpoints = (builder) => ({
577
+ getApiStatus: builder.query({
578
+ query: ({ apiUrl }) => ({ url: `${apiUrl}/status`, method: "GET" }),
579
+ providesTags: ["NPC"],
580
+ transformResponse: (response) => response
581
+ })
582
+ });
583
+
584
+ // src/apiSlice.ts
585
+ var api = (0, import_query.createApi)({
586
+ reducerPath: "api",
587
+ baseQuery: (0, import_query.fetchBaseQuery)({
588
+ baseUrl: "/",
589
+ prepareHeaders: (headers, { getState }) => {
590
+ return headers;
591
+ }
592
+ }),
593
+ tagTypes: ["NPC", "Memory", "Cortex", "Ghost", "Soul", "Bridge", "Rule"],
594
+ endpoints: (builder) => ({
595
+ ...buildCortexEndpoints(builder),
596
+ ...buildNpcEndpoints(builder),
597
+ ...buildGhostEndpoints(builder),
598
+ ...buildSoulEndpoints(builder),
599
+ ...buildBridgeAndRuleEndpoints(builder),
600
+ ...buildArweaveEndpoints(builder),
601
+ ...buildSystemEndpoints(builder)
474
602
  })
475
603
  });
476
604
 
477
605
  // src/errors.ts
606
+ var DEFAULT_API_URL = "http://localhost:8080";
607
+ var PRODUCTION_API_URL = "https://api.forboc.ai";
608
+ var resolveApiUrl = (apiUrl) => apiUrl || DEFAULT_API_URL;
478
609
  var extractThunkErrorMessage = (error, fallback) => {
479
610
  if (typeof error === "string") return error;
480
611
  if (error && typeof error === "object") {
@@ -506,9 +637,9 @@ var validateBridgeThunk = (0, import_toolkit.createAsyncThunk)(
506
637
  "bridge/validate",
507
638
  async ({ action, context, npcId, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
508
639
  try {
509
- const url = apiUrl || "https://api.forboc.ai";
640
+ const url = resolveApiUrl(apiUrl);
510
641
  requireApiKeyGuidance(url, apiKey);
511
- const data = await dispatch2(sdkApi.endpoints.postBridgeValidate.initiate({
642
+ const data = await dispatch2(api.endpoints.postBridgeValidate.initiate({
512
643
  request: { action, context },
513
644
  npcId,
514
645
  apiUrl: url,
@@ -524,9 +655,9 @@ var loadBridgePresetThunk = (0, import_toolkit.createAsyncThunk)(
524
655
  "bridge/loadPreset",
525
656
  async ({ presetName, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
526
657
  try {
527
- const url = apiUrl || "https://api.forboc.ai";
658
+ const url = resolveApiUrl(apiUrl);
528
659
  requireApiKeyGuidance(url, apiKey);
529
- return await dispatch2(sdkApi.endpoints.postBridgePreset.initiate({ presetName, apiUrl: url, apiKey })).unwrap();
660
+ return await dispatch2(api.endpoints.postBridgePreset.initiate({ presetName, apiUrl: url, apiKey })).unwrap();
530
661
  } catch (error) {
531
662
  return rejectWithValue(extractThunkErrorMessage(error, "Failed to load preset"));
532
663
  }
@@ -536,9 +667,9 @@ var getBridgeRulesThunk = (0, import_toolkit.createAsyncThunk)(
536
667
  "bridge/rules",
537
668
  async ({ apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
538
669
  try {
539
- const url = apiUrl || "https://api.forboc.ai";
670
+ const url = resolveApiUrl(apiUrl);
540
671
  requireApiKeyGuidance(url, apiKey);
541
- return await dispatch2(sdkApi.endpoints.getBridgeRules.initiate({ apiUrl: url, apiKey })).unwrap();
672
+ return await dispatch2(api.endpoints.getBridgeRules.initiate({ apiUrl: url, apiKey })).unwrap();
542
673
  } catch (error) {
543
674
  return rejectWithValue(extractThunkErrorMessage(error, "Failed to list bridge rules"));
544
675
  }
@@ -548,9 +679,9 @@ var listRulesetsThunk = (0, import_toolkit.createAsyncThunk)(
548
679
  "bridge/listRulesets",
549
680
  async ({ apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
550
681
  try {
551
- const url = apiUrl || "https://api.forboc.ai";
682
+ const url = resolveApiUrl(apiUrl);
552
683
  requireApiKeyGuidance(url, apiKey);
553
- return await dispatch2(sdkApi.endpoints.getRulesets.initiate({ apiUrl: url, apiKey })).unwrap();
684
+ return await dispatch2(api.endpoints.getRulesets.initiate({ apiUrl: url, apiKey })).unwrap();
554
685
  } catch (error) {
555
686
  return rejectWithValue(extractThunkErrorMessage(error, "Failed to list rulesets"));
556
687
  }
@@ -560,9 +691,9 @@ var listRulePresetsThunk = (0, import_toolkit.createAsyncThunk)(
560
691
  "bridge/listRulePresets",
561
692
  async ({ apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
562
693
  try {
563
- const url = apiUrl || "https://api.forboc.ai";
694
+ const url = resolveApiUrl(apiUrl);
564
695
  requireApiKeyGuidance(url, apiKey);
565
- return await dispatch2(sdkApi.endpoints.getRulePresets.initiate({ apiUrl: url, apiKey })).unwrap();
696
+ return await dispatch2(api.endpoints.getRulePresets.initiate({ apiUrl: url, apiKey })).unwrap();
566
697
  } catch (error) {
567
698
  return rejectWithValue(extractThunkErrorMessage(error, "Failed to list rule presets"));
568
699
  }
@@ -572,9 +703,9 @@ var registerRulesetThunk = (0, import_toolkit.createAsyncThunk)(
572
703
  "bridge/registerRuleset",
573
704
  async ({ ruleset, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
574
705
  try {
575
- const url = apiUrl || "https://api.forboc.ai";
706
+ const url = resolveApiUrl(apiUrl);
576
707
  requireApiKeyGuidance(url, apiKey);
577
- return await dispatch2(sdkApi.endpoints.postRuleRegister.initiate({ request: ruleset, apiUrl: url, apiKey })).unwrap();
708
+ return await dispatch2(api.endpoints.postRuleRegister.initiate({ request: ruleset, apiUrl: url, apiKey })).unwrap();
578
709
  } catch (error) {
579
710
  return rejectWithValue(extractThunkErrorMessage(error, "Failed to register ruleset"));
580
711
  }
@@ -584,9 +715,9 @@ var deleteRulesetThunk = (0, import_toolkit.createAsyncThunk)(
584
715
  "bridge/deleteRuleset",
585
716
  async ({ rulesetId, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
586
717
  try {
587
- const url = apiUrl || "https://api.forboc.ai";
718
+ const url = resolveApiUrl(apiUrl);
588
719
  requireApiKeyGuidance(url, apiKey);
589
- return await dispatch2(sdkApi.endpoints.deleteRule.initiate({ rulesetId, apiUrl: url, apiKey })).unwrap();
720
+ return await dispatch2(api.endpoints.deleteRule.initiate({ rulesetId, apiUrl: url, apiKey })).unwrap();
590
721
  } catch (error) {
591
722
  return rejectWithValue(extractThunkErrorMessage(error, "Failed to delete ruleset"));
592
723
  }
@@ -638,121 +769,82 @@ var bridgeSlice_default = bridgeSlice.reducer;
638
769
  // src/soulSlice.ts
639
770
  var import_toolkit2 = require("@reduxjs/toolkit");
640
771
 
641
- // src/handlers/arweave.ts
642
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
643
- var getLocalWalletToken = () => {
644
- const maybeEnv = globalThis.process?.env;
645
- return maybeEnv?.ARWEAVE_WALLET_JWK ?? null;
646
- };
647
- var withTimeout = async (promiseFactory, timeoutMs = 6e4) => {
648
- const controller = new AbortController();
649
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
650
- try {
651
- return await promiseFactory(controller.signal);
652
- } finally {
653
- clearTimeout(timeout);
654
- }
655
- };
656
- async function handler_ArweaveUpload(instruction, maxRetries = 3) {
657
- const headers = {
658
- "Content-Type": instruction.auiContentType || "application/json"
659
- };
660
- const authToken = instruction.auiAuthHeader ?? (getLocalWalletToken() ? `Bearer ${getLocalWalletToken()}` : null);
661
- if (authToken) {
662
- headers.Authorization = authToken;
663
- }
664
- let attempt = 0;
665
- while (attempt < maxRetries) {
666
- attempt += 1;
667
- try {
668
- const response = await withTimeout(
669
- (signal) => fetch(instruction.auiEndpoint, {
670
- method: "POST",
671
- headers,
672
- body: JSON.stringify(instruction.auiPayload),
673
- signal
674
- })
675
- );
676
- let responseBody = null;
677
- try {
678
- responseBody = await response.json();
679
- } catch {
680
- responseBody = null;
681
- }
682
- const txId = responseBody?.id ?? `ar_tx_sdk_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
683
- const success = response.status >= 200 && response.status < 300;
684
- if (!success && attempt < maxRetries) {
685
- await sleep(250 * 2 ** (attempt - 1));
686
- continue;
687
- }
688
- return {
689
- aurTxId: txId,
690
- aurStatus: response.status,
691
- aurSuccess: success,
692
- aurError: success ? null : `upload_failed_status_${response.status}`
693
- };
694
- } catch (error) {
695
- const message = error instanceof Error ? error.message : String(error);
696
- if (attempt < maxRetries) {
697
- await sleep(250 * 2 ** (attempt - 1));
698
- continue;
699
- }
700
- return {
701
- aurTxId: `ar_tx_failed_${Date.now()}`,
702
- aurStatus: 0,
703
- aurSuccess: false,
704
- aurError: `upload_request_failed:${message}`
705
- };
706
- }
772
+ // src/functional_core.ts
773
+ var just = (value) => ({
774
+ _tag: "Just",
775
+ map: (f) => just(f(value)),
776
+ chain: (f) => f(value),
777
+ getOrElse: (_defaultValue) => value,
778
+ match: (cases) => cases.just(value)
779
+ });
780
+ var nothing = () => ({
781
+ _tag: "Nothing",
782
+ map: (_f) => nothing(),
783
+ chain: (_f) => nothing(),
784
+ getOrElse: (defaultValue) => defaultValue,
785
+ match: (cases) => cases.nothing()
786
+ });
787
+ var fmap = (m, f) => m.map(f);
788
+ var mbind = (m, f) => m.chain(f);
789
+ var orElse = (m, defaultValue) => m.getOrElse(defaultValue);
790
+ var match = (m, onJust, onNothing) => m.match({ just: onJust, nothing: onNothing });
791
+ var isJust = (m) => m._tag === "Just";
792
+ var isNothing = (m) => m._tag === "Nothing";
793
+ var fromNullable = (value) => value != null ? just(value) : nothing();
794
+ var requireJust = (m, errorMsg) => m.match({
795
+ just: (v) => v,
796
+ nothing: () => {
797
+ throw new Error(errorMsg);
707
798
  }
708
- return {
709
- aurTxId: `ar_tx_failed_${Date.now()}`,
710
- aurStatus: 0,
711
- aurSuccess: false,
712
- aurError: "upload_retry_exhausted"
799
+ });
800
+ var left = (error) => ({
801
+ _tag: "Left",
802
+ map: (_f) => left(error),
803
+ chain: (_f) => left(error),
804
+ getOrElse: (defaultValue) => defaultValue,
805
+ match: (cases) => cases.left(error)
806
+ });
807
+ var right = (value) => ({
808
+ _tag: "Right",
809
+ map: (f) => right(f(value)),
810
+ chain: (f) => f(value),
811
+ getOrElse: (_defaultValue) => value,
812
+ match: (cases) => cases.right(value)
813
+ });
814
+ var efmap = (e, f) => e.map(f);
815
+ var ebind = (e, f) => e.chain(f);
816
+ var ematch = (e, onLeft, onRight) => e.match({ left: onLeft, right: onRight });
817
+ var isLeft = (e) => e._tag === "Left";
818
+ var isRight = (e) => e._tag === "Right";
819
+ function compose(...fns) {
820
+ return (...args) => {
821
+ const last = fns[fns.length - 1];
822
+ const rest = fns.slice(0, -1);
823
+ return rest.reduceRight((acc, fn) => fn(acc), last(...args));
713
824
  };
714
825
  }
715
- async function handler_ArweaveDownload(instruction) {
716
- try {
717
- const response = await withTimeout(
718
- (signal) => fetch(instruction.adiGatewayUrl, {
719
- method: "GET",
720
- signal
721
- })
722
- );
723
- if (response.status < 200 || response.status >= 300) {
724
- return {
725
- adrBody: null,
726
- adrStatus: response.status,
727
- adrSuccess: false,
728
- adrError: `download_failed_status_${response.status}`
729
- };
730
- }
731
- try {
732
- const body = await response.json();
733
- return {
734
- adrBody: body,
735
- adrStatus: response.status,
736
- adrSuccess: true,
737
- adrError: null
738
- };
739
- } catch {
740
- return {
741
- adrBody: null,
742
- adrStatus: response.status,
743
- adrSuccess: false,
744
- adrError: "download_invalid_json"
745
- };
746
- }
747
- } catch (error) {
748
- return {
749
- adrBody: null,
750
- adrStatus: 0,
751
- adrSuccess: false,
752
- adrError: error instanceof Error ? error.message : String(error)
753
- };
754
- }
826
+ function curry(fn) {
827
+ const arity = fn.length;
828
+ const curried = (...args) => args.length >= arity ? fn(...args) : (...moreArgs) => curried(...args, ...moreArgs);
829
+ return curried;
755
830
  }
831
+ var createDispatcher = (entries) => {
832
+ const table = new Map(entries);
833
+ return {
834
+ dispatch: (key, ...args) => {
835
+ const handler = table.get(key);
836
+ return handler ? just(handler(...args)) : nothing();
837
+ },
838
+ has: (key) => table.has(key),
839
+ keys: () => [...table.keys()]
840
+ };
841
+ };
842
+ var _ = /* @__PURE__ */ Symbol.for("forbocai_wildcard");
843
+ var testCase = (value, predicate, handler) => predicate === _ ? just(handler(value)) : typeof predicate === "function" ? predicate(value) ? just(handler(value)) : nothing() : predicate === value ? just(handler(value)) : nothing();
844
+ var multiMatch = (value, cases) => cases.length === 0 ? nothing() : testCase(value, cases[0][0], cases[0][1]).match({
845
+ just: (v) => just(v),
846
+ nothing: () => multiMatch(value, cases.slice(1))
847
+ });
756
848
 
757
849
  // src/soulSlice.ts
758
850
  var initialState2 = {
@@ -769,24 +861,25 @@ var remoteExportSoulThunk = (0, import_toolkit2.createAsyncThunk)(
769
861
  try {
770
862
  const state = getState().npc;
771
863
  const npcId = argNpcId || state.activeNpcId;
772
- const npc = state.entities[npcId];
773
- if (!npc) throw new Error(`NPC ${npcId} not found`);
774
- const url = apiUrl || "https://api.forboc.ai";
864
+ const npc = requireJust(fromNullable(state.entities[npcId]), `NPC ${npcId} not found`);
865
+ const url = resolveApiUrl(apiUrl);
775
866
  requireApiKeyGuidance(url, apiKey);
776
867
  const phase1 = await dispatch2(
777
- sdkApi.endpoints.postSoulExport.initiate({
868
+ api.endpoints.postSoulExport.initiate({
778
869
  npcId,
779
870
  request: { npcIdRef: npcId, persona: npc.persona || "NPC", npcState: npc.state },
780
871
  apiUrl: url,
781
872
  apiKey
782
873
  })
783
874
  ).unwrap();
784
- const uploadResult = await handler_ArweaveUpload({
785
- ...phase1.se1Instruction,
786
- auiAuthHeader: phase1.se1Instruction.auiAuthHeader ?? null
787
- });
875
+ const uploadResult = await dispatch2(
876
+ api.endpoints.postArweaveUpload.initiate({
877
+ ...phase1.se1Instruction,
878
+ auiAuthHeader: phase1.se1Instruction.auiAuthHeader ?? null
879
+ })
880
+ ).unwrap();
788
881
  const final = await dispatch2(
789
- sdkApi.endpoints.postSoulExportConfirm.initiate({
882
+ api.endpoints.postSoulExportConfirm.initiate({
790
883
  npcId,
791
884
  request: {
792
885
  secUploadResult: uploadResult,
@@ -811,14 +904,16 @@ var importSoulFromArweaveThunk = (0, import_toolkit2.createAsyncThunk)(
811
904
  "soul/import",
812
905
  async ({ txId, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
813
906
  try {
814
- const url = apiUrl || "https://api.forboc.ai";
907
+ const url = resolveApiUrl(apiUrl);
815
908
  requireApiKeyGuidance(url, apiKey);
816
909
  const phase1 = await dispatch2(
817
- sdkApi.endpoints.postNpcImport.initiate({ request: { txIdRef: txId }, apiUrl: url, apiKey })
910
+ api.endpoints.postNpcImport.initiate({ request: { txIdRef: txId }, apiUrl: url, apiKey })
911
+ ).unwrap();
912
+ const downloadResult = await dispatch2(
913
+ api.endpoints.postArweaveDownload.initiate(phase1.si1Instruction)
818
914
  ).unwrap();
819
- const downloadResult = await handler_ArweaveDownload(phase1.si1Instruction);
820
915
  const npc = await dispatch2(
821
- sdkApi.endpoints.postNpcImportConfirm.initiate({
916
+ api.endpoints.postNpcImportConfirm.initiate({
822
917
  request: {
823
918
  sicTxId: txId,
824
919
  sicDownloadResult: downloadResult
@@ -844,9 +939,9 @@ var getSoulListThunk = (0, import_toolkit2.createAsyncThunk)(
844
939
  "soul/list",
845
940
  async ({ limit = 50, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
846
941
  try {
847
- const url = apiUrl || "https://api.forboc.ai";
942
+ const url = resolveApiUrl(apiUrl);
848
943
  requireApiKeyGuidance(url, apiKey);
849
- const data = await dispatch2(sdkApi.endpoints.getSouls.initiate({ limit, apiUrl: url, apiKey })).unwrap();
944
+ const data = await dispatch2(api.endpoints.getSouls.initiate({ limit, apiUrl: url, apiKey })).unwrap();
850
945
  return data.souls || [];
851
946
  } catch (error) {
852
947
  return rejectWithValue(extractThunkErrorMessage(error, "Failed to list souls"));
@@ -857,9 +952,9 @@ var verifySoulThunk = (0, import_toolkit2.createAsyncThunk)(
857
952
  "soul/verify",
858
953
  async ({ txId, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
859
954
  try {
860
- const url = apiUrl || "https://api.forboc.ai";
955
+ const url = resolveApiUrl(apiUrl);
861
956
  requireApiKeyGuidance(url, apiKey);
862
- return await dispatch2(sdkApi.endpoints.postSoulVerify.initiate({ txId, apiUrl: url, apiKey })).unwrap();
957
+ return await dispatch2(api.endpoints.postSoulVerify.initiate({ txId, apiUrl: url, apiKey })).unwrap();
863
958
  } catch (error) {
864
959
  return rejectWithValue(extractThunkErrorMessage(error, "Soul verify failed"));
865
960
  }
@@ -869,18 +964,20 @@ var importNpcFromSoulThunk = (0, import_toolkit2.createAsyncThunk)(
869
964
  "soul/importNpc",
870
965
  async ({ txId, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
871
966
  try {
872
- const url = apiUrl || "https://api.forboc.ai";
967
+ const url = resolveApiUrl(apiUrl);
873
968
  requireApiKeyGuidance(url, apiKey);
874
969
  const phase1 = await dispatch2(
875
- sdkApi.endpoints.postNpcImport.initiate({
970
+ api.endpoints.postNpcImport.initiate({
876
971
  request: { txIdRef: txId },
877
972
  apiUrl: url,
878
973
  apiKey
879
974
  })
880
975
  ).unwrap();
881
- const downloadResult = await handler_ArweaveDownload(phase1.si1Instruction);
976
+ const downloadResult = await dispatch2(
977
+ api.endpoints.postArweaveDownload.initiate(phase1.si1Instruction)
978
+ ).unwrap();
882
979
  return await dispatch2(
883
- sdkApi.endpoints.postNpcImportConfirm.initiate({
980
+ api.endpoints.postNpcImportConfirm.initiate({
884
981
  request: { sicTxId: txId, sicDownloadResult: downloadResult },
885
982
  apiUrl: url,
886
983
  apiKey
@@ -945,9 +1042,9 @@ var startGhostThunk = (0, import_toolkit3.createAsyncThunk)(
945
1042
  "ghost/start",
946
1043
  async (config, { dispatch: dispatch2, rejectWithValue }) => {
947
1044
  try {
948
- const apiUrl = config.apiUrl || "https://api.forboc.ai";
1045
+ const apiUrl = resolveApiUrl(config.apiUrl);
949
1046
  requireApiKeyGuidance(apiUrl, config.apiKey);
950
- const data = await dispatch2(sdkApi.endpoints.postGhostRun.initiate({
1047
+ const data = await dispatch2(api.endpoints.postGhostRun.initiate({
951
1048
  request: { testSuite: config.testSuite, duration: config.duration ?? 300 },
952
1049
  apiUrl,
953
1050
  apiKey: config.apiKey
@@ -966,11 +1063,10 @@ var getGhostStatusThunk = (0, import_toolkit3.createAsyncThunk)(
966
1063
  async ({ sessionId, apiUrl, apiKey }, { dispatch: dispatch2, getState, rejectWithValue }) => {
967
1064
  try {
968
1065
  const state = getState().ghost;
969
- const targetSession = sessionId || state.activeSessionId;
970
- if (!targetSession) throw new Error("No active Ghost session");
971
- const url = apiUrl || "https://api.forboc.ai";
1066
+ const targetSession = requireJust(fromNullable(sessionId || state.activeSessionId), "No active Ghost session");
1067
+ const url = resolveApiUrl(apiUrl);
972
1068
  requireApiKeyGuidance(url, apiKey);
973
- const data = await dispatch2(sdkApi.endpoints.getGhostStatus.initiate({ sessionId: targetSession, apiUrl: url, apiKey })).unwrap();
1069
+ const data = await dispatch2(api.endpoints.getGhostStatus.initiate({ sessionId: targetSession, apiUrl: url, apiKey })).unwrap();
974
1070
  return {
975
1071
  sessionId: data.ghostSessionId,
976
1072
  status: data.ghostStatus,
@@ -989,11 +1085,10 @@ var getGhostResultsThunk = (0, import_toolkit3.createAsyncThunk)(
989
1085
  async ({ sessionId, apiUrl, apiKey }, { dispatch: dispatch2, getState, rejectWithValue }) => {
990
1086
  try {
991
1087
  const state = getState().ghost;
992
- const targetSession = sessionId || state.activeSessionId;
993
- if (!targetSession) throw new Error("No active Ghost session");
994
- const url = apiUrl || "https://api.forboc.ai";
1088
+ const targetSession = requireJust(fromNullable(sessionId || state.activeSessionId), "No active Ghost session");
1089
+ const url = resolveApiUrl(apiUrl);
995
1090
  requireApiKeyGuidance(url, apiKey);
996
- const data = await dispatch2(sdkApi.endpoints.getGhostResults.initiate({ sessionId: targetSession, apiUrl: url, apiKey })).unwrap();
1091
+ const data = await dispatch2(api.endpoints.getGhostResults.initiate({ sessionId: targetSession, apiUrl: url, apiKey })).unwrap();
997
1092
  return {
998
1093
  sessionId: data.resultsSessionId,
999
1094
  totalTests: data.resultsTotalTests,
@@ -1021,11 +1116,10 @@ var stopGhostThunk = (0, import_toolkit3.createAsyncThunk)(
1021
1116
  async ({ sessionId, apiUrl, apiKey }, { dispatch: dispatch2, getState, rejectWithValue }) => {
1022
1117
  try {
1023
1118
  const state = getState().ghost;
1024
- const targetSession = sessionId || state.activeSessionId;
1025
- if (!targetSession) throw new Error("No active Ghost session");
1026
- const url = apiUrl || "https://api.forboc.ai";
1119
+ const targetSession = requireJust(fromNullable(sessionId || state.activeSessionId), "No active Ghost session");
1120
+ const url = resolveApiUrl(apiUrl);
1027
1121
  requireApiKeyGuidance(url, apiKey);
1028
- const data = await dispatch2(sdkApi.endpoints.postGhostStop.initiate({ sessionId: targetSession, apiUrl: url, apiKey })).unwrap();
1122
+ const data = await dispatch2(api.endpoints.postGhostStop.initiate({ sessionId: targetSession, apiUrl: url, apiKey })).unwrap();
1029
1123
  return {
1030
1124
  stopped: data.stopped,
1031
1125
  status: data.stopStatus,
@@ -1040,9 +1134,9 @@ var getGhostHistoryThunk = (0, import_toolkit3.createAsyncThunk)(
1040
1134
  "ghost/history",
1041
1135
  async ({ limit = 10, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
1042
1136
  try {
1043
- const url = apiUrl || "https://api.forboc.ai";
1137
+ const url = resolveApiUrl(apiUrl);
1044
1138
  requireApiKeyGuidance(url, apiKey);
1045
- const data = await dispatch2(sdkApi.endpoints.getGhostHistory.initiate({ limit, apiUrl: url, apiKey })).unwrap();
1139
+ const data = await dispatch2(api.endpoints.getGhostHistory.initiate({ limit, apiUrl: url, apiKey })).unwrap();
1046
1140
  return (data.sessions || []).map((s) => ({
1047
1141
  sessionId: s.sessionId,
1048
1142
  testSuite: s.testSuite,
@@ -1101,8 +1195,8 @@ var ghostSlice = (0, import_toolkit3.createSlice)({
1101
1195
  var { clearGhostSession } = ghostSlice.actions;
1102
1196
  var ghostSlice_default = ghostSlice.reducer;
1103
1197
 
1104
- // src/utils/sdkVersion.ts
1105
- var SDK_VERSION = "0.6.1";
1198
+ // src/utils/version.ts
1199
+ var VERSION = "0.6.4";
1106
1200
 
1107
1201
  // src/utils/generateNPCId.ts
1108
1202
  var generateNPCId = () => `ag_${Date.now().toString(36)}`;
@@ -1270,9 +1364,9 @@ var initRemoteCortexThunk = (0, import_toolkit5.createAsyncThunk)(
1270
1364
  "cortex/initRemote",
1271
1365
  async ({ model = "api-integrated", authKey, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
1272
1366
  try {
1273
- const url = apiUrl || "https://api.forboc.ai";
1367
+ const url = resolveApiUrl(apiUrl);
1274
1368
  requireApiKeyGuidance(url, apiKey);
1275
- const data = await dispatch2(sdkApi.endpoints.postCortexInit.initiate({
1369
+ const data = await dispatch2(api.endpoints.postCortexInit.initiate({
1276
1370
  request: { requestedModel: model, authKey },
1277
1371
  apiUrl: url,
1278
1372
  apiKey
@@ -1292,9 +1386,9 @@ var listCortexModelsThunk = (0, import_toolkit5.createAsyncThunk)(
1292
1386
  "cortex/listModels",
1293
1387
  async ({ apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
1294
1388
  try {
1295
- const url = apiUrl || "https://api.forboc.ai";
1389
+ const url = resolveApiUrl(apiUrl);
1296
1390
  requireApiKeyGuidance(url, apiKey);
1297
- return await dispatch2(sdkApi.endpoints.getCortexModels.initiate({ apiUrl: url, apiKey })).unwrap();
1391
+ return await dispatch2(api.endpoints.getCortexModels.initiate({ apiUrl: url, apiKey })).unwrap();
1298
1392
  } catch (error) {
1299
1393
  return rejectWithValue(extractThunkErrorMessage(error, "Failed to list cortex models"));
1300
1394
  }
@@ -1305,7 +1399,7 @@ var completeRemoteThunk = (0, import_toolkit5.createAsyncThunk)(
1305
1399
  async ({ cortexId, prompt, options, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
1306
1400
  try {
1307
1401
  requireApiKeyGuidance(apiUrl, apiKey);
1308
- const data = await dispatch2(sdkApi.endpoints.postCortexComplete.initiate({
1402
+ const data = await dispatch2(api.endpoints.postCortexComplete.initiate({
1309
1403
  cortexId,
1310
1404
  prompt,
1311
1405
  options,
@@ -1506,8 +1600,8 @@ var directiveSlice_default = directiveSlice.reducer;
1506
1600
 
1507
1601
  // src/listeners.ts
1508
1602
  var import_toolkit8 = require("@reduxjs/toolkit");
1509
- var sdkListenerMiddleware = (0, import_toolkit8.createListenerMiddleware)();
1510
- var startAppListening = sdkListenerMiddleware.startListening.withTypes();
1603
+ var listenerMiddleware = (0, import_toolkit8.createListenerMiddleware)();
1604
+ var startAppListening = listenerMiddleware.startListening.withTypes();
1511
1605
  startAppListening({
1512
1606
  actionCreator: removeNPC,
1513
1607
  effect: async (action, listenerApi) => {
@@ -1524,11 +1618,38 @@ startAppListening({
1524
1618
  }
1525
1619
  });
1526
1620
 
1621
+ // src/runtimeRegistry.ts
1622
+ var createRuntimeRegistry = () => {
1623
+ const _store = {};
1624
+ return {
1625
+ get: (ns, key) => _store[ns]?.[key],
1626
+ set: (ns, key, value) => {
1627
+ if (!_store[ns]) _store[ns] = {};
1628
+ _store[ns][key] = value;
1629
+ },
1630
+ delete: (ns, key) => {
1631
+ if (_store[ns]) {
1632
+ delete _store[ns][key];
1633
+ return true;
1634
+ }
1635
+ return false;
1636
+ },
1637
+ has: (ns, key) => !!(_store[ns]?.[key] !== void 0),
1638
+ clear: (ns) => {
1639
+ if (ns) {
1640
+ delete _store[ns];
1641
+ } else {
1642
+ Object.keys(_store).forEach((k) => delete _store[k]);
1643
+ }
1644
+ }
1645
+ };
1646
+ };
1647
+
1527
1648
  // src/store.ts
1528
- var createSDKStore = (extraReducers = {}) => {
1649
+ var createRuntimeStore = (extraReducers = {}, registry = createRuntimeRegistry()) => {
1529
1650
  return (0, import_toolkit9.configureStore)({
1530
1651
  reducer: {
1531
- [sdkApi.reducerPath]: sdkApi.reducer,
1652
+ [api.reducerPath]: api.reducer,
1532
1653
  npc: npcSlice_default,
1533
1654
  cortex: cortexSlice_default,
1534
1655
  memory: memorySlice_default,
@@ -1539,46 +1660,120 @@ var createSDKStore = (extraReducers = {}) => {
1539
1660
  ...extraReducers
1540
1661
  },
1541
1662
  middleware: (getDefaultMiddleware) => getDefaultMiddleware({
1542
- serializableCheck: false
1543
- // Allow non-serializable for engine refs in specific slices if needed, though we try to keep them external
1544
- }).prepend(sdkListenerMiddleware.middleware).concat(sdkApi.middleware)
1663
+ thunk: { extraArgument: registry },
1664
+ serializableCheck: {
1665
+ ignoredActionPaths: [
1666
+ "meta.arg.cortex",
1667
+ "meta.arg.memory",
1668
+ "meta.arg.onProgress",
1669
+ "meta.baseQueryMeta.request",
1670
+ "meta.baseQueryMeta.response"
1671
+ ]
1672
+ }
1673
+ }).prepend(listenerMiddleware.middleware).concat(api.middleware)
1545
1674
  });
1546
1675
  };
1547
- var store = createSDKStore();
1676
+ var store = createRuntimeStore();
1548
1677
  var dispatch = store.dispatch;
1549
1678
 
1550
1679
  // src/thunks.ts
1551
1680
  var import_toolkit10 = require("@reduxjs/toolkit");
1552
- var extractThunkErrorMessage2 = (e) => {
1553
- if (typeof e === "string") return e;
1554
- if (e?.data?.message) return String(e.data.message);
1555
- if (e?.error) return String(e.error);
1556
- if (e?.message) return String(e.message);
1557
- return "Protocol processing failed";
1681
+
1682
+ // src/protocolHandlers.ts
1683
+ var persistMemoryRecursively = async (memory, instructions, index = 0) => !memory || index >= instructions.length ? void 0 : memory.store(instructions[index].text, instructions[index].type, instructions[index].importance).then(() => persistMemoryRecursively(memory, instructions, index + 1));
1684
+ var handleIdentifyActor = (ctx, nextTape, turn) => ctx.recurse(nextTape, {
1685
+ type: "IdentifyActorResult",
1686
+ actor: { npcId: ctx.npcId, persona: ctx.persona, data: nextTape.npcState }
1687
+ }, turn + 1);
1688
+ var handleQueryVector = async (ctx, instruction, nextTape, turn) => {
1689
+ ctx.dispatch(directiveReceived({
1690
+ id: ctx.directiveId,
1691
+ response: { memoryRecall: { query: instruction.query, limit: instruction.limit, threshold: instruction.threshold } }
1692
+ }));
1693
+ return ctx.memory ? ctx.memory.recall(instruction.query, instruction.limit, instruction.threshold).then((recalled) => ctx.recurse(nextTape, {
1694
+ type: "QueryVectorResult",
1695
+ memories: recalled.map((m) => ({ text: m.text, type: m.type, importance: m.importance, similarity: m.similarity }))
1696
+ }, turn + 1)) : ctx.rejectWithValue("API requested memory recall, but no memory engine is configured");
1697
+ };
1698
+ var handleExecuteInference = async (ctx, instruction, nextTape, turn) => {
1699
+ ctx.dispatch(contextComposed({ id: ctx.directiveId, prompt: instruction.prompt, constraints: instruction.constraints }));
1700
+ const generatedText = await ctx.cortex.complete(instruction.prompt, {
1701
+ maxTokens: instruction.constraints.maxTokens,
1702
+ temperature: instruction.constraints.temperature,
1703
+ stop: instruction.constraints.stop
1704
+ });
1705
+ return ctx.recurse(nextTape, {
1706
+ type: "ExecuteInferenceResult",
1707
+ generatedOutput: generatedText
1708
+ }, turn + 1);
1558
1709
  };
1710
+ var handleFinalize = async (ctx, finalize) => {
1711
+ ctx.dispatch(verdictValidated({
1712
+ id: ctx.directiveId,
1713
+ verdict: {
1714
+ valid: finalize.valid,
1715
+ signature: finalize.signature,
1716
+ memoryStore: finalize.memoryStore,
1717
+ stateDelta: finalize.stateTransform,
1718
+ action: finalize.action,
1719
+ dialogue: finalize.dialogue
1720
+ }
1721
+ }));
1722
+ return finalize.valid ? applyFinalizeSuccess(ctx, finalize) : applyFinalizeBlocked(ctx, finalize);
1723
+ };
1724
+ var applyFinalizeBlocked = (ctx, finalize) => {
1725
+ ctx.dispatch(blockAction({ id: ctx.npcId, reason: finalize.dialogue || "Validation Failed" }));
1726
+ return { dialogue: finalize.dialogue, action: finalize.action, thought: finalize.dialogue };
1727
+ };
1728
+ var applyFinalizeSuccess = async (ctx, finalize) => {
1729
+ if (finalize.memoryStore?.length && !ctx.memory) {
1730
+ return ctx.rejectWithValue("API returned memoryStore instructions, but no memory engine is configured");
1731
+ }
1732
+ await persistMemoryRecursively(ctx.memory, finalize.memoryStore || []);
1733
+ if (finalize.stateTransform) {
1734
+ ctx.dispatch(updateNPCState({ id: ctx.npcId, delta: finalize.stateTransform }));
1735
+ }
1736
+ ctx.dispatch(setLastAction({ id: ctx.npcId, action: finalize.action }));
1737
+ ctx.dispatch(addToHistory({ id: ctx.npcId, role: "user", content: ctx.text }));
1738
+ ctx.dispatch(addToHistory({ id: ctx.npcId, role: "assistant", content: finalize.dialogue }));
1739
+ return { dialogue: finalize.dialogue, action: finalize.action, thought: finalize.dialogue };
1740
+ };
1741
+ var dispatchInstruction = (ctx, instruction, nextTape, turn) => {
1742
+ const handlers = {
1743
+ "IdentifyActor": () => handleIdentifyActor(ctx, nextTape, turn),
1744
+ "QueryVector": () => handleQueryVector(ctx, instruction, nextTape, turn),
1745
+ "ExecuteInference": () => handleExecuteInference(ctx, instruction, nextTape, turn),
1746
+ "Finalize": () => handleFinalize(ctx, instruction)
1747
+ };
1748
+ const handler = handlers[instruction.type];
1749
+ return handler ? handler() : Promise.resolve(ctx.rejectWithValue("API returned unknown instruction type"));
1750
+ };
1751
+
1752
+ // src/thunks.ts
1753
+ var extractThunkErrorMessage2 = (e) => multiMatch(e, [
1754
+ [(e2) => typeof e2 === "string", (e2) => e2],
1755
+ [(e2) => !!e2?.data?.message, (e2) => String(e2.data.message)],
1756
+ [(e2) => !!e2?.error, (e2) => String(e2.error)],
1757
+ [(e2) => !!e2?.message, (e2) => String(e2.message)],
1758
+ [_, () => "Protocol processing failed"]
1759
+ ]).getOrElse("Protocol processing failed");
1760
+ var safeDispatch = async (promise) => promise.then((v) => right(v)).catch((e) => left(extractThunkErrorMessage2(e)));
1559
1761
  var processNPC = (0, import_toolkit10.createAsyncThunk)(
1560
1762
  "npc/process",
1561
1763
  async ({ npcId: argNpcId, text, context = {}, apiUrl, apiKey, memory, cortex, persona: argPersona }, { getState, dispatch: dispatch2, rejectWithValue }) => {
1562
1764
  const stateNpcId = selectActiveNpcId(getState());
1563
1765
  const activeNpc = selectActiveNPC(getState());
1564
- const npcId = argNpcId || stateNpcId;
1565
- const persona = argPersona || activeNpc?.persona;
1566
1766
  const currentState = activeNpc?.state || {};
1567
- if (!npcId) {
1568
- return rejectWithValue("No npcId provided and no active NPC selected");
1569
- }
1570
- if (!persona) {
1571
- return rejectWithValue("No persona provided and no active NPC persona available");
1572
- }
1573
- if (!cortex) {
1574
- return rejectWithValue("No local cortex provided. SDK remote cortex fallback is disabled.");
1575
- }
1576
- if (argNpcId && argNpcId !== stateNpcId) {
1577
- dispatch2(setNPCInfo({ id: argNpcId, persona }));
1578
- }
1579
- const directiveId = `${npcId}:${Date.now()}`;
1580
- dispatch2(directiveRunStarted({ id: directiveId, npcId, observation: text }));
1767
+ let directiveId;
1581
1768
  try {
1769
+ const npcId = requireJust(fromNullable(argNpcId || stateNpcId), "No npcId provided and no active NPC selected");
1770
+ const persona = requireJust(fromNullable(argPersona || activeNpc?.persona), "No persona provided and no active NPC persona available");
1771
+ requireJust(fromNullable(cortex), "No local cortex provided. SDK remote cortex fallback is disabled.");
1772
+ if (argNpcId && argNpcId !== stateNpcId) {
1773
+ dispatch2(setNPCInfo({ id: argNpcId, persona }));
1774
+ }
1775
+ directiveId = `${npcId}:${Date.now()}`;
1776
+ dispatch2(directiveRunStarted({ id: directiveId, npcId, observation: text }));
1582
1777
  const initialTape = {
1583
1778
  observation: text,
1584
1779
  context,
@@ -1587,104 +1782,33 @@ var processNPC = (0, import_toolkit10.createAsyncThunk)(
1587
1782
  memories: [],
1588
1783
  vectorQueried: false
1589
1784
  };
1590
- const maxTurns = 12;
1591
- const persistMemoryInstructionsRecursively = async (instructions, index = 0) => {
1592
- if (!memory || index >= instructions.length) {
1593
- return;
1594
- }
1595
- const inst = instructions[index];
1596
- await memory.store(inst.text, inst.type, inst.importance);
1597
- await persistMemoryInstructionsRecursively(instructions, index + 1);
1598
- };
1599
- const runProtocolRecursively = async (tape, lastResult, turn) => {
1600
- if (turn >= maxTurns) {
1601
- return rejectWithValue(`Protocol loop exceeded max turns (${maxTurns})`);
1785
+ const runProtocol = async (tape, lastResult, turn) => {
1786
+ if (turn >= 12) {
1787
+ return rejectWithValue("Protocol loop exceeded max turns (12)");
1602
1788
  }
1603
1789
  const request = { tape, lastResult };
1604
1790
  const processResult = await dispatch2(
1605
- sdkApi.endpoints.postNpcProcess.initiate({ npcId, request, apiUrl, apiKey })
1791
+ api.endpoints.postNpcProcess.initiate({ npcId, request, apiUrl, apiKey })
1606
1792
  ).unwrap();
1607
- const nextTape = processResult.tape;
1608
- const instruction = processResult.instruction;
1609
- if (instruction.type === "IdentifyActor") {
1610
- return runProtocolRecursively(nextTape, {
1611
- type: "IdentifyActorResult",
1612
- actor: {
1613
- npcId,
1614
- persona,
1615
- data: nextTape.npcState
1616
- }
1617
- }, turn + 1);
1618
- }
1619
- if (instruction.type === "QueryVector") {
1620
- dispatch2(directiveReceived({
1621
- id: directiveId,
1622
- response: { memoryRecall: { query: instruction.query, limit: instruction.limit, threshold: instruction.threshold } }
1623
- }));
1624
- if (!memory) {
1625
- return rejectWithValue("API requested memory recall, but no memory engine is configured");
1626
- }
1627
- const recalled = await memory.recall(instruction.query, instruction.limit, instruction.threshold);
1628
- return runProtocolRecursively(nextTape, {
1629
- type: "QueryVectorResult",
1630
- memories: recalled.map((m) => ({ text: m.text, type: m.type, importance: m.importance, similarity: m.similarity }))
1631
- }, turn + 1);
1632
- }
1633
- if (instruction.type === "ExecuteInference") {
1634
- dispatch2(contextComposed({ id: directiveId, prompt: instruction.prompt, constraints: instruction.constraints }));
1635
- const generatedText = await cortex.complete(instruction.prompt, {
1636
- maxTokens: instruction.constraints.maxTokens,
1637
- temperature: instruction.constraints.temperature,
1638
- stop: instruction.constraints.stop
1639
- });
1640
- return runProtocolRecursively(nextTape, {
1641
- type: "ExecuteInferenceResult",
1642
- generatedOutput: generatedText
1643
- }, turn + 1);
1644
- }
1645
- if (instruction.type === "Finalize") {
1646
- const finalize = instruction;
1647
- dispatch2(verdictValidated({
1648
- id: directiveId,
1649
- verdict: {
1650
- valid: finalize.valid,
1651
- signature: finalize.signature,
1652
- memoryStore: finalize.memoryStore,
1653
- stateDelta: finalize.stateTransform,
1654
- action: finalize.action,
1655
- dialogue: finalize.dialogue
1656
- }
1657
- }));
1658
- if (!finalize.valid) {
1659
- dispatch2(blockAction({ id: npcId, reason: finalize.dialogue || "Validation Failed" }));
1660
- return {
1661
- dialogue: finalize.dialogue,
1662
- action: finalize.action,
1663
- thought: finalize.dialogue
1664
- };
1665
- }
1666
- if (finalize.memoryStore?.length && !memory) {
1667
- return rejectWithValue("API returned memoryStore instructions, but no memory engine is configured");
1668
- }
1669
- await persistMemoryInstructionsRecursively(finalize.memoryStore || []);
1670
- if (finalize.stateTransform) {
1671
- dispatch2(updateNPCState({ id: npcId, delta: finalize.stateTransform }));
1672
- }
1673
- dispatch2(setLastAction({ id: npcId, action: finalize.action }));
1674
- dispatch2(addToHistory({ id: npcId, role: "user", content: text }));
1675
- dispatch2(addToHistory({ id: npcId, role: "assistant", content: finalize.dialogue }));
1676
- return {
1677
- dialogue: finalize.dialogue,
1678
- action: finalize.action,
1679
- thought: finalize.dialogue
1680
- };
1681
- }
1682
- return rejectWithValue("API returned unknown instruction type");
1793
+ const ctx = {
1794
+ npcId,
1795
+ persona,
1796
+ text,
1797
+ directiveId,
1798
+ memory,
1799
+ cortex,
1800
+ dispatch: dispatch2,
1801
+ rejectWithValue,
1802
+ recurse: runProtocol
1803
+ };
1804
+ return dispatchInstruction(ctx, processResult.instruction, processResult.tape, turn);
1683
1805
  };
1684
- return runProtocolRecursively(initialTape, void 0, 0);
1806
+ return runProtocol(initialTape, void 0, 0);
1685
1807
  } catch (e) {
1686
1808
  const message = extractThunkErrorMessage2(e);
1687
- dispatch2(directiveRunFailed({ id: directiveId, error: String(message) }));
1809
+ if (directiveId) {
1810
+ dispatch2(directiveRunFailed({ id: directiveId, error: String(message) }));
1811
+ }
1688
1812
  return rejectWithValue(String(message));
1689
1813
  }
1690
1814
  }
@@ -1694,8 +1818,7 @@ var localExportSoulThunk = (0, import_toolkit10.createAsyncThunk)(
1694
1818
  async ({ id, memory }, { getState }) => {
1695
1819
  const state = getState().npc;
1696
1820
  const npcId = id || state.activeNpcId;
1697
- const npc = state.entities[npcId];
1698
- if (!npc) throw new Error(`NPC ${npcId} not found`);
1821
+ const npc = requireJust(fromNullable(state.entities[npcId]), `NPC ${npcId} not found`);
1699
1822
  const memories = memory ? await memory.export() : [];
1700
1823
  return exportToSoul(npcId, "NPC", npc.persona, npc.state, memories);
1701
1824
  }
@@ -1703,77 +1826,99 @@ var localExportSoulThunk = (0, import_toolkit10.createAsyncThunk)(
1703
1826
  var checkApiStatusThunk = (0, import_toolkit10.createAsyncThunk)(
1704
1827
  "system/checkApiStatus",
1705
1828
  async ({ apiUrl }, { dispatch: dispatch2, rejectWithValue }) => {
1706
- try {
1707
- return await dispatch2(sdkApi.endpoints.getApiStatus.initiate({ apiUrl })).unwrap();
1708
- } catch (e) {
1709
- return rejectWithValue(e?.message || "Connection failed");
1710
- }
1829
+ const result = await safeDispatch(dispatch2(api.endpoints.getApiStatus.initiate({ apiUrl })).unwrap());
1830
+ return result.match({
1831
+ left: (e) => rejectWithValue(e),
1832
+ right: (v) => v
1833
+ });
1711
1834
  }
1712
1835
  );
1713
1836
  var listMemoryRemoteThunk = (0, import_toolkit10.createAsyncThunk)(
1714
1837
  "memory/listRemote",
1715
1838
  async ({ npcId, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
1716
- try {
1717
- const data = await dispatch2(sdkApi.endpoints.getMemoryList.initiate({ npcId, apiUrl, apiKey })).unwrap();
1718
- return data || [];
1719
- } catch (e) {
1720
- return rejectWithValue(e?.message || "Failed to list memories");
1721
- }
1839
+ const result = await safeDispatch(dispatch2(api.endpoints.getMemoryList.initiate({ npcId, apiUrl, apiKey })).unwrap());
1840
+ return result.match({
1841
+ left: (e) => rejectWithValue(e),
1842
+ right: (v) => v || []
1843
+ });
1722
1844
  }
1723
1845
  );
1724
1846
  var recallMemoryRemoteThunk = (0, import_toolkit10.createAsyncThunk)(
1725
1847
  "memory/recallRemote",
1726
1848
  async ({ npcId, query, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
1727
- try {
1728
- const data = await dispatch2(
1729
- sdkApi.endpoints.postMemoryRecall.initiate({
1730
- npcId,
1731
- request: { query },
1732
- apiUrl,
1733
- apiKey
1734
- })
1735
- ).unwrap();
1736
- return data || [];
1737
- } catch (e) {
1738
- return rejectWithValue(e?.message || "Failed to recall memories");
1739
- }
1849
+ const result = await safeDispatch(dispatch2(
1850
+ api.endpoints.postMemoryRecall.initiate({ npcId, request: { query }, apiUrl, apiKey })
1851
+ ).unwrap());
1852
+ return result.match({
1853
+ left: (e) => rejectWithValue(e),
1854
+ right: (v) => v || []
1855
+ });
1740
1856
  }
1741
1857
  );
1742
1858
  var storeMemoryRemoteThunk = (0, import_toolkit10.createAsyncThunk)(
1743
1859
  "memory/storeRemote",
1744
1860
  async ({ npcId, observation, importance = 0.8, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
1745
- try {
1746
- return await dispatch2(
1747
- sdkApi.endpoints.postMemoryStore.initiate({
1748
- npcId,
1749
- request: { observation, importance },
1750
- apiUrl,
1751
- apiKey
1752
- })
1753
- ).unwrap();
1754
- } catch (e) {
1755
- return rejectWithValue(e?.message || "Failed to store memory");
1756
- }
1861
+ const result = await safeDispatch(dispatch2(
1862
+ api.endpoints.postMemoryStore.initiate({ npcId, request: { observation, importance }, apiUrl, apiKey })
1863
+ ).unwrap());
1864
+ return result.match({
1865
+ left: (e) => rejectWithValue(e),
1866
+ right: (v) => v
1867
+ });
1757
1868
  }
1758
1869
  );
1759
1870
  var clearMemoryRemoteThunk = (0, import_toolkit10.createAsyncThunk)(
1760
1871
  "memory/clearRemote",
1761
1872
  async ({ npcId, apiUrl, apiKey }, { dispatch: dispatch2, rejectWithValue }) => {
1762
- try {
1763
- return await dispatch2(
1764
- sdkApi.endpoints.deleteMemoryClear.initiate({ npcId, apiUrl, apiKey })
1765
- ).unwrap();
1766
- } catch (e) {
1767
- return rejectWithValue(e?.message || "Failed to clear memories");
1768
- }
1873
+ const result = await safeDispatch(dispatch2(
1874
+ api.endpoints.deleteMemoryClear.initiate({ npcId, apiUrl, apiKey })
1875
+ ).unwrap());
1876
+ return result.match({
1877
+ left: (e) => rejectWithValue(e),
1878
+ right: (v) => v
1879
+ });
1769
1880
  }
1770
1881
  );
1882
+
1883
+ // src/handlers/arweave.ts
1884
+ var handler_ArweaveUpload = async (instruction, maxRetries = 3) => store.dispatch(
1885
+ api.endpoints.postArweaveUpload.initiate({ ...instruction, maxRetries })
1886
+ ).unwrap();
1887
+ var handler_ArweaveDownload = async (instruction) => store.dispatch(
1888
+ api.endpoints.postArweaveDownload.initiate(instruction)
1889
+ ).unwrap();
1890
+
1891
+ // src/configOps.ts
1892
+ var normalizeStatusUrl = (apiUrl) => apiUrl.endsWith("/status") ? apiUrl : `${apiUrl.replace(/\/+$/, "")}/status`;
1893
+ var checkApiConnectivity = async (apiUrl = DEFAULT_API_URL) => {
1894
+ try {
1895
+ const res = await fetch(normalizeStatusUrl(apiUrl), { signal: AbortSignal.timeout(1500) });
1896
+ return res.ok;
1897
+ } catch {
1898
+ return false;
1899
+ }
1900
+ };
1901
+ var resolveReachableApiUrl = async (apiUrl) => {
1902
+ if (apiUrl) return await checkApiConnectivity(apiUrl) ? apiUrl : null;
1903
+ if (await checkApiConnectivity(DEFAULT_API_URL)) return DEFAULT_API_URL;
1904
+ if (await checkApiConnectivity(PRODUCTION_API_URL)) return PRODUCTION_API_URL;
1905
+ return null;
1906
+ };
1907
+ var resolveApiUrlWithFallback = async (apiUrl) => {
1908
+ if (apiUrl) return apiUrl;
1909
+ return await resolveReachableApiUrl() || PRODUCTION_API_URL;
1910
+ };
1771
1911
  // Annotate the CommonJS export names for ESM import in node:
1772
1912
  0 && (module.exports = {
1773
- SDK_VERSION,
1913
+ DEFAULT_API_URL,
1914
+ PRODUCTION_API_URL,
1915
+ VERSION,
1916
+ _,
1774
1917
  addToHistory,
1918
+ api,
1775
1919
  blockAction,
1776
1920
  bridgeSlice,
1921
+ checkApiConnectivity,
1777
1922
  checkApiStatusThunk,
1778
1923
  clearBlock,
1779
1924
  clearBridgeValidation,
@@ -1782,13 +1927,17 @@ var clearMemoryRemoteThunk = (0, import_toolkit10.createAsyncThunk)(
1782
1927
  clearMemoryRemoteThunk,
1783
1928
  clearSoulState,
1784
1929
  completeRemoteThunk,
1930
+ compose,
1785
1931
  contextComposed,
1786
1932
  cortexInitFailed,
1787
1933
  cortexInitStart,
1788
1934
  cortexInitSuccess,
1789
1935
  cortexSlice,
1936
+ createDispatcher,
1790
1937
  createInitialState,
1791
- createSDKStore,
1938
+ createRuntimeRegistry,
1939
+ createRuntimeStore,
1940
+ curry,
1792
1941
  delay,
1793
1942
  deleteRulesetThunk,
1794
1943
  directiveReceived,
@@ -1796,7 +1945,12 @@ var clearMemoryRemoteThunk = (0, import_toolkit10.createAsyncThunk)(
1796
1945
  directiveRunStarted,
1797
1946
  directiveSlice,
1798
1947
  dispatch,
1948
+ ebind,
1949
+ efmap,
1950
+ ematch,
1799
1951
  exportToSoul,
1952
+ fmap,
1953
+ fromNullable,
1800
1954
  generateNPCId,
1801
1955
  getBridgeRulesThunk,
1802
1956
  getGhostHistoryThunk,
@@ -1809,12 +1963,20 @@ var clearMemoryRemoteThunk = (0, import_toolkit10.createAsyncThunk)(
1809
1963
  importNpcFromSoulThunk,
1810
1964
  importSoulFromArweaveThunk,
1811
1965
  initRemoteCortexThunk,
1966
+ isJust,
1967
+ isLeft,
1968
+ isNothing,
1969
+ isRight,
1970
+ just,
1971
+ left,
1812
1972
  listCortexModelsThunk,
1813
1973
  listMemoryRemoteThunk,
1814
1974
  listRulePresetsThunk,
1815
1975
  listRulesetsThunk,
1816
1976
  loadBridgePresetThunk,
1817
1977
  localExportSoulThunk,
1978
+ match,
1979
+ mbind,
1818
1980
  memoise,
1819
1981
  memoiseAsync,
1820
1982
  memoryClear,
@@ -1825,14 +1987,21 @@ var clearMemoryRemoteThunk = (0, import_toolkit10.createAsyncThunk)(
1825
1987
  memoryStoreFailed,
1826
1988
  memoryStoreStart,
1827
1989
  memoryStoreSuccess,
1990
+ multiMatch,
1991
+ nothing,
1828
1992
  npcSlice,
1993
+ orElse,
1829
1994
  pipe,
1830
1995
  processNPC,
1831
1996
  recallMemoryRemoteThunk,
1832
1997
  registerRulesetThunk,
1833
1998
  remoteExportSoulThunk,
1834
1999
  removeNPC,
1835
- sdkApi,
2000
+ requireJust,
2001
+ resolveApiUrl,
2002
+ resolveApiUrlWithFallback,
2003
+ resolveReachableApiUrl,
2004
+ right,
1836
2005
  selectActiveDirective,
1837
2006
  selectActiveDirectiveId,
1838
2007
  selectActiveNPC,