@sixb/agent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -2
  3. package/dist/abort.d.ts +6 -0
  4. package/dist/abort.d.ts.map +1 -0
  5. package/dist/agent-prompt.d.ts +120 -0
  6. package/dist/agent-prompt.d.ts.map +1 -0
  7. package/dist/agent-runtime/errors.d.ts +13 -0
  8. package/dist/agent-runtime/errors.d.ts.map +1 -0
  9. package/dist/agent-runtime/preflight.d.ts +18 -0
  10. package/dist/agent-runtime/preflight.d.ts.map +1 -0
  11. package/dist/agent-runtime/profile.d.ts +14 -0
  12. package/dist/agent-runtime/profile.d.ts.map +1 -0
  13. package/dist/artifacts/layout-check/layout-check.d.ts +87 -0
  14. package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -0
  15. package/dist/artifacts/materialize.d.ts +115 -0
  16. package/dist/artifacts/materialize.d.ts.map +1 -0
  17. package/dist/artifacts/publish-tool.d.ts +86 -0
  18. package/dist/artifacts/publish-tool.d.ts.map +1 -0
  19. package/dist/ask-parent-tool.d.ts +36 -0
  20. package/dist/ask-parent-tool.d.ts.map +1 -0
  21. package/dist/attachments.d.ts +68 -0
  22. package/dist/attachments.d.ts.map +1 -0
  23. package/dist/child-files.d.ts +96 -0
  24. package/dist/child-files.d.ts.map +1 -0
  25. package/dist/child-questions.d.ts +24 -0
  26. package/dist/child-questions.d.ts.map +1 -0
  27. package/dist/computer-runner.d.ts +65 -0
  28. package/dist/computer-runner.d.ts.map +1 -0
  29. package/dist/context-budget.d.ts +28 -0
  30. package/dist/context-budget.d.ts.map +1 -0
  31. package/dist/context-compaction.d.ts +48 -0
  32. package/dist/context-compaction.d.ts.map +1 -0
  33. package/dist/conversation-memory.d.ts +21 -0
  34. package/dist/conversation-memory.d.ts.map +1 -0
  35. package/dist/errors.d.ts +46 -0
  36. package/dist/errors.d.ts.map +1 -0
  37. package/dist/execution-plan.d.ts +34 -0
  38. package/dist/execution-plan.d.ts.map +1 -0
  39. package/dist/failure.d.ts +14 -0
  40. package/dist/failure.d.ts.map +1 -0
  41. package/dist/family-mailbox.d.ts +60 -0
  42. package/dist/family-mailbox.d.ts.map +1 -0
  43. package/dist/file-ref.d.ts +6 -0
  44. package/dist/file-ref.d.ts.map +1 -0
  45. package/dist/image-attachments.d.ts +34 -0
  46. package/dist/image-attachments.d.ts.map +1 -0
  47. package/dist/index.d.ts +35 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +12168 -0
  50. package/dist/index.js.map +65 -0
  51. package/dist/message-authors.d.ts +34 -0
  52. package/dist/message-authors.d.ts.map +1 -0
  53. package/dist/message-times.d.ts +8 -0
  54. package/dist/message-times.d.ts.map +1 -0
  55. package/dist/model-adapters.d.ts +55 -0
  56. package/dist/model-adapters.d.ts.map +1 -0
  57. package/dist/model-lines.d.ts +16 -0
  58. package/dist/model-lines.d.ts.map +1 -0
  59. package/dist/requester.d.ts +15 -0
  60. package/dist/requester.d.ts.map +1 -0
  61. package/dist/run-agent-turn.d.ts +63 -0
  62. package/dist/run-agent-turn.d.ts.map +1 -0
  63. package/dist/run-child.d.ts +77 -0
  64. package/dist/run-child.d.ts.map +1 -0
  65. package/dist/run-conversation-turn.d.ts +42 -0
  66. package/dist/run-conversation-turn.d.ts.map +1 -0
  67. package/dist/run-credential.d.ts +22 -0
  68. package/dist/run-credential.d.ts.map +1 -0
  69. package/dist/run-environment.d.ts +115 -0
  70. package/dist/run-environment.d.ts.map +1 -0
  71. package/dist/run-fate.d.ts +15 -0
  72. package/dist/run-fate.d.ts.map +1 -0
  73. package/dist/run-sandbox.d.ts +60 -0
  74. package/dist/run-sandbox.d.ts.map +1 -0
  75. package/dist/run-subagent.d.ts +51 -0
  76. package/dist/run-subagent.d.ts.map +1 -0
  77. package/dist/run-workflow-agent-node.d.ts +41 -0
  78. package/dist/run-workflow-agent-node.d.ts.map +1 -0
  79. package/dist/sandbox-api-context.d.ts +34 -0
  80. package/dist/sandbox-api-context.d.ts.map +1 -0
  81. package/dist/sandbox-file-registry.d.ts +9 -0
  82. package/dist/sandbox-file-registry.d.ts.map +1 -0
  83. package/dist/sandbox-files.d.ts +71 -0
  84. package/dist/sandbox-files.d.ts.map +1 -0
  85. package/dist/sandbox-handle.d.ts +15 -0
  86. package/dist/sandbox-handle.d.ts.map +1 -0
  87. package/dist/sandbox-readiness.d.ts +8 -0
  88. package/dist/sandbox-readiness.d.ts.map +1 -0
  89. package/dist/skills/built-in.d.ts +15 -0
  90. package/dist/skills/built-in.d.ts.map +1 -0
  91. package/dist/subagent-continuation.d.ts +27 -0
  92. package/dist/subagent-continuation.d.ts.map +1 -0
  93. package/dist/subagent-inbox.d.ts +53 -0
  94. package/dist/subagent-inbox.d.ts.map +1 -0
  95. package/dist/subagent-tools.d.ts +282 -0
  96. package/dist/subagent-tools.d.ts.map +1 -0
  97. package/dist/thread-context.d.ts +12 -0
  98. package/dist/thread-context.d.ts.map +1 -0
  99. package/dist/tools/attachments.d.ts +11 -0
  100. package/dist/tools/attachments.d.ts.map +1 -0
  101. package/dist/tools/bash.d.ts +60 -0
  102. package/dist/tools/bash.d.ts.map +1 -0
  103. package/dist/tools/model-spec.d.ts +4 -0
  104. package/dist/tools/model-spec.d.ts.map +1 -0
  105. package/dist/tools/read.d.ts +43 -0
  106. package/dist/tools/read.d.ts.map +1 -0
  107. package/dist/tools/result-media.d.ts +22 -0
  108. package/dist/tools/result-media.d.ts.map +1 -0
  109. package/dist/tools/result-output.d.ts +18 -0
  110. package/dist/tools/result-output.d.ts.map +1 -0
  111. package/dist/tools/tool-files.d.ts +59 -0
  112. package/dist/tools/tool-files.d.ts.map +1 -0
  113. package/dist/tools/view-file.d.ts +40 -0
  114. package/dist/tools/view-file.d.ts.map +1 -0
  115. package/dist/tsconfig.json +5 -0
  116. package/dist/turn-runtime.d.ts +19 -0
  117. package/dist/turn-runtime.d.ts.map +1 -0
  118. package/dist/types.d.ts +76 -0
  119. package/dist/types.d.ts.map +1 -0
  120. package/dist/workflow-input-attachments.d.ts +18 -0
  121. package/dist/workflow-input-attachments.d.ts.map +1 -0
  122. package/package.json +59 -4
  123. package/src/abort.ts +40 -0
  124. package/src/agent-prompt.ts +758 -0
  125. package/src/agent-runtime/errors.ts +44 -0
  126. package/src/agent-runtime/preflight.ts +314 -0
  127. package/src/agent-runtime/profile.ts +23 -0
  128. package/src/artifacts/layout-check/check.cjs +478 -0
  129. package/src/artifacts/layout-check/layout-check.ts +460 -0
  130. package/src/artifacts/materialize.ts +380 -0
  131. package/src/artifacts/publish-tool.ts +700 -0
  132. package/src/ask-parent-tool.ts +100 -0
  133. package/src/attachments.ts +850 -0
  134. package/src/child-files.ts +540 -0
  135. package/src/child-questions.ts +42 -0
  136. package/src/computer-runner.ts +284 -0
  137. package/src/context-budget.ts +161 -0
  138. package/src/context-compaction.ts +529 -0
  139. package/src/conversation-memory.ts +45 -0
  140. package/src/errors.ts +85 -0
  141. package/src/execution-plan.ts +50 -0
  142. package/src/failure.ts +71 -0
  143. package/src/family-mailbox.ts +189 -0
  144. package/src/file-ref.ts +18 -0
  145. package/src/image-attachments.ts +322 -0
  146. package/src/index.ts +54 -0
  147. package/src/message-authors.ts +77 -0
  148. package/src/message-times.ts +21 -0
  149. package/src/model-adapters.ts +227 -0
  150. package/src/model-lines.ts +28 -0
  151. package/src/requester.ts +21 -0
  152. package/src/run-agent-turn.ts +347 -0
  153. package/src/run-child.ts +319 -0
  154. package/src/run-conversation-turn.ts +257 -0
  155. package/src/run-credential.ts +55 -0
  156. package/src/run-environment.ts +769 -0
  157. package/src/run-fate.ts +51 -0
  158. package/src/run-sandbox.ts +63 -0
  159. package/src/run-subagent.ts +347 -0
  160. package/src/run-workflow-agent-node.ts +270 -0
  161. package/src/sandbox-api-context.ts +234 -0
  162. package/src/sandbox-file-registry.ts +26 -0
  163. package/src/sandbox-files.ts +326 -0
  164. package/src/sandbox-handle.ts +19 -0
  165. package/src/sandbox-readiness.ts +22 -0
  166. package/src/skills/built-in.ts +183 -0
  167. package/src/skills/sixb-artifacts/SKILL.md +95 -0
  168. package/src/skills/sixb-artifacts/canvas.md +104 -0
  169. package/src/skills/sixb-artifacts/document.md +63 -0
  170. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/first-job.html +42 -0
  171. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/region.html +29 -0
  172. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/shared.css +35 -0
  173. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/boards/welcome.html +31 -0
  174. package/src/skills/sixb-artifacts/examples/canvas/onboarding-flow/canvas.json +107 -0
  175. package/src/skills/sixb-artifacts/examples/canvas/retro/canvas.json +158 -0
  176. package/src/skills/sixb-artifacts/examples/document/incident-report/document.md +35 -0
  177. package/src/skills/sixb-artifacts/examples/document/operations-review/document.md +41 -0
  178. package/src/skills/sixb-artifacts/examples/document/operations-review/figures/restorations.svg +1 -0
  179. package/src/skills/sixb-artifacts/examples/page/collections-desk/index.html +169 -0
  180. package/src/skills/sixb-artifacts/examples/page/collections-desk/queries/overdue.json +13 -0
  181. package/src/skills/sixb-artifacts/examples/page/dispatch-board/data/dispatch.json +234 -0
  182. package/src/skills/sixb-artifacts/examples/page/dispatch-board/index.html +245 -0
  183. package/src/skills/sixb-artifacts/examples/page/fleet-planner/data/plan.json +53 -0
  184. package/src/skills/sixb-artifacts/examples/page/fleet-planner/index.html +462 -0
  185. package/src/skills/sixb-artifacts/examples/page/service-explorer/data/service.json +276 -0
  186. package/src/skills/sixb-artifacts/examples/page/service-explorer/index.html +549 -0
  187. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/queries/overdue.json +13 -0
  188. package/src/skills/sixb-artifacts/examples/sheet/overdue-invoices/workbook.json +30 -0
  189. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Inventory.csv +13 -0
  190. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/sheets/Spend.csv +6 -0
  191. package/src/skills/sixb-artifacts/examples/sheet/parts-inventory/workbook.json +47 -0
  192. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Quarters.csv +5 -0
  193. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/sheets/Regions.csv +5 -0
  194. package/src/skills/sixb-artifacts/examples/sheet/service-metrics/workbook.json +78 -0
  195. package/src/skills/sixb-artifacts/examples/slides/launch-plan/index.html +63 -0
  196. package/src/skills/sixb-artifacts/examples/slides/q3-review/index.html +133 -0
  197. package/src/skills/sixb-artifacts/file.md +17 -0
  198. package/src/skills/sixb-artifacts/page.md +215 -0
  199. package/src/skills/sixb-artifacts/queries.md +66 -0
  200. package/src/skills/sixb-artifacts/references.md +68 -0
  201. package/src/skills/sixb-artifacts/sheet.md +223 -0
  202. package/src/skills/sixb-artifacts/slides.md +137 -0
  203. package/src/skills/sixb-memory/SKILL.md +68 -0
  204. package/src/skills/text-assets.d.ts +25 -0
  205. package/src/subagent-continuation.ts +51 -0
  206. package/src/subagent-inbox.ts +101 -0
  207. package/src/subagent-tools.ts +1609 -0
  208. package/src/thread-context.ts +25 -0
  209. package/src/tools/attachments.ts +28 -0
  210. package/src/tools/bash.ts +217 -0
  211. package/src/tools/model-spec.ts +22 -0
  212. package/src/tools/read.ts +262 -0
  213. package/src/tools/result-media.ts +147 -0
  214. package/src/tools/result-output.ts +44 -0
  215. package/src/tools/tool-files.ts +204 -0
  216. package/src/tools/view-file.ts +155 -0
  217. package/src/turn-runtime.ts +33 -0
  218. package/src/types.ts +79 -0
  219. package/src/workflow-input-attachments.ts +140 -0
