@zero-gravity/zero-gravity 0.0.0-stage → 0.1.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 (73) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +50 -2
  4. package/THIRD-PARTY-NOTICES.md +100 -0
  5. package/dist/adv-context-SLTP32JQ.js +36 -0
  6. package/dist/advanced-EPLZB6DG.js +164 -0
  7. package/dist/agents-JYRQHH7R.js +181 -0
  8. package/dist/chat-AEHVCKXX.js +47 -0
  9. package/dist/chunk-2OH5KHWO.js +112 -0
  10. package/dist/chunk-2ZYSAYMJ.js +108 -0
  11. package/dist/chunk-4BZ4IXTO.js +161 -0
  12. package/dist/chunk-4ITJY25Z.js +144 -0
  13. package/dist/chunk-4JBLZQAQ.js +65 -0
  14. package/dist/chunk-6QLYRU3N.js +28 -0
  15. package/dist/chunk-7TACFVY2.js +57 -0
  16. package/dist/chunk-AY36KJTH.js +3023 -0
  17. package/dist/chunk-BJABQO7S.js +378 -0
  18. package/dist/chunk-C2GFK4JP.js +387 -0
  19. package/dist/chunk-CDC2K2KP.js +47 -0
  20. package/dist/chunk-DKCCXMSE.js +27 -0
  21. package/dist/chunk-FC3UOHOO.js +194 -0
  22. package/dist/chunk-FIASMDLX.js +216 -0
  23. package/dist/chunk-GMVDCQVW.js +88 -0
  24. package/dist/chunk-JQYZX56A.js +231 -0
  25. package/dist/chunk-JU5PGDOD.js +138 -0
  26. package/dist/chunk-JUZP5SXD.js +309 -0
  27. package/dist/chunk-KGA7VWQG.js +70 -0
  28. package/dist/chunk-L7VNR5LM.js +407 -0
  29. package/dist/chunk-LOSXCWHU.js +145 -0
  30. package/dist/chunk-NVC433AX.js +24 -0
  31. package/dist/chunk-QH27MDJM.js +248 -0
  32. package/dist/chunk-QUC5URWQ.js +708 -0
  33. package/dist/chunk-R2CPYTSP.js +31 -0
  34. package/dist/chunk-R5KQACGR.js +2833 -0
  35. package/dist/chunk-R6DONQKN.js +153 -0
  36. package/dist/chunk-RIX4S3J7.js +4747 -0
  37. package/dist/chunk-SZKAZ2VN.js +35 -0
  38. package/dist/chunk-T6DDNE3W.js +1338 -0
  39. package/dist/chunk-U4URD6TU.js +4605 -0
  40. package/dist/chunk-U5UIUB6L.js +51 -0
  41. package/dist/chunk-UMC77TR3.js +79 -0
  42. package/dist/chunk-UQURXFAE.js +80 -0
  43. package/dist/chunk-VBG7T7XY.js +1703 -0
  44. package/dist/chunk-VCCMJIAG.js +326 -0
  45. package/dist/chunk-VS375NYD.js +91 -0
  46. package/dist/chunk-WANZOLI5.js +1073 -0
  47. package/dist/chunk-WUF3TVAE.js +51 -0
  48. package/dist/chunk-XCWLFZSM.js +149 -0
  49. package/dist/chunk-YJEUXO5I.js +76 -0
  50. package/dist/chunk-YR6RCC6Y.js +894 -0
  51. package/dist/chunk-ZQFAX275.js +35 -0
  52. package/dist/config-ELG4FQ3K.js +30 -0
  53. package/dist/config-IEWRCG7R.js +50 -0
  54. package/dist/doctor-ZZC2D3RW.js +357 -0
  55. package/dist/ext-context-RIMZMEPB.js +37 -0
  56. package/dist/index.js +20 -0
  57. package/dist/init-UB3E47KM.js +22 -0
  58. package/dist/integrations-HW4VTLN4.js +183 -0
  59. package/dist/main-RAWWT22W.js +115 -0
  60. package/dist/mcp-SWD4SO35.js +232 -0
  61. package/dist/mcp-context-PM5FY665.js +28 -0
  62. package/dist/memory-QQ54GRCN.js +128 -0
  63. package/dist/memory-session-R6DGT6CS.js +14 -0
  64. package/dist/memory-summary-4P26B2ZY.js +18 -0
  65. package/dist/plugins-VUGTEUNV.js +166 -0
  66. package/dist/providers-O3WOVP5Q.js +417 -0
  67. package/dist/report-DDIZ6BLF.js +28 -0
  68. package/dist/sec-context-VQHW6TOZ.js +15 -0
  69. package/dist/security-SAYW4LU4.js +95 -0
  70. package/dist/sessions-CL6CRNQL.js +160 -0
  71. package/dist/skills-7KDGTTKX.js +126 -0
  72. package/dist/version-6E6A23B3.js +13 -0
  73. package/package.json +70 -4
