@sixb/agent 0.2.1 → 0.2.2

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 (76) hide show
  1. package/README.md +2 -1
  2. package/dist/agent-prompt.d.ts +13 -0
  3. package/dist/agent-prompt.d.ts.map +1 -1
  4. package/dist/agent-runtime/preflight.d.ts.map +1 -1
  5. package/dist/artifacts/layout-check/layout-check.d.ts.map +1 -1
  6. package/dist/background-commands.d.ts +95 -0
  7. package/dist/background-commands.d.ts.map +1 -0
  8. package/dist/background-notices.d.ts +31 -0
  9. package/dist/background-notices.d.ts.map +1 -0
  10. package/dist/computer-runner.d.ts +63 -2
  11. package/dist/computer-runner.d.ts.map +1 -1
  12. package/dist/context-compaction.d.ts +3 -0
  13. package/dist/context-compaction.d.ts.map +1 -1
  14. package/dist/execution-plan.d.ts +12 -2
  15. package/dist/execution-plan.d.ts.map +1 -1
  16. package/dist/index.d.ts +2 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +2287 -230
  19. package/dist/index.js.map +28 -18
  20. package/dist/login-shell.d.ts +16 -0
  21. package/dist/login-shell.d.ts.map +1 -0
  22. package/dist/run-child.d.ts +3 -0
  23. package/dist/run-child.d.ts.map +1 -1
  24. package/dist/run-conversation-turn.d.ts +6 -2
  25. package/dist/run-conversation-turn.d.ts.map +1 -1
  26. package/dist/run-environment.d.ts +12 -2
  27. package/dist/run-environment.d.ts.map +1 -1
  28. package/dist/run-sandbox.d.ts +23 -0
  29. package/dist/run-sandbox.d.ts.map +1 -1
  30. package/dist/sandbox-files.d.ts.map +1 -1
  31. package/dist/tools/background.d.ts +50 -0
  32. package/dist/tools/background.d.ts.map +1 -0
  33. package/dist/tools/bash.d.ts +12 -4
  34. package/dist/tools/bash.d.ts.map +1 -1
  35. package/dist/tools/model-spec.d.ts +9 -2
  36. package/dist/tools/model-spec.d.ts.map +1 -1
  37. package/dist/tools/tool-outputs.d.ts +12 -2
  38. package/dist/tools/tool-outputs.d.ts.map +1 -1
  39. package/dist/tools/web-fetch/cache.d.ts +33 -0
  40. package/dist/tools/web-fetch/cache.d.ts.map +1 -0
  41. package/dist/tools/web-fetch/html-markdown.d.ts +25 -0
  42. package/dist/tools/web-fetch/html-markdown.d.ts.map +1 -0
  43. package/dist/tools/web-fetch/network.d.ts +55 -0
  44. package/dist/tools/web-fetch/network.d.ts.map +1 -0
  45. package/dist/tools/web-fetch/tool.d.ts +96 -0
  46. package/dist/tools/web-fetch/tool.d.ts.map +1 -0
  47. package/dist/tools/web-search.d.ts +40 -0
  48. package/dist/tools/web-search.d.ts.map +1 -0
  49. package/dist/workspace-instructions.d.ts +15 -0
  50. package/dist/workspace-instructions.d.ts.map +1 -0
  51. package/package.json +13 -4
  52. package/src/agent-prompt.ts +60 -1
  53. package/src/agent-runtime/preflight.ts +2 -1
  54. package/src/artifacts/layout-check/layout-check.ts +4 -4
  55. package/src/background-commands.ts +573 -0
  56. package/src/background-notices.ts +178 -0
  57. package/src/computer-runner.ts +211 -9
  58. package/src/context-compaction.ts +4 -1
  59. package/src/execution-plan.ts +15 -2
  60. package/src/index.ts +3 -0
  61. package/src/login-shell.ts +18 -0
  62. package/src/run-child.ts +5 -0
  63. package/src/run-conversation-turn.ts +23 -4
  64. package/src/run-environment.ts +92 -12
  65. package/src/run-sandbox.ts +41 -0
  66. package/src/sandbox-files.ts +2 -1
  67. package/src/tools/background.ts +127 -0
  68. package/src/tools/bash.ts +80 -11
  69. package/src/tools/model-spec.ts +25 -3
  70. package/src/tools/tool-outputs.ts +46 -6
  71. package/src/tools/web-fetch/cache.ts +91 -0
  72. package/src/tools/web-fetch/html-markdown.ts +479 -0
  73. package/src/tools/web-fetch/network.ts +452 -0
  74. package/src/tools/web-fetch/tool.ts +619 -0
  75. package/src/tools/web-search.ts +139 -0
  76. package/src/workspace-instructions.ts +163 -0
