loopengine 0.3.93 → 0.3.95

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.d.ts CHANGED
@@ -136,6 +136,7 @@ export { LEVERS, PLAYBOOK_VERSION, activePlaybook, setPlaybookProjectDir, type L
136
136
  export { startPlaybookSync, syncPlaybook, playbookSyncConfig } from './core/playbook-sync.js';
137
137
  export { workspaceRole, canDecide, inboxOnly, inboxOnlyAllows, roleLabel, agentsFor, type WorkspaceRole } from './core/workspace-roles.js';
138
138
  export { inboxPageHtml, renderInboxOnlyPage } from './web/inbox-page.js';
139
+ export { compressResponses, serveConsoleAsset } from './web/response-compression.js';
139
140
  export { workflowsOverviewPageHtml } from './web/workflows-overview-page.js';
140
141
  export { workflowsOverview, startsOf, type WorkflowsOverview, type WorkflowOverviewRow } from './web/workflows-overview.js';
141
142
  export { listInbox, getInboxCase, timelineOf, type InboxDeps, type InboxItem, type InboxCase, type InboxPending, type InboxStep } from './web/inbox-admin.js';
package/dist/index.js CHANGED
@@ -127,6 +127,7 @@ export { LEVERS, PLAYBOOK_VERSION, activePlaybook, setPlaybookProjectDir } from
127
127
  export { startPlaybookSync, syncPlaybook, playbookSyncConfig } from './core/playbook-sync.js';
128
128
  export { workspaceRole, canDecide, inboxOnly, inboxOnlyAllows, roleLabel, agentsFor } from './core/workspace-roles.js';
129
129
  export { inboxPageHtml, renderInboxOnlyPage } from './web/inbox-page.js';
130
+ export { compressResponses, serveConsoleAsset } from './web/response-compression.js';
130
131
  export { workflowsOverviewPageHtml } from './web/workflows-overview-page.js';
131
132
  export { workflowsOverview, startsOf } from './web/workflows-overview.js';
132
133
  export { listInbox, getInboxCase, timelineOf } from './web/inbox-admin.js';
@@ -96,11 +96,25 @@ export const consoleShellScript = `<script>
96
96
  function remember(key, value) {
97
97
  try { sessionStorage.setItem('le-side:' + key, JSON.stringify(value)); } catch (e) {}
98
98
  }
99
+ // A list asked for again while it's still loading, or within a couple
100
+ // of seconds of arriving (a page reloading the sidebar as it opens),
101
+ // reuses that answer instead of another round trip.
102
+ var recent = {};
103
+ function getJson(url) {
104
+ var hit = recent[url];
105
+ if (hit && (!hit.at || Date.now() - hit.at < 2000)) return hit.promise;
106
+ var entry = { at: 0, promise: null };
107
+ entry.promise = fetch(url, { headers: { accept: 'application/json' } })
108
+ .then(function (r) { return r.ok ? r.json() : null; })
109
+ .catch(function () { return null; })
110
+ .then(function (data) { entry.at = Date.now(); return data; });
111
+ recent[url] = entry;
112
+ return entry.promise;
113
+ }
99
114
  function cachedFetch(key, url, render) {
100
115
  var seen = recall(key);
101
116
  if (seen) { try { render(seen); } catch (e) {} }
102
- return fetch(url, { headers: { accept: 'application/json' } })
103
- .then(function (r) { return r.ok ? r.json() : null; })
117
+ return getJson(url)
104
118
  .then(function (data) {
105
119
  if (!data) return;
106
120
  if (!seen || JSON.stringify(seen) !== JSON.stringify(data)) render(data);
@@ -109,29 +123,19 @@ export const consoleShellScript = `<script>
109
123
  .catch(function () {});
110
124
  }
111
125
 
