@north-light/crouter 0.3.221 → 0.3.222

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 (155) hide show
  1. package/dist/api/client.d.ts +21 -1
  2. package/dist/api/client.js +34 -0
  3. package/dist/api/dto/chat-inventory.d.ts +13 -0
  4. package/dist/api/dto/human-requests.d.ts +88 -0
  5. package/dist/api/dto/human-requests.js +4 -0
  6. package/dist/api/dto/human.d.ts +3 -0
  7. package/dist/api/dto/reviews.d.ts +2 -0
  8. package/dist/api/index.d.ts +1 -0
  9. package/dist/api/index.js +1 -0
  10. package/dist/api/routes.d.ts +7 -0
  11. package/dist/api/routes.js +10 -0
  12. package/dist/builtin-memory/00-runtime-base/00-authoring.md +31 -0
  13. package/dist/builtin-memory/00-runtime-base/01-escalation.md +14 -0
  14. package/dist/builtin-memory/{insights/listen.md → 00-runtime-base/02-insight-capture.md} +1 -0
  15. package/dist/builtin-memory/02-turn-lifecycle/00-ending-a-turn.md +27 -0
  16. package/dist/builtin-memory/{02-lifecycle/01-resident.md → 02-turn-lifecycle/02-resident.md} +5 -0
  17. package/dist/builtin-memory/04-base-worker.md +4 -8
  18. package/dist/builtin-memory/04-orchestration-kernel.md +1 -1
  19. package/dist/builtin-memory/05-kinds/advisor/01-orchestrator.md +1 -0
  20. package/dist/builtin-memory/05-kinds/advisor/advice-contract.md +1 -0
  21. package/dist/builtin-memory/05-kinds/design/00-base.md +2 -1
  22. package/dist/builtin-memory/05-kinds/design/01-orchestrator.md +2 -1
  23. package/dist/builtin-memory/05-kinds/design/design-contract.md +19 -0
  24. package/dist/builtin-memory/05-kinds/developer/00-base.md +1 -0
  25. package/dist/builtin-memory/05-kinds/developer/01-orchestrator.md +1 -0
  26. package/dist/builtin-memory/05-kinds/explore/00-base.md +1 -0
  27. package/dist/builtin-memory/05-kinds/explore/01-orchestrator.md +1 -0
  28. package/dist/builtin-memory/05-kinds/general/00-base.md +1 -0
  29. package/dist/builtin-memory/05-kinds/plan/00-base.md +2 -1
  30. package/dist/builtin-memory/05-kinds/plan/01-orchestrator.md +2 -1
  31. package/dist/builtin-memory/05-kinds/plan/plan-contract.md +28 -0
  32. package/dist/builtin-memory/05-kinds/plan/reviewers/architecture-fit.md +1 -0
  33. package/dist/builtin-memory/05-kinds/plan/reviewers/code-smells.md +1 -0
  34. package/dist/builtin-memory/05-kinds/plan/reviewers/lens-contract.md +1 -0
  35. package/dist/builtin-memory/05-kinds/plan/reviewers/pattern-consistency.md +1 -0
  36. package/dist/builtin-memory/05-kinds/plan/reviewers/requirements-coverage.md +1 -0
  37. package/dist/builtin-memory/05-kinds/plan/reviewers/security.md +1 -0
  38. package/dist/builtin-memory/05-kinds/review/00-base.md +1 -0
  39. package/dist/builtin-memory/05-kinds/review/01-orchestrator.md +1 -0
  40. package/dist/builtin-memory/05-kinds/review/companion/00-base.md +1 -0
  41. package/dist/builtin-memory/05-kinds/review/security-findings.md +1 -0
  42. package/dist/builtin-memory/05-kinds/spec/00-base.md +4 -3
  43. package/dist/builtin-memory/05-kinds/spec/01-orchestrator.md +1 -0
  44. package/dist/builtin-memory/05-kinds/spec/requirements.md +1 -0
  45. package/dist/builtin-memory/design/guide.md +35 -0
  46. package/dist/builtin-memory/design/roadmap.md +21 -0
  47. package/dist/builtin-memory/insights/capture.md +1 -1
  48. package/dist/builtin-memory/internal/plugins.md +10 -1
  49. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  50. package/dist/builtin-memory/plan/roadmap.md +6 -28
  51. package/dist/builtin-memory/spec/guide.md +19 -8
  52. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +28 -15
  53. package/dist/clients/attach/render/markdown-source.js +106 -1
  54. package/dist/clients/attach/session/file-links.d.ts +13 -4
  55. package/dist/clients/attach/session/file-links.js +54 -58
  56. package/dist/clients/attach/viewer.js +525 -523
  57. package/dist/clients/inbox/controller.js +1 -1
  58. package/dist/clients/inbox/resolve.d.ts +1 -0
  59. package/dist/clients/inbox/review/review-client.js +3 -1
  60. package/dist/commands/__tests__/human.test.js +2 -2
  61. package/dist/commands/human/request.d.ts +2 -0
  62. package/dist/commands/human/request.js +281 -0
  63. package/dist/commands/human.js +5 -2
  64. package/dist/commands/sys/config.js +2 -2
  65. package/dist/commands/sys/doctor.js +54 -2
  66. package/dist/core/__tests__/broker-extension-canvas-db-boundary.test.js +7 -4
  67. package/dist/core/__tests__/fixtures/memory-slash-live-probe.d.ts +1 -0
  68. package/dist/core/__tests__/fixtures/memory-slash-live-probe.js +71 -0
  69. package/dist/core/__tests__/human-action-delivery.test.d.ts +1 -0
  70. package/dist/core/__tests__/human-action-delivery.test.js +140 -0
  71. package/dist/core/__tests__/human-actions.test.d.ts +1 -0
  72. package/dist/core/__tests__/human-actions.test.js +116 -0
  73. package/dist/core/__tests__/inline-memory-refs.test.js +1 -1
  74. package/dist/core/__tests__/profile-project-memory-delivery.test.js +1 -1
  75. package/dist/core/__tests__/prospective-inventory-capability-parity.test.d.ts +1 -0
  76. package/dist/core/__tests__/prospective-inventory-capability-parity.test.js +91 -0
  77. package/dist/core/__tests__/seam/memory-slash-node-relative-inventory.test.d.ts +1 -0
  78. package/dist/core/__tests__/seam/memory-slash-node-relative-inventory.test.js +127 -0
  79. package/dist/core/__tests__/seam/prospective-inventory-stdout.test.d.ts +1 -0
  80. package/dist/core/__tests__/seam/prospective-inventory-stdout.test.js +31 -0
  81. package/dist/core/canvas/db.js +23 -0
  82. package/dist/core/canvas/human-deliveries.d.ts +53 -0
  83. package/dist/core/canvas/human-deliveries.js +75 -0
  84. package/dist/core/config.d.ts +13 -1
  85. package/dist/core/config.js +51 -1
  86. package/dist/core/feed/inbox.d.ts +6 -0
  87. package/dist/core/feed/inbox.js +9 -1
  88. package/dist/core/human/action-binding.d.ts +21 -0
  89. package/dist/core/human/action-binding.js +40 -0
  90. package/dist/core/human/completion.d.ts +38 -0
  91. package/dist/core/human/completion.js +27 -0
  92. package/dist/core/human/convention.d.ts +2 -0
  93. package/dist/core/human/convention.js +2 -0
  94. package/dist/core/human/tickets.d.ts +25 -6
  95. package/dist/core/human/tickets.js +19 -13
  96. package/dist/core/human/types.d.ts +5 -0
  97. package/dist/core/human-actions.d.ts +25 -0
  98. package/dist/core/human-actions.js +101 -0
  99. package/dist/core/memory-resolver.js +1 -1
  100. package/dist/core/profiles/select.d.ts +2 -0
  101. package/dist/core/profiles/select.js +21 -4
  102. package/dist/core/runtime/broker/frame-dispatch.js +2 -5
  103. package/dist/core/runtime/broker-inventory.d.ts +1 -2
  104. package/dist/core/runtime/broker-inventory.js +2 -77
  105. package/dist/core/runtime/broker-persona-guidance.js +1 -1
  106. package/dist/core/runtime/broker.js +4 -4
  107. package/dist/core/runtime/chat-inventory-rows.d.ts +8 -0
  108. package/dist/core/runtime/chat-inventory-rows.js +105 -0
  109. package/dist/core/runtime/command-surface.d.ts +8 -3
  110. package/dist/core/runtime/command-surface.js +42 -6
  111. package/dist/core/runtime/launch-target.d.ts +25 -0
  112. package/dist/core/runtime/launch-target.js +54 -0
  113. package/dist/core/runtime/persona.js +3 -3
  114. package/dist/core/runtime/prospective-inventory-cli.d.ts +1 -0
  115. package/dist/core/runtime/prospective-inventory-cli.js +61 -0
  116. package/dist/core/runtime/prospective-inventory.d.ts +10 -0
  117. package/dist/core/runtime/prospective-inventory.js +88 -0
  118. package/dist/core/runtime/spawn.d.ts +3 -1
  119. package/dist/core/runtime/spawn.js +5 -3
  120. package/dist/core/substrate/on-read.js +17 -28
  121. package/dist/core/substrate/render-node.d.ts +3 -2
  122. package/dist/core/substrate/render-node.js +3 -2
  123. package/dist/core/substrate/render.js +51 -19
  124. package/dist/core/substrate/schema.d.ts +5 -1
  125. package/dist/core/substrate/schema.js +4 -4
  126. package/dist/core/user-settings.d.ts +4 -0
  127. package/dist/core/user-settings.js +1 -0
  128. package/dist/daemon/api/__tests__/profile-launch-gates.test.js +52 -3
  129. package/dist/daemon/api/handlers/human-requests.d.ts +2 -0
  130. package/dist/daemon/api/handlers/human-requests.js +409 -0
  131. package/dist/daemon/api/handlers/human.js +3 -0
  132. package/dist/daemon/api/handlers/inbox.js +3 -0
  133. package/dist/daemon/api/handlers/nodes.d.ts +1 -3
  134. package/dist/daemon/api/handlers/nodes.js +11 -46
  135. package/dist/daemon/api/handlers/prospective-chat-inventory.d.ts +2 -0
  136. package/dist/daemon/api/handlers/prospective-chat-inventory.js +59 -0
  137. package/dist/daemon/api/handlers/reviews.js +10 -2
  138. package/dist/daemon/api/server.js +4 -0
  139. package/dist/daemon/crtrd.js +6 -0
  140. package/dist/daemon/human/deliver-action.d.ts +16 -0
  141. package/dist/daemon/human/deliver-action.js +168 -0
  142. package/dist/daemon/human/finish.d.ts +8 -5
  143. package/dist/daemon/human/finish.js +45 -6
  144. package/dist/daemon/human/sweep.js +4 -1
  145. package/dist/daemon/reconcilers/human-delivery-lane.d.ts +10 -0
  146. package/dist/daemon/reconcilers/human-delivery-lane.js +41 -0
  147. package/dist/daemon/review/finish.d.ts +8 -3
  148. package/dist/daemon/review/finish.js +19 -1
  149. package/dist/types.d.ts +8 -0
  150. package/dist/types.js +1 -0
  151. package/package.json +1 -1
  152. package/runtime.lock.json +2 -2
  153. package/dist/builtin-memory/00-runtime-base.md +0 -55
  154. package/dist/builtin-memory/design.md +0 -55
  155. /package/dist/builtin-memory/{02-lifecycle/00-terminal.md → 02-turn-lifecycle/01-terminal.md} +0 -0
