@try-works/dsh-righthand 0.1.6 → 0.1.8

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/README.md CHANGED
@@ -28,6 +28,9 @@ dsh --profile <profile> --patch ./cordis.patch.yml
28
28
  | `rh_task_create` / `rh_task_list` / `rh_task_next` / `rh_task_update` / `rh_task_delete` | tasks | `ctx.storageDomain` (typed `righthand_tasks` domain; state machine open → done/failed) |
29
29
  | `rh_text_summarise` / `rh_text_extract` / `rh_text_classify` / `rh_text_translate` | text | `ctx.llm` (one model call per verb) |
30
30
  | `rh_weather_forecast` / `rh_weather_air` | weather | Open-Meteo (keyless), every request through the SSRF-guarded fetcher |
31
+ | `rh_files_put` / `rh_files_get` / `rh_files_list` / `rh_files_share` / `rh_files_delete` | files | Cloudflare R2 (S3-compatible, SigV4-signed; credentials from `R2_ACCESS_KEY_ID` / `R2_SECRET_ACCESS_KEY`, bucket from settings) |
32
+ | `rh_events_create` / `rh_events_due` / `rh_events_list` / `rh_events_free` / `rh_events_cancel` | events | `ctx.storageDomain` (typed `righthand_events` domain; the agent is the scheduler — `rh_events_due` runs each turn) |
33
+ | `rh_notify_send` | notify | ntfy.sh (keyless — the topic name is the only secret) |
31
34
  | `rh_credential_describe` / `rh_credential_set` / `rh_credential_unset` | secrets | `ctx.credentials` (values never echoed) |
32
35
  | `rh_settings_get` / `rh_settings_set` | secrets | `ctx.settings` (namespace `righthand`) |
33
36
  | `rh_run` | exec | `ctx.subprocess` (collect mode, bounded output) |
@@ -67,6 +70,8 @@ Namespace "righthand" (registered by the secrets family):
67
70
  | `accountId` | "" | Cloudflare account id used by righthand Cloudflare tools |
68
71
  | `defaultScriptPrefix` | "rh-" | default name prefix for generated workers/scripts |
69
72
  | `defaultZone` | "" | default Cloudflare zone |
73
+ | `defaultR2Bucket` | "" | default R2 bucket for `rh_files_*` |
74
+ | `defaultNotifyTopic` | "" | default ntfy topic for `rh_notify_send` |
70
75
 
71
76
  `rh_settings_get` returns the resolved values; `rh_settings_set` merges a
72
77
  partial patch (persisted by the harness settings provider).