112
- // Who is signed in and their role (GET /config/settings), read once.
113
- var settings = fetch('/config/settings')
114
- .then(function (r) { return r.ok ? r.json() : null; })
115
- .catch(function () { return null; });
116
- // On the Inbox, the lists wait for the role: an approver or viewer sees
117
- // the Inbox only, and the rest of the sidebar is hidden. Other pages
118
- // are only open to the roles that see everything.
119
- // The server marks the page for an Inbox-only role before it's shown.
126
+ // Who is signed in and their role (GET /config/settings), read once;
127
+ // pages read it through leShell.settings() rather than asking again.
128
+ var settings = getJson('/config/settings');
129
+ // An approver or viewer sees the Inbox only, with the rest of the
130
+ // sidebar hidden. The server knows the role from the request and marks
131
+ // the page before it's sent (and those roles can't open any other
132
+ // page), so the lists draw at once instead of waiting on a role check.
120
133
  var markedInboxOnly = Boolean(app && app.classList.contains('le-inbox-only'));
121
134
  if (markedInboxOnly) {
122
135
  var inboxBrand = document.querySelector('.le-brand');
123
136
  if (inboxBrand) inboxBrand.setAttribute('href', '/inbox');
124
137
  }
125
- var fullAccess = markedInboxOnly ? Promise.resolve(false) : page === 'inbox' ? settings.then(function (s) {
126
- var role = s && s.signIn && s.signIn.role;
127
- var only = role === 'approver' || role === 'viewer';
128
- if (only && app) {
129
- app.classList.add('le-inbox-only');
130
- var brand = document.querySelector('.le-brand');
131
- if (brand) brand.setAttribute('href', '/inbox');
132
- }
133
- return !only;
134
- }) : Promise.resolve(true);
138
+ var fullAccess = Promise.resolve(!markedInboxOnly);
135
139
 
136
140
  function tabHref(name, tab) {
137
141
  if (tab === 'chat') return '/playground?agent=' + enc(name);
@@ -168,20 +172,17 @@ export const consoleShellScript = `<script>
168
172
  return n ? '<span class="le-count warn">' + n + ' to set</span>' : '';
169
173
  }
170
174
 
175
+ // Each agent's count comes with GET /agents (toSet).
171
176
  function loadToSet() {
177
+ var next = {};
178
+ agents.forEach(function (a) { next[a.name] = a.toSet || 0; });
179
+ var changed = JSON.stringify(next) !== JSON.stringify(toSet);
180
+ toSet = next;
181
+ remember('toSet', toSet);
182
+ if (changed) renderList();
172
183
  agents.forEach(function (a) {
173
- fetch('/agents/' + enc(a.name) + '/env')
174
- .then(function (r) { return r.ok ? r.json() : []; })
175
- .then(function (vars) {
176
- var n = (vars || []).filter(function (v) { return v.slot === 'agent' && v.scope === 'agent' && !v.set; }).length;
177
- var changed = toSet[a.name] !== n;
178
- toSet[a.name] = n;
179
- remember('toSet', toSet);
180
- if (changed) renderList();
181
- var slots = document.querySelectorAll('[data-le-env-count="' + a.name + '"]');
182
- for (var i = 0; i < slots.length; i++) slots[i].innerHTML = envCountHtml(a.name);
183
- })
184
- .catch(function () {});
184
+ var slots = document.querySelectorAll('[data-le-env-count="' + a.name + '"]');
185
+ for (var i = 0; i < slots.length; i++) slots[i].innerHTML = envCountHtml(a.name);
185
186
  });
186
187
  }
187
188
 
@@ -628,6 +629,6 @@ export const consoleShellScript = `<script>
628
629
  }
629
630
 
630
631
 