@@ -0,0 +1,139 @@
1
+ import { AgentToolPublicError, type JsonValue } from "@sixb/core"
2
+ import {
3
+ type AgentRunModels,
4
+ type AgentRunWebPlan,
5
+ webDomainPolicy,
6
+ } from "@sixb/core/internal/agents"
7
+ import { isSixbError } from "@sixb/core/internal/errors"
8
+ import type { JsonObject, ModelTool, ModelToolOutput, WebSearchHit } from "@sixb/core/models"
9
+ import { AgentToolExecutionError } from "../errors"
10
+ import { agentToolErrorText } from "../model-adapters"
11
+
12
+ /** How many results one search asks for. */
13
+ const MAX_RESULTS = 8
14
+ const MAX_QUERY_CHARACTERS = 2_000
15
+
16
+ export const WEB_SEARCH_TOOL_SPEC = {
17
+ name: "web_search",
18
+ description:
19
+ "Search the web for current or external information. Returns up to 8 results, each a title, URL, date and snippet.",
20
+ inputSchema: {
21
+ type: "object",
22
+ properties: { query: { type: "string", minLength: 1, maxLength: MAX_QUERY_CHARACTERS } },
23
+ required: ["query"],
24
+ additionalProperties: false,
25
+ } satisfies JsonObject,
26
+ } as const
27
+
28
+ export interface WebSearchToolInput {
29
+ readonly query: string
30
+ }
31
+
32
+ /** What a search stores, and the app shows: its query and the results the domain lists kept. */
33
+ export interface WebSearchToolOutput {
34
+ readonly query: string
35
+ readonly results: readonly WebSearchHit[]
36
+ }
37
+
38
+ /**
39
+ * Search through the run's session, which calls the project's web search model where the project
40
+ * is, and drop the results its domain lists refuse.
41
+ */
42
+ export function createWebSearchTool(input: {
43
+ readonly search: AgentRunModels["webSearch"]
44
+ readonly web: AgentRunWebPlan
45
+ }): ModelTool<WebSearchToolInput> {
46
+ const { allowedDomains, blockedDomains } = input.web
47
+ const domains = {
48
+ ...(allowedDomains ? { allowedDomains } : {}),
49
+ ...(blockedDomains ? { blockedDomains } : {}),
50
+ }
51
+ const policy = webDomainPolicy(domains)
52
+
53
+ return {
54
+ ...WEB_SEARCH_TOOL_SPEC,
55
+ parseInput: parseWebSearchInput,
56
+ async execute({ query }, { signal }): Promise<JsonValue> {
57
+ let found: readonly WebSearchHit[]
58
+ try {
59
+ const result = await input.search({ query, maxResults: MAX_RESULTS, ...domains }, signal)
60
+ found = result.results
61
+ } catch (error) {
62
+ signal.throwIfAborted()
63
+ throw webSearchError(error)
64
+ }
65
+
66
+ // The domains reach the provider as a hint only: each result is checked here again.
67
+ const results = found.filter((hit) => !policy.refuses(new URL(hit.url)))
68
+ const output: WebSearchToolOutput = { query, results }
69
+ return output as unknown as JsonValue
70
+ },
71
+ toModelOutput: (output) => webSearchModelOutput(output as unknown as WebSearchToolOutput),
72
+ errorText: agentToolErrorText,
73
+ }
74
+ }
75
+
76
+ /**
77
+ * The results as the model reads them: a numbered list, wrapped as untrusted web content. Read
78
+ * from the stored output alone, so a replayed conversation sends the same bytes.
79
+ */
80
+ export function webSearchModelOutput(output: WebSearchToolOutput): ModelToolOutput {
81
+ if (output.results.length === 0) return { type: "text", value: "No results." }
82
+
83
+ const lines = output.results.map((hit, index) => {
84
+ const date = hit.publishedAt ? ` (${hit.publishedAt.slice(0, 10)})` : ""
85
+ const url = oneLine(hit.url)
86
+ const heading = `${index + 1}. ${oneLine(hit.title) || url} — ${url}${date}`
87
+ const snippet = oneLine(hit.snippet)
88
+ return snippet ? `${heading}\n ${snippet}` : heading
89
+ })
90
+
91
+ return {
92
+ type: "text",
93
+ value: `<web_content source="web_search" untrusted="true">\n${lines.join("\n")}\n</web_content>`,
94
+ }
95
+ }
96
+
97
+ function parseWebSearchInput(value: unknown): WebSearchToolInput {
98
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
99
+ throw publicError("input must be an object.")
100
+ }
101
+
102
+ for (const key of Object.keys(value)) {
103
+ if (key !== "query") throw publicError(`input contains unknown property '${key}'.`)
104
+ }
105
+
106
+ const query = (value as { readonly query?: unknown }).query
107
+ if (typeof query !== "string" || !query.trim()) {
108
+ throw publicError("query must be a nonempty string.")
109
+ }
110
+ if (query.length > MAX_QUERY_CHARACTERS) {
111
+ throw publicError(`query must be at most ${MAX_QUERY_CHARACTERS} characters.`)
112
+ }
113
+
114
+ return { query: query.trim() }
115
+ }
116
+
117
+ /** A limit refusal is the model's to know; anything else stays generic. */
118
+ function webSearchError(error: unknown): Error {
119
+ if (
120
+ isSixbError(error) &&
121
+ (error.code === "ai.usage_limit_exceeded" || error.code === "ai.usage_limit_unavailable")
122
+ ) {
123
+ return publicError("is blocked by the project's AI usage limits.")
124
+ }
125
+
126
+ return new AgentToolExecutionError("web_search", { cause: error })
127
+ }
128
+
129
+ /** Web text on one line, unable to close the wrapper it sits in. */
130
+ function oneLine(text: string): string {
131
+ return text
132
+ .replace(/\s+/g, " ")
133
+ .trim()
134
+ .replace(/<(\/?)web_content/gi, "&lt;$1web_content")
135
+ }
136
+
137
+ function publicError(message: string): AgentToolPublicError {
138
+ return new AgentToolPublicError(`[SixbAgent] web_search ${message}`)
139
+ }
@@ -0,0 +1,163 @@
1
+ import type { CommandResult, Sandbox } from "@sixb/core"
2
+ import type { WorkspaceInstructionsFile } from "./agent-prompt"
3
+
4
+ /** Past this many UTF-8 bytes in all, the files are cut: the root's come first, so they are kept. */
5
+ export const WORKSPACE_INSTRUCTIONS_MAX_BYTES = 32 * 1024
6
+
7
+ const READ_TIMEOUT_MS = 5_000
8
+
9
+ /**
10
+ * Read the instruction files a workspace carries: in each folder from its repository's root down
11
+ * to the working directory, `AGENTS.md`, else `CLAUDE.md`; outside a repository, the working
12
+ * directory's alone. One command, so it costs one round trip on every provider, and on a computer
13
+ * it reads the user's folder as the user.
14
+ *
15
+ * Never fails the run: a command that fails, times out or prints what cannot be parsed is warned
16
+ * about and reads as no files.
17
+ */
18
+ export async function readWorkspaceInstructions(
19
+ sandbox: Sandbox,
20
+ workingDirectory: string,
21
+ signal?: AbortSignal
22
+ ): Promise<readonly WorkspaceInstructionsFile[]> {
23
+ let result: CommandResult
24
+ try {
25
+ result = await sandbox.runCommand("bash", ["-c", READ_INSTRUCTIONS_SCRIPT], {
26
+ cwd: workingDirectory,
27
+ timeout: READ_TIMEOUT_MS,
28
+ ...(signal ? { signal } : {}),
29
+ })
30
+ } catch (error) {
31
+ // A run that ends while it reads has nothing to warn about.
32
+ if (!signal?.aborted) warn(error)
33
+ return []
34
+ }
35
+ if (signal?.aborted) return []
36
+
37
+ if (result.timedOut || result.exitCode !== 0) {
38
+ warn(
39
+ result.timedOut
40
+ ? `timed out after ${READ_TIMEOUT_MS} ms`
41
+ : result.stderr.trim() || `exited with code ${result.exitCode}`
42
+ )
43
+ return []
44
+ }
45
+
46
+ try {
47
+ return boundedFiles(parseRecords(result.stdout))
48
+ } catch (error) {
49
+ warn(error)
50
+ return []
51
+ }
52
+ }
53
+
54
+ /** One file as the script printed it: its path from the working directory, and its first bytes. */
55
+ interface InstructionsRecord {
56
+ readonly path: string
57
+ readonly bytes: Uint8Array
58
+ }
59
+
60
+ /** The script prints the working directory's file first: the root's comes first in the prompt. */
61
+ function parseRecords(stdout: string): InstructionsRecord[] {
62
+ const lines = stdout.split("\n").filter((line) => line !== "")
63
+
64
+ const records = lines.map((line) => {
65
+ const match = /^(\d+) (AGENTS\.md|CLAUDE\.md) ([A-Za-z0-9+/]*={0,2})$/.exec(line)
66
+ if (!match || match[3] === undefined || match[3].length % 4 !== 0) {
67
+ throw new Error("Invalid sandbox output.")
68
+ }
69
+
70
+ const up = Number(match[1])
71
+ return {
72
+ path: `${"../".repeat(up)}${match[2]}`,
73
+ bytes: new Uint8Array(Buffer.from(match[3], "base64")),
74
+ }
75
+ })
76
+
77
+ return records.reverse()
78
+ }
79
+
80
+ /**
81
+ * The files within the byte budget, in order. A file that crosses it is cut at its last whole line
82
+ * within what is left, and says where it goes on. A cut at a line leaves a few bytes: a later file
83
+ * that fits in them still comes whole, and one that does not is cut the same way.
84
+ */
85
+ function boundedFiles(records: readonly InstructionsRecord[]): WorkspaceInstructionsFile[] {
86
+ const decoder = new TextDecoder("utf-8", { fatal: true })
87
+ const files: WorkspaceInstructionsFile[] = []
88
+ let remaining = WORKSPACE_INSTRUCTIONS_MAX_BYTES
89
+
90
+ for (const { path, bytes } of records) {
91
+ if (bytes.includes(0)) {
92
+ warn(`'${path}' is binary, not UTF-8 text.`)
93
+ continue
94
+ }
95
+
96
+ const cut = bytes.byteLength > remaining ? cutPoint(bytes, remaining) : bytes.byteLength
97
+ const kept = bytes.subarray(0, cut)
98
+ let text: string
99
+ try {
100
+ text = decoder.decode(kept)
101
+ } catch {
102
+ warn(`'${path}' is not UTF-8 text.`)
103
+ continue
104
+ }
105
+ remaining -= cut
106
+
107
+ if (cut < bytes.byteLength) {
108
+ files.push({ path, text, continuesAtLine: kept.filter((byte) => byte === 10).length + 1 })
109
+ } else if (text.trim()) {
110
+ files.push({ path, text })
111
+ }
112
+ }
113
+
114
+ return files
115
+ }
116
+
117
+ /** After the last newline within `limit` bytes, else at the last character boundary. */
118
+ function cutPoint(bytes: Uint8Array, limit: number): number {
119
+ const newline = bytes.subarray(0, limit).lastIndexOf(10)
120
+ if (newline !== -1) return newline + 1
121
+
122
+ let cut = limit
123
+ // A UTF-8 continuation byte is 10xxxxxx: never cut before one.
124
+ while (cut > 0 && ((bytes[cut] ?? 0) & 0xc0) === 0x80) cut -= 1
125
+ return cut
126
+ }
127
+
128
+ function warn(reason: unknown): void {
129
+ console.warn("[SixbAgent] Could not read the workspace's instruction files:", reason)
130
+ }
131
+
132
+ /**
133
+ * Finds the repository's root (the nearest folder with `.git`, a directory or a worktree's file),
134
+ * then prints one line per file from the working directory up to it: how many folders up, the
135
+ * name, and at most one byte past the budget in base64, so a cut is seen.
136
+ */
137
+ const READ_INSTRUCTIONS_SCRIPT = `# sixb-read-workspace-instructions
138
+ set -u -o pipefail
139
+ for tool in head base64 tr dirname; do command -v "$tool" >/dev/null || exit 20; done
140
+ here="$(pwd -P)" || exit 21
141
+ root="$here"
142
+ dir="$here"
143
+ while :; do
144
+ if [ -e "$dir/.git" ]; then root="$dir"; break; fi
145
+ [ "$dir" = / ] && break
146
+ dir="$(dirname -- "$dir")"
147
+ done
148
+ up=0
149
+ dir="$here"
150
+ while :; do
151
+ for name in AGENTS.md CLAUDE.md; do
152
+ file="$dir/$name"
153
+ if [ -f "$file" ] && [ -r "$file" ]; then
154
+ printf '%s %s ' "$up" "$name"
155
+ head -c ${WORKSPACE_INSTRUCTIONS_MAX_BYTES + 1} -- "$file" | base64 | tr -d '\\n' || exit 22
156
+ printf '\\n'
157
+ break
158
+ fi
159
+ done
160
+ [ "$dir" = "$root" ] && break
161
+ dir="$(dirname -- "$dir")"
162
+ up=$((up + 1))
163
+ done`