@sixb/agent 0.2.3 → 0.2.4

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 (80) hide show
  1. package/README.md +2 -2
  2. package/dist/artifacts/publish-tool.d.ts +26 -44
  3. package/dist/artifacts/publish-tool.d.ts.map +1 -1
  4. package/dist/ask-tool.d.ts +62 -0
  5. package/dist/ask-tool.d.ts.map +1 -0
  6. package/dist/attachments.d.ts +1 -1
  7. package/dist/attachments.d.ts.map +1 -1
  8. package/dist/background-commands.d.ts +3 -3
  9. package/dist/background-commands.d.ts.map +1 -1
  10. package/dist/background-notices.d.ts.map +1 -1
  11. package/dist/child-files.d.ts +1 -1
  12. package/dist/child-questions.d.ts +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1380 -596
  16. package/dist/index.js.map +30 -26
  17. package/dist/run-agent-turn.d.ts.map +1 -1
  18. package/dist/run-conversation-turn.d.ts.map +1 -1
  19. package/dist/run-environment.d.ts +4 -1
  20. package/dist/run-environment.d.ts.map +1 -1
  21. package/dist/run-subagent.d.ts +1 -1
  22. package/dist/subagent-tools.d.ts +20 -1
  23. package/dist/subagent-tools.d.ts.map +1 -1
  24. package/dist/tools/background.d.ts +50 -18
  25. package/dist/tools/background.d.ts.map +1 -1
  26. package/dist/tools/bash.d.ts +1 -0
  27. package/dist/tools/bash.d.ts.map +1 -1
  28. package/dist/tools/edit-text.d.ts +22 -0
  29. package/dist/tools/edit-text.d.ts.map +1 -0
  30. package/dist/tools/edit.d.ts +54 -0
  31. package/dist/tools/edit.d.ts.map +1 -0
  32. package/dist/tools/file-writes.d.ts +52 -0
  33. package/dist/tools/file-writes.d.ts.map +1 -0
  34. package/dist/tools/model-spec.d.ts.map +1 -1
  35. package/dist/tools/read.d.ts +16 -3
  36. package/dist/tools/read.d.ts.map +1 -1
  37. package/dist/tools/view-file.d.ts +20 -23
  38. package/dist/tools/view-file.d.ts.map +1 -1
  39. package/dist/tools/web-fetch/tool.d.ts +1 -0
  40. package/dist/tools/web-fetch/tool.d.ts.map +1 -1
  41. package/dist/tools/web-search.d.ts +1 -0
  42. package/dist/tools/web-search.d.ts.map +1 -1
  43. package/dist/tools/write.d.ts +36 -0
  44. package/dist/tools/write.d.ts.map +1 -0
  45. package/package.json +4 -4
  46. package/src/agent-prompt.ts +9 -9
  47. package/src/artifacts/publish-tool.ts +76 -94
  48. package/src/ask-tool.ts +223 -0
  49. package/src/attachments.ts +7 -6
  50. package/src/background-commands.ts +5 -5
  51. package/src/background-notices.ts +5 -12
  52. package/src/child-files.ts +1 -1
  53. package/src/child-questions.ts +1 -1
  54. package/src/context-compaction.ts +4 -1
  55. package/src/index.ts +1 -1
  56. package/src/run-agent-turn.ts +14 -4
  57. package/src/run-child.ts +1 -1
  58. package/src/run-conversation-turn.ts +4 -1
  59. package/src/run-environment.ts +36 -21
  60. package/src/run-subagent.ts +3 -3
  61. package/src/skills/sixb-artifacts/SKILL.md +7 -7
  62. package/src/skills/sixb-artifacts/canvas.md +2 -2
  63. package/src/skills/sixb-artifacts/page.md +2 -2
  64. package/src/skills/sixb-artifacts/slides.md +2 -2
  65. package/src/subagent-tools.ts +115 -81
  66. package/src/tools/background.ts +227 -67
  67. package/src/tools/bash.ts +2 -1
  68. package/src/tools/edit-text.ts +241 -0
  69. package/src/tools/edit.ts +166 -0
  70. package/src/tools/file-writes.ts +270 -0
  71. package/src/tools/model-spec.ts +9 -13
  72. package/src/tools/read.ts +75 -9
  73. package/src/tools/tool-outputs.ts +2 -2
  74. package/src/tools/view-file.ts +78 -80
  75. package/src/tools/web-fetch/tool.ts +2 -1
  76. package/src/tools/web-search.ts +1 -0
  77. package/src/tools/write.ts +95 -0
  78. package/dist/ask-parent-tool.d.ts +0 -36
  79. package/dist/ask-parent-tool.d.ts.map +0 -1
  80. package/src/ask-parent-tool.ts +0 -100
