@graview/tools 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 (111) hide show
  1. package/LICENSE +96 -0
  2. package/README.md +47 -0
  3. package/dist/agent/adapters.d.ts +43 -0
  4. package/dist/agent/adapters.d.ts.map +1 -0
  5. package/dist/agent/adapters.js +52 -0
  6. package/dist/agent/adapters.js.map +1 -0
  7. package/dist/agent/tools.d.ts +105 -0
  8. package/dist/agent/tools.d.ts.map +1 -0
  9. package/dist/agent/tools.js +311 -0
  10. package/dist/agent/tools.js.map +1 -0
  11. package/dist/cli.d.ts +37 -0
  12. package/dist/cli.d.ts.map +1 -0
  13. package/dist/cli.js +306 -0
  14. package/dist/cli.js.map +1 -0
  15. package/dist/conversation.d.ts +108 -0
  16. package/dist/conversation.d.ts.map +1 -0
  17. package/dist/conversation.js +698 -0
  18. package/dist/conversation.js.map +1 -0
  19. package/dist/decide.d.ts +43 -0
  20. package/dist/decide.d.ts.map +1 -0
  21. package/dist/decide.js +125 -0
  22. package/dist/decide.js.map +1 -0
  23. package/dist/derive.d.ts +84 -0
  24. package/dist/derive.d.ts.map +1 -0
  25. package/dist/derive.js +302 -0
  26. package/dist/derive.js.map +1 -0
  27. package/dist/edit.d.ts +70 -0
  28. package/dist/edit.d.ts.map +1 -0
  29. package/dist/edit.js +97 -0
  30. package/dist/edit.js.map +1 -0
  31. package/dist/figure.d.ts +53 -0
  32. package/dist/figure.d.ts.map +1 -0
  33. package/dist/figure.js +86 -0
  34. package/dist/figure.js.map +1 -0
  35. package/dist/index.d.ts +44 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +31 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/intelligence.d.ts +132 -0
  40. package/dist/intelligence.d.ts.map +1 -0
  41. package/dist/intelligence.js +463 -0
  42. package/dist/intelligence.js.map +1 -0
  43. package/dist/local.d.ts +192 -0
  44. package/dist/local.d.ts.map +1 -0
  45. package/dist/local.js +365 -0
  46. package/dist/local.js.map +1 -0
  47. package/dist/loop.d.ts +84 -0
  48. package/dist/loop.d.ts.map +1 -0
  49. package/dist/loop.js +173 -0
  50. package/dist/loop.js.map +1 -0
  51. package/dist/mcp-stdio.d.ts +38 -0
  52. package/dist/mcp-stdio.d.ts.map +1 -0
  53. package/dist/mcp-stdio.js +83 -0
  54. package/dist/mcp-stdio.js.map +1 -0
  55. package/dist/pins.d.ts +29 -0
  56. package/dist/pins.d.ts.map +1 -0
  57. package/dist/pins.js +60 -0
  58. package/dist/pins.js.map +1 -0
  59. package/dist/plan.d.ts +150 -0
  60. package/dist/plan.d.ts.map +1 -0
  61. package/dist/plan.js +303 -0
  62. package/dist/plan.js.map +1 -0
  63. package/dist/providers/insight.d.ts +14 -0
  64. package/dist/providers/insight.d.ts.map +1 -0
  65. package/dist/providers/insight.js +81 -0
  66. package/dist/providers/insight.js.map +1 -0
  67. package/dist/providers/invariant.d.ts +14 -0
  68. package/dist/providers/invariant.d.ts.map +1 -0
  69. package/dist/providers/invariant.js +123 -0
  70. package/dist/providers/invariant.js.map +1 -0
  71. package/dist/providers/jev.d.ts +115 -0
  72. package/dist/providers/jev.d.ts.map +1 -0
  73. package/dist/providers/jev.js +148 -0
  74. package/dist/providers/jev.js.map +1 -0
  75. package/dist/providers/lens.d.ts +24 -0
  76. package/dist/providers/lens.d.ts.map +1 -0
  77. package/dist/providers/lens.js +36 -0
  78. package/dist/providers/lens.js.map +1 -0
  79. package/dist/providers/llm.d.ts +25 -0
  80. package/dist/providers/llm.d.ts.map +1 -0
  81. package/dist/providers/llm.js +44 -0
  82. package/dist/providers/llm.js.map +1 -0
  83. package/dist/providers/schema.d.ts +12 -0
  84. package/dist/providers/schema.d.ts.map +1 -0
  85. package/dist/providers/schema.js +508 -0
  86. package/dist/providers/schema.js.map +1 -0
  87. package/dist/providers/structure.d.ts +14 -0
  88. package/dist/providers/structure.d.ts.map +1 -0
  89. package/dist/providers/structure.js +211 -0
  90. package/dist/providers/structure.js.map +1 -0
  91. package/dist/questions.d.ts +162 -0
  92. package/dist/questions.d.ts.map +1 -0
  93. package/dist/questions.js +316 -0
  94. package/dist/questions.js.map +1 -0
  95. package/dist/run.d.ts +202 -0
  96. package/dist/run.d.ts.map +1 -0
  97. package/dist/run.js +453 -0
  98. package/dist/run.js.map +1 -0
  99. package/dist/space.d.ts +50 -0
  100. package/dist/space.d.ts.map +1 -0
  101. package/dist/space.js +55 -0
  102. package/dist/space.js.map +1 -0
  103. package/dist/types.d.ts +122 -0
  104. package/dist/types.d.ts.map +1 -0
  105. package/dist/types.js +2 -0
  106. package/dist/types.js.map +1 -0
  107. package/dist/usage.d.ts +10 -0
  108. package/dist/usage.d.ts.map +1 -0
  109. package/dist/usage.js +59 -0
  110. package/dist/usage.js.map +1 -0
  111. package/package.json +61 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local.d.ts","sourceRoot":"","sources":["../src/local.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,KAAK,SAAS,EAAE,KAAK,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAClG,OAAO,EAAgD,KAAK,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEjG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAa,KAAK,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5D;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,MAAM,kBAAkB,GAAG,OAAO,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,CAAC;AAE3E,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,MAAM,EAAE,kBAAkB,CAAC;IACpC,QAAQ,CAAC,KAAK,CAAC,EAAE;QACf,yEAAyE;QACzE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;KACzB,CAAC;IACF;;;;;;OAMG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE;QAClB,QAAQ,CAAC,MAAM,CAAC,E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kB,EAC1B,KAAK,GAAE;IAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,IAAI,CAAA;CAAO,GAChE,MAAM,GAAG,SAAS,CASpB;AAMD,sEAAsE;AACtE,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,kBAAkB,GAAG,MAAM,CASvE"}
