pinokiod 8.3.13 → 8.3.15

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 (53) hide show
  1. package/kernel/agent_instructions.js +0 -1
  2. package/kernel/api/index.js +76 -12
  3. package/kernel/environment.js +1 -1
  4. package/kernel/index.js +15 -2
  5. package/kernel/plugin_sources.js +1 -1
  6. package/kernel/prototype.js +1 -1
  7. package/kernel/request_file.js +5 -14
  8. package/kernel/shell.js +12 -0
  9. package/kernel/shells.js +13 -1
  10. package/package.json +1 -1
  11. package/server/index.js +10 -5
  12. package/server/lib/agent_jobs.js +198 -0
  13. package/server/lib/agent_sessions.js +131 -0
  14. package/server/lib/brain.js +161 -91
  15. package/server/lib/content_validation.js +1 -1
  16. package/server/public/agent-bar-app.js +28 -6
  17. package/server/public/agent-bar-compose.css +675 -0
  18. package/server/public/agent-bar-compose.js +658 -0
  19. package/server/public/agent-bar-panel.css +2 -0
  20. package/server/public/agent-bar-panel.js +22 -7
  21. package/server/public/agent-bar-shell.css +38 -0
  22. package/server/public/agent-bar-shell.js +128 -34
  23. package/server/public/agent-bar.css +7 -1
  24. package/server/public/agent-bar.js +10 -1
  25. package/server/public/terminal_input_utils.js +4 -0
  26. package/server/views/app.ejs +5 -1
  27. package/server/views/partials/main_sidebar.ejs +2 -0
  28. package/system/plugin/antigravity-cli-auto/pinokio.js +44 -6
  29. package/system/plugin/claude/pinokio.js +43 -1
  30. package/system/plugin/claude-auto/pinokio.js +43 -1
  31. package/system/plugin/codex/pinokio.js +42 -1
  32. package/system/plugin/codex-auto/pinokio.js +42 -1
  33. package/system/plugin/grok/pinokio.js +1 -1
  34. package/system/plugin/grok-auto/pinokio.js +37 -10
  35. package/system/plugin/opencode/pinokio.js +24 -0
  36. package/system/plugin/opencode-auto/pinokio.js +82 -10
  37. package/test/agent-bar-compose.test.js +544 -0
  38. package/test/agent-bar-shell.test.js +149 -0
  39. package/test/agent-instructions.test.js +0 -2
  40. package/test/agent-jobs.test.js +534 -0
  41. package/test/agent-sessions.test.js +130 -0
  42. package/test/antigravity-cli-plugin.test.js +63 -18
  43. package/test/anywhere-api.test.js +1 -1
  44. package/test/anywhere-onboarding.test.js +1 -2
  45. package/test/brain.test.js +116 -69
  46. package/test/grok-plugin.test.js +2 -1
  47. package/test/opencode-plugin.test.js +7 -4
  48. package/test/plugin-action-functions.test.js +423 -0
  49. package/test/request-file.test.js +1 -12
  50. package/test/shell-log-path.test.js +64 -0
  51. package/test/shell-stop-while-starting.test.js +70 -0
  52. package/test/shells-live-error.test.js +66 -2
  53. package/test/terminal-mouse-input.test.js +12 -0
@@ -6,7 +6,6 @@ const path = require("path")
6
6
  // and it is the `gepeto` managed skill. It is not kept at the top of the home
7
7
  // folder, because that folder is above every folder an agent starts in, so an
8
8
  // agent that also reads the folders above its own would load it twice.
9
- // spec/requirements/instruction-sync.md
10
9
 
