opencode-courier 0.3.0 → 0.4.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.
Files changed (141) hide show
  1. package/README.md +175 -274
  2. package/dist/index.js +47 -73
  3. package/dist/kernel/protocol.d.ts +20 -0
  4. package/dist/kernel/protocol.js +36 -0
  5. package/dist/kernel/tool.d.ts +5 -0
  6. package/dist/kernel/tool.js +5 -0
  7. package/dist/person/events.d.ts +23 -0
  8. package/dist/person/events.js +113 -0
  9. package/dist/person/form.d.ts +26 -0
  10. package/dist/person/form.js +64 -0
  11. package/dist/person/index.d.ts +17 -0
  12. package/dist/person/index.js +5 -0
  13. package/dist/{relay.d.ts → person/permission.d.ts} +27 -21
  14. package/dist/{relay.js → person/permission.js} +9 -5
  15. package/dist/person/ports.d.ts +58 -0
  16. package/dist/person/ports.js +2 -0
  17. package/dist/{question → person/question}/answer.d.ts +33 -4
  18. package/dist/{question → person/question}/answer.js +43 -8
  19. package/dist/person/question/index.d.ts +7 -0
  20. package/dist/{question → person/question}/index.js +3 -3
  21. package/dist/{question → person/question}/lifecycle.d.ts +1 -1
  22. package/dist/{question → person/question}/pure.d.ts +1 -2
  23. package/dist/{question → person/question}/pure.js +1 -1
  24. package/dist/{question → person/question}/relay.d.ts +1 -1
  25. package/dist/{question → person/question}/relay.js +14 -8
  26. package/dist/{question → person/question}/shared.d.ts +13 -3
  27. package/dist/person/question/shared.js +52 -0
  28. package/dist/person/question/types.d.ts +121 -0
  29. package/dist/person/question/types.js +1 -0
  30. package/dist/person/rpc-handlers.d.ts +160 -0
  31. package/dist/person/rpc-handlers.js +62 -0
  32. package/dist/person/rpc.d.ts +227 -0
  33. package/dist/person/rpc.js +70 -0
  34. package/dist/person/text.d.ts +68 -0
  35. package/dist/person/text.js +262 -0
  36. package/dist/person/tools.d.ts +20 -0
  37. package/dist/person/tools.js +55 -0
  38. package/dist/person/tui.d.ts +46 -0
  39. package/dist/{bounded.d.ts → platform/bounded.d.ts} +4 -0
  40. package/dist/{bounded.js → platform/bounded.js} +4 -0
  41. package/dist/platform/events.d.ts +34 -0
  42. package/dist/platform/events.js +121 -0
  43. package/dist/platform/hub.d.ts +195 -0
  44. package/dist/{hub.js → platform/hub.js} +27 -71
  45. package/dist/{version.js → platform/version.js} +1 -1
  46. package/dist/rpc.d.ts +2 -0
  47. package/dist/rpc.js +3 -0
  48. package/dist/scheduling/index.d.ts +6 -0
  49. package/dist/scheduling/index.js +5 -0
  50. package/dist/{later.d.ts → scheduling/later.d.ts} +7 -3
  51. package/dist/{later.js → scheduling/later.js} +12 -4
  52. package/dist/scheduling/text.d.ts +6 -0
  53. package/dist/scheduling/text.js +10 -0
  54. package/dist/scheduling/tools.d.ts +14 -0
  55. package/dist/scheduling/tools.js +48 -0
  56. package/dist/skill.d.ts +4 -0
  57. package/dist/skill.js +54 -1
  58. package/dist/{cleanup.d.ts → tree/cleanup.d.ts} +1 -27
  59. package/dist/{cleanup.js → tree/cleanup.js} +9 -16
  60. package/dist/tree/context.d.ts +15 -0
  61. package/dist/tree/context.js +34 -0
  62. package/dist/tree/domain.d.ts +101 -0
  63. package/dist/tree/domain.js +68 -0
  64. package/dist/{watch.d.ts → tree/events.d.ts} +10 -37
  65. package/dist/tree/events.js +204 -0
  66. package/dist/tree/forget.d.ts +24 -0
  67. package/dist/tree/forget.js +59 -0
  68. package/dist/tree/group.d.ts +82 -0
  69. package/dist/tree/group.js +203 -0
  70. package/dist/tree/index.d.ts +10 -0
  71. package/dist/tree/index.js +11 -0
  72. package/dist/tree/limits.d.ts +10 -0
  73. package/dist/{limits.js → tree/limits.js} +6 -55
  74. package/dist/tree/panel.d.ts +13 -0
  75. package/dist/tree/panel.js +75 -0
  76. package/dist/tree/ports.d.ts +276 -0
  77. package/dist/tree/ports.js +1 -0
  78. package/dist/tree/report.d.ts +23 -0
  79. package/dist/tree/report.js +33 -0
  80. package/dist/tree/roster.d.ts +27 -0
  81. package/dist/tree/roster.js +62 -0
  82. package/dist/tree/rpc-handlers.d.ts +201 -0
  83. package/dist/tree/rpc-handlers.js +20 -0
  84. package/dist/tree/rpc.d.ts +344 -0
  85. package/dist/tree/rpc.js +83 -0
  86. package/dist/tree/send.d.ts +14 -0
  87. package/dist/tree/send.js +99 -0
  88. package/dist/tree/spawn.d.ts +21 -0
  89. package/dist/tree/spawn.js +173 -0
  90. package/dist/tree/status.d.ts +128 -0
  91. package/dist/tree/status.js +62 -0
  92. package/dist/{stop.d.ts → tree/stop.d.ts} +1 -9
  93. package/dist/{stop.js → tree/stop.js} +9 -13
  94. package/dist/tree/store.d.ts +24 -0
  95. package/dist/tree/store.js +264 -0
  96. package/dist/{tree.d.ts → tree/subtree.d.ts} +5 -6
  97. package/dist/{tree.js → tree/subtree.js} +7 -5
  98. package/dist/tree/summary.d.ts +7 -0
  99. package/dist/tree/summary.js +35 -0
  100. package/dist/tree/text.d.ts +77 -0
  101. package/dist/tree/text.js +287 -0
  102. package/dist/tree/tools.d.ts +54 -0
  103. package/dist/{tools.js → tree/tools.js} +12 -142
  104. package/dist/tree/tui.d.ts +53 -0
  105. package/dist/tui.d.ts +3 -0
  106. package/dist/tui.js +1219 -0
  107. package/dist/webhook/index.d.ts +5 -0
  108. package/dist/webhook/index.js +3 -0
  109. package/dist/{webhook.d.ts → webhook/receiver.d.ts} +17 -23
  110. package/dist/{webhook.js → webhook/receiver.js} +58 -50
  111. package/dist/webhook/subscriptions.d.ts +29 -0
  112. package/dist/webhook/subscriptions.js +52 -0
  113. package/dist/webhook/text.d.ts +23 -0
  114. package/dist/webhook/text.js +82 -0
  115. package/dist/webhook/tools.d.ts +19 -0
  116. package/dist/webhook/tools.js +46 -0
  117. package/package.json +18 -7
  118. package/dist/courier.d.ts +0 -200
  119. package/dist/courier.js +0 -315
  120. package/dist/group.d.ts +0 -86
  121. package/dist/group.js +0 -247
  122. package/dist/hub.d.ts +0 -300
  123. package/dist/limits.d.ts +0 -65
  124. package/dist/notices.d.ts +0 -356
  125. package/dist/notices.js +0 -678
  126. package/dist/question/index.d.ts +0 -6
  127. package/dist/question/shared.js +0 -24
  128. package/dist/report.d.ts +0 -48
  129. package/dist/report.js +0 -88
  130. package/dist/roster.d.ts +0 -93
  131. package/dist/roster.js +0 -206
  132. package/dist/tools.d.ts +0 -94
  133. package/dist/watch.js +0 -474
  134. /package/dist/{question → person/question}/lifecycle.js +0 -0
  135. /package/dist/{question → person/question}/runtime.d.ts +0 -0
  136. /package/dist/{question → person/question}/runtime.js +0 -0
  137. /package/dist/{json.d.ts → platform/json.d.ts} +0 -0
  138. /package/dist/{json.js → platform/json.js} +0 -0
  139. /package/dist/{storage.d.ts → platform/storage.d.ts} +0 -0
  140. /package/dist/{storage.js → platform/storage.js} +0 -0
  141. /package/dist/{version.d.ts → platform/version.d.ts} +0 -0
