pinokiod 8.3.7 → 8.3.9

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.
@@ -0,0 +1,56 @@
1
+ const fs = require("fs")
2
+ const path = require("path")
3
+
4
+ // The launcher guide: the template from the proto repository with this
5
+ // machine's paths filled in. It is written into an app folder that has none,
6
+ // and it is the `gepeto` managed skill. It is not kept at the top of the home
7
+ // folder, because that folder is above every folder an agent starts in, so an
8
+ // agent that also reads the folders above its own would load it twice.
9
+ // spec/requirements/instruction-sync.md
10
+
11
+ const FILES = [
12
+ "AGENTS.md",
13
+ "CLAUDE.md",
14
+ "GEMINI.md",
15
+ "QWEN.md",
16
+ ".windsurfrules",
17
+ ".cursorrules",
18
+ ".clinerules"
19
+ ]
20
+
21
+ const render = async (kernel, root) => {
22
+ const template = kernel.path("prototype/system/AGENTS.md")
23
+ if (!(await kernel.exists(template))) {
24
+ return ""
25
+ }
26
+ const structure = await fs.promises.readFile(kernel.path("prototype/system/structure/clone"), "utf-8")
27
+ return kernel.renderFile(template, {
28
+ structure,
29
+ examples: kernel.path("prototype/system/examples"),
30
+ browser_logs: kernel.path("logs/browser.log"),
31
+ PINOKIO_DOCUMENTATION: kernel.path("prototype/PINOKIO.md"),
32
+ PTERM_DOCUMENTATION: kernel.path("prototype/PTERM.md"),
33
+ app_root: root,
34
+ proto_path: kernel.path("prototype"),
35
+ home_path: kernel.homedir
36
+ })
37
+ }
38
+
39
+ // Earlier versions wrote the guide at the top of the home folder on every
40
+ // start. Those copies are removed. Every copy Pinokio ever wrote there starts
41
+ // with GUIDE_HEADING; the guide's current first line is checked as well, in
42
+ // case the template's heading changes. A file that starts with neither is the
43
+ // user's own and is left alone.
44
+ const GUIDE_HEADING = "# Development Guide for Pinokio Projects"
45
+ const removeOwn = async (root, guide) => {
46
+ const headings = [GUIDE_HEADING, guide.split(/\r?\n/, 1)[0]].filter(Boolean)
47
+ for (const filename of FILES) {
48
+ const filepath = path.resolve(root, filename)
49
+ const text = await fs.promises.readFile(filepath, "utf8").catch(() => null)
50
+ if (text !== null && headings.includes(text.split(/\r?\n/, 1)[0])) {
51
+ await fs.promises.rm(filepath, { force: true }).catch(() => {})
52
+ }
53
+ }
54
+ }
55
+
56
+ module.exports = { FILES, render, removeOwn }
@@ -378,7 +378,7 @@ class AppLogSessions {
378
378
  run.ended_at = endedAt
379
379
  session.updated_at = endedAt
380
380
  for (const key of this.requestKeys({ ...requestOrRun, path: run.scriptPath })) {
381
- this.activeRunsByKey.delete(key)
381
+ if (this.activeRunsByKey.get(key) === run) this.activeRunsByKey.delete(key)
382
382
  }
383
383
  await this.persistSession(session)
384
384
 
@@ -2,8 +2,8 @@ const fs = require('fs')
2
2
  const fetch = require('cross-fetch')
3
3
  const { rimraf } = require('rimraf')
4
4
  const decompress = require('decompress');
5
- const NODE_VERSION = "24.22.1"
6
- const PNPM_VERSION = "11.9.0"
5
+ const NODE_VERSION = "24.22.3"
6
+ const PNPM_VERSION = "11.24.0"
7
7
 
8
8
  const normalizeVersion = (version) => {
9
9
  const match = String(version || "").match(/^\d+\.\d+\.\d+/)
@@ -3,6 +3,7 @@ const portfinder = require('portfinder-cp')
3
3
  const fs = require('fs')
4
4
  const Util = require('./util')
5
5
  const ManagedSkills = require('./managed_skills')
6
+ const AgentInstructions = require('./agent_instructions')
6
7
  const { pipConfigDisabledPath } = require('./pip_env')
7
8
  const TEMP_ENV_KEYS = ["TMP", "TEMP", "TMPDIR", "PIP_TMPDIR"]
8
9
  const CACHE_ENV_KEYS = ["UV_CACHE_DIR", "PIP_CACHE_DIR"]
@@ -803,45 +804,6 @@ const init = async (options, kernel) => {
803
804
  }
804
805
  const homeRoot = path.resolve(kernel.homedir)
805
806
  const isHomeRoot = path.resolve(root) === homeRoot
806
- const writeFileIfChanged = async (targetPath, content) => {
807
- let shouldWrite = true
808
- try {
809
- const existingContent = await fs.promises.readFile(targetPath, "utf8")
810
- shouldWrite = existingContent !== content
811
- } catch (error) {
812
- if (!(error && error.code === "ENOENT")) {
813
- throw error
814
- }
815
- }
816
-
817
- if (shouldWrite) {
818
- await fs.promises.writeFile(targetPath, content, "utf8")
819
- }
820
- }
821
- const backupFileIfChanged = async (targetPath, desiredContent) => {
822
- let existingContent
823
- try {
824
- existingContent = await fs.promises.readFile(targetPath, "utf8")
825
- } catch (error) {
826
- if (error && error.code === "ENOENT") {
827
- return
828
- }
829
- throw error
830
- }
831
- if (existingContent === desiredContent) {
832
- return
833
- }
834
- const backupPath = `${targetPath}.pinokio.backup`
835
- try {
836
- await fs.promises.access(backupPath, fs.constants.F_OK)
837
- return
838
- } catch (error) {
839
- if (!(error && error.code === "ENOENT")) {
840
- throw error
841
- }
842
- }
843
- await fs.promises.copyFile(targetPath, backupPath)
844
- }
845
807
  let current = path.resolve(root, "ENVIRONMENT")
846
808
  let exists = await kernel.exists(current)
847
809
  if (exists) {
@@ -875,67 +837,13 @@ const init = async (options, kernel) => {
875
837
  }
876
838
  }
877
839
 
878
- const agentTemplatePath = kernel.path("prototype/system/AGENTS.md")
879
- const agentTemplateExists = await kernel.exists(agentTemplatePath)
880
- if (agentTemplateExists) {
881
- const agentFiles = [
882
- "AGENTS.md",
883
- "CLAUDE.md",
884
- "GEMINI.md",
885
- "QWEN.md",
886
- ".windsurfrules",
887
- ".cursorrules",
888
- ".clinerules"
889
- ]
890
- const structure_path = kernel.path("prototype/system/structure/clone")
891
- const structure_content = await fs.promises.readFile(structure_path, "utf-8")
892
- const proto_path = kernel.path("prototype")
893
- const home_path = kernel.homedir
894
- const rendered_recipe = await kernel.renderFile(agentTemplatePath, {
895
- structure: structure_content,
896
- examples: kernel.path("prototype/system/examples"),
897
- browser_logs: kernel.path("logs/browser.log"),
898
- PINOKIO_DOCUMENTATION: kernel.path("prototype/PINOKIO.md"),
899
- PTERM_DOCUMENTATION: kernel.path("prototype/PTERM.md"),
900
- app_root: root,
901
- proto_path,
902
- home_path,
903
- })
840
+ const rendered_recipe = await AgentInstructions.render(kernel, root)
841
+ if (rendered_recipe) {
904
842
  if (isHomeRoot) {
905
- const soulPath = path.resolve(root, "SOUL.md")
906
- let soulExists = await kernel.exists(soulPath)
907
- if (!soulExists) {
908
- for (const filename of agentFiles) {
909
- const destination = path.resolve(root, filename)
910
- await backupFileIfChanged(destination, rendered_recipe)
911
- }
912
- await fs.promises.writeFile(soulPath, "", "utf8")
913
- soulExists = true
914
- }
915
- let renderedOutput = rendered_recipe
916
- if (soulExists) {
917
- const soulContent = await fs.promises.readFile(soulPath, "utf8")
918
- const soulBody = soulContent.trim()
919
- if (soulBody.length > 0) {
920
- const soulWrapper = [
921
- "## User Soul",
922
- "",
923
- "The following instructions come from `SOUL.md`.",
924
- "",
925
- "If this section conflicts with the general Pinokio defaults earlier in this document, follow this section.",
926
- "",
927
- "If there is no conflict, follow both.",
928
- ].join("\n")
929
- const separator = rendered_recipe.endsWith("\n") ? "\n" : "\n\n"
930
- renderedOutput = `${rendered_recipe}${separator}${soulWrapper}\n\n${soulBody}\n`
931
- }
932
- }
933
- for (const filename of agentFiles) {
934
- const destination = path.resolve(root, filename)
935
- await writeFileIfChanged(destination, renderedOutput)
936
- }
843
+ // not kept at the top of the home folder: spec/requirements/instruction-sync.md
844
+ await AgentInstructions.removeOwn(root, rendered_recipe)
937
845
  } else {
938
- for (const filename of agentFiles) {
846
+ for (const filename of AgentInstructions.FILES) {
939
847
  const destination = path.resolve(root, filename)
940
848
  const destinationExists = await kernel.exists(destination)
941
849
  if (!destinationExists) {
@@ -1,6 +1,7 @@
1
1
  const fs = require("fs")
2
2
  const os = require("os")
3
3
  const path = require("path")
4
+ const AgentInstructions = require("./agent_instructions")
4
5
 
5
6
  const INDEX_FILENAME = "index.json"
6
7
  const INDEX_VERSION = 1
@@ -306,7 +307,7 @@ const composeBuiltinSkillContent = async (kernel, id) => {
306
307
  return readSkillContent(path.resolve(__dirname, "../prototype/system/SKILL_PINOKIO.md"))
307
308
  }
308
309
  if (id === "gepeto") {
309
- const agentsContent = await readSkillContent(path.resolve(kernel.homedir, "AGENTS.md"))
310
+ const agentsContent = await AgentInstructions.render(kernel, kernel.homedir).catch(() => "")
310
311
  if (!agentsContent.trim()) {
311
312
  return ""
312
313
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinokiod",
3
- "version": "8.3.7",
3
+ "version": "8.3.9",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -196,15 +196,17 @@ Follow these sections in order:
196
196
 
197
197
  ### 4. Using Apps
198
198
  - Create or reuse one app-specific skill folder for the selected app:
199
- - `<current_working_directory>/pinokio_agent/skills/<scope>/<app_id>/`
199
+ - if a `skill_dir` is given for the app, in its search result or in the request, that folder is the app-specific skill folder; use it exactly as given
200
+ - otherwise `<current_working_directory>/pinokio_agent/skills/<scope>/<app_id>/`
200
201
  - App-specific skill folder structure:
201
202
  - `SKILL.md`: persistent, shareable across machines, not tied to a specific host, filesystem, or path, app-specific delta relative to the workspace/root Pinokio instructions
202
203
  - include frontmatter with only:
203
204
  - `name`: short stable app-specific skill name using lowercase letters, digits, and hyphens only; derive it from a normalized app identity such as `<scope>-<app_id>` and keep it under 64 characters
204
205
  - `description`: one clear sentence describing what this app-specific skill does and when it should be used
206
+ - `version`: the `app_version` given with the `skill_dir`, when there is one
205
207
  - optional `clients/`: reusable local client files
206
208
  - optional `references/`: saved API artifacts such as OpenAPI specs, Gradio config, or concise notes
207
- - outputs: `<app_skill_folder>/output/<target_host>/...`
209
+ - outputs: the output folder named in the request when there is one, otherwise `<app_skill_folder>/output/<target_host>/...`
208
210
 
209
211
  - Saved app-specific `SKILL.md` policy:
210
212
  - treat it as a persistent, shareable delta relative to the workspace/root Pinokio instructions
@@ -235,6 +237,7 @@ Follow these sections in order:
235
237
  - do not add sections such as `Launch command`, `Poll status`, or `Base URL` unless the app has a genuine app-specific exception that is not already covered by the workspace/root Pinokio instructions
236
238
 
237
239
  - Reuse an existing app-specific skill when possible:
240
+ - if a `skill_state` comes with the `skill_dir`: `none` means nothing is saved yet, `current` means the saved skill can be used as it is, and `check` means it was written for a different or unknown version of the app, so verify it against the running app before relying on it and then set its `version` to the current `app_version`
238
241
  - if `<app_skill_folder>/SKILL.md` exists and still describes the app's current API correctly and still follows this policy, read it first and follow it
239
242
  - if the folder already contains a reusable client for the needed operation and it still works against the current app API and does not hardcode per-run values, reuse that client
240
243
  - if the folder has no `SKILL.md`, or the saved instructions or saved client no longer match the current API or this policy, rediscover the app interface and rewrite the app-specific skill folder
package/server/index.js CHANGED
@@ -84,6 +84,7 @@ const WorkspaceStatusManager = require("../kernel/workspace_status")
84
84
  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
+ const { createBrain } = require("./lib/brain")
87
88
  const { createTerminalGitResetHandler } = require("./lib/terminal_git_reset")
88
89
  const { createDesktopEventRouter } = require("./lib/desktop_event_router")
89
90
  const { deletePluginFolder } = require("./lib/plugin_delete")
@@ -11890,6 +11891,12 @@ class Server {
11890
11891
  })
11891
11892
  }
11892
11893
  }))
11894
+ const brain = createBrain({
11895
+ kernel: this.kernel,
11896
+ copyUploads: copyLauncherUploadsToDir,
11897
+ pluginHref: resolveUniversalLauncherPluginHref
11898
+ })
11899
+ this.app.post("/brain/ask", ex(brain.handleAsk))
11893
11900
  this.app.post("/launcher/prepare", ex(async (req, res) => {
11894
11901
  try {
11895
11902
  const body = req.body && typeof req.body === "object" ? req.body : {}
@@ -0,0 +1,279 @@
1
+ "use strict"
2
+
3
+ // The brain: the one folder every Ask from the top bar runs in.
4
+ //
5
+ // <pinokio home>/brain
6
+ // AGENTS.md, CLAUDE.md, GEMINI.md the same fixed instructions
7
+ // me/preferences.md which app the user wants for which kind of task
8
+ // me/log.md one line per Ask
9
+ // me/files/<id>/ the files given to, or made by, one Ask
10
+ //
11
+ // What agents learn about an app is not kept here but in the app's own folder:
12
+ //
13
+ // <pinokio home>/api/<app>/.pinokio-skill
14
+ // SKILL.md, clients/, references/
15
+ //
16
+ // Pinokio, not the agent, does the bookkeeping: it tells the agent where each
17
+ // app's skill is, writes the instruction files and adds a log line. It only
18
+ // rewrites instruction files it wrote itself, and none of this bookkeeping can
19
+ // stop an Ask. An Ask from an app's page runs in the app's own folder, so there
20
+ // the place of the app's skill and the output folder are added to the request.
21
+
22
+ const fs = require("fs")
23
+ const path = require("path")
24
+ const crypto = require("crypto")
25
+ const git = require("isomorphic-git")
26
+ const ManagedSkills = require("../../kernel/managed_skills")
27
+
28
+ const LOG_PROMPT_LENGTH = 200
29
+ const BRAIN_HEADING = "# Pinokio Brain"
30
+ // The same instructions under each name an agent may look for. `AGENTS.md` is
31
+ // read by most agents. Claude skips it when a `CLAUDE.md` is in the folder or
32
+ // any folder above, and Gemini does not read it unless told to.
33
+ const INSTRUCTION_FILES = ["AGENTS.md", "CLAUDE.md", "GEMINI.md"]
34
+ const SKILL_FOLDER = ".pinokio-skill"
35
+
36
+ const brainRoot = (kernel) => kernel.path("brain")
37
+
38
+ // ---- an app's skill ---------------------------------------------------------
39
+ // An app's version is the commit its launcher is at, plus the commit of each
40
+ // repository the launcher keeps the app's code in: a folder directly inside
41
+ // the launcher's folder (`app`, `facefusion`) or directly inside `app`
42
+ // (`app/comfyui`). An update to either one changes the version.
43
+ const commitOf = async (dir) => {
44
+ const repository = await fs.promises.stat(path.resolve(dir, ".git", "HEAD")).then(() => true, () => false)
45
+ return repository ? git.resolveRef({ fs, dir, ref: "HEAD" }).then((oid) => oid.slice(0, 7), () => "") : ""
46
+ }
47
+ const foldersIn = (dir) => {
48
+ return fs.promises.readdir(dir, { withFileTypes: true }).then((entries) => {
49
+ return entries.filter((entry) => entry.isDirectory() && entry.name !== ".git").map((entry) => path.resolve(dir, entry.name)).sort()
50
+ }, () => [])
51
+ }
52
+ const versionOf = async (appDir) => {
53
+ const inside = [...await foldersIn(appDir), ...await foldersIn(path.resolve(appDir, "app"))]
54
+ const commits = await Promise.all([appDir, ...inside].map(commitOf))
55
+ return commits.filter(Boolean).join("+")
56
+ }
57
+ // The app version a saved skill was learned on; null when no skill is saved.
58
+ const skillVersion = async (skillDir) => {
59
+ const content = await fs.promises.readFile(path.resolve(skillDir, "SKILL.md"), "utf8").catch(() => "")
60
+ if (!content) {
61
+ return null
62
+ }
63
+ const head = content.match(/^---\r?\n([\s\S]*?)\r?\n---/)
64
+ const line = head && head[1].match(/^version:\s*(.*)$/m)
65
+ return line ? line[1].trim().replace(/^["']|["']$/g, "") : ""
66
+ }
67
+ const describeApp = async (kernel, appName) => {
68
+ const appDir = kernel.path("api", appName)
69
+ const skillDir = path.resolve(appDir, SKILL_FOLDER)
70
+ const [appVersion, learnedOn] = await Promise.all([versionOf(appDir), skillVersion(skillDir)])
71
+ let state = "none"
72
+ if (learnedOn !== null) {
73
+ state = appVersion && learnedOn !== appVersion ? "check" : "current"
74
+ // The folder keeps itself out of the app's own git: one file that ignores
75
+ // everything in it, written when missing and never replaced.
76
+ await fs.promises.writeFile(path.resolve(skillDir, ".gitignore"), "*\n", { flag: "wx" }).catch(() => {})
77
+ }
78
+ return { skill_dir: skillDir, skill_state: state, app_version: appVersion }
79
+ }
80
+ // Search results tell the agent where each app's skill is, so the agent never
81
+ // has to name the folder itself.
82
+ const addSkills = async (kernel, apps) => {
83
+ if (!Array.isArray(apps)) {
84
+ return apps
85
+ }
86
+ return Promise.all(apps.map(async (app) => {
87
+ try {
88
+ const appName = app && (app.app_id || app.name)
89
+ return appName ? { ...app, ...await describeApp(kernel, appName) } : app
90
+ } catch (_) {
91
+ return app
92
+ }
93
+ }))
94
+ }
95
+
96
+ // ---- before each Ask --------------------------------------------------------
97
+ const createBrain = ({ kernel, copyUploads, pluginHref }) => {
98
+ const two = (number) => String(number).padStart(2, "0")
99
+ const newId = (now) => {
100
+ const day = `${now.getFullYear()}${two(now.getMonth() + 1)}${two(now.getDate())}`
101
+ return `${day}-${crypto.randomBytes(4).toString("hex")}`
102
+ }
103
+
104
+ // Fixed text: it only comes out different when Pinokio's own skills change.
105
+ const buildInstructions = async () => {
106
+ const pinokio = (await ManagedSkills.readEnabledManagedSkillBody(kernel, "pinokio").catch(() => "")).trim()
107
+ const gepeto = await ManagedSkills.getManagedSkill(kernel, "gepeto", { sync: false }).catch(() => null)
108
+ const sections = [
109
+ [
110
+ BRAIN_HEADING,
111
+ "",
112
+ "This file is written by Pinokio. Do not edit it: Pinokio puts its own text back before the next Ask.",
113
+ "",
114
+ "This folder is shared by every Ask on this computer. Other Asks may be running here at the same time, so do not delete or move files you did not create.",
115
+ "",
116
+ "- What was learned about an app is kept in that app's own folder: the `skill_dir` given with the app's search result.",
117
+ "- Files you make for a request go in the output folder named at the end of the request."
118
+ ].join("\n"),
119
+ [
120
+ "## Which app to use",
121
+ "",
122
+ "Before choosing an app, read `me/preferences.md` if it exists. Each line there is the user's own choice of app for a kind of task. A line that fits the request wins over the ranking rules.",
123
+ "",
124
+ "Keep that file right:",
125
+ "- When the user says which app to use for a kind of task, or names an app in a request (\"use X to do Y\"), write one line: the kind of task in a few words, then the app's `app_id` in backticks. Example: ``- speak text aloud: `Qwen3-TTS-MLX` ``",
126
+ "- When no line fits and you had to choose between several apps that could do it, finish the request first. Then ask the user once, in one line, whether to use that app for this kind of task from now on. Write the line only if they say yes.",
127
+ "- Keep one line per kind of task. If there is already one, replace it.",
128
+ "- When the user says to stop using an app for a kind of task, or the app is no longer installed, remove the line.",
129
+ "- Tell the user in one line what you saved or removed."
130
+ ].join("\n")
131
+ ]
132
+ if (pinokio) {
133
+ sections.push(["## Pinokio", "", pinokio].join("\n"))
134
+ }
135
+ if (gepeto && gepeto.enabled && gepeto.valid && gepeto.path) {
136
+ sections.push([
137
+ "## Building launchers",
138
+ "",
139
+ `Before building or changing a Pinokio launcher, read \`${gepeto.path}\`.`
140
+ ].join("\n"))
141
+ }
142
+ return `${sections.join("\n\n")}\n`
143
+ }
144
+ const writeInstructions = async (dir) => {
145
+ const content = await buildInstructions()
146
+ for (const filename of INSTRUCTION_FILES) {
147
+ const filepath = path.resolve(dir, filename)
148
+ // written when missing; rewritten only when its first line is Pinokio's own
149
+ // heading. Any other file, or one that cannot be read, is left alone.
150
+ const existing = await fs.promises.readFile(filepath, "utf8").catch((error) => (error.code === "ENOENT" ? undefined : null))
151
+ const ours = typeof existing === "string" && existing.split(/\r?\n/, 1)[0] === BRAIN_HEADING
152
+ if (existing === undefined || (ours && existing !== content)) {
153
+ await attempt(filename, () => fs.promises.writeFile(filepath, content, "utf8"))
154
+ }
155
+ }
156
+ }
157
+
158
+ const appendLog = async (dir, { id, now, tool, app, prompt }) => {
159
+ const when = `${now.getFullYear()}-${two(now.getMonth() + 1)}-${two(now.getDate())} ${two(now.getHours())}:${two(now.getMinutes())}`
160
+ let asked = prompt.replace(/\s+/g, " ").trim()
161
+ if (asked.length > LOG_PROMPT_LENGTH) {
162
+ asked = `${asked.slice(0, LOG_PROMPT_LENGTH)}…`
163
+ }
164
+ const who = `${String(tool || "agent").replace(/\s+/g, " ").slice(0, 80)}${app ? ` in ${app}` : ""}`
165
+ const line = `- ${when} | ${id} | ${who} | ${asked}\n`
166
+ await fs.promises.appendFile(path.resolve(dir, "me", "log.md"), line, "utf8")
167
+ }
168
+
169
+ // Bookkeeping must never stop an Ask: a step that fails is reported and skipped.
170
+ const attempt = async (what, step) => {
171
+ try {
172
+ return await step()
173
+ } catch (error) {
174
+ console.warn(`[brain] ${what} failed:`, error && error.message ? error.message : error)
175
+ }
176
+ }
177
+
178
+ const makeFolders = (dir) => attempt("folders", () => fs.promises.mkdir(path.resolve(dir, "me", "files"), { recursive: true }))
179
+
180
+ const prepare = async ({ prompt, tool, uploadToken }) => {
181
+ const href = pluginHref(tool)
182
+ const dir = brainRoot(kernel)
183
+ const now = new Date()
184
+ const id = newId(now)
185
+ await fs.promises.mkdir(dir, { recursive: true }) // the agent starts here
186
+ await makeFolders(dir)
187
+
188
+ // The request the agent gets: the user's words, then where this Ask's files are.
189
+ const request = prompt ? [prompt] : []
190
+ if (uploadToken) {
191
+ const filesDir = path.resolve(dir, "me", "files", id)
192
+ await fs.promises.mkdir(filesDir)
193
+ let copied = []
194
+ try {
195
+ copied = await copyUploads(uploadToken, filesDir)
196
+ } finally {
197
+ if (copied.length === 0) {
198
+ await fs.promises.rm(filesDir, { recursive: true, force: true }).catch(() => {})
199
+ }
200
+ }
201
+ if (copied.length > 0) {
202
+ request.push(`Attached files:\n${copied.map((name) => `- me/files/${id}/${name}`).join("\n")}`)
203
+ }
204
+ }
205
+ if (request.length > 0) {
206
+ request.push(`Output folder: me/files/${id}/`)
207
+ }
208
+
209
+ await attempt("instructions", () => writeInstructions(dir))
210
+ await attempt("log", () => appendLog(dir, { id, now, tool, prompt }))
211
+
212
+ const params = new URLSearchParams()
213
+ params.set("cwd", dir)
214
+ params.set("chrome", "full")
215
+ params.set("session", id)
216
+ if (request.length > 0) {
217
+ params.set("prompt", request.join("\n\n"))
218
+ }
219
+ return {
220
+ ok: true,
221
+ cwd: dir,
222
+ url: `${href}?${params.toString()}`
223
+ }
224
+ }
225
+
226
+ // An Ask from an app's page. The agent runs in the app's folder, which the
227
+ // page starts itself; this hands back what the page adds to the request.
228
+ const prepareForApp = async ({ app, prompt, tool }) => {
229
+ const appStat = /^[^/\\:]+$/.test(app) && app !== "." && app !== ".."
230
+ ? await fs.promises.stat(kernel.path("api", app)).catch(() => null)
231
+ : null
232
+ if (!appStat || !appStat.isDirectory()) {
233
+ const error = new Error("App not found.")
234
+ error.status = 404
235
+ throw error
236
+ }
237
+ const dir = brainRoot(kernel)
238
+ const now = new Date()
239
+ const id = newId(now)
240
+ await makeFolders(dir)
241
+
242
+ const { skill_dir, skill_state, app_version } = await describeApp(kernel, app)
243
+ await attempt("log", () => appendLog(dir, { id, now, tool, app, prompt }))
244
+ return {
245
+ ok: true,
246
+ append: [
247
+ "Pinokio brain:",
248
+ `- This app's skill (skill_dir): ${skill_dir} (skill_state: ${skill_state}${app_version ? `, app_version: ${app_version}` : ""})`,
249
+ `- Output folder: ${path.resolve(dir, "me", "files", id)}`
250
+ ].join("\n")
251
+ }
252
+ }
253
+
254
+ const handleAsk = async (req, res) => {
255
+ try {
256
+ const body = req.body && typeof req.body === "object" ? req.body : {}
257
+ const ask = {
258
+ prompt: typeof body.prompt === "string" ? body.prompt.trim() : "",
259
+ tool: typeof body.tool === "string" ? body.tool : "",
260
+ uploadToken: typeof body.uploadToken === "string" ? body.uploadToken.trim() : "",
261
+ app: typeof body.app === "string" ? body.app : ""
262
+ }
263
+ res.json(await (ask.app ? prepareForApp(ask) : prepare(ask)))
264
+ } catch (error) {
265
+ const status = Number.isInteger(error && error.status) ? error.status : 500
266
+ res.status(status).json({
267
+ ok: false,
268
+ error: error && error.message ? error.message : "Failed to prepare the Ask."
269
+ })
270
+ }
271
+ }
272
+
273
+ return { handleAsk }
274
+ }
275
+
276
+ module.exports = {
277
+ addSkills,
278
+ createBrain
279
+ }