pinokiod 8.3.14 → 8.3.16

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinokiod",
3
- "version": "8.3.14",
3
+ "version": "8.3.16",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/server/index.js CHANGED
@@ -85,6 +85,7 @@ const Setup = require("../kernel/bin/setup")
85
85
  const { createTerminalSessionHelpers } = require("./lib/terminal_session_helpers")
86
86
  const { createLauncherInstructionBootstrap } = require("./lib/launcher_instruction_bootstrap")
87
87
  const { createBrain } = require("./lib/brain")
88
+ const { registerSessionFiles } = require("./lib/session_files")
88
89
  const { createJobs, registerJobRoutes } = require("./lib/agent_jobs")
89
90
  const RequestFile = require("../kernel/request_file")
90
91
  const { createTerminalGitResetHandler } = require("./lib/terminal_git_reset")
@@ -11902,6 +11903,7 @@ class Server {
11902
11903
  pluginHref: resolveUniversalLauncherPluginHref
11903
11904
  })
11904
11905
  this.app.post("/brain/ask", ex(brain.handleAsk))
11906
+ registerSessionFiles(this.app, { kernel: this.kernel })
11905
11907
  registerJobRoutes(this.app, {
11906
11908
  jobs: createJobs({ kernel: this.kernel, ended: brain.jobEnded }),
11907
11909
  prepare: brain.prepareJob
@@ -0,0 +1,248 @@
1
+ "use strict"
2
+
3
+ // The files an agent made for one session, for the page that shows the session.
4
+ //
5
+ // A session's files are in its output folder (agent_sessions.js): the agent is
6
+ // told that folder in its request, and whatever it puts there is listed here.
7
+ // Nothing else is reachable through these addresses, so a page on another
8
+ // device can show a session's files without being able to read the rest of
9
+ // the computer.
10
+ //
11
+ // GET /pinokio/session-files?cwd=<start folder>&session=<id>
12
+ // { ok, files: [{ path, size, modified }], more }
13
+ // GET /pinokio/session-files/file/<path>?cwd=...&session=...[&download=1]
14
+ // the file itself; with download=1 the browser saves it
15
+ // GET /pinokio/session-files/markdown/<path>?cwd=...&session=...
16
+ // { ok, html }: the file as a page, safe to put into a document
17
+ //
18
+ // `cwd` is the folder the session started in: the brain or an app's folder.
19
+ // `path` is inside the output folder, written with `/`.
20
+
21
+ const fs = require("fs")
22
+ const path = require("path")
23
+ const marked = require("marked")
24
+
25
+ const ID = /^\d{8}-\d{6}-[a-f0-9]{8}$/
26
+ // what one listing holds, however much an agent made
27
+ const MAX_FILES = 2000
28
+ const MAX_DEPTH = 12
29
+ const MAX_MARKDOWN_BYTES = 2 * 1024 * 1024
30
+ const BASE = "/pinokio/session-files"
31
+
32
+ const fail = (status, message) => Object.assign(new Error(message), { status })
33
+ const inside = (parent, child) => {
34
+ const relative = path.relative(parent, child)
35
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative))
36
+ }
37
+
38
+ // The output folder of the session `id` that started in `cwd`. Only the two
39
+ // places a session can start in have one: the brain, and an app's own folder.
40
+ const outputDir = (home, cwd, id) => {
41
+ if (typeof id !== "string" || !ID.test(id)) {
42
+ throw fail(400, "Unknown session.")
43
+ }
44
+ if (typeof cwd !== "string" || !cwd.trim() || !path.isAbsolute(cwd.trim())) {
45
+ throw fail(400, "Unknown folder.")
46
+ }
47
+ const start = path.resolve(cwd.trim())
48
+ if (path.relative(path.resolve(home, "brain"), start) === "") {
49
+ return path.resolve(start, "sessions", id, "output")
50
+ }
51
+ const api = path.resolve(home, "api")
52
+ const relative = path.relative(api, start)
53
+ if (relative && !relative.startsWith("..") && !path.isAbsolute(relative) && !relative.includes(path.sep)) {
54
+ return path.resolve(start, ".pinokio-sessions", id, "output")
55
+ }
56
+ throw fail(404, "This session keeps no files.")
57
+ }
58
+
59
+ // A path given by a page, as the parts of a path inside the output folder.
60
+ const partsOf = (raw) => {
61
+ const parts = String(raw || "").replace(/\\/g, "/").split("/").filter((part) => part && part !== ".")
62
+ if (parts.length === 0 || parts.some((part) => part === ".." || part.includes("\0"))) {
63
+ throw fail(400, "Invalid path.")
64
+ }
65
+ return parts
66
+ }
67
+
68
+ // Every file in the output folder, by name. A link to somewhere else is not
69
+ // followed and not listed: the folder only shows what is really in it.
70
+ const list = async (dir) => {
71
+ const files = []
72
+ let more = false
73
+ const walk = async (folder, prefix, depth) => {
74
+ let entries
75
+ try {
76
+ entries = await fs.promises.readdir(folder, { withFileTypes: true })
77
+ } catch (error) {
78
+ return
79
+ }
80
+ entries.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }))
81
+ for (const entry of entries) {
82
+ if (files.length >= MAX_FILES) {
83
+ more = true
84
+ return
85
+ }
86
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name
87
+ if (entry.isDirectory()) {
88
+ if (depth >= MAX_DEPTH) {
89
+ more = true
90
+ continue
91
+ }
92
+ await walk(path.resolve(folder, entry.name), relative, depth + 1)
93
+ } else if (entry.isFile()) {
94
+ const stat = await fs.promises.stat(path.resolve(folder, entry.name)).catch(() => null)
95
+ if (stat) {
96
+ files.push({ path: relative, size: stat.size, modified: stat.mtimeMs })
97
+ }
98
+ }
99
+ }
100
+ }
101
+ await walk(dir, "", 0)
102
+ return { files, more }
103
+ }
104
+
105
+ // The full path of one file in the output folder. A link that leads out of the
106
+ // folder is refused, wherever in the path it is.
107
+ const locate = async (dir, raw) => {
108
+ const target = path.resolve(dir, ...partsOf(raw))
109
+ if (!inside(dir, target)) {
110
+ throw fail(400, "Invalid path.")
111
+ }
112
+ const [realDir, realTarget] = await Promise.all([
113
+ fs.promises.realpath(dir).catch(() => null),
114
+ fs.promises.realpath(target).catch(() => null)
115
+ ])
116
+ if (!realDir || !realTarget || !inside(realDir, realTarget)) {
117
+ throw fail(404, "File not found.")
118
+ }
119
+ const stat = await fs.promises.stat(realTarget).catch(() => null)
120
+ if (!stat || !stat.isFile()) {
121
+ throw fail(404, "File not found.")
122
+ }
123
+ return { file: realTarget, size: stat.size }
124
+ }
125
+
126
+ const escapeHtml = (text) => String(text == null ? "" : text).replace(/[&<>"']/g, (char) => ({
127
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
128
+ }[char]))
129
+
130
+ const fileAddress = (relative, cwd, id, download) => {
131
+ const query = new URLSearchParams({ cwd, session: id })
132
+ if (download) {
133
+ query.set("download", "1")
134
+ }
135
+ return `${BASE}/file/${relative.split("/").map(encodeURIComponent).join("/")}?${query.toString()}`
136
+ }
137
+
138
+ // Where a link written in a file leads, as a path inside the output folder.
139
+ // Null when it is not a file of this session: another site, a place in the
140
+ // page, or a path that climbs out of the folder.
141
+ const linkedPath = (from, href) => {
142
+ let link = String(href || "").trim()
143
+ if (!link || link.startsWith("#") || link.startsWith("//") || /^[a-z][a-z0-9+.-]*:/i.test(link)) {
144
+ return null
145
+ }
146
+ link = link.split("#")[0].split("?")[0]
147
+ try {
148
+ link = decodeURIComponent(link)
149
+ } catch (error) {
150
+ return null
151
+ }
152
+ const parts = link.startsWith("/") ? [] : from.split("/").slice(0, -1)
153
+ for (const piece of link.replace(/\\/g, "/").split("/")) {
154
+ if (piece === "..") {
155
+ if (parts.length === 0) {
156
+ return null
157
+ }
158
+ parts.pop()
159
+ } else if (piece && piece !== ".") {
160
+ parts.push(piece)
161
+ }
162
+ }
163
+ return parts.length > 0 ? parts.join("/") : null
164
+ }
165
+
166
+ // A markdown file as a page. The text was written by an agent, so nothing in
167
+ // it is trusted: HTML written in the file is left out, and a link only ever
168
+ // becomes one of two things: a web address that opens in a new tab, or the
169
+ // name of another file of this session, which the page opens itself. A picture
170
+ // is shown only when it is a file of this session.
171
+ const renderMarkdown = (text, { from, cwd, id }) => {
172
+ const renderer = new marked.Renderer()
173
+ renderer.html = () => ""
174
+ renderer.link = (href, title, label) => {
175
+ const link = String(href || "").trim()
176
+ if (/^https?:\/\//i.test(link)) {
177
+ return `<a href="${escapeHtml(link)}" target="_blank" rel="noopener noreferrer">${label}</a>`
178
+ }
179
+ const target = linkedPath(from, link)
180
+ return target ? `<a href="#" data-session-file="${escapeHtml(target)}">${label}</a>` : label
181
+ }
182
+ renderer.image = (href, title, label) => {
183
+ const link = String(href || "").trim()
184
+ const target = linkedPath(from, link)
185
+ if (target) {
186
+ return `<img src="${escapeHtml(fileAddress(target, cwd, id))}" alt="${escapeHtml(label)}" loading="lazy">`
187
+ }
188
+ if (/^https?:\/\//i.test(link)) {
189
+ return `<a href="${escapeHtml(link)}" target="_blank" rel="noopener noreferrer">${escapeHtml(label || link)}</a>`
190
+ }
191
+ return escapeHtml(label)
192
+ }
193
+ return marked.parse(String(text || ""), { renderer, mangle: false, headerIds: false })
194
+ }
195
+
196
+ const registerSessionFiles = (app, { kernel }) => {
197
+ const handle = (fn) => (req, res) => {
198
+ Promise.resolve(fn(req, res)).catch((error) => {
199
+ const status = error && error.status ? error.status : 500
200
+ if (status === 500) {
201
+ console.warn("[session-files]", error && error.message ? error.message : error)
202
+ }
203
+ res.status(status).json({ ok: false, error: status === 500 ? "Could not read this session's files." : error.message })
204
+ })
205
+ }
206
+ const dirOf = (req) => outputDir(kernel.homedir, req.query.cwd, req.query.session)
207
+
208
+ app.get(BASE, handle(async (req, res) => {
209
+ const found = await list(dirOf(req))
210
+ res.set("Cache-Control", "no-store")
211
+ res.json({ ok: true, files: found.files, more: found.more })
212
+ }))
213
+
214
+ app.get(`${BASE}/file/*`, handle(async (req, res) => {
215
+ const { file } = await locate(dirOf(req), req.params[0])
216
+ // A file an agent made is never a page of Pinokio's: opened by itself it
217
+ // runs no script and reaches nothing.
218
+ res.set("Content-Security-Policy", "sandbox; default-src 'none'; img-src 'self' data:; media-src 'self'; style-src 'unsafe-inline'")
219
+ res.set("X-Content-Type-Options", "nosniff")
220
+ res.set("Cache-Control", "no-store")
221
+ if (req.query.download === "1") {
222
+ res.attachment(path.basename(file))
223
+ }
224
+ await new Promise((resolve, reject) => {
225
+ res.sendFile(file, { dotfiles: "allow" }, (error) => {
226
+ // a browser that stops reading (a video it has enough of) is not an error
227
+ if (error && !res.headersSent) {
228
+ reject(fail(404, "File not found."))
229
+ } else {
230
+ resolve()
231
+ }
232
+ })
233
+ })
234
+ }))
235
+
236
+ app.get(`${BASE}/markdown/*`, handle(async (req, res) => {
237
+ const { file, size } = await locate(dirOf(req), req.params[0])
238
+ if (size > MAX_MARKDOWN_BYTES) {
239
+ throw fail(413, "This file is too large to show.")
240
+ }
241
+ const text = await fs.promises.readFile(file, "utf8")
242
+ const from = partsOf(req.params[0]).join("/")
243
+ res.set("Cache-Control", "no-store")
244
+ res.json({ ok: true, html: renderMarkdown(text, { from, cwd: String(req.query.cwd), id: String(req.query.session) }) })
245
+ }))
246
+ }
247
+
248
+ module.exports = { registerSessionFiles, outputDir, list, locate, linkedPath, renderMarkdown, fileAddress, MAX_FILES }
@@ -17,7 +17,8 @@
17
17
  // in the panel right away, as today.