@@ -1,9 +1,9 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
3
  import { isAbsolute } from "node:path";
4
- import { markLeft, membershipOf } from "./group.js";
5
- import { keepReason } from "./notices.js";
6
- import { remove, rosterKey } from "./roster.js";
4
+ import { forgetDropped } from "./forget.js";
5
+ import { childStore } from "./store.js";
6
+ import { keepReason } from "./text.js";
7
7
  /** At most this many changes and commits are returned; the reason still counts them all. */
8
8
  export const MAX_LISTED = 50;
9
9
  /**
@@ -11,11 +11,15 @@ export const MAX_LISTED = 50;
11
11
  * or commits found nowhere else is kept unless `force` is set; the result says so.
12
12
  */
13
13
  export async function cleanup(ports, parentID, input) {
14
- const entry = (await ports.storage.get(rosterKey(parentID, input.sessionID)));
14
+ const entry = await childStore(ports.storage).entry(parentID, input.sessionID);
15
15
  if (!entry)
16
16
  throw new Error(`${input.sessionID} is not on the courier_children list of ${parentID}.`);
17
17
  const { directory } = entry;
18
- const forget = () => forgetChild(ports, entry);
18
+ // A member still out is dropped from its group, so the group is released without it; the result names that group.
19
+ const forget = async () => {
20
+ const group = await forgetDropped(ports, entry);
21
+ return group ? { group } : {};
22
+ };
19
23
  if (!entry.isolated)
20
24
  return { sessionID: input.sessionID, directory, outcome: "forgotten", ...(await forget()) };
21
25
  // With force the state only decides whether there is anything left to remove, so a worktree git
@@ -42,17 +46,6 @@ export async function cleanup(ports, parentID, input) {
42
46
  });
43
47
  return { sessionID: input.sessionID, directory, outcome: "removed", ...(await forget()) };
44
48
  }
45
- /**
46
- * Drops a member still out from its group as `dropped`, so the group is released without it, then the roster entry
47
- * and report state. A held report stays with its group. Returns the group it was dropped from.
48
- */
49
- async function forgetChild(ports, entry) {
50
- const member = entry.group ? await membershipOf(ports.storage, entry.parentID, entry.group, entry.sessionID) : undefined;
51
- if (member?.out && (await markLeft(ports.storage, member, "dropped", ports.now())))
52
- ports.nudge();
53
- await remove(ports.storage, entry.parentID, entry.sessionID);
54
- return member?.out ? { group: member.group } : {};
55
- }
56
49
  /** Names the git to run, by absolute path, overriding the places `GIT_LOCATIONS` lists. */
