@try-works/dsh-righthand 0.1.5 → 0.1.7

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.
@@ -0,0 +1,294 @@
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
+
13
+ import type { Context } from '@deepseek-ai/cordis'
14
+ import { defineTool } from '@deepseek-ai/dsh-tools'
15
+ import { credentialRef } from '@deepseek-ai/dsh-credentials'
16
+ import { settingsNamespace } from '@deepseek-ai/dsh-settings'
17
+ import { signRequest, presignGet } from './sigv4.ts'
18
+
19
+ export const name = 'righthand-files'
20
+ export const inject = ['tools', 'credentials', 'settings']
21
+
22
+ export const R2_ACCESS_KEY_REF = 'R2_ACCESS_KEY_ID'
23
+ export const R2_SECRET_KEY_REF = 'R2_SECRET_ACCESS_KEY'
24
+
25
+ export interface FilesConfig {
26
+ /** Bucket name; defaults to the righthand settings defaultR2Bucket. */
27
+ bucket?: string
28
+ }
29
+
30
+ export interface R2Options {
31
+ accountId: string
32
+ accessKeyId: string
33
+ secretAccessKey: string
34
+ bucket: string
35
+ fetchImpl?: typeof fetch
36
+ now?: () => Date
37
+ }
38
+
39
+ function amzDate(d: Date): string {
40
+ return d.toISOString().replace(/[:-]|\.\d{3}/g, '')
41
+ }
42
+
43
+ export interface ListEntry {
44
+ key: string
45
+ size: number
46
+ lastModified: string
47
+ }
48
+
49
+ /** Minimal ListObjectsV2 XML parse: Key / Size / LastModified triples. */
50
+ function parseListXml(xml: string): ListEntry[] {
51
+ const out: ListEntry[] = []
52
+ const contents = xml.split('<Contents>').slice(1)
53
+ for (const block of contents) {
54
+ const grab = (tag: string): string => {
55
+ const a = block.indexOf('<' + tag + '>')
56
+ const b = block.indexOf('</' + tag + '>')
57
+ return a < 0 || b < 0 ? '' : block.slice(a + tag.length + 2, b)
58
+ }
59
+ const key = grab('Key')
60
+ if (key === '') continue
61
+ out.push({ key, size: Number(grab('Size') ?? 0), lastModified: grab('LastModified') })
62
+ }
63
+ return out
64
+ }
65
+
66
+ /**
67
+ * The R2 client factory. Pure over its options; every call signs fresh.
68
+ */
69
+ export function createR2Client(opts: R2Options) {
70
+ const fetchImpl = opts.fetchImpl ?? fetch
71
+ const now = opts.now ?? (() => new Date())
72
+ const base = 'https://' + opts.accountId + '.r2.cloudflarestorage.com/' + opts.bucket
73
+
74
+ async function request(method: string, key: string, payload: string, extraHeaders: Record<string, string> = {}): Promise<Response> {
75
+ const url = base + '/' + key
76
+ const parsed = new URL(url)
77
+ const signed = signRequest({
78
+ method,
79
+ url,
80
+ headers: { host: parsed.host, ...extraHeaders },
81
+ payload,
82
+ accessKeyId: opts.accessKeyId,
83
+ secretAccessKey: opts.secretAccessKey,
84
+ region: 'auto',
85
+ amzDate: amzDate(now()),
86
+ })
87
+ return fetchImpl(url, { method, headers: signed.headers, body: payload === '' ? undefined : payload })
88
+ }
89
+
90
+ return {
91
+ async put(key: string, content: string, contentType?: string): Promise<{ key: string; size: number }> {
92
+ const res = await request('PUT', key, content, contentType ? { 'content-type': contentType } : {})
93
+ if (!res.ok) throw new Error('R2 PUT failed: HTTP ' + res.status)
94
+ return { key, size: Buffer.byteLength(content) }
95
+ },
96
+
97
+ async get(key: string): Promise<{ found: boolean; content: string; contentType: string }> {
98
+ const res = await request('GET', key, '')
99
+ if (res.status === 404) return { found: false, content: '', contentType: '' }
100
+ if (!res.ok) throw new Error('R2 GET failed: HTTP ' + res.status)
101
+ return { found: true, content: await res.text(), contentType: res.headers.get('content-type') ?? '' }
102
+ },
103
+
104
+ async list(prefix?: string, maxKeys?: number): Promise<ListEntry[]> {
105
+ const q = '?list-type=2' + (prefix ? '&prefix=' + encodeURIComponent(prefix) : '') + (maxKeys ? '&max-keys=' + maxKeys : '')
106
+ const url = base + '/' + q
107
+ const parsed = new URL(url)
108
+ const signed = signRequest({
109
+ method: 'GET',
110
+ url,
111
+ headers: { host: parsed.host },
112
+ payload: '',
113
+ accessKeyId: opts.accessKeyId,
114
+ secretAccessKey: opts.secretAccessKey,
115
+ region: 'auto',
116
+ amzDate: amzDate(now()),
117
+ })
118
+ const res = await fetchImpl(url, { method: 'GET', headers: signed.headers })
119
+ if (!res.ok) throw new Error('R2 list failed: HTTP ' + res.status)
120
+ return parseListXml(await res.text())
121
+ },
122
+
123
+ share(key: string, expiresSeconds: number): string {
124
+ return presignGet({
125
+ url: base + '/' + key,
126
+ accessKeyId: opts.accessKeyId,
127
+ secretAccessKey: opts.secretAccessKey,
128
+ region: 'auto',
129
+ amzDate: amzDate(now()),
130
+ expiresSeconds,
131
+ })
132
+ },
133
+
134
+ async delete(key: string): Promise<{ key: string; existed: boolean }> {
135
+ const res = await request('DELETE', key, '')
136
+ if (res.status === 404) return { key, existed: false }
137
+ if (!res.ok) throw new Error('R2 DELETE failed: HTTP ' + res.status)
138
+ return { key, existed: true }
139
+ },
140
+ }
141
+ }
142
+
143
+
144
+ export function apply(ctx: Context, config: FilesConfig = {}): void {
145
+ const ns = settingsNamespace('righthand')
146
+
147
+ /** Resolve accountId + credentials + bucket at call time. */
148
+ async function client(): Promise<ReturnType<typeof createR2Client>> {
149
+ const settings = ctx.settings.get(ns) as { accountId?: string; defaultR2Bucket?: string } | undefined
150
+ const accountId = settings?.accountId ?? ''
151
+ if (accountId === '') throw new Error('righthand accountId is not set (rh_settings_set { accountId })')
152
+ const bucket = config.bucket ?? settings?.defaultR2Bucket ?? ''
153
+ if (bucket === '') throw new Error('R2 bucket is not set (plugin config bucket or settings defaultR2Bucket)')
154
+ const access = await ctx.credentials.resolve(credentialRef(R2_ACCESS_KEY_REF))
155
+ const secret = await ctx.credentials.resolve(credentialRef(R2_SECRET_KEY_REF))
156
+ if (access === undefined || secret === undefined) {
157
+ throw new Error('R2 credentials are not set (rh_credential_set R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY)')
158
+ }
159
+ return createR2Client({ accountId, accessKeyId: access.value, secretAccessKey: secret.value, bucket })
160
+ }
161
+
162
+ ctx.tools.register(defineTool({
163
+ name: 'rh_files_put',
164
+ 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.',
165
+ parameters: {
166
+ key: { type: 'string', required: true, description: 'Object key, e.g. reports/2026-08-30.csv.' },
167
+ content: { type: 'string', required: true, description: 'The full text content to store.' },
168
+ contentType: { type: 'string', description: 'Content type, e.g. text/csv. Defaults to text/plain.' },
169
+ },
170
+ output: {
171
+ schema: {
172
+ type: 'object',
173
+ additionalProperties: false,
174
+ properties: {
175
+ key: { type: 'string', required: true },
176
+ size: { type: 'integer', required: true },
177
+ },
178
+ },
179
+ render: (_args, value) => [{ type: 'text', text: 'stored ' + value.key + ' (' + value.size + ' bytes)' }],
180
+ },
181
+ async execute(args) {
182
+ const c = await client()
183
+ return c.put(args.key, args.content, args.contentType)
184
+ },
185
+ }))
186
+
187
+ ctx.tools.register(defineTool({
188
+ name: 'rh_files_get',
189
+ description: 'Read a stored file back by its key. found: false means the key is absent, not an error.',
190
+ parameters: {
191
+ key: { type: 'string', required: true, description: 'The object key to read.' },
192
+ },
193
+ output: {
194
+ schema: {
195
+ type: 'object',
196
+ additionalProperties: false,
197
+ properties: {
198
+ found: { type: 'boolean', required: true },
199
+ key: { type: 'string', required: true },
200
+ content: { type: 'string' },
201
+ contentType: { type: 'string' },
202
+ },
203
+ },
204
+ render: (_args, value) => [{ type: 'text', text: value.found && typeof value.content === 'string' ? value.content : '(absent)' }],
205
+ },
206
+ async execute(args) {
207
+ const c = await client()
208
+ const out = await c.get(args.key)
209
+ return {
210
+ key: args.key,
211
+ found: out.found,
212
+ ...out.found ? { content: out.content, contentType: out.contentType } : {},
213
+ }
214
+ },
215
+ }))
216
+
217
+ ctx.tools.register(defineTool({
218
+ name: 'rh_files_list',
219
+ description: 'List objects in the bucket, optionally by key prefix. Newest first is not guaranteed by S3; entries carry lastModified.',
220
+ parameters: {
221
+ prefix: { type: 'string', description: 'Only keys starting with this, e.g. reports/.' },
222
+ maxKeys: { type: 'integer', description: 'Max entries (default 100).' },
223
+ },
224
+ output: {
225
+ schema: {
226
+ type: 'object',
227
+ additionalProperties: false,
228
+ properties: {
229
+ entries: { type: 'array', required: true, items: { type: 'json' } },
230
+ },
231
+ },
232
+ render: (_args, value) => [{ type: 'text', text: value.entries.length + ' objects' }],
233
+ },
234
+ async execute(args) {
235
+ const c = await client()
236
+ const entries = await c.list(args.prefix, args.maxKeys)
237
+ return { entries: entries as any[] }
238
+ },
239
+ }))
240
+
241
+ ctx.tools.register(defineTool({
242
+ name: 'rh_files_share',
243
+ 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.',
244
+ parameters: {
245
+ key: { type: 'string', required: true, description: 'The object key to share.' },
246
+ minutes: { type: 'integer', description: 'Validity in minutes (default 60, max 10080 = 7 days).' },
247
+ },
248
+ output: {
249
+ schema: {
250
+ type: 'object',
251
+ additionalProperties: false,
252
+ properties: {
253
+ key: { type: 'string', required: true },
254
+ url: { type: 'string', required: true },
255
+ expiresAt: { type: 'string', required: true },
256
+ },
257
+ },
258
+ render: (_args, value) => [{ type: 'text', text: value.url }],
259
+ },
260
+ async execute(args) {
261
+ const minutes = Math.min(Math.max(args.minutes ?? 60, 1), 10080)
262
+ const c = await client()
263
+ const url = c.share(args.key, minutes * 60)
264
+ return { key: args.key, url, expiresAt: new Date(Date.now() + minutes * 60000).toISOString() }
265
+ },
266
+ }))
267
+
268
+ ctx.tools.register(defineTool({
269
+ name: 'rh_files_delete',
270
+ description: 'Delete an object by key. Returns whether it existed.',
271
+ parameters: {
272
+ key: { type: 'string', required: true, description: 'The object key to delete.' },
273
+ },
274
+ output: {
275
+ schema: {
276
+ type: 'object',
277
+ additionalProperties: false,
278
+ properties: {
279
+ key: { type: 'string', required: true },
280
+ existed: { type: 'boolean', required: true },
281
+ },
282
+ },
283
+ render: (_args, value) => [{ type: 'text', text: 'deleted ' + value.key + ': ' + value.existed }],
284
+ },
285
+ async execute(args) {
286
+ const c = await client()
287
+ return c.delete(args.key)
288
+ },
289
+ }))
290
+ }
291
+
292
+
293
+
294
+
package/src/index.ts CHANGED
@@ -16,6 +16,8 @@
16
16
  * - secrets-tools: rh_credential_describe/set/unset + rh_settings_get/set