@@ -0,0 +1,309 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ fail,
4
+ providerError
5
+ } from "./chunk-4ITJY25Z.js";
6
+
7
+ // src/streaming/stream-errors.ts
8
+ var DEFAULT_RETRY_POLICY = { maxAttempts: 3, baseDelayMs: 1e3, maxDelayMs: 3e4 };
9
+ function idleTimeoutError(provider, seconds) {
10
+ return providerError(provider, "timeout", {
11
+ message: `No data was received from the provider for ${seconds}s.`,
12
+ hint: "Check your connection, or raise network.requestTimeoutSeconds for slow or local models."
13
+ });
14
+ }
15
+ function malformedStreamError(provider, detail) {
16
+ return providerError(provider, "malformed-response", { detail });
17
+ }
18
+ function interruptedError(provider) {
19
+ return fail(provider, "stream-interrupted").error;
20
+ }
21
+ function canRetry(error, textEmitted, attempt, policy) {
22
+ if (textEmitted || !error.retryable) return false;
23
+ if (attempt >= policy.maxAttempts) return false;
24
+ if (error.retryAfterSeconds !== void 0 && error.retryAfterSeconds * 1e3 > policy.maxDelayMs) return false;
25
+ return true;
26
+ }
27
+ function retryDelayMs(error, attempt, policy, random = Math.random) {
28
+ if (error.retryAfterSeconds !== void 0) return Math.min(policy.maxDelayMs, Math.max(0, Math.round(error.retryAfterSeconds * 1e3)));
29
+ const base = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (attempt - 1));
30
+ return Math.round(base * (0.8 + 0.4 * random()));
31
+ }
32
+
33
+ // src/streaming/stream-event.ts
34
+ var TERMINAL_EVENT_TYPES = ["stream_complete", "stream_error", "stream_cancelled"];
35
+ function isTerminalEvent(event) {
36
+ return TERMINAL_EVENT_TYPES.includes(event.type);
37
+ }
38
+ var MAX_TOKEN_COUNT = 1e9;
39
+ function validCount(value) {
40
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= MAX_TOKEN_COUNT;
41
+ }
42
+ function validateProviderEvent(value) {
43
+ if (typeof value !== "object" || value === null) return null;
44
+ const e = value;
45
+ switch (e["type"]) {
46
+ case "text":
47
+ return typeof e["text"] === "string" ? { type: "text", text: e["text"] } : null;
48
+ case "usage": {
49
+ const u = e["usage"];
50
+ if (typeof u !== "object" || u === null) return null;
51
+ const r = u;
52
+ const usage = {};
53
+ for (const key of ["inputTokens", "outputTokens", "totalTokens"]) {
54
+ const v = r[key];
55
+ if (v === void 0) continue;
56
+ if (!validCount(v)) return null;
57
+ usage[key] = v;
58
+ }
59
+ return { type: "usage", usage };
60
+ }
61
+ case "error": {
62
+ const err = e["error"];
63
+ if (typeof err !== "object" || err === null) return null;
64
+ const r = err;
65
+ if (typeof r["code"] !== "string" || typeof r["message"] !== "string" || typeof r["provider"] !== "string" || typeof r["retryable"] !== "boolean") return null;
66
+ return { type: "error", error: err };
67
+ }
68
+ case "done": {
69
+ const fr = e["finishReason"];
70
+ if (fr === void 0) return { type: "done" };
71
+ if (fr === "stop" || fr === "length" || fr === "content-filter" || fr === "other") return { type: "done", finishReason: fr };
72
+ return { type: "done" };
73
+ }
74
+ default:
75
+ return null;
76
+ }
77
+ }
78
+ var EventOrder = class {
79
+ #started = false;
80
+ #terminal = false;
81
+ get terminated() {
82
+ return this.#terminal;
83
+ }
84
+ accept(event) {
85
+ if (this.#terminal) return false;
86
+ if (event.type === "stream_start") {
87
+ if (this.#started) return false;
88
+ this.#started = true;
89
+ return true;
90
+ }
91
+ if (!this.#started) return false;
92
+ if (isTerminalEvent(event)) this.#terminal = true;
93
+ return true;
94
+ }
95
+ };
96
+
97
+ // src/streaming/stream-controller.ts
98
+ var StreamController = class {
99
+ #abort = new AbortController();
100
+ #outer;
101
+ #onOuterAbort = () => this.cancel();
102
+ #timer = null;
103
+ #state = "idle";
104
+ #waiter = null;
105
+ #aborted;
106
+ constructor(outer) {
107
+ this.#outer = outer;
108
+ this.#aborted = new Promise((resolve) => {
109
+ this.#waiter = resolve;
110
+ });
111
+ if (outer?.aborted) {
112
+ this.#state = "cancelled";
113
+ this.#abort.abort();
114
+ this.#waiter?.("cancelled");
115
+ } else {
116
+ outer?.addEventListener("abort", this.#onOuterAbort, { once: true });
117
+ this.#state = "active";
118
+ }
119
+ }
120
+ get signal() {
121
+ return this.#abort.signal;
122
+ }
123
+ get state() {
124
+ return this.#state;
125
+ }
126
+ /** Resolves when the request is cancelled or times out. Never rejects. */
127
+ get aborted() {
128
+ return this.#aborted;
129
+ }
130
+ cancel() {
131
+ this.#end("cancelled");
132
+ }
133
+ /** (Re)start the idle timer. Call on every received event. `ms <= 0` disables it. */
134
+ touch(ms) {
135
+ this.#clearTimer();
136
+ if (this.#state !== "active" || ms <= 0) return;
137
+ this.#timer = setTimeout(() => this.#end("timed-out"), ms);
138
+ }
139
+ /** Release the timer and listener. Safe to call more than once. */
140
+ dispose() {
141
+ this.#clearTimer();
142
+ this.#outer?.removeEventListener("abort", this.#onOuterAbort);
143
+ if (this.#state === "active") this.#state = "finished";
144
+ if (!this.#abort.signal.aborted) this.#abort.abort();
145
+ }
146
+ #end(reason) {
147
+ if (this.#state !== "active") return;
148
+ this.#state = reason;
149
+ this.#clearTimer();
150
+ this.#abort.abort();
151
+ this.#waiter?.(reason);
152
+ }
153
+ #clearTimer() {
154
+ if (this.#timer) clearTimeout(this.#timer);
155
+ this.#timer = null;
156
+ }
157
+ };
158
+
159
+ // src/streaming/stream-engine.ts
160
+ var MAX_IGNORED_EVENTS = 20;
161
+ function abortableSleep(ms, signal) {
162
+ return new Promise((resolve) => {
163
+ if (signal.aborted) return resolve();
164
+ const done = () => {
165
+ clearTimeout(timer);
166
+ signal.removeEventListener("abort", done);
167
+ resolve();
168
+ };
169
+ const timer = setTimeout(done, ms);
170
+ signal.addEventListener("abort", done, { once: true });
171
+ });
172
+ }
173
+ async function* streamResponse(backend, messages, request) {
174
+ const policy = request.retry ?? DEFAULT_RETRY_POLICY;
175
+ const now = request.now ?? Date.now;
176
+ const sleep = request.sleep ?? abortableSleep;
177
+ const idleMs = request.idleTimeoutMs ?? 0;
178
+ const order = new EventOrder();
179
+ const started = now();
180
+ const emit = function* (event) {
181
+ if (order.accept(event)) yield event;
182
+ };
183
+ yield* emit({ type: "stream_start", provider: backend.id, model: backend.model, streaming: request.stream });
184
+ let text = "";
185
+ let chunks = 0;
186
+ let ignored = 0;
187
+ let usage;
188
+ const outer = request.signal;
189
+ for (let attempt = 1; ; attempt += 1) {
190
+ const controller = new StreamController(outer);
191
+ try {
192
+ let outcome = { kind: "error", error: interruptedError(backend.id) };
193
+ let iterator;
194
+ let ignoredThisAttempt = 0;
195
+ try {
196
+ if (controller.signal.aborted) {
197
+ outcome = { kind: "cancelled" };
198
+ } else {
199
+ const events = backend.chat(messages, {
200
+ signal: controller.signal,
201
+ stream: request.stream,
202
+ ...request.maxTokens !== void 0 ? { maxTokens: request.maxTokens } : {}
203
+ });
204
+ iterator = events[Symbol.asyncIterator]();
205
+ controller.touch(idleMs);
206
+ read: for (; ; ) {
207
+ const next = await Promise.race([iterator.next(), controller.aborted]);
208
+ if (typeof next === "string") {
209
+ outcome = next === "timed-out" ? { kind: "error", error: idleTimeoutError(backend.id, Math.round(idleMs / 1e3)) } : { kind: "cancelled" };
210
+ break;
211
+ }
212
+ if (next.done) break;
213
+ controller.touch(idleMs);
214
+ const event = validateProviderEvent(next.value);
215
+ if (event === null) {
216
+ ignored += 1;
217
+ ignoredThisAttempt += 1;
218
+ if (ignoredThisAttempt > MAX_IGNORED_EVENTS) {
219
+ outcome = { kind: "error", error: malformedStreamError(backend.id, `more than ${MAX_IGNORED_EVENTS} unrecognised events`) };
220
+ break;
221
+ }
222
+ continue;
223
+ }
224
+ switch (event.type) {
225
+ case "text":
226
+ if (event.text === "") break;
227
+ yield* emit({ type: "text_delta", text: event.text, index: chunks });
228
+ text += event.text;
229
+ chunks += 1;
230
+ break;
231
+ case "usage":
232
+ usage = { ...usage, ...event.usage };
233
+ yield* emit({ type: "usage_update", usage: { ...usage }, estimated: false });
234
+ break;
235
+ case "error":
236
+ outcome = event.error.code === "cancelled" ? { kind: "cancelled" } : { kind: "error", error: event.error };
237
+ break read;
238
+ case "done":
239
+ outcome = { kind: "complete", ...event.finishReason ? { finishReason: event.finishReason } : {} };
240
+ break read;
241
+ }
242
+ }
243
+ }
244
+ } catch (err) {
245
+ outcome = outer?.aborted ? { kind: "cancelled" } : { kind: "error", error: { ...interruptedError(backend.id), detail: err instanceof Error ? err.name : "error" } };
246
+ } finally {
247
+ void iterator?.return?.().catch(() => void 0);
248
+ }
249
+ if (outcome.kind === "complete") {
250
+ yield* emit({
251
+ type: "stream_complete",
252
+ text,
253
+ ...usage ? { usage } : {},
254
+ ...outcome.finishReason ? { finishReason: outcome.finishReason } : {},
255
+ durationMs: Math.max(0, now() - started),
256
+ chunks,
257
+ ignoredEvents: ignored,
258
+ attempts: attempt
259
+ });
260
+ return;
261
+ }
262
+ if (outcome.kind === "cancelled" || outer?.aborted) {
263
+ yield* emit({ type: "stream_cancelled", partialText: text });
264
+ return;
265
+ }
266
+ if (canRetry(outcome.error, chunks > 0, attempt, policy)) {
267
+ const delayMs = retryDelayMs(outcome.error, attempt, policy, request.random);
268
+ yield* emit({ type: "stream_retry", attempt: attempt + 1, maxAttempts: policy.maxAttempts, delayMs, error: outcome.error });
269
+ await sleep(delayMs, outer ?? new AbortController().signal);
270
+ if (outer?.aborted) {
271
+ yield* emit({ type: "stream_cancelled", partialText: text });
272
+ return;
273
+ }
274
+ continue;
275
+ }
276
+ yield* emit({ type: "stream_error", error: outcome.error, partialText: text, attempts: attempt });
277
+ return;
278
+ } finally {
279
+ controller.dispose();
280
+ }
281
+ }
282
+ }
283
+
284
+ // src/chat/engine.ts
285
+ async function runTurn(backend, messages, options) {
286
+ const { onText, onEvent, ...request } = options;
287
+ const retry = request.retry ?? { ...DEFAULT_RETRY_POLICY, maxAttempts: 1 };
288
+ for await (const event of streamResponse(backend, messages, { ...request, retry })) {
289
+ onEvent?.(event);
290
+ switch (event.type) {
291
+ case "text_delta":
292
+ onText?.(event.text);
293
+ break;
294
+ case "stream_complete":
295
+ return { status: "complete", text: event.text, ...event.usage ? { usage: event.usage } : {}, ...event.finishReason ? { finishReason: event.finishReason } : {}, attempts: event.attempts };
296
+ case "stream_error":
297
+ return { status: "failed", error: event.error, partialText: event.partialText, attempts: event.attempts };
298
+ case "stream_cancelled":
299
+ return { status: "cancelled", partialText: event.partialText };
300
+ default:
301
+ break;
302
+ }
303
+ }
304
+ return { status: "cancelled", partialText: "" };
305
+ }
306
+
307
+ export {
308
+ runTurn
309
+ };
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/providers/endpoint.ts
4
+ function isLoopbackHost(hostname) {
5
+ const h = hostname.toLowerCase().replace(/^\[|\]$/g, "");
6
+ if (h === "localhost" || h === "::1") return true;
7
+ return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
8
+ }
9
+ function validateEndpoint(raw, options = {}) {
10
+ const text = raw.trim();
11
+ if (text === "" || text.length > 300) return { ok: false, reason: "endpoint must be a URL of at most 300 characters" };
12
+ let url;
13
+ try {
14
+ url = new URL(text);
15
+ } catch {
16
+ return { ok: false, reason: "that is not a valid URL (example: https://api.example.com/v1)" };
17
+ }
18
+ if (url.protocol !== "https:" && url.protocol !== "http:") return { ok: false, reason: "endpoint must start with https:// (or http:// for localhost)" };
19
+ if (url.username || url.password) return { ok: false, reason: "endpoint must not contain a username or password; keys belong in an environment variable" };
20
+ if (url.search || url.hash) return { ok: false, reason: "endpoint must not contain a query string or fragment" };
21
+ if (url.protocol === "http:" && !isLoopbackHost(url.hostname) && !options.allowInsecureHttp) {
22
+ return {
23
+ ok: false,
24
+ reason: "remote endpoints must use https:// so credentials are encrypted in transit (plain http is allowed for localhost only; set ZG_ALLOW_INSECURE_HTTP=1 to override for a trusted network)"
25
+ };
26
+ }
27
+ return { ok: true, value: `${url.origin}${url.pathname.replace(/\/+$/, "")}` };
28
+ }
29
+ var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
30
+ var RESERVED_ENV_VARS = /* @__PURE__ */ new Set([
31
+ "OPENAI_API_KEY",
32
+ "ANTHROPIC_API_KEY",
33
+ "GEMINI_API_KEY",
34
+ "GOOGLE_API_KEY",
35
+ "OLLAMA_API_KEY"
36
+ ]);
37
+ function validateEnvVarName(raw, opts = {}) {
38
+ const name = raw.trim();
39
+ if (!ENV_NAME.test(name)) {
40
+ return { ok: false, reason: "must be an environment variable NAME such as MY_PROVIDER_API_KEY (letters, digits, underscore). Never paste the key itself." };
41
+ }
42
+ if (!opts.allowReserved && RESERVED_ENV_VARS.has(name.toUpperCase())) {
43
+ return { ok: false, reason: `${name} belongs to a built-in provider; use a different variable for a custom endpoint so that key is never sent to another host` };
44
+ }
45
+ return { ok: true, value: name };
46
+ }
47
+ var MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}$/;
48
+ function validateModelId(raw) {
49
+ const id = raw.trim();
50
+ if (!MODEL_ID.test(id)) {
51
+ return { ok: false, reason: "that is not a valid model identifier (letters, digits and . _ : / @ + - only, up to 128 characters)" };
52
+ }
53
+ return { ok: true, value: id };
54
+ }
55
+ function validateDisplayName(raw) {
56
+ const name = raw.trim();
57
+ if (name === "" || name.length > 60) return { ok: false, reason: "display name must be 1 to 60 characters" };
58
+ for (const ch of name) {
59
+ const code = ch.codePointAt(0) ?? 0;
60
+ if (code < 32 || code >= 127 && code <= 159) return { ok: false, reason: "display name must not contain control characters" };
61
+ }
62
+ return { ok: true, value: name };
63
+ }
64
+
65
+ export {
66
+ validateEndpoint,
67
+ validateEnvVarName,
68
+ validateModelId,
69
+ validateDisplayName
70
+ };