package/dist/local.js ADDED
@@ -0,0 +1,365 @@
1
+ import { DECISION_BRIDGE_PATH } from "@graview/core";
2
+ import { graphResponder, llmResponder } from "./conversation.js";
3
+ import { completionDecide } from "./decide.js";
4
+ import { jevDecide } from "./providers/jev.js";
5
+ export const DEFAULT_INTELLIGENCE = { source: "graph" };
6
+ /**
7
+ * FOUR RUNGS, TWO AXES. Each rung says which capabilities it serves; a
8
+ * surface asks for a capability, never for a rung; and what the chosen
9
+ * rung cannot serve falls DOWN to the graph, which is keyless and always
10
+ * there. Pretending the ladder has one axis is how a switch starts lying:
11
+ * a decision provider is the best rung for a decision and no rung at all
12
+ * for prose.
13
+ */
14
+ export const RUNGS = {
15
+ graph: { label: "Graph only", serves: ["decide", "propose"] },
16
+ local: { label: "Onboard AI", serves: ["prose", "decide", "propose"] },
17
+ decision: { label: "Jev", serves: ["decide"] },
18
+ remote: { label: "LLM", serves: ["prose", "decide", "propose"] },
19
+ };
20
+ /**
21
+ * Which rung answers a capability under this config: the chosen one when
22
+ * it serves the capability, the graph otherwise — with `fell` saying so,
23
+ * which is what a seat's honesty sentence is made of.
24
+ */
25
+ export function rungFor(config, capability) {
26
+ if (RUNGS[config.source].serves.includes(capability))
27
+ return { rung: config.source, fell: false };
28
+ return { rung: "graph", fell: true };
29
+ }
30
+ /** The sentence a seat says on a rung that cannot talk. Part of the answer, not chrome. */
31
+ export function rungHonesty(config, capability) {
32
+ const { fell } = rungFor(config, capability);
33
+ if (!fell)
34
+ return undefined;
35
+ const rung = RUNGS[config.source].label;
36
+ return capability === "prose"
37
+ ? `(${rung} decides rather than talks — the graph is answering here.)`
38
+ : `(${rung} cannot ${capability} — the graph is answering here.)`;
39
+ }
40
+ const STORED = "graview:intelligence";
41
+ /** The saved rung, or the keyless default — never a throw. */
42
+ export function loadIntelligenceConfig() {
43
+ try {
44
+ const raw = globalThis.localStorage?.getItem(STORED);
45
+ if (!raw)
46
+ return DEFAULT_INTELLIGENCE;
47
+ const parsed = JSON.parse(raw);
48
+ if (parsed.source in RUNGS)
49
+ return parsed;
50
+ return DEFAULT_INTELLIGENCE;
51
+ }
52
+ catch {
53
+ return DEFAULT_INTELLIGENCE;
54
+ }
55
+ }
56
+ export function saveIntelligenceConfig(config) {
57
+ try {
58
+ globalThis.localStorage?.setItem(STORED, JSON.stringify(config));
59
+ }
60
+ catch {
61
+ // A rung that cannot be remembered still applies for this visit.
62
+ }
63
+ }
64
+ /* ------------------------------------------------------------- adapters */
65
+ const XAI_BASE = "https://api.x.ai/v1";
66
+ const XAI_DEFAULT_MODEL = "grok-4-fast";
67
+ /**
68
+ * Any OpenAI-compatible /chat/completions endpoint as one Completion.
69
+ * The call goes STRAIGHT from the browser to the provider — the key is
70
+ * sent nowhere else, and there is no relay to trust.
71
+ */
72
+ export function openAiCompatibleCompletion(options) {
73
+ const call = options.fetch ?? globalThis.fetch;
74
+ return async (prompt) => {
75
+ const response = await call(`${options.baseUrl.replace(/\/$/, "")}/chat/completions`, {
76
+ method: "POST",
77
+ headers: {
78
+ "content-type": "application/json",
79
+ authorization: `Bearer ${options.apiKey}`,
80
+ },
81
+ body: JSON.stringify({
82
+ model: options.model,
83
+ messages: [{ role: "user", content: prompt }],
84
+ }),
85
+ // A hung provider must not hang the conversation: the floor answers.
86
+ ...(typeof AbortSignal !== "undefined" && "timeout" in AbortSignal
87
+ ? { signal: AbortSignal.timeout(45_000) }
88
+ : {}),
89
+ });
90
+ if (!response.ok) {
91
+ throw new Error(`${options.model} answered ${response.status}: ${(await response.text()).slice(0, 160)}`);
92
+ }
93
+ const parsed = (await response.json());
94
+ const content = parsed.choices?.[0]?.message?.content;
95
+ if (typeof content !== "string")
96
+ throw new Error(`${options.model} answered with no content`);
97
+ return content;
98
+ };
99
+ }
100
+ /** xAI's Grok, as a preset of the same shape. */
101
+ export function xaiCompletion(options) {
102
+ return openAiCompatibleCompletion({
103
+ baseUrl: XAI_BASE,
104
+ apiKey: options.apiKey,
105
+ model: options.model ?? XAI_DEFAULT_MODEL,
106
+ ...(options.fetch ? { fetch: options.fetch } : {}),
107
+ });
108
+ }
109
+ const WEBLLM_DEFAULT_MODEL = "Llama-3.2-3B-Instruct-q4f16_1-MLC";
110
+ /**
111
+ * A model in the browser, warmed lazily and NEVER on the critical path.
112
+ *
113
+ * The weights are on the order of a couple of gigabytes, fetched once and
114
+ * cached by the browser; until they are warm the chat answers from the
115
+ * graph. WebLLM arrives by dynamic import at the moment someone turns the
116
+ * rung on — it is not a build dependency, because most installs never
117
+ * will. Chrome's built-in Prompt API is used first where it exists: no
118
+ * download at all.
119
+ */
120
+ /*
121
+ * ONE ENGINE PER MODEL, module-wide. Rebuilding the responder (a settings
122
+ * save, a re-render) must not drop a two-gigabyte engine and warm a new
123
+ * one — and a bring-up that failed stays failed rather than re-downloading
124
+ * on every turn; a page reload is the retry.
125
+ */
126
+ const ENGINES = new Map();
127
+ export function localCompletion(options = {}) {
128
+ const cacheKey = options.load ? null : (options.model ?? WEBLLM_DEFAULT_MODEL);
129
+ const held = cacheKey
130
+ ? (ENGINES.get(cacheKey) ?? ENGINES.set(cacheKey, { engine: null, failed: null }).get(cacheKey))
131
+ : { engine: null, failed: null };
132
+ let engine = held.engine;
133
+ let warming = false;
134
+ const say = (status) => options.onStatus?.(status);
135
+ const bringUp = async () => {
136
+ if (options.load)
137
+ return options.load();
138
+ // Chrome's built-in model first: zero download, no WebGPU contention.
139
+ const prompt = globalThis
140
+ .LanguageModel;
141
+ if (prompt) {
142
+ const session = await prompt.create();
143
+ return {
144
+ chat: {
145
+ completions: {
146
+ create: async ({ messages }) => ({
147
+ choices: [
148
+ { message: { content: await session.prompt(messages[messages.length - 1]?.content ?? "") } },
149
+ ],
150
+ }),
151
+ },
152
+ },
153
+ };
154
+ }
155
+ /*
156
+ * CAPABILITY GATING, STATED. WebLLM needs WebGPU; without it the
157
+ * engine would download megabytes of loader only to fail obscurely.
158
+ * Failing here, first, is what lets the chat header say WHY the rung
159
+ * is unavailable in this browser rather than shrugging — and the
160
+ * graph floor answers either way.
161
+ */
162
+ if (!globalThis.navigator?.gpu) {
163
+ throw new Error("this browser has no WebGPU, which the local model needs");
164
+ }
165
+ const url = "https://esm.run/@mlc-ai/web-llm";
166
+ const webllm = (await import(/* @vite-ignore */ url));
167
+ return webllm.CreateMLCEngine(options.model ?? WEBLLM_DEFAULT_MODEL, {
168
+ initProgressCallback: (report) => say({ state: "warming", progress: report.progress, detail: report.text }),
169
+ });
170
+ };
171
+ const warm = () => {
172
+ engine = held.engine ?? engine;
173
+ if (engine || warming)
174
+ return;
175
+ if (held.failed !== null) {
176
+ say({ state: "failed", detail: held.failed });
177
+ return;
178
+ }
179
+ warming = true;
180
+ say({ state: "warming" });
181
+ void bringUp()
182
+ .then((ready) => {
183
+ engine = ready;
184
+ held.engine = ready;
185
+ say({ state: "ready" });
186
+ })
187
+ .catch((error) => {
188
+ held.failed = error instanceof Error ? error.message : String(error);
189
+ say({ state: "failed", detail: held.failed });
190
+ })
191
+ .finally(() => {
192
+ warming = false;
193
+ });
194
+ };
195
+ const complete = async (prompt) => {
196
+ engine = held.engine ?? engine;
197
+ if (!engine)
198
+ throw new Error("The local model is not warm yet");
199
+ const answer = await engine.chat.completions.create({
200
+ messages: [{ role: "user", content: prompt }],
201
+ });
202
+ const content = answer.choices?.[0]?.message?.content;
203
+ if (typeof content !== "string")
204
+ throw new Error("The local model answered with no content");
205
+ return content;
206
+ };
207
+ return { complete, ready: () => (held.engine ?? engine) !== null, warm };
208
+ }
209
+ /* ------------------------------------------------------ the whole ladder */
210
+ /**
211
+ * THE MODEL BEHIND A RUNG, when the person has chosen one.
212
+ *
213
+ * A conversation is not the only thing a model is good for: drawing a
214
+ * kind's figure is one prompt and one answer, judged by the checker's own
215
+ * function. Both reach the same configured provider through this, so there
216
+ * is one place a key is read and one place a rung is honoured — and a
217
+ * keyless config answers `undefined` rather than a completion that throws,
218
+ * so a caller can say what it will do INSTEAD of drawing.
219
+ */
220
+ export function completionFor(config, hooks = {}) {
221
+ if (config.source === "remote" && config.remote?.apiKey) {
222
+ const model = config.remote.model ?? (config.remote.preset === "custom" ? "a model" : XAI_DEFAULT_MODEL);
223
+ return config.remote.preset === "custom" && config.remote.baseUrl
224
+ ? openAiCompatibleCompletion({ baseUrl: config.remote.baseUrl, apiKey: config.remote.apiKey, model })
225
+ : xaiCompletion({ apiKey: config.remote.apiKey, ...(config.remote.model ? { model: config.remote.model } : {}) });
226
+ }
227
+ if (config.source === "local") {
228
+ const local = localCompletion({
229
+ ...(config.local?.model ? { model: config.local.model } : {}),
230
+ ...(hooks.onStatus ? { onStatus: hooks.onStatus } : {}),
231
+ });
232
+ /*
233
+ * A cold engine is warmed rather than refused: the first ask pays for
234
+ * the bring-up, and `complete` throws while it is cold — which the
235
+ * callers already treat as "say what happened instead", never as a
236
+ * silent failure.
237
+ */
238
+ if (!local.ready())
239
+ local.warm();
240
+ return local.complete;
241
+ }
242
+ return undefined;
243
+ }
244
+ /**
245
+ * One Responder from one config. The graph is always the floor: a remote
246
+ * failure or a cold local model answers from the graph WITH A NOTE rather
247
+ * than failing the conversation — a chat that errors where it could have
248
+ * answered is worse than either rung alone.
249
+ */
250
+ export function configuredResponder(config, hooks = {}) {
251
+ const floor = hooks.floor ?? graphResponder();
252
+ const built = config.source;
253
+ const switched = (reply) => {
254
+ const now = hooks.current?.();
255
+ if (!now || now.source === built)
256
+ return reply;
257
+ return note(reply, `(answered on the ${RUNGS[built].label} rung — you switched to ${RUNGS[now.source].label} meanwhile.)`);
258
+ };
259
+ const honest = (responder) => async (store, text, context) => switched(await responder(store, text, context));
260
+ /*
261
+ * GROUNDED FACTS OUTRANK ANY MODEL. Whatever rung is chosen, a question
262
+ * the graph can answer from its own structure — a standing, a named
263
+ * thing, a who or a when — is answered by the graph: a small local model
264
+ * asked "who can play left back" will fluently invent a goalkeeper, and
265
+ * no rung is allowed to replace a fact with a guess about the same fact.
266
+ *
267
+ * A READING OF A CHANGE IS NOT A FACT, and treating it as one was the
268
+ * ladder shutting the model out of the only thing it is better at.
269
+ * Speaking a change loosely — "add details to Meal, the name of the food
270
+ * and the number of people it can feed" — is two fields in one sentence,
271
+ * and a pattern-matcher can only ever see one of them. So the floor's
272
+ * reading goes UP to the model as a starting point: keep it, correct it,
273
+ * or split it. What the model may not do is come back with less: an
274
+ * answer with no proposals never replaces a reading that had them.
275
+ */
276
+ const groundedFirst = (modelled, name) => async (store, text, context) => {
277
+ const known = await floor(store, text, context);
278
+ if (known.grounded)
279
+ return note(known, "(from the graph)");
280
+ try {
281
+ const answered = await modelled(store, text, {
282
+ ...context,
283
+ ...(known.proposals.length > 0 ? { reading: known.proposals } : {}),
284
+ });
285
+ if (answered.proposals.length === 0 && known.proposals.length > 0) {
286
+ return note(known, "(from the graph)");
287
+ }
288
+ return answered;
289
+ }
290
+ catch (error) {
291
+ return note(known, `(${name} did not answer — ${error instanceof Error ? error.message : String(error)}. The graph answered instead.)`);
292
+ }
293
+ };
294
+ if (config.source === "remote" && config.remote?.apiKey) {
295
+ const model = config.remote.model ?? (config.remote.preset === "custom" ? "a model" : XAI_DEFAULT_MODEL);
296
+ const complete = completionFor(config);
297
+ if (complete)
298
+ return honest(groundedFirst(llmResponder({ complete }), model));
299
+ }
300
+ /*
301
+ * THE RUNG THAT SAYS WHAT IT CANNOT DO. A decision provider has no prose,
302
+ * so the conversation is the graph's — and the seat SAYS so, in the
303
+ * answer itself, so every surface the seat speaks from carries the
304
+ * sentence unchanged: the chat panel now, a figure's bubble later. The
305
+ * same honesty the seat shows when it is refused an act.
306
+ */
307
+ if (config.source === "decision") {
308
+ const why = rungHonesty(config, "prose");
309
+ return honest(async (store, text, context) => note(await floor(store, text, context), why));
310
+ }
311
+ if (config.source === "local") {
312
+ const local = localCompletion({
313
+ ...(config.local?.model ? { model: config.local.model } : {}),
314
+ ...(hooks.onStatus ? { onStatus: hooks.onStatus } : {}),
315
+ });
316
+ const modelled = groundedFirst(llmResponder({ complete: local.complete }), "the local model");
317
+ return honest(async (store, text, context) => {
318
+ if (!local.ready()) {
319
+ local.warm();
320
+ const answered = await floor(store, text, context);
321
+ return answered.grounded
322
+ ? note(answered, "(from the graph)")
323
+ : note(answered, "(the local model is warming — the graph answered meanwhile)");
324
+ }
325
+ return modelled(store, text, context);
326
+ });
327
+ }
328
+ return honest(floor);
329
+ }
330
+ /**
331
+ * THE DECISION BEHIND A RUNG, for a surface that asks for one — a field
332
+ * that wants filling, a matrix that wants judging. On the decision rung
333
+ * it is the provider exactly, by the person's key or through the dev
334
+ * server's door; on a model rung it is the model with the parse-and-refuse
335
+ * layer behind it; on the graph rung it is nothing here, because the
336
+ * graph decides by its own rules and needs the store to do it
337
+ * (`graphDecide`). A surface holding `undefined` falls down to that.
338
+ */
339
+ export function decideFor(config, hooks = {}) {
340
+ if (config.source === "decision") {
341
+ const decision = config.decision ?? {};
342
+ return decision.apiKey
343
+ ? jevDecide({ apiKey: decision.apiKey, ...(decision.model ? { model: decision.model } : {}) })
344
+ : jevDecide({ baseUrl: decision.bridge ?? DECISION_BRIDGE_PATH, ...(decision.model ? { model: decision.model } : {}) });
345
+ }
346
+ const complete = completionFor(config, hooks);
347
+ return complete ? completionDecide(complete) : undefined;
348
+ }
349
+ function note(reply, added) {
350
+ return { ...reply, say: `${reply.say} ${added}` };
351
+ }
352
+ /** A word for the header: where answers are coming from right now. */
353
+ export function describeIntelligence(config) {
354
+ if (config.source === "remote" && config.remote?.apiKey) {
355
+ return config.remote.preset === "custom"
356
+ ? (config.remote.model ?? "custom model")
357
+ : (config.remote.model ?? XAI_DEFAULT_MODEL);
358
+ }
359
+ if (config.source === "local")
360
+ return "on-device";
361
+ if (config.source === "decision")
362
+ return `${config.decision?.model ?? "jev"} — decides; the graph talks`;
363
+ return "graph-native";
364
+ }
365
+ //# sourceMappingURL=local.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local.js","sourceRoot":"","sources":["../src/local.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAA+C,MAAM,eAAe,CAAC;AAClG,OAAO,EAAE,cAAc,EAAE,YAAY,EAAkC,MAAM,mBAAmB,CAAC;AACjG,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAAE,SAAS,EAAe,MAAM,oBAAoB,CAAC;AAiD5D,MAAM,CAAC,MAAM,oBAAoB,GAAuB,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AAE5E;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,KAAK,GAEd;IACF,KAAK,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC,EAAE;IAC7D,KAAK,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS,CAAC,EAAE;IACtE,QAAQ,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE;IAC9C,MAAM,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,SAAS,CAAC,EAAE;CACjE,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,OAAO,CACrB,MAA0B,EAC1B,UAAkC;IAElC,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IAClG,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE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,oBAAoB,EAAE,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IAC5H,CAAC;IACD,MAAM,QAAQ,GAAG,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC9C,OAAO,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3D,CAAC;AAED,SAAS,IAAI,CAAC,KAAgB,EAAE,KAAa;IAC3C,OAAO,EAAE,GAAG,KAAK,EAAE,GAAG,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,KAAK,EAAE,EAAE,CAAC;AACpD,CAAC;AAED,sEAAsE;AACtE,MAAM,UAAU,oBAAoB,CAAC,MAA0B;IAC7D,IAAI,MAAM,CAAC,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC;QACxD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,KAAK,QAAQ;YACtC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,IAAI,cAAc,CAAC;YACzC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,IAAI,iBAAiB,CAAC,CAAC;IACjD,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,OAAO;QAAE,OAAO,WAAW,CAAC;IAClD,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU;QAAE,OAAO,GAAG,MAAM,CAAC,QAAQ,EAAE,KAAK,IAAI,KAAK,6BAA6B,CAAC;IACzG,OAAO,cAAc,CAAC;AACxB,CAAC"}
package/dist/loop.d.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { type AnySchema, type Principal, type Store, type Violation } from "@graview/core";
2
+ import type { ToolCall } from "./agent/tools.js";
3
+ import type { ChatReply } from "./conversation.js";
4
+ import { type PlanOptions, type PlannedCall } from "./plan.js";
5
+ import { type Answer, type Decide } from "./providers/jev.js";
6
+ import { type DerivedQuestion, type OfferedQuestion } from "./questions.js";
7
+ /**
8
+ * A LOOP: ACT, RE-JUDGE, ACT AGAIN, AND KNOW WHEN TO STOP.
9
+ *
10
+ * `store.violations()` already says what is wrong and every rule names its
11
+ * repairs. A loop takes one violation, asks which repair to take — a
12
+ * Choice over a CLOSED set, so an invented repair is impossible — applies
13
+ * it as the declared act, re-judges, and goes again. Every turn is
14
+ * attributed to the loop's own seat and lands under one batch, so a loop
15
+ * that went wrong comes back out through the same control as anything
16
+ * else: one undo.
17
+ *
18
+ * It stops for a reason it can SAY. Nothing left; not sure enough of the
19
+ * repair; a state it has been in before (the loop is going in a circle);
20
+ * the budget spent; the provider failed; the policy refused. The sentence
21
+ * is part of the result and of the seat's reply, and it is announced on
22
+ * the same path a tool call is, so the rail carries it too.
23
+ */
24
+ export interface LoopDeclaration {
25
+ readonly name: string;
26
+ /** Which rules to keep; every rule otherwise. */
27
+ readonly rules?: readonly string[];
28
+ /** What this loop may spend. Twenty turns unless said otherwise. */
29
+ readonly budget?: {
30
+ readonly turns?: number;
31
+ readonly questions?: number;
32
+ readonly usd?: number;
33
+ };
34
+ }
35
+ export type StopWhy = "nothing-left" | "unsure" | "seen-before" | "budget" | "failed" | "refused" | "no-repair";
36
+ export interface Stopped {
37
+ readonly why: StopWhy;
38
+ /** The sentence the seat says. */
39
+ readonly said: string;
40
+ /** For `unsure`: the question the loop hands to a person, at its node. */
41
+ readonly question?: OfferedQuestion;
42
+ }
43
+ export interface LoopTurn {
44
+ readonly turn: number;
45
+ readonly violation: Violation;
46
+ /** The repair question asked, when there was more than one repair to choose from. */
47
+ readonly asked?: DerivedQuestion;
48
+ readonly answer?: Answer;
49
+ readonly confidence: number;
50
+ readonly call: PlannedCall;
51
+ /** Violations before and after this turn — what the turn did to the standing. */
52
+ readonly before: number;
53
+ readonly after: number;
54
+ }
55
+ export interface LoopOptions<S extends AnySchema> extends PlanOptions<S> {
56
+ readonly decide: Decide;
57
+ readonly author?: Principal;
58
+ readonly onCall?: (call: ToolCall) => void;
59
+ readonly batch?: string;
60
+ /** Below this confidence the loop stops and asks. 0.5 otherwise. */
61
+ readonly floor?: number;
62
+ readonly splitWithin?: number;
63
+ /** For rules whose evaluation wants a context. */
64
+ readonly context?: Readonly<Record<string, unknown>>;
65
+ }
66
+ export interface LoopResult {
67
+ readonly name: string;
68
+ readonly author: Principal;
69
+ readonly batch: string;
70
+ readonly turns: readonly LoopTurn[];
71
+ readonly stopped: Stopped;
72
+ readonly usage: {
73
+ readonly questions: number;
74
+ readonly calls: number;
75
+ readonly inputTokens: number;
76
+ readonly usd: number;
77
+ };
78
+ /** Violations still standing when it stopped. */
79
+ readonly remaining: number;
80
+ }
81
+ export declare function runLoop<S extends AnySchema>(store: Store<S>, loop: LoopDeclaration, options: LoopOptions<S>): Promise<LoopResult>;
82
+ /** A loop, spoken by the seat: the stop sentence, and the question if it stopped to ask. */
83
+ export declare function replyFromLoop(result: LoopResult): ChatReply;
84
+ //# sourceMappingURL=loop.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop.d.ts","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,KAAK,SAAS,EAAE,KAAK,SAAS,EAAE,KAAK,KAAK,EAAE,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AACpG,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAuB,KAAK,WAAW,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AACpF,OAAO,EAAc,KAAK,MAAM,EAAE,KAAK,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,EAAyB,KAAK,eAAe,EAAE,KAAK,eAAe,EAAE,MAAM,gBAAgB,CAAC;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