@@ -84,6 +89,7 @@ canonical example of the current DSH-native form (tool-to-tool via
84
89
  |---|---|
85
90
  | `blueprint/daily-digest` | Collect sources, summarize, send on a schedule — extractive locally, LLM synthesis as escalation |
86
91
  | `blueprint/data-adapter` | Wrap one keyless public API as a tool family: guarded fetch, normalize, one tool per query. Worked example ships in the plugin: `rh_weather_*` |
92
+ | (phase 5) `rh_files_*` on R2 | The first family on an actual Cloudflare primitive: S3-compatible API, SigV4 signing pinned to the AWS test vector, credentials from the credential provider |
87
93
  | `blueprint/research-radar` | Multi-source research over a rolling window (Reddit, X, YouTube, HN, Polymarket, web): score, dedupe, synthesize with citations |
88
94
  | `blueprint/web-scraper` | Fetch a page, extract title/headings/links/text, make it searchable — static HTML first, render/vision as escalation |
89
95
  | `blueprint/vision-worker` | Cloudflare Worker exposing kimi-k2.6 vision: route image requests for text-only models, return a versioned `VisionEnvelope` |
@@ -141,10 +147,11 @@ so the agent cannot deploy or destroy without the gate.
141
147
 
142
148
  ## Service availability
143
149
 
144
- The store and task families need `ctx.storageDomain`, which the web profile
145
- provides (`storage` + `storage-json` + `storage-domain` rows). In a profile
146
- without it — e.g. the headless bundle — those nine tools stay dormant and the
147
- other seven tools still register; the plugin never fails the boot.
150
+ The store, task and events families need `ctx.storageDomain`, which the web
151
+ profile provides (`storage` + `storage-json` + `storage-domain` rows). In a
152
+ profile without it — e.g. the headless bundle — those fourteen tools stay
153
+ dormant and the other nineteen tools (secrets, settings, exec, text, weather,
154
+ files, notify) still register; the plugin never fails the boot.
148
155
 
149
156
  ## Development
150
157
 
@@ -0,0 +1,44 @@
1
+ /**
2
+ * events-tools — rh_events_* over ctx.storageDomain.
3
+ * Reminders and the free-slot query. The agent IS the scheduler:
4
+ * rh_events_due is the check the agent runs each turn — an event whose
5
+ * time has come is returned once (pending → notified), so a missed run
6
+ * cannot go quiet without a record. Repeating events are one-off here;
7
+ * a real scheduler is the documented Cloudflare cron escalation.
8
+ * @module dsh-righthand/events-tools
9
+ */
10
+ import type { Context } from '@deepseek-ai/cordis';
11
+ import type { Domain } from '@deepseek-ai/dsh-storage-domain';
12
+ export declare const name = "righthand-events";
13
+ export declare const inject: string[];
14
+ export interface Event {
15
+ id: string;
16
+ title: string;
17
+ detail: string;
18
+ at: string;
19
+ state: 'pending' | 'notified' | 'cancelled';
20
+ createdAt: string;
21
+ }
22
+ export declare const eventsDomain: {
23
+ name: string;
24
+ version: number;
25
+ tables: {
26
+ events: import("@deepseek-ai/dsh-storage-domain").DomainTableSpec<string, {
27
+ id: string;
28
+ title: string;
29
+ detail: string;
30
+ at: string;
31
+ state: "pending" | "notified" | "cancelled";
32
+ createdAt: string;
33
+ }>;
34
+ };
35
+ };
36
+ export type EventsDomain = Domain<typeof eventsDomain>;
37
+ /**
38
+ * Free slots: gaps of at least durationMinutes between pending events at or
39
+ * after now, within working hours 09:00–17:00, over the next horizonHours.
40
+ * Pure and exported for tests.
41
+ */
42
+ export declare function freeSlots(events: readonly Event[], now: Date, durationMinutes: number, horizonHours?: number): string[];
43
+ export declare function apply(ctx: Context): void;
44
+ //# sourceMappingURL=events-tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events-tools.d.ts","sourceRoot":"","sources":["../src/events-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAGlD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iCAAiC,CAAA;AAG7D,eAAO,MAAM,IAAI,qBAAqB,CAAA;AACtC,eAAO,MAAM,MAAM,UAA6B,CAAA;AAEhD,MAAM,WAAW,KAAK;IACpB,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,CAAA;IACd,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,SAAS,GAAG,UAAU,GAAG,WAAW,CAAC;IAC5C,SAAS,EAAE,MAAM,CAAA;CAClB;AAED,eAAO,MAAM,YAAY;;;;;;;;;;;;;CAavB,CAAA;AAEF,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,YAAY,CAAC,CAAA;AAMtD;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,SAAS,KAAK,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,EAAE,YAAY,SAAK,GAAG,MAAM,EAAE,CA6BnH;AAED,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAwJxC"}
@@ -0,0 +1,219 @@
1
+ /**
2
+ * events-tools — rh_events_* over ctx.storageDomain.
3
+ * Reminders and the free-slot query. The agent IS the scheduler:
4
+ * rh_events_due is the check the agent runs each turn — an event whose
5
+ * time has come is returned once (pending → notified), so a missed run
6
+ * cannot go quiet without a record. Repeating events are one-off here;
7
+ * a real scheduler is the documented Cloudflare cron escalation.
8
+ * @module dsh-righthand/events-tools
9
+ */
10
+ import { defineTool } from '@deepseek-ai/dsh-tools';
11
+ import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
12
+ import { z } from 'zod';
13
+ export const name = 'righthand-events';
14
+ export const inject = ['tools', 'storageDomain'];
15
+ export const eventsDomain = defineDomain({
16
+ name: 'righthand_events',
17
+ version: 1,
18
+ tables: {
19
+ events: domainTable(z.object({
20
+ id: z.string(),
21
+ title: z.string(),
22
+ detail: z.string(),
23
+ at: z.string(),
24
+ state: z.enum(['pending', 'notified', 'cancelled']),
25
+ createdAt: z.string(),
26
+ })),
27
+ },
28
+ });
29
+ function newId() {
30
+ return 'e-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6);
31
+ }
32
+ /**
33
+ * Free slots: gaps of at least durationMinutes between pending events at or
34
+ * after now, within working hours 09:00–17:00, over the next horizonHours.
35
+ * Pure and exported for tests.
36
+ */
37
+ export function freeSlots(events, now, durationMinutes, horizonHours = 24) {
38
+ const horizonEnd = now.getTime() + horizonHours * 3600000;
39
+ const busy = events
40
+ .filter(e => e.state === 'pending')
41
+ .map(e => new Date(e.at).getTime())
42
+ .filter(t => Number.isFinite(t) && t >= now.getTime() && t <= horizonEnd)
43
+ .sort((a, b) => a - b);
44
+ const slots = [];
45
+ let cursor = now.getTime();
46
+ const dayStart = (t) => {
47
+ const d = new Date(t);
48
+ d.setHours(9, 0, 0, 0);
49
+ return d.getTime();
50
+ };
51
+ const dayEnd = (t) => {
52
+ const d = new Date(t);
53
+ d.setHours(17, 0, 0, 0);
54
+ return d.getTime();
55
+ };
56
+ const need = durationMinutes * 60000;
57
+ for (const b of busy) {
58
+ let from = Math.max(cursor, dayStart(cursor));
59
+ if (from < b && b - from >= need && from + need <= dayEnd(from) && from + need <= horizonEnd) {
60
+ slots.push(new Date(from).toISOString());
61
+ }
62
+ cursor = Math.max(b, dayEnd(cursor) + 1);
63
+ if (cursor > horizonEnd)
64
+ break;
65
+ }
66
+ return slots;
67
+ }
68
+ export function apply(ctx) {
69
+ let domain;
70
+ let ready;
71
+ ctx.effect(() => {
72
+ ready = (async () => {
73
+ domain = await ctx.storageDomain.open(eventsDomain);
74
+ })();
75
+ return () => { };
76
+ });
77
+ const ensure = async () => {
78
+ if (domain === undefined) {
79
+ await ready;
80
+ }
81
+ if (domain === undefined)
82
+ throw new Error('righthand events are not open (storageDomain not mounted)');
83
+ return domain;
84
+ };
85
+ const all = async () => {
86
+ const d = await ensure();
87
+ return [...d.table('events').entries()].map(([, e]) => e);
88
+ };
89
+ ctx.tools.register(defineTool({
90
+ name: 'rh_events_create',
91
+ description: 'Schedule a reminder at an ISO datetime. One-off: the agent checks rh_events_due each turn and the event is delivered exactly once (pending to notified), so a missed run is never silently dropped.',
92
+ parameters: {
93
+ title: { type: 'string', required: true, description: 'What to be reminded of.' },
94
+ at: { type: 'string', required: true, description: 'ISO datetime when it is due, e.g. 2026-08-31T09:00:00Z.' },
95
+ detail: { type: 'string', description: 'Optional longer note.' },
96
+ },
97
+ output: {
98
+ schema: {
99
+ type: 'object',
100
+ additionalProperties: false,
101
+ properties: {
102
+ id: { type: 'string', required: true },
103
+ title: { type: 'string', required: true },
104
+ at: { type: 'string', required: true },
105
+ },
106
+ },
107
+ render: (_args, value) => [{ type: 'text', text: 'event ' + value.id + ': ' + value.title + ' at ' + value.at }],
108
+ },
109
+ async execute(args) {
110
+ const d = await ensure();
111
+ const at = new Date(args.at);
112
+ if (Number.isNaN(at.getTime()))
113
+ throw new Error('at must be a valid ISO datetime');
114
+ const event = {
115
+ id: newId(),
116
+ title: args.title.trim(),
117
+ detail: args.detail ?? '',
118
+ at: at.toISOString(),
119
+ state: 'pending',
120
+ createdAt: new Date().toISOString(),
121
+ };
122
+ if (event.title === '')
123
+ throw new Error('an event needs a title');
124
+ await d.table('events').put(event.id, event);
125
+ return { id: event.id, title: event.title, at: event.at };
126
+ },
127
+ }));
128
+ ctx.tools.register(defineTool({
129
+ name: 'rh_events_due',
130
+ description: 'The pending events whose time has come (at <= now). Each is delivered exactly once: returned events are marked notified. This is the check to run every turn — the agent is the scheduler.',
131
+ parameters: {},
132
+ output: {
133
+ schema: {
134
+ type: 'object',
135
+ additionalProperties: false,
136
+ properties: {
137
+ due: { type: 'array', required: true, items: { type: 'json' } },
138
+ },
139
+ },
140
+ render: (_args, value) => [{ type: 'text', text: value.due.length === 0 ? '(nothing due)' : value.due.map((e) => e.title + ' at ' + e.at).join(' / ') }],
141
+ },
142
+ async execute() {
143
+ const d = await ensure();
144
+ const now = Date.now();
145
+ const due = [];
146
+ for (const e of [...d.table('events').entries()].map(([, v]) => v)) {
147
+ if (e.state === 'pending' && new Date(e.at).getTime() <= now) {
148
+ const notified = { ...e, state: 'notified' };
149
+ await d.table('events').put(e.id, notified);
150
+ due.push(notified);
151
+ }
152
+ }
153
+ due.sort((a, b) => a.at.localeCompare(b.at));
154
+ return { due: due.map(e => ({ id: e.id, title: e.title, detail: e.detail, at: e.at })) };
155
+ },
156
+ }));
157
+ ctx.tools.register(defineTool({
158
+ name: 'rh_events_list',
159
+ description: 'List events: upcoming pending ones first, then notified and cancelled.',
160
+ parameters: {
161
+ state: { type: 'string', description: 'Filter: pending | notified | cancelled. Omit for all.' },
162
+ },
163
+ output: {
164
+ schema: { type: 'array', items: { type: 'json' } },
165
+ render: (_args, value) => [{ type: 'text', text: value.length === 0 ? '(no events)' : value.map((e) => e.at + ' ' + e.title + ' [' + e.state + ']').join(' / ') }],
166
+ },
167
+ async execute(args) {
168
+ const events = await all();
169
+ const wanted = args.state ?? null;
170
+ const filtered = wanted ? events.filter(e => e.state === wanted) : events;
171
+ const rank = { pending: 0, notified: 1, cancelled: 2 };
172
+ filtered.sort((a, b) => (rank[a.state] - rank[b.state]) || a.at.localeCompare(b.at));
173
+ return filtered.map(e => ({ id: e.id, title: e.title, detail: e.detail, at: e.at, state: e.state }));
174
+ },
175
+ }));
176
+ ctx.tools.register(defineTool({
177
+ name: 'rh_events_free',
178
+ description: 'When is there nothing booked: the next free slots of at least durationMinutes within working hours (09:00-17:00) over the next horizonHours.',
179
+ parameters: {
180
+ durationMinutes: { type: 'integer', required: true, description: 'How long the free block must be.' },
181
+ horizonHours: { type: 'integer', description: 'How far ahead to look (default 24).' },
182
+ },
183
+ output: {
184
+ schema: { type: 'array', items: { type: 'string' } },
185
+ render: (_args, value) => [{ type: 'text', text: value.length === 0 ? '(no free slot)' : value.join(' / ') }],
186
+ },
187
+ async execute(args) {
188
+ const events = await all();
189
+ return freeSlots(events, new Date(), args.durationMinutes, args.horizonHours ?? 24);
190
+ },
191
+ }));
192
+ ctx.tools.register(defineTool({
193
+ name: 'rh_events_cancel',
194
+ description: 'Cancel an event by id. Returns whether it existed. Cancelled events stay in the record — a cancellation is news too.',
195
+ parameters: {
196
+ id: { type: 'string', required: true, description: 'The event id.' },
197
+ },
198
+ output: {
199
+ schema: {
200
+ type: 'object',
201
+ additionalProperties: false,
202
+ properties: {
203
+ id: { type: 'string', required: true },
204
+ existed: { type: 'boolean', required: true },
205
+ },
206
+ },
207
+ render: (_args, value) => [{ type: 'text', text: 'cancelled ' + value.id + ': ' + value.existed }],
208
+ },
209
+ async execute(args) {
210
+ const d = await ensure();
211
+ const e = d.table('events').get(args.id);
212
+ if (e === undefined)
213
+ return { id: args.id, existed: false };
214
+ await d.table('events').put(args.id, { ...e, state: 'cancelled' });
215
+ return { id: args.id, existed: true };
216
+ },
217
+ }));
218
+ }
219
+ //# sourceMappingURL=events-tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events-tools.js","sourceRoot":"","sources":["../src/events-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AACnD,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAA;AAE3E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,MAAM,CAAC,MAAM,IAAI,GAAG,kBAAkB,CAAA;AACtC,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,OAAO,EAAE,eAAe,CAAC,CAAA;AAWhD,MAAM,CAAC,MAAM,YAAY,GAAG,YAAY,CAAC;IACvC,IAAI,EAAE,kBAAkB;IACxB,OAAO,EAAE,CAAC;IACV,MAAM,EAAE;QACN,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC;YAC3B,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE;YACd,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;YACjB,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE;YAClB,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE;YACd,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;YACnD,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;SACtB,CAAC,CAAC;KACJ;CACF,CAAC,CAAA;AAIF,SAAS,KAAK;I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I,EAAE,SAAS,EAAE,QAAQ,EAAE,IAAI,EAAE;iBAC7C;aACF;YACD,MAAM,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,GAAG,KAAK,CAAC,EAAE,GAAG,IAAI,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;SACnG;QACD,KAAK,CAAC,OAAO,CAAC,IAAI;YAChB,MAAM,CAAC,GAAG,MAAM,MAAM,EAAE,CAAA;YACxB,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YACxC,IAAI,CAAC,KAAK,SAAS;gBAAE,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAA;YAC3D,MAAM,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAA;YAClE,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;QACvC,CAAC;KACF,CAAC,CAAC,CAAA;AACL,CAAC"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * files-tools — rh_files_* over Cloudflare R2 (the user's own account).
3
+ * The first family on an actual Cloudflare primitive. S3-compatible API,
4
+ * signed with SigV4 (src/sigv4.ts, pinned to the AWS test vector).
5
+ *
6
+ * Credentials resolve at call time from the credential provider
7
+ * (R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY); accountId and bucket come
8
+ * from the righthand settings namespace. The client is a pure factory so
9
+ * tests drive it with a stubbed fetch.
10
+ * @module dsh-righthand/files-tools
11
+ */
12
+ import type { Context } from '@deepseek-ai/cordis';
13
+ export declare const name = "righthand-files";
14
+ export declare const inject: string[];
15
+ export declare const R2_ACCESS_KEY_REF = "R2_ACCESS_KEY_ID";
16
+ export declare const R2_SECRET_KEY_REF = "R2_SECRET_ACCESS_KEY";
17
+ export interface FilesConfig {
18
+ /** Bucket name; defaults to the righthand settings defaultR2Bucket. */
19
+ bucket?: string;
20
+ }
21
+ export interface R2Options {
22
+ accountId: string;
23
+ accessKeyId: string;
24
+ secretAccessKey: string;
25
+ bucket: string;
26
+ fetchImpl?: typeof fetch;
27
+ now?: () => Date;
28
+ }
29
+ export interface ListEntry {
30
+ key: string;
31
+ size: number;
32
+ lastModified: string;
33
+ }
34
+ /**
35
+ * The R2 client factory. Pure over its options; every call signs fresh.
36
+ */
37
+ export declare function createR2Client(opts: R2Options): {
38
+ put(key: string, content: string, contentType?: string): Promise<{
39
+ key: string;
40
+ size: number;
41
+ }>;
42
+ get(key: string): Promise<{
43
+ found: boolean;
44
+ content: string;
45
+ contentType: string;
46
+ }>;
47
+ list(prefix?: string, maxKeys?: number): Promise<ListEntry[]>;
48
+ share(key: string, expiresSeconds: number): string;
49
+ delete(key: string): Promise<{
50
+ key: string;
51
+ existed: boolean;
52
+ }>;
53
+ };
54
+ export declare function apply(ctx: Context, config?: FilesConfig): void;
55
+ //# sourceMappingURL=files-tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files-tools.d.ts","sourceRoot":"","sources":["../src/files-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAMlD,eAAO,MAAM,IAAI,oBAAoB,CAAA;AACrC,eAAO,MAAM,MAAM,UAAuC,CAAA;AAE1D,eAAO,MAAM,iBAAiB,qBAAqB,CAAA;AACnD,eAAO,MAAM,iBAAiB,yBAAyB,CAAA;AAEvD,MAAM,WAAW,WAAW;IAC1B,uEAAuE;IACvE,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,SAAS;IACxB,SAAS,EAAE,MAAM,CAAA;IACjB,WAAW,EAAE,MAAM,CAAA;IACnB,eAAe,EAAE,MAAM,CAAA;IACvB,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,CAAC,EAAE,OAAO,KAAK,CAAA;IACxB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAA;CACjB;AAMD,MAAM,WAAW,SAAS;IACxB,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,MAAM,CAAA;IACZ,YAAY,EAAE,MAAM,CAAA;CACrB;AAmBD;;GAEG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,SAAS;aAsB3B,MAAM,WAAW,MAAM,gBAAgB,MAAM,GAAG,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;aAMtF,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;kBAOrE,MAAM,YAAY,MAAM,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;eAmBxD,MAAM,kBAAkB,MAAM,GAAG,MAAM;gBAWhC,MAAM,GAAG,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC;EAOxE;AAGD,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,WAAgB,GAAG,IAAI,CAkJlE"}
@@ -0,0 +1,259 @@
1
+ /**
2
+ * files-tools — rh_files_* over Cloudflare R2 (the user's own account).
3
+ * The first family on an actual Cloudflare primitive. S3-compatible API,
4
+ * signed with SigV4 (src/sigv4.ts, pinned to the AWS test vector).
5
+ *
6
+ * Credentials resolve at call time from the credential provider
7
+ * (R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY); accountId and bucket come
8
+ * from the righthand settings namespace. The client is a pure factory so
9
+ * tests drive it with a stubbed fetch.
10
+ * @module dsh-righthand/files-tools
11
+ */
12
+ import { defineTool } from '@deepseek-ai/dsh-tools';
13
+ import { credentialRef } from '@deepseek-ai/dsh-credentials';
14
+ import { settingsNamespace } from '@deepseek-ai/dsh-settings';
15
+ import { signRequest, presignGet } from "./sigv4.js";
16
+ export const name = 'righthand-files';
17
+ export const inject = ['tools', 'credentials', 'settings'];
18
+ export const R2_ACCESS_KEY_REF = 'R2_ACCESS_KEY_ID';
19
+ export const R2_SECRET_KEY_REF = 'R2_SECRET_ACCESS_KEY';
20
+ function amzDate(d) {
21
+ return d.toISOString().replace(/[:-]|\.\d{3}/g, '');
22
+ }
23
+ /** Minimal ListObjectsV2 XML parse: Key / Size / LastModified triples. */
24
+ function parseListXml(xml) {
25
+ const out = [];
26
+ const contents = xml.split('<Contents>').slice(1);
27
+ for (const block of contents) {
28
+ const grab = (tag) => {
29
+ const a = block.indexOf('<' + tag + '>');
30
+ const b = block.indexOf('</' + tag + '>');
31
+ return a < 0 || b < 0 ? '' : block.slice(a + tag.length + 2, b);
32
+ };
33
+ const key = grab('Key');
34
+ if (key === '')
35
+ continue;
36
+ out.push({ key, size: Number(grab('Size') ?? 0), lastModified: grab('LastModified') });
37
+ }
38
+ return out;
39
+ }
40
+ /**
41
+ * The R2 client factory. Pure over its options; every call signs fresh.
42
+ */
43
+ export function createR2Client(opts) {
44
+ const fetchImpl = opts.fetchImpl ?? fetch;
45
+ const now = opts.now ?? (() => new Date());
46
+ const base = 'https://' + opts.accountId + '.r2.cloudflarestorage.com/' + opts.bucket;
47
+ async function request(method, key, payload, extraHeaders = {}) {
48
+ const url = base + '/' + key;
49
+ const parsed = new URL(url);
50
+ const signed = signRequest({
51
+ method,
52
+ url,
53
+ headers: { host: parsed.host, ...extraHeaders },
54
+ payload,
55
+ accessKeyId: opts.accessKeyId,
56
+ secretAccessKey: opts.secretAccessKey,
57
+ region: 'auto',
58
+ amzDate: amzDate(now()),
59
+ });
60
+ return fetchImpl(url, { method, headers: signed.headers, body: payload === '' ? undefined : payload });
61
+ }
62
+ return {
63
+ async put(key, content, contentType) {
64
+ const res = await request('PUT', key, content, contentType ? { 'content-type': contentType } : {});
65
+ if (!res.ok)
66
+ throw new Error('R2 PUT failed: HTTP ' + res.status);
67
+ return { key, size: Buffer.byteLength(content) };
68
+ },
69
+ async get(key) {
70
+ const res = await request('GET', key, '');
71
+ if (res.status === 404)
72
+ return { found: false, content: '', contentType: '' };
73
+ if (!res.ok)
74
+ throw new Error('R2 GET failed: HTTP ' + res.status);
75
+ return { found: true, content: await res.text(), contentType: res.headers.get('content-type') ?? '' };
76
+ },
77
+ async list(prefix, maxKeys) {
78
+ const q = '?list-type=2' + (prefix ? '&prefix=' + encodeURIComponent(prefix) : '') + (maxKeys ? '&max-keys=' + maxKeys : '');
79
+ const url = base + '/' + q;
80
+ const parsed = new URL(url);
81
+ const signed = signRequest({
82
+ method: 'GET',
83
+ url,
84
+ headers: { host: parsed.host },
85
+ payload: '',
86
+ accessKeyId: opts.accessKeyId,
87
+ secretAccessKey: opts.secretAccessKey,
88
+ region: 'auto',
89
+ amzDate: amzDate(now()),
90
+ });
91
+ const res = await fetchImpl(url, { method: 'GET', headers: signed.headers });
92
+ if (!res.ok)
93
+ throw new Error('R2 list failed: HTTP ' + res.status);
94
+ return parseListXml(await res.text());
95
+ },
96
+ share(key, expiresSeconds) {
97
+ return presignGet({
98
+ url: base + '/' + key,
99
+ accessKeyId: opts.accessKeyId,
100
+ secretAccessKey: opts.secretAccessKey,
101
+ region: 'auto',
102
+ amzDate: amzDate(now()),
103
+ expiresSeconds,
104
+ });
105
+ },
106
+ async delete(key) {
107
+ const res = await request('DELETE', key, '');
108
+ if (res.status === 404)
109
+ return { key, existed: false };
110
+ if (!res.ok)
111
+ throw new Error('R2 DELETE failed: HTTP ' + res.status);
112
+ return { key, existed: true };
113
+ },
114
+ };
115
+ }
116
+ export function apply(ctx, config = {}) {
117
+ const ns = settingsNamespace('righthand');
118
+ /** Resolve accountId + credentials + bucket at call time. */
119
+ async function client() {
120
+ const settings = ctx.settings.get(ns);
121
+ const accountId = settings?.accountId ?? '';
122
+ if (accountId === '')
123
+ throw new Error('righthand accountId is not set (rh_settings_set { accountId })');
124
+ const bucket = config.bucket ?? settings?.defaultR2Bucket ?? '';
125
+ if (bucket === '')
126
+ throw new Error('R2 bucket is not set (plugin config bucket or settings defaultR2Bucket)');
127
+ const access = await ctx.credentials.resolve(credentialRef(R2_ACCESS_KEY_REF));
128
+ const secret = await ctx.credentials.resolve(credentialRef(R2_SECRET_KEY_REF));
129
+ if (access === undefined || secret === undefined) {
130
+ throw new Error('R2 credentials are not set (rh_credential_set R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY)');
131
+ }
132
+ return createR2Client({ accountId, accessKeyId: access.value, secretAccessKey: secret.value, bucket });
133
+ }
134
+ ctx.tools.register(defineTool({
135
+ name: 'rh_files_put',
136
+ description: 'Store a file in the R2 bucket and return its key. Content is text (reports, CSV, transcripts, code); content type defaults to text/plain.',
137
+ parameters: {
138
+ key: { type: 'string', required: true, description: 'Object key, e.g. reports/2026-08-30.csv.' },
139
+ content: { type: 'string', required: true, description: 'The full text content to store.' },
140
+ contentType: { type: 'string', description: 'Content type, e.g. text/csv. Defaults to text/plain.' },
141
+ },
142
+ output: {
143
+ schema: {
144
+ type: 'object',
145
+ additionalProperties: false,
146
+ properties: {
147
+ key: { type: 'string', required: true },
148
+ size: { type: 'integer', required: true },
149
+ },
150
+ },
151
+ render: (_args, value) => [{ type: 'text', text: 'stored ' + value.key + ' (' + value.size + ' bytes)' }],
152
+ },
153
+ async execute(args) {
154
+ const c = await client();
155
+ return c.put(args.key, args.content, args.contentType);
156
+ },
157
+ }));
158
+ ctx.tools.register(defineTool({
159
+ name: 'rh_files_get',
160
+ description: 'Read a stored file back by its key. found: false means the key is absent, not an error.',
161
+ parameters: {
162
+ key: { type: 'string', required: true, description: 'The object key to read.' },
163
+ },
164
+ output: {
165
+ schema: {
166
+ type: 'object',
167
+ additionalProperties: false,
168
+ properties: {
169
+ found: { type: 'boolean', required: true },
170
+ key: { type: 'string', required: true },
171
+ content: { type: 'string' },
172
+ contentType: { type: 'string' },
173
+ },
174
+ },
175
+ render: (_args, value) => [{ type: 'text', text: value.found && typeof value.content === 'string' ? value.content : '(absent)' }],
176
+ },
177
+ async execute(args) {
178
+ const c = await client();
179
+ const out = await c.get(args.key);
180
+ return {
181
+ key: args.key,
182
+ found: out.found,
183
+ ...out.found ? { content: out.content, contentType: out.contentType } : {},
184
+ };
185
+ },
186
+ }));
187
+ ctx.tools.register(defineTool({
188
+ name: 'rh_files_list',
189
+ description: 'List objects in the bucket, optionally by key prefix. Newest first is not guaranteed by S3; entries carry lastModified.',
190
+ parameters: {
191
+ prefix: { type: 'string', description: 'Only keys starting with this, e.g. reports/.' },
192
+ maxKeys: { type: 'integer', description: 'Max entries (default 100).' },
193
+ },
194
+ output: {
195
+ schema: {
196
+ type: 'object',
197
+ additionalProperties: false,
198
+ properties: {
199
+ entries: { type: 'array', required: true, items: { type: 'json' } },
200
+ },
201
+ },
202
+ render: (_args, value) => [{ type: 'text', text: value.entries.length + ' objects' }],
203
+ },
204
+ async execute(args) {
205
+ const c = await client();
206
+ const entries = await c.list(args.prefix, args.maxKeys);
207
+ return { entries: entries };
208
+ },
209
+ }));
210
+ ctx.tools.register(defineTool({
211
+ name: 'rh_files_share',
212
+ description: 'Get a presigned download URL for a key, valid for the given minutes (default 60, max 10080). Anyone with the URL can read the object for that window.',
213
+ parameters: {
214
+ key: { type: 'string', required: true, description: 'The object key to share.' },
215
+ minutes: { type: 'integer', description: 'Validity in minutes (default 60, max 10080 = 7 days).' },
216
+ },
217
+ output: {
218
+ schema: {
219
+ type: 'object',
220
+ additionalProperties: false,
221
+ properties: {
222
+ key: { type: 'string', required: true },
223
+ url: { type: 'string', required: true },
224
+ expiresAt: { type: 'string', required: true },
225
+ },
226
+ },
227
+ render: (_args, value) => [{ type: 'text', text: value.url }],
228
+ },
229
+ async execute(args) {
230
+ const minutes = Math.min(Math.max(args.minutes ?? 60, 1), 10080);
231
+ const c = await client();
232
+ const url = c.share(args.key, minutes * 60);
233
+ return { key: args.key, url, expiresAt: new Date(Date.now() + minutes * 60000).toISOString() };
234
+ },
235
+ }));
236
+ ctx.tools.register(defineTool({
237
+ name: 'rh_files_delete',
238
+ description: 'Delete an object by key. Returns whether it existed.',
239
+ parameters: {
240
+ key: { type: 'string', required: true, description: 'The object key to delete.' },
241
+ },
242
+ output: {
243
+ schema: {
244
+ type: 'object',
245
+ additionalProperties: false,
246
+ properties: {
247
+ key: { type: 'string', required: true },
248
+ existed: { type: 'boolean', required: true },
249
+ },
250
+ },
251
+ render: (_args, value) => [{ type: 'text', text: 'deleted ' + value.key + ': ' + value.existed }],
252
+ },
253
+ async execute(args) {
254
+ const c = await client();
255
+ return c.delete(args.key);
256
+ },
257
+ }));
258
+ }
259
+ //# sourceMappingURL=files-tools.js.map