18
18
  // 4. Sessions (Run): every send starts its own session (a `session` value on
19
19
  // the launch link, the same thing shells already get), so nothing running
20
- // is replaced. The dropdown lists this app's running agent and shell
20
+ // is replaced. "N running" counts every running session, here and in
21
+ // other places, and its list starts with this app's running agent and shell
21
22
  // sessions, read from GET /info/shells; picking one shows it in the panel
22
23
  // again. Opening a running session's link attaches to it, it is not re-run.
23
24
  // Nothing is removed from the page: the Ask AI and Feed buttons are hidden by
@@ -470,6 +471,8 @@
470
471
  menu.textContent = '';
471
472
  menu.hidden = !state.menu;
472
473
  menu.dataset.menu = state.menu || '';
474
+ // the dock's list keeps the look it has on every other page
475
+ menu.classList.toggle('agent-bar__menu--running', state.menu === 'running' && Boolean(everywhere()));
473
476
  if (state.menu === 'agent') {
474
477
  agentMenuRows(menu, state.tools, state.loaded, state.tool, (tool) => {
475
478
  state.tool = tool.value;
@@ -487,6 +490,9 @@
487
490
  menu.appendChild(menuRow(toolIcon(shell), shell.label, shell.description, false, () => openShell(shell)));
488
491
  });
489
492
  }