package/src/index.ts ADDED
@@ -0,0 +1,54 @@
1
+ export { waitForAbort } from "./abort"
2
+ export type { AgentWorkspacePromptContext } from "./agent-prompt"
3
+ export { createAskParentTool } from "./ask-parent-tool"
4
+ export {
5
+ ComputerRunner,
6
+ type ComputerRunnerOptions,
7
+ type OpenComputerSandbox,
8
+ } from "./computer-runner"
9
+ export { prepareAgentModel } from "./context-budget"
10
+ export {
11
+ AgentEnvironmentSaveError,
12
+ AgentRequesterLeftThreadError,
13
+ isLostExecution,
14
+ } from "./errors"
15
+ export { type ResolvedAgentExecutionPlan, resolveRunPlan } from "./execution-plan"
16
+ export type { AgentRunFailure } from "./failure"
17
+ export { toAgentExecutionFailure, toAgentRunFailure } from "./failure"
18
+ export type { FamilyMailbox } from "./family-mailbox"
19
+ export type { ConversationReaders } from "./message-authors"
20
+ export type { AgentToolCaller } from "./model-adapters"
21
+ export { agentRequester } from "./requester"
22
+ export { runAgentTurn, stoppedByWorker } from "./run-agent-turn"
23
+ export { type ChildParent, ChildRunner, type ChildRunnerHost } from "./run-child"
24
+ export { type ConversationTurnRunner, runConversationTurn } from "./run-conversation-turn"
25
+ export { runApiCredential, runTokenFor } from "./run-credential"
26
+ export type {
27
+ AgentExecutionEnvironment,
28
+ ConversationAgentExecutionEnvironment,
29
+ OpenedRunSandbox,
30
+ OpenRunSandbox,
31
+ } from "./run-environment"
32
+ export {
33
+ createConversationAgentEnvironment,
34
+ createSubagentEnvironment,
35
+ createWorkflowAgentNodeEnvironment,
36
+ } from "./run-environment"
37
+ export { agentRunFailureDetails, recordFate } from "./run-fate"
38
+ export type { AcquiredRunSandbox, BeforeFinalizeOptions, RunSandbox } from "./run-sandbox"
39
+ export { SANDBOX_CONTEXT_DIRECTORY } from "./run-sandbox"
40
+ export type { SubagentWork } from "./run-subagent"
41
+ export { runSubagent } from "./run-subagent"
42
+ export type { WorkflowAgentFailurePhase } from "./run-workflow-agent-node"
43
+ export { runWorkflowAgentNode, WorkflowAgentNodeExecutionError } from "./run-workflow-agent-node"
44
+ export { withBuiltInSkills } from "./skills/built-in"
45
+ export { SubagentInbox } from "./subagent-inbox"
46
+ export type { TurnDelegation } from "./subagent-tools"
47
+ export { SubagentCoordinator } from "./subagent-tools"
48
+ export { workflowInputToolAttachments } from "./tools/attachments"
49
+ export type { AgentTurnRuntime } from "./turn-runtime"
50
+ export { createAgentTurnRuntime } from "./turn-runtime"
51
+ export type {
52
+ AgentExecutionContext,
53
+ AgentRunSettings,
54
+ } from "./types"
@@ -0,0 +1,77 @@
1
+ import { type Principal, principalsEqual, type UserPrincipal } from "@sixb/core"
2
+ import type { AgentMessageRecord, AgentThreadRecord } from "@sixb/core/storage"
3
+ import {
4
+ type ConversationPerson,
5
+ renderConversationPeople,
6
+ renderMessageAuthor,
7
+ } from "./agent-prompt"
8
+
9
+ /** What the model reads of who writes in a conversation. Nothing of it is stored or shown. */
10
+ export interface ConversationAuthors {
11
+ /** Who takes part, for the newest user message only; absent in a one-person conversation. */
12
+ readonly section?: string
13
+ /** The `<sixb_author>` closing each retained user message, by message id. */
14
+ readonly byMessageId: ReadonlyMap<string, string>
15
+ }
16
+
17
+ const ALONE: ConversationAuthors = { byMessageId: new Map() }
18
+
19
+ /**
20
+ * A thread with the participants who can read it now: the people the model is told about, with
21
+ * their display names as the turn read them (`AgentTurnContext.readers` and `names`).
22
+ */
23
+ export interface ConversationReaders {
24
+ readonly thread: AgentThreadRecord
25
+ readonly participants: readonly UserPrincipal[]
26
+ readonly names: Readonly<Record<string, string>>
27
+ }
28
+
29
+ /**
30
+ * Who wrote each retained user message, when the thread has participants or several people wrote
31
+ * in it; nothing in a conversation its owner holds alone, so its messages do not change.
32
+ *
33
+ * Each message's author derives from stored data, so a turn replays the bytes the previous one
34
+ * sent. They change only when someone renames their account. The section naming who takes part
35
+ * rides on the newest user message: on the next turn only that message, the history's tail, loses
36
+ * it.
37
+ */
38
+ export function conversationAuthors(input: {
39
+ readonly conversation: ConversationReaders
40
+ readonly messages: readonly AgentMessageRecord[]
41
+ }): ConversationAuthors {
42
+ const { thread, participants, names } = input.conversation
43
+
44
+ const authored = input.messages.filter(
45
+ (message): message is AgentMessageRecord & { authorPrincipal: Principal } =>
46
+ message.role === "user" && message.authorPrincipal !== undefined
47
+ )
48
+ const owner = thread.ownerPrincipal
49
+ const someoneElseWrote = authored.some(
50
+ (message) => !principalsEqual(message.authorPrincipal, owner)
51
+ )
52
+ if (participants.length === 0 && !someoneElseWrote) return ALONE
53
+
54
+ // Each user goes by their display name; anyone else, or a user without one, by their id.
55
+ const personOf = (principal: Principal): ConversationPerson => {
56
+ const name = principal.type === "user" ? names[`user:${principal.id}`] : undefined
57
+ return name ? { id: principal.id, name } : { id: principal.id }
58
+ }
59
+
60
+ return {
61
+ section: renderConversationPeople({
62
+ owner: personOf(owner),
63
+ participants: participants.map(personOf),
64
+ }),
65
+ byMessageId: new Map(
66
+ authored.map((message) => [
67
+ message.id,
68
+ renderMessageAuthor(personOf(message.authorPrincipal)),
69
+ ])
70
+ ),
71
+ }
72
+ }
73
+
74
+ /** Everything the authors add to the model input, for its token estimate. */
75
+ export function conversationAuthorsText(authors: ConversationAuthors): string {
76
+ return [authors.section ?? "", ...authors.byMessageId.values()].join("\n")
77
+ }
@@ -0,0 +1,21 @@
1
+ import type { AgentTurnHistory } from "@sixb/core/internal/agents"
2
+ import { renderCurrentTime } from "./agent-prompt"
3
+
4
+ /**
5
+ * The `<sixb_current_time>` closing each retained user message: when it was sent, in the time zone
6
+ * of the run that answered it (the project's when that run captured none). Stored data only, so
7
+ * every later run replays the same bytes and the history stays a cacheable prefix.
8
+ */
9
+ export function userMessageTimes(
10
+ history: AgentTurnHistory,
11
+ projectTimeZone: string
12
+ ): ReadonlyMap<string, string> {
13
+ return new Map(
14
+ history.messages
15
+ .filter((message) => message.role === "user")
16
+ .map((message) => [
17
+ message.id,
18
+ renderCurrentTime(message.createdAt, history.sentTimeZones[message.id] ?? projectTimeZone),
19
+ ])
20
+ )
21
+ }
@@ -0,0 +1,227 @@
1
+ import type { AgentMessagePart, JsonValue } from "@sixb/core"
2
+ import { AgentToolPublicError } from "@sixb/core"
3
+ import {
4
+ type AgentToolCall,
5
+ type AgentToolCallFile,
6
+ type AgentToolCallOptions,
7
+ type AgentToolCallResult,
8
+ AgentToolResultValidationError,
9
+ type AgentToolSpec,
10
+ } from "@sixb/core/internal/agents"
11
+ import { createSixbError } from "@sixb/core/internal/errors"
12
+ import type {
13
+ ModelAssistantPart,
14
+ ModelStep,
15
+ ModelTool,
16
+ ModelToolResultPart,
17
+ } from "@sixb/core/models"
18
+ import { AgentToolExecutionError, AgentToolOutputError } from "./errors"
19
+ import type { AgentToolModelOutput } from "./tools/result-output"
20
+
21
+ export type AgentErrorDetails =
22
+ | { readonly threadId: string; readonly runId: string }
23
+ | { readonly parentRunId: string; readonly runId: string }
24
+ | { readonly workflowId: string; readonly agentStepId: string; readonly runId: string }
25
+ | {
26
+ readonly agentStepId: string
27
+ readonly workflowId: string
28
+ readonly workflowRunId: string
29
+ readonly nodeRunId: string
30
+ }
31
+
32
+ /** How a run calls a project tool: through its session, or for a workflow step in the worker. */
33
+ export type AgentToolCaller = (
34
+ call: AgentToolCall,
35
+ options: AgentToolCallOptions
36
+ ) => Promise<AgentToolCallResult>
37
+
38
+ interface ProjectModelToolsInput {
39
+ readonly specs: readonly AgentToolSpec[]
40
+ readonly runId: string
41
+ readonly callTool: AgentToolCaller
42
+ /** The bytes the run's file budget has left, which a call's files may take. */
43
+ readonly fileBytesLeft: () => number
44
+ /** Copy the files a call stored into the sandbox, before the model reads its output. */
45
+ readonly installFiles: (input: {
46
+ readonly toolName: string
47
+ readonly files: readonly AgentToolCallFile[]
48
+ readonly signal: AbortSignal
49
+ }) => Promise<void>
50
+ readonly toolResultToModelOutput: (input: {
51
+ readonly output: JsonValue
52
+ readonly signal: AbortSignal
53
+ readonly toolCallId: string
54
+ }) => AgentToolModelOutput | Promise<AgentToolModelOutput>
55
+ readonly errorDetails?: AgentErrorDetails
56
+ }
57
+
58
+ /**
59
+ * The project's tools as the model is offered them. A call runs where the project is, through
60
+ * `callTool`, which checks its input against the tool's schema; the files it stored are copied into
61
+ * the sandbox before the model reads its output.
62
+ */
63
+ export function projectModelTools(input: ProjectModelToolsInput): readonly ModelTool[] {
64
+ const names = new Set<string>()
65
+ return input.specs.map((spec) => {
66
+ if (names.has(spec.name)) {
67
+ throw createSixbError(
68
+ "internal.unexpected",
69
+ `[SixbAgent] Agent run '${input.runId}' has duplicate selected tool name '${spec.name}'.`,
70
+ input.errorDetails === undefined ? undefined : { details: input.errorDetails }
71
+ )
72
+ }
73
+ names.add(spec.name)
74
+ return projectModelTool(spec, input)
75
+ })
76
+ }
77
+
78
+ function projectModelTool(
79
+ spec: AgentToolSpec,
80
+ context: Omit<ProjectModelToolsInput, "specs">
81
+ ): ModelTool<Readonly<Record<string, unknown>>> {
82
+ return {
83
+ ...spec,
84
+ parseInput(value) {
85
+ // The tool's schema is checked where it runs; the loop hands over a JSON object.
86
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
87
+ throw new TypeError(`[SixbAgent] Agent tool '${spec.name}' input must be a JSON object.`)
88
+ }
89
+ return value as Readonly<Record<string, unknown>>
90
+ },
91
+ async execute(toolInput, { signal, toolCallId }) {
92
+ let result: AgentToolCallResult
93
+ try {
94
+ result = await context.callTool(
95
+ { toolName: spec.name, toolCallId, input: toolInput },
96
+ { signal, maxFileBytes: context.fileBytesLeft() }
97
+ )
98
+ } catch (error) {
99
+ if (error instanceof AgentToolResultValidationError) {
100
+ throw new AgentToolOutputError(spec.name, error.reason, { cause: error })
101
+ }
102
+ if (error instanceof AgentToolPublicError) throw error
103
+ throw new AgentToolExecutionError(spec.name, { cause: error })
104
+ }
105
+ await context.installFiles({ toolName: spec.name, files: result.files, signal })
106
+ return result.output
107
+ },
108
+ toModelOutput(output, { signal, toolCallId }) {
109
+ return context.toolResultToModelOutput({ output, signal, toolCallId })
110
+ },
111
+ errorText: agentToolErrorText,
112
+ }
113
+ }
114
+
115
+ type ToolOutcome =
116
+ | { readonly state: "output-available"; readonly output: JsonValue }
117
+ | { readonly state: "output-error"; readonly errorText: string }
118
+
119
+ /** Project validated model-loop steps into Sixb's durable trace contract. */
120
+ export function agentTraceFromModelSteps(
121
+ steps: readonly ModelStep[],
122
+ errorDetails?: AgentErrorDetails
123
+ ): readonly AgentMessagePart[] {
124
+ return steps.flatMap((step) => tracePartsFromModelContent(step.content, errorDetails))
125
+ }
126
+
127
+ /** Convert an aborted model loop, retaining only coherent content from its in-flight step. */
128
+ export function agentTraceFromPartialModelLoop(
129
+ steps: readonly ModelStep[],
130
+ partialContent: readonly ModelAssistantPart[],
131
+ errorDetails?: AgentErrorDetails
132
+ ): readonly AgentMessagePart[] {
133
+ return [
134
+ ...agentTraceFromModelSteps(steps, errorDetails),
135
+ ...(partialContent.length === 0
136
+ ? []
137
+ : tracePartsFromModelContent(partialContent, errorDetails, "Tool execution was cancelled.")),
138
+ ]
139
+ }
140
+
141
+ function tracePartsFromModelContent(
142
+ content: readonly ModelAssistantPart[],
143
+ errorDetails?: AgentErrorDetails,
144
+ missingToolResultText = "Tool call did not produce a result."
145
+ ): AgentMessagePart[] {
146
+ const results = new Map(
147
+ content.filter((part) => part.type === "tool-result").map((part) => [part.toolCallId, part])
148
+ )
149
+ return [
150
+ { type: "step-start" },
151
+ ...content.flatMap((part): AgentMessagePart[] => {
152
+ switch (part.type) {
153
+ case "text":
154
+ case "reasoning": {
155
+ return [
156
+ {
157
+ type: part.type,
158
+ text: part.text,
159
+ ...(part.providerData === undefined ? {} : { providerMetadata: part.providerData }),
160
+ },
161
+ ]
162
+ }
163
+ case "provider-state":
164
+ return [
165
+ {
166
+ type: "provider-state",
167
+ providerId: part.providerId,
168
+ data: part.data,
169
+ },
170
+ ]
171
+ case "tool-call": {
172
+ return [
173
+ {
174
+ type: "tool-call",
175
+ ...(part.dynamic === true ? { dynamic: true } : {}),
176
+ toolCallId: part.toolCallId,
177
+ toolName: part.toolName,
178
+ input: part.input,
179
+ ...(part.providerExecuted === undefined
180
+ ? {}
181
+ : { providerExecuted: part.providerExecuted }),
182
+ ...(part.providerData === undefined ? {} : { providerMetadata: part.providerData }),
183
+ ...toolOutcome(results.get(part.toolCallId), missingToolResultText),
184
+ },
185
+ ]
186
+ }
187
+ case "tool-result":
188
+ return []
189
+ default:
190
+ return assertUnreachableModelPart(part, errorDetails)
191
+ }
192
+ }),
193
+ ]
194
+ }
195
+
196
+ function toolOutcome(
197
+ result: ModelToolResultPart | undefined,
198
+ missingResultText: string
199
+ ): ToolOutcome {
200
+ if (!result) return { state: "output-error", errorText: missingResultText }
201
+ if (result.originalOutput !== undefined) {
202
+ return { state: "output-available", output: result.originalOutput }
203
+ }
204
+ const { output } = result
205
+ switch (output.type) {
206
+ case "text":
207
+ case "json":
208
+ return { state: "output-available", output: output.value }
209
+ case "error-text":
210
+ return { state: "output-error", errorText: output.value }
211
+ case "error-json":
212
+ return { state: "output-error", errorText: JSON.stringify(output.value) }
213
+ }
214
+ }
215
+
216
+ function assertUnreachableModelPart(part: never, errorDetails?: AgentErrorDetails): never {
217
+ throw createSixbError(
218
+ "internal.unexpected",
219
+ `[SixbAgent] Model trace content '${(part as { type?: unknown }).type}' is not supported.`,
220
+ errorDetails === undefined ? undefined : { details: errorDetails }
221
+ )
222
+ }
223
+
224
+ /** Expose only failures that the tool author explicitly marked as safe for the model and storage. */
225
+ export function agentToolErrorText(error: unknown): string {
226
+ return error instanceof AgentToolPublicError ? error.message : "An error occurred."
227
+ }
@@ -0,0 +1,28 @@
1
+ import type { LanguageModelTier } from "@sixb/core"
2
+
3
+ /**
4
+ * One language model on one line, as the prompt lists the models the Agent can ask or delegate
5
+ * to: under its tier, else as a list item, then its name, what the caller adds about it, and its
6
+ * description.
7
+ */
8
+ export function renderModelLine(input: {
9
+ readonly tier?: LanguageModelTier
10
+ /** How the caller names the model, such as the reference a command takes. */
11
+ readonly reference: string
12
+ readonly name?: string
13
+ /** Written as given between the name and the description, such as `(default; tools)`. */
14
+ readonly details?: string
15
+ readonly description?: string
16
+ }): string {
17
+ const name = input.name === undefined ? "" : ` ${oneLine(input.name)}`
18
+ const details = input.details === undefined ? "" : ` ${input.details}`
19
+ const description = input.description === undefined ? "" : `: ${oneLine(input.description)}`
20
+ const line = `${input.reference}${name}${details}${description}`
21
+
22
+ return input.tier === undefined ? `- ${line}` : `${input.tier.padEnd(10)}${line}`
23
+ }
24
+
25
+ // A provider's catalog text may span lines; each model keeps to one.
26
+ function oneLine(text: string): string {
27
+ return text.replace(/\s+/g, " ").trim()
28
+ }
@@ -0,0 +1,21 @@
1
+ import type { AuthorizablePrincipal } from "@sixb/core"
2
+
3
+ /** Who an Agent run works for, as its prompt names them. */
4
+ export type AgentRequester =
5
+ | { readonly type: "user"; readonly id: string; readonly displayName?: string }
6
+ | { readonly type: "serviceAccount" }
7
+
8
+ /**
9
+ * The requester of an Agent execution: the user, with their display name as the run read it when
10
+ * it started, or a service account. A renamed user is named correctly from the next run.
11
+ */
12
+ export function agentRequester(
13
+ requestedBy: AuthorizablePrincipal | undefined,
14
+ names: Readonly<Record<string, string>>
15
+ ): AgentRequester | undefined {
16
+ if (requestedBy === undefined) return undefined
17
+ if (requestedBy.type === "serviceAccount") return { type: "serviceAccount" }
18
+
19
+ const displayName = names[`user:${requestedBy.id}`]?.trim()
20
+ return { type: "user", id: requestedBy.id, ...(displayName ? { displayName } : {}) }
21
+ }