@@ -220,7 +220,7 @@ export class InboxController {
220
220
  async cancelFromInbox(dir) {
221
221
  this.submittingDir = dir;
222
222
  try {
223
- await cancelTicketViaDaemon(dir, { reason: 'Canceled from the inbox.', actor: 'human' });
223
+ await cancelTicketViaDaemon(dir, { reason: 'Canceled from the inbox.', actor: 'human', disposition: 'dismissed' });
224
224
  this.status = 'canceled';
225
225
  }
226
226
  catch (error) {
@@ -4,6 +4,7 @@ export declare function resolveTicketPage(dir: string, responses: PageResponses)
4
4
  export declare function cancelTicketViaDaemon(dir: string, opts: {
5
5
  reason: string;
6
6
  actor: string;
7
+ disposition?: 'canceled' | 'dismissed';
7
8
  }): Promise<void>;
8
9
  export declare function daemonErrorMessage(err: unknown): string;
9
10
  export type ResolveFailure = 'unreachable' | 'already_resolved' | 'delivery_failed' | 'other';
@@ -67,7 +67,9 @@ export function createReviewClient(opts = {}) {
67
67
  };
68
68
  },
69
69
  async cancel(reviewId, reason) {
70
- await request(() => cliClient().cancelReview(reviewId, { reason, actor: 'human' }));
70
+ // The recipient surface: closing a review here is a dismissal, never the
71
+ // requester withdrawing it.
72
+ await request(() => cliClient().cancelReview(reviewId, { reason, actor: 'human', disposition: 'dismissed' }));
71
73
  },
72
74
  };
73
75
  }