631
- window.leShell = { loadError: function () { return loadError; }, ready: ready, reloadGoals: reloadGoals, reloadJobs: reloadJobs, reloadWorkflows: reloadWorkflows, reloadInboxCount: reloadInboxCount, renderHead: renderHead, setTab: setTab, setActive: setActive, setDisplayName: setDisplayName, displayNameOf: displayNameOf, esc: esc, tabHref: tabHref, envCountHtml: envCountHtml, setCount: setCount, wireModelPicker: wireModelPicker, loadProviderKeys: loadProviderKeys, applyProviderKeys: applyProviderKeys, abilityOriginBadge: abilityOriginBadge, toggleAbilityDetails: toggleAbilityDetails };
632
+ window.leShell = { loadError: function () { return loadError; }, ready: ready, settings: function () { return settings; }, getJson: getJson, reloadGoals: reloadGoals, reloadJobs: reloadJobs, reloadWorkflows: reloadWorkflows, reloadInboxCount: reloadInboxCount, renderHead: renderHead, setTab: setTab, setActive: setActive, setDisplayName: setDisplayName, displayNameOf: displayNameOf, esc: esc, tabHref: tabHref, envCountHtml: envCountHtml, setCount: setCount, wireModelPicker: wireModelPicker, loadProviderKeys: loadProviderKeys, applyProviderKeys: applyProviderKeys, abilityOriginBadge: abilityOriginBadge, toggleAbilityDetails: toggleAbilityDetails };
632
633
  })();
