@assuredloop/orca-bot-kit 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -508,7 +508,7 @@ verdict: which of these matter, and in what order, is for you or for Bot Father.
508
508
  ## Sessions and bots that talk
509
509
 
510
510
  Ask the kit how to reach a session, and it answers with the road and the
511
- address ([ADR 0018](docs/adr/0018-messaging-transport.md)):
511
+ address ([ADR 0030](docs/adr/0030-messaging-transport.md)):
512
512
 
513
513
  ```sh
514
514
  obk message to --bots /path/to/my-bots --to api-bot/daily
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assuredloop/orca-bot-kit",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,21 @@
1
+ ---
2
+ name: temporary
3
+ title: Temporary sessions of your own
4
+ applies: all
5
+ ---
6
+
7
+ For a piece of work that wants a helper, a long-lived session may make a
8
+ temporary session of its own bot, without asking Bot Father:
9
+ `"${OBK_CLI:-obk}" temp make --bots <bots> --name <name> --prompt <the task>`,
10
+ run in your own tab. It takes your settings unless you say otherwise, and gets
11
+ a work dir, a tab and a mailbox.
12
+
13
+ A new tab can stop on a first-run screen. Answer it yourself, from the table
14
+ the command's output points to.
15
+
16
+ Retire it when its work is done:
17
+ `"${OBK_CLI:-obk}" temp retire --bots <bots> --name <name>`. Before you make
18
+ another, first retire any of yours whose work is done.
19
+
20
+ You manage only the temporary sessions you made; a temporary session makes
21
+ none of its own. Every other session is Bot Father's to make, change or retire.
package/src/book.js CHANGED
@@ -30,6 +30,9 @@ const HEADER = `# What Orca calls this bot on this machine, and where each of it
30
30
  #
31
31
  # \`retired\` holds what the book knew about each session \`obk retire\` took off
32
32
  # the bot, with when, so the conversations it had are still accounted for.