493
+ } else if (state.menu === 'running' && everywhere()) {
494
+ // the dock's list: this app's sessions first, then every other place's
495
+ everywhere().list(menu, { picked: leave, changed: render });
490
496
  } else if (state.menu === 'running') {
491
497
  const openKeys = panelKeys();
492
498
  menu.appendChild(el('div', 'agent-bar__menu-title', 'Running in this app'));
@@ -522,7 +528,7 @@
522
528
  input.disabled = state.busy;
523
529
  agent.show(tool, state.busy, state.menu === 'agent');
524
530
  // running sessions: a small count in the field, only when there are any
525
- const count = state.sessions.length;
531
+ const count = everywhere() ? everywhere().count() : state.sessions.length;
526
532
  running.hidden = !(isRun && count > 0);
527
533
  running.textContent = '';
528
534
  running.append(el('span', 'agent-bar__dot'), `${count} running`);
@@ -605,8 +611,22 @@
605
611
  return toolsPromise;
606
612
  }
607
613
 
614
+ // The dock knows every running session, in this app and anywhere else: the
615
+ // count and the list are its own. Without it (the page's own panel) only
616
+ // this app's sessions are known, and those are what is shown.
617
+ function everywhere() {
618
+ const drawer = askDrawer();
619
+ return drawer && typeof drawer.count === 'function' && typeof drawer.list === 'function' ? drawer : null;
620
+ }
621
+
608
622
  function loadSessions() {
609
623
  if (!isRun || !workspaceCwd) return Promise.resolve();
624
+ const dock = everywhere();
625
+ if (dock) {
626
+ // its own look at what is running; the bar is told if anything changed
627
+ if (typeof dock.look === 'function') dock.look();
628
+ return loadTools();
629
+ }
610
630
  return Promise.all([loadTools(), fetch('/info/shells').then((res) => (res.ok ? res.json() : []))])
611
631
  .then((results) => {
612
632
  state.sessions = readSessions(results[1]);
@@ -803,16 +823,18 @@
803
823
  // a shell opened from the top bar's shell button (agent-bar-shell.js)
804
824
  window.addEventListener('pinokio:shell-opened', () => window.setTimeout(loadSessions, 1500));
805
825
  // The dock saw the running sessions change (one was stopped from its window,
806
- // or ended) and hands over the list it read. Most changes are in other
807
- // places: the bar is drawn again only when this app's own sessions differ,
808
- // because a redraw resets a Stop that is waiting for its second click.
826
+ // or ended) and hands over the list it read. It says so only when what it
827
+ // lists has changed, so its list is drawn again each time. Without its list,
828
+ // most changes are in other places: the bar is drawn again only when this
829
+ // app's own sessions differ, because a redraw resets a Stop that is waiting
830
+ // for its second click.
809
831
  window.addEventListener('pinokio:sessions-changed', (event) => {
810
832
  const shells = event.detail && event.detail.shells;
811
833
  if (!isRun || !workspaceCwd || !Array.isArray(shells)) return;
812
834
  loadTools().then(() => {
813
835
  const next = readSessions(shells);
814
836
  const signature = (list) => JSON.stringify(list.map((session) => [session.key, session.startTime]));
815
- if (signature(next) === signature(state.sessions)) return;
837
+ if (!everywhere() && signature(next) === signature(state.sessions)) return;
816
838
  state.sessions = next;
817
839
  render();
818
840
  });
@@ -15,8 +15,9 @@
15
15
  // Each bar still decides everything it decides today: the modes, the folder
16
16
  // names, what is sent. It draws itself again on every change and writes what it
17
17
  // shows on .agent-bar (data-item, data-engaged, data-busy). This file watches
18
- // that and lays the same parts out again. From a bar's own script it uses two
19
- // things only: leave() and tool(), on PinokioAgentBar or PinokioAgentBarApp.
18
+ // that and lays the same parts out again. From a bar's own script it uses
19
+ // leave() and tool(), on PinokioAgentBar or PinokioAgentBarApp, and the home
20
+ // bar's hint().
20
21
  (function (window, document) {
21
22
  'use strict';
22
23
  if (window.PinokioAgentCompose) return;
@@ -47,6 +48,9 @@
47
48
  download: 'What should we download?',
48
49
  };
49
50
  const LINK_GREETING = 'Ready when you are';
51
+ // said in the empty text while the cursor is not in it, where the bar's own
52
+ // line would repeat the greeting
53
+ const TYPE_HERE = 'Type here…';
50
54
  // the starter text agent-bar.js gives Create plugin (PLUGIN_PROMPT_SEED there)
51
55
  const PLUGIN_SEED = 'A Pinokio plugin for: ';
52
56
  // The face: the filled mark the mode chip has at rest, and the same character
@@ -314,12 +318,30 @@
314
318
  // to paste, so Download keeps its own placeholder.
315
319
  // On an app's page the greeting is the bar's own line, which names the app.
316
320
  const greetingNow = () => (isApp ? restPlaceholder.replace(/…$/, '') : (GREETINGS[item()] || ''));
321
+ // Under the large face the blinking cursor is all that marks the empty text
322
+ // as a place to type. Where there is none, the text says so itself, in the
323
+ // bar's own line at rest. A phone only shows the cursor with its keyboard:
324
+ // the view can be open with the keyboard down (a link that was followed
325
+ // without a tap, or the keyboard put away).
326
+ // (A page in a layout pane is itself cut to what the keyboard leaves, so the
327
+ // keyboard is measured on the layout's window.)
328
+ function keyboardUp() {
329
+ const win = window.frameElement ? window.parent : window;
330
+ const vv = win.visualViewport;
331
+ return !vv || win.innerHeight - vv.height > 120;
332
+ }
333
+ const cursorShown = () => document.activeElement === input && (!isTouch() || keyboardUp());
334
+ function hintNow() {
335
+ if (cursorShown()) return '';
336
+ const rest = isApp ? restPlaceholder : (typeof host.hint === 'function' ? host.hint() : '');
337
+ return rest.replace(/…$/, '') === greet.textContent ? TYPE_HERE : rest;
338
+ }
317
339
  function words() {
318
340
  const large = shape === 'centre' || (shape === 'screen' && roomy);
319
341
  const greeting = greetingNow();
320
342
  greet.textContent = shape === 'centre' ? LINK_GREETING : greeting;
321
- if (isApp) input.placeholder = shape && large ? '' : restPlaceholder;
322
- else if (shape && !isDownload()) input.placeholder = large ? '' : greeting;
343
+ if (isApp) input.placeholder = shape && large ? hintNow() : restPlaceholder;
344
+ else if (shape && !isDownload()) input.placeholder = large ? hintNow() : greeting;
323
345
  // what the on-screen keyboard prints on its Return key
324
346
  input.enterKeyHint = isDownload() ? 'go' : (isTouch() ? 'enter' : 'send');
325
347
  nameInputs.forEach((nameInput) => { nameInput.enterKeyHint = 'go'; });
@@ -365,8 +387,13 @@
365
387
  const left = Math.max(8, Math.min(edge, window.innerWidth - width - 8));
366
388
  list.style.right = 'auto';
367
389
  list.style.left = `${left - frame.left}px`;
368
- const below = window.innerHeight - a.bottom - 14;
369
- const above = a.top - 14;
390
+ // Room is counted in what can be seen: on a phone the keyboard covers the
391
+ // lower part of the window, and a list hung there would be under it.
392
+ const vv = window.visualViewport;
393
+ const seenTop = vv ? vv.offsetTop : 0;
394
+ const seenBottom = vv ? Math.min(window.innerHeight, vv.offsetTop + vv.height) : window.innerHeight;
395
+ const below = seenBottom - a.bottom - 14;
396
+ const above = a.top - seenTop - 14;
370
397
  if (below < 200 && above > below) {
371
398
  list.style.top = 'auto';
372
399
  list.style.bottom = `${frame.bottom - a.top + 6}px`;
@@ -579,6 +606,28 @@
579
606
  if (shape && event.target.closest && event.target.closest(KEEPS_CURSOR)) event.preventDefault();
580
607
  });
581
608
 
609
+ // A press on the box itself, anywhere that is not a button, a list, a
610
+ // message (whose words can be selected) or a field of its own, is a press on
611
+ // the text: the cursor stays in it, or goes to it. (A phone that refused the
612
+ // cursor its keyboard gives it on a tap, and only to a field that takes the
613
+ // cursor anew.)
614
+ const OWN_PRESS = 'button, a, input, textarea, select, label, .agent-bar__menu, .agent-bar__files, .agent-bar__note';
615
+ const onBox = (event) => Boolean(shape) && Boolean(event.target.closest)
616
+ && field.contains(event.target) && !event.target.closest(OWN_PRESS);
617
+ inner.addEventListener('pointerdown', (event) => {
618
+ if (onBox(event)) event.preventDefault();
619
+ });
620
+ inner.addEventListener('click', (event) => {
621
+ if (!onBox(event) || input.disabled) return;
622
+ if (document.activeElement === input && !cursorShown()) input.blur();
623
+ input.focus();
624
+ });
625
+ // (after the bar has drawn itself: leaving the bar takes the cursor out too,
626
+ // and the bar at rest has its own line)
627
+ const cursorMoved = () => window.setTimeout(() => { if (shape) words(); }, 0);
628
+ input.addEventListener('focus', cursorMoved);
629
+ input.addEventListener('blur', cursorMoved);
630
+
582
631
  input.addEventListener('input', listen);
583
632
  nameInputs.forEach((nameInput) => nameInput.addEventListener('input', listen));
584
633