@shipmates/pi 0.0.0 → 0.3.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/LICENSE +661 -0
- package/dist/format.d.ts +12 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/format.js +100 -0
- package/dist/format.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +121 -0
- package/dist/index.js.map +1 -0
- package/dist/mode.d.ts +43 -0
- package/dist/mode.d.ts.map +1 -0
- package/dist/mode.js +47 -0
- package/dist/mode.js.map +1 -0
- package/dist/session.d.ts +140 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +501 -0
- package/dist/session.js.map +1 -0
- package/dist/shared.d.ts +15 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +34 -0
- package/dist/shared.js.map +1 -0
- package/dist/spawn.d.ts +116 -0
- package/dist/spawn.d.ts.map +1 -0
- package/dist/spawn.js +314 -0
- package/dist/spawn.js.map +1 -0
- package/dist/tools.d.ts +4 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +512 -0
- package/dist/tools.js.map +1 -0
- package/package.json +65 -13
- package/skills/ralph-loop/SKILL.md +83 -0
- package/skills/shipmates/SKILL.md +35 -0
- package/src/format.ts +124 -0
- package/src/index.ts +148 -0
- package/src/mode.ts +58 -0
- package/src/session.ts +565 -0
- package/src/shared.ts +61 -0
- package/src/spawn.ts +431 -0
- package/src/tools.ts +687 -0
- package/.npm-publish.log +0 -0
- package/README.md +0 -5
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: ralph-loop
|
|
3
|
+
disable-model-invocation: true
|
|
4
|
+
description: Run a plan as a Ralph loop through shipmates, one fresh worker session per step, each step reviewed, pushes gated by the approval policy the human gives.
|
|
5
|
+
license: AGPL-3.0-only
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# ralph-loop
|
|
9
|
+
|
|
10
|
+
You are the **orchestrator** of a Ralph loop. A plan in git is done one step at a time, each step by a fresh **worker** session running the same step prompt, so no step inherits another's context. You never build a step yourself: you spawn, route, review, gate and keep the loop moving. The plan in git is the only state; your memory is a cache of it.
|
|
11
|
+
|
|
12
|
+
The tools are shipmates' (`session_*`, `human_ask`); read the `shipmates` skill (in this package, beside this one) if it is not in your context yet.
|
|
13
|
+
|
|
14
|
+
## The brief
|
|
15
|
+
|
|
16
|
+
The human's message after this skill is the **brief**. Take each item from it, use the default when it is absent, and ask the human (`human_ask`, blocking) only for a missing required item. Restate the whole brief in your first reply, so the human sees what you will run.
|
|
17
|
+
|
|
18
|
+
- **Repo and plan** (required): the repo folder, the plan file, and the ref holding it (for example `origin/work`).
|
|
19
|
+
- **Step prompt** (required): where the prompt every worker runs lives, a file or a section of the plan. Workers read it there themselves: a spawn prompt is capped at 8 KB, and the step prompt evolves in git between steps.
|
|
20
|
+
- **Approval** (default `always`): when a step's pushes need the human.
|
|
21
|
+
- `always`: every step's pushes go to the human.
|
|
22
|
+
- `when-unsure`: the step goes ahead on the human's standing approval when it is **certain** (below); otherwise the human decides.
|
|
23
|
+
- `never`: the step goes ahead when the review verdict is `CLEAN`; the human decides only when it is not.
|
|
24
|
+
- Free text works too ("ask me for anything touching the contracts"). Apply it literally; where it is ambiguous for a case, the human decides.
|
|
25
|
+
- **Review** (default on, 2 fix rounds): a reviewer per step, and where its brief lives if not the default below.
|
|
26
|
+
- **Lanes** (default 1): how many steps may run at once, and the plan's own lane or port-slot rules.
|
|
27
|
+
- **Budget** (default 5 steps): stop and report after this many steps are complete.
|
|
28
|
+
|
|
29
|
+
## Certain
|
|
30
|
+
|
|
31
|
+
A step is **certain** when every one of these holds:
|
|
32
|
+
|
|
33
|
+
- the reviewer's verdict is `CLEAN`;
|
|
34
|
+
- the worker measured the step's "Done when" and it fully holds;
|
|
35
|
+
- every decision in the worker's report was settled by the plan or by an earlier answer of the human;
|
|
36
|
+
- every push is a fast-forward or a new branch;
|
|
37
|
+
- neither the worker nor the reviewer listed anything under `UNSURE:`.
|
|
38
|
+
|
|
39
|
+
## Guardrails
|
|
40
|
+
|
|
41
|
+
These always go to the human, whatever the approval policy: deleting a branch or tag, a force push or reset of any shared ref, publishing a package, merging a pull request, and anything the plan or a repo's AGENTS.md reserves for the human.
|
|
42
|
+
|
|
43
|
+
## The loop
|
|
44
|
+
|
|
45
|
+
1. **Start.** `session_register` with role `orchestrator:<plan name>` and a status line. Fetch, read the plan at its ref, and work out the next step the step prompt would select (the step prompt defines how; when it lets a message name the step, name it).
|
|
46
|
+
2. **Spawn a worker** for each free lane: `session_spawn(<repo folder>, <worker contract>, {role: '<plan name>/<step>'})`.
|
|
47
|
+
3. **End your turn idle.** Every message wakes you. Stay out of `waiting-for-human` while workers run: that state holds their reports until the human next writes to you.
|
|
48
|
+
4. **On every wake**, fetch and re-read the plan first, then act on each message:
|
|
49
|
+
- `DONE <step>` from a worker: start its review (below), or with review off go to the gate.
|
|
50
|
+
- a `session_ask` from a worker: answer what the plan or the human's earlier answers settle (`session_answer`); merge the rest into one `human_ask` with `onBehalfOf` set to the question ids, and when the human answers, relay it to the worker with origin `human-relayed` and `relayItem`, then `session_answer` its questions.
|
|
51
|
+
- `BLOCKED <step>: <why>`: raise it to the human with a non-blocking `human_ask` carrying the worker's reason, and keep that lane idle until they answer.
|
|
52
|
+
- a reviewer's verdict: `ISSUES` within the fix rounds goes back to the worker (`session_tell`, the issues verbatim), and its next `DONE` is reviewed again; otherwise go to the gate.
|
|
53
|
+
- `PUSHED <step>` from a worker: the step is complete. Check the plan at its ref shows it ticked, count it, and spawn the next step while the budget allows.
|
|
54
|
+
5. **The gate.** Decide by the approval policy and the guardrails:
|
|
55
|
+
- **Go ahead**: `session_tell` the worker "push the listed refs now", with origin `human-relayed` and `relayQuote` set to the sentence of the brief that grants the approval. Only the human's own words satisfy a push gate, and shipmates refuses words the human never typed. shipmates searches the human's last 20 messages in your session; when the brief is older, ask the human to restate the approval.
|
|
56
|
+
- **Ask the human**: one non-blocking `human_ask` with options `Approve` and `Hold`, whose question names the step, the pushes, the review verdict and the reason you ask. On `Approve`, relay it to the worker with origin `human-relayed` and `relayItem`; on `Hold` or any other answer, pass the human's words to the worker and follow them.
|
|
57
|
+
6. **Keep the status line current**: the step, its phase (building, review round N, at the gate, pushing) and steps done out of the budget.
|
|
58
|
+
7. **Stop** when the budget is spent, the plan has no next step, or every lane waits on the human. End with a report in your chat: the steps completed with their pushes, what is open and on whom, and what comes next. If `assistant_notify` is available, send it the one-line summary.
|
|
59
|
+
|
|
60
|
+
## Worker contract
|
|
61
|
+
|
|
62
|
+
The spawn prompt for a worker; fill in the brackets:
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
You are a worker in a Ralph loop; your owner is the orchestrator that spawned you. Do ONE step of [plan] on [ref] in [repo]: read the step prompt at [location] and follow it as written, for step [step] [and lane or port slot, when lanes run in parallel].
|
|
66
|
+
Where it tells you to bring something to the human, bring it to your owner instead:
|
|
67
|
+
- a decision you cannot settle from the plan: session_ask your owner, one question per decision, with your recommendation and the alternative you rejected;
|
|
68
|
+
- when the step is built and verified: session_tell your owner a report whose FIRST line is `DONE [step]`, then the "Done when" measurements, every push (repo, ref, old..new, and whether it is a fast-forward, a new branch or a deletion), the Decisions block, and under `UNSURE:` anything you are not sure of;
|
|
69
|
+
- when a premise fails or you cannot go on: a report whose first line is `BLOCKED [step]: [why]`.
|
|
70
|
+
After a report, end your turn without declaring waiting-for-human: your owner's messages wake you.
|
|
71
|
+
Push only when your owner tells you to push with the human's own words attached (origin human-relayed). Then push exactly the listed refs and session_tell your owner `PUSHED [step]` with each ref's old..new.
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Reviewer contract
|
|
75
|
+
|
|
76
|
+
Spawn one reviewer per step, role `<plan name>/review-<step>`, after its first `DONE`; for each later round, `session_tell` the same reviewer to review the step again in full. Unless the brief names another brief, the spawn prompt is:
|
|
77
|
+
|
|
78
|
+
```
|
|
79
|
+
You review step [step] of [plan] on [ref] in [repo], READ-ONLY: modify, stage, commit, check out or push nothing; use git, read and grep. Read the step's section and its "Done when", the step prompt at [location] (its rules bind the step), the AGENTS.md of every repo the step touched, and the worker's report (session_read [worker role]). Review the diff of every ref the report lists against its base.
|
|
80
|
+
Check: the step does what its section says and nothing more; "Done when" holds, re-measured wherever that is cheap; every rule of the step prompt and of each repo's AGENTS.md is followed; each listed push is what the report claims.
|
|
81
|
+
Bound every shell command with `timeout` and cap its output; never search node_modules, dist, .git or a generated bundle.
|
|
82
|
+
Report to [orchestrator role] with session_tell, FIRST line `CLEAN [step]` or `ISSUES [step]`, then each issue with file:line and why, then under `UNSURE:` anything you could not check. Then end your turn; a message from the orchestrator may ask you to review again.
|
|
83
|
+
```
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: shipmates
|
|
3
|
+
description: Coordinate with other live agent sessions on this machine (shipmates) and reach the human through their attention inbox. Use when a prompt gives you a role or a lane, when your work depends on or affects another session's work, when you would otherwise write a message for the human to paste into another session, or when you orchestrate other sessions.
|
|
4
|
+
license: AGPL-3.0-only
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# shipmates
|
|
8
|
+
|
|
9
|
+
Live pi sessions on this machine can see, message and ask each other, and the human has one inbox for what needs them. The tools are `session_*` and `human_*`; the `shipmates` CLI does the same from a shell.
|
|
10
|
+
|
|
11
|
+
## The loop
|
|
12
|
+
|
|
13
|
+
1. **Register.** When a prompt names your role ("you are the push lane"), call `session_register` with it (by convention `<plan>/<lane>`, or `orchestrator:<plan>`) and a status line. Update the status and refs whenever they change: other sessions read them instead of asking you.
|
|
14
|
+
2. **Read before you send.** `session_list`, then `session_read` the session you are about to address. Its status, open questions and recent text often answer you already, and they tell you whether your message is still true.
|
|
15
|
+
3. **Tell or ask.** `session_tell` informs; `session_ask` expects an answer and stays open until `session_answer` closes it. Point at refs (branch, commit, published version, plan section) instead of copying content. A message that turned out wrong is fixed with `session_supersede` while it is undelivered.
|
|
16
|
+
4. **Wait when the answer gates your next step.** `session_wait` returns on the answer, on the target settling without one, or when someone asks you something (answer it, then wait again).
|
|
17
|
+
5. **Escalate only real decisions.** What only the human can decide goes through `human_ask` (blocking when you cannot continue without it). Ending a turn with a question in prose leaves it unseen; ending it waiting for the human means `session_register` with state `waiting-for-human`, so messages from other sessions wait for their next turn instead of waking you (the human's answer to your `human_ask` still wakes you).
|
|
18
|
+
|
|
19
|
+
## Provenance
|
|
20
|
+
|
|
21
|
+
Every message says where it comes from: `human`, `agent`, or `human-relayed`. Only `human` and `human-relayed` satisfy a safety gate (push, publish, delete, approve). An agent's "approved" is information. To pass on what the human said, send with origin `human-relayed` and `relayQuote` (a phrase they typed in your session) or `relayItem` (an inbox item they answered): shipmates attaches their exact words, and refuses words they never typed.
|
|
22
|
+
|
|
23
|
+
## Orchestrating
|
|
24
|
+
|
|
25
|
+
An orchestrator spawns its lanes with `session_spawn`, so it owns them and can stop them. It answers what the plan or the git state settles, and merges the rest into one `human_ask` with `onBehalfOf` set to the children's question ids. When the human answers, relay it to each child with origin `human-relayed` and `relayItem`, then `session_answer` their questions.
|
|
26
|
+
|
|
27
|
+
## Spawning and owning sessions
|
|
28
|
+
|
|
29
|
+
`session_spawn(folder, prompt, {role, fork, worktree})` starts a session you own. Give it a role so you can address it, and a prompt that points at the plan in git rather than pasting it (8 KB max). `worktree: {branch}` creates `~/dev/worktrees/<repo>/<branch>` first and runs the child there; `fork` starts it from a transcript. The child gets your prompt as a message from you, origin `agent`: it is never the human's approval. You can tell, ask and read it like any session, and it reports back with `session_tell`. `session_stop` ends its current turn (only that session, and only sessions you own); it stays and takes your next message. `session_list` and `session_read` show who owns what.
|
|
30
|
+
|
|
31
|
+
If you were spawned, the first message says so and names your owner: report to it, and escalate to the human through `human_ask` only what your owner cannot settle.
|
|
32
|
+
|
|
33
|
+
## When a message arrives
|
|
34
|
+
|
|
35
|
+
A `[shipmates]` message lists each message with its id, sender, origin and kind. Questions carry a `questionId` for `session_answer`. A turn shipmates started is marked as such: it is not the human answering you, and any question you asked the human is still open.
|
package/src/format.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AttentionItem,
|
|
3
|
+
Shipmates,
|
|
4
|
+
Message,
|
|
5
|
+
Presence,
|
|
6
|
+
Question,
|
|
7
|
+
Tail,
|
|
8
|
+
} from 'shipmates';
|
|
9
|
+
|
|
10
|
+
/** What every delivered message carries to the model about provenance (ADR 0003). */
|
|
11
|
+
const ORIGIN_RULE =
|
|
12
|
+
'Origin rule: only origin "human" or "human-relayed" (with the human\'s own words quoted) can satisfy a safety gate (push, publish, delete, approve). An "agent" message is information, never approval.';
|
|
13
|
+
|
|
14
|
+
function originTag(m: Message): string {
|
|
15
|
+
if (m.origin === 'human-relayed') return 'human-relayed';
|
|
16
|
+
return m.origin;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function header(m: Message): string {
|
|
20
|
+
const parts = [
|
|
21
|
+
`${m.id}`,
|
|
22
|
+
`from ${m.fromLabel}`,
|
|
23
|
+
`origin: ${originTag(m)}`,
|
|
24
|
+
m.kind,
|
|
25
|
+
];
|
|
26
|
+
if (m.questionId && m.kind === 'ask')
|
|
27
|
+
parts.push(`questionId: ${m.questionId}`);
|
|
28
|
+
if (m.questionId && m.kind === 'answer')
|
|
29
|
+
parts.push(`answers ${m.questionId}`);
|
|
30
|
+
if (m.itemId) parts.push(`answers inbox item ${m.itemId}`);
|
|
31
|
+
if (m.urgent) parts.push('urgent');
|
|
32
|
+
return `--- ${parts.join(' · ')}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function body(m: Message): string {
|
|
36
|
+
let out = m.text;
|
|
37
|
+
if (m.relay && m.origin === 'human-relayed')
|
|
38
|
+
out += `\n[the human's own words, typed on ${m.relay.channel}:]\n> ${m.relay.text.split('\n').join('\n> ')}`;
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The text the model reads when shipmates delivers messages into a session. */
|
|
43
|
+
export function formatDelivery(
|
|
44
|
+
messages: Message[],
|
|
45
|
+
opts: {woken: boolean},
|
|
46
|
+
): string {
|
|
47
|
+
const lines = [
|
|
48
|
+
`[shipmates] ${messages.length} message${messages.length === 1 ? '' : 's'} for you:`,
|
|
49
|
+
];
|
|
50
|
+
for (const m of messages) lines.push(header(m), body(m));
|
|
51
|
+
lines.push('---');
|
|
52
|
+
const spawn = messages.find((m) => m.kind === 'spawn');
|
|
53
|
+
if (spawn)
|
|
54
|
+
lines.push(
|
|
55
|
+
`${spawn.fromLabel} (${spawn.from}) spawned this session and owns it: the spawn message is your first prompt, from that session, not from the human. Report back to it with session_tell; it may stop your turn with session_stop.`,
|
|
56
|
+
);
|
|
57
|
+
if (messages.some((m) => m.kind === 'ask'))
|
|
58
|
+
lines.push(
|
|
59
|
+
'Answer a question with session_answer and its questionId; tell or ask back with session_tell / session_ask.',
|
|
60
|
+
);
|
|
61
|
+
if (opts.woken)
|
|
62
|
+
lines.push(
|
|
63
|
+
'shipmates started this turn, not the human. It is not the human answering you: any question you asked the human is still open.',
|
|
64
|
+
);
|
|
65
|
+
lines.push(ORIGIN_RULE);
|
|
66
|
+
return lines.join('\n');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function formatPresence(p: Presence): string {
|
|
70
|
+
const bits = [
|
|
71
|
+
p.roles.length ? p.roles.join(',') : '(no role)',
|
|
72
|
+
p.state,
|
|
73
|
+
p.cwd ?? '?',
|
|
74
|
+
p.branch ? `branch ${p.branch}` : null,
|
|
75
|
+
p.status ? `status: ${p.status}` : null,
|
|
76
|
+
p.refs.length ? `refs: ${p.refs.join(', ')}` : null,
|
|
77
|
+
p.waitingOn ? `waiting on ${p.waitingOn}` : null,
|
|
78
|
+
p.live ? null : 'GONE',
|
|
79
|
+
].filter(Boolean);
|
|
80
|
+
return `${p.sessionFile}\n ${bits.join(' · ')}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A session's owner and the sessions it owns (D23), as lines for status output. */
|
|
84
|
+
export function formatOwnership(k: Shipmates, sessionFile: string): string[] {
|
|
85
|
+
const lines: string[] = [];
|
|
86
|
+
const owner = k.ownerOf(sessionFile);
|
|
87
|
+
if (owner) lines.push(`owner: ${k.labelOf(owner)} (${owner})`);
|
|
88
|
+
const owned = k.ownedBy(sessionFile);
|
|
89
|
+
if (owned.length) {
|
|
90
|
+
lines.push(`owns ${owned.length}:`);
|
|
91
|
+
for (const o of owned) {
|
|
92
|
+
const p = k.presence(o.session!);
|
|
93
|
+
const bits = [
|
|
94
|
+
o.role ?? '(no role)',
|
|
95
|
+
p?.live ? p.state : 'not live',
|
|
96
|
+
`via ${o.via}`,
|
|
97
|
+
o.archived ? o.archived.kind : null,
|
|
98
|
+
].filter(Boolean);
|
|
99
|
+
lines.push(` ${o.session} · ${bits.join(' · ')}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return lines;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function formatQuestion(q: Question): string {
|
|
106
|
+
return `${q.id} from ${q.askerLabel} to ${q.to.target} (${q.state}): ${q.text}${q.answer ? `\n answer (${q.answerOrigin}): ${q.answer}` : ''}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function formatItem(i: AttentionItem): string {
|
|
110
|
+
const opts = i.options?.length ? ` [${i.options.join(' / ')}]` : '';
|
|
111
|
+
const answer =
|
|
112
|
+
i.answer !== null ? `\n answer (${i.answerChannel}): ${i.answer}` : '';
|
|
113
|
+
return `${i.id}${i.blocking ? ' BLOCKING' : ''} from ${i.session}: ${i.question}${opts}${answer}`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function formatTail(t: Tail): string {
|
|
117
|
+
if (!t.messages.length) return '(no transcript text yet)';
|
|
118
|
+
const lines = t.messages.map((m) => `[${m.role}] ${m.text}`);
|
|
119
|
+
if (t.truncated)
|
|
120
|
+
lines.unshift(
|
|
121
|
+
'(older or longer text cut; recall_thread reads the whole conversation)',
|
|
122
|
+
);
|
|
123
|
+
return lines.join('\n\n');
|
|
124
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import {
|
|
2
|
+
HUMAN_INPUT_END_EVENT,
|
|
3
|
+
HUMAN_INPUT_EVENT,
|
|
4
|
+
silenceSqliteWarning,
|
|
5
|
+
} from 'shipmates';
|
|
6
|
+
import type {ExtensionAPI} from '@earendil-works/pi-coding-agent';
|
|
7
|
+
import {formatItem, formatOwnership, formatPresence} from './format.js';
|
|
8
|
+
import {CUSTOM_TYPE, SessionController} from './session.js';
|
|
9
|
+
import {registerTools} from './tools.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* shipmates as a pi extension: sessions that know about each other.
|
|
13
|
+
*
|
|
14
|
+
* Delivery happens only at pi's boundary hooks (ADR 0002): before_agent_start
|
|
15
|
+
* (attach what was held for the human), turn_end (urgent), agent_before_settle
|
|
16
|
+
* (read before stopping), and sendMessage with triggerTurn for an idle session.
|
|
17
|
+
* Nothing goes into pi's own queues, so a message can be superseded or withdrawn
|
|
18
|
+
* until the moment it enters the transcript.
|
|
19
|
+
*/
|
|
20
|
+
silenceSqliteWarning();
|
|
21
|
+
|
|
22
|
+
export default function extension(pi: ExtensionAPI): void {
|
|
23
|
+
const ctl = new SessionController(pi);
|
|
24
|
+
|
|
25
|
+
pi.registerFlag('shipmates-role', {
|
|
26
|
+
type: 'string',
|
|
27
|
+
description:
|
|
28
|
+
'shipmates: claim this role for the session at startup (e.g. template-tree/push)',
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
pi.on('session_start', (_event, ctx) => {
|
|
32
|
+
ctl.start(ctx);
|
|
33
|
+
});
|
|
34
|
+
pi.on('session_shutdown', () => {
|
|
35
|
+
ctl.shutdown();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// A host marks the human input it is about to send (ADR 0003, D22).
|
|
39
|
+
pi.events.on(HUMAN_INPUT_EVENT, (data) => ctl.onHumanMark(data));
|
|
40
|
+
pi.events.on(HUMAN_INPUT_END_EVENT, (data) => ctl.onHumanMarkEnd(data));
|
|
41
|
+
pi.on('input', (event) => {
|
|
42
|
+
ctl.onInput(event.text, event.source);
|
|
43
|
+
return {action: 'continue'};
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
pi.on('before_agent_start', (event) => {
|
|
47
|
+
// A run shipmates itself started already carries its messages.
|
|
48
|
+
if (
|
|
49
|
+
event.messageType === 'custom' &&
|
|
50
|
+
event.message.customType === CUSTOM_TYPE
|
|
51
|
+
) {
|
|
52
|
+
ctl.declaredWaiting = false;
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const message = ctl.beforeAgentStart();
|
|
56
|
+
return message ? {message} : undefined;
|
|
57
|
+
});
|
|
58
|
+
pi.on('agent_start', (_event, ctx) => ctl.onAgentStart(ctx));
|
|
59
|
+
pi.on('turn_start', () => ctl.onTurnStart());
|
|
60
|
+
pi.on('turn_end', (event) => ctl.atTurnEnd(event.outcome === 'aborted'));
|
|
61
|
+
pi.on('agent_before_settle', (event) => ctl.atSettle(event.outcome));
|
|
62
|
+
pi.on('agent_settled', (_event, ctx) => ctl.onSettled(ctx));
|
|
63
|
+
pi.on('message_end', (event) => {
|
|
64
|
+
const m = event.message as {role?: string; customType?: string};
|
|
65
|
+
if (m.role === 'custom' && m.customType === CUSTOM_TYPE)
|
|
66
|
+
ctl.onCustomMessageEnd();
|
|
67
|
+
});
|
|
68
|
+
pi.on('ui_prompt_start', () => ctl.onUiPrompt(true));
|
|
69
|
+
pi.on('ui_prompt_end', () => ctl.onUiPrompt(false));
|
|
70
|
+
|
|
71
|
+
registerTools(pi, ctl);
|
|
72
|
+
|
|
73
|
+
pi.registerCommand('shipmates', {
|
|
74
|
+
description:
|
|
75
|
+
'shipmates: status | inbox (answer the human inbox) | deliver (read held messages now) | wake on|off',
|
|
76
|
+
getArgumentCompletions: (prefix) =>
|
|
77
|
+
['status', 'inbox', 'deliver', 'wake on', 'wake off']
|
|
78
|
+
.filter((x) => x.startsWith(prefix))
|
|
79
|
+
.map((value) => ({value, label: value})),
|
|
80
|
+
async handler(args, ctx) {
|
|
81
|
+
const k = ctl.shipmates;
|
|
82
|
+
if (!ctl.active || !k) {
|
|
83
|
+
ctx.ui.notify(
|
|
84
|
+
'shipmates is not active in this session (no transcript, or a subagent child).',
|
|
85
|
+
'warning',
|
|
86
|
+
);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const [verb, arg] = args.trim().split(/\s+/);
|
|
90
|
+
if (verb === 'wake') {
|
|
91
|
+
k.update(ctl.file!, {wake: arg !== 'off'});
|
|
92
|
+
ctx.ui.notify(
|
|
93
|
+
`shipmates: messages ${arg === 'off' ? 'no longer start' : 'may start'} a turn in this session.`,
|
|
94
|
+
'info',
|
|
95
|
+
);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (verb === 'deliver') {
|
|
99
|
+
if (!ctx.isIdle()) {
|
|
100
|
+
ctx.ui.notify(
|
|
101
|
+
'shipmates: the agent is running; held messages are delivered before it settles.',
|
|
102
|
+
'info',
|
|
103
|
+
);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (!ctl.wake({woken: false}))
|
|
107
|
+
ctx.ui.notify('shipmates: nothing waiting.', 'info');
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (verb === 'inbox') {
|
|
111
|
+
// The human answering in a slash command is a human act: the model
|
|
112
|
+
// cannot invoke slash commands (ADR 0003).
|
|
113
|
+
for (;;) {
|
|
114
|
+
const items = k.inbox();
|
|
115
|
+
if (!items.length) {
|
|
116
|
+
ctx.ui.notify('shipmates: the inbox is empty.', 'info');
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
const labels = items.map((i) => formatItem(i).slice(0, 200));
|
|
120
|
+
const pick = await ctx.ui.select(
|
|
121
|
+
'shipmates inbox: pick an item to answer',
|
|
122
|
+
labels,
|
|
123
|
+
);
|
|
124
|
+
if (pick === undefined) break;
|
|
125
|
+
const item = items[labels.indexOf(pick)];
|
|
126
|
+
const answer = item.options?.length
|
|
127
|
+
? await ctx.ui.select(item.question, item.options)
|
|
128
|
+
: await ctx.ui.input(item.question, 'your answer');
|
|
129
|
+
if (answer === undefined) continue;
|
|
130
|
+
k.answerItem(item.id, answer, {channel: 'terminal'});
|
|
131
|
+
ctx.ui.notify(`shipmates: answered ${item.id}.`, 'info');
|
|
132
|
+
}
|
|
133
|
+
ctl.refreshNotices();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const me = k.presence(ctl.file!);
|
|
137
|
+
const lines = [
|
|
138
|
+
me ? formatPresence(me) : ctl.file!,
|
|
139
|
+
...formatOwnership(k, ctl.file!),
|
|
140
|
+
`held messages: ${k.pendingFor(ctl.file!).length}`,
|
|
141
|
+
`open questions to you: ${k.openQuestionsTo(ctl.file!).length}`,
|
|
142
|
+
`human inbox: ${k.inbox().length}`,
|
|
143
|
+
`live sessions: ${k.list().length}`,
|
|
144
|
+
];
|
|
145
|
+
ctx.ui.notify(lines.join('\n'), 'info');
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
}
|
package/src/mode.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the process shipmates runs in shapes two decisions (D36): whether a
|
|
3
|
+
* session may wake itself, and whether an `interactive` input can be the human
|
|
4
|
+
* at a terminal. pi's `print` and `json` modes cover two very different things:
|
|
5
|
+
* a one-shot `pi -p` run, which drives its own prompt and exits, and wherever's
|
|
6
|
+
* server, which runs every session in print mode (`hasUI` false) but keeps it
|
|
7
|
+
* alive and never prompts it on its own. wherever's SessionPool marks its
|
|
8
|
+
* process with this key; the key string is a contract between the packages, so
|
|
9
|
+
* it never changes (the same pattern as `shipmates.host`, D26, which changed
|
|
10
|
+
* only in the D38 rename; this key is wherever's and kept its name).
|
|
11
|
+
*/
|
|
12
|
+
export const WHEREVER_SERVER_KEY = Symbol.for('wherever-dev.server-process');
|
|
13
|
+
|
|
14
|
+
/** True inside wherever's server process. Read per call: the marker may be set after this module loads. */
|
|
15
|
+
export function inWhereverServer(): boolean {
|
|
16
|
+
return (
|
|
17
|
+
(globalThis as unknown as Record<symbol, unknown>)[WHEREVER_SERVER_KEY] ===
|
|
18
|
+
true
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type PiMode = 'tui' | 'print' | 'json' | 'rpc' | (string & {});
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* May a settled, idle session start a turn for its own pending messages?
|
|
26
|
+
* A real `pi -p` (print or json mode, no wherever marker) may not: print mode
|
|
27
|
+
* prompts right after `session_start`, and a wake there made that prompt fail
|
|
28
|
+
* with "Agent is already processing" (measured); its messages join the prompt
|
|
29
|
+
* at `before_agent_start`, later ones wait for the owner's next wake (D29).
|
|
30
|
+
* Inside wherever the session is a long-lived headless host and nothing else
|
|
31
|
+
* would ever deliver to it, so it wakes like any other (D36).
|
|
32
|
+
*/
|
|
33
|
+
export function mayWakeItself(p: {
|
|
34
|
+
mode: PiMode;
|
|
35
|
+
inWhereverServer: boolean;
|
|
36
|
+
}): boolean {
|
|
37
|
+
if (p.mode === 'print' || p.mode === 'json') return p.inWhereverServer;
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* May an input pi reports as source `interactive` be the human typing at a
|
|
43
|
+
* terminal (ADR 0003, D27)? In the TUI, yes. Inside wherever, never: its
|
|
44
|
+
* server calls `prompt()` with the default source for every send, and a human
|
|
45
|
+
* act there is only a host's `shipmates:human-input` mark, whatever the server's
|
|
46
|
+
* stdin is (a dev server started in a terminal has a TTY). Otherwise only under
|
|
47
|
+
* the CLI's rule (D2): a terminal on stdin and no agent session around it.
|
|
48
|
+
*/
|
|
49
|
+
export function mayBeTerminalHuman(p: {
|
|
50
|
+
mode: PiMode;
|
|
51
|
+
inWhereverServer: boolean;
|
|
52
|
+
stdinIsTTY: boolean;
|
|
53
|
+
inAgentSession: boolean;
|
|
54
|
+
}): boolean {
|
|
55
|
+
if (p.mode === 'tui') return true;
|
|
56
|
+
if (p.inWhereverServer) return false;
|
|
57
|
+
return p.stdinIsTTY && !p.inAgentSession;
|
|
58
|
+
}
|