@h-sandbox/deepagents 0.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,204 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
204
+ Copyright 2026 Harakiri Sandbox contributors.
package/README.md ADDED
@@ -0,0 +1,209 @@
1
+ # Harakiri Sandbox for Deep Agents
2
+
3
+ An optional TypeScript backend for [Deep Agents](https://docs.langchain.com/oss/javascript/deepagents/sandboxes).
4
+ The framework owns planning and tool selection. Harakiri owns sandbox execution,
5
+ files, lifecycle and policy. Your application owns identity, checkpoints and
6
+ result verification. No framework dependencies are added to the core SDK.
7
+
8
+ ## Start with Deep Agents
9
+
10
+ The integration point in an existing Deep Agents application is its `backend`:
11
+
12
+ ```ts
13
+ import { createDeepAgent } from "deepagents";
14
+ import { HarakiriSandboxBackend } from "@h-sandbox/deepagents";
15
+
16
+ // Supply your model and a ready, application-owned Harakiri sandbox.
17
+ const agent = createDeepAgent({
18
+ model,
19
+ backend: new HarakiriSandboxBackend(sandbox)
20
+ });
21
+ ```
22
+
23
+ This is a **sandbox-backed agent**: the agent loop, model calls and checkpoints
24
+ run in your application; the framework's shell and filesystem tools run in the
25
+ sandbox. It does not deploy your entire agent process into the sandbox. Custom
26
+ tools you register yourself are not automatically isolated: local shell or file
27
+ callbacks still run on your application host.
28
+
29
+ For a complete, executable workflow, start with
30
+ [the single-file repository repair](https://github.com/nabilblk/h-sandbox/blob/main/packages/deepagents/examples/run-repair.ts).
31
+ It imports the real Deep Agents SDK, receives a Harakiri backend, fixes a bug,
32
+ verifies the original tests and returns a diff after confirmed cleanup.
33
+
34
+ ## Availability
35
+
36
+ **Unpublished release candidate.** Native tools and an independently verified
37
+ model repair have passed; final release checks and npm publication are pending.
38
+ Evaluate the adapter archive with the exact published SDK below. Node 20+ is
39
+ the consumer target; repository tooling uses Node 22+.
40
+
41
+ ```bash
42
+ # In a reviewed Harakiri checkout:
43
+ pnpm install --frozen-lockfile
44
+ pnpm --filter @h-sandbox/deepagents build
45
+ mkdir -p /tmp/harakiri-framework-candidate
46
+ pnpm --filter @h-sandbox/deepagents pack --pack-destination /tmp/harakiri-framework-candidate
47
+
48
+ # In your server-side application, using the resulting adapter archive path:
49
+ npm install --save-exact @h-sandbox/sdk@0.5.0-rc.11 "$DEEPAGENTS_TARBALL" \
50
+ deepagents@1.14.0 langchain@1.5.11 @langchain/core@1.2.12 \
51
+ @langchain/langgraph@1.4.17 langsmith@0.9.0 zod@4.4.3
52
+ ```
53
+
54
+ The tested peers are **SDK 0.5.0-rc.11 and Deep Agents 1.14.0**, both exact because
55
+ these preview contracts are evolving. The reviewed archive identifies this
56
+ adapter candidate. Commit your application's lockfile. Other framework or SDK
57
+ versions need a fresh compatibility run.
58
+
59
+ ## Connect an Existing Sandbox
60
+
61
+ ```ts
62
+ import { HarakiriClient } from "@h-sandbox/sdk";
63
+ import { HarakiriSandboxBackend } from "@h-sandbox/deepagents";
64
+ import { createDeepAgent } from "deepagents";
65
+ import { initChatModel } from "langchain/chat_models/universal";
66
+
67
+ const client = HarakiriClient.fromEnv();
68
+ const modelName = process.env.HARAKIRI_AGENT_MODEL;
69
+ const sandboxId = process.env.HARAKIRI_SANDBOX_ID;
70
+ if (!modelName || !sandboxId) throw new Error("Select a model and an existing sandbox.");
71
+
72
+ // Install the selected model provider package in this application first.
73
+ const model = await initChatModel(modelName);
74
+ const sandbox = await client.sandboxes.connect(sandboxId);
75
+ await sandbox.wait({ timeoutMs: 180_000 });
76
+ const backend = new HarakiriSandboxBackend(sandbox, { timeoutMs: 60_000 });
77
+ const agent = createDeepAgent({ model, backend, subagents: [], memory: [], skills: [] });
78
+ const result = await agent.invoke({
79
+ messages: [{ role: "user", content: "Run python3 --version in the sandbox." }]
80
+ }, { recursionLimit: 20 });
81
+ console.log(result.messages.at(-1)?.content);
82
+ // Borrowed sandbox: its application owner decides when to terminate it.
83
+ ```
84
+
85
+ Set `HARAKIRI_API_URL` to your installation and supply `HARAKIRI_API_KEY` through
86
+ your server's secret configuration. Use `sandboxes:read` and `sandboxes:write`.
87
+ Never send that key to a browser, an LLM, graph state or the sandbox. Model
88
+ credentials stay in the application process, not sandbox environment variables.
89
+ Do not log complete graph state: prompts, tool outputs and files may be sensitive.
90
+
91
+ ## Ownership and Recovery
92
+
93
+ `new HarakiriSandboxBackend(sandbox)` borrows exactly one sandbox. It does not
94
+ create, resume, change egress or terminate it. `backend.reference` contains only
95
+ `sandboxId`; `execute()` returns an additional `{ sandboxId, commandId }` reference.
96
+ Persist references in a tenant/thread-scoped record, then `backend.observe(ref)`
97
+ to observe an existing command without resubmitting it.
98
+
99
+ For finite, disposable jobs, `withHarakiriSandbox(client, input, task, options)`
100
+ creates once, waits for readiness, runs the task and confirms termination and
101
+ capacity release. It cleans up even when readiness or the task fails. It rejects
102
+ caller idempotency keys and create-time Git source because they can refer to an
103
+ existing resource or obscure ownership. `HarakiriTaskCleanupError` retains the
104
+ sandbox ID and both workload and cleanup failures. TTL remains a crash safety net.
105
+
106
+ Do not use that helper across a real human approval pause: a paused graph returns
107
+ control, so the helper would clean up. Use an application-owned sandbox instead.
108
+ After a cleanup timeout, `sandbox.waitForTermination()` observes without another DELETE.
109
+
110
+ ## Examples and Verification
111
+
112
+ From this reviewed checkout after building:
113
+
114
+ ```bash
115
+ # Requires your explicit API URL/key and installed template, not a maintainer URL.
116
+ export HARAKIRI_TEMPLATE="your-linux-template"
117
+ # Install and configure the chosen LangChain model integration first.
118
+ export HARAKIRI_AGENT_MODEL="provider:your-tool-capable-model"
119
+ pnpm --filter @h-sandbox/deepagents exec tsx examples/run-repair.ts
120
+
121
+ # Secondary, model-free lifecycle example, not an agent-reasoning demo:
122
+ pnpm --filter @h-sandbox/deepagents exec tsx examples/run-checkpoint.ts
123
+ ```
124
+
125
+ `run-repair.ts` is self-contained: model selection, the `createDeepAgent` call,
126
+ fixture setup, invocation, outcome verification and cleanup live in one file.
127
+ Its exported `repairRepository(client, model, template)` is tested through the
128
+ actual framework with scripted model decisions. The initial invoice tests fail
129
+ because quantity is ignored. Expected success is three passing tests, a nonempty
130
+ implementation diff and a confirmed-cleanup sandbox ID. Model claims alone are
131
+ not accepted; editing the test contract also fails verification.
132
+
133
+ `run-checkpoint.ts` is model-free: two graph instances share an in-memory
134
+ checkpointer, pause for approval and retrieve one command's result. It does not
135
+ claim process-restart durability. Production applications supply a persistent
136
+ checkpointer and their own authorized sandbox lookup.
137
+
138
+ The repair example requires **Node.js, Git,
139
+ bash and GNU file tools** in the selected template. Its blocked egress policy
140
+ requires enforcement support in your installation. It downloads no dependencies
141
+ inside the sandbox. A local/self-hosted model is supported through LangChain;
142
+ model availability, tool quality and zero cost are not guaranteed.
143
+ Blocked sandbox egress does not block model calls from the application.
144
+
145
+ Choose a provider integration that supports the framework's text-block tool
146
+ results. `@langchain/ollama@1.3.0` rejects those blocks before making a model
147
+ request, so it is not a drop-in choice for this example. The disposable
148
+ [Ollama acceptance harness](https://github.com/nabilblk/h-sandbox/blob/main/infra/sdk-acceptance/README.md)
149
+ uses strict text-only normalization and `think: false`; this compatibility
150
+ handling is not installed by the Harakiri adapter. Applications can call the
151
+ exported `repairRepository(client, model, template)` with their configured model.
152
+
153
+ ```bash
154
+ pnpm --filter @h-sandbox/deepagents typecheck
155
+ pnpm --filter @h-sandbox/deepagents test
156
+ pnpm --filter @h-sandbox/deepagents test:package
157
+
158
+ # Optional: creates and deletes one sandbox on an explicitly selected test system.
159
+ HARAKIRI_DEEPAGENTS_ACCEPTANCE=disposable-runtime \
160
+ pnpm --filter @h-sandbox/deepagents test:native
161
+ ```
162
+
163
+ Local contract tests use the actual Deep Agents and LangGraph libraries with a
164
+ scripted model and synthetic API, not real inference or a runtime. The native
165
+ command exercises remote shell/file operations with scripted decisions. Real
166
+ model acceptance and publication are separate gates. On September 24, the
167
+ digest-pinned Qwen3 4B Instruct model completed this repair on an isolated amd64
168
+ runner: five responses, no truncated responses or invalid tool calls, unchanged
169
+ original tests, a verified patch and confirmed cleanup. The overall run then
170
+ failed its final operator-key revocation check after the captured browser token
171
+ expired. See [the qualification run](https://github.com/nabilblk/h-sandbox/actions/runs/36004058904).
172
+ The full suite must pass before publication. This is one small repair, not a
173
+ model-quality or production reliability benchmark.
174
+
175
+ ## Boundaries
176
+
177
+ - Linux backend: upstream `BaseSandbox` supplies read/list/glob/grep and edit
178
+ behavior. A working directory is not a filesystem jail. Do not share one
179
+ sandbox across untrusted tenants or attach untrusted local tools to the agent.
180
+ - Commands are shell strings. Transport/auth failures throw, while nonzero shell
181
+ exits are ordinary tool results. The adapter never retries a mutation.
182
+ A framework or model can still request the same action again; approval and
183
+ idempotent application operations are required where repeat effects matter.
184
+ - Execution timeout, status-polling timeout and sandbox TTL are separate.
185
+ Cancellation stops polling/between-file work, not a running remote command.
186
+ Submission, file and log HTTP requests use the SDK transport; supply bounded
187
+ `fetch` in client configuration if you need per-request transport deadlines.
188
+ - Output is stdout followed by stderr, not a chronological merge. The default
189
+ combined UTF-8 log limit is 64 KiB; provider truncation flags remain visible.
190
+ A fixed-size termination notice is outside that limit so timeouts/kills are
191
+ visible to the agent even with empty logs or a tiny limit, without inventing
192
+ an exit code. Grep preserves truncation and drops a clipped final match. Narrow
193
+ the query or increase `maxOutputBytes` for byte-limited searches; the upstream
194
+ generic incomplete-search note only mentions match counts.
195
+ - Files use checksum-verified **buffered** SDK transfers, not streaming. Batches
196
+ are sequential, at most 64 paths and 32 MiB decoded by default; runtime
197
+ per-file limits also apply. Transfers are not transactional. Specific path
198
+ errors return per-file results; unrepresentable failures throw
199
+ `HarakiriTransferError` with earlier successful paths and the original cause,
200
+ including cancellation between files. Cancellation before any work remains a
201
+ direct abort. Download contents from earlier iterations are not retained in
202
+ the exception; `completedPaths` identifies completed reads, not local writes.
203
+ - Upstream edits are read/modify/write, not atomic. Serialize conflicting writers.
204
+ - Durable graph state is not durable sandbox storage. Use Harakiri workspaces
205
+ explicitly when files must survive runtime replacement. Reconnect does not
206
+ revive an expired sandbox or rebind command IDs to another runtime.
207
+
208
+ See the [technical integration guide](https://github.com/nabilblk/h-sandbox/blob/main/docs/integrations/deepagents.md)
209
+ for contracts, operations and the release checklist. Apache-2.0 licensed.
@@ -0,0 +1,24 @@
1
+ import { type HarakiriSandbox } from "@h-sandbox/sdk";
2
+ import { BaseSandbox, type FileDownloadResponse, type FileUploadResponse } from "deepagents";
3
+ import { type CommandReference } from "./errors.js";
4
+ import { type ExecutionOptions } from "./execution.js";
5
+ export type HarakiriSandboxBackendOptions = ExecutionOptions & {
6
+ /** Total decoded bytes per transfer batch. Default 32 MiB, at most 256 MiB. */
7
+ maxBatchBytes?: number;
8
+ };
9
+ /** A borrowed, single-sandbox backend. Construction never creates or destroys resources. */
10
+ export declare class HarakiriSandboxBackend extends BaseSandbox {
11
+ #private;
12
+ constructor(sandbox: HarakiriSandbox, options?: HarakiriSandboxBackendOptions);
13
+ get id(): string;
14
+ /** Persist only this reference, scoped to your application's tenant and thread. */
15
+ get reference(): {
16
+ sandboxId: string;
17
+ };
18
+ execute(command: string): Promise<import("./execution.js").HarakiriExecuteResponse>;
19
+ /** Read-only command recovery. Never submits a command or resumes a runtime. */
20
+ observe(reference: CommandReference): Promise<import("./execution.js").HarakiriExecuteResponse>;
21
+ grep(pattern: string, path?: string, glob?: string | null, maxCount?: number | null): Promise<import("deepagents").GrepResult>;
22
+ uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]>;
23
+ downloadFiles(paths: string[]): Promise<FileDownloadResponse[]>;
24
+ }
@@ -0,0 +1,141 @@
1
+ import { HarakiriApiError } from "@h-sandbox/sdk";
2
+ import { BaseSandbox } from "deepagents";
3
+ import { HarakiriExecutionError, HarakiriTransferError } from "./errors.js";
4
+ import { executionOptions, observeCommand, positiveInteger } from "./execution.js";
5
+ import { grepWithOutputStatus } from "./search.js";
6
+ function fileError(error) {
7
+ if (!(error instanceof HarakiriApiError))
8
+ return null;
9
+ switch (error.code) {
10
+ case "file_not_found": return "file_not_found";
11
+ case "file_permission_denied": return "permission_denied";
12
+ case "invalid_file_path": return "invalid_path";
13
+ default: return null;
14
+ }
15
+ }
16
+ /** A borrowed, single-sandbox backend. Construction never creates or destroys resources. */
17
+ export class HarakiriSandboxBackend extends BaseSandbox {
18
+ #sandbox;
19
+ #execution;
20
+ #maxBatchBytes;
21
+ constructor(sandbox, options = {}) {
22
+ super();
23
+ if (typeof sandbox.files.readBytes !== "function" || typeof sandbox.processes.connect !== "function") {
24
+ throw new TypeError("This adapter requires Harakiri SDK 0.5.0-rc.11 or newer, not npm rc.10.");
25
+ }
26
+ this.#sandbox = sandbox;
27
+ this.#execution = executionOptions(sandbox, options);
28
+ this.#maxBatchBytes = positiveInteger("maxBatchBytes", options.maxBatchBytes ?? 33_554_432, 268_435_456);
29
+ }
30
+ get id() { return this.#sandbox.id; }
31
+ /** Persist only this reference, scoped to your application's tenant and thread. */
32
+ get reference() { return { sandboxId: this.id }; }
33
+ async execute(command) {
34
+ if (!command.trim())
35
+ throw new TypeError("A nonempty shell command is required.");
36
+ this.#execution.signal?.throwIfAborted();
37
+ let reference;
38
+ try {
39
+ const process = await this.#sandbox.processes.start({
40
+ command, cwd: this.#execution.cwd, timeoutMs: this.#execution.timeoutMs, detached: true
41
+ });
42
+ reference = process.reference;
43
+ }
44
+ catch (cause) {
45
+ throw new HarakiriExecutionError("submission", this.id, undefined, cause);
46
+ }
47
+ try {
48
+ await this.#execution.onCommandStarted?.({ ...reference });
49
+ }
50
+ catch (cause) {
51
+ throw new HarakiriExecutionError("checkpoint", this.id, reference, cause);
52
+ }
53
+ return this.observe(reference);
54
+ }
55
+ /** Read-only command recovery. Never submits a command or resumes a runtime. */
56
+ observe(reference) {
57
+ return observeCommand(this.#sandbox, reference, this.#execution);
58
+ }
59
+ grep(pattern, path = "/", glob = null, maxCount = null) {
60
+ return grepWithOutputStatus(this, pattern, path, glob, maxCount);
61
+ }
62
+ async uploadFiles(files) {
63
+ this.#checkBatch(files.length);
64
+ let bytes = 0;
65
+ for (const [, content] of files) {
66
+ if (!(content instanceof Uint8Array))
67
+ throw new TypeError("File content must be Uint8Array.");
68
+ bytes += content.byteLength;
69
+ this.#checkBytes(bytes);
70
+ }
71
+ const results = [];
72
+ for (const [path, content] of files) {
73
+ try {
74
+ this.#execution.signal?.throwIfAborted();
75
+ if (!validPath(path)) {
76
+ results.push({ path, error: "invalid_path" });
77
+ continue;
78
+ }
79
+ await this.#sandbox.files.write(this.#path(path), content, { createParents: true });
80
+ results.push({ path, error: null });
81
+ }
82
+ catch (cause) {
83
+ const error = this.#execution.signal?.aborted ? null : fileError(cause);
84
+ if (error)
85
+ results.push({ path, error });
86
+ else
87
+ throw new HarakiriTransferError("upload", this.id, path, results.filter(r => !r.error).map(r => r.path), cause);
88
+ }
89
+ }
90
+ return results;
91
+ }
92
+ async downloadFiles(paths) {
93
+ this.#checkBatch(paths.length);
94
+ const results = [];
95
+ let bytes = 0;
96
+ for (const path of paths) {
97
+ try {
98
+ this.#execution.signal?.throwIfAborted();
99
+ if (!validPath(path)) {
100
+ results.push({ path, content: null, error: "invalid_path" });
101
+ continue;
102
+ }
103
+ const absolute = this.#path(path);
104
+ const { file } = await this.#sandbox.files.stat(absolute);
105
+ if (file.type === "directory" || file.type === "dir") {
106
+ results.push({ path, content: null, error: "is_directory" });
107
+ continue;
108
+ }
109
+ this.#checkBytes(bytes + file.size);
110
+ const content = await this.#sandbox.files.readBytes(absolute);
111
+ bytes += content.byteLength;
112
+ this.#checkBytes(bytes);
113
+ results.push({ path, content, error: null });
114
+ }
115
+ catch (cause) {
116
+ const error = this.#execution.signal?.aborted ? null : fileError(cause);
117
+ if (error)
118
+ results.push({ path, content: null, error });
119
+ else
120
+ throw new HarakiriTransferError("download", this.id, path, results.filter(r => !r.error).map(r => r.path), cause);
121
+ }
122
+ }
123
+ return results;
124
+ }
125
+ #path(path) {
126
+ return path.startsWith("/") ? path : `${this.#execution.cwd.replace(/\/+$/, "")}/${path}`;
127
+ }
128
+ #checkBatch(count) {
129
+ this.#execution.signal?.throwIfAborted();
130
+ if (count > 64)
131
+ throw new RangeError("Transfer batches are limited to 64 files.");
132
+ }
133
+ #checkBytes(bytes) {
134
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > this.#maxBatchBytes) {
135
+ throw new RangeError(`Transfer batch exceeds ${this.#maxBatchBytes} decoded bytes.`);
136
+ }
137
+ }
138
+ }
139
+ function validPath(path) {
140
+ return typeof path === "string" && path.length > 0 && !path.includes("\0");
141
+ }
@@ -0,0 +1,27 @@
1
+ export type CommandReference = Readonly<{
2
+ sandboxId: string;
3
+ commandId: string;
4
+ }>;
5
+ /** A failed observation is not permission to submit the command again. */
6
+ export declare class HarakiriExecutionError extends Error {
7
+ readonly stage: "submission" | "checkpoint" | "observation";
8
+ readonly sandboxId: string;
9
+ readonly reference: CommandReference | undefined;
10
+ readonly name = "HarakiriExecutionError";
11
+ constructor(stage: "submission" | "checkpoint" | "observation", sandboxId: string, reference: CommandReference | undefined, cause: unknown);
12
+ }
13
+ /** Includes no file contents. Earlier successful uploads must not be replayed blindly. */
14
+ export declare class HarakiriTransferError extends Error {
15
+ readonly operation: "upload" | "download";
16
+ readonly sandboxId: string;
17
+ readonly path: string;
18
+ readonly completedPaths: readonly string[];
19
+ readonly name = "HarakiriTransferError";
20
+ constructor(operation: "upload" | "download", sandboxId: string, path: string, completedPaths: readonly string[], cause: unknown);
21
+ }
22
+ /** Workload and cleanup failures are both retained, including non-Error throws. */
23
+ export declare class HarakiriTaskCleanupError extends AggregateError {
24
+ readonly sandboxId: string;
25
+ readonly name = "HarakiriTaskCleanupError";
26
+ constructor(sandboxId: string, errors: unknown[]);
27
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,37 @@
1
+ /** A failed observation is not permission to submit the command again. */
2
+ export class HarakiriExecutionError extends Error {
3
+ stage;
4
+ sandboxId;
5
+ reference;
6
+ name = "HarakiriExecutionError";
7
+ constructor(stage, sandboxId, reference, cause) {
8
+ super(`Sandbox command ${stage} failed. Inspect or reconnect; do not automatically replay the command.`, { cause });
9
+ this.stage = stage;
10
+ this.sandboxId = sandboxId;
11
+ this.reference = reference;
12
+ }
13
+ }
14
+ /** Includes no file contents. Earlier successful uploads must not be replayed blindly. */
15
+ export class HarakiriTransferError extends Error {
16
+ operation;
17
+ sandboxId;
18
+ path;
19
+ completedPaths;
20
+ name = "HarakiriTransferError";
21
+ constructor(operation, sandboxId, path, completedPaths, cause) {
22
+ super(`Sandbox file ${operation} failed. Earlier transfers may have completed.`, { cause });
23
+ this.operation = operation;
24
+ this.sandboxId = sandboxId;
25
+ this.path = path;
26
+ this.completedPaths = completedPaths;
27
+ }
28
+ }
29
+ /** Workload and cleanup failures are both retained, including non-Error throws. */
30
+ export class HarakiriTaskCleanupError extends AggregateError {
31
+ sandboxId;
32
+ name = "HarakiriTaskCleanupError";
33
+ constructor(sandboxId, errors) {
34
+ super(errors, "Sandbox cleanup was not confirmed. Retain the sandbox ID for recovery.");
35
+ this.sandboxId = sandboxId;
36
+ }
37
+ }
@@ -0,0 +1,37 @@
1
+ import type { HarakiriSandbox, SandboxCommandLogsResponse, SandboxCommandSummary } from "@h-sandbox/sdk";
2
+ import type { ExecuteResponse } from "deepagents";
3
+ import { type CommandReference } from "./errors.js";
4
+ export type ExecutionOptions = {
5
+ /** Remote execution budget. Defaults to the runtime's advertised command timeout. */
6
+ timeoutMs?: number;
7
+ /** Command-status polling budget, excluding log download; never extends TTL. */
8
+ observationTimeoutMs?: number;
9
+ /** Combined UTF-8 log limit, excluding a fixed termination notice. Default 64 KiB; at most 1 MiB. */
10
+ maxOutputBytes?: number;
11
+ /** Must be absolute. This is a working directory, not a security boundary. */
12
+ cwd?: string;
13
+ /** Stops observation. It does not kill the remote command. */
14
+ signal?: AbortSignal;
15
+ /** Persist the acknowledged reference before waiting. Never receives credentials. */
16
+ onCommandStarted?: (reference: CommandReference) => void | Promise<void>;
17
+ };
18
+ export type HarakiriExecuteResponse = ExecuteResponse & {
19
+ reference: CommandReference;
20
+ finishReason: SandboxCommandSummary["finishReason"];
21
+ };
22
+ export declare function positiveInteger(name: string, value: number, maximum?: number): number;
23
+ export declare function executionOptions(sandbox: HarakiriSandbox, options: ExecutionOptions): {
24
+ cwd: string;
25
+ timeoutMs: number;
26
+ observationTimeoutMs: number;
27
+ maxOutputBytes: number;
28
+ /** Stops observation. It does not kill the remote command. */
29
+ signal?: AbortSignal;
30
+ /** Persist the acknowledged reference before waiting. Never receives credentials. */
31
+ onCommandStarted?: (reference: CommandReference) => void | Promise<void>;
32
+ };
33
+ export declare function commandOutput(logs: SandboxCommandLogsResponse, maxBytes: number): {
34
+ output: string;
35
+ truncated: boolean;
36
+ };
37
+ export declare function observeCommand(sandbox: HarakiriSandbox, reference: CommandReference, options: ReturnType<typeof executionOptions>): Promise<HarakiriExecuteResponse>;
@@ -0,0 +1,78 @@
1
+ import { HarakiriExecutionError } from "./errors.js";
2
+ export function positiveInteger(name, value, maximum = Number.MAX_SAFE_INTEGER) {
3
+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) {
4
+ throw new RangeError(`${name} must be a positive integer no greater than ${maximum}.`);
5
+ }
6
+ return value;
7
+ }
8
+ export function executionOptions(sandbox, options) {
9
+ const cwd = options.cwd ?? sandbox.runtimeMetadata.workdir;
10
+ if (!cwd.startsWith("/") || cwd.includes("\0"))
11
+ throw new TypeError("cwd must be an absolute path without NUL characters.");
12
+ const timeoutMs = positiveInteger("timeoutMs", options.timeoutMs ?? sandbox.runtimeMetadata.limits.commandTimeoutMs);
13
+ return {
14
+ ...options, cwd, timeoutMs,
15
+ observationTimeoutMs: positiveInteger("observationTimeoutMs", options.observationTimeoutMs ?? timeoutMs + 10_000),
16
+ maxOutputBytes: positiveInteger("maxOutputBytes", options.maxOutputBytes ?? 65_536, 1_048_576)
17
+ };
18
+ }
19
+ export function commandOutput(logs, maxBytes) {
20
+ const separator = logs.stdout && logs.stderr && !logs.stdout.endsWith("\n") ? "\n" : "";
21
+ let remaining = maxBytes;
22
+ let output = "";
23
+ let truncated = Boolean(logs.stdoutTruncated || logs.stderrTruncated);
24
+ for (const part of [logs.stdout, separator, logs.stderr]) {
25
+ if (Buffer.byteLength(part) <= remaining) {
26
+ output += part;
27
+ remaining -= Buffer.byteLength(part);
28
+ continue;
29
+ }
30
+ truncated = true;
31
+ // Bound allocation first, then avoid splitting a UTF-8 sequence at the limit.
32
+ const bytes = Buffer.from(part.slice(0, remaining));
33
+ let end = Math.min(bytes.length, remaining);
34
+ while (end > 0 && end < bytes.length && (bytes[end] & 0xc0) === 0x80)
35
+ end--;
36
+ output += bytes.subarray(0, end).toString("utf8");
37
+ remaining = 0;
38
+ }
39
+ return { output, truncated };
40
+ }
41
+ function terminationNotice(command) {
42
+ // Deep Agents displays output and numeric exit codes, not our finishReason field.
43
+ switch (command.finishReason) {
44
+ case "timeout": return "[Command timed out; execution did not complete normally.]";
45
+ case "killed": return "[Command was killed; execution did not complete normally.]";
46
+ case "error": return "[Command ended with a runtime error; execution did not complete normally.]";
47
+ default: return command.exitCode === null
48
+ ? "[Command ended without an exit code; normal completion is unconfirmed.]" : "";
49
+ }
50
+ }
51
+ export async function observeCommand(sandbox, reference, options) {
52
+ if (reference.sandboxId !== sandbox.id || !/^cmd_[A-Za-z0-9_-]+$/.test(reference.commandId)) {
53
+ throw new TypeError("The command reference must belong to this sandbox.");
54
+ }
55
+ try {
56
+ options.signal?.throwIfAborted();
57
+ const { command } = await sandbox.processes.wait(reference.commandId, {
58
+ statuses: ["succeeded", "failed", "killed"],
59
+ timeoutMs: options.observationTimeoutMs,
60
+ signal: options.signal
61
+ });
62
+ options.signal?.throwIfAborted();
63
+ const logs = await sandbox.processes.logs(reference.commandId);
64
+ options.signal?.throwIfAborted();
65
+ const result = commandOutput(logs, options.maxOutputBytes);
66
+ const notice = terminationNotice(command);
67
+ return {
68
+ ...result,
69
+ output: notice ? `${notice}${result.output ? `\n${result.output}` : ""}` : result.output,
70
+ exitCode: command.exitCode,
71
+ finishReason: command.finishReason,
72
+ reference: { ...reference }
73
+ };
74
+ }
75
+ catch (cause) {
76
+ throw new HarakiriExecutionError("observation", sandbox.id, { ...reference }, cause);
77
+ }
78
+ }
@@ -0,0 +1,4 @@
1
+ export { HarakiriSandboxBackend, type HarakiriSandboxBackendOptions } from "./backend.js";
2
+ export { withHarakiriSandbox, type OwnedSandboxInput, type OwnedSandboxOptions } from "./lifecycle.js";
3
+ export { HarakiriExecutionError, HarakiriTransferError, HarakiriTaskCleanupError, type CommandReference } from "./errors.js";
4
+ export type { HarakiriExecuteResponse } from "./execution.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { HarakiriSandboxBackend } from "./backend.js";
2
+ export { withHarakiriSandbox } from "./lifecycle.js";
3
+ export { HarakiriExecutionError, HarakiriTransferError, HarakiriTaskCleanupError } from "./errors.js";
@@ -0,0 +1,13 @@
1
+ import type { CreateSandboxInput, HarakiriClient, HarakiriSandbox } from "@h-sandbox/sdk";
2
+ import { HarakiriSandboxBackend, type HarakiriSandboxBackendOptions } from "./backend.js";
3
+ export type OwnedSandboxInput = Omit<CreateSandboxInput, "idempotencyKey" | "source" | "cleanupOnSourceError" | "wait" | "waitTimeoutMs">;
4
+ export type OwnedSandboxOptions = {
5
+ backend?: HarakiriSandboxBackendOptions;
6
+ readinessTimeoutMs?: number;
7
+ cleanupTimeoutMs?: number;
8
+ };
9
+ /** For one-shot jobs only. Checkpointed applications should manage a borrowed sandbox explicitly. */
10
+ export declare function withHarakiriSandbox<T>(client: HarakiriClient, input: OwnedSandboxInput, task: (context: {
11
+ sandbox: HarakiriSandbox;
12
+ backend: HarakiriSandboxBackend;
13
+ }) => Promise<T>, options?: OwnedSandboxOptions): Promise<T>;
@@ -0,0 +1,35 @@
1
+ import { HarakiriSandboxBackend } from "./backend.js";
2
+ import { HarakiriTaskCleanupError } from "./errors.js";
3
+ import { positiveInteger } from "./execution.js";
4
+ /** For one-shot jobs only. Checkpointed applications should manage a borrowed sandbox explicitly. */
5
+ export async function withHarakiriSandbox(client, input, task, options = {}) {
6
+ for (const field of ["idempotencyKey", "source", "cleanupOnSourceError", "wait", "waitTimeoutMs"]) {
7
+ if (field in input)
8
+ throw new TypeError(`${field} is not supported by the owned-task helper. Use an application-owned sandbox.`);
9
+ }
10
+ const readinessTimeoutMs = positiveInteger("readinessTimeoutMs", options.readinessTimeoutMs ?? 180_000);
11
+ const cleanupTimeoutMs = positiveInteger("cleanupTimeoutMs", options.cleanupTimeoutMs ?? 90_000);
12
+ options.backend?.signal?.throwIfAborted();
13
+ // Retain the accepted handle before readiness so failures still enter cleanup.
14
+ const sandbox = await client.sandboxes.create({ ...input, wait: false });
15
+ let result;
16
+ const failures = [];
17
+ try {
18
+ await sandbox.wait({ timeoutMs: readinessTimeoutMs, signal: options.backend?.signal });
19
+ const backend = new HarakiriSandboxBackend(sandbox, options.backend);
20
+ result = await task({ sandbox, backend });
21
+ }
22
+ catch (error) {
23
+ failures.push(error);
24
+ }
25
+ try {
26
+ // Caller cancellation must not cancel confirmation of the owned runtime's cleanup.
27
+ await sandbox.kill({ wait: true, timeoutMs: cleanupTimeoutMs });
28
+ }
29
+ catch (error) {
30
+ throw new HarakiriTaskCleanupError(sandbox.id, [...failures, error]);
31
+ }
32
+ if (failures.length)
33
+ throw failures[0];
34
+ return result;
35
+ }
@@ -0,0 +1,2 @@
1
+ import { BaseSandbox, type GrepResult } from "deepagents";
2
+ export declare function grepWithOutputStatus(backend: BaseSandbox, pattern: string, path: string, glob: string | null, maxCount: number | null): Promise<GrepResult>;
package/dist/search.js ADDED
@@ -0,0 +1,42 @@
1
+ import { BaseSandbox } from "deepagents";
2
+ /** Request-local wrapper for 1.14.0, whose BaseSandbox.grep drops execute metadata. */
3
+ class GrepSandbox extends BaseSandbox {
4
+ backend;
5
+ truncated = false;
6
+ error;
7
+ constructor(backend) {
8
+ super();
9
+ this.backend = backend;
10
+ }
11
+ get id() { return this.backend.id; }
12
+ uploadFiles(files) { return this.backend.uploadFiles(files); }
13
+ downloadFiles(paths) { return this.backend.downloadFiles(paths); }
14
+ async execute(command) {
15
+ const result = await this.backend.execute(command);
16
+ if (result.exitCode !== 0 && result.exitCode !== 1) {
17
+ this.error = "Search did not complete normally. Inspect the command before relying on its results.";
18
+ return { ...result, output: "" };
19
+ }
20
+ this.truncated ||= result.truncated === true;
21
+ // Grep emits newline-terminated records. Never parse a clipped tail as a match.
22
+ return this.truncated
23
+ ? { ...result, output: result.output.slice(0, result.output.lastIndexOf("\n") + 1) }
24
+ : result;
25
+ }
26
+ }
27
+ export async function grepWithOutputStatus(backend, pattern, path, glob, maxCount) {
28
+ const search = new GrepSandbox(backend);
29
+ // Reuse upstream quoting, shell construction, match parsing and count limits.
30
+ const result = await search.grep(pattern, path, glob, maxCount);
31
+ if (search.error)
32
+ return { error: search.error };
33
+ if (!search.truncated)
34
+ return result;
35
+ return {
36
+ ...result, truncated: true,
37
+ // The pinned framework ignores truncated when there are no matches.
38
+ ...(!result.matches?.length ? {
39
+ error: "Search output was truncated before a complete match could be returned. Narrow the pattern or path."
40
+ } : {})
41
+ };
42
+ }
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@h-sandbox/deepagents",
3
+ "version": "0.1.0-rc.0",
4
+ "description": "Deep Agents sandbox backend for the Harakiri control plane.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/nabilblk/h-sandbox.git",
21
+ "directory": "packages/deepagents"
22
+ },
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "sideEffects": false,
27
+ "files": [
28
+ "dist",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "peerDependencies": {
33
+ "@h-sandbox/sdk": "0.5.0-rc.11",
34
+ "deepagents": "1.14.0"
35
+ },
36
+ "devDependencies": {
37
+ "deepagents": "1.14.0",
38
+ "@langchain/core": "1.2.12",
39
+ "@langchain/langgraph": "1.4.17",
40
+ "langchain": "1.5.11",
41
+ "langsmith": "0.9.0",
42
+ "zod": "4.4.3",
43
+ "tsx": "^4.23.13",
44
+ "@h-sandbox/sdk": "0.5.0-rc.11"
45
+ },
46
+ "scripts": {
47
+ "clean": "rm -rf dist",
48
+ "build": "pnpm --filter @h-sandbox/sdk build && pnpm clean && tsc -p tsconfig.json",
49
+ "typecheck": "pnpm build && tsc -p tsconfig.tests.json",
50
+ "lint": "tsc -p tsconfig.json --noEmit",
51
+ "test": "pnpm build && node --test --import tsx test/*.test.ts",
52
+ "test:package": "node ../../scripts/test-deepagents-package.mjs",
53
+ "test:native": "pnpm build && tsx test/native.mts"
54
+ }
55
+ }