57
50
  export const GIT_ENV = "OPENCODE_COURIER_GIT";
58
51
  /**
@@ -0,0 +1,15 @@
1
+ import type { ContextPorts } from "./ports.js";
2
+ /** The part of a session context this hook changes. */
3
+ export interface Shaped {
4
+ readonly sessionID: string;
5
+ tools: Record<string, unknown>;
6
+ system: Array<{
7
+ type: "text";
8
+ text: string;
9
+ }>;
10
+ }
11
+ /**
12
+ * The `context` hook: names a session's role in its tree in a system part, and hides courier_spawn
13
+ * from one at `maxDepth`. A session nobody spawned that has started none is pointed to the skill, if it could spawn.
14
+ */
15
+ export declare function shapeContext(ports: ContextPorts, event: Shaped): Promise<void>;
@@ -0,0 +1,34 @@
1
+ import { setBounded } from "../platform/bounded.js";
2
+ import { childStore } from "./store.js";
3
+ import { ROLE_PREFIX, rolePart } from "./text.js";
4
+ /** How many sessions' depths an instance remembers. */
5
+ const ROLES_MAX = 1000;
6
+ /**
7
+ * The `context` hook: names a session's role in its tree in a system part, and hides courier_spawn
8
+ * from one at `maxDepth`. A session nobody spawned that has started none is pointed to the skill, if it could spawn.
9
+ */
10
+ export async function shapeContext(ports, event) {
11
+ try {
12
+ const depth = await depthOf(ports, event.sessionID);
13
+ if (depth === null && !event.tools.courier_spawn)
14
+ return;
15
+ if (depth !== null && depth >= ports.limits.maxDepth)
16
+ delete event.tools.courier_spawn;
17
+ if (!event.system.some((part) => part.text.startsWith(ROLE_PREFIX)))
18
+ event.system.push({ type: "text", text: rolePart(depth, ports.limits) });
19
+ }
20
+ catch (error) {
21
+ ports.log(`courier: cannot tell the role of session ${event.sessionID}: ${String(error)}`);
22
+ }
23
+ }
24
+ async function depthOf(ports, sessionID) {
25
+ const known = ports.roles.get(sessionID);
26
+ if (known !== undefined)
27
+ return known;
28
+ // The reverse index alone: a scan here would run for every session's first request, courier or not.
29
+ const children = childStore(ports.storage);
30
+ const chain = await children.indexedLineage(sessionID);
31
+ const depth = chain.length || ((await children.children(sessionID)).length ? 0 : null);
32
+ setBounded(ports.roles, sessionID, depth, ROLES_MAX);
33
+ return depth;
34
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The tree's pure rules, on plain data: the limits, a session's lineage, whether it runs, and a group
3
+ * member's standing. Imports nothing of the plugin's but `kernel/` and `platform/json.ts`.
4
+ */
5
+ import type { Plugin } from "@opencode/plugin";
6
+ import type { Status } from "../kernel/protocol.js";
7
+ type Context = Plugin.Context;
8
+ /** The limits on the tree of sessions courier_spawn builds, from the plugin's options. */
9
+ export interface Limits {
10
+ readonly maxDepth: number;
11
+ readonly maxChildren: number;
12
+ readonly maxTotal: number;
13
+ }
14
+ export declare const DEFAULT_LIMITS: Limits;
15
+ /** The limits in the plugin's options; one that is not a positive integer keeps its default and is named in `problems`. */
16
+ export declare function readLimits(options: unknown): {
17
+ limits: Limits;
18
+ problems: string[];
19
+ };
20
+ /** The `nativeChildren` option: whether a child started without isolate gets OpenCode's own `parentID`; off unless `true`. */
21
+ export declare function readNativeChildren(options: unknown): {
22
+ nativeChildren: boolean;
23
+ problems: string[];
24
+ };
25
+ /** A session's times, as `session.get` gives them. */
26
+ type Times = Awaited<ReturnType<Context["session"]["get"]>>["time"];
27
+ /** Whether a session with these times runs: it has never finished a turn, or something reached it after the last one ended. */
28
+ export declare const busy: (time: Pick<Times, "updated" | "idle">) => boolean;
29
+ /** A session started with courier_spawn, recorded under the session that started it. */
30
+ export interface RosterEntry {
31
+ readonly sessionID: string;
32
+ readonly parentID: string;
33
+ readonly title: string;
34
+ readonly directory: string;
35
+ readonly isolated: boolean;
36
+ readonly createdAt: number;
37
+ /** For an isolated child, the directory its worktree was made from; for the record, nothing acts on it. */
38
+ readonly source?: string;
39
+ /** For an isolated child, the project its worktree belongs to; courier_cleanup removes it from there. */
40
+ readonly project?: string;
41
+ /** For an isolated child, the commit its worktree was made from; its own work is what came after. */
42
+ readonly base?: string;
43
+ /** `"status"` when its brief asked for a report with a status; absent for a child an earlier release briefed. */
44
+ readonly reports?: "status";
45
+ /** The join group courier_spawn put it in, whose release holds its report; absent for a child in none. */
46
+ readonly group?: string;
47
+ /** Created with OpenCode's own `parentID` (the `nativeChildren` option), so OpenCode shows its asks in its parent's view. */
48
+ readonly native?: true;
49
+ }
50
+ /** `lineage` over roster entries already read. */
51
+ export declare function lineageIn(entries: ReadonlyArray<RosterEntry>, sessionID: string): RosterEntry[];
52
+ /** Roster entries by their session, for `lineageBy`. */
53
+ export declare function bySession(entries: ReadonlyArray<RosterEntry>): Map<string, RosterEntry>;
54
+ /** `lineage` over roster entries already read and mapped by `bySession`. */
55
+ export declare function lineageBy(bySession: ReadonlyMap<string, RosterEntry>, sessionID: string): RosterEntry[];
56
+ /**
57
+ * The session whose view OpenCode shows the asks of a lineage's first session in: up its native parents, to the
58
+ * first session that is not a native child (an isolated one, or the top). The session itself when it is not native.
59
+ */
60
+ export declare function nativeRootOf(chain: ReadonlyArray<RosterEntry>): string;
61
+ /** What a report lists besides its text; `checks` are the commands the session ran and what each gave. */
62
+ export interface Artifacts {
63
+ readonly branch?: string;
64
+ readonly commits?: ReadonlyArray<string>;
65
+ readonly files?: ReadonlyArray<string>;
66
+ readonly checks?: ReadonlyArray<{
67
+ readonly command: string;
68
+ readonly result: string;
69
+ }>;
70
+ }
71
+ /** A report held with its group: its status, text and artifacts, as courier_send was given them, and when. */
72
+ export interface HeldReport {
73
+ readonly at: number;
74
+ readonly status: Status;
75
+ readonly message: string;
76
+ readonly artifacts?: Artifacts;
77
+ }
78
+ /** A member of a group that left it without a report, and why: its turn failed or was interrupted, it was deleted, or courier_cleanup dropped it. */
79
+ export interface LeftMember {
80
+ readonly sessionID: string;
81
+ readonly title: string;
82
+ readonly by: "failed" | "interrupted" | "deleted" | "dropped";
83
+ }
84
+ export declare const isGroupName: (value: unknown) => value is string;
85
+ /** A member of a group, as stored: its title for the release notice, and its report or how it left. */
86
+ export interface Member {
87
+ readonly title: string;
88
+ readonly joinedAt: number;
89
+ readonly report?: HeldReport;
90
+ readonly left?: {
91
+ readonly at: number;
92
+ readonly by: LeftMember["by"];
93
+ };
94
+ }
95
+ /** What is known of a member's standing: its report is held, still out, or it left, or it is no longer in an open group. */
96
+ export type Standing = "held" | "out" | LeftMember["by"] | "released";
97
+ /** A member's standing from its stored value, or `released` when there is none. */
98
+ export declare function standingOf(member: Member | undefined): Standing;
99
+ /** Whether every member of a group has a held report or has left: released once the parent's turn has ended. */
100
+ export declare const complete: (members: ReadonlyArray<Member>) => boolean;
101
+ export {};
@@ -0,0 +1,68 @@
1
+ import { millis, obj } from "../platform/json.js";
2
+ export const DEFAULT_LIMITS = { maxDepth: 3, maxChildren: 5, maxTotal: 20 };
3
+ /** The limits in the plugin's options; one that is not a positive integer keeps its default and is named in `problems`. */
4
+ export function readLimits(options) {
5
+ const given = obj(options);
6
+ const problems = [];
7
+ const read = (name) => {
8
+ const value = given[name];
9
+ if (value === undefined)
10
+ return DEFAULT_LIMITS[name];
11
+ if (typeof value === "number" && Number.isInteger(value) && value > 0)
12
+ return value;
13
+ problems.push(`${name} must be a positive integer, not ${JSON.stringify(value)}; using ${DEFAULT_LIMITS[name]}`);
14
+ return DEFAULT_LIMITS[name];
15
+ };
16
+ const limits = { maxDepth: read("maxDepth"), maxChildren: read("maxChildren"), maxTotal: read("maxTotal") };
17
+ return { limits, problems };
18
+ }
19
+ /** The `nativeChildren` option: whether a child started without isolate gets OpenCode's own `parentID`; off unless `true`. */
20
+ export function readNativeChildren(options) {
21
+ const value = obj(options).nativeChildren;
22
+ if (value === undefined || typeof value === "boolean")
23
+ return { nativeChildren: value === true, problems: [] };
24
+ return { nativeChildren: false, problems: [`nativeChildren must be true or false, not ${JSON.stringify(value)}; using false`] };
25
+ }
26
+ /** Whether a session with these times runs: it has never finished a turn, or something reached it after the last one ended. */
27
+ export const busy = (time) => time.idle === undefined || millis(time.updated) > millis(time.idle);
28
+ /** `lineage` over roster entries already read. */
29
+ export function lineageIn(entries, sessionID) {
30
+ return lineageBy(bySession(entries), sessionID);
31
+ }
32
+ /** Roster entries by their session, for `lineageBy`. */
33
+ export function bySession(entries) {
34
+ return new Map(entries.map((entry) => [entry.sessionID, entry]));
35
+ }
36
+ /** `lineage` over roster entries already read and mapped by `bySession`. */
37
+ export function lineageBy(bySession, sessionID) {
38
+ const chain = [];
39
+ for (let entry = bySession.get(sessionID); entry && !chain.includes(entry); entry = bySession.get(entry.parentID))
40
+ chain.push(entry);
41
+ return chain;
42
+ }
43
+ /**
44
+ * The session whose view OpenCode shows the asks of a lineage's first session in: up its native parents, to the
45
+ * first session that is not a native child (an isolated one, or the top). The session itself when it is not native.
46
+ */
47
+ export function nativeRootOf(chain) {
48
+ let root = chain[0].sessionID;
49
+ for (const entry of chain) {
50
+ if (!entry.native)
51
+ break;
52
+ root = entry.parentID;
53
+ }
54
+ return root;
55
+ }
56
+ /** What a group may be called: short, and with no `/`, which separates the parts of its keys, or `"`, which closes an attribute. */
57
+ const NAME = /^[\w.-]{1,60}$/;
58
+ export const isGroupName = (value) => typeof value === "string" && NAME.test(value);
59
+ /** A member's standing from its stored value, or `released` when there is none. */
60
+ export function standingOf(member) {
61
+ if (!member)
62
+ return "released";
63
+ if (member.report)
64
+ return "held";
65
+ return member.left?.by ?? "out";
66
+ }
67
+ /** Whether every member of a group has a held report or has left: released once the parent's turn has ended. */
68
+ export const complete = (members) => members.every((member) => member.report || member.left);
@@ -1,9 +1,5 @@
1
- import type { Hub, WatchPorts, WatchState } from "./hub.js";
2
- import { type ExecutionError } from "./notices.js";
3
- import { type FormCreated, type FormSettled, type PermissionAsked, type PermissionReplied } from "./relay.js";
4
- export type { FormsTold, WatchPorts, WatchState } from "./hub.js";
5
- /** How long to wait before subscribing again after the event stream ended or broke. */
6
- export declare const RESUBSCRIBE_MS = 5000;
1
+ import type { EventModule } from "../platform/events.js";
2
+ import type { ExecutionError, Waits, WatchPorts, WatchState } from "./ports.js";
7
3
  /** The part of OpenCode's `session.execution.failed` event the notice is made from. */
8
4
  export interface ExecutionFailed {
9
5
  readonly id: string;
@@ -59,40 +55,17 @@ export declare function noteInterrupted(ports: WatchPorts, event: SessionEvent):
59
55
  * started, whose reports can no longer be delivered; it leaves its own group. Returns the sessions forgotten.
60
56
  */
61
57
  export declare function noteDeleted(ports: WatchPorts, event: SessionEvent): Promise<string[]>;
58
+ /** A `Waits` asking `suppliers` one after another, cheapest first: the first that waits answers. */
59
+ export declare const waitsOn: (...suppliers: Waits[]) => Waits;
60
+ /** A `Waits` asking `suppliers` at once, as cheap as each other: it waits when one does, and fails when one fails. */
61
+ export declare const together: (...suppliers: Waits[]) => Waits;
62
62
  /**
63
63
  * Tells the parent of a spawned session whose turn ended without reporting to it since its last
64
64
  * prompt, unless it waits; finds the session by the reverse index alone. Returns the parents told.
65
65
  */
66
- export declare function reportSilent(ports: WatchPorts, seen: Set<string>, event: SessionEvent): Promise<string[]>;
66
+ export declare function reportSilent(ports: WatchPorts, seen: Set<string>, event: SessionEvent, outside: Waits): Promise<string[]>;
67
67
  /**
68
- * Tells the session at the top, the parent of a child or the session a chain of children started
69
- * from, what a waiting child asks and which answers there are, waking it. Returns the sessions told.
68
+ * Tells parents of a child's failed or silent turn, unless it waits on what `outside` says, and notes
69
+ * its prompts, interruptions and deletion; `after` a turn's end, seals the groups of its session.
70
70
  */
71
- export declare function reportAsked(ports: WatchPorts, state: WatchState, event: PermissionAsked): Promise<string[]>;
72
- /**
73
- * Tells the session told about a request that it was answered some other way, so it does not pass on
74
- * a stale question; requests answered through courier_answer no longer wait and are skipped.
75
- */
76
- export declare function reportReplied(ports: WatchPorts, state: WatchState, event: PermissionReplied): Promise<string[]>;
77
- /**
78
- * Tells the top session about a form OpenCode shows in a spawned session, such as web search asking
79
- * for its provider, which only the person can answer; question forms are left to the question relay.
80
- */
81
- export declare function reportForm(ports: WatchPorts, state: WatchState, event: FormCreated): Promise<string[]>;
82
- /** Tells the session told about a form that it was answered or withdrawn, so it does not send the person to a form that is gone. */
83
- export declare function reportFormSettled(ports: WatchPorts, state: WatchState, event: FormSettled): Promise<string[]>;
84
- /**
85
- * Relays the requests that spawned sessions already wait on, in every loaded location, which the
86
- * event stream does not repeat: those asked while it was down, before the watcher (re)subscribed.
87
- */
88
- export declare function relayPending(ports: WatchPorts, state: WatchState): Promise<void>;
89
- /**
90
- * Follows OpenCode's events until `signal` aborts: tells parents of a spawned child's failed or silent
91
- * turn, its pending permission or form, notes forms and shutdowns for the relay; ends after its current event.
92
- */
93
- export declare function watchChildren(ports: WatchPorts, state: WatchState, signal: AbortSignal, retryMs?: number): Promise<void>;
94
- /**
95
- * Makes the hub start its subscriptions to OpenCode's events with this copy's watcher, the one loaded
96
- * last; `join` starts them. The second is a standby, connected before the first's member leaves.
97
- */
98
- export declare function watchFromHub(hub: Pick<Hub, "subscribe">, state: WatchState, retryMs?: number): void;
71
+ export declare function treeEvents(state: WatchState, outside: Waits): EventModule<WatchPorts>;
@@ -0,0 +1,204 @@
1
+ import { envelope } from "../kernel/protocol.js";
2
+ import { claim, SEEN_MAX, setBounded } from "../platform/bounded.js";
3
+ import { forgetDeleted } from "./forget.js";
4
+ import { hasCompleteGroup, leave, outIn } from "./group.js";
5
+ import { awaited, reportOf, stoppedSincePrompt } from "./report.js";
6
+ import { childStore, groupStore } from "./store.js";
7
+ import { lastReply } from "./status.js";
8
+ import { failureNotice, silentNotice } from "./text.js";
9
+ /**
10
+ * Tells the parent of a child whose turn failed, since a child that cannot reach its model cannot
11
+ * call courier_send. Returns the parents told.
12
+ */
13
+ export async function reportFailure(ports, seen, event) {
14
+ if (!claim(seen, event.id))
15
+ return [];
16
+ const { sessionID, error } = event.data;
17
+ const children = childStore(ports.storage);
18
+ const entries = await children.entriesOf(sessionID);
19
+ const at = event.created ?? ports.now();
20
+ // Not in the way of the notice: kept only so the limits stop counting the child.
21
+ if (entries.length)
22
+ await children.settled(sessionID, "failed", at).catch((error) => ports.log(`courier watch: could not note the failed turn of ${sessionID}: ${String(error)}`));
23
+ const out = await Promise.all(entries.map((entry) => outIn(ports, entry)));
24
+ // Left before the notice, so the parent waits on the group meanwhile; nudged after it, so the group's
25
+ // message does not overtake the notice, short of an interval tick falling in between.
26
+ const completed = await Promise.all(out.map((member) => (member ? leave(ports, member, "failed", at) : Promise.resolve(false))));
27
+ // A session courier_stop stopped is not a failure to tell: its parent was told of the stop, or ordered it.
28
+ const quiet = entries.length > 0 && (await stoppedSincePrompt(children, sessionID).catch(() => false));
29
+ try {
30
+ if (quiet)
31
+ return [];
32
+ await Promise.all(entries.map((entry, index) => ports.session.synthetic({
33
+ sessionID: entry.parentID,
34
+ text: envelope(sessionID, failureNotice(entry.title, error, out[index]?.group), { failed: error.type }),
35
+ description: `Session ${sessionID} failed`,
36
+ metadata: { source: "courier", from: sessionID, failed: true },
37
+ delivery: "steer",
38
+ })));
39
+ }
40
+ finally {
41
+ if (completed.includes(true))
42
+ ports.nudge();
43
+ }
44
+ return entries.map((entry) => entry.parentID);
45
+ }
46
+ /** Inbox items that are not courier's or the parent's business: the person's own prompts, compactions and moves. */
47
+ const UNOWED = new Set(["user", "compaction", "move"]);
48
+ /** Remembers the type of an item enqueued for a spawned session, for `notePrompt`; other sessions cost one read. */
49
+ export async function noteEnqueued(ports, inbox, event) {
50
+ const { sessionID, inboxID, item } = event.data;
51
+ if ((await childStore(ports.storage).indexedParent(sessionID)) === undefined)
52
+ return false;
53
+ setBounded(inbox, inboxID, item.type, SEEN_MAX);
54
+ return true;
55
+ }
56
+ /**
57
+ * Notes that a message reached a spawned session, which then owes its parent a report, unless `inbox` knows it for one of
58
+ * `UNOWED` (`spawn` notes the task itself); reads the reverse index alone, and claims nothing: the note is the same twice.
59
+ */
60
+ export async function notePrompt(ports, event, inbox) {
61
+ const { sessionID, inboxID } = event.data;
62
+ // Kept, not deleted: the hub's other subscription looks it up for the same delivery.
63
+ if (inboxID !== undefined && UNOWED.has(inbox?.get(inboxID) ?? ""))
64
+ return false;
65
+ const children = childStore(ports.storage);
66
+ if ((await children.indexedParent(sessionID)) === undefined)
67
+ return false;
68
+ await children.prompted(sessionID, event.created ?? ports.now());
69
+ return true;
70
+ }
71
+ /**
72
+ * Notes that a spawned session's turn was stopped, which takes it out of its group without a report; one
73
+ * stopped by a shutdown resumes on the next start.
74
+ */
75
+ export async function noteInterrupted(ports, event) {
76
+ if (event.data.reason === "shutdown")
77
+ return false;
78
+ const { sessionID } = event.data;
79
+ const children = childStore(ports.storage);
80
+ const entry = await children.indexedEntry(sessionID);
81
+ if (entry === undefined)
82
+ return false;
83
+ const at = event.created ?? ports.now();
84
+ await children.settled(sessionID, "interrupted", at);
85
+ const member = await outIn(ports, entry);
86
+ if (member && (await leave(ports, member, "interrupted", at)))
87
+ ports.nudge();
88
+ return true;
89
+ }
90
+ /**
91
+ * Drops the report state, and the groups, of a session OpenCode deleted, and the report state of the sessions it
92
+ * started, whose reports can no longer be delivered; it leaves its own group. Returns the sessions forgotten.
93
+ */
94
+ export async function noteDeleted(ports, event) {
95
+ const { sessionID } = event.data;
96
+ const children = childStore(ports.storage);
97
+ const [parentID, started] = await Promise.all([children.indexedParent(sessionID), children.children(sessionID)]);
98
+ const forgotten = [...(parentID === undefined ? [] : [sessionID]), ...started.map((child) => child.sessionID)];
99
+ const entry = parentID === undefined ? undefined : await children.entry(parentID, sessionID);
100
+ const member = entry && (await outIn(ports, entry));
101
+ await forgetDeleted(ports, sessionID, forgotten, member, event.created);
102
+ return forgotten;
103
+ }
104
+ /** A `Waits` asking `suppliers` one after another, cheapest first: the first that waits answers. */
105
+ export const waitsOn = (...suppliers) => async (ports, sessionID, since) => {
106
+ for (const supplier of suppliers)
107
+ if (await supplier(ports, sessionID, since))
108
+ return true;
109
+ return false;
110
+ };
111
+ /** A `Waits` asking `suppliers` at once, as cheap as each other: it waits when one does, and fails when one fails. */
112
+ export const together = (...suppliers) => async (ports, sessionID, since) => (await Promise.all(suppliers.map((supplier) => supplier(ports, sessionID, since)))).includes(true);
113
+ /**
114
+ * Whether a session prompted at `prompt` waits: on an untold report of a session it started, a complete group of
115
+ * its about to be delivered, or what `outside` says it waits on. Cheapest first.
116
+ */
117
+ async function waits(ports, outside, sessionID, prompt) {
118
+ const children = childStore(ports.storage);
119
+ const started = await children.children(sessionID);
120
+ if ((await Promise.all(started.map((entry) => awaited(children, entry.sessionID)))).includes(true))
121
+ return true;
122
+ // A group with a member still out is waited on through that member, above; one whose every out member was told of is not.
123
+ if (started.some((entry) => entry.group) && (await hasCompleteGroup(groupStore(ports.storage), sessionID)))
124
+ return true;
125
+ return outside(ports, sessionID, prompt);
126
+ }
127
+ /**
128
+ * Tells the parent of a spawned session whose turn ended without reporting to it since its last
129
+ * prompt, unless it waits; finds the session by the reverse index alone. Returns the parents told.
130
+ */
131
+ export async function reportSilent(ports, seen, event, outside) {
132
+ const { sessionID } = event.data;
133
+ const children = childStore(ports.storage);
134
+ const entry = await children.indexedEntry(sessionID);
135
+ // Claimed after the lookup, so other sessions' turns do not crowd `seen`, and before anything is told.
136
+ if (!entry || !claim(seen, event.id))
137
+ return [];
138
+ const report = await reportOf(children, sessionID);
139
+ if (!report?.owes || (await waits(ports, outside, sessionID, report.prompt)))
140
+ return [];
141
+ if (await stoppedSincePrompt(children, sessionID).catch(() => false))
142
+ return [];
143
+ // The notice goes out without the reply rather than not at all.
144
+ const lastText = await ports.session.context({ sessionID }).then(lastReply, () => undefined);
145
+ const group = (await outIn(ports, entry))?.group;
146
+ // Before the notice, which may end the parent's turn at once: once told, it no longer waits for this one.
147
+ const toldAt = event.created ?? ports.now();
148
+ await children.told(sessionID, toldAt).catch((error) => ports.log(`courier watch: could not note that the parent of ${sessionID} was told: ${String(error)}`));
149
+ try {
150
+ await ports.session.synthetic({
151
+ sessionID: entry.parentID,
152
+ text: envelope(sessionID, silentNotice(entry.title, lastText, report.progressed, group), { ended: "without-report" }),
153
+ description: `Session ${sessionID} ended without a report`,
154
+ metadata: { source: "courier", from: sessionID, ended: "without-report" },
155
+ delivery: "steer",
156
+ });
157
+ }
158
+ catch (error) {
159
+ // Not told after all: the parent still waits for it.
160
+ await children.untold(sessionID, toldAt).catch(() => undefined);
161
+ throw error;
162
+ }
163
+ return [entry.parentID];
164
+ }
165
+ const TURN_ENDS = new Set(["session.execution.succeeded", "session.execution.failed", "session.execution.interrupted"]);
166
+ /** A session's turn ended, sealing its groups: one that is complete has the scheduler deliver it now. */
167
+ async function sealGroups(ports, event) {
168
+ if (event.data.reason === "shutdown")
169
+ return;
170
+ try {
171
+ if (await hasCompleteGroup(groupStore(ports.storage), event.data.sessionID))
172
+ ports.nudge();
173
+ }
174
+ catch (error) {
175
+ ports.log(`courier watch: could not read the groups of ${event.data.sessionID}: ${String(error)}`);
176
+ }
177
+ }
178
+ /** The events of spawned sessions' turns and inboxes, and their deletion: the tree's. */
179
+ function routeTree(ports, state, outside, event) {
180
+ if (event.type === "session.execution.failed")
181
+ return reportFailure(ports, state.seen, event);
182
+ if (event.type === "session.execution.succeeded")
183
+ return reportSilent(ports, state.seen, event, outside);
184
+ if (event.type === "session.execution.interrupted")
185
+ return noteInterrupted(ports, event);
186
+ if (event.type === "session.inbox.enqueued")
187
+ return noteEnqueued(ports, state.inbox, event);
188
+ if (event.type === "session.inbox.delivered")
189
+ return notePrompt(ports, event, state.inbox);
190
+ if (event.type === "session.deleted")
191
+ return noteDeleted(ports, event);
192
+ return undefined;
193
+ }
194
+ /**
195
+ * Tells parents of a child's failed or silent turn, unless it waits on what `outside` says, and notes
196
+ * its prompts, interruptions and deletion; `after` a turn's end, seals the groups of its session.
197
+ */
198
+ export function treeEvents(state, outside) {
199
+ return {
200
+ handle: (ports, event) => routeTree(ports, state, outside, event),
201
+ // After: a silent end is judged while the group the nudge may deliver is still there to wait on.
202
+ after: (ports, event) => (TURN_ENDS.has(event.type) ? sealGroups(ports, event) : undefined),
203
+ };
204
+ }
@@ -0,0 +1,24 @@
1
+ import type { CleanupPorts, GroupStore, Membership, ReportKeys, RosterEntry, RosterStorage, WatchPorts } from "./ports.js";
2
+ /** Drops a member from its group as its roster entry goes, unless its report is held: that still goes to the parent. True when dropped. */
3
+ export declare function dropMember(groups: GroupStore, parentID: string, group: string, sessionID: string): Promise<boolean>;
4
+ /** Drops every group of a parent, whose members' reports can no longer be delivered. */
5
+ export declare function dropGroups(groups: GroupStore, parentID: string): Promise<void>;
6
+ /**
7
+ * Forgets a child: its roster entry, its reverse key, its report state and, given its group, its membership. Only
8
+ * the entry's removal can fail it: keys left behind lead nowhere, and the next load drops them.
9
+ */
10
+ export declare function forgetChild(storage: RosterStorage, parentID: string, sessionID: string, group?: string): Promise<{
11
+ droppedFromGroup: boolean;
12
+ }>;
13
+ /**
14
+ * Drops a member still out from its group as `dropped`, so the group is released without it, then the roster entry
15
+ * and report state. A held report stays with its group. Returns the group it was dropped from.
16
+ */
17
+ export declare function forgetDropped(ports: Pick<CleanupPorts, "storage" | "now" | "nudge">, entry: RosterEntry): Promise<string | undefined>;
18
+ /**
19
+ * Forgets what a session OpenCode deleted leaves: the report state of `forgotten`, itself and the sessions it started,
20
+ * and its groups; `member`, its place in its own group, it leaves at `created`, or now.
21
+ */
22
+ export declare function forgetDeleted(ports: WatchPorts, sessionID: string, forgotten: ReadonlyArray<string>, member: Membership | undefined, created?: number): Promise<void>;
23
+ /** Removes report keys of sessions with no roster entry; a key that will not go is left for the next load. */
24
+ export declare function forgetReports(storage: RosterStorage, keys: ReportKeys, sessions: ReadonlyArray<string>): Promise<void>;
@@ -0,0 +1,59 @@
1
+ import { leave, markLeft, membershipFor } from "./group.js";
2
+ import { childStore, groupStore } from "./store.js";
3
+ // Forgetting a child and what it leaves behind. Its roster entry and report state go together; its group is another
4
+ // aggregate, left best effort and alongside, so a report held there outlives the entry and still reaches the parent.
5
+ /** Drops a member from its group as its roster entry goes, unless its report is held: that still goes to the parent. True when dropped. */
6
+ export async function dropMember(groups, parentID, group, sessionID) {
7
+ const member = await groups.member(parentID, group, sessionID);
8
+ if (!member || member.report)
9
+ return false;
10
+ await groups.remove(parentID, group, sessionID);
11
+ return true;
12
+ }
13
+ /** Drops every group of a parent, whose members' reports can no longer be delivered. */
14
+ export async function dropGroups(groups, parentID) {
15
+ const members = await groups.ofParent(parentID);
16
+ await Promise.all(members.map((member) => groups.remove(parentID, member.group, member.sessionID)));
17
+ }
18
+ /**
19
+ * Forgets a child: its roster entry, its reverse key, its report state and, given its group, its membership. Only
20
+ * the entry's removal can fail it: keys left behind lead nowhere, and the next load drops them.
21
+ */
22
+ export async function forgetChild(storage, parentID, sessionID, group) {
23
+ const [, dropped] = await Promise.all([
24
+ childStore(storage).remove(parentID, sessionID),
25
+ group ? dropMember(groupStore(storage), parentID, group, sessionID).catch(() => false) : false,
26
+ ]);
27
+ return { droppedFromGroup: dropped };
28
+ }
29
+ /**
30
+ * Drops a member still out from its group as `dropped`, so the group is released without it, then the roster entry
31
+ * and report state. A held report stays with its group. Returns the group it was dropped from.
32
+ */
33
+ export async function forgetDropped(ports, entry) {
34
+ const groups = groupStore(ports.storage);
35
+ const member = await membershipFor(groups, entry);
36
+ if (member?.out && (await markLeft(groups, member, "dropped", ports.now())))
37
+ ports.nudge();
38
+ await forgetChild(ports.storage, entry.parentID, entry.sessionID);
39
+ return member?.out ? member.group : undefined;
40
+ }
41
+ /**
42
+ * Forgets what a session OpenCode deleted leaves: the report state of `forgotten`, itself and the sessions it started,
43
+ * and its groups; `member`, its place in its own group, it leaves at `created`, or now.
44
+ */
45
+ export async function forgetDeleted(ports, sessionID, forgotten, member, created) {
46
+ const children = childStore(ports.storage);
47
+ // Its groups go whether or not it has children on the roster: a held report outlives the member's entry.
48
+ const [completed] = await Promise.all([
49
+ member ? leave(ports, member, "deleted", created ?? ports.now()) : Promise.resolve(false),
50
+ ...forgotten.map((id) => children.forgetReport(id)),
51
+ dropGroups(groupStore(ports.storage), sessionID),
52
+ ]);
53
+ if (completed)
54
+ ports.nudge();
55
+ }
56
+ /** Removes report keys of sessions with no roster entry; a key that will not go is left for the next load. */
57
+ export async function forgetReports(storage, keys, sessions) {
58
+ await childStore(storage).dropReported(sessions.flatMap((sessionID) => keys.get(sessionID) ?? []));
59
+ }