@fatelabs/opencode-estelle 0.0.0-stage → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +6 -0
  3. package/README.md +46 -2
  4. package/adapters/claude.mjs +17 -0
  5. package/adapters/codex.mjs +85 -0
  6. package/adapters/cursor.mjs +66 -0
  7. package/adapters/dsh-host.mjs +181 -0
  8. package/adapters/dsh-plugin.mjs +11 -0
  9. package/adapters/dsh.mjs +54 -0
  10. package/adapters/grok.mjs +63 -0
  11. package/adapters/host-bridge.mjs +85 -0
  12. package/adapters/kimi.mjs +135 -0
  13. package/adapters/opencode-mirror.mjs +103 -0
  14. package/adapters/opencode-plugin.mjs +143 -0
  15. package/adapters/opencode.mjs +15 -0
  16. package/adapters/pi-extension.mjs +107 -0
  17. package/adapters/pi.mjs +13 -0
  18. package/adapters/plugin-envelope.mjs +56 -0
  19. package/agents/estelle-grounder.md +34 -0
  20. package/agents/estelle-historian.md +28 -0
  21. package/agents/estelle-repair.md +29 -0
  22. package/agents/estelle-reviewer.md +32 -0
  23. package/commands/cloud.md +28 -0
  24. package/commands/code.md +6 -0
  25. package/commands/handoff.md +25 -0
  26. package/commands/monitor.md +6 -0
  27. package/commands/resume.md +6 -0
  28. package/commands/review.md +6 -0
  29. package/commands/rooms.md +7 -0
  30. package/instructions.md +19 -0
  31. package/package.json +34 -4
  32. package/runtime/auth.mjs +27 -0
  33. package/runtime/checkpoint.mjs +208 -0
  34. package/runtime/claude-setup.mjs +130 -0
  35. package/runtime/cli.mjs +112 -0
  36. package/runtime/codex-trust.mjs +68 -0
  37. package/runtime/credential.mjs +341 -0
  38. package/runtime/dsh-session.mjs +91 -0
  39. package/runtime/dsh-telemetry.mjs +31 -0
  40. package/runtime/hooks.mjs +234 -0
  41. package/runtime/identity.mjs +20 -0
  42. package/runtime/io.mjs +155 -0
  43. package/runtime/key-check.mjs +51 -0
  44. package/runtime/kimi-history.mjs +163 -0
  45. package/runtime/mailbox.mjs +46 -0
  46. package/runtime/migration.mjs +118 -0
  47. package/runtime/move.mjs +443 -0
  48. package/runtime/native-export.mjs +204 -0
  49. package/runtime/native-index.mjs +77 -0
  50. package/runtime/native-tree.mjs +117 -0
  51. package/runtime/queued-context.mjs +152 -0
  52. package/runtime/redact.mjs +74 -0
  53. package/runtime/reindex.mjs +259 -0
  54. package/runtime/setup.mjs +174 -0
  55. package/runtime/stream.mjs +755 -0
  56. package/runtime/version.mjs +2 -0
  57. package/runtime/write-warning.mjs +67 -0
  58. package/skills/abstain-right/SKILL.md +19 -0
  59. package/skills/api-call-ground/SKILL.md +19 -0
  60. package/skills/bug-hunt/SKILL.md +20 -0
  61. package/skills/chain-of-verification/SKILL.md +19 -0
  62. package/skills/change-impact/SKILL.md +19 -0
  63. package/skills/coding-workflow/SKILL.md +20 -0
  64. package/skills/commit-guard/SKILL.md +20 -0
  65. package/skills/context-checkpoint/SKILL.md +19 -0
  66. package/skills/continuity-brief/SKILL.md +19 -0
  67. package/skills/dead-code-sweep/SKILL.md +19 -0
  68. package/skills/deep-search/SKILL.md +19 -0
  69. package/skills/diff-review/SKILL.md +19 -0
  70. package/skills/estelle/SKILL.md +119 -0
  71. package/skills/estelle-loop/SKILL.md +19 -0
  72. package/skills/estelle-monitor-install/SKILL.md +20 -0
  73. package/skills/evidence-traceability-audit/SKILL.md +19 -0
  74. package/skills/grounded-generate/SKILL.md +19 -0
  75. package/skills/incident-rca/SKILL.md +20 -0
  76. package/skills/mutation-test/SKILL.md +19 -0
  77. package/skills/program-repair/SKILL.md +20 -0
  78. package/skills/prompt-injection-defense/SKILL.md +19 -0
  79. package/skills/property-based-test/SKILL.md +19 -0
  80. package/skills/refactor-rfc/SKILL.md +19 -0
  81. package/skills/root-cause-loop/SKILL.md +19 -0
  82. package/skills/test-first/SKILL.md +19 -0
  83. package/skills/threat-model-stride/SKILL.md +19 -0
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 2025 OpenAI
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.
package/NOTICE ADDED
@@ -0,0 +1,6 @@
1
+ Estelle Plugins
2
+ Copyright Fate Labs
3
+
4
+ Includes adapted public plugin assets and hook behavior from uqeu/estelle-cli,
5
+ commit 6d5633d5537160ce8632a01d86c619ddc3a3e29e (Apache-2.0).
6
+ The hosted Estelle backend is not included.
package/README.md CHANGED
@@ -1,3 +1,47 @@
1
- # Temporary Holding Version
1
+ # OpenCode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Package: `plugins/opencode` (npm name `@fatelabs/opencode-estelle`). Requires OpenCode 1.19 or later, Node.js 22 on
4
+ the `PATH` of the OpenCode process, and `ESTELLE_API_KEY` in that process's environment for hooks. Written and tested
5
+ against OpenCode 1.19.6.
6
+
7
+ One plugin adds everything: the Estelle MCP server, the `/estelle:*` commands, four Estelle subagents, the skills,
8
+ Estelle's instructions and the session hooks. Nothing else is configured by hand.
9
+
10
+ ## Install
11
+
12
+ From npm, once the package is published:
13
+
14
+ ```sh
15
+ opencode plugin @fatelabs/opencode-estelle -g
16
+ ```
17
+
18
+ Before that, from a clone of this repository (the path must be absolute):
19
+
20
+ ```json
21
+ { "plugin": ["file:///absolute/path/to/estelle-plugins/plugins/opencode"] }
22
+ ```
23
+
24
+ in `~/.config/opencode/opencode.json`, or in a project's `opencode.json` for one project. Restart OpenCode.
25
+
26
+ ## Sign in
27
+
28
+ With `ESTELLE_API_KEY` set, MCP and the hooks use that one key. Without it, MCP signs in with OpenCode's own OAuth
29
+ (`opencode mcp auth Estelle`) and the hooks report `credential_missing` in `doctor`; recall, capture and identity need
30
+ the key.
31
+
32
+ ## Check it
33
+
34
+ - `opencode mcp list` shows `Estelle connected`.
35
+ - In a session, `/estelle:resume` is offered, and the agent list has `estelle-reviewer`.
36
+ - `node <package>/runtime/cli.mjs doctor` shows `opencode` status rows after a turn.
37
+
38
+ If you use an xAI model: Estelle's `review` tool schema is refused by xAI until a server change lands. Add
39
+ `"tools": { "Estelle_review": false }` to your config meanwhile.
40
+
41
+ What OpenCode can and cannot do for Estelle, with sources: [docs/hosts/opencode.md](https://github.com/Fate-Labs-CA/estelle-plugins/blob/main/docs/hosts/opencode.md).
42
+
43
+ ## Copy/paste setup prompt
44
+
45
+ ```text
46
+ Install Estelle for OpenCode from https://github.com/Fate-Labs-CA/estelle-plugins using plugins/opencode. Follow docs/install/opencode.md. Use `opencode plugin @fatelabs/opencode-estelle -g` if the package is on npm; otherwise add the absolute file:// path of plugins/opencode to the plugin array of my OpenCode config, preserving everything else in it. Keep hooks and MCP on the same ESTELLE_API_KEY environment key; never request or display credentials. Then tell me to restart OpenCode. Report package loading, `opencode mcp list`, and observed hooks separately. No paid installation tests.
47
+ ```
@@ -0,0 +1,17 @@
1
+ export function normalize(raw) {
2
+ return {
3
+ host: 'claude-code', event: raw.hook_event_name, sessionId: raw.session_id,
4
+ cwd: raw.cwd, transcriptPath: raw.transcript_path || undefined,
5
+ prompt: typeof raw.prompt === 'string' ? raw.prompt : '',
6
+ toolName: raw.tool_name || '', toolInput: raw.tool_input || {},
7
+ toolResponse: raw.tool_response, agentId: raw.agent_id, agentType: raw.agent_type,
8
+ agentTranscriptPath: raw.agent_transcript_path, raw,
9
+ };
10
+ }
11
+
12
+ const CONTEXT_EVENTS = new Set(['SessionStart', 'UserPromptSubmit', 'PreToolUse',
13
+ 'PostToolUse', 'SubagentStart']);
14
+ export function formatContext(text, event) {
15
+ if (!text || !CONTEXT_EVENTS.has(event)) return null;
16
+ return { hookSpecificOutput: { hookEventName: event, additionalContext: text } };
17
+ }
@@ -0,0 +1,85 @@
1
+ // Native Codex hook contract: https://github.com/openai/codex/tree/rust-v0.166.0/codex-rs/hooks
2
+ export const HOOK_EVENTS = Object.freeze([
3
+ 'PreModelRequest', 'PostModelRequest', 'PreToolUse', 'PermissionRequest',
4
+ 'PostToolUse', 'PreCompact', 'PostCompact', 'SessionStart', 'SessionEnd',
5
+ 'UserPromptSubmit', 'SubagentStart', 'SubagentStop', 'Stop', 'Interrupt',
6
+ ]);
7
+ const CONTEXT_EVENTS = new Set([
8
+ 'SessionStart', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'SubagentStart',
9
+ ]);
10
+ const PERMISSION_MODES = new Set(['default', 'acceptEdits', 'plan', 'dontAsk', 'bypassPermissions']);
11
+ const REQUIRED = Object.freeze({
12
+ PreModelRequest: ['model', 'turn_id'],
13
+ PostModelRequest: ['model', 'turn_id', 'status', 'error', 'token_usage'],
14
+ PreToolUse: ['model', 'turn_id', 'permission_mode', 'tool_name', 'tool_input', 'tool_use_id'],
15
+ PermissionRequest: ['model', 'turn_id', 'permission_mode', 'tool_name', 'tool_input'],
16
+ PostToolUse: ['model', 'turn_id', 'permission_mode', 'tool_name', 'tool_input', 'tool_use_id', 'tool_response'],
17
+ PreCompact: ['model', 'turn_id', 'trigger'],
18
+ PostCompact: ['model', 'turn_id', 'trigger'],
19
+ SessionStart: ['model', 'permission_mode', 'source'],
20
+ SessionEnd: ['reason'],
21
+ UserPromptSubmit: ['model', 'turn_id', 'permission_mode', 'prompt'],
22
+ SubagentStart: ['model', 'turn_id', 'permission_mode', 'agent_id', 'agent_type'],
23
+ SubagentStop: ['model', 'turn_id', 'permission_mode', 'agent_id', 'agent_type',
24
+ 'agent_transcript_path', 'last_assistant_message', 'stop_hook_active'],
25
+ Stop: ['model', 'turn_id', 'permission_mode', 'last_assistant_message', 'stop_hook_active'],
26
+ Interrupt: ['model', 'turn_id', 'permission_mode'],
27
+ });
28
+ const STRING_FIELDS = ['model', 'turn_id', 'permission_mode', 'tool_name', 'tool_use_id',
29
+ 'trigger', 'source', 'reason', 'prompt', 'agent_id', 'agent_type', 'last_assistant_message', 'status'];
30
+ const nullableString = (value, name) => {
31
+ if (value !== null && typeof value !== 'string') throw new TypeError(`${name} must be a string or null`);
32
+ };
33
+
34
+ /** Validate host identity and preserve wire fields without inventing transcript or turn IDs. */
35
+ export function normalize(payload) {
36
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new TypeError('Codex hook input must be an object');
37
+ const event = payload.hook_event_name;
38
+ if (!HOOK_EVENTS.includes(event)) throw new TypeError('Unsupported Codex hook_event_name');
39
+ for (const key of ['session_id', 'cwd']) {
40
+ if (typeof payload[key] !== 'string' || !payload[key]) throw new TypeError(`Codex ${key} is required`);
41
+ }
42
+ for (const key of ['transcript_path', ...REQUIRED[event]]) {
43
+ if (!Object.hasOwn(payload, key)) throw new TypeError(`Codex ${key} is required for ${event}`);
44
+ }
45
+ for (const key of STRING_FIELDS) {
46
+ if (Object.hasOwn(payload, key) && typeof payload[key] !== 'string') throw new TypeError(`Codex ${key} must be a string`);
47
+ }
48
+ nullableString(payload.transcript_path, 'transcript_path');
49
+ if (Object.hasOwn(payload, 'agent_transcript_path')) nullableString(payload.agent_transcript_path, 'agent_transcript_path');
50
+ if (Object.hasOwn(payload, 'error')) nullableString(payload.error, 'error');
51
+ if (Object.hasOwn(payload, 'stop_hook_active') && typeof payload.stop_hook_active !== 'boolean') throw new TypeError('Codex stop_hook_active must be boolean');
52
+ if (payload.permission_mode !== undefined && !PERMISSION_MODES.has(payload.permission_mode)) throw new TypeError('Unsupported Codex permission_mode');
53
+ if (payload.trigger !== undefined && !['manual', 'auto'].includes(payload.trigger)) throw new TypeError('Unsupported Codex compact trigger');
54
+ if (payload.source !== undefined && !['startup', 'resume', 'clear', 'compact', 'fork'].includes(payload.source)) throw new TypeError('Unsupported Codex session source');
55
+ if (event === 'PostModelRequest' && !['completed', 'failed', 'cancelled'].includes(payload.status)) throw new TypeError('Unsupported Codex model request status');
56
+ return normalizedFields(payload, event);
57
+ }
58
+
59
+ function normalizedFields(payload, event) {
60
+ return {
61
+ host: 'codex', event, sessionId: payload.session_id, turnId: payload.turn_id ?? null,
62
+ transcriptPath: payload.transcript_path, cwd: payload.cwd, prompt: payload.prompt ?? null,
63
+ toolName: payload.tool_name ?? null, toolInput: payload.tool_input ?? null,
64
+ toolResponse: payload.tool_response ?? null, toolUseId: payload.tool_use_id ?? null,
65
+ agentId: payload.agent_id ?? null, agentType: payload.agent_type ?? null,
66
+ agentTranscriptPath: payload.agent_transcript_path ?? null,
67
+ lastAssistantMessage: payload.last_assistant_message ?? null,
68
+ source: payload.source ?? null, trigger: payload.trigger ?? null,
69
+ permissionMode: payload.permission_mode ?? null, model: payload.model ?? null, raw: payload,
70
+ };
71
+ }
72
+
73
+ /** Only native context-bearing hooks may inject. Model-request hooks are observers. */
74
+ export function formatContext(text, event, options = {}) {
75
+ if (typeof text !== 'string') throw new TypeError('Codex hook context must be text');
76
+ if (!HOOK_EVENTS.includes(event)) throw new TypeError('Unsupported Codex context event');
77
+ const replacement = Object.hasOwn(options, 'updatedMCPToolOutput');
78
+ if (replacement && event !== 'PostToolUse') throw new TypeError('updatedMCPToolOutput requires PostToolUse');
79
+ if (!CONTEXT_EVENTS.has(event) || (!text.trim() && !replacement)) return null;
80
+ return { hookSpecificOutput: {
81
+ hookEventName: event,
82
+ ...(text.trim() ? { additionalContext: text } : {}),
83
+ ...(replacement ? { updatedMCPToolOutput: options.updatedMCPToolOutput } : {}),
84
+ } };
85
+ }
@@ -0,0 +1,66 @@
1
+ // Cursor native lowerCamel hooks. Transcript dialect is not assumed from its filename.
2
+ import { isAbsolute, normalize as pathNormalize } from 'node:path';
3
+ const EVENTS = Object.freeze({ sessionStart: 'SessionStart', sessionEnd: 'SessionEnd',
4
+ beforeSubmitPrompt: 'UserPromptSubmit', preToolUse: 'PreToolUse', postToolUse: 'PostToolUse',
5
+ postToolUseFailure: 'PostToolUseFailure', subagentStart: 'SubagentStart', subagentStop: 'SubagentStop',
6
+ preCompact: 'PreCompact', stop: 'Stop' });
7
+ export const HOOK_EVENTS = Object.freeze(Object.keys(EVENTS));
8
+ const CONTEXT_EVENTS = new Set(['SessionStart', 'PostToolUse', 'PostToolUseFailure']);
9
+ const optionalText = (value, name) => {
10
+ if (value != null && typeof value !== 'string') throw new TypeError(`Cursor ${name} must be text`);
11
+ return value ?? null;
12
+ };
13
+
14
+ function workspace(payload) {
15
+ if (typeof payload.cwd === 'string' && isAbsolute(payload.cwd)) return pathNormalize(payload.cwd);
16
+ const roots = payload.workspace_roots;
17
+ if (!Array.isArray(roots) || roots.length !== 1 || typeof roots[0] !== 'string' || !isAbsolute(roots[0])) {
18
+ throw new TypeError('Cursor workspace requires an explicit absolute cwd or one workspace root');
19
+ }
20
+ return pathNormalize(roots[0]);
21
+ }
22
+
23
+ function toolResponse(payload, event) {
24
+ if (event !== 'PostToolUse') return null;
25
+ if (typeof payload.tool_output !== 'string') throw new TypeError('Cursor tool_output must be JSON text');
26
+ try { return JSON.parse(payload.tool_output); }
27
+ catch { throw new TypeError('Cursor tool_output must be valid JSON'); }
28
+ }
29
+
30
+ export function normalize(payload) {
31
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new TypeError('Cursor hook input must be an object');
32
+ const event = EVENTS[payload.hook_event_name];
33
+ if (!event) throw new TypeError('Unsupported Cursor hook event');
34
+ const sessionId = payload.conversation_id;
35
+ if (typeof sessionId !== 'string' || !sessionId || (payload.session_id != null && payload.session_id !== sessionId)) {
36
+ throw new TypeError('Cursor conversation identity is missing or disagrees with session_id');
37
+ }
38
+ const toolName = optionalText(payload.tool_name, 'tool_name');
39
+ if (['PreToolUse', 'PostToolUse', 'PostToolUseFailure'].includes(event) && (!toolName || !Object.hasOwn(payload, 'tool_input'))) {
40
+ throw new TypeError('Cursor tool events require tool_name and tool_input');
41
+ }
42
+ const response = toolResponse(payload, event);
43
+ return { host: 'cursor', event, sessionId, cwd: workspace(payload),
44
+ turnId: optionalText(payload.generation_id, 'generation_id'),
45
+ transcriptPath: optionalText(payload.transcript_path, 'transcript_path'),
46
+ agentTranscriptPath: optionalText(payload.agent_transcript_path, 'agent_transcript_path'),
47
+ prompt: optionalText(payload.prompt, 'prompt'), toolName, toolInput: payload.tool_input ?? null,
48
+ toolResponse: response, toolUseId: optionalText(payload.tool_use_id, 'tool_use_id'),
49
+ model: optionalText(payload.model_id ?? payload.model, 'model'),
50
+ // user_email identifies a Cursor account, never an authenticated Estelle owner.
51
+ raw: { ...payload, tool_response: response && typeof response === 'object'
52
+ ? { ...response, is_error: response.is_error === true || response.isError === true } : response } };
53
+ }
54
+
55
+ /** Only passive additional_context boundaries are used; stop never auto-continues the agent. */
56
+ export function formatContext(text, event) {
57
+ if (typeof text !== 'string') throw new TypeError('Cursor hook context must be text');
58
+ return CONTEXT_EVENTS.has(event) && text.trim() ? { additional_context: text } : null;
59
+ }
60
+
61
+ /** Cursor rejects schema-invalid successful permission responses, even for optional hooks. */
62
+ export function defaultOutput(nativeEvent) {
63
+ if (nativeEvent === 'beforeSubmitPrompt') return { continue: true };
64
+ if (nativeEvent === 'preToolUse' || nativeEvent === 'subagentStart') return { permission: 'allow' };
65
+ return null;
66
+ }
@@ -0,0 +1,181 @@
1
+ // The hook host for DeepSeek Harness. dsh has no external hook protocol, so these listeners are the host: they run on dsh's
2
+ // own events and start the same `runtime/cli.mjs hook` process every other host starts. dsh-plugin.mjs is the mounted entry.
3
+ // Hooks never stop a turn: a failed hook is logged and the agent continues, as on every other host.
4
+ import { execFile } from 'node:child_process';
5
+ import { appendFile, mkdir, readdir, readFile } from 'node:fs/promises';
6
+ import { readdirSync, readFileSync } from 'node:fs';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { dirname, join } from 'node:path';
9
+ import { hash, stateDirectory } from '../runtime/io.mjs';
10
+ import { WRITE_TOOLS } from './dsh.mjs';
11
+
12
+ const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
13
+ const CLI = join(ROOT, 'runtime', 'cli.mjs');
14
+ const HOOK_TIMEOUT_MS = 20_000;
15
+ const SESSION_END_TIMEOUT_MS = 3_000;
16
+ const MAX_HOOK_OUTPUT_BYTES = 2_000_000;
17
+ const MAX_TRANSCRIPT_BYTES = 256 * 1024 * 1024;
18
+ const MAX_SKILLS = 256;
19
+ const SKILL_RANK = 650; // Below every root dsh scans, so a person's own skill of the same name wins.
20
+ const CONTEXT_SOURCE = Object.freeze({ kind: 'estelle' });
21
+ const CAPTURED = new Set(['user/message', 'assistant/message', 'tool/call', 'tool/result', 'turn/end']);
22
+ const WRITES = new Set(WRITE_TOOLS);
23
+
24
+ const textBlocks = text => [{ type: 'text', text }];
25
+ const blocksText = content => (Array.isArray(content) ? content : []).filter(block => block?.type === 'text')
26
+ .map(block => block.text).join('');
27
+ const isSubagent = session => session?.header?.origin === 'subagent';
28
+
29
+ /** One hook, one process, one bounded answer. Null on any failure: the runtime records its own diagnostics. */
30
+ function runHook(ctx, payload, timeout = HOOK_TIMEOUT_MS) {
31
+ return new Promise(resolve => {
32
+ const child = execFile(process.execPath, [CLI, 'hook', 'dsh'], { cwd: payload.cwd, timeout, maxBuffer: MAX_HOOK_OUTPUT_BYTES },
33
+ (error, stdout) => {
34
+ if (error) { ctx.logger.warn(`estelle: ${payload.hook_event_name} hook failed: ${error.code ?? error.message}`); return resolve(null); }
35
+ try { resolve(stdout.trim() ? JSON.parse(stdout) : null); }
36
+ catch { ctx.logger.warn(`estelle: ${payload.hook_event_name} hook answered with text that is not JSON`); resolve(null); }
37
+ });
38
+ child.stdin.on('error', () => {}); // A hook that died before reading its input already reported through the callback.
39
+ child.stdin.end(JSON.stringify(payload));
40
+ });
41
+ }
42
+
43
+ /** The readable JSONL our runtime maps. dsh's own log is compressed and its persistence seam exposes no path. */
44
+ function transcriptWriter(ctx) {
45
+ const directory = join(stateDirectory(), 'dsh-transcripts');
46
+ const tails = new Map();
47
+ const written = new Map();
48
+ const pathOf = id => join(directory, `${hash(id).slice(0, 40)}.jsonl`);
49
+ const append = (id, event) => {
50
+ if (!CAPTURED.has(event.type)) return;
51
+ const line = JSON.stringify({ type: event.type, seq: event.seq, time: event.time, data: event.data }) + '\n';
52
+ const size = (written.get(id) ?? 0) + Buffer.byteLength(line);
53
+ if (size > MAX_TRANSCRIPT_BYTES) return; // A later reader sees an incomplete log, never a truncated line.
54
+ written.set(id, size);
55
+ const next = (tails.get(id) ?? mkdir(directory, { recursive: true, mode: 0o700 }))
56
+ .then(() => appendFile(pathOf(id), line, { mode: 0o600 }))
57
+ .catch(error => ctx.logger.warn(`estelle: transcript write failed: ${error.code ?? error.message}`));
58
+ tails.set(id, next);
59
+ };
60
+ return { append, pathOf, flush: id => tails.get(id) ?? Promise.resolve() };
61
+ }
62
+
63
+ function registerCommands(ctx, createUserMessage) {
64
+ ctx.inject(['commands'], child => {
65
+ const directory = join(ROOT, 'commands');
66
+ for (const entry of readdirSync(directory).sort()) {
67
+ const source = readFileSync(join(directory, entry), 'utf8');
68
+ const [, description, body] = /^---\ndescription: (.+)\n---\n([\s\S]+)$/.exec(source) ?? [];
69
+ if (!description) throw new Error(`Command needs one description line: ${entry}`);
70
+ child.commands.register({
71
+ name: `estelle-${entry.replace(/\.md$/, '')}`, description, input: { hint: '<what you want>' },
72
+ // A dsh command creates no model message by itself. Ours are instructions to the model, so they submit one.
73
+ handler: ({ agent, rawInput }) => {
74
+ const asked = rawInput.trim() || 'what the person asked for';
75
+ agent.followup(createUserMessage({ content: textBlocks(body.replaceAll('$ARGUMENTS', asked)), source: { kind: 'user' } }));
76
+ return { kind: 'success' };
77
+ },
78
+ });
79
+ }
80
+ });
81
+ }
82
+
83
+ function registerSkills(ctx) {
84
+ ctx.inject(['skills'], child => {
85
+ const directory = join(ROOT, 'skills');
86
+ const candidates = async () => {
87
+ const names = (await readdir(directory)).sort().slice(0, MAX_SKILLS);
88
+ const rows = await Promise.all(names.map(async skill => {
89
+ const locator = join(directory, skill, 'SKILL.md');
90
+ const [, frontMatter] = /^---\n([\s\S]*?)\n---\n/.exec(await readFile(locator, 'utf8')) ?? [];
91
+ const description = /^description: (.+)$/m.exec(frontMatter ?? '')?.[1]?.replace(/^"|"$/g, '');
92
+ return description ? { name: skill, description, locator, provider: 'estelle', source: 'bundled', rank: SKILL_RANK,
93
+ invocation: { modelInvocable: true, userInvocable: true }, resourceBase: { kind: 'directory', path: dirname(locator) } } : null;
94
+ }));
95
+ return rows.filter(Boolean);
96
+ };
97
+ child.skills.registerProvider(() => ({ name: 'estelle', list: candidates, async get(candidate) {
98
+ const { rank: _rank, locator: _locator, ...summary } = candidate;
99
+ return { ...summary, content: await readFile(candidate.locator, 'utf8') };
100
+ } }));
101
+ });
102
+ }
103
+
104
+ function registerInstructions(ctx) {
105
+ ctx.inject(['systemPrompt'], child => {
106
+ const text = readFileSync(join(ROOT, 'instructions.md'), 'utf8');
107
+ child.systemPrompt.section({ name: 'estelle', order: child.systemPrompt.getSectionOrder('TOOL_GOAL'), text });
108
+ });
109
+ }
110
+
111
+ export function applyEstelle(ctx, { createUserMessage }) {
112
+ const contextMessage = text => createUserMessage({ content: textBlocks(text), source: CONTEXT_SOURCE });
113
+ const transcripts = transcriptWriter(ctx);
114
+ const running = new Set();
115
+ const track = work => { running.add(work); work.finally(() => running.delete(work)); return work; };
116
+ // Dispose returns once hooks in flight settle, and dsh bounds its own shutdown at five seconds.
117
+ ctx.effect(() => () => Promise.allSettled([...running]), 'estelle: drain hooks in flight');
118
+ const cwdOf = agent => agent.session?.header?.cwd ?? process.cwd();
119
+ const base = (agent, event) => ({ hook_event_name: event, session_id: agent.session.header.id, cwd: cwdOf(agent),
120
+ transcript_path: transcripts.pathOf(agent.session.header.id) });
121
+ const live = new Map();
122
+
123
+ ctx.on('session/event', (session, event) => {
124
+ if (isSubagent(session)) return;
125
+ transcripts.append(session.header.id, event);
126
+ // turn/end, not agent/turn-stopping: it is the event that makes the turn's final line readable by the stream.
127
+ const agent = live.get(session.header.id);
128
+ if (event.type === 'turn/end' && agent) {
129
+ track(transcripts.flush(session.header.id).then(() => runHook(ctx, base(agent, 'Stop'))));
130
+ }
131
+ });
132
+
133
+ ctx.on('agent/created', async ({ agent, source }) => {
134
+ if (isSubagent(agent.session)) return;
135
+ live.set(agent.session.header.id, agent);
136
+ const output = await track(runHook(ctx, { ...base(agent, 'SessionStart'), source: String(source ?? 'startup') }));
137
+ if (output?.context) agent.inject(contextMessage(output.context));
138
+ });
139
+
140
+ ctx.on('agent/pre-step', async ({ agent, messages }, next) => {
141
+ const asked = messages.filter(message => message.source?.kind === 'user');
142
+ if (!asked.length || isSubagent(agent.session)) return next();
143
+ const output = await track(runHook(ctx, { ...base(agent, 'UserPromptSubmit'), prompt: asked.map(m => blocksText(m.content)).join('\n') }));
144
+ const decision = await next();
145
+ return output?.context && decision.kind === 'enter'
146
+ ? { ...decision, messages: [...decision.messages, contextMessage(output.context)] } : decision;
147
+ });
148
+
149
+ ctx.on('tools/pre-execute', async (execution, next) => {
150
+ if (!execution.agent || !WRITES.has(execution.name)) return next();
151
+ const output = await track(runHook(ctx, { ...base(execution.agent, 'PreToolUse'), tool_name: execution.name,
152
+ tool_input: execution.arguments, tool_use_id: execution.callId }));
153
+ // ⛔ A warning and never a refusal: the write goes ahead either way.
154
+ if (output?.warning) {
155
+ ctx.logger.warn(output.warning);
156
+ execution.agent.inject(contextMessage(output.warning));
157
+ }
158
+ return next();
159
+ });
160
+
161
+ ctx.on('tools/post-execute', async (execution, result, next) => {
162
+ const decision = await next();
163
+ if (execution.agent && !isSubagent(execution.agent.session)) {
164
+ // Observation only. The agent does not wait for capture, and dispose drains what is still running.
165
+ track(transcripts.flush(execution.agent.session.header.id).then(() => runHook(ctx, { ...base(execution.agent, 'PostToolUse'),
166
+ tool_name: execution.name, tool_input: execution.arguments, tool_use_id: execution.callId,
167
+ tool_response: { is_error: result?.isError === true } })));
168
+ }
169
+ return decision;
170
+ });
171
+
172
+ ctx.on('agent/disposed', ({ agent }) => {
173
+ if (isSubagent(agent.session)) return;
174
+ live.delete(agent.session.header.id);
175
+ track(transcripts.flush(agent.session.header.id).then(() => runHook(ctx, base(agent, 'SessionEnd'), SESSION_END_TIMEOUT_MS)));
176
+ });
177
+
178
+ registerCommands(ctx, createUserMessage);
179
+ registerSkills(ctx);
180
+ registerInstructions(ctx);
181
+ }
@@ -0,0 +1,11 @@
1
+ // The Cordis plugin plugins/dsh/cordis.patch.yml mounts. The one line that needs dsh's own package lives here, so the
2
+ // listeners in dsh-host.mjs can run under test without an installed harness.
3
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
4
+ import { applyEstelle } from './dsh-host.mjs';
5
+
6
+ export const name = 'estelle';
7
+ export const inject = ['agents'];
8
+
9
+ export function apply(ctx) {
10
+ applyEstelle(ctx, { createUserMessage });
11
+ }