33
+ #
34
+ # \`temporary\` marks a session another session of this bot made with
35
+ # \`obk temp make\`: which session made it, and when. Its maker retires it.
33
36
  `;
34
37
 
35
38
  export const bookFile = (home) => path.join(home, 'sessions.yaml');
package/src/bot.js CHANGED
@@ -21,7 +21,7 @@ export const botsDir = (bots) => path.join(bots, 'bots');
21
21
  export const botDir = (bots, name) => path.join(botsDir(bots), name);
22
22
 
23
23
  /** A bot's name: the folder it lives in, and safe to be one. */
24
- const NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
24
+ export const NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
25
25
 
26
26
  /** The file that says what a bot is. A folder without one is not a bot. */
27
27
  const BOT_YAML = 'bot.yaml';
package/src/cli.js CHANGED
@@ -17,8 +17,8 @@ import { addCommand, groomCommand, grooming, upCommand } from './groom.js';
17
17
  import { checkHealth, orcaSettingFindings } from './health.js';
18
18
  import { initBots } from './init.js';
19
19
  import { APPROVALS, HARNESSES, ownCli, shellWord, workDirOf } from './launch.js';
20
- import { checkMail, lookUp, noMailboxYet, sendMessage } from './message.js';
21
- import { orcaCli, orcaTrouble, RELOAD_LINE } from './orca.js';
20
+ import { checkMail, lookUp, noMailboxYet, sendMessage, sessionInTab } from './message.js';
21
+ import { orcaCli, orcaTrouble, RELOAD_LINE, TERMINAL_ENV } from './orca.js';
22
22
  import { allowCommand, allowIn, beyondDefaults, refuseBroad, refuseNoCodexForm, runsOnClaude, runsOnCodex, takeBack, writePermissions } from './permissions.js';
23
23
  import { pauseSessions, unpauseSessions } from './pause.js';
24
24
  import { recordSession, SHELL_ENV, TAB_ENV } from './record.js';
@@ -28,6 +28,7 @@ import { readRoster } from './roster.js';
28
28
  import { buildAgents, buildRules, CODEX_CAP } from './rules.js';
29
29
  import { addSkill, buildSkills, linkSkills, removeSkill } from './skills.js';
30
30
  import { addSource, fetchSources } from './sources.js';
31
+ import { makeTemp, retireTemp } from './temp.js';
31
32
  import { readUsage } from './usage.js';
32
33
  import { BOT_FATHER, bringUp, ownMailbox } from './up.js';
33
34
 
@@ -95,6 +96,21 @@ Usage:
95
96
  bot whose Orca project holds a tab your book does
96
97
  not name, and moves the folder only once Orca no
97
98
  longer lists the project.
99
+ obk temp make --bots <path> --name <session>
100
+ (--prompt <text> | --prompt-file <path>) [--harness claude|codex]
101
+ [--model <m>] [--effort <e>] [--context <c>]
102
+ [--approval ${APPROVALS.join('|')}]
103
+ Run in a long-lived session's own tab: make a
104
+ temporary session of that session's bot for a piece
105
+ of work, and bring it up. It takes your harness,
106
+ model, effort, context and approval unless you say
107
+ otherwise, works in work/<session>, and has the task
108
+ as its start prompt. The book records it as
109
+ temporary, made by you.
110
+ obk temp retire --bots <path> --name <session>
111
+ Run in the maker's own tab: retire a temporary
112
+ session it made, as obk retire does. It refuses a
113
+ long-lived session, or one another session made.
98
114
  obk rules build --bots <path> [--bot <bot>]
99
115
  Build every bot's AGENTS.md from its charter and
100
116
  the rule units it carries, or just the one you
@@ -242,6 +258,8 @@ const COMMANDS = {
242
258
  'message check': ['bots'],
243
259
  'session record': ['bots', 'bot'],
244
260
  'session mailbox': ['bots', 'bot', 'session'],
261
+ 'temp make': ['bots', 'name'],
262
+ 'temp retire': ['bots', 'name'],
245
263
  };
246
264
 
247
265
  /** What each flag is for, in the sentence a caller reads when it is missing. */
@@ -335,9 +353,9 @@ async function run(argv) {
335
353
  return 1;
336
354
  }
337
355
 
338
- // `bot`, `rules`, `skills`, `session`, `source` and `message` are commands of
339
- // two words; the rest are one.
340
- const words = ['bot', 'rules', 'skills', 'session', 'source', 'message'].includes(positionals[0]) ? 2 : 1;
356
+ // `bot`, `rules`, `skills`, `session`, `source`, `message` and `temp` are
357
+ // commands of two words; the rest are one.
358
+ const words = ['bot', 'rules', 'skills', 'session', 'source', 'message', 'temp'].includes(positionals[0]) ? 2 : 1;
341
359
  const command = positionals.slice(0, words).join(' ');
342
360
  const extra = positionals.slice(words);
343
361
 
@@ -534,8 +552,6 @@ const commands = {
534
552
 
535
553
  async retire(bots, values) {
536
554
  refuseWhenOrcaIsDown();
537
- const closedLines = (closed) => closed.map((tab) => `closed ${tab.bot} ${tab.name} tab ${tab.tabId} terminal ${tab.terminal}`);
538
-
539
555
  if (values.session !== undefined) {
540
556
  const retired = await retireSession(bots, { bot: values.bot, session: values.session });
541
557
  return {
@@ -543,6 +559,7 @@ const commands = {
543
559
  lines: [
544
560
  ...closedLines(retired.closed),
545
561
  `retired ${retired.bot} ${retired.session}: off ${path.join('bots', retired.bot, 'bot.yaml')}, and its conversations kept in the book under retired`,
562
+ ...leftLines(retired.promptsLeft),
546
563
  ],
547
564
  };
548
565
  }
@@ -571,6 +588,39 @@ const commands = {
571
588
  retired.windowReloaded ? "reloaded Orca's window, so its sidebar no longer shows the project" : RELOAD_LINE,
572
589
  ]),
573
590
  `retired ${retired.bot}: moved to ${path.relative(bots, retired.moved)}, with its book, charter and memory`,
591
+ ...leftLines(retired.promptsLeft),
592
+ ],
593
+ };
594
+ },
595
+
596
+ async 'temp make'(bots, values) {
597
+ const tab = callerTab(bots, true);
598
+ refuseWhenOrcaIsDown();
599
+ const given = { name: values.name };
600
+ for (const [flag, key] of [['harness', 'harness'], ['model', 'model'], ['effort', 'effort'], ['approval', 'approval'], ['prompt', 'prompt'], ['prompt-file', 'prompt_file']]) {
601
+ if (values[flag] !== undefined) given[key] = values[flag];
602
+ }
603
+ if (values.context !== undefined) given.context = asNumberOrText(values.context);
604
+ const made = await makeTemp(bots, { tab, ...given });
605
+ const { tabs, rules, skills, permissions, paused, projects } = made.up;
606
+ const answer = { bots, bot: made.bot, session: made.session, maker: made.maker, settings: made.settings, created: [], completed: [], rules, skills, permissions, tabs, paused, projects };
607
+ const retire = `${shellWord(ownCli())} temp retire --bots ${shellWord(bots)} --name ${made.session}`;
608
+ return {
609
+ answer,
610
+ lines: tabLines(answer, `Made ${made.bot}/${made.session}, a temporary session of ${made.maker}'s, working in work/${made.session}. Retire it when its work is done: ${retire}`),
611
+ };
612
+ },
613
+
614
+ async 'temp retire'(bots, values) {
615
+ const tab = callerTab(bots, true);
616
+ refuseWhenOrcaIsDown();
617
+ const retired = await retireTemp(bots, { tab, name: values.name });
618
+ return {
619
+ answer: { bots, ...retired },
620
+ lines: [
621
+ ...closedLines(retired.closed),
622
+ `retired ${retired.bot} ${retired.session}, a temporary session of ${retired.maker}'s: off ${path.join('bots', retired.bot, 'bot.yaml')}, and its conversations kept in the book under retired`,
623
+ ...leftLines(retired.promptsLeft),
574
624
  ],
575
625
  };
576
626
  },
@@ -832,11 +882,12 @@ const commands = {
832
882
  },
833
883
 