17
17
  * - task-tools: rh_task_create/list/next/update/delete over ctx.storageDomain
18
18
  * - text-tools: rh_text_summarise/extract/classify/translate over ctx.llm
19
+ * - weather-tools: rh_weather_forecast/air over Open-Meteo (keyless, SSRF-guarded)
20
+ * - files-tools: rh_files_put/get/list/share/delete over Cloudflare R2
19
21
  * - exec-tools: rh_run / rh_run_bg over ctx.subprocess + ctx.jobs
20
22
  * - guard-tools: tools/pre-execute policy (config.rules)
21
23
  * - skills: the packaged dsh-righthand skill (ctx.skills)
@@ -30,6 +32,8 @@ import * as execTools from './exec-tools.ts'
30
32
  import * as guardTools from './guard-tools.ts'
31
33
  import * as taskTools from './task-tools.ts'
32
34
  import * as textTools from './text-tools.ts'
35
+ import * as weatherTools from './weather-tools.ts'
36
+ import * as filesTools from './files-tools.ts'
33
37
  import * as righthandSkills from './skills.ts'
34
38
  import type { GuardRule } from './guard-tools.ts'
35
39
 
@@ -56,14 +60,21 @@ export function apply(ctx: Context, config: RighthandConfig = {}): void {
56
60
  ctx.plugin(execTools)
57
61
  ctx.plugin(taskTools)
58
62
  ctx.plugin(textTools)
63
+ ctx.plugin(weatherTools)
64
+ ctx.plugin(filesTools)
59
65
  ctx.plugin(guardTools, { rules: config.rules ?? [] })
60
66
  ctx.plugin(righthandSkills)
61
67
  }