@@ -0,0 +1,223 @@
1
+ import { type AgentMessage, AgentToolPublicError } from "@sixb/core"
2
+ import {
3
+ AGENT_QUESTION_LIMITS,
4
+ type AgentQuestion,
5
+ agentQuestionsText,
6
+ isChildAskTool,
7
+ } from "@sixb/core/internal/agents"
8
+ import { assertJsonValue, isJsonObject, type JsonObject, type ModelTool } from "@sixb/core/models"
9
+ import { agentToolErrorText } from "./model-adapters"
10
+ import type { SubagentInbox } from "./subagent-inbox"
11
+
12
+ export const ASK_TOOL_NAME = "ask"
13
+
14
+ export interface AskInput {
15
+ readonly questions: readonly AgentQuestion[]
16
+ }
17
+
18
+ /** What a sub-agent's `ask` answers: its parent's answer, or that it comes in a later turn. */
19
+ export type AskParentOutput =
20
+ | { readonly answer: string }
21
+ /** `question`: its id, which the answer of a later turn replies to. */
22
+ | { readonly status: "deferred"; readonly question: string; readonly note: string }
23
+ /** It paused on a held call too: only a decision continues it, without an answer. */
24
+ | { readonly status: "unanswered"; readonly question: string; readonly note: string }
25
+
26
+ /** What the Agent's `ask` answers: the user sees the questions, and the turn ends. */
27
+ export interface AskUserOutput {
28
+ readonly status: "asked"
29
+ readonly note: string
30
+ }
31
+
32
+ /** Read by the child only once it continues: its loop pauses right after the step that asked. */
33
+ const DEFERRED_NOTE =
34
+ "Your parent's turn ended before it could answer. You continue with its answer, a <sixb_parent_answer> block, once it has one."
35
+
36
+ const UNANSWERED_NOTE =
37
+ "Your parent's turn ended before it could answer, and you paused on a call that waits for the user's approval: you continue once the user decides, without an answer. Ask again if you still need one."
38
+
39
+ const ASKED_NOTE = "The user sees your questions. Their answer comes as their next message."
40
+
41
+ /**
42
+ * What a question deferred in the step that held a call reads as once the child continues: the
43
+ * decision continues it, and no answer comes with it. Only a continuation reads it, as the child
44
+ * paused right after that step, so what its thread keeps may say so without changing a byte the
45
+ * model already read.
46
+ */
47
+ export function unansweredQuestion<TMessage extends Pick<AgentMessage, "parts">>(
48
+ messages: readonly TMessage[]
49
+ ): readonly TMessage[] {
50
+ return messages.map((message) => ({
51
+ ...message,
52
+ parts: message.parts.map((part) =>
53
+ part.type === "tool-call" &&
54
+ isChildAskTool(part.toolName) &&
55
+ part.state === "output-available" &&
56
+ isJsonObject(part.output) &&
57
+ part.output.status === "deferred" &&
58
+ typeof part.output.question === "string"
59
+ ? {
60
+ ...part,
61
+ output: { status: "unanswered", question: part.output.question, note: UNANSWERED_NOTE },
62
+ }
63
+ : part
64
+ ),
65
+ }))
66
+ }
67
+
68
+ /**
69
+ * A sub-agent's questions to its parent, which it waits for within its step. Its parent reads them
70
+ * as one text and answers with `message_agent`; when its turn ends first, the child pauses on them
71
+ * and a later turn continues it with the answer.
72
+ */
73
+ export function createAskParentTool(inbox: SubagentInbox): ModelTool<AskInput> {
74
+ return {
75
+ name: ASK_TOOL_NAME,
76
+ strict: true,
77
+ description: [
78
+ "Ask your parent agent, and wait for its answer, which this tool returns.",
79
+ "Ask only when you cannot go on without a decision that only your parent or the user can make, never what the project's data or your task answers. Put related questions in one call.",
80
+ ].join("\n"),
81
+ inputSchema: askInputSchema(),
82
+ parseInput: parseAskInput,
83
+ execute: async ({ questions }, { signal, callId, toolCallId }) => {
84
+ const reply = await inbox.ask(
85
+ agentQuestionsText(questions),
86
+ `${callId}:${toolCallId}`,
87
+ signal
88
+ )
89
+ const output: AskParentOutput =
90
+ reply.kind === "answer"
91
+ ? { answer: reply.text }
92
+ : { status: "deferred", question: reply.questionId, note: DEFERRED_NOTE }
93
+ assertJsonValue(output)
94
+ return output
95
+ },
96
+ errorText: agentToolErrorText,
97
+ }
98
+ }
99
+
100
+ /**
101
+ * The Agent's questions to the user. The turn ends after the step that asks (see
102
+ * {@link stepAskedUser}); the app and the TUI show the questions with their choices, and the
103
+ * user's answer is their next message, which the next turn reads after this call.
104
+ */
105
+ export function createAskUserTool(): ModelTool<AskInput> {
106
+ return {
107
+ name: ASK_TOOL_NAME,
108
+ strict: true,
109
+ description: [
110
+ "Ask the user, and end your turn: they see your questions with their choices, and their answer comes as their next message.",
111
+ "Ask only when you cannot go on without an answer only the user can give, never what the conversation, the project's data or the task answers: otherwise make a reasonable assumption and say it. Put related questions in one call.",
112
+ ].join("\n"),
113
+ inputSchema: askInputSchema(),
114
+ parseInput: parseAskInput,
115
+ execute: async () => {
116
+ const output: AskUserOutput = { status: "asked", note: ASKED_NOTE }
117
+ return { ...output }
118
+ },
119
+ errorText: agentToolErrorText,
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Whether a step of the Agent's asked the user: the turn ends after it. A call refused for its
125
+ * input did not ask: the model reads why and tries again.
126
+ */
127
+ export function stepAskedUser(step: {
128
+ readonly content: readonly {
129
+ readonly type: string
130
+ readonly toolName?: string
131
+ readonly output?: { readonly type: string }
132
+ }[]
133
+ }): boolean {
134
+ return step.content.some(
135
+ (part) =>
136
+ part.type === "tool-result" && part.toolName === ASK_TOOL_NAME && part.output?.type === "json"
137
+ )
138
+ }
139
+
140
+ function askInputSchema(): JsonObject {
141
+ return {
142
+ type: "object",
143
+ properties: {
144
+ questions: {
145
+ type: "array",
146
+ minItems: 1,
147
+ maxItems: AGENT_QUESTION_LIMITS.questions,
148
+ description: `One to ${AGENT_QUESTION_LIMITS.questions} questions, asked together.`,
149
+ items: {
150
+ type: "object",
151
+ properties: {
152
+ question: { type: "string", minLength: 1, description: "One short question." },
153
+ choices: {
154
+ type: "array",
155
+ maxItems: AGENT_QUESTION_LIMITS.choices,
156
+ items: { type: "string", minLength: 1 },
157
+ description: `Up to ${AGENT_QUESTION_LIMITS.choices} answers to pick from, when there are a few. A typed answer is always possible.`,
158
+ },
159
+ multiple: {
160
+ type: "boolean",
161
+ description: "Several of the choices may be picked. Default: false.",
162
+ },
163
+ },
164
+ required: ["question"],
165
+ additionalProperties: false,
166
+ },
167
+ },
168
+ },
169
+ required: ["questions"],
170
+ additionalProperties: false,
171
+ }
172
+ }
173
+
174
+ function parseAskInput(value: unknown): AskInput {
175
+ if (!isJsonObject(value) || Object.keys(value).some((key) => key !== "questions")) {
176
+ throw askError("ask expects { questions: [...] }.")
177
+ }
178
+ const { questions } = value
179
+ if (
180
+ !Array.isArray(questions) ||
181
+ questions.length === 0 ||
182
+ questions.length > AGENT_QUESTION_LIMITS.questions
183
+ ) {
184
+ throw askError(`ask expects 1 to ${AGENT_QUESTION_LIMITS.questions} questions.`)
185
+ }
186
+ return {
187
+ questions: questions.map((entry, index): AgentQuestion => {
188
+ const at = `questions[${index}]`
189
+ if (
190
+ !isJsonObject(entry) ||
191
+ Object.keys(entry).some((key) => !["question", "choices", "multiple"].includes(key))
192
+ ) {
193
+ throw askError(`${at} must be { question, choices?, multiple? }.`)
194
+ }
195
+ if (typeof entry.question !== "string" || !entry.question.trim()) {
196
+ throw askError(`${at}.question must be a non-empty question.`)
197
+ }
198
+ const choices = entry.choices ?? []
199
+ if (
200
+ !Array.isArray(choices) ||
201
+ choices.length > AGENT_QUESTION_LIMITS.choices ||
202
+ choices.some((choice) => typeof choice !== "string" || !choice.trim())
203
+ ) {
204
+ throw askError(
205
+ `${at}.choices must be up to ${AGENT_QUESTION_LIMITS.choices} non-empty answers.`
206
+ )
207
+ }
208
+ if (entry.multiple !== undefined && typeof entry.multiple !== "boolean") {
209
+ throw askError(`${at}.multiple must be true or false.`)
210
+ }
211
+ const picked = (choices as string[]).map((choice) => choice.trim())
212
+ return {
213
+ question: entry.question.trim(),
214
+ ...(picked.length > 0 ? { choices: picked } : {}),
215
+ ...(entry.multiple === true && picked.length > 0 ? { multiple: true } : {}),
216
+ }
217
+ }),
218
+ }
219
+ }
220
+
221
+ function askError(message: string): AgentToolPublicError {
222
+ return new AgentToolPublicError(`[SixbAgent] ${message}`)
223
+ }
@@ -28,10 +28,11 @@ const MAX_ASSISTANT_ATTACHMENTS = 50
28
28
 
29
29
  /**
30
30
  * Where a parent finds what its children wrote to `out/`, a directory per spawn key, in the context
31
- * directory: `wait_agent` copies them there, and later turns materialize them there again.
31
+ * directory: `wait` and `stop` copy them there, and later turns materialize them there again.
32
32
  */
33
33
  export const CHILD_FILES_DIRECTORY = "children"
34
- const WAIT_AGENT_TOOL = "wait_agent"
34
+ /** The tools whose results hold a child's files: `wait_agent` is what earlier threads hold. */
35
+ const CHILD_FILE_TOOLS: ReadonlySet<string> = new Set(["wait", "stop", "wait_agent"])
35
36
 
36
37
  /**
37
38
  * How many files, and bytes, a sandbox receives of a run's attachments: also what a parent Agent
@@ -385,7 +386,7 @@ async function prepareOneAttachment(input: {
385
386
  mayInlineContent &&
386
387
  remainingTextBytes > 0 &&
387
388
  shouldAttemptTextInline(mediaType, fileName, stat.sizeBytes)
388
- // A tool can return a file the sandbox holds already, such as an attachment view_file showed:
389
+ // A tool can return a file the sandbox holds already, such as an attachment read showed:
389
390
  // its output named that path, and the file stays there once.
390
391
  const alreadyAt =
391
392
  item.origin === "tool-result-file" ? input.materialized.get(fileRefKey(fileRef)) : undefined
@@ -466,7 +467,7 @@ async function prepareOneAttachment(input: {
466
467
  }
467
468
 
468
469
  metadataNote = !item.inlineContent
469
- ? "[Historical file kept as metadata: use view_file with the sandbox path when its contents are needed.]"
470
+ ? "[Historical file kept as metadata: use read with the sandbox path when its contents are needed.]"
470
471
  : remainingTextBytes === 0 && shouldAttemptTextInline(mediaType, fileName, stat.sizeBytes)
471
472
  ? "[File not inlined: the attachment text budget is exhausted; use the sandbox path or content URL.]"
472
473
  : "[File not inlined: available through the sandbox path or content URL.]"
@@ -912,7 +913,7 @@ function sandboxAttachmentPath(
912
913
  /**
913
914
  * Where the call that returned a tool file put it in the sandbox, as its output showed: a later
914
915
  * turn materializes it there again, so the replayed output still names a file that exists.
915
- * `wait_agent` copies a child's file under `children/<key>/`, its `logicalPath`; a tool that
916
+ * `wait` copies a child's file under `children/<key>/`, its `logicalPath`; a tool that
916
917
  * stored a file put it at its call's tool-file path.
917
918
  */
918
919
  function toolResultSandboxPath(
@@ -922,7 +923,7 @@ function toolResultSandboxPath(
922
923
  const { toolCall, fileRef } = item
923
924
  if (!toolCall) return undefined
924
925
 
925
- if (toolCall.toolName === WAIT_AGENT_TOOL) {
926
+ if (CHILD_FILE_TOOLS.has(toolCall.toolName)) {
926
927
  const path =
927
928
  fileRef.logicalPath === undefined ? undefined : posix.normalize(fileRef.logicalPath)
928
929
  if (!path || path.startsWith("/") || path === ".." || path.startsWith("../")) return undefined
@@ -8,7 +8,7 @@ import { type AgentSandboxHandle, contextPath } from "./sandbox-handle"
8
8
  // A background command runs in the call that starts it, held open until it ends: a provider that
9
9
  // kills what a call left behind once it returns (a cgroup, a PID namespace) leaves it alone, and
10
10
  // it needs nothing of a provider but `runCommand`. It runs in a process group of its own, which
11
- // `bash_stop` signals from inside the sandbox; the held call's abort is the fallback where another
11
+ // `stop` signals from inside the sandbox; the held call's abort is the fallback where another
12
12
  // call cannot reach it. Its output goes to a file in the run's context directory, which the agent
13
13
  // reads with `read` as any other file.
14
14
 
@@ -37,7 +37,7 @@ export type BackgroundCommandStatus = "running" | "exited" | "stopped"
37
37
 
38
38
  /** A background command as its tools report it, and as a chat can show it. */
39
39
  export interface BackgroundCommandState {
40
- /** `bg_<hex>`: the id `bash_output` and `bash_stop` take, never the same in two runs. */
40
+ /** `bg_<hex>`: the id `wait` and `stop` take, never the same in two runs. */
41
41
  readonly id: string
42
42
  readonly command: string
43
43
  readonly status: BackgroundCommandStatus
@@ -53,7 +53,7 @@ export interface BackgroundCommandState {
53
53
  readonly outputPath: string
54
54
  }
55
55
 
56
- /** What `bash_output` and `bash_stop` return: its state, and what it wrote since the last read. */
56
+ /** What `wait` and `stop` return of it: its state, and what it wrote since the last read. */
57
57
  export interface BackgroundCommandOutput extends BackgroundCommandState {
58
58
  /** What it wrote since the last read: its newest 20,000 bytes at most. */
59
59
  readonly output: string
@@ -128,7 +128,7 @@ export class BackgroundCommands {
128
128
  const running = [...this.#commands.values()].filter((entry) => entry.status === "running")
129
129
  if (running.length >= MAX_RUNNING) {
130
130
  throw new AgentToolPublicError(
131
- `[SixbAgent] ${MAX_RUNNING} background commands are running already: stop one with bash_stop first.`
131
+ `[SixbAgent] ${MAX_RUNNING} background commands are running already: stop one with stop first.`
132
132
  )
133
133
  }
134
134
 
@@ -460,7 +460,7 @@ async function signalGroup(entry: BackgroundCommand, signal: "TERM" | "KILL"): P
460
460
  /**
461
461
  * Stop the commands a `sixb` that ended without stopping them left running: one killed, or that
462
462
  * crashed. Their pid files are all that is left of them. Each group still running its command
463
- * gets SIGTERM, then SIGKILL after the grace period `bash_stop` gives, in one call.
463
+ * gets SIGTERM, then SIGKILL after the grace period `stop` gives, in one call.
464
464
  */
465
465
  export async function stopLeftRunning(
466
466
  sandbox: Sandbox,
@@ -1,19 +1,11 @@
1
1
  import { type AgentMessage, stableJsonStringify } from "@sixb/core"
2
2
  import type { ModelTool } from "@sixb/core/models"
3
3
  import type { BackgroundCommandState, BackgroundCommands } from "./background-commands"
4
- import { BASH_OUTPUT_TOOL_SPEC, BASH_STOP_TOOL_SPEC } from "./tools/background"
5
- import { BASH_TOOL_SPEC } from "./tools/bash"
4
+ import { reportedCommands } from "./tools/background"
6
5
 
7
6
  /** A command's displayed form in a notice: its first line, cut. */
8
7
  const NOTICE_COMMAND_CHARS = 80
9
8
 
10
- /** The tools whose results report a background command's state. */
11
- const STATE_TOOLS: ReadonlySet<string> = new Set([
12
- BASH_TOOL_SPEC.name,
13
- BASH_OUTPUT_TOOL_SPEC.name,
14
- BASH_STOP_TOOL_SPEC.name,
15
- ])
16
-
17
9
  /** A notice's line that tells a command ended, and its id. */
18
10
  const ENDED_LINE = /^Background command (\S+) \(`.*?`\) (?:exited with code|was stopped)/gm
19
11
 
@@ -113,9 +105,10 @@ export function backgroundCommandsLeftRunning(
113
105
  for (const part of message.parts) {
114
106
  if (part.type !== "tool-call" || part.state !== "output-available") continue
115
107
 
116
- if (STATE_TOOLS.has(part.toolName) && isCommandState(part.output)) {
117
- if (part.output.status === "running") running.set(part.output.id, part.output)
118
- else running.delete(part.output.id)
108
+ for (const command of reportedCommands(part.toolName, part.output)) {
109
+ if (!isCommandState(command)) continue
110
+ if (command.status === "running") running.set(command.id, command)
111
+ else running.delete(command.id)
119
112
  }
120
113
  if (part.modelOutput?.type === "text") {
121
114
  for (const [, id] of part.modelOutput.value.matchAll(ENDED_LINE)) {
@@ -171,7 +171,7 @@ async function readHandedSources(
171
171
 
172
172
  /**
173
173
  * The child's side: the files its parent handed over, at the same paths in its sandbox, listed in
174
- * `$SIXB_ATTACHMENTS` and readable with `view_file`.
174
+ * `$SIXB_ATTACHMENTS` and readable with `read`.
175
175
  */
176
176
  export async function prepareHandedFiles(input: {
177
177
  readonly projectId: string
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * A question a child asked: the id of its mail and what it asks. A child paused on it keeps both in
3
- * its thread, the text as its `ask_parent` call's input and the id in that call's output.
3
+ * its thread, the questions as its `ask` call's input and the id in that call's output.
4
4
  */
5
5
  export interface QuestionRef {
6
6
  readonly id: string
@@ -1100,11 +1100,14 @@ function summaryReasoning(
1100
1100
  * the provider cached. The instruction asks for text alone; a call the model makes anyway never
1101
1101
  * runs.
1102
1102
  */
1103
- function summaryTool(tool: Pick<ModelTool, "name" | "description" | "inputSchema">): ModelTool {
1103
+ function summaryTool(
1104
+ tool: Pick<ModelTool, "name" | "description" | "inputSchema" | "strict">
1105
+ ): ModelTool {
1104
1106
  return {
1105
1107
  name: tool.name,
1106
1108
  description: tool.description,
1107
1109
  inputSchema: tool.inputSchema,
1110
+ ...(tool.strict ? { strict: true } : {}),
1108
1111
  parseInput: (value) => value,
1109
1112
  execute: async () => {
1110
1113
  throw new Error("[SixbAgent] A context summary runs no tools.")
package/src/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { waitForAbort } from "./abort"
2
2
  export type { AgentWorkspacePromptContext } from "./agent-prompt"
3
3
  export { renderBoardPreviews } from "./artifacts/board-previews"
4
- export { createAskParentTool } from "./ask-parent-tool"
4
+ export { createAskParentTool } from "./ask-tool"
5
5
  export type { BackgroundCommandStatus } from "./background-commands"
6
6
  export {
7
7
  type ComputerBackgroundCommand,
@@ -19,6 +19,7 @@ import {
19
19
  type ConversationAgentRunRecord,
20
20
  coerceAgentRunFinishReason,
21
21
  } from "@sixb/core/storage"
22
+ import { stepAskedUser } from "./ask-tool"
22
23
  import { createAgentContextGuard } from "./context-guard"
23
24
  import { conversationModelMessages, conversationModelSettings } from "./conversation-messages"
24
25
  import { AgentContextCompactionError, throwIfExecutionLost } from "./errors"
@@ -245,6 +246,7 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
245
246
  try {
246
247
  let chunkIndex = 0
247
248
  let result: PausableModelLoopResult
249
+ let askedUser = false
248
250
  try {
249
251
  result = await runModelLoop({
250
252
  model: plan.model,
@@ -276,8 +278,12 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
276
278
  },
277
279
  // The approval records decide, never the tool output: the model can send a command's
278
280
  // output elsewhere, or print one of its own. A held call waits for the children still
279
- // at work: pausing ends the turn, and that would cancel them.
280
- pauseAfterStep: () => input.session.heldCalls.pausesAfterStep(),
281
+ // at work: pausing ends the turn, and that would cancel them. A question to the user ends
282
+ // the turn too: the answer is the user's next message.
283
+ pauseAfterStep: async (step) => {
284
+ if (stepAskedUser(step)) askedUser = true
285
+ return (await input.session.heldCalls.pausesAfterStep()) || askedUser
286
+ },
281
287
  })
282
288
  } catch (error) {
283
289
  const interrupted = await finalizeIfInterrupted(error)
@@ -340,10 +346,14 @@ export async function runAgentTurn(input: RunAgentTurnInput): Promise<AgentRunRe
340
346
  const interruptedWhileWaiting = await finalizeIfInterrupted()
341
347
  if (interruptedWhileWaiting) return interruptedWhileWaiting
342
348
 
349
+ // A turn that stopped on its question alone simply ends: nothing waits for a decision.
350
+ const held = await input.session.heldCalls.holdsRun()
343
351
  const finishReason =
344
- result.status === "paused" || (await input.session.heldCalls.holdsRun())
352
+ held || (result.status === "paused" && !askedUser)
345
353
  ? "awaiting_approval"
346
- : (coerceAgentRunFinishReason(result.finishReason) ?? "unknown")
354
+ : result.status === "paused"
355
+ ? "stop"
356
+ : (coerceAgentRunFinishReason(result.finishReason) ?? "unknown")
347
357
  const assistant: AgentMessage = { role: "assistant", parts: interruptedParts }
348
358
  const diagnostics = [
349
359
  outputLimitDiagnostic(finishReason),
package/src/run-child.ts CHANGED
@@ -14,7 +14,7 @@ import type {
14
14
  ExecutionRecord,
15
15
  SubagentRunRecord,
16
16
  } from "@sixb/core/storage"
17
- import { createAskParentTool } from "./ask-parent-tool"
17
+ import { createAskParentTool } from "./ask-tool"
18
18
  import { prepareAgentModel } from "./context-budget"
19
19
  import { isLostExecution } from "./errors"
20
20
  import { resolveRunPlan } from "./execution-plan"
@@ -18,6 +18,7 @@ import type {
18
18
  ExecutionRecord,
19
19
  SubagentRunRecord,
20
20
  } from "@sixb/core/storage"
21
+ import { createAskUserTool } from "./ask-tool"
21
22
  import { prepareAgentModel } from "./context-budget"
22
23
  import { AgentEnvironmentSaveError, AgentRequesterLeftThreadError, isLostExecution } from "./errors"
23
24
  import { resolveRunPlan } from "./execution-plan"
@@ -114,10 +115,12 @@ export async function runConversationTurn(input: {
114
115
  runner.startChild(child, family, environment.networkPolicy)
115
116
  }
116
117
  )
117
- const frameworkTools = await delegation.createTools()
118
+ // The Agent's own: its children, and its questions to the user, which end the turn.
119
+ const frameworkTools = [...(await delegation.createTools()), createAskUserTool()]
118
120
  environment = await createConversationAgentEnvironment({
119
121
  session,
120
122
  frameworkTools,
123
+ children: delegation.waitable(),
121
124
  thread: prepared.thread,
122
125
  ...(prepared.execution.requestedBy === undefined
123
126
  ? {}
@@ -87,10 +87,12 @@ import {
87
87
  } from "./subagent-context"
88
88
  import type { SubagentHistory } from "./subagent-continuation"
89
89
  import { agentThreadModelContext, type LoadedAgentThreadModelContext } from "./thread-context"
90
- import { createBashOutputTool, createBashStopTool } from "./tools/background"
90
+ import { createStopTool, createWaitTool, type WaitableChildren } from "./tools/background"
91
91
  import { createBashTool } from "./tools/bash"
92
+ import { createEditTool } from "./tools/edit"
93
+ import { FileReadLedger } from "./tools/file-writes"
92
94
  import { agentModelToolSpecs, fetchesWeb } from "./tools/model-spec"
93
- import { createReadTool } from "./tools/read"
95
+ import { createReadTool, READ_TOOL_SPEC } from "./tools/read"
94
96
  import {
95
97
  AgentToolResultMediaBridge,
96
98
  allocateInlineImages,
@@ -103,9 +105,10 @@ import {
103
105
  savedToolOutputFiles,
104
106
  ToolOutputFiles,
105
107
  } from "./tools/tool-outputs"
106
- import { createViewFileTool, VIEW_FILE_TOOL_SPEC } from "./tools/view-file"
108
+ import { LEGACY_VIEW_FILE_TOOL, type SandboxFileViewer } from "./tools/view-file"
107
109
  import { createWebFetchTool } from "./tools/web-fetch/tool"
108
110
  import { createWebSearchTool } from "./tools/web-search"
111
+ import { createWriteTool } from "./tools/write"
109
112
  import type { AgentTurnRuntime } from "./turn-runtime"
110
113
  import type { AgentExecutionContext, AgentRunFiles, AgentTurnContext } from "./types"
111
114
  import { prepareWorkflowInputAttachments } from "./workflow-input-attachments"
@@ -184,6 +187,8 @@ export interface CreateConversationAgentEnvironmentInput extends CreateAgentEnvi
184
187
  readonly history: AgentTurnHistory
185
188
  /** Framework-owned tools of the conversational Agent: delegation. */
186
189
  readonly frameworkTools?: readonly ModelTool[]
190
+ /** Its children, which `wait` and `stop` reach beside its background commands. */
191
+ readonly children?: WaitableChildren
187
192
  }
188
193
 
189
194
  export interface CreateSubagentEnvironmentInput extends CreateAgentEnvironmentInput {
@@ -198,7 +203,7 @@ export interface CreateSubagentEnvironmentInput extends CreateAgentEnvironmentIn
198
203
  readonly requestedBy?: Principal
199
204
  /** Its thread's messages, whose files are projected again, and the paused run it continues. */
200
205
  readonly history: SubagentHistory
201
- /** Framework-owned tools of a child: `ask_parent`. */
206
+ /** Framework-owned tools of a child: `ask`, to its parent. */
202
207
  readonly frameworkTools?: readonly ModelTool[]
203
208
  /** Weigh the thread before the first call, and compact it on the child's thread when needed. */
204
209
  readonly preflight?: { readonly budget: AgentContextBudget; readonly runtime: AgentTurnRuntime }
@@ -415,6 +420,7 @@ export async function createConversationAgentEnvironment(
415
420
  imageBudget,
416
421
  ontologyDocs,
417
422
  frameworkTools: input.frameworkTools,
423
+ ...(input.children ? { children: input.children } : {}),
418
424
  ...(memory ? { memory } : {}),
419
425
  ...(conversation === undefined ? {} : { conversation }),
420
426
  onDetachedTeardown: input.onDetachedTeardown,
@@ -814,6 +820,8 @@ interface AgentEnvironmentSetup
814
820
  readonly ontologyDocs?: RenderedOntologyDocs
815
821
  readonly errorDetails?: AgentErrorDetails
816
822
  readonly frameworkTools?: readonly ModelTool[]
823
+ /** The Agent's children, which `wait` and `stop` reach beside its background commands. */
824
+ readonly children?: WaitableChildren
817
825
  /**
818
826
  * A conversation, or a child of one, publishes artifacts into its conversation, through its
819
827
  * session, and edits them from their installed copies; other runs return text.
@@ -892,17 +900,15 @@ async function startAgentEnvironment(
892
900
  }),
893
901
  ]
894
902
 
895
- appendBuiltInTool(
896
- tools,
897
- createViewFileTool({
898
- resolveSandbox: () => ready,
899
- attachments: attachmentContext,
900
- registry: fileRegistry,
901
- filesForToolCall: ({ toolCallId, signal }) =>
902
- filesForToolCall({ toolName: "view_file", toolCallId, signal }),
903
- toolResultToModelOutput: (output) => mediaBridge.toModelOutput(output),
904
- })
905
- )
903
+ // How `read` shows an image, a PDF or another file that is not text: as itself, stored with
904
+ // the call, through the run's media bridge.
905
+ const fileViewer: SandboxFileViewer = {
906
+ attachments: attachmentContext,
907
+ registry: fileRegistry,
908
+ filesForToolCall: ({ toolCallId, signal }) =>
909
+ filesForToolCall({ toolName: READ_TOOL_SPEC.name, toolCallId, signal }),
910
+ toolResultToModelOutput: (output) => mediaBridge.toModelOutput(output),
911
+ }
906
912
  const resolveSandbox = () => ready
907
913
  // Its own budget: saving outputs never takes what published artifacts and tool files need.
908
914
  const toolOutputFiles = new ToolOutputFiles({
@@ -918,10 +924,14 @@ async function startAgentEnvironment(
918
924
  console.error("[SixbAgent] Could not stop the run's background commands:", error)
919
925
  })
920
926
  }
921
- appendBuiltInTool(tools, createReadTool(resolveSandbox))
927
+ // One per run: `edit` and `write` change only files this run read, as it read them.
928
+ const fileReads = new FileReadLedger()
929
+ appendBuiltInTool(tools, createReadTool(resolveSandbox, fileReads, fileViewer))
930
+ appendBuiltInTool(tools, createEditTool(resolveSandbox, fileReads))
931
+ appendBuiltInTool(tools, createWriteTool(resolveSandbox, fileReads))
922
932
  appendBuiltInTool(tools, createBashTool(resolveSandbox, background))
923
- appendBuiltInTool(tools, createBashOutputTool(resolveSandbox, background))
924
- appendBuiltInTool(tools, createBashStopTool(resolveSandbox, background))
933
+ appendBuiltInTool(tools, createWaitTool(resolveSandbox, background, input.children))
934
+ appendBuiltInTool(tools, createStopTool(resolveSandbox, background, input.children))
925
935
  if (plan.web?.search) {
926
936
  appendBuiltInTool(tools, createWebSearchTool({ search: input.webSearch, web: plan.web }))
927
937
  }
@@ -1141,11 +1151,16 @@ function agentSandboxPath(handle: AgentSandboxHandle, path: string): string {
1141
1151
  }
1142
1152
 
1143
1153
  /**
1144
- * The tools whose images reach the model after their step: the project's and `view_file`, whose
1145
- * outputs go through the run's media bridge. A replay asks the same of the stored trace.
1154
+ * The tools whose images reach the model after their step: the project's and `read`, whose
1155
+ * outputs go through the run's media bridge, and `view_file`, which earlier threads hold. A replay
1156
+ * asks the same of the stored trace.
1146
1157
  */
1147
1158
  function suppliesToolFiles(plan: Pick<ResolvedAgentExecutionPlan, "tools">): SuppliesToolFiles {
1148
- const names = new Set([...plan.tools.map((tool) => tool.name), VIEW_FILE_TOOL_SPEC.name])
1159
+ const names = new Set([
1160
+ ...plan.tools.map((tool) => tool.name),
1161
+ READ_TOOL_SPEC.name,
1162
+ LEGACY_VIEW_FILE_TOOL,
1163
+ ])
1149
1164
  return (toolName) => names.has(toolName)
1150
1165
  }
1151
1166
 
@@ -17,7 +17,7 @@ import {
17
17
  type SubagentRunRecord,
18
18
  } from "@sixb/core/storage"
19
19
  import { renderCurrentTime, sentSettings } from "./agent-prompt"
20
- import { unansweredQuestion } from "./ask-parent-tool"
20
+ import { unansweredQuestion } from "./ask-tool"
21
21
  import { storeChildOutputs } from "./child-files"
22
22
  import { createAgentContextGuard } from "./context-guard"
23
23
  import { throwIfExecutionLost } from "./errors"
@@ -84,7 +84,7 @@ export async function runSubagent(input: {
84
84
  readonly runFiles: AgentRunFiles
85
85
  /**
86
86
  * What its parent sends it while it runs, read before its next step, and the questions it asks,
87
- * through the inbox's `ask_parent` among its tools.
87
+ * through the inbox's `ask` among its tools.
88
88
  */
89
89
  readonly inbox: SubagentInbox
90
90
  }): Promise<SubagentRunRecord> {
@@ -262,7 +262,7 @@ async function settleSubagent(
262
262
 
263
263
  /**
264
264
  * Keep the child's outcome: its answer, what it wrote under `out/`, and what it did as its thread's
265
- * next message. A paused child keeps its files too, for the run that continues it; `wait_agent`
265
+ * next message. A paused child keeps its files too, for the run that continues it; `wait`
266
266
  * hands over only a finished child's, as an unfinished one's would pass for complete. Its `out/`
267
267
  * is stored even when its workspace is kept: a continuation that finds it lost gets it back.
268
268
  */