@niwa-labs/sessions 0.0.0-stage → 0.0.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 +21 -0
- package/README.md +17 -2
- package/package.json +46 -4
- package/src/actions.ts +350 -0
- package/src/ask.ts +230 -0
- package/src/box.ts +87 -0
- package/src/caps.ts +149 -0
- package/src/catalog.ts +146 -0
- package/src/cockpit/actions.ts +52 -0
- package/src/cockpit/index.tsx +36 -0
- package/src/cockpit/pages.tsx +190 -0
- package/src/cockpit/transcript.ts +64 -0
- package/src/confirm.ts +228 -0
- package/src/discover.ts +107 -0
- package/src/identity.ts +64 -0
- package/src/index.ts +1874 -0
- package/src/insert-plugin.ts +263 -0
- package/src/insert-routing.ts +84 -0
- package/src/life.ts +59 -0
- package/src/prompt.ts +50 -0
- package/src/records-entry.ts +91 -0
- package/src/records.ts +395 -0
- package/src/refusal.ts +13 -0
- package/src/reverse.ts +260 -0
- package/src/support.ts +93 -0
- package/src/visible.ts +28 -0
- package/test/access-self-answer.test.ts +197 -0
- package/test/box-socket.test.ts +132 -0
- package/test/cockpit-actions.test.ts +19 -0
- package/test/cockpit-transcript.test.ts +71 -0
- package/test/fixtures/restart-host.ts +175 -0
- package/test/grant-box.test.ts +102 -0
- package/test/insert-permission.test.ts +285 -0
- package/test/restart.test.ts +168 -0
- package/test/sessions-reverse.test.ts +341 -0
- package/test/sessions.test.ts +658 -0
- package/tsconfig.json +15 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Niwa Labs contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @niwa-labs/sessions
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Session control: start, resume, ask, send, interrupt, reverse requests, the catalog and the list of harnesses, and the registration of harness actions (discovery, confirmation, support, insert reports and permission questions).
|
|
4
|
+
|
|
5
|
+
The root entry holds the plugins and their factories; `@niwa-labs/sessions/records` holds the records, the typed action references and the pure helpers that other plugins may import.
|
|
6
|
+
|
|
7
|
+
## The box of a session
|
|
8
|
+
|
|
9
|
+
Every session niwa starts runs in a box of the host's sandbox (`sessions({ sandbox: sandbox({ adapter, profiles }) })`,
|
|
10
|
+
srt by default). The box is the host's default (`box`, by default `{ allow: ["project", "toolchains"] }`), what the
|
|
11
|
+
start asks for (`session.start { box: { allow } }` adds to it, `{ only }` replaces it), and always the profile of the
|
|
12
|
+
installation the session runs on, a temp directory of its own (`TMPDIR`) and the host's socket. The places of every
|
|
13
|
+
other installation, of every profile it did not take, the user's keys and niwa's own journal and secrets are closed
|
|
14
|
+
to it. A start that names no working directory is not given the host's directory to write. What a start asks beyond
|
|
15
|
+
the default is held to the caller's `box.use@<profile>`, `box.read@<path>`, `box.write@<path>` and `box.net@<host>`
|
|
16
|
+
rules; a refused box says every reason, and nothing is started. `session.box.manifest` records the box before the
|
|
17
|
+
process starts: the request with where each item came from, the paths and their origins, what was closed and left
|
|
18
|
+
out, the rules taken, the policy the sandbox applies and the names of the environment.
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niwa-labs/sessions",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.ts",
|
|
8
|
+
"./records": "./src/records-entry.ts",
|
|
9
|
+
"./cockpit": "./src/cockpit/index.tsx"
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@niwa-labs/cockpit-sdk": "0.0.0",
|
|
13
|
+
"@niwa-labs/core": "0.0.0",
|
|
14
|
+
"@niwa-labs/git": "0.0.0",
|
|
15
|
+
"@niwa-labs/harness": "0.0.0",
|
|
16
|
+
"@niwa-labs/history": "0.0.0",
|
|
17
|
+
"@niwa-labs/plugin": "0.0.0",
|
|
18
|
+
"@niwa-labs/requests": "0.0.0",
|
|
19
|
+
"@niwa-labs/sandbox": "0.0.0",
|
|
20
|
+
"@niwa-labs/ui-kit": "0.0.0",
|
|
21
|
+
"zod": "^4.6.7"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@happy-dom/global-registrator": "^21.0.4",
|
|
25
|
+
"@niwa-labs/testing": "0.0.0",
|
|
26
|
+
"@tanstack/react-query": "^5.108.2",
|
|
27
|
+
"@types/react": "^19.3.0",
|
|
28
|
+
"@types/react-dom": "^19.3.0",
|
|
29
|
+
"react": "^19.3.1",
|
|
30
|
+
"react-dom": "^19.3.1"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@tanstack/react-query": "^5.108.2",
|
|
34
|
+
"react": "^19.3.1",
|
|
35
|
+
"react-dom": "^19.3.1"
|
|
36
|
+
},
|
|
37
|
+
"peerDependenciesMeta": {
|
|
38
|
+
"@tanstack/react-query": {
|
|
39
|
+
"optional": true
|
|
40
|
+
},
|
|
41
|
+
"react": {
|
|
42
|
+
"optional": true
|
|
43
|
+
},
|
|
44
|
+
"react-dom": {
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/actions.ts
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The actions of the sessions module, as typed references: name, description and the two schemas.
|
|
3
|
+
*
|
|
4
|
+
* A caller imports these to call a session action with input and output checked by the type
|
|
5
|
+
* checker, on the host and on a client. The module's factory builds its real actions from the same
|
|
6
|
+
* references (`action(sessionStart, { recovery, run })`), so the schemas are one value.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
|
|
11
|
+
import { JsonSchemaValue, actionRef, getRef, Address } from "@niwa-labs/core";
|
|
12
|
+
import {
|
|
13
|
+
AssistantRecordSchema,
|
|
14
|
+
CompactionRecordSchema,
|
|
15
|
+
DeliveryReceiptSchema,
|
|
16
|
+
NestedRecordSchema,
|
|
17
|
+
HarnessIdSchema,
|
|
18
|
+
HarnessKindSchema,
|
|
19
|
+
HarnessSidesSchema,
|
|
20
|
+
MachineIdSchema,
|
|
21
|
+
OptionsBlockNameSchema,
|
|
22
|
+
withBlocks,
|
|
23
|
+
SessionModeSchema,
|
|
24
|
+
ThinkingRecordSchema,
|
|
25
|
+
ToolsModeSchema,
|
|
26
|
+
ToolCallRecordSchema,
|
|
27
|
+
ToolResultRecordSchema,
|
|
28
|
+
UnknownRecordSchema,
|
|
29
|
+
UserRecordSchema,
|
|
30
|
+
} from "@niwa-labs/harness";
|
|
31
|
+
import { SessionWorktree, WorktreeOption } from "@niwa-labs/git/records";
|
|
32
|
+
import { BoxAccessSchema } from "@niwa-labs/sandbox";
|
|
33
|
+
import { CoverageSchema, ReadAnswerSchema, SearchMatchSchema, SearchQuerySchema, readInput } from "@niwa-labs/history/records";
|
|
34
|
+
|
|
35
|
+
import { NiwaSessionIdSchema } from "./identity.ts";
|
|
36
|
+
import { PromptInputSchema } from "./prompt.ts";
|
|
37
|
+
import { BelongingSource } from "./records.ts";
|
|
38
|
+
import { VisibleActionsInputSchema } from "./visible.ts";
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The session an action is given: the id niwa gave it (`s-3fa9c2`) or any text that names one, such
|
|
42
|
+
* as the start or the end of the id. A session niwa did not start has no such id: it is named by its
|
|
43
|
+
* pair, `<harness> <native>` or `{ harness, native }`.
|
|
44
|
+
*/
|
|
45
|
+
export const SessionRefInput = z.union([
|
|
46
|
+
z.string().min(1),
|
|
47
|
+
z.object({ harness: z.string().min(1), native: z.string().min(1) }),
|
|
48
|
+
]);
|
|
49
|
+
|
|
50
|
+
/** One session, as the actions report it. */
|
|
51
|
+
export const SessionEntrySchema = z.object({
|
|
52
|
+
/** The id niwa gave the session; absent for a session niwa did not start. */
|
|
53
|
+
id: NiwaSessionIdSchema.optional(),
|
|
54
|
+
/** The pointer: which harness, and which session of it, `<harness> <native>`. */
|
|
55
|
+
ref: z.string().min(1),
|
|
56
|
+
/**
|
|
57
|
+
* A readable title: the harness's own name or summary of the session, else its first message
|
|
58
|
+
* from a person, trimmed to about 60 characters. Absent when neither is known.
|
|
59
|
+
*/
|
|
60
|
+
title: z.string().optional(),
|
|
61
|
+
run: z.string().optional(),
|
|
62
|
+
cwd: z.string().optional(),
|
|
63
|
+
model: z.string().optional(),
|
|
64
|
+
startedAt: z.number().int().nonnegative().optional(),
|
|
65
|
+
lastActivityAt: z.number().int().nonnegative().optional(),
|
|
66
|
+
/** What niwa knows about its state right now. */
|
|
67
|
+
state: z.enum(["running", "idle", "ended", "unknown"]),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
/** Whom a session serves: a record of its own, apart from the session. */
|
|
71
|
+
export const BelongingSchema = z.object({
|
|
72
|
+
session: z.string().min(1),
|
|
73
|
+
to: Address,
|
|
74
|
+
source: BelongingSource,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
/** A harness whose sessions could not be listed: its absence from the list proves nothing. */
|
|
78
|
+
export const UnreadableSchema = z.object({ harness: z.string().min(1), reason: z.string() });
|
|
79
|
+
|
|
80
|
+
/** How many sessions a page of `session.list` holds when no limit is said. */
|
|
81
|
+
export const SESSION_LIST_DEFAULT = 100;
|
|
82
|
+
/** The most sessions one page may hold: a page must stay far below the wire line limit. */
|
|
83
|
+
export const SESSION_LIST_MAX = 500;
|
|
84
|
+
|
|
85
|
+
export const sessionList = actionRef("session.list", {
|
|
86
|
+
description: "Lists the sessions niwa knows about, most recently active first and a page at a time (`nextCursor` gives the next page), each with a readable title when one is known, and whom each serves.",
|
|
87
|
+
input: z.object({
|
|
88
|
+
/** Only sessions of this harness. */
|
|
89
|
+
harness: z.string().min(1).optional(),
|
|
90
|
+
/** Only sessions in this working directory. */
|
|
91
|
+
cwd: z.string().min(1).optional(),
|
|
92
|
+
managedOnly: z.boolean().describe("List only sessions that niwa started, using its own catalog.").optional(),
|
|
93
|
+
limit: z.number().int().positive().max(SESSION_LIST_MAX).describe(`How many sessions one page holds; ${SESSION_LIST_DEFAULT} when not said.`).optional(),
|
|
94
|
+
cursor: z.string().min(1).describe("The `nextCursor` of the previous page: the page that follows it. Keep the other fields the same.").optional(),
|
|
95
|
+
}),
|
|
96
|
+
output: z.object({
|
|
97
|
+
/** One page of the sessions, the most recently active first. */
|
|
98
|
+
sessions: z.array(SessionEntrySchema),
|
|
99
|
+
/** How many sessions match in all, across every page. */
|
|
100
|
+
total: z.number().int().nonnegative(),
|
|
101
|
+
/** Pass as `cursor` to get the next page; absent on the last page. */
|
|
102
|
+
nextCursor: z.string().min(1).optional(),
|
|
103
|
+
/** Says that the page is not the whole list, and how to get the rest; absent on the last page. */
|
|
104
|
+
hint: z.string().optional(),
|
|
105
|
+
/** The attachments of the listed sessions, each with its source. */
|
|
106
|
+
belongings: z.array(BelongingSchema),
|
|
107
|
+
unreadable: z.array(UnreadableSchema),
|
|
108
|
+
}),
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
export const sessionGet = getRef("session.get", {
|
|
112
|
+
kind: "session",
|
|
113
|
+
noun: "session niwa started",
|
|
114
|
+
detail: "It says the harness and the harness's own id of the session, its state, and whom it serves.",
|
|
115
|
+
entity: SessionEntrySchema.extend({
|
|
116
|
+
id: NiwaSessionIdSchema,
|
|
117
|
+
/** Whom the session serves, each with its source. */
|
|
118
|
+
belongings: z.array(BelongingSchema),
|
|
119
|
+
}),
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
export const sessionBelong = actionRef("session.belong", {
|
|
123
|
+
description: "Says whom a session serves: the address it belongs to, with the source of the choice. The same session and the same address are one belonging, however many times it is said.",
|
|
124
|
+
input: z.object({
|
|
125
|
+
/** The session that serves this address. */
|
|
126
|
+
session: SessionRefInput,
|
|
127
|
+
/** Whom the session serves. */
|
|
128
|
+
to: Address,
|
|
129
|
+
/** Where the attachment came from. */
|
|
130
|
+
source: z.literal("explicit"),
|
|
131
|
+
}),
|
|
132
|
+
output: z.object({
|
|
133
|
+
session: z.string().min(1),
|
|
134
|
+
to: Address,
|
|
135
|
+
source: z.literal("explicit"),
|
|
136
|
+
/** True when the belonging was already written and nothing new was said. */
|
|
137
|
+
known: z.boolean(),
|
|
138
|
+
}),
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
export const sessionRead = actionRef("session.read", {
|
|
142
|
+
description: "Reads the transcript of a session through the harness's reading side. The transcript is never written into niwa's journal.",
|
|
143
|
+
/** The session to read, and what to read of it: see `history.read`, which takes the same. */
|
|
144
|
+
input: readInput(SessionRefInput),
|
|
145
|
+
output: ReadAnswerSchema,
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
export const sessionSearch = actionRef("session.search", {
|
|
149
|
+
description: "Searches the transcript of a session through the harness's reading side: the records that hold every word of the query, case aside, each with its index and a short snippet. The index is the one session records are counted by from the start, as agent.fetch-from-old fetches them.",
|
|
150
|
+
input: SearchQuerySchema.extend({
|
|
151
|
+
/** The session to search. */
|
|
152
|
+
session: SessionRefInput,
|
|
153
|
+
}),
|
|
154
|
+
output: z.object({
|
|
155
|
+
/** The records that matched, in the harness's order. */
|
|
156
|
+
matches: z.array(SearchMatchSchema),
|
|
157
|
+
/** True when there are more matches after these. */
|
|
158
|
+
more: z.boolean(),
|
|
159
|
+
/** How much of the session was actually read: a failed read is not "no matches". */
|
|
160
|
+
coverage: CoverageSchema,
|
|
161
|
+
}),
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
export const sessionRunning = actionRef("session.running", {
|
|
165
|
+
description:
|
|
166
|
+
"What is running now, one line each: the sessions niwa runs, the latest first. A session whose state cannot be known is reported as unknown, never as idle. With all, the sessions found on the machine that niwa does not run are listed too.",
|
|
167
|
+
input: z.object({
|
|
168
|
+
/** Only sessions of this harness. */
|
|
169
|
+
harness: z.string().min(1).optional(),
|
|
170
|
+
/** At most this many lines of each list. Default: 20. */
|
|
171
|
+
limit: z.number().int().positive().optional(),
|
|
172
|
+
/** Add the sessions found on the machine that niwa does not run: their state cannot be known. */
|
|
173
|
+
all: z.boolean().optional(),
|
|
174
|
+
}),
|
|
175
|
+
output: z.object({
|
|
176
|
+
/** `<session> <last activity> <model> <title>`. */
|
|
177
|
+
running: z.array(z.string()),
|
|
178
|
+
/** The sessions whose state cannot be known right now, in the same form. */
|
|
179
|
+
unknown: z.array(z.string()),
|
|
180
|
+
/** How many sessions were left out of the two lists by the limit. */
|
|
181
|
+
omitted: z.number().int().nonnegative(),
|
|
182
|
+
unreadable: z.array(UnreadableSchema),
|
|
183
|
+
}),
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* A harness instance as the sessions module binds it: its name (the id its author gave), its kind, the model it is
|
|
188
|
+
* pinned to, what its sides can do, and the options block a start of it takes. An instance is named by its author, so
|
|
189
|
+
* it is listed and got by that name, as a direction is. Several instances may be of one kind.
|
|
190
|
+
*/
|
|
191
|
+
const HarnessItem = z.object({
|
|
192
|
+
name: HarnessIdSchema,
|
|
193
|
+
kind: HarnessKindSchema,
|
|
194
|
+
/** The model each session of it runs unless the start names another; absent, the harness's own. */
|
|
195
|
+
model: z.string().min(1).optional(),
|
|
196
|
+
/** What each of its sides can do: within what its kind declares, narrowed by what was found on the machine. */
|
|
197
|
+
capabilities: HarnessSidesSchema,
|
|
198
|
+
/** The block a start of this harness may carry; absent, it takes none. */
|
|
199
|
+
block: OptionsBlockNameSchema.optional(),
|
|
200
|
+
/** The schema of the options block used by workflow sessions and `session.start`. */
|
|
201
|
+
options: JsonSchemaValue.optional(),
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
export const harnessList = actionRef("harness.list", {
|
|
205
|
+
description:
|
|
206
|
+
"List the harnesses sessions are started on: the name, the kind, the model it is pinned to, what its sides can do, and the options block of each (`claude` for Claude Code) with its JSON Schema. One kind may have several. Take a name from here to start a session on it, or to get one.",
|
|
207
|
+
input: z.object({}),
|
|
208
|
+
output: z.object({ items: z.array(HarnessItem) }),
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
export const harnessGet = actionRef("harness.get", {
|
|
212
|
+
description:
|
|
213
|
+
"Get one harness by its name: its kind, its machine, the model it is pinned to, what its sides can do, the options block a start of it takes and the JSON Schema of that block. A harness with no block takes no options; the block of another kind is refused by session.start.",
|
|
214
|
+
input: z.object({ name: HarnessIdSchema }),
|
|
215
|
+
output: HarnessItem.extend({
|
|
216
|
+
machine: MachineIdSchema,
|
|
217
|
+
}),
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
/** The fields of `session.start`: every other key of its input is an options block. */
|
|
221
|
+
const SessionStartFields = z.object({
|
|
222
|
+
/** The harness to start the session on. */
|
|
223
|
+
harness: z.string().min(1),
|
|
224
|
+
/** The prompt: plain text becomes one volatile section. */
|
|
225
|
+
prompt: PromptInputSchema,
|
|
226
|
+
/** The model the session runs, for its whole life; the instance's own when absent. */
|
|
227
|
+
model: z.string().min(1).optional(),
|
|
228
|
+
/** The effort the session thinks with, for its whole life; the kind says which levels it takes. */
|
|
229
|
+
effort: z.string().min(1).optional(),
|
|
230
|
+
/** The working mode of the session, for its whole life; the instance's own, else `auto`, when absent. */
|
|
231
|
+
mode: SessionModeSchema.optional(),
|
|
232
|
+
cwd: z.string().min(1).optional(),
|
|
233
|
+
/**
|
|
234
|
+
* Run the session in a new git worktree (the git module's `git.worktree.create`): `true`, or the repository,
|
|
235
|
+
* the base and the description. The repository is `cwd` by default, else the host's directory; the session's
|
|
236
|
+
* cwd is the worktree. It stays until it is removed.
|
|
237
|
+
*/
|
|
238
|
+
worktree: WorktreeOption.optional(),
|
|
239
|
+
/** Which niwa actions the session sees, and which harness tools are off. */
|
|
240
|
+
visible: VisibleActionsInputSchema.optional(),
|
|
241
|
+
/**
|
|
242
|
+
* What the session's box has besides the host's default (`allow`) or instead of it (`only`):
|
|
243
|
+
* `"project"` (the working directory, writable), `"toolchains"`, a profile by its name, or a path
|
|
244
|
+
* (`{ read }`, `{ write }`) or a host (`{ net }`). The profile of the installation is always in it.
|
|
245
|
+
* Wider than the host's default takes the caller's `box.*` rules.
|
|
246
|
+
*/
|
|
247
|
+
box: BoxAccessSchema.optional(),
|
|
248
|
+
/**
|
|
249
|
+
* The tools the session may use, for its whole life: `all` (the harness's own, the default),
|
|
250
|
+
* `niwa-only` (only the tools of niwa's MCP servers), or `{ allow }` (exactly these of the
|
|
251
|
+
* harness's own). A harness that cannot hold a session to it refuses the start.
|
|
252
|
+
*/
|
|
253
|
+
tools: ToolsModeSchema.optional(),
|
|
254
|
+
/**
|
|
255
|
+
* The caller's own id of this start: the prompt is recorded as an input under it with what became of it, and a
|
|
256
|
+
* retry with it answers the session it made instead of making another. Default: the operation of the call.
|
|
257
|
+
*/
|
|
258
|
+
operation: z.string().min(1).max(200).optional(),
|
|
259
|
+
/** How long, in milliseconds, a turn of the session may go with no progress before it counts as stuck; kept in its record. */
|
|
260
|
+
stuckAfter: z.number().int().positive().optional(),
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
/** The names of the fields of `session.start`, so the rest of an input is known as its blocks. */
|
|
264
|
+
export const SESSION_START_FIELDS: readonly string[] = Object.keys(SessionStartFields.shape);
|
|
265
|
+
|
|
266
|
+
export const sessionStart = actionRef("session.start", {
|
|
267
|
+
description:
|
|
268
|
+
"Starts a session. With `worktree` it runs in a new git worktree of the repository (`cwd` by default), which stays until it is removed. It returns as soon as the harness has named the session; until then there is a start in progress, not a session. The prompt becomes the first turn, delivered like a send: the receipt says whether it started or was queued, and the end of that turn is not waited for. Give `operation` to make a retry safe: the same id with the same prompt answers the session it made. The block named after the harness's kind (`claude` for Claude Code) holds the options of that kind for the whole life of the session; the block of another kind is refused.",
|
|
269
|
+
// Every key that is not a field is the options block of the harness's kind, an object named after it: what
|
|
270
|
+
// is in it is the kind's schema to check, so it is checked once the harness is known.
|
|
271
|
+
input: withBlocks(SessionStartFields),
|
|
272
|
+
target: (input) => input.harness,
|
|
273
|
+
output: z.object({
|
|
274
|
+
/** The id niwa gave the session: what every session action takes. */
|
|
275
|
+
session: NiwaSessionIdSchema,
|
|
276
|
+
/** The worktree the session runs in, when it was started in one. */
|
|
277
|
+
worktree: SessionWorktree.optional(),
|
|
278
|
+
/** The harness and the id it gave the session, `<harness> <native>`. */
|
|
279
|
+
ref: z.string().min(1),
|
|
280
|
+
/** What became of the prompt: the first turn started or queued. Absent when there was none. */
|
|
281
|
+
receipt: DeliveryReceiptSchema.optional(),
|
|
282
|
+
/** The operation the prompt is recorded under: the one given, or the call's own. */
|
|
283
|
+
operation: z.string().min(1),
|
|
284
|
+
}),
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
export const sessionResume = actionRef("session.resume", {
|
|
288
|
+
description: "Resumes a session.",
|
|
289
|
+
input: z.object({
|
|
290
|
+
session: SessionRefInput,
|
|
291
|
+
prompt: PromptInputSchema.optional(),
|
|
292
|
+
/** Which niwa actions the session sees, and which harness tools are off. */
|
|
293
|
+
visible: VisibleActionsInputSchema.optional(),
|
|
294
|
+
}),
|
|
295
|
+
output: z.object({ resumed: z.boolean() }),
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
export const sessionSend = actionRef("session.send", {
|
|
299
|
+
description:
|
|
300
|
+
"Sends a message into a session and says what happened to it: delivered into the running turn, queued after the current turn, or started a new turn. A send that fails says whether the message was not sent (sending it again is safe) or may have been (it is never sent again by itself). Give `operation` to make a retry safe: the same id with the same message answers what became of it, and sends it only if it was not sent.",
|
|
301
|
+
input: z.object({
|
|
302
|
+
session: SessionRefInput,
|
|
303
|
+
message: z.string(),
|
|
304
|
+
into: z.literal("turn").optional(),
|
|
305
|
+
/** The caller's own id of this send: a retry with it never sends the message twice. */
|
|
306
|
+
operation: z.string().min(1).max(200).optional(),
|
|
307
|
+
}),
|
|
308
|
+
output: z.object({ receipt: DeliveryReceiptSchema }),
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
export const sessionInterrupt = actionRef("session.interrupt", {
|
|
312
|
+
description: "Interrupts the running turn of a session. It happens only on an explicit request, and only where the harness declares it can.",
|
|
313
|
+
input: z.object({ session: SessionRefInput }),
|
|
314
|
+
output: z.object({ interrupted: z.boolean() }),
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
export const sessionEnd = actionRef("session.end", {
|
|
318
|
+
description:
|
|
319
|
+
"Ends a session: a turn it runs is interrupted where the harness can, its process is let go where the harness holds one, and its end is written with the reason. A session that already ended is left as it is.",
|
|
320
|
+
input: z.object({ session: SessionRefInput, reason: z.string().min(1) }),
|
|
321
|
+
output: z.object({ ended: z.boolean() }),
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
export const sessionAsk = actionRef("session.ask", {
|
|
325
|
+
description: "Asks a session and returns a value that passed a schema. A harness with structured output answers natively; for the others the session is given the question's id and calls `submit-answer`.",
|
|
326
|
+
input: z.object({
|
|
327
|
+
session: SessionRefInput,
|
|
328
|
+
prompt: PromptInputSchema,
|
|
329
|
+
/** The schema the answer must pass, as a JSON schema. */
|
|
330
|
+
schema: JsonSchemaValue,
|
|
331
|
+
}),
|
|
332
|
+
output: z.object({ value: z.unknown() }),
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
/** One open question of a session: the request that waits, and the schema its answer must pass. */
|
|
336
|
+
export const OpenQuestionSchema = z.object({
|
|
337
|
+
/** The id of the request: what `submit-answer` takes as `question`. */
|
|
338
|
+
request: z.string().min(1),
|
|
339
|
+
/** The schema of the answer, as JSON Schema. `{}` when nothing says what it must pass. */
|
|
340
|
+
schema: JsonSchemaValue,
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
export const sessionOpenQuestions = actionRef("session.open-questions", {
|
|
344
|
+
description: "Lists the open questions of the session that a niwa MCP server with this mark serves, each with the schema its answer must pass. An unknown mark has none.",
|
|
345
|
+
input: z.object({
|
|
346
|
+
/** The mark the niwa MCP server was given in NIWA_SESSION_MARK. */
|
|
347
|
+
mark: z.string().min(1),
|
|
348
|
+
}),
|
|
349
|
+
output: z.object({ questions: z.array(OpenQuestionSchema) }),
|
|
350
|
+
});
|
package/src/ask.ts
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Asking a session means: give it a prompt, get back a value that passed a schema.
|
|
3
|
+
*
|
|
4
|
+
* The harness declares which of two ways it has:
|
|
5
|
+
*
|
|
6
|
+
* - it does structured output natively: it is asked and answers with a value;
|
|
7
|
+
* - it does not: niwa asks it through a request. The question niwa asks of a session is
|
|
8
|
+
* a request, the request waits for the answer, and the answer comes back through
|
|
9
|
+
* `submit-answer`. The wait is a request, so it survives a restart.
|
|
10
|
+
*
|
|
11
|
+
* An answer that does not pass the schema is never returned as a value. The request
|
|
12
|
+
* refuses it, and the question stays open for a corrected answer.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { z } from "zod";
|
|
16
|
+
|
|
17
|
+
import { AnswerSchema, FormSchemaSchema, action, answerOfValue, toJsonSchema } from "@niwa-labs/core";
|
|
18
|
+
import type { Action, ActionContext, Answer, JournalReader, Question, Address } from "@niwa-labs/core";
|
|
19
|
+
|
|
20
|
+
import { PromptSchema } from "@niwa-labs/harness";
|
|
21
|
+
import { QuestionName, RequestCreated, RequestId, answeredBy, requestAsk, requestResolve } from "@niwa-labs/requests/records";
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
/** The name of the action a session calls when the harness cannot answer natively. */
|
|
25
|
+
export const SUBMIT_ANSWER_ACTION = "submit-answer";
|
|
26
|
+
|
|
27
|
+
/** The name of the question a session's answer is asked with. */
|
|
28
|
+
export const SESSION_QUESTION = QuestionName.parse("session.answer");
|
|
29
|
+
|
|
30
|
+
/** How a session gives the value of an answer, by the kind of the question. */
|
|
31
|
+
function valueText(question: Question): string {
|
|
32
|
+
switch (question.kind) {
|
|
33
|
+
case "form":
|
|
34
|
+
return "an object for an object, a number as a number, as JSON that passes the schema";
|
|
35
|
+
case "text":
|
|
36
|
+
return "the text";
|
|
37
|
+
case "multi":
|
|
38
|
+
return "the list of the ids of the options you pick";
|
|
39
|
+
case "choice":
|
|
40
|
+
case "confirm":
|
|
41
|
+
case "permission":
|
|
42
|
+
return "the id of the option you pick";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** What the question puts besides its wording: the options, or the schema of the value. */
|
|
47
|
+
function questionBody(question: Question): string[] {
|
|
48
|
+
switch (question.kind) {
|
|
49
|
+
case "form":
|
|
50
|
+
return ["The value must pass this schema:", JSON.stringify(question.schema, null, 2)];
|
|
51
|
+
case "text":
|
|
52
|
+
return [];
|
|
53
|
+
case "choice":
|
|
54
|
+
case "multi":
|
|
55
|
+
case "confirm":
|
|
56
|
+
case "permission":
|
|
57
|
+
return [
|
|
58
|
+
"The options:",
|
|
59
|
+
...question.options.map((option) => `- ${option.id}: ${option.label}${option.description === undefined ? "" : ` (${option.description})`}`),
|
|
60
|
+
];
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The text of a question, as the session that may answer it reads it.
|
|
66
|
+
*
|
|
67
|
+
* The text says what is asked, what the answer must look like — the question carries its own
|
|
68
|
+
* options or schema, so it needs no process that knows it — and how the answer is given back.
|
|
69
|
+
* The id of the request is in it twice: the session needs it to answer, and the answer is bound
|
|
70
|
+
* to it.
|
|
71
|
+
*/
|
|
72
|
+
export function questionText(args: {
|
|
73
|
+
/** The id of the request that waits for the answer. */
|
|
74
|
+
readonly request: string;
|
|
75
|
+
/** The name of the question. */
|
|
76
|
+
readonly question: string;
|
|
77
|
+
/** What was asked. */
|
|
78
|
+
readonly input: Question;
|
|
79
|
+
}): string {
|
|
80
|
+
const lines = [
|
|
81
|
+
"niwa asks you a question.",
|
|
82
|
+
`Question: ${args.question}`,
|
|
83
|
+
`Request id: ${args.request}`,
|
|
84
|
+
"",
|
|
85
|
+
"What is asked:",
|
|
86
|
+
args.input.title,
|
|
87
|
+
];
|
|
88
|
+
if (args.input.detail !== undefined) lines.push(args.input.detail);
|
|
89
|
+
const body = questionBody(args.input);
|
|
90
|
+
if (body.length > 0) lines.push("", ...body);
|
|
91
|
+
lines.push(
|
|
92
|
+
"",
|
|
93
|
+
`Answer with the niwa tool ${SUBMIT_ANSWER_ACTION}, request id ${args.request}`,
|
|
94
|
+
`Call it with question set to the request id above (not to the name of the question) and value set to the answer itself: ${valueText(args.input)}. If your tool can pass the value only as text, pass the JSON of the answer as that text.`,
|
|
95
|
+
);
|
|
96
|
+
return lines.join("\n");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** What was asked of a session, as the session reads it: a prompt is its sections' text. */
|
|
100
|
+
function promptText(prompt: unknown): string {
|
|
101
|
+
const parsed = PromptSchema.safeParse(prompt);
|
|
102
|
+
if (parsed.success) return parsed.data.sections.map((section) => section.text).join("\n");
|
|
103
|
+
return typeof prompt === "string" ? prompt : (JSON.stringify(prompt, null, 2) ?? "");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Ask a session that cannot answer natively.
|
|
108
|
+
*
|
|
109
|
+
* The question niwa asks of a session is a request, addressed to that session: the request
|
|
110
|
+
* waits for the answer, and the wait survives a restart. The answer comes back through
|
|
111
|
+
* `submit-answer`.
|
|
112
|
+
*
|
|
113
|
+
* The question is a form: its value must pass `schema`. The zod schema is held while the ask
|
|
114
|
+
* waits, so an answer that fails a refinement is refused and the question stays open.
|
|
115
|
+
*/
|
|
116
|
+
export async function askNonNative(
|
|
117
|
+
ctx: ActionContext,
|
|
118
|
+
args: {
|
|
119
|
+
/** The session that may answer. */
|
|
120
|
+
readonly to: Address;
|
|
121
|
+
/** What is asked: the prompt of the session. */
|
|
122
|
+
readonly prompt: unknown;
|
|
123
|
+
/** What the value of the answer must pass. */
|
|
124
|
+
readonly schema: z.ZodType<unknown>;
|
|
125
|
+
},
|
|
126
|
+
): Promise<unknown> {
|
|
127
|
+
const { answer } = answeredBy(await ctx.step(requestAsk, {
|
|
128
|
+
to: args.to,
|
|
129
|
+
question: SESSION_QUESTION,
|
|
130
|
+
input: {
|
|
131
|
+
kind: "form",
|
|
132
|
+
title: "Answer the prompt",
|
|
133
|
+
detail: promptText(args.prompt),
|
|
134
|
+
schema: FormSchemaSchema.parse(toJsonSchema(args.schema, "input")),
|
|
135
|
+
},
|
|
136
|
+
check: args.schema,
|
|
137
|
+
}));
|
|
138
|
+
if (!("form" in answer)) throw new Error("the session answered a form with something else");
|
|
139
|
+
return answer.form;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The request with this exact id, with its question, as the journal holds it.
|
|
144
|
+
*
|
|
145
|
+
* Only the exact id the session was given names a request: a short text would have to be matched
|
|
146
|
+
* against the requests of everyone, and a refusal that lists the candidates would show a session
|
|
147
|
+
* the requests of others.
|
|
148
|
+
*/
|
|
149
|
+
function requestNamed(journal: JournalReader | undefined, id: string): { id: RequestId; input: Question } | undefined {
|
|
150
|
+
for (const stored of journal?.find({ type: RequestCreated.name, field: "id", equals: id }) ?? []) {
|
|
151
|
+
const parsed = RequestCreated.schema.safeParse(stored.data);
|
|
152
|
+
if (parsed.success) return { id: parsed.data.id, input: parsed.data.input };
|
|
153
|
+
}
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The action a session calls to answer a question.
|
|
159
|
+
*
|
|
160
|
+
* The question niwa asked of a session is a request: the id the session was given is the id
|
|
161
|
+
* of that request, and the answer is given to the request by name.
|
|
162
|
+
*/
|
|
163
|
+
export function submitAnswerAction(journal: () => JournalReader | undefined): Action<{ question: string; value: unknown }, { accepted: boolean }> {
|
|
164
|
+
return action(SUBMIT_ANSWER_ACTION, {
|
|
165
|
+
description:
|
|
166
|
+
"Answers the question niwa asked of a session. `value` is the answer as a plain value of the question: the object that passes its schema for a form, the id of the option picked for a choice, the list of ids for a multi, the text for a text; a tool layer that can only pass text may pass that JSON as text, and it is read as JSON when the value as given does not pass.",
|
|
167
|
+
input: z.object({
|
|
168
|
+
/** The id of the request the question is, as it was given with the question: not its name. */
|
|
169
|
+
question: z.string().min(1),
|
|
170
|
+
/** The answer. It must fit the question, as given or read as JSON text. */
|
|
171
|
+
value: z.unknown(),
|
|
172
|
+
}),
|
|
173
|
+
output: z.object({ accepted: z.boolean() }),
|
|
174
|
+
// The answer is written under the id of the operation, and the first answer stands: a
|
|
175
|
+
// call that was cut off may be made again, and the same answer stands.
|
|
176
|
+
recovery: "repeat",
|
|
177
|
+
effect: "record",
|
|
178
|
+
world: "niwa",
|
|
179
|
+
async run(input, ctx) {
|
|
180
|
+
// The value is the answer given as a plain value; the question says which answer it is.
|
|
181
|
+
const named = requestNamed(journal(), input.question);
|
|
182
|
+
if (named === undefined) throw new Error(`the request "${input.question}" does not exist`);
|
|
183
|
+
const id = named.id;
|
|
184
|
+
/** Give a plain value as the answer. A refusal may be tried again as the JSON the value holds, unless it is final. */
|
|
185
|
+
const give = async (value: unknown): Promise<{ accepted: boolean } | { refused: string; final: boolean }> => {
|
|
186
|
+
const answer = AnswerSchema.safeParse(answerOfValue(named.input, value));
|
|
187
|
+
if (!answer.success) {
|
|
188
|
+
return { refused: `the value is not an answer to the question: ${answer.error.message}`, final: false };
|
|
189
|
+
}
|
|
190
|
+
// An answer to a request that was cancelled or expired, or that another answer closed,
|
|
191
|
+
// is not accepted, as the answer of the addressee is not.
|
|
192
|
+
const outcome = await ctx.step.outcome(requestResolve, { id, answer: answer.data });
|
|
193
|
+
switch (outcome.status) {
|
|
194
|
+
case "completed":
|
|
195
|
+
return { accepted: outcome.value.answered };
|
|
196
|
+
case "failed":
|
|
197
|
+
return { refused: outcome.error, final: false };
|
|
198
|
+
case "denied":
|
|
199
|
+
return { refused: outcome.reason, final: true };
|
|
200
|
+
case "unknown":
|
|
201
|
+
return { refused: "the answer could not be given: its outcome is unknown", final: true };
|
|
202
|
+
case "cancelled":
|
|
203
|
+
return { refused: `the answer was not given: ${outcome.reason}`, final: true };
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
const given = await give(input.value);
|
|
207
|
+
if ("accepted" in given) return given;
|
|
208
|
+
// Some tool layers pass an argument with no declared type as text: an answer that does not
|
|
209
|
+
// pass as given, and is JSON text, is read as that JSON. The question still decides.
|
|
210
|
+
const decoded = given.final ? undefined : jsonText(input.value);
|
|
211
|
+
if (decoded === undefined) throw new Error(given.refused);
|
|
212
|
+
const read = await give(decoded.value);
|
|
213
|
+
if ("accepted" in read) return read;
|
|
214
|
+
// The answer is refused as given and as read: what the model is told is both, as it cannot
|
|
215
|
+
// know which way it was taken.
|
|
216
|
+
throw new Error(`${given.refused} (read as the JSON it holds: ${read.refused})`);
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** The JSON a text holds, when the value is a text that is JSON and not a bare string. */
|
|
222
|
+
function jsonText(value: unknown): { value: unknown } | undefined {
|
|
223
|
+
if (typeof value !== "string") return undefined;
|
|
224
|
+
try {
|
|
225
|
+
const parsed: unknown = JSON.parse(value);
|
|
226
|
+
return typeof parsed === "string" ? undefined : { value: parsed };
|
|
227
|
+
} catch {
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
}
|