62
68
 
63
69
  // Individual modules stay importable for selective mounting.
64
- export { storeTools, secretsTools, execTools, taskTools, textTools, guardTools, righthandSkills }
70
+ export { storeTools, secretsTools, execTools, taskTools, textTools, weatherTools, filesTools, guardTools, righthandSkills }
65
71
  export { SKILL_NAME, SKILL_DESCRIPTION, skillDirectory, skillBody } from './skills.ts'
66
72
  export type { GuardRule } from './guard-tools.ts'
67
73
  export { guardFactsFor } from './guard-tools.ts'
68
74
  export type { GuardFacts } from './guard-tools.ts'
75
+ export { isBlockedIP, guardedFetch, normalizeForecast, normalizeAir } from './weather-tools.ts'
76
+ export { createR2Client, R2_ACCESS_KEY_REF, R2_SECRET_KEY_REF } from './files-tools.ts'
77
+ export { signRequest, presignGet } from './sigv4.ts'
78
+ export type { R2Options, ListEntry } from './files-tools.ts'
79
+ export type { WeatherConfig, ForecastOut, AirOut } from './weather-tools.ts'
69
80
 
@@ -27,6 +27,7 @@ export const righthandSettingsSchema = z.object({
27
27
  accountId: z.string().default(''),
28
28
  defaultScriptPrefix: z.string().default('rh-'),
29
29
  defaultZone: z.string().default(''),
30
+ defaultR2Bucket: z.string().default(''),
30
31
  })
