@terminals-tech/sdk 1.0.0-rc.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +15 -19
  2. package/dist/WebContainerManager-4LIOGRVM.js +22 -0
  3. package/dist/browser-http-client-ZQLDWZMU.js +317 -0
  4. package/dist/cache-VKYSQRXX.js +45 -0
  5. package/dist/capabilities-MIPUMBLL.js +96 -0
  6. package/dist/chunk-2ESYSVXG.js +48 -0
  7. package/dist/chunk-2WTYE4SW.js +190 -0
  8. package/dist/chunk-3LFMIVJM.js +40 -0
  9. package/dist/chunk-ABCK4FWN.js +136 -0
  10. package/dist/chunk-AFDUOYHD.js +2060 -0
  11. package/dist/chunk-BCOQMFKT.js +265 -0
  12. package/dist/chunk-BYXBJQAS.js +0 -0
  13. package/dist/chunk-DKFJIILR.js +9798 -0
  14. package/dist/chunk-EXI3LJVJ.js +51 -0
  15. package/dist/chunk-FOXUEYWK.js +42 -0
  16. package/dist/chunk-GJWAJAX3.js +173 -0
  17. package/dist/chunk-H3POJCFA.js +333 -0
  18. package/dist/chunk-KASHT6C5.js +784 -0
  19. package/dist/chunk-KHR7ZYCX.js +4034 -0
  20. package/dist/chunk-L45BSQDJ.js +296 -0
  21. package/dist/chunk-LLGZTP3G.js +5521 -0
  22. package/dist/chunk-NTMBOESX.js +152 -0
  23. package/dist/chunk-OCLSAUCD.js +474 -0
  24. package/dist/chunk-OSSRZOGC.js +190 -0
  25. package/dist/chunk-PPFTKJDB.js +497 -0
  26. package/dist/chunk-PWAHFID5.js +381 -0
  27. package/dist/chunk-Q2VI6ICE.js +188 -0
  28. package/dist/chunk-QJFKEQHF.js +6460 -0
  29. package/dist/chunk-QWXPVB2L.js +320 -0
  30. package/dist/chunk-QWZRZKLZ.js +896 -0
  31. package/dist/chunk-STMI72WH.js +1005 -0
  32. package/dist/chunk-TSQ3BGLA.js +11945 -0
  33. package/dist/chunk-UJDUQNE2.js +79 -0
  34. package/dist/chunk-VZA2NUH3.js +118 -0
  35. package/dist/chunk-WGBCRNMB.js +1817 -0
  36. package/dist/chunk-WU4OTGJE.js +752 -0
  37. package/dist/chunk-XPJ63Y6T.js +70 -0
  38. package/dist/chunk-Y2EULKA2.js +172 -0
  39. package/dist/chunk-YJEZWCYV.js +94 -0
  40. package/dist/chunk-ZVO47SQV.js +150 -0
  41. package/dist/container-lite-QD3CRLS4.js +327 -0
  42. package/dist/core-H2UUDATO.js +146 -0
  43. package/dist/crypto-D4LMI2RN.js +45 -0
  44. package/dist/db-BWC2GGBN.js +50 -0
  45. package/dist/demo-T655Z5S4.js +87 -0
  46. package/dist/diagnostics-6RQTBR6I.js +113 -0
  47. package/dist/dist-OPDCWARF.js +727 -0
  48. package/dist/dist-VXJEKX3T.js +2441 -0
  49. package/dist/dist-VYGJXGUS.js +1008 -0
  50. package/dist/embeddings-7QXTXUMC.js +15 -0
  51. package/dist/embeddings-MAEWWUHW.js +9 -0
  52. package/dist/graph-RKMNE2X5.js +36 -0
  53. package/dist/hvm-CBEP3M4F.js +126 -0
  54. package/dist/index.cjs +49874 -8001
  55. package/dist/index.d.cts +1629 -1363
  56. package/dist/index.d.ts +1629 -1363
  57. package/dist/index.js +2462 -8130
  58. package/dist/mcp-NK34ZNM5.js +101 -0
  59. package/dist/mcp-client-service-browser-SGB2K3VZ.js +14 -0
  60. package/dist/neuro-state-XHRGIRVO.js +498 -0
  61. package/dist/nodes-K6GKI2FM.js +364 -0
  62. package/dist/package-EXUIU2RL.js +93 -0
  63. package/dist/package-VGL7HYTO.js +106 -0
  64. package/dist/package-XHMLOAQ4.js +98 -0
  65. package/dist/pg-events-QJAM2HIP.js +15 -0
  66. package/dist/pglite-adapter-43IOUBMV.js +50 -0
  67. package/dist/pgliteService-IUGNNOVU.js +258 -0
  68. package/dist/policy-IRJCM6FS.js +13 -0
  69. package/dist/registry-5WTDYQVQ.js +26 -0
  70. package/dist/registry-FW63E7FE.js +16 -0
  71. package/dist/registry-ZQ2IBLF6.js +9 -0
  72. package/dist/resolver-ALOJSOK5.js +24 -0
  73. package/dist/scheduler-B5CEYKWT.js +127 -0
  74. package/dist/secret-store-H7273UIT.js +18 -0
  75. package/dist/server-VW6DYDLH.js +18 -0
  76. package/dist/skills-VN7IN7SJ.js +6375 -0
  77. package/dist/stack-4KWCQQP7.js +103 -0
  78. package/dist/storage-L7MWNSPG.js +13 -0
  79. package/dist/supabaseService-6AYP2VY3.js +476 -0
  80. package/dist/topology-CIWWNVAN.js +13 -0
  81. package/dist/webcontainer-XWCE56F3.js +281 -0
  82. package/package.json +9 -3