834
884
  'message send'(bots, values) {
885
+ const tab = callerTab(bots, values.from === undefined);
835
886
  refuseWhenOrcaIsDown();
836
887
  const answer = sendMessage(bots, {
837
888
  to: values.to,
838
889
  from: values.from,
839
- tab: process.env[TAB_ENV],
890
+ tab,
840
891
  subject: values.subject,
841
892
  text: values.text,
842
893
  textFile: values['text-file'],
@@ -865,11 +916,13 @@ const commands = {
865
916
  },
866
917
 
867
918
  'message check'(bots, values) {
919
+ // Named or not, the mail is read as the caller's own terminal when it has one.
920
+ const tab = callerTab(bots, values.bot === undefined || process.env[TERMINAL_ENV] !== undefined);
868
921
  refuseWhenOrcaIsDown();
869
922
  const answer = checkMail(bots, {
870
923
  bot: values.bot,
871
924
  session: values.session,
872
- tab: process.env[TAB_ENV],
925
+ tab,
873
926
  peek: values.peek === true,
874
927
  });
875
928
  const where = `${answer.bot}/${answer.session}`;
@@ -973,6 +1026,12 @@ function toLines(answer, bots, where) {
973
1026
  * about the message.
974
1027
  */
975
1028
  function nudgeLine(answer, where) {
1029
+ if (answer.nudged && answer.nudgeWatched === false) {
1030
+ return ` its tab was typed into, and Orca could not say whether it was taken: ${answer.nudgeUnseen} The message waits in its mailbox for its next check either way.`;
1031
+ }
1032
+ if (answer.nudged && answer.nudgeUnseen !== undefined) {
1033
+ return ' its tab was typed into, but Orca did not see the line start a turn: it may be queued behind the work in hand, or lost. The message waits in its mailbox for its next check either way.';
1034
+ }
976
1035
  if (answer.nudged) return ' its tab was told to look; it will read it when it is done with what it is doing.';
977
1036
  if (answer.blocked !== undefined) {
978
1037
  return ` its tab has something waiting to be answered (${answer.blocked}), so nothing was typed into it. Settle that, and the mail is there.`;
@@ -1010,11 +1069,33 @@ function settingsOf(values) {
1010
1069
  return settings;
1011
1070
  }
1012
1071
 
1072
+ /** The tabs a command closed, one line each. */
1073
+ const closedLines = (closed) => closed.map((tab) => `closed ${tab.bot} ${tab.name} tab ${tab.tabId} terminal ${tab.terminal}`);
1074
+
1075
+ /** What a retire could not remove, and how to: nothing reads these files now (#393). */
1076
+ const leftLines = (left = []) => left.flatMap(({ file, reason }) => [
1077
+ `left ${file}: it could not be removed (${reason}). Nothing reads it now.`,
1078
+ ` Remove it with: rm ${shellWord(file)}`,
1079
+ ]);
1080
+
1013
1081
  /** A context window written as a plain number stays one in the file. */
1014
1082
  const asNumberOrText = (value) => (/^\d+$/.test(value) ? Number(value) : value);
1015
1083
 
1016
1084
  const oneLine = (value) => (Array.isArray(value) ? value.join(' ') : String(value)).replace(/\s+/g, ' ').trim();
1017
1085
 
1086
+ /**
1087
+ * The Orca tab this command runs in, with the caller taken to be the session
1088
+ * there only once sessionInTab has shown it is, when the command takes its
1089
+ * caller from the tab (#408). Asked before Orca is: a Codex that Orca brought
1090
+ * back by itself may run in a sandbox that cannot reach Orca at all, and
1091
+ * "Orca is not ready" would send its user the wrong way.
1092
+ */
1093
+ function callerTab(bots, takesCaller) {
1094
+ const tab = process.env[TAB_ENV];
1095
+ if (takesCaller && tab !== undefined) sessionInTab(bots, tab);
1096
+ return tab;
1097
+ }
1098
+
1018
1099
  function refuseWhenOrcaIsDown() {
1019
1100
  const trouble = orcaTrouble();
1020
1101
  if (trouble !== undefined) throw new Error(trouble);
@@ -1264,6 +1345,7 @@ function sessionLines(session) {
1264
1345
  ...(book.tab === undefined
1265
1346
  ? []
1266
1347
  : [` tab ${book.tab}${book.launched === undefined ? '' : ` launched ${book.launched}`}`]),
1348
+ ...(book.temporary === undefined ? [] : [` temporary, made by ${book.temporary.maker}${book.temporary.made === undefined ? '' : ` at ${book.temporary.made}`}`]),
1267
1349
  ...(book.session === undefined ? [] : [` conversation ${book.session}`]),
1268
1350
  ...(book.history ?? [])
1269
1351
  .filter((was) => was?.session !== undefined)
package/src/health.js CHANGED
@@ -281,7 +281,11 @@ function runningOn(bots, home, bot, book, handles, sessions) {
281
281
  // see may still match, by the harness's own defaults; the rest of what
282
282
  // bot.yaml asks for is not on it either way.
283
283
  const drift = off.length === 0 ? '' : ` ${parts}, as the harness's own record of its conversation ${conversation} says.`;
284
- found.push(finding('session', entry.tab, `${bot.name}'s session ${session.name} was not started by the kit: the harness in its tab ${entry.tab} carries nothing of the kit's launch line, as when Orca brings its tabs back by itself after a restart or an update. So it runs on the harness's own defaults and whatever Orca added, not on what ${path.join(home, 'bot.yaml')} asks for.${drift} ${restart} starts it on bot.yaml.`, bot.name));
284
+ // A Codex brought back this way also runs its commands in Codex's shared
285
+ // background server, under whichever tab started it (#408).
286
+ const daemon = harness !== 'codex' ? '' : ` Without the kit's line it also runs without --no-daemon, so its commands run in Codex's shared background server, under the tab of whichever session started that server: another tab's identity, not its own. So the kit refuses its commands that take the caller from its tab, such as reading its mail.`;
287
+ const held = harness !== 'codex' ? '' : ` If Codex then shows "This conversation is open in another app", Codex's shared background server still holds the conversation, and it can outlive the session that started it: once every such session is back on the kit's line, stop the server with Codex's own \`codex app-server daemon stop\`, then restart this session again. That stops the server for everything using it, Codex sessions outside the kit included, so first check that nothing else needs it.`;
288
+ found.push(finding('session', entry.tab, `${bot.name}'s session ${session.name} was not started by the kit: the harness in its tab ${entry.tab} carries nothing of the kit's launch line, as when Orca brings its tabs back by itself after a restart or an update. So it runs on the harness's own defaults and whatever Orca added, not on what ${path.join(home, 'bot.yaml')} asks for.${drift}${daemon} ${restart} starts it on bot.yaml.${held}`, bot.name));
285
289
  } else if (off.length > 0) {
286
290
  found.push(finding('session', file, `${bot.name}'s session ${session.name} does not run on what ${path.join(home, 'bot.yaml')} asks for. ${parts}. That is what the harness's own record of its conversation ${conversation} says. A session takes these when it starts, so if bot.yaml changed after it started, ${restart} starts it on them; if not, something else set them, such as a default of the harness's own or a change made inside the session.`, bot.name));
287
291
  }
package/src/init.js CHANGED
@@ -86,8 +86,9 @@ charter: |
86
86
  Good looks like: every bot has a charter its owner recognises, the skills it
87
87
  needs and no more, and sessions that come back after a restart.
88
88
 
89
- Ask first before: retiring a bot or a session, restarting anything, or
90
- changing a bot's rules in a way its owner did not ask for.
89
+ Ask first before: retiring a bot or a long-lived session, restarting
90
+ anything, or changing a bot's rules in a way its owner did not ask for. A
91
+ temporary session is its maker's to retire, without asking.
91
92
 
92
93
  When the kit itself goes wrong (an obk command fails in a way its own message
93
94
  does not explain, or does something other than what it says), tell your owner
package/src/launch.js CHANGED
@@ -51,7 +51,7 @@ export const harnessOf = (session, botHarness) => (set(session.harness) ? sessio
51
51
 
52
52
  /**
53
53
  * A session's name on Claude Code, which is also the address another Claude
54
- * session writes to (ADR 0018). It goes on the launch line as `-n`, and it is
54
+ * session writes to (ADR 0030). It goes on the launch line as `-n`, and it is
55
55
  * re-applied every time the session is started: a resume keeps the name by
56
56
  * itself (tech notes, section 2), and the kit does not depend on that.
57
57
  *
@@ -224,7 +224,7 @@ export function launchCommand(session, { harness, home, workDir, prompt, promptF
224
224
 
225
225
  if (harness === 'claude') {
226
226
  // The name is the address other Claude sessions write to, so it goes on
227
- // every launch line, a resume included (ADR 0018).
227
+ // every launch line, a resume included (ADR 0030).
228
228
  if (address !== undefined) words.push('-n', address);
229
229
  // The context window rides on the model name: `sonnet[1m]`.
230
230
  if (set(session.model)) words.push('--model', set(session.context) ? `${session.model}[${session.context}]` : session.model);
package/src/message.js CHANGED
@@ -1,4 +1,4 @@
1
- // `obk message`: one session writing to another (PRD 6.9, ADR 0018).
1
+ // `obk message`: one session writing to another (PRD 6.9, ADR 0030).
2
2
  //
3
3
  // Two roads, and the bot never picks. Claude to Claude in the same approval
4
4
  // class is the harness's own messaging, which no command line can send for it —
@@ -20,7 +20,7 @@ import path from 'node:path';
20
20
 
21
21
  import { MAILBOX_WAIT_MS, readBook, takeMailboxTurn } from './book.js';
22
22
  import { botDir, botNames, readBot } from './bot.js';
23
- import { harnessOf, isAddressOf, ownCli, reachesMail, shellWord } from './launch.js';
23
+ import { harnessOf, isAddressOf, ownCli, reachesMail, SHELL_ENV, shellWord } from './launch.js';
24
24
  import { ackMailbox, coordinatorOf, postMessage, readMailbox, tabs, tabToTypeInto, TERMINAL_ENV, TIMED_OUT, typeIntoTab, useMailbox } from './orca.js';
25
25
 
26
26
  /**
@@ -360,17 +360,37 @@ function whoIsWriting(bots, sender, tab, asked = '--from <bot>/<session>: which
360
360
  return found;
361
361
  }
362
362
 
363
- /** The session the book says is in this Orca tab, wherever in the fleet it is. */
364
- function sessionInTab(bots, tab) {
363
+ /**
364
+ * The session the book says is in this Orca tab, wherever in the fleet it is,
365
+ * when the caller is that session.
366
+ *
367
+ * A Codex session is the caller only when the kit's launch line started the
368
+ * Codex it runs under: `shell` is the mark that line leaves, and everything the
369
+ * harness runs inherits it. A Codex that Orca brought back by itself has no
370
+ * mark and no `--no-daemon`, so it runs its commands in Codex's shared
371
+ * background server, whose every process carries the tab of whichever session
372
+ * started it (#408). Its tab then says nothing about who is asking. Inside
373
+ * Codex's sandbox `ps` does not run, so the environment is all there is to go
374
+ * on. A Claude session has no such server, and one Orca brought back is still
375
+ * the session in its tab.
376
+ */
377
+ export function sessionInTab(bots, tab, shell = process.env[SHELL_ENV]) {
365
378
  for (const name of botNames(bots)) {
366
379
  const book = readBook(botDir(bots, name));
367
380
  for (const [session, entry] of Object.entries(book.sessions)) {
368
- if (entry?.tab === tab) return findSession(bots, `${name}/${session}`);
381
+ if (entry?.tab !== tab) continue;
382
+ const found = findSession(bots, `${name}/${session}`);
383
+ if (found.harness === 'codex' && (shell === undefined || shell === '')) throw new Error(notTheCodexInTab(found, tab));
384
+ return found;
369
385
  }
370
386
  }
371
387
  return undefined;
372
388
  }
373
389
 
390
+ /** Why a caller in a Codex session's tab is not taken to be that session, and what puts it right. */
391
+ const notTheCodexInTab = (found, tab) =>
392
+ `this command takes its caller from the Orca tab it runs in, ${tab}, which is ${found.bot}/${found.session}'s, a Codex session; but it did not come from a Codex the kit started there: nothing of the kit's launch line is in its environment. A Codex that Orca brought back by itself, after a restart or an update, runs its commands in Codex's shared background server, under the tab of whichever session started that server, so the kit cannot tell which session is asking. Nothing was done. \`${shellWord(ownCli())} restart --bots ${shellWord(found.bots)} --bot <bot> --session <name>\` starts each such session on the kit's line; \`${shellWord(ownCli())} health --bots ${shellWord(found.bots)}\` names them. If Codex then shows "This conversation is open in another app", Codex's shared background server still holds that conversation, and it can outlive the session that started it: once every such session is back on the kit's line, stop the server with Codex's own \`codex app-server daemon stop\`, then restart the stuck session again. That stops the server for everything using it, Codex sessions outside the kit included, so first check that nothing else needs it.`;
393
+
374
394
  /**
375
395
  * The message as it will travel: the text itself when it is short enough, and
376
396
  * otherwise a file beside the bots folder with a body that names it.
@@ -442,11 +462,19 @@ function nudge(to, from, subject) {
442
462
  if (found.unsure !== undefined) return { nudged: false, nudgeTrouble: found.unsure };
443
463
  if (found.handle === undefined) return { nudged: false };
444
464
 
445
- typeIntoTab(
465
+ const sent = typeIntoTab(
446
466
  found.handle,
447
467
  `Fleet mail from ${from.bot}/${from.session}: ${subject}. Read it with ${shellWord(ownCli())} message check --bots ${shellWord(to.bots)} --bot ${shellWord(to.bot)} --session ${shellWord(to.session)}`,
468
+ { watch: true },
448
469
  );
449
- return { nudged: true };
470
+ // Typed is not taken. A harness busy with a turn queues the line and gives
471
+ // it no turn of its own, and a line can be lost, and Orca's receipt looks
472
+ // the same for both: only a turn start it saw says the line landed (#394).
473
+ if (sent?.send?.prompt?.stages?.includes('turn_started')) return { nudged: true };
474
+ // Where Orca did not watch the line at all, as when its own notice has
475
+ // just started a turn in the tab, it saw nothing either way, and says so.
476
+ if (sent?.send?.prompt?.observation === 'unsupported') return { nudged: true, nudgeUnseen: unseen(sent), nudgeWatched: false };
477
+ return { nudged: true, nudgeUnseen: unseen(sent) };
450
478
  } catch (error) {
451
479
  // The message is already queued, and it is waiting whatever Orca says
452
480
  // about the tab. So this is reported rather than thrown: a send that ends
@@ -457,6 +485,14 @@ function nudge(to, from, subject) {
457
485
  }
458
486
  }
459
487
 
488
+ /** Orca's words about a line it did not see start a turn, or what its receipt says when it gives none. */
489
+ function unseen(sent) {
490
+ const warnings = Array.isArray(sent?.warnings) ? sent.warnings.filter((warning) => typeof warning === 'string') : [];
491
+ if (warnings.length > 0) return warnings.join(' ');
492
+ const stages = sent?.send?.prompt?.stages;
493
+ return `Orca's receipt shows ${Array.isArray(stages) ? stages.join(', ') : 'no stages'} and no turn start`;
494
+ }
495
+
460
496
  /**
461
497
  * The look before the nudge. Orca now and then refuses a handle it has just
462
498
  * listed as stale, and a fresh listing hands out one that works (tech notes,
package/src/orca.js CHANGED
@@ -584,20 +584,28 @@ export const closeTab = (handle) =>
584
584
  * The wait is short because the caller is telling a session it has mail, not
585
585
  * handing it work: mail that has to wait for the next check is a smaller cost
586
586
  * than a command that hangs for half a minute.
587
+ *
588
+ * With `watch`, the line is sent with that wait from the start, and Orca's
589
+ * receipt says whether it saw the line start a turn (#394). It gives back
590
+ * Orca's `result`: the receipt is in its `send.prompt`, and Orca's words about
591
+ * a turn it did not see in its `warnings`.
587
592
  */
588
- export function typeIntoTab(handle, text) {
593
+ export function typeIntoTab(handle, text, { watch = false } = {}) {
589
594
  const args = ['terminal', 'send', '--terminal', handle, '--text', text, '--enter'];
590
- const answer = ask(args);
591
- if (answer.ok === true) return answer.result.send;
595
+ const answer = ask(watch ? [...args, '--wait-submit', String(SUBMIT_WAIT_S)] : args);
596
+ if (answer.ok === true) return answer.result;
592
597
 
593
598
  const again = answer.error?.data?.orchestrationRequestId;
594
599
  if (answer.error?.code !== 'agent_prompt_blocked' || typeof again !== 'string') {
595
600
  throw new Error(`Orca refused ${args.join(' ')}: ${answer.error?.message ?? 'no reason given'}`);
596
601
  }
597
- return orca([...args, '--retry-request', again, '--wait-submit', String(SUBMIT_WAIT_S)]).send;
602
+ return orca([...args, '--retry-request', again, '--wait-submit', String(SUBMIT_WAIT_S)]);
598
603
  }
599
604
 
600
- /** How long a re-issued line is given to be submitted before Orca gives up on it. */
605
+ /**
606
+ * How long a watched or re-issued line is given to be submitted before Orca
607
+ * gives up on it. An idle harness started its turn in about 2 s, live (#394).
608
+ */
601
609
  const SUBMIT_WAIT_S = 5;
602
610
 
603
611
  /** Where Orca names the terminal a process runs in, in every pane it opens. */
package/src/retire.js CHANGED
@@ -9,12 +9,15 @@
9
9
  // What goes is what the kit made for it: its tabs, closed one at a time by
10
10
  // their own handles; its Orca project, after the tabs and never before; its
11
11
  // start-prompt files beside the bots folder; and, for a bot, the skill links
12
- // the kit made in its folder. A tab the book does not name is the user's, so a
12
+ // the kit made in its folder. A prompt file that cannot be removed, as under a
13
+ // harness's sandbox that may not write beside the bots folder, does not stop a
14
+ // retire halfway: nothing reads it once its session is gone, so the retire
15
+ // finishes and names it, with how to remove it (#393). A tab the book does not name is the user's, so a
13
16
  // bot whose project holds one is not retired until they have dealt with it.
14
17
  //
15
18
  // Closing a tab here ends the conversation in it on purpose, so unlike a
16
19
  // restart or a pause it does not wait for the book to know which one it was.
17
- // The mailbox Runs stay: Orca has no way to remove one (ADR 0018).
20
+ // The mailbox Runs stay: Orca has no way to remove one (ADR 0030).
18
21
 
19
22
  import { existsSync, mkdirSync, renameSync, rmSync } from 'node:fs';
20
23
  import path from 'node:path';
@@ -31,7 +34,8 @@ import { promptPath, sessionsOf } from './up.js';
31
34
  export const retiredDir = (bots) => path.join(bots, 'retired');
32
35
 
33
36
  /**
34
- * Retire the session `session` of the bot `bot`. Returns `{ bot, session, closed }`.
37
+ * Retire the session `session` of the bot `bot`. Returns `{ bot, session,
38
+ * closed }`, and `promptsLeft` when its prompt file could not be removed.
35
39
  */
36
40
  export async function retireSession(bots, { bot, session }) {
37
41
  const home = fleetMember(bots, bot, 'retire', session);
@@ -47,15 +51,16 @@ export async function retireSession(bots, { bot, session }) {
47
51
  delete book.sessions[session];
48
52
  book.retired = [...(Array.isArray(book.retired) ? book.retired : []), { name: session, ...entry, retired: at }];
49
53
  });
50
- rmSync(promptPath(bots, bot, session), { force: true });
54
+ const left = removePrompts([promptPath(bots, bot, session)]);
51
55
 
52
- return { bot, session, closed };
56
+ return { bot, session, closed, ...left };
53
57
  }
54
58
 
55
59
  /**
56
60
  * Retire the bot `bot`. Returns `{ bot, closed, project, windowReloaded, moved }`:
57
61
  * the tabs it closed, the Orca project it took away (if it had one), whether
58
- * Orca's window was reloaded after that, and where the bot is now.
62
+ * Orca's window was reloaded after that, and where the bot is now; and
63
+ * `promptsLeft` when a prompt file could not be removed.
59
64
  * When Orca does not confirm the project gone, it returns `{ bot, closed,
60
65
  * project, trouble }` instead, and the bot is left where it was.
61
66
  */
@@ -103,12 +108,28 @@ export async function retireBot(bots, { bot }) {
103
108
  windowReloaded = reloadWindow();
104
109
  }
105
110
 
106
- for (const name of new Set([...known.sessions, ...booked].map((session) => session.name))) {
107
- rmSync(promptPath(bots, bot, name), { force: true });
108
- }
111
+ const names = new Set([...known.sessions, ...booked].map((session) => session.name));
112
+ const left = removePrompts([...names].map((name) => promptPath(bots, bot, name)));
109
113
  unlinkSkills(home);
110
114
  mkdirSync(retiredDir(bots), { recursive: true });
111
115
  renameSync(botDir(bots, bot), moved);
112
116
 
113
- return { bot, closed, ...(project === undefined ? {} : { project: project.id, windowReloaded }), moved };
117
+ return { bot, closed, ...(project === undefined ? {} : { project: project.id, windowReloaded }), moved, ...left };
118
+ }
119
+
120
+ /**
121
+ * Remove start-prompt files, and say which could not be: `{ promptsLeft: [{
122
+ * file, reason }] }`, or nothing when every one went. One that is not there is
123
+ * nothing to remove.
124
+ */
125
+ function removePrompts(files) {
126
+ const promptsLeft = files.flatMap((file) => {
127
+ try {
128
+ rmSync(file, { force: true });
129
+ return [];
130
+ } catch (error) {
131
+ return [{ file, reason: error.message }];
132
+ }
133
+ });
134
+ return promptsLeft.length === 0 ? {} : { promptsLeft };
114
135
  }
package/src/temp.js ADDED
@@ -0,0 +1,173 @@
1
+ // `obk temp make` and `obk temp retire`: a session's own temporary sessions
2
+ // (PRD 6.4, #227).
3
+ //
4
+ // Any long-lived session can make a temporary session of its own bot for a
5
+ // piece of work, and retire it when the work is done, without Bot Father, who
6
+ // stays the manager of long-lived sessions. A temporary session is an ordinary
7
+ // session in every other way: in bot.yaml, brought up with a tab and a mailbox,
8
+ // its conversations kept in the book. What makes it temporary is one field of
9
+ // its book entry, `temporary: { maker, made }`, and the book is the one place
10
+ // that says so (ADR 0012).
11
+ //
12
+ // The caller is the session whose tab this runs in, as the book records it: the
13
+ // tab says who is calling now. The maker is kept by its session name, not its
14
+ // tab, so it still owns what it made after a restart gives it a new tab.
15
+ //
16
+ // Everything that can refuse is checked before anything is written, so a
17
+ // refusal leaves bot.yaml, the book and Orca as they were. The one write that
18
+ // may fall outside what a harness's sandbox lets a session write, its start
19
+ // prompt's file beside the bots folder, is made first, the way #383 puts the
20
+ // risky write before bot.yaml: refused there, nothing else has changed, and the
21
+ // same command run again with that access goes through.
22
+
23
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
24
+ import path from 'node:path';
25
+
26
+ import { readBook, updateBook } from './book.js';
27
+ import { addSession, dropSession, NAME, readBot } from './bot.js';
28
+ import { isShortPrompt, ownCli, shellWord, startPrompt, workDirOf } from './launch.js';
29
+ import { sessionInTab } from './message.js';
30
+ import { retireSession } from './retire.js';
31
+ import { bringUp, promptPath } from './up.js';
32
+
33
+ /** The settings a temporary session takes from its maker unless told otherwise. */
34
+ const INHERITED = ['model', 'effort', 'context', 'approval'];
35
+
36
+ /**
37
+ * Make a temporary session of the caller's own bot and bring it up. `given`
38
+ * holds what the caller said: `name`, `prompt` or `prompt_file`, and any of
39
+ * `harness` and the inherited settings. Returns `{ bot, session, maker,
40
+ * settings, up }`, where `up` is what bringing it up answered.
41
+ */
42
+ export async function makeTemp(bots, { tab, ...given }) {
43
+ const caller = callerIn(bots, tab, 'make');
44
+ if (caller.temporary !== undefined) {
45
+ throw new Error(`${caller.bot}/${caller.session} is a temporary session, and only a long-lived session makes one. Nothing was made.`);
46
+ }
47
+ // The name is a folder under work/ and a file beside the bots folder, so it
48
+ // is held to the rule a bot's name is: one plain name, never a path.
49
+ if (!NAME.test(given.name)) {
50
+ throw new Error(`${given.name} cannot be a session's name: a name is lower-case letters, digits and single hyphens, such as review-250. Nothing was made.`);
51
+ }
52
+ if (given.prompt === undefined && given.prompt_file === undefined) {
53
+ throw new Error(`temp make needs the task: --prompt <text> or --prompt-file <path>. Nothing was made.`);
54
+ }
55
+ if (given.prompt !== undefined && given.prompt_file !== undefined) {
56
+ throw new Error(`temp make was given the task twice, as --prompt and as --prompt-file, and a session is told its duty once. Give it one way. Nothing was made.`);
57
+ }
58
+
59
+ const bot = readBot(caller.home, caller.bot);
60
+ const maker = bot.sessions.find((session) => session.name === caller.session);
61
+ const settings = { name: given.name };
62
+ const harness = given.harness ?? maker?.harness;
63
+ if (harness !== undefined) settings.harness = harness;
64
+ for (const field of INHERITED) {
65
+ const value = given[field] ?? maker?.[field];
66
+ if (value !== undefined) settings[field] = value;
67
+ }
68
+ if (given.prompt !== undefined) settings.prompt = given.prompt;
69
+ else settings.prompt_file = given.prompt_file;
70
+ settings.work_dir = `work/${given.name}`;
71
+
72
+ const written = bot.sessions.some((session) => session.name === given.name) ? undefined : writePromptFirst(bots, caller, settings);
73
+ // Refuses a name the bot already has, and a setting that will not work,
74
+ // before it writes anything; the prompt written first goes with a refusal.
75
+ let added;
76
+ try {
77
+ added = addSession(bots, caller.bot, settings);
78
+ } catch (error) {
79
+ if (written !== undefined) rmSync(written, { force: true });
80
+ throw error;
81
+ }
82
+ const made = new Date().toISOString();
83
+ try {
84
+ await updateBook(caller.home, (book) => {
85
+ book.sessions[given.name] = { ...book.sessions[given.name], temporary: { maker: caller.session, made } };
86
+ });
87
+ } catch (error) {
88
+ // A session in bot.yaml that the book does not call temporary would be a
89
+ // long-lived one to everything that reads it, its maker's retire included,
90
+ // so it is taken back off rather than left that way.
91
+ const failed = `${caller.bot}/${given.name} could not be recorded in the book as temporary (${error.message})`;
92
+ try {
93
+ dropSession(bots, caller.bot, given.name);
94
+ } catch (undo) {
95
+ throw new Error(`${failed}, and taking it back off bot.yaml failed too (${undo.message}). It is in bot.yaml as a session the book does not call temporary. Take it off with ${shellWord(ownCli())} retire --bots ${shellWord(bots)} --bot ${caller.bot} --session ${given.name}`);
96
+ }
97
+ // Off bot.yaml, nothing is made; a prompt file that stays is only a file,
98
+ // and nothing reads it (#393).
99
+ try {
100
+ if (written !== undefined) rmSync(written, { force: true });
101
+ } catch (left) {
102
+ throw new Error(`${failed}, so it was taken back off bot.yaml and nothing was made. Its start prompt ${written} could not be removed (${left.message}), and nothing reads it. Remove it with rm ${shellWord(written)}`);
103
+ }
104
+ throw new Error(`${failed}, so it was taken back off bot.yaml and nothing was made. Run this again once the book can be written.`);
105
+ }
106
+
107
+ let up;
108
+ try {
109
+ up = await bringUp(bots, { bot: caller.bot, session: given.name });
110
+ } catch (error) {
111
+ const cli = shellWord(ownCli());
112
+ throw new Error(`${caller.bot}/${given.name} is made, in bot.yaml and in the book as temporary with its maker ${caller.session}, and could not be brought up: ${error.message} Bring it up with ${cli} up --bots ${shellWord(bots)} --bot ${caller.bot} --session ${given.name} or retire it with ${cli} temp retire --bots ${shellWord(bots)} --name ${given.name}`);
113
+ }
114
+ return { bot: caller.bot, session: given.name, maker: caller.session, settings: added.session, up };
115
+ }
116
+
117
+ /**
118
+ * Write the start prompt's file where bringing the session up will write it,
119
+ * when its prompt goes to the harness out of a file at all, and say where. A
120
+ * prompt that cannot be read yet is left to `addSession`, which refuses it in
121
+ * its own words.
122
+ */
123
+ function writePromptFirst(bots, caller, settings) {
124
+ let prompt;
125
+ try {
126
+ prompt = startPrompt(settings, { home: caller.home, workDir: workDirOf(settings, caller.home) });
127
+ } catch {
128
+ return undefined;
129
+ }
130
+ if (isShortPrompt(prompt)) return undefined;
131
+
132
+ const file = promptPath(bots, caller.bot, settings.name);
133
+ try {
134
+ mkdirSync(path.dirname(file), { recursive: true });
135
+ writeFileSync(file, prompt);
136
+ } catch (error) {
137
+ throw new Error(`${caller.bot}/${settings.name}'s start prompt could not be written to ${file} (${error.message}), and it is written first, so nothing was made. Run this again where that folder can be written: from a harness's sandbox, with the access to write it.`);
138
+ }
139
+ return file;
140
+ }
141
+
142
+ /**
143
+ * Retire a temporary session the caller made. Returns what `retireSession`
144
+ * does, with the maker.
145
+ */
146
+ export async function retireTemp(bots, { tab, name }) {
147
+ const caller = callerIn(bots, tab, 'retire');
148
+ const bot = readBot(caller.home, caller.bot);
149
+ if (!bot.sessions.some((session) => session.name === name)) {
150
+ throw new Error(`${caller.bot} has no session called ${name}, so there is nothing of yours to retire. Nothing was retired.`);
151
+ }
152
+ const temporary = readBook(caller.home).sessions[name]?.temporary;
153
+ if (temporary === undefined) {
154
+ throw new Error(`${caller.bot}/${name} is a long-lived session, and those are Bot Father's to retire. Nothing was retired.`);
155
+ }
156
+ if (temporary.maker !== caller.session) {
157
+ throw new Error(`${caller.bot}/${name} is a temporary session ${temporary.maker} made, not ${caller.session}, so it is ${temporary.maker}'s to retire. Nothing was retired.`);
158
+ }
159
+ return { ...(await retireSession(bots, { bot: caller.bot, session: name })), maker: caller.session };
160
+ }
161
+
162
+ /**
163
+ * The session this runs in, as the book knows it, with its home and whether it
164
+ * is itself temporary.
165
+ */
166
+ function callerIn(bots, tab, what) {
167
+ const found = tab === undefined ? undefined : sessionInTab(bots, tab);
168
+ if (found === undefined) {
169
+ throw new Error(`temp ${what} is run by a session in its own tab, and this is not one of the fleet's tabs, so there is no session here to ${what} it for. Nothing was done.`);
170
+ }
171
+ const entry = readBook(found.home).sessions[found.session] ?? {};
172
+ return { bot: found.bot, session: found.session, home: found.home, temporary: entry.temporary };
173
+ }