31
32
 
32
33
  /** Register the settings namespace + the secret/credential tools. */
@@ -119,7 +120,7 @@ export function apply(ctx: Context): void {
119
120
  },
120
121
  async execute() {
121
122
  const v = scope.get()
122
- return { accountId: v.accountId, defaultScriptPrefix: v.defaultScriptPrefix, defaultZone: v.defaultZone }
123
+ return { accountId: v.accountId, defaultScriptPrefix: v.defaultScriptPrefix, defaultZone: v.defaultZone, defaultR2Bucket: v.defaultR2Bucket }
123
124
  },
124
125
  }))
125
126
 
package/src/sigv4.ts ADDED
@@ -0,0 +1,122 @@
1
+ /**
2
+ * sigv4 — AWS Signature Version 4 for Cloudflare R2 (S3-compatible API).
3
+ * Dependency-free: node:crypto only. Exported pure so tests pin it against
4
+ * the AWS published test vector.
5
+ * @module dsh-righthand/sigv4
6
+ */
7
+
8
+ import { createHmac, createHash } from 'node:crypto'
9
+
10
+ function hmac(key: Buffer | string, data: string): Buffer {
11
+ return createHmac('sha256', key).update(data).digest()
12
+ }
13
+
14
+ function sha256Hex(data: string): string {
15
+ return createHash('sha256').update(data).digest('hex')
16
+ }
17
+
18
+ /** URI-encode one path segment the S3 way. */
19
+ function uriEncode(segment: string): string {
20
+ return encodeURIComponent(segment).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())
21
+ }
22
+
23
+ /** Canonical URI: slashes preserved, each segment encoded. */
24
+ function canonicalPath(pathname: string): string {
25
+ if (pathname === '' || pathname === '/') return '/'
26
+ return pathname.split('/').map(uriEncode).join('/')
27
+ }
28
+
29
+ export interface SignRequestInput {
30
+ method: string
31
+ /** Full URL, e.g. https://<account>.r2.cloudflarestorage.com/<bucket>/<key> */
32
+ url: string
33
+ /** Headers to sign (lowercase names), e.g. host, content-type. */
34
+ headers: Record<string, string>
35
+ /** Exact payload bytes; '' for GET/DELETE without a body. */
36
+ payload: string
37
+ accessKeyId: string
38
+ secretAccessKey: string
39
+ /** R2 uses region 'auto'. */
40
+ region: string
41
+ /** yyyyMMdd'T'HHmmss'Z' — injectable for tests. */
42
+ amzDate: string
43
+ }
44
+
45
+ export interface SignedRequest {
46
+ headers: Record<string, string>
47
+ }
48
+
49
+ /**
50
+ * Sign one S3 request. Returns the headers to send, including host,
51
+ * x-amz-content-sha256, x-amz-date and Authorization.
52
+ */
53
+ export function signRequest(input: SignRequestInput): SignedRequest {
54
+ const parsed = new URL(input.url)
55
+ const date = input.amzDate.slice(0, 8)
56
+ const scope = date + '/' + input.region + '/s3/aws4_request'
57
+ const payloadHash = sha256Hex(input.payload)
58
+
59
+ const headers: Record<string, string> = {
60
+ ...input.headers,
61
+ 'x-amz-content-sha256': payloadHash,
62
+ 'x-amz-date': input.amzDate,
63
+ }
64
+ const names = Object.keys(headers).sort()
65
+ const canonicalHeaders = names.map(n => n + ':' + headers[n].trim() + String.fromCharCode(10)).join('')
66
+ const signedHeaders = names.join(';')
67
+ const canonicalRequest = [
68
+ input.method,
69
+ canonicalPath(parsed.pathname),
70
+ parsed.searchParams.toString(),
71
+ canonicalHeaders,
72
+ signedHeaders,
73
+ payloadHash,
74
+ ].join(String.fromCharCode(10))
75
+ const stringToSign = ['AWS4-HMAC-SHA256', input.amzDate, scope, sha256Hex(canonicalRequest)].join(String.fromCharCode(10))
76
+ const kDate = hmac('AWS4' + input.secretAccessKey, date)
77
+ const kRegion = hmac(kDate, input.region)
78
+ const kService = hmac(kRegion, 's3')
79
+ const kSigning = hmac(kService, 'aws4_request')
80
+ const signature = hmac(kSigning, stringToSign).toString('hex')
81
+ const authorization = 'AWS4-HMAC-SHA256 Credential=' + input.accessKeyId + '/' + scope
82
+ + ', SignedHeaders=' + signedHeaders
83
+ + ', Signature=' + signature
84
+ return { headers: { ...headers, authorization } }
85
+ }
86
+
87
+ /**
88
+ * Presign a GET for query-string auth: a shareable URL valid for
89
+ * expiresSeconds (S3 max 7 days).
90
+ */
91
+ export function presignGet(input: Omit<SignRequestInput, 'method' | 'headers' | 'payload'> & { expiresSeconds: number }): string {
92
+ const parsed = new URL(input.url)
93
+ const date = input.amzDate.slice(0, 8)
94
+ const scope = date + '/' + input.region + '/s3/aws4_request'
95
+ const credential = input.accessKeyId + '/' + scope
96
+ const query: Record<string, string> = {
97
+ 'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',
98
+ 'X-Amz-Credential': credential,
99
+ 'X-Amz-Date': input.amzDate,
100
+ 'X-Amz-Expires': String(input.expiresSeconds),
101
+ 'X-Amz-SignedHeaders': 'host',
102
+ }
103
+ const canonicalQuery = Object.keys(query).sort().map(k => uriEncode(k) + '=' + uriEncode(query[k])).join('&')
104
+ const canonicalRequest = [
105
+ 'GET',
106
+ canonicalPath(parsed.pathname),
107
+ canonicalQuery,
108
+ 'host:' + parsed.host + String.fromCharCode(10),
109
+ 'host',
110
+ 'UNSIGNED-PAYLOAD',
111
+ ].join(String.fromCharCode(10))
112
+ const stringToSign = ['AWS4-HMAC-SHA256', input.amzDate, scope, sha256Hex(canonicalRequest)].join(String.fromCharCode(10))
113
+ const kDate = hmac('AWS4' + input.secretAccessKey, date)
114
+ const kRegion = hmac(kDate, input.region)
115
+ const kService = hmac(kRegion, 's3')
116
+ const kSigning = hmac(kService, 'aws4_request')
117
+ const signature = hmac(kSigning, stringToSign).toString('hex')
118
+ parsed.search = canonicalQuery + '&X-Amz-Signature=' + signature
119
+ return parsed.toString()
120
+ }
121
+
122
+