@@ -0,0 +1,190 @@
1
+ // ../../lib/errors/types.ts
2
+ var ErrorCodes = {
3
+ // Auth errors
4
+ AUTH_TOKEN_EXPIRED: "AUTH_TOKEN_EXPIRED",
5
+ AUTH_TOKEN_REFRESH_FAILED: "AUTH_TOKEN_REFRESH_FAILED",
6
+ AUTH_SESSION_INVALID: "AUTH_SESSION_INVALID",
7
+ AUTH_INIT_RACE: "AUTH_INIT_RACE",
8
+ AUTH_PROVIDER_UNAVAILABLE: "AUTH_PROVIDER_UNAVAILABLE",
9
+ // Inference errors
10
+ INFERENCE_PROVIDER_UNAVAILABLE: "INFERENCE_PROVIDER_UNAVAILABLE",
11
+ INFERENCE_CIRCUIT_OPEN: "INFERENCE_CIRCUIT_OPEN",
12
+ INFERENCE_TIMEOUT: "INFERENCE_TIMEOUT",
13
+ INFERENCE_RATE_LIMITED: "INFERENCE_RATE_LIMITED",
14
+ INFERENCE_API_ERROR: "INFERENCE_API_ERROR",
15
+ // Sync errors
16
+ SYNC_CONFLICT: "SYNC_CONFLICT",
17
+ SYNC_OFFLINE: "SYNC_OFFLINE",
18
+ SYNC_FAILED: "SYNC_FAILED",
19
+ SYNC_LEADER_CHANGED: "SYNC_LEADER_CHANGED",
20
+ // MCP errors
21
+ MCP_CONNECTION_FAILED: "MCP_CONNECTION_FAILED",
22
+ MCP_TOOL_EXECUTION_FAILED: "MCP_TOOL_EXECUTION_FAILED",
23
+ MCP_SERVER_UNAVAILABLE: "MCP_SERVER_UNAVAILABLE",
24
+ // WebContainer errors
25
+ WEBCONTAINER_NOT_SUPPORTED: "WEBCONTAINER_NOT_SUPPORTED",
26
+ WEBCONTAINER_COOP_MISSING: "WEBCONTAINER_COOP_MISSING",
27
+ WEBCONTAINER_BOOT_FAILED: "WEBCONTAINER_BOOT_FAILED",
28
+ WEBCONTAINER_FS_ERROR: "WEBCONTAINER_FS_ERROR",
29
+ // Network errors
30
+ NETWORK_OFFLINE: "NETWORK_OFFLINE",
31
+ NETWORK_TIMEOUT: "NETWORK_TIMEOUT",
32
+ NETWORK_DNS_FAILED: "NETWORK_DNS_FAILED",
33
+ // Storage errors
34
+ STORAGE_QUOTA_EXCEEDED: "STORAGE_QUOTA_EXCEEDED",
35
+ STORAGE_ACCESS_DENIED: "STORAGE_ACCESS_DENIED",
36
+ STORAGE_CORRUPTED: "STORAGE_CORRUPTED",
37
+ // Platform errors
38
+ PLATFORM_STACK_FAILED: "PLATFORM_STACK_FAILED",
39
+ PLATFORM_NODE_FAILED: "PLATFORM_NODE_FAILED",
40
+ PLATFORM_TRAINING_FAILED: "PLATFORM_TRAINING_FAILED",
41
+ PLATFORM_TRAINING_NOT_CONFIGURED: "PLATFORM_TRAINING_NOT_CONFIGURED",
42
+ PLATFORM_TRAINING_UNAUTHORIZED: "PLATFORM_TRAINING_UNAUTHORIZED",
43
+ PLATFORM_TRAINING_OFFLINE: "PLATFORM_TRAINING_OFFLINE",
44
+ PLATFORM_TRAINING_RATE_LIMITED: "PLATFORM_TRAINING_RATE_LIMITED",
45
+ PLATFORM_TRAINING_INVALID_REQUEST: "PLATFORM_TRAINING_INVALID_REQUEST",
46
+ // Generic
47
+ UNKNOWN_ERROR: "UNKNOWN_ERROR",
48
+ RUNAWAY_ERRORS: "RUNAWAY_ERRORS"
49
+ };
50
+ var DEFAULT_ERROR_BUS_CONFIG = {
51
+ dedupWindowMs: 5e3,
52
+ maxErrorsBeforeCutoff: 100,
53
+ retentionMs: 5 * 60 * 1e3,
54
+ maxPerSourcePerMinute: 10,
55
+ cutoffPauseMs: 3e4
56
+ };
57
+
58
+ // ../../lib/errors/base.ts
59
+ var TerminalsError = class _TerminalsError extends Error {
60
+ /** Error source domain */
61
+ source;
62
+ /** Machine-readable error code */
63
+ code;
64
+ /** Error severity level */
65
+ severity;
66
+ /** Whether the operation can be retried */
67
+ retryable;
68
+ /** Whether error should be shown to user */
69
+ userFacing;
70
+ /** Additional context/metadata */
71
+ metadata;
72
+ /** Original error if this wraps another error */
73
+ cause;
74
+ constructor(message, options) {
75
+ super(message);
76
+ this.name = this.constructor.name;
77
+ this.source = options.source;
78
+ this.code = options.code;
79
+ this.severity = options.severity ?? "error";
80
+ this.retryable = options.retryable ?? false;
81
+ this.userFacing = options.userFacing ?? false;
82
+ this.metadata = options.metadata;
83
+ this.cause = options.cause;
84
+ if (Error.captureStackTrace) {
85
+ Error.captureStackTrace(this, this.constructor);
86
+ }
87
+ }
88
+ /**
89
+ * Convert to ErrorInput for error bus emission.
90
+ */
91
+ toErrorInput() {
92
+ return {
93
+ source: this.source,
94
+ severity: this.severity,
95
+ message: this.message,
96
+ code: this.code,
97
+ userFacing: this.userFacing,
98
+ retryable: this.retryable,
99
+ metadata: {
100
+ ...this.metadata,
101
+ errorName: this.name,
102
+ ...this.cause && {
103
+ causeName: this.cause.name,
104
+ causeMessage: this.cause.message
105
+ }
106
+ }
107
+ };
108
+ }
109
+ /**
110
+ * Serialize for logging/transmission.
111
+ */
112
+ toJSON() {
113
+ return {
114
+ name: this.name,
115
+ message: this.message,
116
+ source: this.source,
117
+ code: this.code,
118
+ severity: this.severity,
119
+ retryable: this.retryable,
120
+ userFacing: this.userFacing,
121
+ metadata: this.metadata,
122
+ stack: this.stack,
123
+ cause: this.cause ? { name: this.cause.name, message: this.cause.message } : void 0
124
+ };
125
+ }
126
+ /**
127
+ * Create from an unknown error.
128
+ */
129
+ static fromUnknown(error, source = "unknown") {
130
+ if (error instanceof _TerminalsError) {
131
+ return error;
132
+ }
133
+ if (error instanceof Error) {
134
+ return new _TerminalsError(error.message, {
135
+ source,
136
+ code: ErrorCodes.UNKNOWN_ERROR,
137
+ severity: "error",
138
+ cause: error
139
+ });
140
+ }
141
+ return new _TerminalsError(String(error), {
142
+ source,
143
+ code: ErrorCodes.UNKNOWN_ERROR,
144
+ severity: "error"
145
+ });
146
+ }
147
+ };
148
+ var SyncError = class extends TerminalsError {
149
+ constructor(message, code = ErrorCodes.SYNC_FAILED, metadata) {
150
+ super(message, {
151
+ source: "sync",
152
+ code,
153
+ severity: code === ErrorCodes.SYNC_CONFLICT ? "warn" : "error",
154
+ retryable: code !== ErrorCodes.SYNC_CONFLICT,
155
+ userFacing: code === ErrorCodes.SYNC_OFFLINE,
156
+ metadata
157
+ });
158
+ }
159
+ };
160
+ var MCPError = class extends TerminalsError {
161
+ constructor(message, code = ErrorCodes.MCP_CONNECTION_FAILED, metadata) {
162
+ super(message, {
163
+ source: "mcp",
164
+ code,
165
+ severity: code === ErrorCodes.MCP_SERVER_UNAVAILABLE ? "warn" : "error",
166
+ retryable: code !== ErrorCodes.MCP_TOOL_EXECUTION_FAILED,
167
+ userFacing: true,
168
+ metadata
169
+ });
170
+ }
171
+ };
172
+ var WebContainerError = class extends TerminalsError {
173
+ constructor(message, code = ErrorCodes.WEBCONTAINER_BOOT_FAILED, metadata) {
174
+ super(message, {
175
+ source: "webcontainer",
176
+ code,
177
+ severity: code === ErrorCodes.WEBCONTAINER_NOT_SUPPORTED ? "info" : "error",
178
+ retryable: code === ErrorCodes.WEBCONTAINER_BOOT_FAILED,
179
+ userFacing: true,
180
+ metadata
181
+ });
182
+ }
183
+ };
184
+
185
+ export {
186
+ ErrorCodes,
187
+ SyncError,
188
+ MCPError,
189
+ WebContainerError
190
+ };
@@ -0,0 +1,497 @@
1
+ import {
2
+ BASE_PHASE_LOCKING_VALUE_NODE_ID,
3
+ BASE_RESONANCE_IQ_ENCODE_NODE_ID,
4
+ BASE_RESONANCE_IQ_PHASE_SHIFT_NODE_ID,
5
+ BASE_RESONANCE_METRICS_NODE_ID,
6
+ COMPUTE_BEND_NODE_ID,
7
+ HVM_PROOF_EDGE_CHECK_NODE_ID,
8
+ PROVIDER_CHAT_NODE_ID,
9
+ SYSTEM_SCHEDULE_NODE_ID,
10
+ SYSTEM_SIGNAL_EMIT_NODE_ID,
11
+ executeBendCompute,
12
+ executeHvmProofEdgeCheck,
13
+ executeIqEncode,
14
+ executeIqPhaseShift,
15
+ executePhaseLockingValueNode,
16
+ executeProviderChat,
17
+ executeResonanceMetrics,
18
+ executeSystemSchedule,
19
+ executeSystemSignalEmit
20
+ } from "./chunk-KASHT6C5.js";
21
+
22
+ // ../../lib/types/safe-types.ts
23
+ function isObject(value) {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ }
26
+ function isArray(value) {
27
+ return Array.isArray(value);
28
+ }
29
+ function isString(value) {
30
+ return typeof value === "string";
31
+ }
32
+
33
+ // ../../lib/terminals-tech/machines/core/runners/registry.ts
34
+ var RunnerRegistry = class {
35
+ workerRunners = /* @__PURE__ */ new Map();
36
+ // key: manifest id
37
+ tierRunners = /* @__PURE__ */ new Map();
38
+ // key: tier name
39
+ /**
40
+ * Register a worker runner for a specific node manifest ID.
41
+ *
42
+ * @param manifestId - Node manifest ID (e.g., 'http-fetch')
43
+ * @param fn - Worker runner function
44
+ */
45
+ registerWorker(manifestId, fn) {
46
+ this.workerRunners.set(manifestId, fn);
47
+ }
48
+ /**
49
+ * Retrieve a registered worker runner by manifest ID.
50
+ *
51
+ * @param manifestId - Node manifest ID
52
+ * @returns Worker runner function or null if not found
53
+ */
54
+ getWorker(manifestId) {
55
+ return this.workerRunners.get(manifestId) || null;
56
+ }
57
+ /**
58
+ * Register a generic runner for a runtime tier.
59
+ *
60
+ * @param tier - Runtime tier name (e.g., 'stack', 'webcontainer')
61
+ * @param fn - Runner function for that tier
62
+ */
63
+ registerRunner(tier, fn) {
64
+ this.tierRunners.set(tier, fn);
65
+ }
66
+ /**
67
+ * Retrieve a registered runner for a runtime tier.
68
+ *
69
+ * @param tier - Runtime tier name
70
+ * @returns Runner function or null if not found
71
+ */
72
+ getRunner(tier) {
73
+ return this.tierRunners.get(tier) || null;
74
+ }
75
+ };
76
+ var runners = new RunnerRegistry();
77
+ import("./demo-T655Z5S4.js").catch((err) => console.warn("[RunnerRegistry] demo runner import failed", err));
78
+ import("./stack-4KWCQQP7.js").catch((err) => console.warn("[RunnerRegistry] stack runner import failed", err));
79
+ runners.registerWorker(PROVIDER_CHAT_NODE_ID, async (_m, input, ctx) => {
80
+ const typedInput = input;
81
+ const secrets = typedInput.__secrets || {};
82
+ try {
83
+ const { decrypt } = await import("./crypto-D4LMI2RN.js");
84
+ const { resolveSecretValue } = await import("./secret-store-H7273UIT.js");
85
+ const outSecrets = {};
86
+ for (const [k, v] of Object.entries(secrets)) {
87
+ try {
88
+ const parsed = JSON.parse(String(v));
89
+ if (isObject(parsed) && "iv" in parsed && "ct" in parsed) {
90
+ outSecrets[k] = decrypt(parsed);
91
+ } else {
92
+ outSecrets[k] = String(v);
93
+ }
94
+ } catch {
95
+ outSecrets[k] = String(v);
96
+ }
97
+ }
98
+ const { __secrets: _secrets, ...clean } = typedInput;
99
+ const out = await executeProviderChat(
100
+ clean,
101
+ {
102
+ getSecret: async (ref) => {
103
+ if (ref) {
104
+ const value = await resolveSecretValue(ref, {
105
+ ownerId: ctx.userId || "anonymous",
106
+ stackId: ctx.stackId,
107
+ nodeId: ctx.nodeId,
108
+ appletId: ctx.appletId,
109
+ worldId: ctx.worldId,
110
+ terminalId: ctx.terminalId
111
+ });
112
+ if (value) {
113
+ const resolved = typeof value === "string" ? value : "";
114
+ return { ...outSecrets, [ref]: resolved, apiKey: resolved };
115
+ }
116
+ }
117
+ return outSecrets;
118
+ }
119
+ }
120
+ );
121
+ return out;
122
+ } catch {
123
+ const { __secrets: _secrets, ...clean } = typedInput;
124
+ const out = await executeProviderChat(
125
+ clean,
126
+ {
127
+ getSecret: async (ref) => {
128
+ const secretsRecord = {};
129
+ if (isObject(secrets)) {
130
+ for (const [key, val] of Object.entries(secrets)) {
131
+ secretsRecord[key] = isString(val) ? val : String(val ?? "");
132
+ }
133
+ }
134
+ if (ref) {
135
+ const secretValue = isObject(secrets) ? secrets[ref] : void 0;
136
+ return {
137
+ ...secretsRecord,
138
+ [ref]: isString(secretValue) ? secretValue : String(secretValue ?? "")
139
+ };
140
+ }
141
+ return secretsRecord;
142
+ }
143
+ }
144
+ );
145
+ return out;
146
+ }
147
+ });
148
+ runners.registerWorker("base.time.timeline.v1", async (_m, input) => {
149
+ const mod = await import("./core-H2UUDATO.js");
150
+ const windowVal = isObject(input) && "window" in input && isString(input.window) ? input.window : void 0;
151
+ const tl = mod.makeTimeline(windowVal);
152
+ const eventsVal = isObject(input) && "events" in input ? input.events : void 0;
153
+ const events = isArray(eventsVal) ? eventsVal : [];
154
+ return tl.process(events);
155
+ });
156
+ runners.registerWorker(SYSTEM_SCHEDULE_NODE_ID, async (_m, input, ctx) => {
157
+ return await executeSystemSchedule(input, { stackId: ctx.stackId });
158
+ });
159
+ runners.registerWorker(HVM_PROOF_EDGE_CHECK_NODE_ID, async (_m, input, ctx) => {
160
+ return await executeHvmProofEdgeCheck(input, {
161
+ stackId: ctx.stackId,
162
+ nodeId: ctx.nodeId
163
+ });
164
+ });
165
+ runners.registerWorker(COMPUTE_BEND_NODE_ID, async (_m, input, ctx) => {
166
+ return await executeBendCompute(input, {
167
+ stackId: ctx.stackId,
168
+ nodeId: ctx.nodeId
169
+ });
170
+ });
171
+ runners.registerWorker(SYSTEM_SIGNAL_EMIT_NODE_ID, async (_m, input, ctx) => {
172
+ return await executeSystemSignalEmit(input, {
173
+ stackId: ctx.stackId,
174
+ nodeId: ctx.nodeId
175
+ });
176
+ });
177
+ runners.registerWorker(BASE_RESONANCE_IQ_ENCODE_NODE_ID, async (_m, input) => {
178
+ return await executeIqEncode(input);
179
+ });
180
+ runners.registerWorker(BASE_RESONANCE_IQ_PHASE_SHIFT_NODE_ID, async (_m, input) => {
181
+ return await executeIqPhaseShift(input);
182
+ });
183
+ runners.registerWorker(BASE_RESONANCE_METRICS_NODE_ID, async (_m, input) => {
184
+ return await executeResonanceMetrics(input);
185
+ });
186
+ runners.registerWorker(BASE_PHASE_LOCKING_VALUE_NODE_ID, async (_m, input) => {
187
+ return await executePhaseLockingValueNode(input);
188
+ });
189
+ runners.registerWorker("base.time.memory.v1", async (_m, input) => {
190
+ const mod = await import("./core-H2UUDATO.js");
191
+ return mod.temporalKV().handle(input);
192
+ });
193
+ runners.registerWorker("base.field.store3d.v1", async (_m, input) => {
194
+ const mod = await import("./core-H2UUDATO.js");
195
+ return mod.fieldStore3d().handle(input);
196
+ });
197
+ runners.registerWorker("base.field.projector.v1", async (_m, input) => {
198
+ const emb = await import("./embeddings-MAEWWUHW.js");
199
+ const pointsVal = isObject(input) && "points" in input ? input.points : void 0;
200
+ const points = isArray(pointsVal) ? pointsVal.filter(
201
+ (point) => isObject(point) && typeof point.x === "number" && typeof point.y === "number" && typeof point.z === "number"
202
+ ) : [];
203
+ const modelVal = isObject(input) && "model" in input ? input.model : void 0;
204
+ const model = isString(modelVal) ? modelVal : "default";
205
+ const embeddings = await emb.encodePoints(points, { model });
206
+ return { embeddings };
207
+ });
208
+ runners.registerWorker("base.semantic.zero-agent.v1", async (_m, input) => {
209
+ const mod = await import("./core-H2UUDATO.js");
210
+ return mod.zeroAgent().handle(input);
211
+ });
212
+ runners.registerWorker("base.semantic.entity-graph.v1", async (_m, input) => {
213
+ const g = await import("./graph-RKMNE2X5.js");
214
+ return g.entityGraph().handle(input);
215
+ });
216
+ runners.registerWorker("base.interface.oracle-adapter.v1", async (_m, input, ctx) => {
217
+ const mod = await import("./core-H2UUDATO.js");
218
+ return mod.httpOracle(ctx?.policies).handle(input);
219
+ });
220
+ runners.registerWorker("astro.transform.buildAgentPrompt.v1", async (_m, input) => {
221
+ const questionVal = isObject(input) && "question" in input ? input.question : void 0;
222
+ const q = String(questionVal || "");
223
+ const product = isObject(input) && "product" in input ? input.product : null;
224
+ const record = isObject(input) && "record" in input ? input.record : null;
225
+ const lines = [];
226
+ if (product) lines.push(`Context (product): ${JSON.stringify(product).slice(0, 2e3)}`);
227
+ if (record) lines.push(`Context (record): ${JSON.stringify(record).slice(0, 2e3)}`);
228
+ const prompt = `${lines.join("\n")}
229
+
230
+ Question: ${q}
231
+ Answer with observed facts first, then suggested follow-ups and uncertainties.`;
232
+ return { prompt };
233
+ });
234
+ runners.registerWorker("transform.object.pickPath.v1", async (_m, input) => {
235
+ const objVal = isObject(input) && "object" in input ? input.object : void 0;
236
+ const obj = isObject(objVal) ? objVal : {};
237
+ const pathVal = isObject(input) && "path" in input ? input.path : void 0;
238
+ const path = String(pathVal || "");
239
+ const segs = path.split(".").filter(Boolean);
240
+ let cur = obj;
241
+ for (const s of segs) {
242
+ if (isObject(cur) && s in cur) {
243
+ cur = cur[s];
244
+ } else {
245
+ cur = void 0;
246
+ break;
247
+ }
248
+ }
249
+ return { value: cur };
250
+ });
251
+ if (!runners.getWorker("provider.http.invoke.v1")) {
252
+ runners.registerWorker("provider.http.invoke.v1", async (_m, input, ctx) => {
253
+ const { isNetworkAllowed, requireNetworkApproval } = await import("./policy-IRJCM6FS.js");
254
+ const urlVal = isObject(input) && "url" in input ? input.url : void 0;
255
+ const url = String(urlVal || "");
256
+ const methodVal = isObject(input) && "method" in input ? input.method : void 0;
257
+ const method = String(methodVal || "GET").toUpperCase();
258
+ const headersVal = isObject(input) && "headers" in input ? input.headers : void 0;
259
+ const headers = isObject(headersVal) ? headersVal : {};
260
+ const body = isObject(input) && "body" in input ? input.body : void 0;
261
+ const parseVal = isObject(input) && "parse" in input ? input.parse : void 0;
262
+ const parse = String(parseVal || "json");
263
+ if (!(isNetworkAllowed(ctx?.policies, url) || await requireNetworkApproval(ctx.stackId, ctx.nodeId, ctx?.policies, url))) {
264
+ throw new Error("egress not allowed (approval required)");
265
+ }
266
+ const res = await fetch(url, {
267
+ method,
268
+ headers,
269
+ body: body ? JSON.stringify(body) : void 0
270
+ });
271
+ const text = await res.text();
272
+ if (!res.ok) throw new Error(`http ${res.status}: ${text.slice(0, 256)}`);
273
+ try {
274
+ return parse === "json" ? JSON.parse(text) : { text };
275
+ } catch {
276
+ return { text };
277
+ }
278
+ });
279
+ }
280
+ if (!runners.getWorker("items.pickPreferred.v1")) {
281
+ runners.registerWorker("items.pickPreferred.v1", async (_m, input) => {
282
+ const itemsVal = isObject(input) && "items" in input ? input.items : void 0;
283
+ const items = isArray(itemsVal) ? itemsVal : [];
284
+ const preferVal = isObject(input) && "prefer" in input ? input.prefer : void 0;
285
+ const prefer = isArray(preferVal) ? preferVal : [];
286
+ const typeKeyVal = isObject(input) && "typeKey" in input ? input.typeKey : void 0;
287
+ const typeKey = String(typeKeyVal || "type");
288
+ const groupKeyVal = isObject(input) && "groupKey" in input ? input.groupKey : void 0;
289
+ const groupKey = String(groupKeyVal || "group");
290
+ const key = (p) => {
291
+ if (isObject(p) && typeKey in p) {
292
+ return String(p[typeKey] || "").toLowerCase();
293
+ }
294
+ return "";
295
+ };
296
+ const groups = /* @__PURE__ */ new Map();
297
+ for (const p of items) {
298
+ const id = isObject(p) && groupKey in p ? String(p[groupKey] ?? "group") : "group";
299
+ const arr = groups.get(id) || [];
300
+ arr.push(p);
301
+ groups.set(id, arr);
302
+ }
303
+ const selected = [];
304
+ for (const [, arr] of groups.entries()) {
305
+ let pick = null;
306
+ for (const t of prefer) {
307
+ pick = arr.find((p) => key(p).includes(String(t).toLowerCase()));
308
+ if (pick) break;
309
+ }
310
+ pick = pick || arr[0];
311
+ if (pick) selected.push(pick);
312
+ }
313
+ return { selected };
314
+ });
315
+ }
316
+ if (!runners.getWorker("transform.buildPrompt.v1")) {
317
+ runners.registerWorker("transform.buildPrompt.v1", async (_m, input) => {
318
+ const questionVal = isObject(input) && "question" in input ? input.question : void 0;
319
+ const q = String(questionVal || "");
320
+ const ctxVal = isObject(input) && "context" in input ? input.context : void 0;
321
+ const ctx = isObject(ctxVal) ? ctxVal : {};
322
+ const preview = JSON.stringify(ctx).slice(0, 2e3);
323
+ const prompt = `Context: ${preview}
324
+
325
+ Question: ${q}
326
+ Answer with observed facts first, then follow-ups and uncertainties.`;
327
+ return { prompt };
328
+ });
329
+ }
330
+ if (!runners.getWorker("intel.embedText.v1")) {
331
+ runners.registerWorker("intel.embedText.v1", async (_m, input) => {
332
+ const { encodeTextBatch } = await import("./embeddings-MAEWWUHW.js");
333
+ const textVal = isObject(input) && "text" in input ? input.text : void 0;
334
+ const text = String(textVal || "");
335
+ const [vec] = await encodeTextBatch([text]);
336
+ return { vector: vec };
337
+ });
338
+ }
339
+ runners.registerWorker("intel.llm.http.v1", async (_m, input, ctx) => {
340
+ const { isNetworkAllowed, requireNetworkApproval } = await import("./policy-IRJCM6FS.js");
341
+ const typedInput = input;
342
+ const promptVal = isObject(input) && "prompt" in input ? input.prompt : void 0;
343
+ const prompt = String(promptVal || "");
344
+ const modelVal = isObject(input) && "model" in input ? input.model : void 0;
345
+ const model = String(modelVal || "openrouter/auto");
346
+ const apiKeyVal = isObject(input) && "apiKey" in input ? input.apiKey : void 0;
347
+ const secretsApiKey = isObject(typedInput.__secrets) ? typedInput.__secrets.OPENROUTER_API_KEY : void 0;
348
+ let apiKey = String(apiKeyVal || (isString(secretsApiKey) ? secretsApiKey : "") || "");
349
+ if (!apiKey) {
350
+ try {
351
+ const { resolveSecretValue } = await import("./secret-store-H7273UIT.js");
352
+ const value = await resolveSecretValue("OPENROUTER_API_KEY", {
353
+ ownerId: ctx.userId || "anonymous",
354
+ stackId: ctx.stackId,
355
+ nodeId: ctx.nodeId,
356
+ appletId: ctx.appletId,
357
+ worldId: ctx.worldId,
358
+ terminalId: ctx.terminalId
359
+ });
360
+ if (value) apiKey = value;
361
+ } catch {
362
+ }
363
+ }
364
+ const url = "https://openrouter.ai/api/v1/chat/completions";
365
+ if (!(isNetworkAllowed(ctx?.policies, url) || await requireNetworkApproval(ctx.stackId, ctx.nodeId, ctx?.policies, url))) {
366
+ throw new Error("egress not allowed (approval required)");
367
+ }
368
+ const res = await fetch(url, {
369
+ method: "POST",
370
+ headers: {
371
+ "Content-Type": "application/json",
372
+ ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {}
373
+ },
374
+ body: JSON.stringify({
375
+ model,
376
+ messages: [{ role: "user", content: prompt }],
377
+ stream: false
378
+ })
379
+ });
380
+ const json = await res.json().catch(() => ({ error: "failed to parse" }));
381
+ if (!res.ok) throw new Error(json?.error || `llm http ${res.status}`);
382
+ const text = json?.choices?.[0]?.message?.content || "";
383
+ return {
384
+ text,
385
+ messages: json?.choices?.[0]?.messages || [{ role: "assistant", content: text }]
386
+ };
387
+ });
388
+ runners.registerWorker("integration.source.poll.v1", async (_m, input, ctx) => {
389
+ const { getProvider } = await import("./registry-FW63E7FE.js");
390
+ const providerIdVal = isObject(input) && "provider" in input ? input.provider : void 0;
391
+ const providerId = String(providerIdVal || "");
392
+ const resourceVal = isObject(input) && "resource" in input ? input.resource : void 0;
393
+ const resource = String(resourceVal || "");
394
+ const configVal = isObject(input) && "config" in input ? input.config : void 0;
395
+ const config = isObject(configVal) ? configVal : {};
396
+ const cursorKeyVal = isObject(input) && "cursorKey" in input ? input.cursorKey : void 0;
397
+ const cursorKey = String(cursorKeyVal || `${providerId}:${resource}`);
398
+ const prov = getProvider(providerId);
399
+ if (!prov?.integration) throw new Error(`provider not found: ${providerId}`);
400
+ const secrets = {};
401
+ try {
402
+ const { resolveSecretValue } = await import("./secret-store-H7273UIT.js");
403
+ const names = ["DISCORD_BOT_TOKEN"];
404
+ for (const n of names) {
405
+ const value = await resolveSecretValue(n, {
406
+ ownerId: ctx.userId || "anonymous",
407
+ stackId: ctx.stackId,
408
+ nodeId: ctx.nodeId,
409
+ appletId: ctx.appletId,
410
+ worldId: ctx.worldId,
411
+ terminalId: ctx.terminalId
412
+ });
413
+ if (value) secrets[n] = value;
414
+ }
415
+ } catch {
416
+ }
417
+ const mem = (await import("./core-H2UUDATO.js")).temporalKV();
418
+ const cur = await mem.handle({ get: { key: cursorKey } });
419
+ const cursor = cur?.value ? String(cur.value) : void 0;
420
+ const req = prov.integration.buildRequest("poll", { resource, config, cursor }, secrets);
421
+ const { isNetworkAllowed, requireNetworkApproval } = await import("./policy-IRJCM6FS.js");
422
+ if (!(isNetworkAllowed(ctx?.policies, req.url) || await requireNetworkApproval(ctx.stackId, ctx.nodeId, ctx?.policies, req.url))) {
423
+ throw new Error("egress not allowed (approval required)");
424
+ }
425
+ const res = await fetch(req.url, {
426
+ method: req.method,
427
+ headers: req.headers
428
+ });
429
+ const text = await res.text();
430
+ const raw = req.parse === "json" ? JSON.parse(text) : text;
431
+ const items = prov.integration.toEnvelope(raw, resource);
432
+ const nextCursor = prov.integration.extractCursor && prov.integration.extractCursor(raw, cursor) || cursor || null;
433
+ if (nextCursor && nextCursor !== cursor)
434
+ await mem.handle({ put: { key: cursorKey, value: nextCursor } });
435
+ return { items, cursor: nextCursor };
436
+ });
437
+ runners.registerWorker("integration.sink.post.v1", async (_m, input, ctx) => {
438
+ const { getProvider } = await import("./registry-FW63E7FE.js");
439
+ const providerIdVal = isObject(input) && "provider" in input ? input.provider : void 0;
440
+ const providerId = String(providerIdVal || "");
441
+ const resourceVal = isObject(input) && "resource" in input ? input.resource : void 0;
442
+ const resource = String(resourceVal || "");
443
+ const configVal = isObject(input) && "config" in input ? input.config : void 0;
444
+ const config = isObject(configVal) ? configVal : {};
445
+ const singleItem = isObject(input) && "item" in input ? input.item : void 0;
446
+ const itemsVal = isObject(input) && "items" in input ? input.items : void 0;
447
+ const itemsArray = isArray(itemsVal) ? itemsVal : void 0;
448
+ const items = itemsArray || (singleItem !== void 0 ? [singleItem] : []);
449
+ const prov = getProvider(providerId);
450
+ if (!prov?.integration) throw new Error(`provider not found: ${providerId}`);
451
+ const secrets = {};
452
+ try {
453
+ const { resolveSecretValue } = await import("./secret-store-H7273UIT.js");
454
+ const names = ["DISCORD_BOT_TOKEN"];
455
+ for (const n of names) {
456
+ const value = await resolveSecretValue(n, {
457
+ ownerId: ctx.userId || "anonymous",
458
+ stackId: ctx.stackId,
459
+ nodeId: ctx.nodeId,
460
+ appletId: ctx.appletId,
461
+ worldId: ctx.worldId,
462
+ terminalId: ctx.terminalId
463
+ });
464
+ if (value) secrets[n] = value;
465
+ }
466
+ } catch {
467
+ }
468
+ const { isNetworkAllowed, requireNetworkApproval } = await import("./policy-IRJCM6FS.js");
469
+ let lastStatus = 0;
470
+ let allOk = true;
471
+ for (const it of items) {
472
+ const itemPayload = isObject(it) ? it : { value: it };
473
+ const req = prov.integration.buildRequest(
474
+ "post",
475
+ { resource, config, item: itemPayload },
476
+ secrets
477
+ );
478
+ if (!(isNetworkAllowed(ctx?.policies, req.url) || await requireNetworkApproval(ctx.stackId, ctx.nodeId, ctx?.policies, req.url))) {
479
+ throw new Error("egress not allowed (approval required)");
480
+ }
481
+ const res = await fetch(req.url, {
482
+ method: req.method,
483
+ headers: req.headers,
484
+ body: req.body ? JSON.stringify(req.body) : void 0
485
+ });
486
+ lastStatus = res.status;
487
+ allOk = allOk && res.ok;
488
+ }
489
+ if (items.length === 0) {
490
+ return { ok: true, status: 204 };
491
+ }
492
+ return { ok: allOk, status: lastStatus };
493
+ });
494
+
495
+ export {
496
+ runners
497
+ };