@dsh-cc/handoff-store 0.6.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm check:readme --write
5
+ README.md: c12d42fa4fa8cfcb3357d1256b81f579f9bd1ccd
6
+ README.zh.md: a8b1737a9a3836c0263896fe34b7cde52da0da6b
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # @dsh-cc/handoff-store
2
+
3
+ English | [中文](README.zh.md)
4
+
5
+ Subagent handoff store: the `handoff_put` / `handoff_get` tool pair lets a sandboxed or read-only subagent park a large artifact (a long review, plan, or report) in a durable store and hand back a short summary embedding a `handoff://<id>` handle; the orchestrator or a follow-up child resolves the handle with `handoff_get`. This closes the residual-bulk gap in dsh-cc's delegation discipline — a critic (no Write) cannot put its report in a repo file, and the parent's only other channel is the full final-message text.
6
+
7
+ ## Store
8
+
9
+ `$DSH_HOME/handoff/<projectKey>/<id>.md`, flat per project (no per-session subdir; the session lives in the ledger). `projectKey = sha256(session cwd)` first 16 hex, derived from the FETCHING session's cwd (CCR `context_retrieve` precedent). `id = sha256(content utf8)` first 16 hex + a 4-hex random suffix — identical content stored twice yields distinct ids. Files are plain UTF-8 JSON envelopes `{v, ts, text, label?, agent?}`, written atomically (temp + rename).
10
+
11
+ **Same-cwd requirement**: a handle only resolves for sessions whose cwd hashes to the same projectKey. Cross-project fetch is intentionally `unknown_id`. **Git-worktree caveat**: two worktrees of one repo are different keys — a child spawned in a different worktree cannot fetch a handle parked elsewhere.
12
+
13
+ ## Retention
14
+
15
+ TTL 24 h (checked against the stored envelope `ts` on every read; expired → typed `expired` error and a lazy delete) plus a 500-entry LRU per project. Both sweeps are DISK-BASED (`readdir` + envelope/mtime over the projectKey dir, run on put) — deliberately no in-memory LRU, because spawned children are separate processes and a fresh store instance must see the same eviction state. Reads bump mtime (LRU touch); the sweep's TTL pass uses mtime as a cheap proxy while the envelope `ts` stays authoritative on read.
16
+
17
+ ## Ledger
18
+
19
+ `$DSH_HOME/handoff/ledger.jsonl`, append-only rows `{ts, project, sessionId, id, label?, agent?, chars}`. A rebuildable observability index, never on the read path; interleaved appends from sibling children are tolerated. All ledger I/O errors are swallowed.
20
+
21
+ ## Settings
22
+
23
+ Namespace `cc-handoff` (settings overlay, re-read on every put — CCR settings pattern):
24
+
25
+ | Key | Default | Meaning |
26
+ |---|---|---|
27
+ | `enabled` | `true` | Master flag; `false` disables `handoff_put`. |
28
+ | `threshold-chars` | `8192` | Advisory size threshold referenced in the tool description. ADVISORY ONLY: put never enforces or rejects on it. |
29
+
30
+ ## Tools
31
+
32
+ - `handoff_put({ content, label?, agent? })` → summary text including `handoff://<id>` and the char count (plus an advisory note when over the threshold). Keyed by the putting session's cwd.
33
+ - `handoff_get({ id, maxChars? })` → the content, head-truncated with a trailing truncation note when `maxChars` is given. Typed errors `unknown_id` / `expired` / `corrupt`. Fail-closed: the id must match `^[0-9a-f]{20}$` and resolves only inside the current projectKey directory — never outside the store root.
34
+
35
+ The plugin is a plain cordis plugin (publishes no Service, memory pattern); it no-ops when the tools service, fs seam, or `dshHomePath` is absent.
package/README.zh.md ADDED
@@ -0,0 +1,35 @@
1
+ # @dsh-cc/handoff-store
2
+
3
+ [English](README.md) | 中文
4
+
5
+ 子代理交接存储:`handoff_put` / `handoff_get` 工具对让被沙箱化或只读的子代理把大体量产物(长评审、计划、报告)存入持久存储,并回传一个内嵌 `handoff://<id>` 句柄的简短摘要;编排者或后续子代理用 `handoff_get` 取回全文。这补上了 dsh-cc 委派纪律下的残余体量缺口——critic(无 Write)无法把评审写进仓库文件,而父级唯一的另一通道是完整最终消息文本。
6
+
7
+ ## 存储
8
+
9
+ `$DSH_HOME/handoff/<projectKey>/<id>.md`,每个项目平铺(无每会话子目录;会话只进台账)。`projectKey = sha256(会话 cwd)` 前 16 位,取自【取回方】会话的 cwd(CCR `context_retrieve` 先例)。`id = sha256(内容 utf8)` 前 16 位 + 4 位十六进制随机后缀——相同内容存两次得到不同 id。文件是纯 UTF-8 JSON 信封 `{v, ts, text, label?, agent?}`,原子写入(temp + rename)。
10
+
11
+ **同 cwd 要求**:句柄只对 cwd 哈希到同一 projectKey 的会话可解析。跨项目取回刻意返回 `unknown_id`。**git worktree 注意**:同一仓库的两个 worktree 是不同的键——在不同 worktree 中生成的子代理无法取回别处存入的句柄。
12
+
13
+ ## 保留策略
14
+
15
+ TTL 24 小时(每次读取依据信封内存储的 `ts` 校验;过期 → 类型化 `expired` 错误并惰性删除),加上每项目 500 条的 LRU。两次清扫都基于磁盘(对 projectKey 目录 `readdir` + 信封/mtime,在 put 时运行)——刻意不做内存 LRU,因为派生的子进程是独立进程,新建的 store 实例必须看到相同的逐出状态。读取会 bump mtime(LRU touch);清扫的 TTL 判定用 mtime 作廉价代理,信封 `ts` 仍是读取路径上的权威判据。
16
+
17
+ ## 台账
18
+
19
+ `$DSH_HOME/handoff/ledger.jsonl`,只追加行 `{ts, project, sessionId, id, label?, agent?, chars}`。可重建的观测索引,绝不在读取路径上;容忍兄弟子进程交错追加。所有台账 I/O 错误都被吞掉。
20
+
21
+ ## 设置
22
+
23
+ 命名空间 `cc-handoff`(每次 put 重读——CCR settings 模式):
24
+
25
+ | 键 | 默认 | 含义 |
26
+ |---|---|---|
27
+ | `enabled` | `true` | 总开关;`false` 禁用 `handoff_put`。 |
28
+ | `threshold-chars` | `8192` | 工具描述引用的建议尺寸阈值。仅供参考:put 永不据此强制或拒绝。 |
29
+
30
+ ## 工具
31
+
32
+ - `handoff_put({ content, label?, agent? })` → 含 `handoff://<id>` 与字符数的摘要文本。以存入方会话的 cwd 为键。
33
+ - `handoff_get({ id, maxChars? })` → 内容;给定 `maxChars` 时按头部截断并附截断说明。类型化错误 `unknown_id` / `expired` / `corrupt`。封闭失败:id 必须匹配 `^[0-9a-f]{20}$`,且只在当前 projectKey 目录内解析——绝不读出存储根之外。
34
+
35
+ 本插件是普通 cordis 插件(不发布 Service,memory 模式);宿主缺少 tools 服务、fs 缝隙或 `dshHomePath` 时整体 no-op。
package/lib/index.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Subagent handoff store: the `handoff_put` / `handoff_get` tool pair plus a
3
+ * disk-based content-addressed store under `$DSH_HOME/handoff/<projectKey>/`.
4
+ *
5
+ * A sandboxed or read-only subagent (e.g. critic, no Write) cannot put a long
6
+ * report in a repo file; the parent's only channel back would otherwise be
7
+ * the full final-message text. handoff_put parks the artifact and returns a
8
+ * short summary embedding `handoff://<id>`; the orchestrator or a follow-up
9
+ * child resolves it with handoff_get. Cross-session and cross-project
10
+ * transfer follow the CCR precedent: the project bucket is keyed by the
11
+ * session cwd, so fetches only resolve within the SAME working directory
12
+ * (two git worktrees of one repo are different projects — caveat documented
13
+ * in the package README).
14
+ *
15
+ * Plain cordis plugin (publishes no Service — mirror of @dsh-cc/memory): it
16
+ * no-ops when the tools service, fs seam, or dshHomePath is absent. State is
17
+ * entirely on disk (TTL 24 h + 500-entry disk-based LRU swept on put), so
18
+ * spawned children in separate processes see the same store.
19
+ *
20
+ * @module @dsh-cc/handoff-store
21
+ */
22
+ import type { Context } from '@deepseek-ai/cordis';
23
+ export { HandoffStore, MAX_ENTRIES, TTL_MS, projectKeyOf } from './store.ts';
24
+ export { HandoffLedger } from './ledger.ts';
25
+ export { registerSettings, SETTINGS_NAMESPACE, SettingsSchema, DEFAULTS, resolveHandoffConfig } from './settings.ts';
26
+ export { defineHandoffPutTool, defineHandoffGetTool, HANDOFF_PUT_TOOL, HANDOFF_GET_TOOL, THRESHOLD_NOTE, HandoffToolError, applyMaxChars, cwdProjectKey, } from './tools.ts';
27
+ export type { HandoffDeps } from './tools.ts';
28
+ export type { HandoffConfig, HandoffError, HandoffLedgerRow, HandoffMeta } from './types.ts';
29
+ declare module '@deepseek-ai/cordis' {
30
+ interface Context {
31
+ /** Harness-home path resolver, provided by @deepseek-ai/dsh-app-boot at boot. Optional in tests. */
32
+ dshHomePath?: (...segments: string[]) => string;
33
+ }
34
+ }
35
+ /**
36
+ * Mount the handoff tools. No-op when the host has no tools service, no fs
37
+ * seam, or no dshHomePath (a providerless host keeps no handoff surface).
38
+ * @param ctx - the plug context.
39
+ * @returns the tools-registration disposer, or `undefined` when not registered.
40
+ */
41
+ export declare function apply(ctx: Context): (() => void) | undefined;
42
+ /** Cordis plugin id. */
43
+ export declare const name = "cc-handoff";
44
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAOlD,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAC5E,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,cAAc,EAAE,QAAQ,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAA;AACpH,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,aAAa,EACb,aAAa,GACd,MAAM,YAAY,CAAA;AACnB,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAC7C,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAK5F,OAAO,QAAQ,qBAAqB,CAAC;IACnC,UAAU,OAAO;QACf,oGAAoG;QACpG,WAAW,CAAC,EAAE,CAAC,GAAG,QAAQ,EAAE,MAAM,EAAE,KAAK,MAAM,CAAA;KAChD;CACF;AAcD;;;;;GAKG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAqB5D;AAED,wBAAwB;AACxB,eAAO,MAAM,IAAI,eAAe,CAAA"}
package/lib/index.js ADDED
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Subagent handoff store: the `handoff_put` / `handoff_get` tool pair plus a
3
+ * disk-based content-addressed store under `$DSH_HOME/handoff/<projectKey>/`.
4
+ *
5
+ * A sandboxed or read-only subagent (e.g. critic, no Write) cannot put a long
6
+ * report in a repo file; the parent's only channel back would otherwise be
7
+ * the full final-message text. handoff_put parks the artifact and returns a
8
+ * short summary embedding `handoff://<id>`; the orchestrator or a follow-up
9
+ * child resolves it with handoff_get. Cross-session and cross-project
10
+ * transfer follow the CCR precedent: the project bucket is keyed by the
11
+ * session cwd, so fetches only resolve within the SAME working directory
12
+ * (two git worktrees of one repo are different projects — caveat documented
13
+ * in the package README).
14
+ *
15
+ * Plain cordis plugin (publishes no Service — mirror of @dsh-cc/memory): it
16
+ * no-ops when the tools service, fs seam, or dshHomePath is absent. State is
17
+ * entirely on disk (TTL 24 h + 500-entry disk-based LRU swept on put), so
18
+ * spawned children in separate processes see the same store.
19
+ *
20
+ * @module @dsh-cc/handoff-store
21
+ */
22
+ import { HandoffLedger } from "./ledger.js";
23
+ import { registerSettings } from "./settings.js";
24
+ import { HandoffStore } from "./store.js";
25
+ import { defineHandoffGetTool, defineHandoffPutTool } from "./tools.js";
26
+ export { HandoffStore, MAX_ENTRIES, TTL_MS, projectKeyOf } from "./store.js";
27
+ export { HandoffLedger } from "./ledger.js";
28
+ export { registerSettings, SETTINGS_NAMESPACE, SettingsSchema, DEFAULTS, resolveHandoffConfig } from "./settings.js";
29
+ export { defineHandoffPutTool, defineHandoffGetTool, HANDOFF_PUT_TOOL, HANDOFF_GET_TOOL, THRESHOLD_NOTE, HandoffToolError, applyMaxChars, cwdProjectKey, } from "./tools.js";
30
+ function dshHomeFn(ctx) {
31
+ try {
32
+ return ctx.dshHomePath;
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ function sessionIdOf(agent) {
39
+ return agent === undefined ? '' : String(agent.session.id);
40
+ }
41
+ /**
42
+ * Mount the handoff tools. No-op when the host has no tools service, no fs
43
+ * seam, or no dshHomePath (a providerless host keeps no handoff surface).
44
+ * @param ctx - the plug context.
45
+ * @returns the tools-registration disposer, or `undefined` when not registered.
46
+ */
47
+ export function apply(ctx) {
48
+ const tools = ctx.get('tools');
49
+ const fs = ctx.get('fs');
50
+ const home = dshHomeFn(ctx);
51
+ if (tools === undefined || fs === undefined || home === undefined)
52
+ return undefined;
53
+ const store = new HandoffStore(home('handoff'));
54
+ const ledger = new HandoffLedger(home('handoff', 'ledger.jsonl'));
55
+ const readSettings = registerSettings(ctx);
56
+ const deps = {
57
+ store,
58
+ ledger,
59
+ readSettings,
60
+ sessionIdOf,
61
+ };
62
+ const offPut = tools.register(defineHandoffPutTool(deps));
63
+ const offGet = tools.register(defineHandoffGetTool(deps));
64
+ return () => {
65
+ offPut();
66
+ offGet();
67
+ };
68
+ }
69
+ /** Cordis plugin id. */
70
+ export const name = 'cc-handoff';
71
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAIH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACzC,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAoB,MAAM,YAAY,CAAA;AAEzF,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM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AC1C,MAAM,IAAI,GAAgB;QACxB,KAAK;QACL,MAAM;QACN,YAAY;QACZ,WAAW;KACZ,CAAA;IACD,MAAM,MAAM,GAAG,KAAK,CAAC,QAAQ,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC,CAAA;IACzD,MAAM,MAAM,GAAG,KAAK,CAAC,QAAQ,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC,CAAA;IACzD,OAAO,GAAG,EAAE;QACV,MAAM,EAAE,CAAA;QACR,MAAM,EAAE,CAAA;IACV,CAAC,CAAA;AACH,CAAC;AAED,wBAAwB;AACxB,MAAM,CAAC,MAAM,IAAI,GAAG,YAAY,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Append-only handoff ledger (`<dshHome>/handoff/ledger.jsonl`).
3
+ *
4
+ * One `appendFile` per row (rows are small; appends are atomic enough even
5
+ * when sibling children interleave rows). The ledger is a rebuildable
6
+ * observability index, NOT on the read path — `handoff_get` never touches it.
7
+ * All I/O errors are swallowed: a failed row must never degrade a put.
8
+ *
9
+ * @module @dsh-cc/handoff-store/ledger
10
+ */
11
+ import type { HandoffLedgerRow } from './types.ts';
12
+ export declare class HandoffLedger {
13
+ private readonly filePath;
14
+ constructor(filePath: string);
15
+ /** Append one row; never throws. */
16
+ append(row: HandoffLedgerRow): Promise<void>;
17
+ }
18
+ //# sourceMappingURL=ledger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledger.d.ts","sourceRoot":"","sources":["../src/ledger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD,qBAAa,aAAa;IACZ,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAAR,QAAQ,EAAE,MAAM;IAE7C,oCAAoC;IAC9B,MAAM,CAAC,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;CAQnD"}
package/lib/ledger.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Append-only handoff ledger (`<dshHome>/handoff/ledger.jsonl`).
3
+ *
4
+ * One `appendFile` per row (rows are small; appends are atomic enough even
5
+ * when sibling children interleave rows). The ledger is a rebuildable
6
+ * observability index, NOT on the read path — `handoff_get` never touches it.
7
+ * All I/O errors are swallowed: a failed row must never degrade a put.
8
+ *
9
+ * @module @dsh-cc/handoff-store/ledger
10
+ */
11
+ import { appendFile, mkdir } from 'node:fs/promises';
12
+ import { dirname } from 'node:path';
13
+ export class HandoffLedger {
14
+ filePath;
15
+ constructor(filePath) {
16
+ this.filePath = filePath;
17
+ }
18
+ /** Append one row; never throws. */
19
+ async append(row) {
20
+ try {
21
+ await mkdir(dirname(this.filePath), { recursive: true });
22
+ await appendFile(this.filePath, `${JSON.stringify(row)}\n`, 'utf8');
23
+ }
24
+ catch {
25
+ // Best-effort observability; never surface into the tool waterfall.
26
+ }
27
+ }
28
+ }
29
+ //# sourceMappingURL=ledger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledger.js","sourceRoot":"","sources":["../src/ledger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAGnC,MAAM,OAAO,aAAa;IACK;IAA7B,YAA6B,QAAgB;QAAhB,aAAQ,GAAR,QAAQ,CAAQ;IAAG,CAAC;IAEjD,oCAAoC;IACpC,KAAK,CAAC,MAAM,CAAC,GAAqB;QAChC,IAAI,CAAC;YACH,MAAM,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;YACxD,MAAM,UAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;QACrE,CAAC;QAAC,MAAM,CAAC;YACP,oEAAoE;QACtE,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Settings namespace registration for the `cc-handoff` overlay.
3
+ * CCR settings.ts pattern: the namespace is registered once at mount; the
4
+ * live scope is re-read on EVERY put so a settings write applies immediately.
5
+ * @module @dsh-cc/handoff-store/settings
6
+ */
7
+ import z from '@deepseek-ai/schemastery';
8
+ import type { Context } from '@deepseek-ai/cordis';
9
+ import type { SettingsNamespace } from '@deepseek-ai/dsh-settings';
10
+ import type { HandoffConfig } from './types.ts';
11
+ /** The settings namespace carrying the live handoff overlay. */
12
+ export declare const SETTINGS_NAMESPACE: SettingsNamespace;
13
+ /** Defaults, also the documented advisory contract. */
14
+ export declare const DEFAULTS: {
15
+ enabled: boolean;
16
+ thresholdChars: number;
17
+ };
18
+ /** Settings namespace schema. */
19
+ export declare const SettingsSchema: z<HandoffConfig>;
20
+ /**
21
+ * Register the settings namespace and return a per-use reader. Graceful
22
+ * without a settings provider: the reader resolves `undefined` and callers
23
+ * fall back to {@link DEFAULTS}.
24
+ * @param ctx - the plug context.
25
+ * @returns the live scope reader.
26
+ */
27
+ export declare function registerSettings(ctx: Context): () => HandoffConfig | undefined;
28
+ /** Effective configuration for one use: defaults overlaid by the live scope. */
29
+ export declare function resolveHandoffConfig(scope: HandoffConfig | undefined): {
30
+ enabled: boolean;
31
+ thresholdChars: number;
32
+ };
33
+ //# sourceMappingURL=settings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"settings.d.ts","sourceRoot":"","sources":["../src/settings.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,CAAC,MAAM,0BAA0B,CAAA;AACxC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,KAAK,EAAE,iBAAiB,EAAoB,MAAM,2BAA2B,CAAA;AAEpF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE/C,gEAAgE;AAChE,eAAO,MAAM,kBAAkB,EAAmB,iBAAiB,CAAA;AAEnE,uDAAuD;AACvD,eAAO,MAAM,QAAQ;;;CAGnB,CAAA;AAEF,iCAAiC;AACjC,eAAO,MAAM,cAAc,EAAE,CAAC,CAAC,aAAa,CAG1C,CAAA;AAEF;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,aAAa,GAAG,SAAS,CAI9E;AAED,gFAAgF;AAChF,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,aAAa,GAAG,SAAS,GAAG;IACtE,OAAO,EAAE,OAAO,CAAA;IAChB,cAAc,EAAE,MAAM,CAAA;CACvB,CAKA"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Settings namespace registration for the `cc-handoff` overlay.
3
+ * CCR settings.ts pattern: the namespace is registered once at mount; the
4
+ * live scope is re-read on EVERY put so a settings write applies immediately.
5
+ * @module @dsh-cc/handoff-store/settings
6
+ */
7
+ import z from '@deepseek-ai/schemastery';
8
+ import { deepFreeze } from '@deepseek-ai/dsh-util-values';
9
+ /** The settings namespace carrying the live handoff overlay. */
10
+ export const SETTINGS_NAMESPACE = 'cc-handoff';
11
+ /** Defaults, also the documented advisory contract. */
12
+ export const DEFAULTS = deepFreeze({
13
+ enabled: true,
14
+ thresholdChars: 8192,
15
+ });
16
+ /** Settings namespace schema. */
17
+ export const SettingsSchema = z.object({
18
+ enabled: z.boolean(),
19
+ 'threshold-chars': z.number().step(1).min(1),
20
+ });
21
+ /**
22
+ * Register the settings namespace and return a per-use reader. Graceful
23
+ * without a settings provider: the reader resolves `undefined` and callers
24
+ * fall back to {@link DEFAULTS}.
25
+ * @param ctx - the plug context.
26
+ * @returns the live scope reader.
27
+ */
28
+ export function registerSettings(ctx) {
29
+ const settings = ctx.get('settings');
30
+ const scope = settings?.register(SETTINGS_NAMESPACE, SettingsSchema);
31
+ return () => scope?.get?.();
32
+ }
33
+ /** Effective configuration for one use: defaults overlaid by the live scope. */
34
+ export function resolveHandoffConfig(scope) {
35
+ return {
36
+ enabled: scope?.enabled ?? DEFAULTS.enabled,
37
+ thresholdChars: scope?.['threshold-chars'] ?? DEFAULTS.thresholdChars,
38
+ };
39
+ }
40
+ //# sourceMappingURL=settings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"settings.js","sourceRoot":"","sources":["../src/settings.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAGxC,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAA;AAGzD,gEAAgE;AAChE,MAAM,CAAC,MAAM,kBAAkB,GAAG,YAAiC,CAAA;AAEnE,uDAAuD;AACvD,MAAM,CAAC,MAAM,QAAQ,GAAG,UAAU,CAAC;IACjC,OAAO,EAAE,IAAI;IACb,cAAc,EAAE,IAAI;CACrB,CAAC,CAAA;AAEF,iCAAiC;AACjC,MAAM,CAAC,MAAM,cAAc,GAAqB,CAAC,CAAC,MAAM,CAAC;IACvD,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE;IACpB,iBAAiB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;CAC7C,CAAC,CAAA;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAY;IAC3C,MAAM,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,UAAU,CAAiC,CAAA;IACpE,MAAM,KAAK,GAAG,QAAQ,EAAE,QAAQ,CAAC,kBAAkB,EAAE,cAAc,CAAC,CAAA;IACpE,OAAO,GAAG,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAA+B,CAAA;AAC1D,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,oBAAoB,CAAC,KAAgC;IAInE,OAAO;QACL,OAAO,EAAE,KAAK,EAAE,OAAO,IAAI,QAAQ,CAAC,OAAO;QAC3C,cAAc,EAAE,KAAK,EAAE,CAAC,iBAAiB,CAAC,IAAI,QAAQ,CAAC,cAAc;KACtE,CAAA;AACH,CAAC"}
package/lib/store.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Content-addressed, project-keyed store for subagent handoff artifacts.
3
+ *
4
+ * Layout: `<root>/<projectKey>/<id>.md` where id = sha256(content
5
+ * utf8).slice(0,16) + a 4-hex random suffix (globally unique even when two
6
+ * children store identical content — the suffix makes every put a NEW
7
+ * artifact), and projectKey = sha256(session cwd).slice(0,16). Flat per
8
+ * project: no per-session subdir (session lives only in the ledger). Files
9
+ * are plain UTF-8 JSON envelopes `{v, ts, text, label?, agent?}`; writes are
10
+ * atomic (temp file + rename). TTL 24 h (authoritative on READ, via the
11
+ * stored envelope ts) and an LRU cap of 500 entries — both DISK-BASED: the
12
+ * sweep runs readdir + mtime over the projectKey dir, so a freshly spawned
13
+ * child process (a new store instance) sees the same eviction state; there is
14
+ * deliberately no in-memory LRU map. The sweep's TTL pass uses mtime as a
15
+ * cheap proxy (get() bumps mtime on access); the strict ts check stays on
16
+ * the read path. Sweep is per-project (the putting session's own bucket).
17
+ *
18
+ * @module @dsh-cc/handoff-store/store
19
+ */
20
+ import type { HandoffError, HandoffMeta } from './types.ts';
21
+ export declare const MAX_ENTRIES = 500;
22
+ export declare const TTL_MS: number;
23
+ /** sha256 hex, first 16 chars. */
24
+ export declare function projectKeyOf(cwd: string): string;
25
+ /** Injectable clock signature (tests pass a fake; never sleep in tests). */
26
+ export type NowFn = () => number;
27
+ export type HandoffResult = {
28
+ ok: true;
29
+ text: string;
30
+ label?: string;
31
+ agent?: string;
32
+ } | {
33
+ ok: false;
34
+ error: HandoffError;
35
+ };
36
+ /**
37
+ * The handoff store. One instance per mounted plugin; `root` is
38
+ * `dshHomePath('handoff')`. State is entirely on disk — two instances
39
+ * (separate child processes) observe the same TTL/LRU behavior. Retrieve
40
+ * errors are typed, never thrown; sweep never throws.
41
+ */
42
+ export declare class HandoffStore {
43
+ readonly root: string;
44
+ private readonly now;
45
+ constructor(root: string, now?: NowFn);
46
+ /** Persist one artifact atomically; returns its 20-hex id. */
47
+ put(projectKey: string, text: string, meta?: HandoffMeta): Promise<string>;
48
+ /**
49
+ * Retrieve one artifact, failing closed on unknown/expired/corrupt. An
50
+ * expired entry is also deleted lazily. `id` must be exactly 20 hex and
51
+ * resolves ONLY inside this projectKey's directory — the tool layer keys
52
+ * projectKey off the fetching session's cwd, so a malformed or
53
+ * cross-project id can never read outside the store root.
54
+ */
55
+ get(projectKey: string, id: string): Promise<HandoffResult>;
56
+ /**
57
+ * Disk-based hygiene for one project bucket: readdir + mtime (NO in-memory
58
+ * bookkeeping — spawned children are separate processes). Drops entries
59
+ * whose mtime is past the TTL (mtime is bumped on access; the strict
60
+ * envelope-ts check remains authoritative on read), then LRU-evicts the
61
+ * oldest by mtime beyond {@link MAX_ENTRIES}. Never throws.
62
+ */
63
+ sweep(projectKey: string): Promise<void>;
64
+ }
65
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAMH,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAE3D,eAAO,MAAM,WAAW,MAAM,CAAA;AAC9B,eAAO,MAAM,MAAM,QAAgB,CAAA;AAKnC,kCAAkC;AAClC,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEhD;AAED,4EAA4E;AAC5E,MAAM,MAAM,KAAK,GAAG,MAAM,MAAM,CAAA;AAQhC,MAAM,MAAM,aAAa,GACrB;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAC1D;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,YAAY,CAAA;CAAE,CAAA;AAEtC;;;;;GAKG;AACH,qBAAa,YAAY;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAO;gBAEf,IAAI,EAAE,MAAM,EAAE,GAAG,GAAE,KAAgB;IAK/C,8DAA8D;IACxD,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,WAAgB,GAAG,OAAO,CAAC,MAAM,CAAC;IAcpF;;;;;;OAMG;IACG,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC;IA2CjE;;;;;;OAMG;IACG,KAAK,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAgC/C"}
package/lib/store.js ADDED
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Content-addressed, project-keyed store for subagent handoff artifacts.
3
+ *
4
+ * Layout: `<root>/<projectKey>/<id>.md` where id = sha256(content
5
+ * utf8).slice(0,16) + a 4-hex random suffix (globally unique even when two
6
+ * children store identical content — the suffix makes every put a NEW
7
+ * artifact), and projectKey = sha256(session cwd).slice(0,16). Flat per
8
+ * project: no per-session subdir (session lives only in the ledger). Files
9
+ * are plain UTF-8 JSON envelopes `{v, ts, text, label?, agent?}`; writes are
10
+ * atomic (temp file + rename). TTL 24 h (authoritative on READ, via the
11
+ * stored envelope ts) and an LRU cap of 500 entries — both DISK-BASED: the
12
+ * sweep runs readdir + mtime over the projectKey dir, so a freshly spawned
13
+ * child process (a new store instance) sees the same eviction state; there is
14
+ * deliberately no in-memory LRU map. The sweep's TTL pass uses mtime as a
15
+ * cheap proxy (get() bumps mtime on access); the strict ts check stays on
16
+ * the read path. Sweep is per-project (the putting session's own bucket).
17
+ *
18
+ * @module @dsh-cc/handoff-store/store
19
+ */
20
+ import { createHash, randomBytes } from 'node:crypto';
21
+ import { readdirSync, rmSync, statSync, utimesSync } from 'node:fs';
22
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
23
+ import { join } from 'node:path';
24
+ export const MAX_ENTRIES = 500;
25
+ export const TTL_MS = 24 * 3600_000;
26
+ const ID_RE = /^[0-9a-f]{20}$/;
27
+ /** sha256 hex, first 16 chars — the shared project-key shape (CCR store.ts). */
28
+ const KEY_LEN = 16;
29
+ /** sha256 hex, first 16 chars. */
30
+ export function projectKeyOf(cwd) {
31
+ return createHash('sha256').update(cwd, 'utf8').digest('hex').slice(0, KEY_LEN);
32
+ }
33
+ /**
34
+ * The handoff store. One instance per mounted plugin; `root` is
35
+ * `dshHomePath('handoff')`. State is entirely on disk — two instances
36
+ * (separate child processes) observe the same TTL/LRU behavior. Retrieve
37
+ * errors are typed, never thrown; sweep never throws.
38
+ */
39
+ export class HandoffStore {
40
+ root;
41
+ now;
42
+ constructor(root, now = Date.now) {
43
+ this.root = root;
44
+ this.now = now;
45
+ }
46
+ /** Persist one artifact atomically; returns its 20-hex id. */
47
+ async put(projectKey, text, meta = {}) {
48
+ const id = `${createHash('sha256').update(text, 'utf8').digest('hex').slice(0, KEY_LEN)}${randomBytes(2).toString('hex')}`;
49
+ const dir = join(this.root, projectKey);
50
+ const file = join(dir, `${id}.md`);
51
+ const envelope = { v: 1, ts: this.now(), text, ...meta };
52
+ await mkdir(dir, { recursive: true });
53
+ // Atomic write: same-directory temp file + rename (CCR store pattern).
54
+ const tmp = `${file}.tmp-${randomBytes(6).toString('hex')}`;
55
+ await writeFile(tmp, JSON.stringify(envelope), 'utf8');
56
+ await rename(tmp, file);
57
+ void this.sweep(projectKey); // sweep-on-put, fire-and-forget
58
+ return id;
59
+ }
60
+ /**
61
+ * Retrieve one artifact, failing closed on unknown/expired/corrupt. An
62
+ * expired entry is also deleted lazily. `id` must be exactly 20 hex and
63
+ * resolves ONLY inside this projectKey's directory — the tool layer keys
64
+ * projectKey off the fetching session's cwd, so a malformed or
65
+ * cross-project id can never read outside the store root.
66
+ */
67
+ async get(projectKey, id) {
68
+ if (!ID_RE.test(id))
69
+ return { ok: false, error: 'unknown_id' };
70
+ const file = join(this.root, projectKey, `${id}.md`);
71
+ // Belt-and-suspenders against future shape changes: the id must name a
72
+ // direct child of the project directory, never anything outside it.
73
+ if (join(file) !== join(this.root, projectKey, `${id}.md`))
74
+ return { ok: false, error: 'unknown_id' };
75
+ let body;
76
+ try {
77
+ body = await readFile(file, 'utf8');
78
+ }
79
+ catch {
80
+ return { ok: false, error: 'unknown_id' };
81
+ }
82
+ let envelope;
83
+ try {
84
+ const parsed = JSON.parse(body);
85
+ if (typeof parsed !== 'object' || parsed === null
86
+ || parsed.v !== 1 || typeof parsed.ts !== 'number'
87
+ || typeof parsed.text !== 'string')
88
+ throw new Error('shape');
89
+ envelope = parsed;
90
+ }
91
+ catch {
92
+ return { ok: false, error: 'corrupt' };
93
+ }
94
+ if (this.now() - envelope.ts > TTL_MS) {
95
+ try {
96
+ rmSync(file, { force: true }); // lazy TTL delete
97
+ }
98
+ catch {
99
+ // best-effort
100
+ }
101
+ return { ok: false, error: 'expired' };
102
+ }
103
+ // LRU touch on disk: bump mtime so the sweep keeps hot entries.
104
+ try {
105
+ const t = this.now() / 1000;
106
+ utimesSync(file, t, t);
107
+ }
108
+ catch {
109
+ // best-effort
110
+ }
111
+ const { label, agent } = envelope;
112
+ return (label === undefined && agent === undefined)
113
+ ? { ok: true, text: envelope.text }
114
+ : { ok: true, text: envelope.text, ...(label === undefined ? {} : { label }), ...(agent === undefined ? {} : { agent }) };
115
+ }
116
+ /**
117
+ * Disk-based hygiene for one project bucket: readdir + mtime (NO in-memory
118
+ * bookkeeping — spawned children are separate processes). Drops entries
119
+ * whose mtime is past the TTL (mtime is bumped on access; the strict
120
+ * envelope-ts check remains authoritative on read), then LRU-evicts the
121
+ * oldest by mtime beyond {@link MAX_ENTRIES}. Never throws.
122
+ */
123
+ async sweep(projectKey) {
124
+ try {
125
+ const dir = join(this.root, projectKey);
126
+ const now = this.now();
127
+ const aged = [];
128
+ for (const name of readdirSync(dir)) {
129
+ if (!name.endsWith('.md') || !ID_RE.test(name.slice(0, -3)))
130
+ continue;
131
+ try {
132
+ const mtime = statSync(join(dir, name)).mtimeMs;
133
+ if (now - mtime > TTL_MS) {
134
+ rmSync(join(dir, name), { force: true });
135
+ continue;
136
+ }
137
+ aged.push({ name, mtime });
138
+ }
139
+ catch {
140
+ // lost a race with a sibling sweep; skip
141
+ }
142
+ }
143
+ // ponytail: full sort of ≤500 entries per put — fine at this scale;
144
+ // heap only if the cap grows orders of magnitude.
145
+ aged.sort((a, b) => a.mtime - b.mtime);
146
+ for (const entry of aged.slice(0, Math.max(0, aged.length - MAX_ENTRIES))) {
147
+ try {
148
+ rmSync(join(dir, entry.name), { force: true });
149
+ }
150
+ catch {
151
+ // best-effort
152
+ }
153
+ }
154
+ }
155
+ catch {
156
+ // Sweep is best-effort hygiene; a failure must never reach the tool.
157
+ }
158
+ }
159
+ }
160
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACnE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AACrE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAGhC,MAAM,CAAC,MAAM,WAAW,GAAG,GAAG,CAAA;AAC9B,MAAM,CAAC,MAAM,MAAM,GAAG,EAAE,GAAG,QAAQ,CAAA;AACnC,MAAM,KAAK,GAAG,gBAAgB,CAAA;AAC9B,gFAAgF;AAChF,MAAM,OAAO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K,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,MAAM,GAAG,WAAW,CAAC,CAAC,EAAE,CAAC;gBAC1E,IAAI,CAAC;oBACH,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;gBAChD,CAAC;gBAAC,MAAM,CAAC;oBACP,cAAc;gBAChB,CAAC;YACH,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,qEAAqE;QACvE,CAAC;IACH,CAAC;CACF"}
package/lib/tools.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The `handoff_put` / `handoff_get` agent tools over the handoff store.
3
+ *
4
+ * `handoff_put` parks a large artifact (review body, long plan, bulk
5
+ * findings) in the store and returns a short summary embedding the
6
+ * `handoff://<id>` handle; the orchestrator or a follow-up child resolves it
7
+ * with `handoff_get({ id })` — the sibling-transfer path. The threshold in
8
+ * the description is the ADVISORY contract only (see cc-handoff.threshold-chars):
9
+ * put never enforces or rejects on size. `handoff_get` derives the project
10
+ * bucket from the FETCHING session's cwd (CCR `context_retrieve` precedent),
11
+ * so only sessions in the SAME working directory can fetch — two git
12
+ * worktrees of one repo are different projects by design.
13
+ *
14
+ * @module @dsh-cc/handoff-store/tools
15
+ */
16
+ import type { Agent } from '@deepseek-ai/dsh-agent';
17
+ import { HandoffLedger } from './ledger.ts';
18
+ import { HandoffStore } from './store.ts';
19
+ import type { HandoffConfig } from './types.ts';
20
+ export declare const HANDOFF_PUT_TOOL = "handoff_put";
21
+ export declare const HANDOFF_GET_TOOL = "handoff_get";
22
+ /** Advisory-threshold sentence shared by the put description and the tool note. */
23
+ export declare const THRESHOLD_NOTE: string;
24
+ /** A model-visible handoff failure (maps to an isError tool result). */
25
+ export declare class HandoffToolError extends Error {
26
+ }
27
+ export interface HandoffDeps {
28
+ store: HandoffStore;
29
+ ledger: HandoffLedger;
30
+ readSettings: () => HandoffConfig | undefined;
31
+ sessionIdOf(agent?: Agent): string;
32
+ }
33
+ /** sha256(session cwd), 16 hex — or undefined when the cwd is unavailable. */
34
+ export declare function cwdProjectKey(agent: Agent | undefined): string | undefined;
35
+ /** Head-truncate with a trailing note when `maxChars` cuts the text. */
36
+ export declare function applyMaxChars(text: string, maxChars: number | undefined): string;
37
+ export declare function defineHandoffPutTool(deps: HandoffDeps): import("@dsh-cc/tools").ToolDefinition;
38
+ export declare function defineHandoffGetTool(deps: HandoffDeps): import("@dsh-cc/tools").ToolDefinition;
39
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAA;AAGnD,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAE3C,OAAO,EAAE,YAAY,EAAgB,MAAM,YAAY,CAAA;AACvD,OAAO,KAAK,EAAE,aAAa,EAAe,MAAM,YAAY,CAAA;AAE5D,eAAO,MAAM,gBAAgB,gBAAgB,CAAA;AAC7C,eAAO,MAAM,gBAAgB,gBAAgB,CAAA;AAE7C,mFAAmF;AACnF,eAAO,MAAM,cAAc,QAE0B,CAAA;AAErD,wEAAwE;AACxE,qBAAa,gBAAiB,SAAQ,KAAK;CAAG;AAE9C,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,YAAY,CAAA;IACnB,MAAM,EAAE,aAAa,CAAA;IACrB,YAAY,EAAE,MAAM,aAAa,GAAG,SAAS,CAAA;IAC7C,WAAW,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,MAAM,CAAA;CACnC;AAED,8EAA8E;AAC9E,wBAAgB,aAAa,CAAC,KAAK,EAAE,KAAK,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAO1E;AAED,wEAAwE;AACxE,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAKhF;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,WAAW,0CAwErD;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,WAAW,0CA+BrD"}
package/lib/tools.js ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The `handoff_put` / `handoff_get` agent tools over the handoff store.
3
+ *
4
+ * `handoff_put` parks a large artifact (review body, long plan, bulk
5
+ * findings) in the store and returns a short summary embedding the
6
+ * `handoff://<id>` handle; the orchestrator or a follow-up child resolves it
7
+ * with `handoff_get({ id })` — the sibling-transfer path. The threshold in
8
+ * the description is the ADVISORY contract only (see cc-handoff.threshold-chars):
9
+ * put never enforces or rejects on size. `handoff_get` derives the project
10
+ * bucket from the FETCHING session's cwd (CCR `context_retrieve` precedent),
11
+ * so only sessions in the SAME working directory can fetch — two git
12
+ * worktrees of one repo are different projects by design.
13
+ *
14
+ * @module @dsh-cc/handoff-store/tools
15
+ */
16
+ import { defineTool } from '@dsh-cc/tools';
17
+ import { getSessionCwd } from '@dsh-cc/session-cwd';
18
+ import { resolveHandoffConfig } from "./settings.js";
19
+ import { projectKeyOf } from "./store.js";
20
+ export const HANDOFF_PUT_TOOL = 'handoff_put';
21
+ export const HANDOFF_GET_TOOL = 'handoff_get';
22
+ /** Advisory-threshold sentence shared by the put description and the tool note. */
23
+ export const THRESHOLD_NOTE = 'Default 8192 (see cc-handoff.threshold-chars). The threshold is advisory: '
24
+ + 'handoff_put never rejects or truncates on size.';
25
+ /** A model-visible handoff failure (maps to an isError tool result). */
26
+ export class HandoffToolError extends Error {
27
+ }
28
+ /** sha256(session cwd), 16 hex — or undefined when the cwd is unavailable. */
29
+ export function cwdProjectKey(agent) {
30
+ if (agent === undefined)
31
+ return undefined;
32
+ try {
33
+ return projectKeyOf(getSessionCwd(agent));
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
39
+ /** Head-truncate with a trailing note when `maxChars` cuts the text. */
40
+ export function applyMaxChars(text, maxChars) {
41
+ if (maxChars === undefined || !Number.isFinite(maxChars) || maxChars < 1 || text.length <= maxChars) {
42
+ return text;
43
+ }
44
+ return `${text.slice(0, maxChars)}\n\n[dsh-cc handoff truncated at ${maxChars} of ${text.length} chars; full text: use handoff_get]`;
45
+ }
46
+ export function defineHandoffPutTool(deps) {
47
+ return defineTool({
48
+ name: HANDOFF_PUT_TOOL,
49
+ description: 'Park a large artifact (a long review, plan, or report that would flood the parent context) in the '
50
+ + 'durable handoff store and return a short summary with a `handoff://<id>` handle. Use it BEFORE '
51
+ + 'writing a big report into your final message: return the summary (at most ~2 KB) and embed the '
52
+ + 'handle; the orchestrator or a follow-up child fetches the full text with handoff_get. '
53
+ + 'Retention 24 h; visible to sessions in the SAME working directory only. '
54
+ + `Threshold: ${THRESHOLD_NOTE}`,
55
+ parameters: {
56
+ content: {
57
+ type: 'string',
58
+ required: true,
59
+ description: 'The full artifact text to store. Stored verbatim; never truncated by the tool.',
60
+ },
61
+ label: {
62
+ type: 'string',
63
+ description: 'Short one-line label describing the artifact (e.g. "review of PR #12").',
64
+ },
65
+ agent: {
66
+ type: 'string',
67
+ description: 'Originating agent name, when known (defaults to the calling agent, if it has one).',
68
+ },
69
+ },
70
+ output: {
71
+ schema: {
72
+ type: 'object',
73
+ additionalProperties: false,
74
+ properties: {
75
+ id: { type: 'string', required: true },
76
+ message: { type: 'string', required: true },
77
+ },
78
+ },
79
+ render: (_args, value) => [{ type: 'text', text: value.message }],
80
+ },
81
+ async execute(args, exec) {
82
+ const cfg = resolveHandoffConfig(deps.readSettings());
83
+ if (!cfg.enabled)
84
+ throw new HandoffToolError('handoff_put unavailable: cc-handoff.enabled is false');
85
+ const projectKey = cwdProjectKey(exec.agent);
86
+ if (projectKey === undefined)
87
+ throw new HandoffToolError('handoff_put unavailable: no session cwd');
88
+ const content = args.content;
89
+ if (typeof content !== 'string' || content.length === 0) {
90
+ throw new HandoffToolError('handoff_put: content must be a non-empty string');
91
+ }
92
+ const agentName = args.agent ?? (exec.agent === undefined ? undefined : exec.agent.name);
93
+ const meta = {
94
+ ...(args.label === undefined ? {} : { label: args.label }),
95
+ ...(agentName === undefined ? {} : { agent: agentName }),
96
+ };
97
+ const id = await deps.store.put(projectKey, content, meta);
98
+ const chars = content.length;
99
+ await deps.ledger.append({
100
+ ts: new Date().toISOString(),
101
+ project: projectKey,
102
+ sessionId: deps.sessionIdOf(exec.agent),
103
+ id,
104
+ ...(meta.label === undefined ? {} : { label: meta.label }),
105
+ ...(meta.agent === undefined ? {} : { agent: meta.agent }),
106
+ chars,
107
+ });
108
+ // Advisory note only — the threshold is never enforced (design decision 5).
109
+ const over = chars > cfg.thresholdChars
110
+ ? ` Over the ${cfg.thresholdChars}-char advisory threshold: your final message should carry only a short summary (≤2 KB) plus the handoff://<id> handle below.`
111
+ : '';
112
+ return {
113
+ id,
114
+ message: `Stored handoff artifact ${id} (${chars} chars, retention 24h). Reference: handoff://${id}`
115
+ + `${over} Fetch it with handoff_get({ id: "${id}" }) — same working directory only.`,
116
+ };
117
+ },
118
+ });
119
+ }
120
+ export function defineHandoffGetTool(deps) {
121
+ return defineTool({
122
+ name: HANDOFF_GET_TOOL,
123
+ description: 'Fetch the FULL text of an artifact a subagent parked with handoff_put, using the 20-hex id from its '
124
+ + '`handoff://<id>` handle. Only sessions in the SAME working directory as the putting session can '
125
+ + 'resolve a handle. Pass maxChars to read a head-truncated prefix when you only need an overview. '
126
+ + 'Artifacts expire after 24 hours.',
127
+ parameters: {
128
+ id: {
129
+ type: 'string',
130
+ required: true,
131
+ description: 'The 20-hex id from a `handoff://<id>` handle.',
132
+ },
133
+ maxChars: {
134
+ type: 'number',
135
+ description: 'Head-truncate the returned text to this many chars, with a trailing truncation note. Omit for the full text.',
136
+ },
137
+ },
138
+ output: {
139
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string', required: true } } },
140
+ render: (_args, value) => [{ type: 'text', text: value.text }],
141
+ },
142
+ async execute(args, exec) {
143
+ const projectKey = cwdProjectKey(exec.agent);
144
+ if (projectKey === undefined)
145
+ throw new HandoffToolError('handoff_get unavailable: no session cwd');
146
+ const outcome = await deps.store.get(projectKey, args.id);
147
+ if (!outcome.ok)
148
+ throw new HandoffToolError(`handoff_get failed: ${outcome.error}`);
149
+ return { text: applyMaxChars(outcome.text, args.maxChars) };
150
+ },
151
+ });
152
+ }
153
+ //# sourceMappingURL=tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.js","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAEnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAA;AACpD,OAAO,EAAgB,YAAY,EAAE,MAAM,YAAY,CAAA;AAGvD,MAAM,CAAC,MAAM,gBAAgB,GAAG,aAAa,CAAA;AAC7C,MAAM,CAAC,MAAM,gBAAgB,GAAG,aAAa,CAAA;AAE7C,mFAAmF;AACnF,MAAM,CAAC,MAAM,cAAc,GACzB,4EAA4E;MAC1E,iDAAiD,CAAA;AAErD,wEAAwE;AACxE,MAAM,OAAO,gBAAiB,SAAQ,KAAK;CAAG;AAS9C,8EAA8E;AAC9E,MAAM,UAAU,aAAa,CAAC,KAAwB;IACpD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IACzC,IAAI,CAAC;QACH,OAAO,YAAY,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAA;IAC3C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAA;IAClB,CAAC;AACH,CAAC;AAED,wEAAwE;AACxE,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,QAA4B;IACtE,IAAI,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,EAAE,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,EAAE;YACjH,MAAM,EAAE,CAAC,KAAc,EAAE,KAAuB,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC;SAC1F;QACD,KAAK,CAAC,OAAO,CAAC,IAAuC,EAAE,IAAuB;YAC5E,MAAM,UAAU,GAAG,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;YAC5C,IAAI,UAAU,KAAK,SAAS;gBAAE,MAAM,IAAI,gBAAgB,CAAC,yCAAyC,CAAC,CAAA;YACnG,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,EAAE,CAAC,CAAA;YACzD,IAAI,CAAC,OAAO,CAAC,EAAE;gBAAE,MAAM,IAAI,gBAAgB,CAAC,uBAAuB,OAAO,CAAC,KAAK,EAAE,CAAC,CAAA;YACnF,OAAO,EAAE,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAA;QAC7D,CAAC;KACF,CAAC,CAAA;AACJ,CAAC"}
package/lib/types.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Types for the subagent handoff store.
3
+ * @module @dsh-cc/handoff-store/types
4
+ */
5
+ /** Optional metadata attached to one handoff artifact. */
6
+ export interface HandoffMeta {
7
+ /** Short human/model-facing label (e.g. "critic review of plan X"). */
8
+ readonly label?: string;
9
+ /** Originating agent name, when known (e.g. "critic"). */
10
+ readonly agent?: string;
11
+ }
12
+ /**
13
+ * Live settings scope shape for the `cc-handoff` namespace. Kebab keys match
14
+ * the settings keys exactly.
15
+ */
16
+ export interface HandoffConfig {
17
+ /** Master flag. Defaults to `true`. */
18
+ enabled?: boolean;
19
+ /**
20
+ * Advisory size threshold in chars: reports/artifacts above it should be
21
+ * handed off with a summary. ADVISORY ONLY — `handoff_put` never enforces
22
+ * or rejects on it.
23
+ */
24
+ 'threshold-chars'?: number;
25
+ }
26
+ /** One append-only handoff-ledger row (`handoff/ledger.jsonl`). */
27
+ export interface HandoffLedgerRow {
28
+ readonly ts: string;
29
+ /** Project bucket key (sha256 of the putting session's cwd, 16 hex). */
30
+ readonly project: string;
31
+ readonly sessionId: string;
32
+ readonly id: string;
33
+ readonly label?: string;
34
+ readonly agent?: string;
35
+ readonly chars: number;
36
+ }
37
+ /** Typed retrieval failure for one handoff lookup. */
38
+ export type HandoffError = 'unknown_id' | 'expired' | 'corrupt';
39
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,0DAA0D;AAC1D,MAAM,WAAW,WAAW;IAC1B,uEAAuE;IACvE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IACvB,0DAA0D;IAC1D,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,uCAAuC;IACvC,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAA;CAC3B;AAED,mEAAmE;AACnE,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,wEAAwE;IACxE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CACvB;AAED,sDAAsD;AACtD,MAAM,MAAM,YAAY,GAAG,YAAY,GAAG,SAAS,GAAG,SAAS,CAAA"}
package/lib/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Types for the subagent handoff store.
3
+ * @module @dsh-cc/handoff-store/types
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG"}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@dsh-cc/handoff-store",
3
+ "description": "Subagent handoff store: handoff_put/handoff_get let sandboxed subagents park large artifacts in a content-addressed store and hand back a handoff://<id> handle",
4
+ "version": "0.6.2",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/dsh-cc/dsh-cc.git",
8
+ "directory": "packages/subagent/handoff-store"
9
+ },
10
+ "type": "module",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/index.d.ts",
14
+ "default": "./lib/index.js"
15
+ },
16
+ "./store": {
17
+ "types": "./lib/store.d.ts",
18
+ "default": "./lib/store.js"
19
+ },
20
+ "./src/*": "./src/*",
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "lib"
25
+ ],
26
+ "license": "Apache-2.0",
27
+ "peerDependencies": {
28
+ "@deepseek-ai/cordis": ">=0.1.2-rc.1",
29
+ "@deepseek-ai/dsh-settings": ">=0.1.2-rc.1",
30
+ "@deepseek-ai/schemastery": "^3.18.1",
31
+ "@deepseek-ai/dsh-util-values": ">=0.1.2-rc.1",
32
+ "@deepseek-ai/dsh-agent": ">=0.1.2-rc.1",
33
+ "@dsh-cc/tools": "^0.6.2",
34
+ "@dsh-cc/session-cwd": "^0.6.2"
35
+ },
36
+ "devDependencies": {
37
+ "@deepseek-ai/cordis": "link:../../../../deepseek-harness/vendor/cordis",
38
+ "@deepseek-ai/dsh-agent": "link:../../../../deepseek-harness/packages/core/agent",
39
+ "@deepseek-ai/dsh-settings": "link:../../../../deepseek-harness/packages/settings/settings",
40
+ "@deepseek-ai/schemastery": "link:../../../../deepseek-harness/vendor/schemastery",
41
+ "@deepseek-ai/dsh-util-values": "link:../../../../deepseek-harness/packages/util/values",
42
+ "vitest": "^4.1.8",
43
+ "@dsh-cc/session-cwd": "^0.6.2",
44
+ "@dsh-cc/tools": "^0.6.2"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ }
49
+ }