633
634
  </script>`;
@@ -339,8 +339,7 @@ ${renderMarkdownScript}
339
339
  }, 15000);
340
340
  }
341
341
 
342
- fetch('/config/settings')
343
- .then(function (r) { return r.ok ? r.json() : null; })
342
+ (window.leShell && window.leShell.settings ? window.leShell.settings() : fetch('/config/settings').then(function (r) { return r.ok ? r.json() : null; }))
344
343
  .then(function (s) { if (s && s.signIn && s.signIn.role) role = s.signIn.role; })
345
344
  .catch(function () {})
346
345
  .then(start);
@@ -0,0 +1,6 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /** Answers GET /_le/assets/<name> from the pages' moved-out code; false
3
+ * for any other request. An asset's name is its content hash, so it's
4
+ * cached for good. */
5
+ export declare function serveConsoleAsset(req: IncomingMessage, res: ServerResponse): boolean;
6
+ export declare function compressResponses(req: IncomingMessage, res: ServerResponse): void;
@@ -0,0 +1,177 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { gzipSync } from 'node:zlib';
3
+ const MIN_BYTES = 1024;
4
+ const COMPRESSIBLE = /^(text\/|application\/(json|javascript)|image\/svg\+xml)/i;
5
+ // The pages are the same few strings sent again and again: their
6
+ // gzipped copies are kept, by content hash.
7
+ const gzipped = new Map();
8
+ const MAX_CACHED = 64;
9
+ function gzipOf(body, hash) {
10
+ const hit = gzipped.get(hash);
11
+ if (hit)
12
+ return hit;
13
+ const out = gzipSync(body, { level: 6 });
14
+ if (gzipped.size >= MAX_CACHED)
15
+ gzipped.delete(gzipped.keys().next().value);
16
+ gzipped.set(hash, out);
17
+ return out;
18
+ }
19
+ // Page code moved out of the pages, by content hash. The pages are
20
+ // strings fixed at start, so this holds a few dozen blocks; the cap only
21
+ // guards against a page that changes on every request.
22
+ const ASSET_MIN_BYTES = 2048;
23
+ const MAX_ASSETS = 512;
24
+ const assets = new Map();
25
+ const leanPages = new Map();
26
+ function keepAsset(text, ext) {
27
+ const body = Buffer.from(text, 'utf8');
28
+ const name = createHash('sha1').update(body).digest('base64url').slice(0, 20) + '.' + ext;
29
+ if (!assets.has(name)) {
30
+ if (assets.size >= MAX_ASSETS)
31
+ assets.delete(assets.keys().next().value);
32
+ assets.set(name, { type: ext === 'js' ? 'text/javascript; charset=utf-8' : 'text/css; charset=utf-8', body });
33
+ }
34
+ return '/_le/assets/' + name;
35
+ }
36
+ // A page with its large plain <script> and <style> blocks as files. They
37
+ // run in the same order and block the page the same way they did inline.
38
+ function leanPage(html, hash) {
39
+ const hit = leanPages.get(hash);
40
+ if (hit !== undefined)
41
+ return hit;
42
+ const out = html
43
+ .replace(/<script>([\s\S]*?)<\/script>/g, (whole, code) => (code.length >= ASSET_MIN_BYTES ? `<script src="${keepAsset(code, 'js')}"></script>` : whole))
44
+ .replace(/<style>([\s\S]*?)<\/style>/g, (whole, css) => (css.length >= ASSET_MIN_BYTES ? `<link rel="stylesheet" href="${keepAsset(css, 'css')}">` : whole));
45
+ if (leanPages.size >= MAX_CACHED)
46
+ leanPages.delete(leanPages.keys().next().value);
47
+ leanPages.set(hash, out);
48
+ return out;
49
+ }
50
+ /** Answers GET /_le/assets/<name> from the pages' moved-out code; false
51
+ * for any other request. An asset's name is its content hash, so it's
52
+ * cached for good. */
53
+ export function serveConsoleAsset(req, res) {
54
+ const path = (req.url ?? '').split('?')[0];
55
+ if (!path.startsWith('/_le/assets/') || (req.method !== 'GET' && req.method !== 'HEAD'))
56
+ return false;
57
+ const asset = assets.get(path.slice('/_le/assets/'.length));
58
+ if (!asset) {
59
+ res.writeHead(404, { 'content-type': 'text/plain', 'cache-control': 'no-store' }).end('Not found');
60
+ return true;
61
+ }
62
+ res.writeHead(200, { 'content-type': asset.type, 'cache-control': 'public, max-age=31536000, immutable' });
63
+ res.end(req.method === 'HEAD' ? undefined : asset.body);
64
+ return true;
65
+ }
66
+ function headerValue(headers, name) {
67
+ const key = Object.keys(headers).find((k) => k.toLowerCase() === name);
68
+ const v = key ? headers[key] : undefined;
69
+ return v === undefined ? undefined : Array.isArray(v) ? v.join(', ') : String(v);
70
+ }
71
+ function dropHeader(headers, name) {
72
+ for (const k of Object.keys(headers))
73
+ if (k.toLowerCase() === name)
74
+ delete headers[k];
75
+ }
76
+ export function compressResponses(req, res) {
77
+ const acceptsGzip = /\bgzip\b/i.test(String(req.headers['accept-encoding'] ?? ''));
78
+ const isGet = req.method === 'GET';
79
+ if (!acceptsGzip && !isGet)
80
+ return;
81
+ const writeHead = res.writeHead.bind(res);
82
+ const write = res.write.bind(res);
83
+ const end = res.end.bind(res);
84
+ // writeHead is held back until the body is known; a write sends it as given.
85
+ let held;
86
+ let streaming = false;
87
+ const release = () => {
88
+ if (!held)
89
+ return;
90
+ const h = held;
91
+ held = undefined;
92
+ if (h.message !== undefined)
93
+ writeHead(h.status, h.message, h.headers);
94
+ else
95
+ writeHead(h.status, h.headers);
96
+ };
97
+ res.writeHead = function (status, ...rest) {
98
+ const message = typeof rest[0] === 'string' ? rest.shift() : undefined;
99
+ const given = rest[0];
100
+ const headers = {};
101
+ if (Array.isArray(given)) {
102
+ for (let i = 0; i + 1 < given.length; i += 2)
103
+ headers[String(given[i])] = given[i + 1];
104
+ }
105
+ else if (given && typeof given === 'object')
106
+ Object.assign(headers, given);
107
+ held = { status, ...(message !== undefined ? { message } : {}), headers };
108
+ // An event stream's head goes out at once, before its first event.
109
+ if (/^text\/event-stream/i.test(headerValue(headers, 'content-type') ?? '')) {
110
+ streaming = true;
111
+ release();
112
+ }
113
+ return res;
114
+ };
115
+ res.write = function (...args) {
116
+ streaming = true;
117
+ release();
118
+ return write(...args);
119
+ };
120
+ res.end = function (...args) {
121
+ const chunk = args[0];
122
+ if (streaming || (chunk !== undefined && chunk !== null && typeof chunk !== 'string' && !Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array))) {
123
+ release();
124
+ return end(...args);
125
+ }
126
+ const encoding = typeof args[1] === 'string' ? args[1] : 'utf8';
127
+ const callback = args.find((a) => typeof a === 'function');
128
+ const status = held?.status ?? res.statusCode;
129
+ // Headers set with setHeader, overlaid by writeHead's own.
130
+ const headers = { ...res.getHeaders(), ...(held?.headers ?? {}) };
131
+ for (const name of res.getHeaderNames())
132
+ res.removeHeader(name);
133
+ const message = held?.message;
134
+ held = undefined;
135
+ const body = chunk === undefined || chunk === null ? Buffer.alloc(0) : typeof chunk === 'string' ? Buffer.from(chunk, encoding) : Buffer.from(chunk);
136
+ const type = headerValue(headers, 'content-type') ?? '';
137
+ const cacheControl = headerValue(headers, 'cache-control') ?? '';
138
+ const already = headerValue(headers, 'content-encoding');
139
+ const hash = body.length ? createHash('sha1').update(body).digest('base64url').slice(0, 27) : '';
140
+ let out = body;
141
+ if (isGet && status === 200 && /^text\/html/i.test(type) && !/no-store/i.test(cacheControl) && !headerValue(headers, 'etag') && body.length) {
142
+ out = Buffer.from(leanPage(body.toString('utf8'), hash), 'utf8');
143
+ const etag = `W/"${hash}"`;
144
+ headers.etag = etag;
145
+ dropHeader(headers, 'cache-control');
146
+ headers['cache-control'] = 'no-cache';
147
+ dropHeader(headers, 'vary');
148
+ headers.vary = 'Accept, Accept-Encoding';
149
+ const asked = String(req.headers['if-none-match'] ?? '');
150
+ if (asked.split(',').some((t) => t.trim() === etag)) {
151
+ dropHeader(headers, 'content-type');
152
+ dropHeader(headers, 'content-length');
153
+ if (message !== undefined)
154
+ writeHead(304, message, headers);
155
+ else
156
+ writeHead(304, headers);
157
+ return end(callback);
158
+ }
159
+ }
160
+ if (acceptsGzip && !already && body.length >= MIN_BYTES && COMPRESSIBLE.test(type) && req.method !== 'HEAD' && status !== 204 && status !== 304) {
161
+ out = gzipOf(out, out === body ? hash : hash + ':lean');
162
+ headers['content-encoding'] = 'gzip';
163
+ const vary = headerValue(headers, 'vary');
164
+ if (!vary || !/accept-encoding/i.test(vary)) {
165
+ dropHeader(headers, 'vary');
166
+ headers.vary = vary ? `${vary}, Accept-Encoding` : 'Accept-Encoding';
167
+ }
168
+ dropHeader(headers, 'content-length');
169
+ headers['content-length'] = String(out.length);
170
+ }
171
+ if (message !== undefined)
172
+ writeHead(status, message, headers);
173
+ else
174
+ writeHead(status, headers);
175
+ return end(out, callback);
176
+ };
177
+ }
@@ -132,8 +132,10 @@ ${consoleShellScript}
132
132
  PLAN;
133
133
  }
134
134
 
135
- fetch('/workflows/overview', { cache: 'no-store' })
136
- .then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
135
+ // The sidebar asks for the same list as the page opens: one request.
136
+ (window.leShell && window.leShell.getJson
137
+ ? window.leShell.getJson('/workflows/overview').then(function (d) { if (!d) throw new Error('could not reach the server'); return d; })
138
+ : fetch('/workflows/overview', { cache: 'no-store' }).then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); }))
137
139
  .then(render)
138
140
  .catch(function (err) { page.innerHTML = '<p class="error">Couldn' + String.fromCharCode(8217) + 't load your workflows: ' + esc(err.message) + '</p>'; });
139
141
  })();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopengine",
3
- "version": "0.3.93",
3
+ "version": "0.3.95",
4
4
  "type": "module",
5
5
  "description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
6
6
  "license": "MIT",