11
10
  const FILES = [
12
11
  "AGENTS.md",
@@ -33,6 +33,10 @@ class Api {
33
33
  this.running = {}
34
34
  this.running_paths = {}
35
35
  this.done = {}
36
+ // The running jobs, by id: the requests of Pinokio's job runner
37
+ // (server/lib/agent_jobs.js). Only a request in here may run a plugin's
38
+ // `job`. A job is kept by its id and by nothing else: see isJob.
39
+ this.jobs = new Map()
36
40
  this.waiter = {}
37
41
  this.proxies = {}
38
42
  this.mods = {}
@@ -426,6 +430,37 @@ class Api {
426
430
  delete this.running[id]
427
431
  delete this.running_paths[id]
428
432
  }
433
+ // A job's request. A job is kept by its id: it does not answer a script that
434
+ // waits for the plugin's file, and says and records nothing under the
435
+ // plugin's path. Only process() lets a `job` in.
436
+ isJob(request) {
437
+ return !!request && request.action === "job"
438
+ }
439
+ // Ends a job: lets go of everything kept under its id, and says so once.
440
+ // False when there is no such job any more.
441
+ endJob(id) {
442
+ if (!this.jobs.has(id)) {
443
+ return false
444
+ }
445
+ try {
446
+ this.kernel.shell.kill({ group: id }) // while the job is known: its shells keep no log (kernel.log)
447
+ } finally {
448
+ // whatever became of the kill, the job is let go of: no further step of it runs
449
+ this.jobs.delete(id)
450
+ this.forgetJob(id)
451
+ this.ondata({ id, type: "disconnect" })
452
+ }
453
+ return true
454
+ }
455
+ // What is kept under a job's id.
456
+ forgetJob(id) {
457
+ this.clearResolvedAction(id)
458
+ this.clearRunning(id)
459
+ delete this.done[id]
460
+ for (const kept of ["local", "global", "rpc", "args", "input"]) {
461
+ delete this.kernel.memory[kept][id]
462
+ }
463
+ }
429
464
  setRunning(request, done) {
430
465
  const id = this.requestId(request)
431
466
  if (!id) {
@@ -537,7 +572,7 @@ class Api {
537
572
  async resolveActionSteps({ request, script, scriptDir, actionKey, input, args }) {
538
573
  const id = this.requestId(request)
539
574
 
540
- if (actionKey === "run" && script && typeof script.installed === "function" && this.isActionCandidate(script.install)) {
575
+ if ((actionKey === "run" || actionKey === "job") && script && typeof script.installed === "function" && this.isActionCandidate(script.install)) {
541
576
  let installed = null
542
577
  try {
543
578
  const context = await this.actionContext({ request, script, scriptDir, actionKey: "installed", input, args })
@@ -546,7 +581,10 @@ class Api {
546
581
  console.warn("Plugin installed check failed", request && request.path, error)
547
582
  }
548
583
  if (installed === false) {
549
- return [this.pluginInstallNoticeStep(request, script)]
584
+ // a job has no page to show the notice on: it prints it
585
+ return [actionKey === "job"
586
+ ? { method: "log", params: { raw: `${script.title || "This plugin"} is not installed. Open its plugin page in Pinokio and click Install.\n` } }
587
+ : this.pluginInstallNoticeStep(request, script)]
550
588
  }
551
589
  }
552
590
 
@@ -572,6 +610,9 @@ class Api {
572
610
  return steps
573
611
  }
574
612
  async stop(req, ondata, options = {}) {
613
+ if (req.params.id && this.jobs.has(req.params.id)) {
614
+ return this.endJob(req.params.id)
615
+ }
575
616
  // 1. set the "stop" flag for the uri, so the next execution in the queue for the uri will NOT queue another task
576
617
  // 2. stream a message closing the socket
577
618
 
@@ -1170,7 +1211,7 @@ class Api {
1170
1211
  rpc: rawrpc,
1171
1212
  rawrpc
1172
1213
  })
1173
- if (i === 0 && request.path) {
1214
+ if (i === 0 && request.path && !this.isJob(request)) {
1174
1215
  // also emit using the script path id so it is guaranteed to hit disk logs
1175
1216
  this.ondata({
1176
1217
  id: request.path,
@@ -1185,8 +1226,12 @@ class Api {
1185
1226
  } catch (_) {}
1186
1227
 
1187
1228
 
1188
- this.state = memory
1189
- this.executing = request
1229
+ // what ran last, for a script. A job is kept by its id and by nothing else,
1230
+ // so nothing here goes on pointing at it once it has ended.
1231
+ if (!this.isJob(request)) {
1232
+ this.state = memory
1233
+ this.executing = request
1234
+ }
1190
1235
  // get fully resolved env
1191
1236
  let env = await Environment.get2(request.path, this.kernel)
1192
1237
  // set template
@@ -1244,7 +1289,7 @@ class Api {
1244
1289
  // 8. the endpoint must exist
1245
1290
  if (!resolved.method) {
1246
1291
  this.ondata({
1247
- id: request.path,
1292
+ id: request.id || request.path,
1248
1293
  type: "error",
1249
1294
  data: "RPC endpoint doesn't exist: " + JSON.stringify(rpc),
1250
1295
  rpc,
@@ -1282,7 +1327,7 @@ class Api {
1282
1327
 
1283
1328
  this.kernel.memory.rpc[id].current = rpc.current
1284
1329
  this.kernel.memory.rpc[id].total = rpc.total
1285
- if (this.kernel && typeof this.kernel.markAppLaunchProgress === "function") {
1330
+ if (!this.isJob(request) && this.kernel && typeof this.kernel.markAppLaunchProgress === "function") {
1286
1331
  this.kernel.markAppLaunchProgress(request.path, rpc.current, rpc.total)
1287
1332
  }
1288
1333
 
@@ -1337,7 +1382,7 @@ class Api {
1337
1382
  //if (!rpc.when) {
1338
1383
  if (typeof rpc.next === "undefined" || rpc.next === null) {
1339
1384
  // last call
1340
- if (script.daemon) {
1385
+ if (script.daemon && !this.isJob(request)) {
1341
1386
  this.ondata({
1342
1387
  id: request.id || request.path,
1343
1388
  type: "start",
@@ -1575,8 +1620,8 @@ class Api {
1575
1620
 
1576
1621
 
1577
1622
  // kill all connected shells
1578
- // if not daemon
1579
- if (script.daemon) {
1623
+ // if not daemon: a job ends when its steps are over, whatever the plugin's file says
1624
+ if (script.daemon && !this.isJob(request)) {
1580
1625
  this.ondata({
1581
1626
  id: request.id || request.path,
1582
1627
  type: "start",
@@ -1709,7 +1754,7 @@ class Api {
1709
1754
  }
1710
1755
  } else {
1711
1756
  let id = request.id || request.path
1712
- if (this.done[request.path]) {
1757
+ if (!this.isJob(request) && this.done[request.path]) {
1713
1758
  this.done[request.path]({
1714
1759
  global: (this.kernel.memory.global[id] || {}),
1715
1760
  local: (this.kernel.memory.local[id] || {}),
@@ -1726,7 +1771,17 @@ class Api {
1726
1771
  if (this.logSessions) {
1727
1772
  await this.logSessions.finishRun(request, { internal_completion: true })
1728
1773
  }
1729
- ondata({ raw: e.toString() })
1774
+ this.ondata({
1775
+ id: request.id || request.path,
1776
+ type: "error",
1777
+ data: e && e.stack ? e.stack : String(e)
1778
+ })
1779
+ } finally {
1780
+ // a job that ended while this step was starting or working: what the
1781
+ // step put under its id goes too
1782
+ if (this.isJob(request) && !this.jobs.has(request.id)) {
1783
+ this.forgetJob(request.id)
1784
+ }
1730
1785
  }
1731
1786
  }, concurrency)
1732
1787
  }
@@ -1910,6 +1965,15 @@ class Api {
1910
1965
  const actionKey = request.action || 'run'
1911
1966
  request.action = actionKey
1912
1967
  const action = script ? script[actionKey] : null
1968
+ // a plugin's `job` runs only for the job runner's own request
1969
+ if (actionKey === "job" && this.jobs.get(request.id) !== request) {
1970
+ this.ondata({
1971
+ id: request.id || request.path,
1972
+ type: "error",
1973
+ data: "A plugin's job is started by Pinokio's job runner only."
1974
+ })
1975
+ return
1976
+ }
1913
1977
 
1914
1978
  // 3. Check if the resolved endpoint has the requested action attribute and resolve it to steps.
1915
1979
  if (this.isActionCandidate(action)) {
@@ -840,7 +840,7 @@ const init = async (options, kernel) => {
840
840
  const rendered_recipe = await AgentInstructions.render(kernel, root)
841
841
  if (rendered_recipe) {
842
842
  if (isHomeRoot) {
843
- // not kept at the top of the home folder: spec/requirements/instruction-sync.md
843
+ // not kept at the top of the home folder (kernel/agent_instructions.js says why)
844
844
  await AgentInstructions.removeOwn(root, rendered_recipe)
845
845
  } else {
846
846
  for (const filename of AgentInstructions.FILES) {
package/kernel/index.js CHANGED
@@ -590,6 +590,10 @@ class Kernel {
590
590
  return loaded.resolved
591
591
  }
592
592
  log(data, group, info) {
593
+ // a job keeps what it prints in its own folder (server/lib/agent_jobs.js)
594
+ if (this.api && this.api.jobs && this.api.jobs.has(group)) {
595
+ return
596
+ }
593
597
  this.log_queue.push({ data, group, info })
594
598
  }
595
599
  async network_active() {
@@ -737,8 +741,17 @@ class Kernel {
737
741
  // 9. announce self to the peer network
738
742
  this.peer.announce()
739
743
  }
744
+ // Where a shell's log is kept under logs/shell/<type>: the path of its group
745
+ // from the home. What comes with Pinokio, such as a built-in plugin, is
746
+ // outside the home: it is kept under `system`, by its path from there.
747
+ shellLogPath(group) {
748
+ const fromHome = path.relative(this.homedir, group)
749
+ const fromSystem = path.relative(this.systemPath(), group)
750
+ const own = path.isAbsolute(group) && fromHome.startsWith("..") && !fromSystem.startsWith("..") && !path.isAbsolute(fromSystem)
751
+ return own ? path.join("system", fromSystem) : fromHome
752
+ }
740
753
  async clearLog(group) {
741
- let relativePath = path.relative(this.homedir, group)
754
+ let relativePath = this.shellLogPath(group)
742
755
  for(let type of ["info", "buf", "cleaned"]) {
743
756
  let logPath = path.resolve(this.homedir, "logs", "shell", type, relativePath)
744
757
  let logFolder = path.dirname(logPath)
@@ -814,7 +827,7 @@ class Kernel {
814
827
  if (group) {
815
828
 
816
829
  // 1. prepare data
817
- let relativePath = path.relative(this.homedir, group)
830
+ let relativePath = this.shellLogPath(group)
818
831
 
819
832
  if (!path.isAbsolute(relativePath)) {
820
833
  for(let type of ["cleaned"]) {
@@ -10,7 +10,7 @@ const LOCAL_PLUGIN_RUN_PREFIX = `${LOCAL_RUN_PREFIX}/plugin`
10
10
  const LOCAL_PLUGIN_ASSET_PREFIX = `${LOCAL_ASSET_PREFIX}/plugin`
11
11
  const SYSTEM_PLUGIN_RUN_PREFIX = `${SYSTEM_RUN_PREFIX}/plugin`
12
12
  const SYSTEM_PLUGIN_ASSET_PREFIX = `${SYSTEM_ASSET_PREFIX}/plugin`
13
- const ACTION_KEYS = new Set(["run", "install", "uninstall", "update"])
13
+ const ACTION_KEYS = new Set(["run", "job", "install", "uninstall", "update"])
14
14
  const STATUS_KEYS = new Set(["installed"])
15
15
  const FUNCTION_KEYS = new Set([...ACTION_KEYS, ...STATUS_KEYS])
16
16
  const BUILTIN_TOOL_ALIASES = {
@@ -127,7 +127,7 @@ class Proto {
127
127
  let response = await mod(payload, ondata, this.kernel)
128
128
  // A new app whose agent is started with the user's words: the words are in
129
129
  // SPEC.md, and the address carries the line that points to it instead
130
- // (kernel/request_file.js, spec/requirements/request-files.md).
130
+ // (kernel/request_file.js).
131
131
  if (response && typeof response.success === "string") {
132
132
  response.success = await RequestFile.pointAddressToSpec(response.success, payload.cwd)
133
133
  }
@@ -1,27 +1,18 @@
1
1
  "use strict"
2
2
 
3
- // How the text of a request reaches an agent: the request is in a file inside
4
- // the folder the agent starts in, and the plugin is started with one line that
5
- // points to the file. spec/requirements/request-files.md
3
+ // How the text of a request reaches an agent: the request is in a file, and the
4
+ // plugin is started with one line that points to the file.
6
5
 
7
6
  const fs = require("fs")
8
7
  const path = require("path")
9
8
 
10
- const FOLDER = [".pinokio-temp", "requests"]
11
9
  const SPEC = "SPEC.md"
12
10
 
13
11
  // The request line. `file` is relative to the folder the agent starts in, with
14
- // `/` on every system.
12
+ // `/` on every system: a session's request.md (server/lib/agent_sessions.js),
13
+ // or SPEC.md.
15
14
  const line = (file) => `My message is in ${file}. Read it and respond as if I had typed it here.`
16
15
 
17
- // An Ask: writes the request into `cwd` and gives back the request line.
18
- const save = async (cwd, id, text) => {
19
- const dir = path.resolve(cwd, ...FOLDER)
20
- await fs.promises.mkdir(dir, { recursive: true })
21
- await fs.promises.writeFile(path.resolve(dir, `${id}.md`), `${text}\n`, "utf8")
22
- return line([...FOLDER, `${id}.md`].join("/"))
23
- }
24
-
25
16
  // Create app and Create plugin: the new folder already holds the user's words as
26
17
  // SPEC.md. Gives back the request line for it, or null when SPEC.md is not there
27
18
  // or holds something else.
@@ -50,4 +41,4 @@ const pointAddressToSpec = async (address, cwd) => {
50
41
  return `${url.pathname}${url.search}${url.hash}`
51
42
  }
52
43
 
53
- module.exports = { line, save, forSpec, pointAddressToSpec }
44
+ module.exports = { line, forSpec, pointAddressToSpec }
package/kernel/shell.js CHANGED
@@ -536,6 +536,9 @@ class Shell {
536
536
  // 2. env
537
537
  // default env
538
538
  await this.init_env(params)
539
+ if (this.ownerStopped()) {
540
+ return ""
541
+ }
539
542
 
540
543
 
541
544
  this.ondata({ raw: `\r\n████\r\n██ Starting Shell ${this.id}\r\n` })
@@ -1507,6 +1510,11 @@ class Shell {
1507
1510
  // })
1508
1511
  return params
1509
1512
  }
1513
+ // The run this shell was started for was stopped while the shell was still
1514
+ // starting: nothing is launched for it.
1515
+ ownerStopped() {
1516
+ return typeof this.ownerActive === "function" && !this.ownerActive()
1517
+ }
1510
1518
  async exec(params) {
1511
1519
  this.parser = new ShellParser()
1512
1520
  this.emitEnvArgsPreview(params)
@@ -1521,6 +1529,10 @@ class Shell {
1521
1529
  this.commandEchoPreview = preparedCommand.preview || null
1522
1530
  this.commandEchoPreviewed = false
1523
1531
  this.quietCmdExecution = !!preparedCommand.quietCmd
1532
+ if (!this.ptyProcess && this.ownerStopped()) {
1533
+ this.kernel.shell.rm(this.id)
1534
+ return ""
1535
+ }
1524
1536
  let res = await new Promise((resolve, reject) => {
1525
1537
  this.resolve = resolve
1526
1538
  this.reject = reject
package/kernel/shells.js CHANGED
@@ -279,6 +279,12 @@ class Shells {
279
279
  if (!parentMeta || !parentMeta.path) {
280
280
  throw new Error(`unable to trigger "${action}" without a parent script`)
281
281
  }
282
+ if (action === "job") {
283
+ throw new Error("A plugin's job is started by Pinokio's job runner only.")
284
+ }
285
+ if (parentMeta.action === "job") {
286
+ throw new Error("A job's steps cannot trigger another action.")
287
+ }
282
288
 
283
289
  const runningKey = getParentRunningKey()
284
290
  if (runningKey && !this.kernel.api.running[runningKey]) {
@@ -447,7 +453,11 @@ class Shells {
447
453
  event: "/error:.*triton/i",
448
454
  break: false
449
455
  }]
450
- params.on = params.on.concat(defaultHandlers)
456
+ // What a job's agent prints is its own text: only handlers the plugin
457
+ // wrote itself apply to it.
458
+ if (!(params.$parent && params.$parent.action === "job")) {
459
+ params.on = params.on.concat(defaultHandlers)
460
+ }
451
461
 
452
462
  const collectBreakErrors = (text) => {
453
463
  const errors = new Set()
@@ -502,6 +512,8 @@ class Shells {
502
512
  if (!isParentRequestActive()) {
503
513
  return ""
504
514
  }
515
+ // starting takes a moment: the shell asks again before it launches anything
516
+ sh.ownerActive = isParentRequestActive
505
517
 
506
518
  let response = await sh.start(params, async (stream, type) => {
507
519
  /*
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinokiod",
3
- "version": "8.3.13",
3
+ "version": "8.3.15",
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 { createJobs, registerJobRoutes } = require("./lib/agent_jobs")
88
89
  const RequestFile = require("../kernel/request_file")
89
90
  const { createTerminalGitResetHandler } = require("./lib/terminal_git_reset")
90
91
  const { createDesktopEventRouter } = require("./lib/desktop_event_router")
@@ -1035,7 +1036,7 @@ class Server {
1035
1036
  } catch (_) { }
1036
1037
  return null
1037
1038
  }
1038
- // the installed catalog for the phone dashboard (spec/requirements/pinokio-anywhere-api.md)
1039
+ // the installed catalog for the phone dashboard
1039
1040
  async composeAnywhereApps() {
1040
1041
  const entries = await this.kernel.api.listApps()
1041
1042
  return { apps: entries.map((entry) => ({ id: entry.id, name: entry.title || entry.name || entry.id, icon: entry.icon })) }
@@ -9608,7 +9609,7 @@ class Server {
9608
9609
  params.set("chrome", "full")
9609
9610
  if (prompt) {
9610
9611
  // Create plugin: the words are in SPEC.md, and the agent is started with
9611
- // the line that points to it (spec/requirements/request-files.md).
9612
+ // the line that points to it.
9612
9613
  const requestLine = normalizedType === "create_plugin" ? await RequestFile.forSpec(targetPath, prompt) : null
9613
9614
  params.set("prompt", requestLine || prompt)
9614
9615
  }
@@ -11901,6 +11902,10 @@ class Server {
11901
11902
  pluginHref: resolveUniversalLauncherPluginHref
11902
11903
  })
11903
11904
  this.app.post("/brain/ask", ex(brain.handleAsk))
11905
+ registerJobRoutes(this.app, {
11906
+ jobs: createJobs({ kernel: this.kernel, ended: brain.jobEnded }),
11907
+ prepare: brain.prepareJob
11908
+ })
11904
11909
  this.app.post("/launcher/prepare", ex(async (req, res) => {
11905
11910
  try {
11906
11911
  const body = req.body && typeof req.body === "object" ? req.body : {}
@@ -17061,10 +17066,10 @@ class Server {
17061
17066
  const stored = [];
17062
17067
  for (const file of files) {
17063
17068
  if (!file || !file.buffer) continue;
17064
- const filename = path.basename(file.originalname || "file");
17065
- const target = path.resolve(baseDir, filename);
17069
+ // never onto a file of this upload: two names can be the same, or differ only in capital letters
17070
+ const target = await resolveLauncherUploadCopyTarget(baseDir, file.originalname);
17066
17071
  await fs.promises.writeFile(target, file.buffer);
17067
- stored.push({ name: filename, size: file.size });
17072
+ stored.push({ name: path.basename(target), size: file.size });
17068
17073
  }
17069
17074
  if (!stored.length) {
17070
17075
  return res.status(400).json({ error: "No valid files provided" });
@@ -0,0 +1,198 @@
1
+ "use strict"
2
+
3
+ // Runs a plugin's `job`: the agent's one-off command, with no page and nobody
4
+ // to answer it. A job runs until its steps end or it is stopped: Pinokio limits
5
+ // neither how many run nor for how long. What a job prints is kept as
6
+ // terminal.txt in its folder. Pinokio learns that a job ended, never whether it
7
+ // did what was asked. Only this runner starts a plugin's `job`: the kernel
8
+ // refuses one from anywhere else, and keeps a job by its id only
9
+ // (kernel/api/index.js, isJob and endJob).
10
+
11
+ const fs = require("fs")
12
+ const path = require("path")
13
+
14
+ // ---- what a terminal printed, as plain text ---------------------------------
15
+ // What a terminal draws with: a window title and the like (ended by a bell or
16
+ // by ESC \), then the pattern the shell itself strips.
17
+ const DRAWING = new RegExp([
18
+ "\\u001B\\][^\\u0007\\u001B]*(?:\\u0007|\\u001B\\\\)",
19
+ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
20
+ "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-Za-z=><~]))"
21
+ ].join("|"), "g")
22
+ // Each piece of output is cleaned by itself. terminal.txt is a record for
23
+ // reading, with no format: a code cut across two pieces may leave a few
24
+ // characters in it.
25
+ const plain = (text) => text.replace(DRAWING, "").replace(/\r\n?/g, "\n")
26
+
27
+ // ---- the jobs ---------------------------------------------------------------
28
+ // kernel its api runs the plugin and tells what happens to each run
29
+ // ended called with a job's id when it has ended, however it ended
30
+ const createJobs = ({ kernel, ended }) => {
31
+ // Every job since Pinokio started, by id: what a running one needs, and then
32
+ // only the word "ended".
33
+ const jobs = new Map()
34
+
35
+ // The one way a job ends, whatever ended it: its steps are over, one of them
36
+ // failed, it was stopped, or it never started. The kernel lets go of what it
37
+ // holds for the job, what the job printed is written out, and only then is it
38
+ // "ended". Everything that ends a job waits for this same result.
39
+ const end = (id) => {
40
+ const job = jobs.get(id)
41
+ if (!job || job === "ended") {
42
+ return null
43
+ }
44
+ if (!job.ending) {
45
+ job.ending = Promise.resolve().then(async () => {
46
+ await job.written
47
+ jobs.set(id, "ended")
48
+ await Promise.resolve().then(() => ended(id)).catch((error) => {
49
+ console.warn("[brain] job:", error && error.message ? error.message : error)
50
+ })
51
+ })
52
+ try {
53
+ kernel.api.endJob(id) // after `ending` is set: the kernel answers with `disconnect`
54
+ } catch (error) {
55
+ console.warn("[brain] job:", error && error.message ? error.message : error)
56
+ }
57
+ }
58
+ return job.ending
59
+ }
60
+
61
+ // One listener for every job. The kernel says `disconnect` when a run is
62
+ // over, whoever stopped it.
63
+ const listen = (packet) => {
64
+ const job = packet && jobs.get(packet.id)
65
+ if (!job || job === "ended" || job.ending) {
66
+ return
67
+ }
68
+ if (packet.type === "stream" && packet.data && typeof packet.data.raw === "string") {
69
+ job.print(plain(packet.data.raw))
70
+ } else if (packet.type === "error") {
71
+ // the plugin's steps failed: there is nothing more to wait for
72
+ job.print(`\n${typeof packet.data === "string" ? packet.data : JSON.stringify(packet.data)}\n`)
73
+ end(packet.id)
74
+ } else if (packet.type === "disconnect") {
75
+ end(packet.id)
76
+ }
77
+ }
78
+ kernel.api.listen("jobs", listen)
79
+
80
+ // Starts a job whose folder is ready: { id, script, cwd, dir, prompt }.
81
+ // script the plugin's file
82
+ // cwd the folder the agent starts in
83
+ // dir the job's folder
84
+ // prompt the request line
85
+ const add = ({ id, script, cwd, dir, prompt }) => {
86
+ const file = path.resolve(dir, "terminal.txt")
87
+ let failed = false
88
+ const write = (step) => step.catch((error) => {
89
+ if (!failed) {
90
+ failed = true
91
+ console.warn(`[brain] job ${id}: what it prints cannot be kept:`, error && error.message ? error.message : error)
92
+ }
93
+ })
94
+ const job = { written: write(fs.promises.writeFile(file, "", "utf8")) }
95
+ job.print = (text) => {
96
+ if (text) {
97
+ job.written = job.written.then(() => write(fs.promises.appendFile(file, text, "utf8")))
98
+ }
99
+ }
100
+ jobs.set(id, job)
101
+
102
+ // the plugin receives the folder and the prompt, nothing else
103
+ const request = { id, uri: script, path: script, cwd, action: "job", input: { cwd, prompt } }
104
+ kernel.api.jobs.set(id, request) // only a request the kernel knows as a job may run one
105
+ // a start that fails is an error of the job like any other
106
+ kernel.api.process(request).catch((error) => listen({ id, type: "error", data: error && error.message ? error.message : String(error) }))
107
+ }
108
+
109
+ // "running" or "ended"; null for a job Pinokio does not know.
110
+ const state = (id) => (!jobs.has(id) ? null : jobs.get(id) === "ended" ? "ended" : "running")
111
+
112
+ // Stops a running job, and gives back its state once it has ended.
113
+ const stop = async (id) => {
114
+ await end(id)
115
+ return state(id)
116
+ }
117
+
118
+ return { add, state, stop }
119
+ }
120
+
121
+ // ---- the calls --------------------------------------------------------------
122
+ // A job runs an agent with nobody watching, so only this computer may start
123
+ // one: a program here, or Pinokio's own page opened here.
124
+ const isThisComputer = (address) => {
125
+ const value = String(address || "").toLowerCase().replace(/^::ffff:/, "")
126
+ return value === "::1" || value === "localhost" || /^127(?:\.\d{1,3}){3}$/.test(value)
127
+ }
128
+ const hostOf = (host) => {
129
+ try {
130
+ return new URL(`http://${host}`).hostname.replace(/^\[|\]$/g, "").toLowerCase()
131
+ } catch (_) {
132
+ return ""
133
+ }
134
+ }
135
+ const isLocal = (req) => {
136
+ if (!isThisComputer(req.socket && req.socket.remoteAddress) || !isThisComputer(hostOf(req.get("host")))) {
137
+ return false
138
+ }
139
+ // passed on by something in between, or by another Pinokio
140
+ if (["forwarded", "x-forwarded-for", "x-forwarded-host", "x-forwarded-proto", "x-pinokio-peer"].some((name) => req.get(name))) {
141
+ return false
142
+ }
143
+ // a page in a browser: only Pinokio's own
144
+ const origin = req.get("origin")
145
+ if (origin) {
146
+ try {
147
+ const from = new URL(origin)
148
+ return from.protocol === "http:" && from.host.toLowerCase() === String(req.get("host") || "").toLowerCase()
149
+ } catch (_) {
150
+ return false
151
+ }
152
+ }
153
+ return true
154
+ }
155
+
156
+ // POST /brain/job { plugin, cwd, prompt, from, label } -> { ok, id, cwd }
157
+ // GET /brain/job/<id> -> { ok, id, state }
158
+ // POST /brain/job/<id>/stop -> { ok, id, state }
159
+ // prepare(job) makes the job's folder and gives back what `add` takes (brain.js)
160
+ const registerJobRoutes = (app, { jobs, prepare }) => {
161
+ const text = (value) => (typeof value === "string" ? value.trim() : "")
162
+ const answer = (handle) => async (req, res) => {
163
+ res.set("Cache-Control", "no-store")
164
+ try {
165
+ if (!isLocal(req)) {
166
+ throw Object.assign(new Error("Only this computer may use jobs."), { status: 403 })
167
+ }
168
+ res.json({ ok: true, ...await handle(req) })
169
+ } catch (error) {
170
+ res.status(Number.isInteger(error && error.status) ? error.status : 500).json({
171
+ ok: false,
172
+ error: error && error.message ? error.message : "The job call failed."
173
+ })
174
+ }
175
+ }
176
+ const known = (id, state) => {
177
+ if (!state) {
178
+ throw Object.assign(new Error("Job not found."), { status: 404 })
179
+ }
180
+ return { id, state }
181
+ }
182
+ app.post("/brain/job", answer(async (req) => {
183
+ const body = req.body && typeof req.body === "object" ? req.body : {}
184
+ const job = await prepare({
185
+ plugin: text(body.plugin),
186
+ cwd: body.cwd === undefined || typeof body.cwd === "string" ? text(body.cwd) : body.cwd, // anything else is refused
187
+ prompt: text(body.prompt),
188
+ from: text(body.from),
189
+ label: text(body.label)
190
+ })
191
+ jobs.add(job)
192
+ return { id: job.id, cwd: job.cwd }
193
+ }))
194
+ app.get("/brain/job/:id", answer(async (req) => known(req.params.id, jobs.state(req.params.id))))
195
+ app.post("/brain/job/:id/stop", answer(async (req) => known(req.params.id, await jobs.stop(req.params.id))))
196
+ }
197
+
198
+ module.exports = { createJobs, plain, registerJobRoutes, isLocal }