@openshain/agent 0.2.0 → 0.3.1

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/dist/session.js CHANGED
@@ -1,375 +1,424 @@
1
- import { buildProjection, compileInputValidator, isOpenshainError, isTerminal, parseWorkId, SESSION_WORK_TYPE, } from "@openshain/core";
2
- import { countToolCalls, pendingQuestions, RUNTIME_PROVIDER_ID, runWork } from "./loop.js";
1
+ import { ASK_USER_TOOL_NAME, buildProjection, eventToFile, isTerminal, newEventId, SESSION_WORK_TYPE, } from "@openshain/core";
2
+ import { jsonOf } from "./client.js";
3
3
  import { pickAgentName } from "./names.js";
4
- /** How much one turn of a session may do before the person hears back. */
5
- export const TURN_LIMITS = { modelCalls: 5, toolCalls: 10 };
6
- /** What the session's model may do: hand work out and look work up. It never touches files itself. */
7
- export const SESSION_TOOLS = Object.freeze([
8
- {
9
- name: "work_run",
10
- description: "Start a work for the person's request and drive it until it completes, fails or stops to ask the person a question. Write the objective in the person's own words and add what the conversation established that the work needs to know. Returns the work's id, status, summary, artifacts and usage, or the question it is waiting on.",
11
- inputSchema: {
12
- type: "object",
13
- properties: {
14
- objective: {
15
- type: "string",
16
- minLength: 1,
17
- description: "The request, in the person's words.",
18
- },
19
- type: {
20
- type: "string",
21
- description: "A short label for the kind of work. Defaults to request.",
22
- },
23
- },
24
- required: ["objective"],
25
- additionalProperties: false,
26
- },
27
- effect: "mutate",
28
- },
29
- {
30
- name: "work_list",
31
- description: "The most recent works in this workspace, newest first, without sessions.",
32
- inputSchema: { type: "object", properties: {}, additionalProperties: false },
33
- effect: "observe",
34
- },
35
- {
36
- name: "work_show",
37
- description: "One work by id: its status, summary, artifacts, usage, and who has to act next.",
38
- inputSchema: {
39
- type: "object",
40
- properties: { id: { type: "string", minLength: 1 } },
41
- required: ["id"],
42
- additionalProperties: false,
43
- },
44
- effect: "observe",
45
- },
46
- ]);
47
- const validators = new Map(SESSION_TOOLS.map((tool) => [tool.name, compileInputValidator(tool.inputSchema)]));
48
- const ROLE = "あなたはこの会社の社員エージェントとして、受付の役で、この人と話す。作業が要るときは work_run に objective を渡して Work にする。objective は人の言葉で書き、会話で分かった前提を添える。会社のファイルは自分では変更しない。ファイルの中身を見ないと答えられない質問も、work_run で Work にして調べる。作業の結果は要約して伝える。件数や金額は Work の結果の数字をそのまま書き、計算し直さない。返答は端末の画面に出るので、Markdown の記法や絵文字は使わず、短い文で書く。過去の作業は work_list と work_show で答える。";
49
- /** Opens a conversation, recorded as a work of type "session", between the person and the model. */
50
- export async function createSession(runtime, options = {}) {
51
- const model = options.model ?? runtime.model;
52
- const { principal, profession } = runtime.config;
53
- const agentName = options.agentName ?? pickAgentName(runtime.config.company.language, await namesInUse(runtime));
54
- const created = await runtime.works.create({
4
+ /** How much one turn of the conversation may do before it stops and the person is told. */
5
+ export const TURN_LIMITS = { modelCalls: 25, toolCalls: 40 };
6
+ /** The tools of the runtime that the loop itself drives; the model never sees them. */
7
+ const LOOP_ONLY_TOOLS = new Set(["work_record", "work_answer"]);
8
+ const ROLE = "あなたはこの会社の社員エージェントとして、受付の役で、この人と話す。作業が要るときは work_create で Work を作り(objective は人の言葉で書き、会話で分かった前提を添える)、その Work の中で Tool を呼び、終わったら work_complete で summary を人の言葉で書いて閉じる。会話の中では Tool を呼べないので、ファイルの中身を見ないと答えられない質問も Work を作って調べる。件数や金額は Tool が返した値をそのまま書き、計算し直さない。/work resume で候補として示された Work は、人の依頼がその objective に沿うときだけ work_select で続ける。沿わなければ続けず、その旨を伝えて新しい Work を作るか work_list で探し直す。返答は端末の画面に出るので、Markdown の記法や絵文字は使わず、短い文で書く。過去の作業は work_list と work_get で答える。";
9
+ /**
10
+ * Opens a conversation, recorded as a work of type "session", between the person and the model.
11
+ * The loop is a client of the runtime: it creates works, calls tools and closes works through
12
+ * the same MCP tools any other agent uses, and records its own model calls with work_record.
13
+ */
14
+ export async function createSession(client, options) {
15
+ const { model, config } = options;
16
+ const agentName = options.agentName ?? pickAgentName(config.company.language, await namesInUse(client));
17
+ const opened = await client.call("work_create", {
55
18
  objective: "会話",
56
- principal: principal.id,
57
- profession: profession.id,
58
19
  type: SESSION_WORK_TYPE,
59
- agentName,
20
+ agent_name: agentName,
60
21
  });
61
- await withHandle(runtime, created.id, options, (handle) => handle.transition("in_progress", "session opened"));
62
- return {
63
- id: created.id,
22
+ if (opened.isError)
23
+ throw new Error(`could not open a session: ${opened.text}`);
24
+ const session = jsonOf(opened);
25
+ const id = session.id;
26
+ /** The session's events as the projection needs them, kept in memory; the runtime holds the record. */
27
+ const events = [];
28
+ let seq = 0;
29
+ const local = (type, payload) => {
30
+ const now = new Date().toISOString();
31
+ seq += 1;
32
+ return {
33
+ v: 1,
34
+ id: newEventId(),
35
+ workId: id,
36
+ seq,
37
+ type,
38
+ payload,
39
+ occurredAt: now,
40
+ recordedAt: now,
41
+ };
42
+ };
43
+ events.push(local("work.created", {
44
+ objective: "会話",
45
+ principal: config.principal.id,
46
+ profession: config.profession.id,
47
+ type: SESSION_WORK_TYPE,
64
48
  agentName,
65
- turn: (text, turnOptions = {}) => withHandle(runtime, created.id, options, async (handle) => {
66
- await handle.append({ type: "human.message", payload: { text } });
67
- return runTurn(runtime, handle, model, options, turnOptions.signal);
68
- }),
69
- close: () => withHandle(runtime, created.id, options, async (handle) => {
70
- if (isTerminal((await handle.current()).status))
71
- return handle.current();
72
- await handle.append({
73
- type: "evidence.recorded",
74
- payload: { claim: "会話を終了", refs: [], artifacts: [] },
75
- });
76
- await handle.append({ type: "work.completed", payload: { summary: "会話を終了" } });
77
- return handle.current();
78
- }),
49
+ }));
50
+ let task;
51
+ let candidate;
52
+ /** Records one of the client's own events on a work through the runtime, and reports it. */
53
+ const record = async (workId, type, payload) => {
54
+ const event = local(type, payload);
55
+ const file = eventToFile({ ...event, workId });
56
+ const result = await client.call("work_record", {
57
+ work_id: workId,
58
+ type,
59
+ payload: file.payload,
60
+ });
61
+ if (result.isError)
62
+ throw new Error(`work_record failed: ${result.text}`);
63
+ await options.onEvent?.(workId, { ...event, workId });
79
64
  };
80
- }
81
- /** The names of the sessions still open, so two people talking at once do not get the same one. */
82
- async function namesInUse(runtime) {
83
- const { works } = await runtime.works.list();
84
- return works
85
- .filter((w) => w.type === SESSION_WORK_TYPE && !isTerminal(w.status))
86
- .flatMap((w) => (w.agentName ? [w.agentName] : []));
87
- }
88
- async function withHandle(runtime, id, options, fn) {
89
- const opened = await runtime.works.open(id);
90
- const handle = options.onEvent ? observed(opened, options.onEvent) : opened;
91
- try {
92
- return await fn(handle);
93
- }
94
- finally {
95
- await handle.close();
96
- }
97
- }
98
- async function runTurn(runtime, handle, model, options, signal) {
99
- const description = model.describe();
100
- const config = {
101
- ...runtime.config,
65
+ /** Records a model event on the session and, while a work is open, on that work as well. */
66
+ const recordModelEvent = async (type, payload) => {
67
+ events.push(local(type, payload));
68
+ await record(id, type, payload);
69
+ if (task)
70
+ await record(task.id, type, payload);
71
+ };
72
+ const describedTools = async () => (await client.listTools()).filter((t) => !LOOP_ONLY_TOOLS.has(t.name));
73
+ const promptConfig = {
74
+ ...config,
102
75
  profession: {
103
- ...runtime.config.profession,
104
- instructions: `${runtime.config.profession.instructions.trim()}\n\n${ROLE}`,
76
+ ...config.profession,
77
+ instructions: `${config.profession.instructions.trim()}\n\n${ROLE}`,
105
78
  },
106
79
  };
107
- const turnStart = (await handle.events()).length;
108
- const tools = [...SESSION_TOOLS];
109
- let modelCalls = 0;
110
- let toolCalls = 0;
111
- for (;;) {
112
- if (signal?.aborted)
113
- return { reply: "", stopped: "aborted" };
114
- if (modelCalls >= TURN_LIMITS.modelCalls) {
115
- return {
116
- reply: "",
117
- stopped: "turn_limit",
118
- detail: `model calls in one turn (${TURN_LIMITS.modelCalls})`,
119
- };
120
- }
121
- const events = await handle.events();
122
- const projection = buildProjection({
123
- events,
124
- config,
125
- tools,
126
- providerId: model.id,
127
- budget: {
128
- modelCallsLeft: TURN_LIMITS.modelCalls - modelCalls,
129
- toolCallsLeft: TURN_LIMITS.toolCalls - toolCalls,
130
- },
131
- });
132
- await handle.append({
133
- type: "model.requested",
134
- payload: {
80
+ async function runTurn(signal) {
81
+ const description = model.describe();
82
+ const tools = await describedTools();
83
+ let modelCalls = 0;
84
+ let toolCalls = 0;
85
+ for (;;) {
86
+ if (signal?.aborted)
87
+ return { reply: "", stopped: "aborted" };
88
+ if (modelCalls >= TURN_LIMITS.modelCalls) {
89
+ return {
90
+ reply: "",
91
+ stopped: "turn_limit",
92
+ detail: `model calls in one turn (${TURN_LIMITS.modelCalls})`,
93
+ };
94
+ }
95
+ const projection = buildProjection({
96
+ events,
97
+ config: promptConfig,
98
+ tools,
99
+ providerId: model.id,
100
+ budget: {
101
+ modelCallsLeft: TURN_LIMITS.modelCalls - modelCalls,
102
+ toolCallsLeft: TURN_LIMITS.toolCalls - toolCalls,
103
+ },
104
+ });
105
+ if (task && task.modelCalls >= config.limits.maxModelCalls) {
106
+ await callTool({
107
+ id: `call_limit_${task.id}`,
108
+ name: "work_fail",
109
+ input: {
110
+ reason: "limit_reached",
111
+ detail: `${config.limits.maxModelCalls} model calls`,
112
+ },
113
+ }, signal);
114
+ return {
115
+ reply: "",
116
+ stopped: "turn_limit",
117
+ detail: `model calls in one work (${config.limits.maxModelCalls})`,
118
+ };
119
+ }
120
+ await recordModelEvent("model.requested", {
135
121
  provider: model.id,
136
122
  model: description.model,
137
123
  messageCount: projection.messages.length,
138
124
  toolNames: tools.map((t) => t.name),
139
- },
140
- });
141
- modelCalls += 1;
142
- let response;
143
- try {
144
- response = await model.generate({
145
- system: projection.system,
146
- messages: projection.messages,
147
- tools: projection.tools,
148
- maxOutputTokens: runtime.config.limits.maxOutputTokens,
149
- budget: projection.budget,
150
- stableMessages: projection.messages.length - 1,
151
- ...(runtime.config.model.options && { providerOptions: runtime.config.model.options }),
152
- }, signal);
153
- }
154
- catch (err) {
155
- const message = err instanceof Error ? err.message : String(err);
156
- await handle.append({
157
- type: "model.failed",
158
- payload: { code: isOpenshainError(err) ? err.code : "model_error", message },
159
125
  });
160
- return { reply: "", stopped: signal?.aborted ? "aborted" : "model_error", detail: message };
161
- }
162
- await handle.append({
163
- type: "model.completed",
164
- payload: {
126
+ modelCalls += 1;
127
+ if (task)
128
+ task.modelCalls += 1;
129
+ let response;
130
+ try {
131
+ response = await model.generate({
132
+ system: projection.system,
133
+ messages: projection.messages,
134
+ tools: projection.tools,
135
+ maxOutputTokens: config.limits.maxOutputTokens,
136
+ budget: projection.budget,
137
+ stableMessages: projection.messages.length - 1,
138
+ ...(config.model?.options && { providerOptions: config.model.options }),
139
+ }, signal);
140
+ }
141
+ catch (err) {
142
+ const message = err instanceof Error ? err.message : String(err);
143
+ await recordModelEvent("model.failed", { code: "model_error", message });
144
+ return { reply: "", stopped: signal?.aborted ? "aborted" : "model_error", detail: message };
145
+ }
146
+ await recordModelEvent("model.completed", {
165
147
  stopReason: response.stopReason,
166
148
  content: response.message.content,
167
- ...(runtime.config.debug.persistRaw && response.raw !== undefined && { raw: response.raw }),
168
- },
169
- });
170
- await handle.append({
171
- type: "usage.recorded",
172
- payload: {
149
+ ...(config.debug?.persistRaw && response.raw !== undefined && { raw: response.raw }),
150
+ });
151
+ await recordModelEvent("usage.recorded", {
173
152
  kind: "model_inference",
174
153
  provider: model.id,
175
154
  model: description.model,
176
155
  usage: response.usage,
177
- },
178
- });
179
- const text = textOf(response.message.content);
180
- switch (response.stopReason) {
181
- case "end_turn":
182
- return { reply: text };
183
- case "tool_call": {
184
- const calls = response.message.content.filter((p) => p.type === "tool_call");
185
- for (const call of calls) {
186
- if (signal?.aborted)
187
- return { reply: text, stopped: "aborted" };
188
- if (toolCalls >= TURN_LIMITS.toolCalls) {
189
- return {
190
- reply: text,
191
- stopped: "turn_limit",
192
- detail: `tool calls in one turn (${TURN_LIMITS.toolCalls})`,
193
- };
156
+ });
157
+ const text = textOf(response.message.content);
158
+ switch (response.stopReason) {
159
+ case "end_turn":
160
+ return { reply: text };
161
+ case "tool_call": {
162
+ const calls = response.message.content.filter((p) => p.type === "tool_call");
163
+ for (const call of calls) {
164
+ if (signal?.aborted)
165
+ return { reply: text, stopped: "aborted" };
166
+ if (toolCalls >= TURN_LIMITS.toolCalls) {
167
+ return {
168
+ reply: text,
169
+ stopped: "turn_limit",
170
+ detail: `tool calls in one turn (${TURN_LIMITS.toolCalls})`,
171
+ };
172
+ }
173
+ toolCalls += 1;
174
+ const outcome = await callTool(call, signal);
175
+ if (outcome === "withdrawn")
176
+ return { reply: text, stopped: "aborted" };
194
177
  }
195
- toolCalls += 1;
196
- await callSessionTool(runtime, handle, model, options, signal, call);
178
+ break;
197
179
  }
198
- break;
180
+ case "max_tokens":
181
+ return { reply: text, stopped: "max_tokens" };
182
+ case "refusal":
183
+ return { reply: text, stopped: "refusal" };
184
+ default:
185
+ return {
186
+ reply: text,
187
+ stopped: "model_error",
188
+ detail: `unexpected stop reason "${response.stopReason}"`,
189
+ };
199
190
  }
200
- case "max_tokens":
201
- return { reply: text, stopped: "max_tokens" };
202
- case "refusal":
203
- return { reply: text, stopped: "refusal" };
204
- default:
205
- return {
206
- reply: text,
207
- stopped: "model_error",
208
- detail: `unexpected stop reason "${response.stopReason}"`,
209
- };
210
191
  }
211
- // Nothing of the turn's own events is needed below; the projection rebuilds from the log.
212
- void turnStart;
213
- }
214
- }
215
- async function callSessionTool(runtime, handle, model, options, signal, call) {
216
- const validate = validators.get(call.name);
217
- if (!validate) {
218
- await handle.append({
219
- type: "tool.rejected",
220
- payload: {
221
- callId: call.id,
222
- name: call.name,
223
- code: "unknown_tool",
224
- reason: `no tool named "${call.name}"; the session offers ${SESSION_TOOLS.map((t) => t.name).join(", ")}`,
225
- },
226
- });
227
- return;
228
- }
229
- const validation = validate(call.input);
230
- if (!validation.ok) {
231
- await handle.append({
232
- type: "tool.rejected",
233
- payload: {
234
- callId: call.id,
235
- name: call.name,
236
- code: "schema_mismatch",
237
- reason: `input does not match the schema of ${call.name}: ${validation.reason}`,
238
- },
239
- });
240
- return;
241
- }
242
- await handle.append({
243
- type: "tool.called",
244
- payload: { callId: call.id, provider: RUNTIME_PROVIDER_ID, name: call.name, input: call.input },
245
- });
246
- let result;
247
- try {
248
- result = await runSessionTool(runtime, handle, model, options, signal, call.name, call.input);
249
192
  }
250
- catch (err) {
251
- result = {
252
- content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }],
253
- isError: true,
254
- };
255
- }
256
- await handle.append({
257
- type: "tool.completed",
258
- payload: { callId: call.id, content: result.content, isError: result.isError ?? false },
259
- });
260
- }
261
- async function runSessionTool(runtime, handle, model, options, signal, name, input) {
262
- switch (name) {
263
- case "work_run": {
264
- const type = typeof input.type === "string" && input.type !== "" ? input.type : "request";
265
- if (type === SESSION_WORK_TYPE) {
266
- return {
193
+ /**
194
+ * One tool call of the model, through the runtime. Keeps track of the work the model is on,
195
+ * asks the person when the runtime says a question is pending, and mirrors the call and its
196
+ * result into the session's projection.
197
+ */
198
+ async function callTool(call, signal) {
199
+ const workId = task?.id ?? id;
200
+ // The loop drives these itself; a model that calls them is refused before the runtime sees it.
201
+ const refusal = LOOP_ONLY_TOOLS.has(call.name)
202
+ ? `${call.name} is the loop's own; it is not a tool for the model`
203
+ : !task && (call.name === "work_complete" || call.name === "work_fail")
204
+ ? `${call.name} needs a work of its own: no work is open; start one with work_create`
205
+ : undefined;
206
+ if (refusal) {
207
+ finish(call.id, { content: [{ type: "text", text: refusal }], isError: true, text: "" });
208
+ return "done";
209
+ }
210
+ events.push(local("tool.called", {
211
+ callId: call.id,
212
+ provider: "runtime",
213
+ name: call.name,
214
+ input: call.input,
215
+ }));
216
+ await options.onEvent?.(workId, events.at(-1));
217
+ const input = call.name === "work_create" && call.input && typeof call.input === "object"
218
+ ? { ...call.input, parent: id, agent_name: agentName }
219
+ : call.input;
220
+ let result;
221
+ try {
222
+ result = await client.call(call.name, input, signal);
223
+ }
224
+ catch (err) {
225
+ result = {
226
+ content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }],
227
+ isError: true,
228
+ text: "",
229
+ };
230
+ }
231
+ task?.callIds.add(call.id);
232
+ const data = result.isError
233
+ ? undefined
234
+ : jsonOf(result);
235
+ if (!result.isError &&
236
+ (call.name === "work_create" || call.name === "work_select") &&
237
+ data?.id) {
238
+ const workId = data.id;
239
+ const history = data.history;
240
+ task = {
241
+ id: workId,
242
+ modelCalls: typeof history?.modelCalls === "number" ? history.modelCalls : 0,
243
+ callIds: new Set([call.id]),
244
+ };
245
+ candidate = undefined;
246
+ await options.onEvent?.(workId, local("work.status_changed", {
247
+ from: "queued",
248
+ to: String(data.status ?? "in_progress"),
249
+ reason: call.name,
250
+ }));
251
+ // A selected work that waits for an answer gets it now, oldest question first.
252
+ if (call.name === "work_select" && data.status === "waiting_input") {
253
+ const answered = await answerPending(workId, signal);
254
+ if (answered === "withdrawn") {
255
+ finish(call.id, result);
256
+ return "withdrawn";
257
+ }
258
+ if (answered.length > 0) {
259
+ result = {
260
+ ...result,
261
+ text: "",
262
+ content: [
263
+ ...result.content,
264
+ { type: "text", text: `answers recorded: ${JSON.stringify(answered)}` },
265
+ ],
266
+ };
267
+ }
268
+ }
269
+ }
270
+ if (!result.isError && call.name === ASK_USER_TOOL_NAME && data?.pending === true && task) {
271
+ const asked = task.id;
272
+ const question = String(data.question ?? "");
273
+ if (!options.onInput) {
274
+ result = {
275
+ ...result,
276
+ text: "",
267
277
  content: [
268
278
  {
269
279
  type: "text",
270
- text: `type "${SESSION_WORK_TYPE}" is reserved for conversations; use another label, such as request`,
280
+ text: "the work waits for the person's answer; it can be resumed later",
271
281
  },
272
282
  ],
273
- isError: true,
274
283
  };
275
284
  }
276
- const agentName = (await handle.current()).agentName;
277
- const child = await runtime.works.create({
278
- objective: String(input.objective),
279
- principal: runtime.config.principal.id,
280
- profession: runtime.config.profession.id,
281
- type,
282
- parent: handle.id,
283
- ...(agentName !== undefined && { agentName }),
284
- });
285
- const done = await runWork(runtime, child.id, {
286
- model,
287
- ...(options.onInput && {
288
- onInput: (q) => options.onInput?.(child.id, q),
289
- }),
290
- ...(options.onWorkEvent && {
291
- onEvent: (e) => options.onWorkEvent?.(child.id, e),
292
- }),
293
- ...(signal && { signal }),
294
- });
295
- return {
296
- content: [
297
- { type: "json", value: await describeWork(runtime, done, signal?.aborted === true) },
298
- ],
299
- };
285
+ else {
286
+ let answer;
287
+ try {
288
+ answer = await options.onInput(asked, question);
289
+ }
290
+ catch {
291
+ // The person took the question back: the work stays waiting_input.
292
+ finish(call.id, {
293
+ content: [{ type: "text", text: "the person withdrew the question; the work waits" }],
294
+ isError: true,
295
+ text: "",
296
+ });
297
+ return "withdrawn";
298
+ }
299
+ const answered = await client.call("work_answer", { call_id: data.call_id, answer }, signal);
300
+ result = answered.isError
301
+ ? answered
302
+ : { content: [{ type: "text", text: answer }], isError: false, text: answer };
303
+ }
300
304
  }
301
- case "work_list": {
302
- const { works } = await runtime.works.list();
303
- const recent = works
304
- .filter((w) => w.type !== SESSION_WORK_TYPE)
305
- .sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0))
306
- .slice(0, 20)
307
- .map((w) => ({
308
- id: w.id,
309
- status: w.status,
310
- type: w.type,
311
- objective: w.objective,
312
- createdAt: w.createdAt,
313
- }));
314
- return { content: [{ type: "json", value: { works: recent } }] };
305
+ finish(call.id, result);
306
+ if (!result.isError && (call.name === "work_complete" || call.name === "work_fail") && task) {
307
+ const closed = task;
308
+ task = undefined;
309
+ foldAway(closed, call.id);
310
+ await options.onEvent?.(closed.id, local(call.name === "work_complete" ? "work.completed" : "work.failed", call.name === "work_complete"
311
+ ? { summary: String(call.input?.summary ?? "") }
312
+ : { reason: String(call.input?.reason ?? ""), detail: "" }));
315
313
  }
316
- case "work_show": {
317
- let id;
314
+ return "done";
315
+ }
316
+ /** Asks the person every question the work still waits on and records the answers. */
317
+ async function answerPending(workId, signal) {
318
+ if (!options.onInput)
319
+ return [];
320
+ const got = await client.call("work_get", { id: workId, history: true }, signal);
321
+ const history = jsonOf(got)?.history;
322
+ const answers = [];
323
+ for (const { callId, question } of history?.pending ?? []) {
324
+ let answer;
318
325
  try {
319
- id = parseWorkId(String(input.id));
326
+ answer = await options.onInput(workId, question);
320
327
  }
321
328
  catch {
322
- return {
323
- content: [{ type: "text", text: `"${String(input.id)}" is not a work id` }],
324
- isError: true,
325
- };
329
+ return "withdrawn";
326
330
  }
327
- const work = await runtime.works.get(id);
328
- return { content: [{ type: "json", value: await describeWork(runtime, work, false) }] };
331
+ const recorded = await client.call("work_answer", { call_id: callId, answer }, signal);
332
+ if (recorded.isError)
333
+ throw new Error(recorded.text);
334
+ answers.push({ question, answer });
329
335
  }
330
- default:
331
- return { content: [{ type: "text", text: `no tool named "${name}"` }], isError: true };
336
+ return answers;
332
337
  }
333
- }
334
- /** A work as the session's model needs to see it: outcome, cost, and who acts next. */
335
- async function describeWork(runtime, work, interrupted) {
336
- const events = await runtime.works.events(work.id);
337
- const usage = {
338
- modelCalls: 0,
339
- toolCalls: countToolCalls(events),
340
- inputTokens: 0,
341
- outputTokens: 0,
342
- };
343
- for (const event of events) {
344
- if (event.type === "model.requested")
345
- usage.modelCalls += 1;
346
- if (event.type === "usage.recorded") {
347
- const { payload } = event;
348
- if (payload.kind === "model_inference") {
349
- usage.inputTokens += payload.usage.inputTokens;
350
- usage.outputTokens += payload.usage.outputTokens;
351
- }
338
+ function finish(callId, result) {
339
+ const event = local("tool.completed", {
340
+ callId,
341
+ content: result.content,
342
+ isError: result.isError,
343
+ });
344
+ events.push(event);
345
+ void options.onEvent?.(task?.id ?? id, event);
346
+ }
347
+ /** Once a work is closed, only its summary stays in the conversation: the tool results are folded away. */
348
+ function foldAway(closed, closingCallId) {
349
+ for (const event of events) {
350
+ if (event.type !== "tool.completed")
351
+ continue;
352
+ const payload = event.payload;
353
+ if (!closed.callIds.has(payload.callId) || payload.callId === closingCallId)
354
+ continue;
355
+ payload.content = [
356
+ {
357
+ type: "text",
358
+ text: `(この結果は Work ${closed.id} を閉じたので省略。要点は work_complete の summary にある)`,
359
+ },
360
+ ];
352
361
  }
353
362
  }
354
- const question = work.status === "waiting_input" ? pendingQuestions(events).map((q) => q.question) : [];
355
363
  return {
356
- id: work.id,
357
- status: work.status,
358
- ...(work.outcome && { summary: work.outcome.summary, artifacts: work.outcome.artifacts }),
359
- ...(work.failure && { failure: work.failure }),
360
- ...(question.length > 0 && { waitingFor: question }),
361
- ...(interrupted &&
362
- work.status === "in_progress" && {
363
- interrupted: "the person stopped this work; it can be resumed",
364
- }),
365
- nextActor: isTerminal(work.status)
366
- ? "nobody"
367
- : work.status === "waiting_input"
368
- ? "person"
369
- : "model",
370
- usage,
364
+ id,
365
+ agentName,
366
+ async turn(text, turnOptions = {}) {
367
+ events.push(local("human.message", { text }));
368
+ await record(id, "human.message", { text });
369
+ if (candidate) {
370
+ const note = `候補の Work: ${candidate.id}(status: ${candidate.status}、objective: ${candidate.objective})。この依頼がその objective に沿うなら work_select で続ける。沿わなければ続けず、その旨を伝えて新しい Work を作るか work_list で探し直す。`;
371
+ events.push(local("prompt.expanded", { name: "work resume", source: "builtin", text: note }));
372
+ await record(id, "prompt.expanded", { name: "work resume", source: "builtin", text: note });
373
+ }
374
+ try {
375
+ const result = await runTurn(turnOptions.signal);
376
+ return task ? { ...result, work: task.id } : result;
377
+ }
378
+ finally {
379
+ // Whatever the turn did, the next one starts from the conversation: a work it left open
380
+ // stays as it is and comes back as a candidate through select; a declined candidate is dropped.
381
+ candidate = undefined;
382
+ if (task) {
383
+ task = undefined;
384
+ await client.call("work_select", { id }).catch(() => undefined);
385
+ }
386
+ }
387
+ },
388
+ async select(workId) {
389
+ const got = await client.call("work_get", { id: workId });
390
+ if (got.isError)
391
+ throw new Error(got.text);
392
+ const work = jsonOf(got);
393
+ if (isTerminal(work.status))
394
+ throw new Error(`${work.id} は ${work.status} で、続けられません`);
395
+ candidate = { id: work.id, objective: work.objective, status: work.status };
396
+ return work;
397
+ },
398
+ currentWork: () => task?.id,
399
+ async close() {
400
+ const selected = await client.call("work_select", { id });
401
+ if (selected.isError) {
402
+ const got = await client.call("work_get", { id });
403
+ return jsonOf(got);
404
+ }
405
+ const closed = await client.call("work_complete", { summary: "会話を終了" });
406
+ if (closed.isError)
407
+ throw new Error(closed.text);
408
+ return jsonOf(closed);
409
+ },
371
410
  };
372
411
  }
412
+ /** The names of the sessions still open, so two people talking at once do not get the same one. */
413
+ async function namesInUse(client) {
414
+ const listed = await client.call("work_list", {});
415
+ if (listed.isError)
416
+ return [];
417
+ const { works } = jsonOf(listed);
418
+ return works
419
+ .filter((w) => w.type === SESSION_WORK_TYPE && !isTerminal(w.status))
420
+ .flatMap((w) => (w.agentName ? [w.agentName] : []));
421
+ }
373
422
  function textOf(content) {
374
423
  return content
375
424
  .filter((p) => p.type === "text")
@@ -377,18 +426,3 @@ function textOf(content) {
377
426
  .join("\n")
378
427
  .trim();
379
428
  }
380
- function observed(handle, onEvent) {
381
- return {
382
- ...handle,
383
- async append(event) {
384
- const recorded = await handle.append(event);
385
- await onEvent(recorded);
386
- return recorded;
387
- },
388
- async transition(to, reason) {
389
- const recorded = await handle.transition(to, reason);
390
- await onEvent(recorded);
391
- return recorded;
392
- },
393
- };
394
- }