@@ -101,11 +101,11 @@ test('human help carries the page authoring model and follows the page-surface s
101
101
  test('page_surface removes the terminal-only human surfaces from the tree', () => {
102
102
  const names = () => registerHuman().children.map((child) => child.name);
103
103
  withPageSurface(false, () => {
104
- assert.deepEqual(names(), ['components', 'send', 'review', 'feedback', 'show', 'cancel', 'list', 'resolve']);
104
+ assert.deepEqual(names(), ['components', 'send', 'review', 'feedback', 'show', 'request', 'cancel', 'list', 'resolve']);
105
105
  });
106
106
  withPageSurface(true, () => {
107
107
  const children = names();
108
- assert.deepEqual(children, ['components', 'send', 'feedback', 'cancel', 'list', 'resolve']);
108
+ assert.deepEqual(children, ['components', 'send', 'feedback', 'request', 'cancel', 'list', 'resolve']);
109
109
  const human = registerHuman();
110
110
  assert.doesNotMatch(human.help.model ?? '', /`review`|`show`/);
111
111
  assert.doesNotMatch(human.rootEntry?.useWhen ?? '', /review a document|live display/);
@@ -0,0 +1,2 @@
1
+ import type { BranchDef } from '../../core/command.js';
2
+ export declare const humanRequestBranch: BranchDef;
@@ -0,0 +1,281 @@
1
+ // `crtr human request` — the command-line face of the durable programmatic
2
+ // request contract. A request is an ordinary page ticket in the human inbox
3
+ // whose creator may exit immediately: there is no reply bridge, the terminal
4
+ // result is durable, and an optional named action carries the completion
5
+ // document to a local command. Every leaf is a thin typed call on crtrd; the
6
+ // daemon owns validation, settlement, and delivery.
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ import { defineBranch, defineLeaf } from '../../core/command.js';
9
+ import { InputError } from '../../core/io.js';
10
+ import { cliClient, rethrowAsCliError } from '../api-client.js';
11
+ // ---------------------------------------------------------------------------
12
+ // shared input helpers
13
+ // ---------------------------------------------------------------------------
14
+ function readJsonFile(path, field, shape) {
15
+ if (!existsSync(path)) {
16
+ throw new InputError({ error: 'not_found', message: `no such file: ${path}`, field, next: `Pass --${field} PATH pointing at a JSON file holding ${shape}.` });
17
+ }
18
+ let raw;
19
+ try {
20
+ raw = readFileSync(path, 'utf8');
21
+ }
22
+ catch (error) {
23
+ throw new InputError({ error: 'unreadable_file', message: `could not read ${path}: ${String(error)}`, field, next: 'Pass a readable JSON file.' });
24
+ }
25
+ let parsed;
26
+ try {
27
+ parsed = JSON.parse(raw);
28
+ }
29
+ catch (error) {
30
+ throw new InputError({ error: 'invalid_json', message: `${path} is not valid JSON: ${String(error)}`, field, next: `Write ${shape} into the file as JSON.` });
31
+ }
32
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
33
+ throw new InputError({ error: 'invalid_field', message: `${path} must hold a JSON object`, field, next: `Write ${shape} into the file as a JSON object.` });
34
+ }
35
+ return parsed;
36
+ }
37
+ /** The page crosses the wire inline, so the CLI reads the authored file and
38
+ * derives its dialect from the extension — the same rule page authoring uses. */
39
+ function readPageFile(path) {
40
+ const html = /\.html?$/i.test(path);
41
+ if (!html && !path.endsWith('.tsx')) {
42
+ throw new InputError({ error: 'invalid_field', message: `page source file must be .tsx, .html, or .htm: ${path}`, field: 'page', next: 'Author the page as a .tsx module or a complete .html document.' });
43
+ }
44
+ if (!existsSync(path)) {
45
+ throw new InputError({ error: 'not_found', message: `page source file does not exist: ${path}`, field: 'page', next: 'Pass --page PATH pointing at the authored page.' });
46
+ }
47
+ return { dialect: html ? 'html' : 'jsx', source: readFileSync(path, 'utf8') };
48
+ }
49
+ function requestId(input) {
50
+ const id = typeof input['request_id'] === 'string' ? input['request_id'].trim() : '';
51
+ if (id === '') {
52
+ throw new InputError({ error: 'missing_request_id', message: 'a request id is required', field: 'request_id', next: 'Pass the request_id returned by `crtr human request create`.' });
53
+ }
54
+ return id;
55
+ }
56
+ /** The one projection of a request record onto leaf output. Absent fields stay
57
+ * absent: a dismissal or a withdrawal has no responses to report. */
58
+ function requestResult(dto) {
59
+ return {
60
+ request_id: dto.request_id,
61
+ state: dto.state,
62
+ title: dto.title,
63
+ ...(dto.subtitle === undefined ? {} : { subtitle: dto.subtitle }),
64
+ source: dto.source,
65
+ emitted_at: dto.emitted_at,
66
+ ...(dto.settled_at === undefined ? {} : { settled_at: dto.settled_at }),
67
+ ...(dto.responses === undefined ? {} : { responses: dto.responses }),
68
+ ...(dto.reason === undefined ? {} : { reason: dto.reason }),
69
+ ...(dto.actor === undefined ? {} : { actor: dto.actor }),
70
+ ...(dto.action === undefined ? {} : { action: dto.action }),
71
+ ...(dto.delivery === undefined ? {} : { delivery: dto.delivery }),
72
+ };
73
+ }
74
+ const RECORD_OUTPUT = [
75
+ { name: 'request_id', type: 'string', required: true, constraint: 'The request — the same 64-hex id the human inbox lists it under.' },
76
+ { name: 'state', type: 'pending | answered | dismissed | canceled', required: true, constraint: 'answered: the person (or an authorized responder) submitted the typed responses. dismissed: the recipient surface closed it unanswered. canceled: the requester withdrew it.' },
77
+ { name: 'title', type: 'string', required: true, constraint: 'Page title as currently published.' },
78
+ { name: 'subtitle', type: 'string', required: false, constraint: 'Page subtitle when the page carries one.' },
79
+ { name: 'source', type: 'object', required: true, constraint: 'Stored provenance from the request creator: sessionName?, askedBy?, emittedAt?, profileName?, nodeId?.' },
80
+ { name: 'emitted_at', type: 'string', required: true, constraint: 'UTC ISO instant of creation; a replace never changes it.' },
81
+ { name: 'settled_at', type: 'string', required: false, constraint: 'UTC ISO instant of the terminal result. Absent while pending.' },
82
+ { name: 'responses', type: 'object', required: false, constraint: 'The typed slot map, keyed by response-bearing component id. Present only when state is answered.' },
83
+ { name: 'reason', type: 'string', required: false, constraint: 'Note recorded by the dismissal or the withdrawal.' },
84
+ { name: 'actor', type: 'string', required: false, constraint: 'Who settled it, when the settling surface named itself.' },
85
+ { name: 'action', type: 'object', required: false, constraint: '{name, payload} frozen at creation; an omitted payload is frozen as null. Absent when no action is bound.' },
86
+ { name: 'delivery', type: 'object', required: false, constraint: 'Completion-delivery state for the bound action: {state: none | pending | running | accepted | permanent_failed, attempt, next_attempt_at?, accepted_at?, permanent_failed_at?, last_failure?}. Absent when no action is bound.' },
87
+ ];
88
+ // ---------------------------------------------------------------------------
89
+ // create
90
+ // ---------------------------------------------------------------------------
91
+ const createLeaf = defineLeaf({
92
+ name: 'create',
93
+ description: 'create a durable request from a JSON request file',
94
+ whenToUse: 'a script or backend needs a human decision that must survive its own exit, rather than an answer routed back to a live node.',
95
+ help: {
96
+ name: 'human request create',
97
+ summary: 'create one durable human request from the typed create object',
98
+ params: [
99
+ {
100
+ kind: 'flag',
101
+ name: 'request-file',
102
+ type: 'path',
103
+ required: true,
104
+ constraint: 'JSON file holding the create object: {"page":{"dialect":"jsx"|"html","source":"<the authored page text, inline>"}, "delivery"?:{"placement":"inline"|"panel"}, "source"?:{"sessionName"?,"askedBy"?,"emittedAt"?,"profileName"?,"nodeId"?}, "creator_cwd"?:"<absolute dir>", "action"?:{"name":"<declared action>","payload":<any JSON, null when omitted>}}. The page text is inline, never a path — the request must stay readable after the creating process is gone. creator_cwd defaults to this directory and is the scope the action name resolves from. delivery.inbox and delivery.reply are pinned: a programmatic request is always answerable from the inbox and never routes to an agent bridge. Unknown fields are rejected.',
105
+ },
106
+ ],
107
+ output: [
108
+ { name: 'request_id', type: 'string', required: true, constraint: 'The created request — pass it to get/replace/respond/cancel. Stable, and the deduplication key every completion destination keys on.' },
109
+ { name: 'state', type: 'string', required: true, constraint: 'Always "pending": creation never settles.' },
110
+ { name: 'action', type: 'object', required: false, constraint: '{name} of the frozen action binding. Absent when the request carries no action.' },
111
+ { name: 'delivery_state', type: 'string', required: true, constraint: 'Always "none" at creation: delivery is enqueued at settlement, not before.' },
112
+ ],
113
+ outputKind: 'object',
114
+ effects: [
115
+ 'Publishes one durable page ticket into the human inbox. It has no reply bridge and outlives this process.',
116
+ 'An action name is resolved from the humanActions map in scope config (project ancestors, then user) BEFORE anything is written — an unknown or unusable name is rejected and leaves no inbox row for a person to answer.',
117
+ 'A resolved action is frozen onto the ticket: name, payload, resolved argv, and cwd. replace can never change it; a different effect needs a cancel and a new request.',
118
+ ],
119
+ },
120
+ run: async (input) => {
121
+ const path = input['requestFile'];
122
+ const body = readJsonFile(path, 'request-file', 'the create object');
123
+ if (body['creator_cwd'] === undefined)
124
+ body['creator_cwd'] = process.cwd();
125
+ try {
126
+ const created = await cliClient().createHumanRequest(body);
127
+ return {
128
+ request_id: created.request_id,
129
+ state: created.state,
130
+ ...(created.action === undefined ? {} : { action: created.action }),
131
+ delivery_state: created.delivery_state,
132
+ };
133
+ }
134
+ catch (error) {
135
+ rethrowAsCliError(error);
136
+ }
137
+ },
138
+ });
139
+ // ---------------------------------------------------------------------------
140
+ // get
141
+ // ---------------------------------------------------------------------------
142
+ const getLeaf = defineLeaf({
143
+ name: 'get',
144
+ description: 'read one request, its terminal result, and its delivery state',
145
+ whenToUse: 'you need the current state of a request you created — including the answers, once someone has settled it.',
146
+ help: {
147
+ name: 'human request get',
148
+ summary: 'read one durable request',
149
+ params: [{ kind: 'positional', name: 'request_id', type: 'string', required: true, constraint: 'request_id returned by `human request create`.' }],
150
+ output: [...RECORD_OUTPUT],
151
+ outputKind: 'object',
152
+ effects: ['None. Read-only.'],
153
+ },
154
+ run: async (input) => {
155
+ try {
156
+ return requestResult(await cliClient().getHumanRequest(requestId(input)));
157
+ }
158
+ catch (error) {
159
+ rethrowAsCliError(error);
160
+ }
161
+ },
162
+ });
163
+ // ---------------------------------------------------------------------------
164
+ // replace
165
+ // ---------------------------------------------------------------------------
166
+ const replaceLeaf = defineLeaf({
167
+ name: 'replace',
168
+ description: 'revise a pending request\'s page in place',
169
+ whenToUse: 'what you are asking changed while the request is still pending, and the same request should keep its identity and its frozen action.',
170
+ help: {
171
+ name: 'human request replace',
172
+ summary: 'republish a pending request\'s page',
173
+ params: [
174
+ { kind: 'positional', name: 'request_id', type: 'string', required: true, constraint: 'request_id returned by `human request create`.' },
175
+ { kind: 'flag', name: 'page', type: 'path', required: true, constraint: 'The revised page: a .tsx module or a complete .html/.htm document. Read here and sent inline.' },
176
+ ],
177
+ output: [...RECORD_OUTPUT],
178
+ outputKind: 'object',
179
+ effects: [
180
+ 'Rewrites the page and its typed response contract in place; open surfaces reload it without a second request.',
181
+ 'Identity is untouched: request id, provenance, emitted time, delivery, and the frozen action binding all survive verbatim.',
182
+ 'Refused with already_settled once the request has a terminal result — a settled request is revised by cancelling and creating a new one.',
183
+ ],
184
+ },
185
+ run: async (input) => {
186
+ const id = requestId(input);
187
+ const body = { page: readPageFile(input['page']) };
188
+ try {
189
+ return requestResult(await cliClient().replaceHumanRequest(id, body));
190
+ }
191
+ catch (error) {
192
+ rethrowAsCliError(error);
193
+ }
194
+ },
195
+ });
196
+ // ---------------------------------------------------------------------------
197
+ // respond
198
+ // ---------------------------------------------------------------------------
199
+ const respondLeaf = defineLeaf({
200
+ name: 'respond',
201
+ description: 'settle a pending request with typed answers',
202
+ whenToUse: 'an authorized host is submitting the answers on the person\'s behalf, rather than the person answering in their inbox.',
203
+ help: {
204
+ name: 'human request respond',
205
+ summary: 'answer a pending request',
206
+ params: [
207
+ { kind: 'positional', name: 'request_id', type: 'string', required: true, constraint: 'request_id returned by `human request create`.' },
208
+ {
209
+ kind: 'flag',
210
+ name: 'response-file',
211
+ type: 'path',
212
+ required: true,
213
+ constraint: 'JSON file holding the respond object: {"responses":{"<component_id>":{...}}, "actor"?:"<who answered>"}. One typed response per response-bearing component; the daemon validates the complete map against the currently published page.',
214
+ },
215
+ ],
216
+ output: [...RECORD_OUTPUT],
217
+ outputKind: 'object',
218
+ effects: [
219
+ 'Settles the request as answered and drops it from the human inbox.',
220
+ 'Competes with the person\'s own answer, a recipient dismissal, and a requester cancel through one first-writer-wins store: a losing attempt returns already_settled and changes nothing.',
221
+ 'When an action is bound, the winning settlement enqueues one at-least-once completion delivery keyed on the request id.',
222
+ ],
223
+ },
224
+ run: async (input) => {
225
+ const id = requestId(input);
226
+ const body = readJsonFile(input['responseFile'], 'response-file', 'the respond object');
227
+ try {
228
+ return requestResult(await cliClient().respondHumanRequest(id, body));
229
+ }
230
+ catch (error) {
231
+ rethrowAsCliError(error);
232
+ }
233
+ },
234
+ });
235
+ // ---------------------------------------------------------------------------
236
+ // cancel
237
+ // ---------------------------------------------------------------------------
238
+ const cancelLeaf = defineLeaf({
239
+ name: 'cancel',
240
+ description: 'withdraw a pending request',
241
+ whenToUse: 'the decision you asked for stopped mattering, or the effect must change — the action binding is immutable, so a new effect needs a new request.',
242
+ help: {
243
+ name: 'human request cancel',
244
+ summary: 'withdraw a pending request',
245
+ params: [
246
+ { kind: 'positional', name: 'request_id', type: 'string', required: true, constraint: 'request_id returned by `human request create`.' },
247
+ { kind: 'flag', name: 'reason', type: 'string', required: false, constraint: 'Short note recorded on the terminal result and carried in the completion document.' },
248
+ ],
249
+ output: [...RECORD_OUTPUT],
250
+ outputKind: 'object',
251
+ effects: [
252
+ 'Settles the request as canceled and drops it from the human inbox — the person is no longer asked.',
253
+ 'Races the person\'s answer through the same first-writer-wins store; whoever lands first is authoritative and the loser returns already_settled.',
254
+ 'When an action is bound, the winning settlement enqueues one completion delivery carrying the canceled event.',
255
+ ],
256
+ },
257
+ run: async (input) => {
258
+ const id = requestId(input);
259
+ const reason = typeof input['reason'] === 'string' && input['reason'] !== '' ? input['reason'] : undefined;
260
+ try {
261
+ return requestResult(await cliClient().cancelHumanRequest(id, reason === undefined ? {} : { reason }));
262
+ }
263
+ catch (error) {
264
+ rethrowAsCliError(error);
265
+ }
266
+ },
267
+ });
268
+ // ---------------------------------------------------------------------------
269
+ // Registration
270
+ // ---------------------------------------------------------------------------
271
+ export const humanRequestBranch = defineBranch({
272
+ name: 'request',
273
+ description: 'durable requests that outlive the process that made them',
274
+ whenToUse: 'a script or backend needs a human decision whose outcome must survive its own exit, instead of an answer pushed back to a live node.',
275
+ help: {
276
+ name: 'human request',
277
+ summary: 'durable programmatic human requests — create, read, revise, and settle',
278
+ model: 'A request is the same page ticket `human send` publishes, minus the agent bridge: nothing waits on it, and the outcome is read with `get` or carried to a local command by a named action. Reach for it when the caller will be gone before the person answers; when a live node should receive the answer, use `crtr human send` instead.\n\nThe page and its typed response contract stay revisable with `replace` while pending. The action binding does not: name, payload, resolved argv, and cwd are frozen at creation, so a different effect means `cancel` plus a new request. An action is a name declared in the humanActions map of scope config — there is no command, shell string, or callback URL anywhere in this surface.\n\nA request ends exactly once. `respond` (an authorized host answering), the person answering in their own inbox, a recipient dismissal, and `cancel` all compete through one first-writer-wins settlement; the loser gets already_settled and no second delivery. Only the winner enqueues the completion document, delivered at least once — the receiving command must deduplicate on the request id.',
279
+ },
280
+ children: [createLeaf, getLeaf, replaceLeaf, respondLeaf, cancelLeaf],
281
+ });
@@ -9,6 +9,7 @@ import { humanList, humanResolve, humanCancel } from './human/queue.js';
9
9
  import { humanReviewBranch } from './human/review.js';
10
10
  import { humanFeedbackBranch } from './human/feedback.js';
11
11
  import { humanComponents } from './human/components.js';
12
+ import { humanRequestBranch } from './human/request.js';
12
13
  import { pageHelpText } from './human/shared.js';
13
14
  export function registerHuman() {
14
15
  // `page_surface` marks a host whose human surface is a rendered page product
@@ -21,9 +22,10 @@ export function registerHuman() {
21
22
  const concept = pageSurface
22
23
  ? 'human-in-the-loop decisions and structured pages'
23
24
  : 'human-in-the-loop decisions, document review, and live display';
25
+ const durableRequests = '`request` publishes the same page with no bridge at all, for a caller that will have exited before the answer arrives: its outcome is read back or carried to a named local action.';
24
26
  const ticketModel = pageSurface
25
- ? 'Tickets queue in the human inbox; nothing opens on screen. `send` routes completion back when the page carries response-bearing components, and publishes a standalone announcement when it does not.'
26
- : 'Tickets queue in the human inbox; nothing opens on screen. `send` routes completion back when the page carries response-bearing components, and publishes a standalone announcement when it does not. `review` is for live document review with anchored comments; `show` is a passive tmux live-watch rather than a ticket.';
27
+ ? `Tickets queue in the human inbox; nothing opens on screen. \`send\` routes completion back when the page carries response-bearing components, and publishes a standalone announcement when it does not. ${durableRequests}`
28
+ : `Tickets queue in the human inbox; nothing opens on screen. \`send\` routes completion back when the page carries response-bearing components, and publishes a standalone announcement when it does not. ${durableRequests} \`review\` is for live document review with anchored comments; \`show\` is a passive tmux live-watch rather than a ticket.`;
27
29
  return defineBranch({
28
30
  name: 'human',
29
31
  rootEntry: {
@@ -48,6 +50,7 @@ export function registerHuman() {
48
50
  ...(pageSurface ? [] : [humanReviewBranch]),
49
51
  humanFeedbackBranch,
50
52
  ...(pageSurface ? [] : [humanShow]),
53
+ humanRequestBranch,
51
54
  humanCancel,
52
55
  humanList,
53
56
  humanResolve,
@@ -181,7 +181,7 @@ const configSet = defineLeaf({
181
181
  name: 'sys config set',
182
182
  summary: 'write a config value by dotted key',
183
183
  params: [
184
- { kind: 'positional', name: 'key', type: 'string', required: true, constraint: `Dotted key path. User-scope scalar settings: ${SCALAR_SETTING_HELP}. Also supported: working_gerunds and whip_messages (non-empty JSON string arrays), brokerThresholds.warning and brokerThresholds.automaticReviveCap (user scope; integer >= 1), modelLadders.defaultProvider, and modelLadders.<anthropic|openai>.<ultra|strong|medium|light>. Keybindings are edited only through sys settings.` },
184
+ { kind: 'positional', name: 'key', type: 'string', required: true, constraint: `Dotted key path. User-scope scalar settings: ${SCALAR_SETTING_HELP}. Also supported: working_gerunds and whip_messages (non-empty JSON string arrays), brokerThresholds.warning and brokerThresholds.automaticReviveCap (user scope; integer >= 1), modelLadders.defaultProvider, and modelLadders.<anthropic|openai>.<ultra|strong|medium|light>. Keybindings are edited only through sys settings. humanActions is an object map edited directly in ~/.crouter/config.json or <repo>/.crouter/config.json.` },
185
185
  { kind: 'flag', name: 'value', type: 'string', required: true, constraint: 'value VALUE — string, required. working_gerunds and whip_messages accept JSON arrays; other values are stored as-is if quoted and coerced to number or boolean when unambiguous.' },
186
186
  { kind: 'flag', name: 'scope', type: 'enum', choices: ['user', 'project'], required: false, constraint: 'Scope to write to. Default: user. Project scope is supported only for modelLadders.' },
187
187
  ],
@@ -261,7 +261,7 @@ export const configBranch = defineBranch({
261
261
  whenToUse: 'inspecting crtr settings, changing supported scalar values, or locating config.json. Keybinding changes belong in sys settings.',
262
262
  help: {
263
263
  name: 'sys config',
264
- summary: 'read and write crtr configuration, including model ladders',
264
+ summary: 'read and write crtr configuration, including model ladders; edit humanActions maps directly in ~/.crouter/config.json or <repo>/.crouter/config.json',
265
265
  },
266
266
  children: [configGet, configSet, configPath],
267
267
  });
@@ -15,10 +15,12 @@ import { detectPackageManager } from './setup-core.js';
15
15
  import { validateEffectiveCommandPlugins } from '../../core/command-plugins/discovery.js';
16
16
  import { discoverHookRegistry } from '../../core/command-hooks/discovery.js';
17
17
  import { resolveBinContributions } from '../../core/runtime/bin-contributions.js';
18
+ import { inspectHumanActions } from '../../core/human-actions.js';
18
19
  import { buildBrokerEnv, resolvePathExecutable } from '../../core/runtime/spawn-env.js';
19
20
  import { listAllPlugins } from '../../core/resolver.js';
20
21
  import { SUBTREE_NAMES, coreCommandPaths, coreHookCatalog } from '../../build-root.js';
21
22
  import { processGeneration, processLocatedGeneration, runtimeManifest, selectedGeneration } from './shared.js';
23
+ import { CONFIG_FILE } from '../../types.js';
22
24
  function pass(scope, name, message) {
23
25
  return { scope, name, status: 'pass', message };
24
26
  }
@@ -198,6 +200,55 @@ function runBinContributionChecks(scopes) {
198
200
  }
199
201
  return results;
200
202
  }
203
+ /** Validate every scope-configured completion action without executing it. */
204
+ function runHumanActionChecks(scopes) {
205
+ const inScope = new Set(scopes);
206
+ const userConfig = join(scopeRoot('user'), CONFIG_FILE);
207
+ const results = [];
208
+ const winningOrigins = new Map();
209
+ for (const action of inspectHumanActions(process.cwd())) {
210
+ if ('kind' in action) {
211
+ if (action.kind === 'unknown_action')
212
+ continue;
213
+ const scope = action.configOrigin === userConfig ? 'user' : 'project';
214
+ const block = action.block === true;
215
+ const winningOrigin = block ? undefined : winningOrigins.get(action.name);
216
+ if (!block && winningOrigin === undefined)
217
+ winningOrigins.set(action.name, action.configOrigin);
218
+ if (!inScope.has(scope))
219
+ continue;
220
+ const checkName = block ? `humanActions:block@${action.configOrigin}` : `humanActions:${action.name}@${action.configOrigin}`;
221
+ const remediation = {
222
+ kind: 'human_action',
223
+ description: block
224
+ ? `Fix or remove the \`humanActions\` block in ${action.configOrigin}. Actions run argv directly without a shell.`
225
+ : `Fix or remove the \`humanActions.${action.name}\` declaration in ${action.configOrigin}. Actions run argv directly without a shell.`,
226
+ };
227
+ if (winningOrigin !== undefined) {
228
+ results.push({
229
+ scope,
230
+ name: checkName,
231
+ status: 'pass',
232
+ message: `warning: shadowed by ${winningOrigin}; ${action.configOrigin}: ${action.reason}`,
233
+ remediation,
234
+ });
235
+ }
236
+ else {
237
+ results.push(failCheck(scope, checkName, `${action.configOrigin}: ${action.reason}`, remediation));
238
+ }
239
+ continue;
240
+ }
241
+ const scope = action.configOrigin === userConfig ? 'user' : 'project';
242
+ const winningOrigin = winningOrigins.get(action.name);
243
+ if (winningOrigin === undefined)
244
+ winningOrigins.set(action.name, action.configOrigin);
245
+ if (!inScope.has(scope))
246
+ continue;
247
+ const shadowedPrefix = winningOrigin === undefined ? '' : `shadowed by ${winningOrigin}; `;
248
+ results.push(pass(scope, `humanActions:${action.name}@${action.configOrigin}`, `${shadowedPrefix}${action.configOrigin} → ${action.argv[0]} (cwd ${action.cwd})`));
249
+ }
250
+ return results;
251
+ }
201
252
  /** Check each enabled plugin's advisory PATH requirements against the exact
202
253
  * broker environment a node launched from this cwd/profile receives. */
203
254
  function runRequiresChecks(scopes) {
@@ -506,12 +557,12 @@ export const sysDoctorLeaf = defineLeaf({
506
557
  { kind: 'flag', name: 'remote', type: 'bool', required: false, constraint: 'Check git remotes with ls-remote (slow — makes network calls).' },
507
558
  ],
508
559
  output: [
509
- { name: 'checks', type: 'object[]', required: true, constraint: 'Each: {scope, name, status, message, fixed?, remediation?}. status: pass | fail. scope may be user | project | canvas. bin:<name> checks report bare-binary contributions (a `bin` block in a plugin manifest or a scope config.json): a pass names the contributor and the resolved target, a fail names an unsafe/reserved command name, malformed target declaration, missing/non-executable/escaping target, or same-precedence name collision that installed nothing; their remediation is always a human_action. requires:<name> checks report each enabled plugin manifest PATH requirement: a pass names the plugin and resolved executable path; a fail names the plugin and carries its declared install hint as remediation. Runtime checks validate selected and process generation manifests, sealing/containment, and full SHA-256 inventories. terminal:nerd-font (user scope) reports whether a Nerd Font is installed for the viewer\'s icon glyphs; its remediation is always a human_action carrying the platform install command, never auto-fixed. Plugin checks appear as plugin:<name>:commands and plugin:<name>:hooks; both are validated statically and never execute plugin code. Hook failures identify manifest/path/target/collision problems and carry disable/update/remove/show remediation; healthy hooks list effective target, phase, and op. remediation (when present) is {kind, description, ...payload} where kind is remove_config_key | rm_path | human_action; fault human_action remediations include the canonical logs command. Sorted by scope then name.' },
560
+ { name: 'checks', type: 'object[]', required: true, constraint: 'Each: {scope, name, status, message, fixed?, remediation?}. status: pass | fail. scope may be user | project | canvas. bin:<name> checks report bare-binary contributions (a `bin` block in a plugin manifest or a scope config.json): a pass names the contributor and the resolved target, a fail names an unsafe/reserved command name, malformed target declaration, missing/non-executable/escaping target, or same-precedence name collision that installed nothing; their remediation is always a human_action. humanActions:<name>@<config-origin> checks validate each user/project scope completion-action declaration: action-name and argv shape, cwd directory, argv[0] regular-file existence, and execute permission; they never execute an action. A malformed effective declaration fails; a malformed shadowed declaration is a pass-level warning that names the winning and shadowed origins. requires:<name> checks report each enabled plugin manifest PATH requirement: a pass names the plugin and resolved executable path; a fail names the plugin and carries its declared install hint as remediation. Runtime checks validate selected and process generation manifests, sealing/containment, and full SHA-256 inventories. terminal:nerd-font (user scope) reports whether a Nerd Font is installed for the viewer\'s icon glyphs; its remediation is always a human_action carrying the platform install command, never auto-fixed. Plugin checks appear as plugin:<name>:commands and plugin:<name>:hooks; both are validated statically and never execute plugin code. Hook failures identify manifest/path/target/collision problems and carry disable/update/remove/show remediation; healthy hooks list effective target, phase, and op. remediation (when present) is {kind, description, ...payload} where kind is remove_config_key | rm_path | human_action; fault human_action remediations include the canonical logs command. Sorted by scope then name.' },
510
561
  { name: 'ok', type: 'boolean', required: true, constraint: 'True when no unresolved fail checks remain.' },
511
562
  ],
512
563
  outputKind: 'object',
513
564
  effects: [
514
- 'Read-only unless --fix is passed. Runtime verification reads and hashes every selected/process generation file; plugin command and hook manifests, bare-binary (`bin`) declarations, and advisory `requires` PATH checks never execute plugin or contributed binaries.',
565
+ 'Read-only unless --fix is passed. Runtime verification reads and hashes every selected/process generation file; plugin command and hook manifests, bare-binary (`bin`) declarations, humanActions declarations, and advisory `requires` PATH checks never execute plugin or contributed binaries.',
515
566
  'With --fix: applies each non-pass check\'s `remediation` — removes stale config entries and deletes dangling plugin/marketplace directories; canvas fault findings and plugin command/hook findings stay read-only (--fix never chmods or rewrites third-party plugin content).',
516
567
  'Each non-pass result carries a structured `remediation` describing the fix action (absolute paths, exact config keys, or a human_action with its command) so callers can apply it directly without --fix.',
517
568
  ],
@@ -531,6 +582,7 @@ export const sysDoctorLeaf = defineLeaf({
531
582
  allResults.push(...await runCommandPluginChecks(scopes));
532
583
  allResults.push(...await runHookPluginChecks(scopes));
533
584
  allResults.push(...runBinContributionChecks(scopes));
585
+ allResults.push(...runHumanActionChecks(scopes));
534
586
  allResults.push(...runRequiresChecks(scopes));
535
587
  allResults.push(...await runFaultChecks());
536
588
  const processLocation = processGeneration();
@@ -41,10 +41,13 @@ function dbReach(root) {
41
41
  }
42
42
  return null;
43
43
  }
44
- test('every shipped broker extension is transitively canvas.db-free', () => {
45
- for (const name of CANVAS_EXTENSION_NAMES) {
46
- const root = join(SOURCE_ROOT, 'pi-extensions', `${name}.ts`);
44
+ test('every shipped broker extension and the prospective preflight are transitively canvas.db-free', () => {
45
+ const roots = [
46
+ ...CANVAS_EXTENSION_NAMES.map((name) => join(SOURCE_ROOT, 'pi-extensions', `${name}.ts`)),
47
+ join(SOURCE_ROOT, 'core/runtime/prospective-inventory-cli.ts'),
48
+ ];
49
+ for (const root of roots) {
47
50
  const reach = dbReach(root);
48
- assert.equal(reach, null, `${name} reaches canvas.db through:\n${reach?.join('\n')}`);
51
+ assert.equal(reach, null, `${root} reaches canvas.db through:\n${reach?.join('\n')}`);
49
52
  }
50
53
  });
@@ -0,0 +1,71 @@
1
+ import { existsSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { DefaultResourceLoader, ExtensionRunner, } from '@earendil-works/pi-coding-agent';
4
+ import { buildRefInventory } from '../../memory/inline-ref-inventory.js';
5
+ import { gatewayCommandRows, gatewayMemoryRows } from '../../runtime/chat-inventory-rows.js';
6
+ import { captureChatCapabilities, registrationChatSurface } from '../../runtime/command-surface.js';
7
+ import { runProspectiveInventory } from '../../runtime/prospective-inventory.js';
8
+ async function main() {
9
+ const extensionPath = process.argv[2];
10
+ const invocations = JSON.parse(process.argv[3] ?? '[]');
11
+ if (extensionPath === undefined)
12
+ throw new Error('extension path is required');
13
+ const cwd = process.cwd();
14
+ const home = process.env['CRTR_HOME'];
15
+ if (home === undefined || home === '')
16
+ throw new Error('CRTR_HOME is required');
17
+ const stateBeforeProspective = existsSync(home);
18
+ const prospective = await runProspectiveInventory({ cwd, profileId: null, extensions: [extensionPath] });
19
+ const stateAfterProspective = existsSync(home);
20
+ const loader = new DefaultResourceLoader({
21
+ cwd,
22
+ agentDir: join(cwd, '.pi'),
23
+ additionalExtensionPaths: [extensionPath],
24
+ noContextFiles: true,
25
+ });
26
+ await loader.reload();
27
+ const loaded = loader.getExtensions();
28
+ if (loaded.errors.length > 0)
29
+ throw new Error(JSON.stringify(loaded.errors));
30
+ const sent = [];
31
+ let activeName = '';
32
+ loaded.runtime.sendMessage = (message, options) => sent.push({ name: activeName, message, options });
33
+ const runner = new ExtensionRunner(loaded.extensions, loaded.runtime, cwd, undefined, undefined);
34
+ const registered = runner.getRegisteredCommands();
35
+ captureChatCapabilities({ commands: registered, templates: [] });
36
+ const commands = gatewayCommandRows(registered.map((command) => {
37
+ const expansion = command.expansion;
38
+ return {
39
+ name: command.invocationName,
40
+ description: command.description ?? '',
41
+ source: 'command',
42
+ ...(expansion === undefined ? {} : { expansion }),
43
+ ...registrationChatSurface(command),
44
+ };
45
+ }));
46
+ const memoryRefs = gatewayMemoryRows(buildRefInventory().refs);
47
+ const notifications = [];
48
+ for (const invocation of invocations) {
49
+ const command = runner.getCommand(invocation.name);
50
+ if (command === undefined)
51
+ throw new Error(`command not registered: ${invocation.name}`);
52
+ activeName = invocation.name;
53
+ await command.handler(invocation.args, {
54
+ cwd,
55
+ ui: { notify: (...args) => notifications.push(args) },
56
+ });
57
+ }
58
+ writeFileSync(3, JSON.stringify({
59
+ prospective,
60
+ stateBeforeProspective,
61
+ stateAfterProspective,
62
+ commands,
63
+ memoryRefs,
64
+ sent,
65
+ notifications,
66
+ }));
67
+ }
68
+ main().catch((error) => {
69
+ process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
70
+ process.exitCode = 1;
71
+ });