@whiteplusms/dsh-redis 0.0.0-stage → 0.1.3

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 (146) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +184 -2
  3. package/README.zh.md +185 -0
  4. package/cordis.patch.yml +4 -0
  5. package/icon.svg +1 -0
  6. package/lib/client/index.d.ts +4 -0
  7. package/lib/client.js +7684 -0
  8. package/lib/connection-errors.d.ts +66 -0
  9. package/lib/connection-errors.js +21 -0
  10. package/lib/domain.d.ts +451 -0
  11. package/lib/domain.js +20 -0
  12. package/lib/host/ai-answer.d.ts +7 -0
  13. package/lib/host/ai-answer.js +132 -0
  14. package/lib/host/ai-budget.d.ts +43 -0
  15. package/lib/host/ai-budget.js +78 -0
  16. package/lib/host/ai-connection-tools.d.ts +8 -0
  17. package/lib/host/ai-connection-tools.js +49 -0
  18. package/lib/host/ai-hash-filter.d.ts +13 -0
  19. package/lib/host/ai-hash-filter.js +97 -0
  20. package/lib/host/ai-hash-pages.d.ts +15 -0
  21. package/lib/host/ai-hash-pages.js +42 -0
  22. package/lib/host/ai-key-pages.d.ts +14 -0
  23. package/lib/host/ai-key-pages.js +27 -0
  24. package/lib/host/ai-locate-tool.d.ts +6 -0
  25. package/lib/host/ai-locate-tool.js +234 -0
  26. package/lib/host/ai-match-tools.d.ts +7 -0
  27. package/lib/host/ai-match-tools.js +112 -0
  28. package/lib/host/ai-page-coordinator.d.ts +21 -0
  29. package/lib/host/ai-page-coordinator.js +81 -0
  30. package/lib/host/ai-page-store.d.ts +40 -0
  31. package/lib/host/ai-page-store.js +104 -0
  32. package/lib/host/ai-profile-tools.d.ts +7 -0
  33. package/lib/host/ai-profile-tools.js +44 -0
  34. package/lib/host/ai-query-scope.d.ts +42 -0
  35. package/lib/host/ai-query-scope.js +104 -0
  36. package/lib/host/ai-reader.d.ts +219 -0
  37. package/lib/host/ai-reader.js +1221 -0
  38. package/lib/host/ai-report-samples.d.ts +26 -0
  39. package/lib/host/ai-report-samples.js +77 -0
  40. package/lib/host/ai-report-tools.d.ts +11 -0
  41. package/lib/host/ai-report-tools.js +70 -0
  42. package/lib/host/ai-set-pages.d.ts +15 -0
  43. package/lib/host/ai-set-pages.js +40 -0
  44. package/lib/host/ai-stream-pages.d.ts +15 -0
  45. package/lib/host/ai-stream-pages.js +42 -0
  46. package/lib/host/ai-tools.d.ts +4 -0
  47. package/lib/host/ai-tools.js +106 -0
  48. package/lib/host/ai-ui-tools.d.ts +10 -0
  49. package/lib/host/ai-ui-tools.js +72 -0
  50. package/lib/host/ai-value.d.ts +12 -0
  51. package/lib/host/ai-value.js +15 -0
  52. package/lib/host/ai-write-tools.d.ts +5 -0
  53. package/lib/host/ai-write-tools.js +101 -0
  54. package/lib/host/ai-writer.d.ts +25 -0
  55. package/lib/host/ai-writer.js +77 -0
  56. package/lib/host/ai-zset-pages.d.ts +15 -0
  57. package/lib/host/ai-zset-pages.js +40 -0
  58. package/lib/host/byte-identity.d.ts +3 -0
  59. package/lib/host/byte-identity.js +12 -0
  60. package/lib/host/client-list.d.ts +13 -0
  61. package/lib/host/client-list.js +35 -0
  62. package/lib/host/connection-service.d.ts +71 -0
  63. package/lib/host/connection-service.js +468 -0
  64. package/lib/host/database-reader.d.ts +10 -0
  65. package/lib/host/database-reader.js +62 -0
  66. package/lib/host/hash-reader.d.ts +12 -0
  67. package/lib/host/hash-reader.js +91 -0
  68. package/lib/host/key-reader.d.ts +20 -0
  69. package/lib/host/key-reader.js +65 -0
  70. package/lib/host/list-reader.d.ts +8 -0
  71. package/lib/host/list-reader.js +61 -0
  72. package/lib/host/match-preset-store.d.ts +36 -0
  73. package/lib/host/match-preset-store.js +201 -0
  74. package/lib/host/profile-snapshots.d.ts +32 -0
  75. package/lib/host/profile-snapshots.js +187 -0
  76. package/lib/host/profile-store.d.ts +15 -0
  77. package/lib/host/profile-store.js +120 -0
  78. package/lib/host/read-context.d.ts +23 -0
  79. package/lib/host/read-context.js +41 -0
  80. package/lib/host/redis-transport.d.ts +34 -0
  81. package/lib/host/redis-transport.js +262 -0
  82. package/lib/host/redis-write-transaction.d.ts +28 -0
  83. package/lib/host/redis-write-transaction.js +180 -0
  84. package/lib/host/resp.d.ts +38 -0
  85. package/lib/host/resp.js +174 -0
  86. package/lib/host/scan-cursors.d.ts +25 -0
  87. package/lib/host/scan-cursors.js +59 -0
  88. package/lib/host/selected-reader.d.ts +22 -0
  89. package/lib/host/selected-reader.js +84 -0
  90. package/lib/host/set-reader.d.ts +12 -0
  91. package/lib/host/set-reader.js +85 -0
  92. package/lib/host/stream-groups.d.ts +17 -0
  93. package/lib/host/stream-groups.js +42 -0
  94. package/lib/host/stream-reader.d.ts +12 -0
  95. package/lib/host/stream-reader.js +105 -0
  96. package/lib/host/string-reader.d.ts +9 -0
  97. package/lib/host/string-reader.js +81 -0
  98. package/lib/host/ui-action-channel.d.ts +4 -0
  99. package/lib/host/ui-action-channel.js +182 -0
  100. package/lib/host/ui-action-coordinator.d.ts +28 -0
  101. package/lib/host/ui-action-coordinator.js +188 -0
  102. package/lib/host/value-prefix.d.ts +5 -0
  103. package/lib/host/value-prefix.js +11 -0
  104. package/lib/host/write-bytes.d.ts +3 -0
  105. package/lib/host/write-bytes.js +9 -0
  106. package/lib/host/write-history.d.ts +18 -0
  107. package/lib/host/write-history.js +79 -0
  108. package/lib/host/write-proposals.d.ts +46 -0
  109. package/lib/host/write-proposals.js +132 -0
  110. package/lib/host/zset-reader.d.ts +12 -0
  111. package/lib/host/zset-reader.js +103 -0
  112. package/lib/host/zset-values.d.ts +6 -0
  113. package/lib/host/zset-values.js +26 -0
  114. package/lib/index.d.ts +6 -0
  115. package/lib/index.js +5 -0
  116. package/lib/redis-answer.d.ts +32 -0
  117. package/lib/redis-answer.js +215 -0
  118. package/lib/redis-databases.d.ts +3 -0
  119. package/lib/redis-databases.js +21 -0
  120. package/lib/redis-read-tools.d.ts +2 -0
  121. package/lib/redis-read-tools.js +7 -0
  122. package/lib/redis-result.d.ts +4 -0
  123. package/lib/redis-result.js +18 -0
  124. package/lib/redis-score.d.ts +2 -0
  125. package/lib/redis-score.js +6 -0
  126. package/lib/remote-service.d.ts +69 -0
  127. package/lib/remote-service.js +187 -0
  128. package/lib/runtime.d.ts +3 -0
  129. package/lib/runtime.js +29 -0
  130. package/lib/stream-id.d.ts +7 -0
  131. package/lib/stream-id.js +19 -0
  132. package/lib/typert.host.d.ts +13 -0
  133. package/lib/typert.host.js +7 -0
  134. package/lib/typert.remote-client.d.ts +98 -0
  135. package/lib/typert.remote-client.js +3 -0
  136. package/lib/typert.shared.d.ts +62 -0
  137. package/lib/typert.shared.js +735 -0
  138. package/lib/ui-action-selection.d.ts +3 -0
  139. package/lib/ui-action-selection.js +12 -0
  140. package/licenses/THIRD_PARTY_NOTICES.txt +9 -0
  141. package/licenses/deepseek-harness-MIT.txt +21 -0
  142. package/licenses/dsh-database-MIT.txt +21 -0
  143. package/licenses/dsh-git-graph-MIT.txt +21 -0
  144. package/licenses/lucide-react-LICENSE.txt +43 -0
  145. package/licenses/phosphor-icons-MIT.txt +21 -0
  146. package/package.json +132 -3
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod';
2
+ import type { PreparedAiResult } from './ai-page-store.js';
3
+ export declare const overviewFields: {
4
+ readonly server: readonly ["redis_version", "uptime_in_seconds"];
5
+ readonly memory: readonly ["used_memory", "used_memory_rss", "maxmemory", "mem_fragmentation_ratio"];
6
+ readonly clients: readonly ["connected_clients", "blocked_clients"];
7
+ readonly stats: readonly ["total_connections_received", "total_commands_processed", "instantaneous_ops_per_sec", "rejected_connections", "evicted_keys", "expired_keys", "keyspace_hits", "keyspace_misses"];
8
+ };
9
+ export declare const memorySamplingNote = "SAMPLES 5 \u662F\u8BF7\u6C42\u53C2\u6570\uFF0C\u7528\u4E8E\u5D4C\u5957\u503C\u4F30\u7B97\uFF1BRedis \u672A\u8FD4\u56DE\u5B9E\u9645\u91C7\u6837\u6570\u91CF\u6216\u8BEF\u5DEE\u3002";
10
+ export declare const memoryScopeNote = "\u547D\u4EE4\u7ED3\u679C\u5305\u542B\u8BE5 Key \u548C\u503C\u7684\u5206\u914D\u53CA\u7BA1\u7406\u5F00\u9500\uFF0C\u53EF\u80FD\u5305\u542B\u5185\u90E8\u788E\u7247\uFF1B\u4E0D\u4EE3\u8868\u6574\u4E2A\u670D\u52A1\u5668\u7684\u5185\u5B58\u3002";
11
+ type AiJson = z.infer<ReturnType<typeof z.json>>;
12
+ export type ReportKind = 'overview' | 'memory' | 'slowlog' | 'clients' | 'stream_groups' | 'compare_strings';
13
+ export type ReportSample = {
14
+ readonly kind: ReportKind;
15
+ readonly sampledAt: string;
16
+ readonly data: AiJson;
17
+ };
18
+ /** Store sanitized metadata only after the corresponding tool result commits. */
19
+ export declare class RedisReportSamples {
20
+ private readonly sessions;
21
+ prepare(session: string, kind: ReportKind, input: AiJson, signal: AbortSignal): PreparedAiResult;
22
+ get(session: string, id: string): ReportSample | null;
23
+ disposeSession(session: string): void;
24
+ dispose(): void;
25
+ }
26
+ export {};
@@ -0,0 +1,77 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { MAX_AI_RESULT_BYTES } from "./ai-budget.js";
4
+ export const overviewFields = {
5
+ server: ['redis_version', 'uptime_in_seconds'],
6
+ memory: ['used_memory', 'used_memory_rss', 'maxmemory', 'mem_fragmentation_ratio'],
7
+ clients: ['connected_clients', 'blocked_clients'],
8
+ stats: ['total_connections_received', 'total_commands_processed', 'instantaneous_ops_per_sec', 'rejected_connections', 'evicted_keys', 'expired_keys', 'keyspace_hits', 'keyspace_misses'],
9
+ };
10
+ const sectionSchema = z.enum(['server', 'memory', 'clients', 'stats']);
11
+ const connectionSchema = z.object({ id: z.string(), generation: z.number().int().nonnegative(), db: z.number().int().nonnegative() });
12
+ const errorSchema = z.enum(['auth', 'network', 'timeout', 'cancelled', 'stale', 'tls-certificate', 'tls-hostname', 'permission', 'oversize', 'protocol', 'busy', 'database', 'type-changed']).nullable();
13
+ const identitySchema = z.object({ base64: z.base64() }).transform(value => 'sha256:' + createHash('sha256').update(Buffer.from(value.base64, 'base64')).digest('hex'));
14
+ const overviewSchema = z.object({ connection: connectionSchema, section: sectionSchema, scope: z.literal('server'), state: z.enum(['value', 'partial', 'failed']), fields: z.record(z.string(), z.string()), missing: z.array(z.string()), sampledAt: z.iso.datetime(), error: errorSchema });
15
+ export const memorySamplingNote = 'SAMPLES 5 是请求参数,用于嵌套值估算;Redis 未返回实际采样数量或误差。';
16
+ export const memoryScopeNote = '命令结果包含该 Key 和值的分配及管理开销,可能包含内部碎片;不代表整个服务器的内存。';
17
+ const memorySchema = z.object({ connection: connectionSchema, key: identitySchema, state: z.enum(['value', 'missing', 'unavailable', 'failed']), bytes: z.string().nullable(), requestedSamples: z.literal(5), actualSamples: z.null(), samplingNote: z.literal(memorySamplingNote), scopeNote: z.literal(memoryScopeNote), sampledAt: z.iso.datetime(), error: errorSchema });
18
+ const slowlogSchema = z.object({ connection: connectionSchema, scope: z.literal('server'), state: z.enum(['value', 'failed']), requestedCount: z.number(), returnedCount: z.number(), entries: z.array(z.object({ id: z.string(), timestampSeconds: z.string(), timestampUtc: z.string().nullable(), durationMicroseconds: z.string() })).max(10), sampledAt: z.iso.datetime(), error: errorSchema });
19
+ const clientsSchema = z.object({ connection: connectionSchema, scope: z.literal('server'), state: z.enum(['value', 'failed']), clients: z.array(z.object({ id: z.string(), ageSeconds: z.string(), idleSeconds: z.string(), db: z.string(), flags: z.string() })).max(20), totalCount: z.number().nullable(), complete: z.boolean(), sampledAt: z.iso.datetime(), error: errorSchema });
20
+ const groupSchema = z.object({ name: identitySchema, consumers: z.string(), pending: z.string(), lastDeliveredId: z.string(), entriesRead: z.string().nullable(), entriesReadReported: z.boolean(), lag: z.string().nullable(), lagStatus: z.enum(['available', 'unknown', 'not-reported']) });
21
+ const groupsSchema = z.object({ connection: connectionSchema, key: identitySchema, state: z.enum(['value', 'missing', 'unsupported', 'changed', 'failed']), type: z.string().nullable().transform(value => value === null || value === 'stream' || value === 'none' ? value : 'other'), groups: z.array(groupSchema).max(20), totalCount: z.number().nullable(), complete: z.boolean(), sampledAt: z.iso.datetime(), error: errorSchema });
22
+ const sideSchema = z.object({ key: identitySchema, state: z.enum(['value', 'missing', 'unsupported', 'changed', 'failed']), length: z.string().nullable(), complete: z.boolean(), sampledAt: z.iso.datetime(), error: errorSchema });
23
+ const compareSchema = z.object({ connection: connectionSchema, comparison: z.enum(['equal', 'different', 'undetermined', 'unavailable']), left: sideSchema, right: sideSchema, bytesComparedPerKey: z.number(), snapshot: z.literal(false) });
24
+ function project(kind, input) {
25
+ if (kind === 'overview') {
26
+ const data = overviewSchema.parse(input), allowed = overviewFields[data.section];
27
+ if (Object.keys(data.fields).some(key => !allowed.includes(key)) || data.missing.some(key => !allowed.includes(key)))
28
+ throw new Error('概况采样包含不支持的字段。');
29
+ return { kind, sampledAt: data.sampledAt, data };
30
+ }
31
+ if (kind === 'memory') {
32
+ const data = memorySchema.parse(input);
33
+ return { kind, sampledAt: data.sampledAt, data };
34
+ }
35
+ if (kind === 'slowlog') {
36
+ const data = slowlogSchema.parse(input);
37
+ return { kind, sampledAt: data.sampledAt, data };
38
+ }
39
+ if (kind === 'clients') {
40
+ const data = clientsSchema.parse(input);
41
+ return { kind, sampledAt: data.sampledAt, data };
42
+ }
43
+ if (kind === 'stream_groups') {
44
+ const data = groupsSchema.parse(input);
45
+ return { kind, sampledAt: data.sampledAt, data };
46
+ }
47
+ const data = compareSchema.parse(input);
48
+ return { kind, sampledAt: data.right.sampledAt, data };
49
+ }
50
+ /** Store sanitized metadata only after the corresponding tool result commits. */
51
+ export class RedisReportSamples {
52
+ sessions = new Map();
53
+ prepare(session, kind, input, signal) {
54
+ const original = z.record(z.string(), z.json()).parse(input), sample = project(kind, input), id = randomUUID();
55
+ const result = { ...original, reportSampleId: id };
56
+ // A nearly full diagnostic result remains readable; it simply cannot be saved as a report.
57
+ if (Buffer.byteLength(JSON.stringify(result)) > MAX_AI_RESULT_BYTES)
58
+ return { result: original, commit: () => undefined, rollback: () => undefined };
59
+ return { result, commit: () => {
60
+ signal.throwIfAborted();
61
+ let entries = this.sessions.get(session);
62
+ if (entries === undefined) {
63
+ entries = new Map();
64
+ this.sessions.set(session, entries);
65
+ }
66
+ entries.set(id, sample);
67
+ if (entries.size > 16) {
68
+ const oldest = entries.keys().next().value;
69
+ if (oldest !== undefined)
70
+ entries.delete(oldest);
71
+ }
72
+ }, rollback: () => undefined };
73
+ }
74
+ get(session, id) { const sample = this.sessions.get(session)?.get(id); return sample === undefined ? null : structuredClone(sample); }
75
+ disposeSession(session) { this.sessions.delete(session); }
76
+ dispose() { this.sessions.clear(); }
77
+ }
@@ -0,0 +1,11 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { RedisAiReader } from './ai-reader.js';
3
+ import type { ReportSample } from './ai-report-samples.js';
4
+ /** Reports have generated names under the trusted profile; no caller-controlled path is accepted. */
5
+ export declare class RedisReports {
6
+ private readonly directory;
7
+ constructor(profileDirectory: string);
8
+ save(sample: ReportSample, signal: AbortSignal): Promise<string>;
9
+ }
10
+ /** Save only a diagnostic result actually delivered in this trusted session. */
11
+ export declare function registerRedisReportTools(ctx: Context, reader: RedisAiReader, reports: RedisReports): void;
@@ -0,0 +1,70 @@
1
+ import { defineTool } from '@deepseek-ai/dsh-tools';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { link, mkdir, open, unlink } from 'node:fs/promises';
4
+ import { resolve } from 'node:path';
5
+ import { z } from 'zod';
6
+ const output = { schema: { type: 'json' }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] };
7
+ /** Reports have generated names under the trusted profile; no caller-controlled path is accepted. */
8
+ export class RedisReports {
9
+ directory;
10
+ constructor(profileDirectory) { this.directory = resolve(profileDirectory, 'data', 'dsh-redis', 'reports'); }
11
+ async save(sample, signal) {
12
+ signal.throwIfAborted();
13
+ const id = randomUUID(), destination = resolve(this.directory, `${id}.json`), temporary = resolve(this.directory, `.staging-${id}.tmp`);
14
+ let created = false;
15
+ try {
16
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
17
+ const file = await open(temporary, 'wx', 0o600);
18
+ created = true;
19
+ try {
20
+ await file.writeFile(JSON.stringify(sample, null, 2) + '\n', 'utf8');
21
+ }
22
+ finally {
23
+ await file.close();
24
+ }
25
+ signal.throwIfAborted();
26
+ await link(temporary, destination);
27
+ return destination;
28
+ }
29
+ finally {
30
+ if (created)
31
+ try {
32
+ await unlink(temporary);
33
+ }
34
+ catch {
35
+ console.warn('[dsh-redis] Report temporary cleanup failed');
36
+ }
37
+ }
38
+ }
39
+ }
40
+ /** Save only a diagnostic result actually delivered in this trusted session. */
41
+ export function registerRedisReportTools(ctx, reader, reports) {
42
+ ctx.tools.register(defineTool({
43
+ name: 'redis_viewer_save_diagnostic_report',
44
+ description: '仅在用户明确要求保存已有诊断结果时调用,sampleId 必须来自本会话诊断结果的 reportSampleId;原采样不重新读取 Redis。只保存近 16 个采样,旧采样或会话结束后不可用。报告将 Key 和消费组名替换为 SHA-256 标识,排除 Redis 值、凭据、慢日志命令名和自由文本。文件写入 DSH profile 的固定目录;不接收路径。中断后保存结果可能未知,应查看目录后再重试。',
45
+ parameters: { sampleId: { type: 'string', required: true } }, output, timeoutMs: 15000,
46
+ async execute(args, exec) {
47
+ exec.signal.throwIfAborted();
48
+ if (exec.agent === undefined)
49
+ throw new Error('Redis 工具调用缺少有效的 DSH 对话身份。');
50
+ if (Object.keys(args).some(key => key !== 'sampleId') || !z.uuid().safeParse(args.sampleId).success)
51
+ throw new Error('报告采样身份无效。');
52
+ const session = exec.agent.session.id, sample = reader.reportSamples.get(session, args.sampleId);
53
+ if (sample === null)
54
+ return { outcome: 'missing', message: '采样不存在、已过期或不属于当前会话,请重新查询。' };
55
+ let started = false;
56
+ try {
57
+ return await reader.withBudget(session, exec.signal, async () => {
58
+ started = true;
59
+ const path = await reports.save(sample, exec.signal);
60
+ return { outcome: 'saved', path, sampledAt: sample.sampledAt, kind: sample.kind };
61
+ });
62
+ }
63
+ catch (error) {
64
+ if (started)
65
+ throw new Error('报告保存结果未知,请检查本地报告目录后再操作。');
66
+ throw error;
67
+ }
68
+ },
69
+ }));
70
+ }
@@ -0,0 +1,15 @@
1
+ import type { DatabaseTarget } from '../domain.js';
2
+ import type { RedisConnections } from './connection-service.js';
3
+ import type { RedisSets } from './set-reader.js';
4
+ import { type PreparedAiPage } from './ai-page-store.js';
5
+ export declare const isAiSetCursor: (cursor: string | null) => boolean;
6
+ /** Set results preserve their own continuation and whole-member identity. */
7
+ export declare class RedisAiSetPages {
8
+ private readonly connections;
9
+ private readonly sets;
10
+ private readonly pages;
11
+ constructor(connections: RedisConnections, sets: RedisSets);
12
+ disposeSession(sessionId: string): void;
13
+ dispose(): void;
14
+ prepare(sessionId: string, target: DatabaseTarget, keyBase64: string, pattern: string, cursor: string | null, selected: object | null, assertSelection: () => void, signal: AbortSignal): Promise<PreparedAiPage>;
15
+ }
@@ -0,0 +1,40 @@
1
+ import { connectionErrorMessages, keyStateMessages } from "../connection-errors.js";
2
+ import { byteIdentity } from "./byte-identity.js";
3
+ import { AiPageStore } from "./ai-page-store.js";
4
+ export const isAiSetCursor = (cursor) => cursor?.startsWith('s:') === true;
5
+ /** Set results preserve their own continuation and whole-member identity. */
6
+ export class RedisAiSetPages {
7
+ connections;
8
+ sets;
9
+ pages = new AiPageStore('s:');
10
+ constructor(connections, sets) {
11
+ this.connections = connections;
12
+ this.sets = sets;
13
+ }
14
+ disposeSession(sessionId) { this.pages.disposeSession(sessionId); this.sets.disposeSession(sessionId); }
15
+ dispose() { this.pages.dispose(); this.sets.dispose(); }
16
+ prepare(sessionId, target, keyBase64, pattern, cursor, selected, assertSelection, signal) {
17
+ signal.throwIfAborted();
18
+ this.connections.assertTarget(sessionId, target);
19
+ assertSelection();
20
+ const identity = byteIdentity(Buffer.from(keyBase64, 'base64'));
21
+ return this.pages.prepare({
22
+ sessionId, binding: JSON.stringify([target.id, target.generation, target.db, keyBase64, pattern, selected !== null]), selection: selected, cursor, signal,
23
+ fetch: async (next) => {
24
+ const read = await this.sets.scan(sessionId, { target, keyBase64, pattern, cursor: next }, signal);
25
+ // Discovery saw Set; a different type in the reader means it changed.
26
+ return read.state === 'unsupported' && read.metadata?.type !== 'set' ? { ...read, state: 'changed', metadata: null } : read;
27
+ },
28
+ rows: page => page.members,
29
+ output: (page, members, next, first) => {
30
+ const errorMessage = page.error !== null ? connectionErrorMessages[page.error].zh : page.state === 'missing' || page.state === 'changed' ? keyStateMessages[page.state].zh : null;
31
+ return { readOnly: true, connection: this.connections.status(sessionId), source: selected === null ? 'explicit' : 'selection', key: identity, errorMessage,
32
+ value: { ...page, members, cursor: next, scanComplete: page.state === 'page' && next === null,
33
+ complete: page.state === 'page' && first && pattern === '*' && next === null && String(members.length) === page.metadata?.length } };
34
+ },
35
+ validate: error => { assertSelection(); this.connections.assertReadResult(sessionId, target, error); },
36
+ discard: () => this.sets.disposeSession(sessionId),
37
+ oversize: '单个 Set 成员或其必要元信息超过 AI 单次结果预算,无法完整返回;请缩小匹配范围。',
38
+ });
39
+ }
40
+ }
@@ -0,0 +1,15 @@
1
+ import type { StreamReadRequest } from '../domain.js';
2
+ import type { RedisConnections } from './connection-service.js';
3
+ import type { RedisStreams } from './stream-reader.js';
4
+ import { type PreparedAiPage } from './ai-page-store.js';
5
+ export declare const isAiStreamCursor: (cursor: string | null) => boolean;
6
+ /** Stream fields remain ordered occurrences; a message is never split. */
7
+ export declare class RedisAiStreamPages {
8
+ private readonly connections;
9
+ private readonly streams;
10
+ private readonly pages;
11
+ constructor(connections: RedisConnections, streams: RedisStreams);
12
+ disposeSession(sessionId: string): void;
13
+ dispose(): void;
14
+ prepare(sessionId: string, request: StreamReadRequest, cursor: string | null, selected: object | null, assertSelection: () => void, signal: AbortSignal): Promise<PreparedAiPage>;
15
+ }
@@ -0,0 +1,42 @@
1
+ import { connectionErrorMessages, keyStateMessages } from "../connection-errors.js";
2
+ import { byteIdentity } from "./byte-identity.js";
3
+ import { aiValue } from "./ai-value.js";
4
+ import { AiPageStore } from "./ai-page-store.js";
5
+ export const isAiStreamCursor = (cursor) => cursor?.startsWith('x:') === true;
6
+ /** Stream fields remain ordered occurrences; a message is never split. */
7
+ export class RedisAiStreamPages {
8
+ connections;
9
+ streams;
10
+ pages = new AiPageStore('x:');
11
+ constructor(connections, streams) {
12
+ this.connections = connections;
13
+ this.streams = streams;
14
+ }
15
+ disposeSession(sessionId) { this.pages.disposeSession(sessionId); this.streams.disposeSession(sessionId); }
16
+ dispose() { this.pages.dispose(); this.streams.dispose(); }
17
+ prepare(sessionId, request, cursor, selected, assertSelection, signal) {
18
+ signal.throwIfAborted();
19
+ this.connections.assertTarget(sessionId, request.target);
20
+ assertSelection();
21
+ const { target, keyBase64, direction, start, end, count } = request;
22
+ const identity = byteIdentity(Buffer.from(keyBase64, 'base64'));
23
+ return this.pages.prepare({
24
+ sessionId, binding: JSON.stringify([target.id, target.generation, target.db, keyBase64, direction, start, end, selected !== null]), selection: selected, cursor, signal, maxRows: count,
25
+ fetch: async (next) => {
26
+ const read = await this.streams.read(sessionId, { target, keyBase64, direction, start, end, count, cursor: next }, signal);
27
+ return read.state === 'unsupported' && read.metadata?.type !== 'stream' ? { ...read, state: 'changed', metadata: null } : read;
28
+ },
29
+ rows: page => page.messages,
30
+ output: (page, rows, next, first) => {
31
+ const messages = rows.map(message => ({ id: message.id, fields: message.fields.map((pair, index) => ({ index, field: pair.field, value: aiValue(pair.value) })) }));
32
+ const errorMessage = page.error !== null ? connectionErrorMessages[page.error].zh : page.state === 'missing' || page.state === 'changed' ? keyStateMessages[page.state].zh : null;
33
+ return { readOnly: true, connection: this.connections.status(sessionId), source: selected === null ? 'explicit' : 'selection', key: identity, errorMessage,
34
+ value: { ...page, messages, cursor: next, scanComplete: page.state === 'page' && next === null,
35
+ complete: page.state === 'page' && first && start === '-' && end === '+' && next === null && String(messages.length) === page.metadata?.length && messages.every(message => message.fields.every(pair => pair.value.complete)) } };
36
+ },
37
+ validate: error => { assertSelection(); this.connections.assertReadResult(sessionId, target, error); },
38
+ discard: () => this.streams.disposeSession(sessionId),
39
+ oversize: '单条 Stream 消息或其必要元信息超过 AI 单次结果上限,无法完整返回;请缩小读取范围。',
40
+ });
41
+ }
42
+ }
@@ -0,0 +1,4 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { RedisAiReader } from './ai-reader.js';
3
+ /** Official registry registrations are owned and unwound by this plugin fiber. */
4
+ export declare function registerRedisTools(ctx: Context, reader: RedisAiReader): void;
@@ -0,0 +1,106 @@
1
+ import { defineTool } from '@deepseek-ai/dsh-tools';
2
+ import { hashFilterParameters, keySearchParameters, registerRedisQueryScope } from "./ai-query-scope.js";
3
+ /** Identity is supplied by DSH execution, never accepted as model arguments. */
4
+ function owner(exec) {
5
+ exec.signal.throwIfAborted();
6
+ if (exec.agent === undefined)
7
+ throw new Error('Redis 工具调用缺少有效的 DSH 对话身份。');
8
+ return exec.agent.session.id;
9
+ }
10
+ function strict(args, allowed) {
11
+ if (Object.keys(args).some(key => !allowed.includes(key)))
12
+ throw new Error('Redis 工具包含不支持的参数。');
13
+ }
14
+ const output = { schema: { type: 'json' }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] };
15
+ const connectionViewMeaning = 'connection.generation 是插件连接与 DB 视图的版本,切换 DB 时可能递增;不能仅凭版本变化推断物理连接重建或 Redis 服务器重启。完成必要查询后无参数调用 redis_viewer_answer,展示本轮实际记录,再依据这些证据用自然语言回答用户问题;卡片展示不代替解释。';
16
+ const reportable = ' 返回的 reportSampleId 标识本次采样;用户明确要求保存该结果时,将它传给 redis_viewer_save_diagnostic_report,不必重新查询。标识只在本会话保留最近 16 个;若未返回该字段则本次结果不可保存报告。';
17
+ /** Official registry registrations are owned and unwound by this plugin fiber. */
18
+ export function registerRedisTools(ctx, reader) {
19
+ const assertQueryScope = registerRedisQueryScope(ctx, reader);
20
+ const diagnostic = (session, exec, kind, read) => reader.withBudget(session, exec.signal, async (stage) => {
21
+ const result = await read(), prepared = reader.reportSamples.prepare(session, kind, result, exec.signal);
22
+ stage(prepared);
23
+ return prepared.result;
24
+ }, exec);
25
+ ctx.tools.register(defineTool({
26
+ name: 'redis_viewer_status', description: '查看当前 DSH 对话已连接的 Redis、当前 DB 和侧栏选择同步状态。selectionSync 为 unavailable 时无法确认侧栏选择,currentSelection 为 null 不代表用户没有选择;仅 synchronized 时才返回当前已同步的 Key/字段/行标识。顶层 sampledAt 是本次状态时间,currentSelection.sampledAt 是该选择在 Host 的记录时间。' + connectionViewMeaning + '不会连接其他服务器。查询前先检查状态;解释当前选中值时,不传key调用redis_viewer_value。所有Redis数据操作只读。',
27
+ parameters: {}, output,
28
+ async execute(args, exec) { const session = owner(exec); return reader.withBudget(session, exec.signal, () => { strict(args, []); return reader.status(session); }); },
29
+ }));
30
+ ctx.tools.register(defineTool({
31
+ name: 'redis_viewer_keys', description: '首次查询须等待 DSH 原生范围确认;拒绝或取消后先澄清,不得自动重试或改用其他工具绕过。使用 SCAN 在当前对话连接的当前 DB 按明确 MATCH 检索 Key。MATCH 过滤返回的名称,并不保证 Redis 只遍历匹配前缀;完成迭代可能遍历整个当前 DB 的键空间,COUNT 100 是工作量提示而非硬上限。用户禁止扫描整个键空间时不能承诺匹配条件能避免遍历。每次调用都必须提供 match,包括续读;根据用户给出的名称线索确定范围,线索不足时请用户补充,只有用户明确要求浏览整个当前 DB 才使用 *。结果 pattern 是实际使用的条件。cursor 是不透明续读令牌,续读保持相同 match;一个 Redis 批次可分为多个结果,空页带 cursor 不等于没有匹配项。只返回本批,不冒充全库。即使 scanComplete 为 true,SCAN 也不是一致性快照,并发变化时不能断言某时刻的完整或唯一集合,跨批可能重复。',
32
+ parameters: keySearchParameters, output, timeoutMs: 15000, finalizeContent: reader.finalizeDelivery,
33
+ async execute(args, exec) { const session = owner(exec); assertQueryScope(exec); return reader.withBudget(session, exec.signal, stage => reader.scan(session, args, exec.signal, stage), exec); },
34
+ }));
35
+ ctx.tools.register(defineTool({
36
+ name: 'redis_viewer_key_metadata', description: '用户只问明确 Key 是否存在、类型或过期时间时优先使用本工具,不读取字段或值。提供 key 或 keyBase64 中恰好一个,无需侧栏选择。ttlMs 为 -1 表示采样时没有设置过期时间,不代表过去从未设置或将来不会过期;非负数为采样时剩余毫秒。sampledAt 是 UTC 的 ISO 8601 时间(Z 表示 UTC),不是本地时间。多命令采样不是原子快照,不能推断业务含义或提出未经用户请求的写入操作。',
37
+ parameters: { key: { type: 'string' }, keyBase64: { type: 'string' } }, output, timeoutMs: 15000,
38
+ async execute(args, exec) { const session = owner(exec); return reader.withBudget(session, exec.signal, () => { strict(args, ['key', 'keyBase64']); return reader.keyMetadata(session, args, exec.signal); }); },
39
+ }));
40
+ ctx.tools.register(defineTool({
41
+ name: 'redis_viewer_value', description: '只读查看当前 DB 中一个 Key,自动识别 String/Hash/List/Set/ZSet/Stream。明确查询 Hash 字段时同时提供 key/keyBase64 和 field/fieldBase64;检查 Set 或 ZSet 成员时同时提供 key/keyBase64 和 member/memberBase64,工具自动识别类型并返回存在性或分数。这些精确查询无需面板选择,不能混用字段、成员、分页或范围参数。不传key/keyBase64时读取侧栏当前Key或选中字段/行;选中具体字段或行时不能传分页或范围参数,需要读取范围请明确指定 Key。需要当前对话中唯一的 Redis 面板可见且选择已同步,界面不可用或选择变化会明确报错。source 区分显式目标和侧栏选择。文本身份与各自的 Base64 身份每组只能传一个。String用offset/bytes,List/ZSet排名用offset/count;Hash/Set/ZSet扫描用match/cursor,续读保留条件;ZSet扫描不能同时传offset/count;Stream用start/end/direction/count/cursor,续读保留方向和范围,按完整消息分批。整数位置和ID用字符串。metadata.ttlMs 为 -1 表示采样时没有设置过期时间,不能据此推断过去从未设置或将来不会过期;非负数是采样时剩余毫秒。值可能只是前缀,检查complete/byteLength/fullByteLength与续读信息,不将部分数据当作完整快照。',
42
+ parameters: { key: { type: 'string' }, keyBase64: { type: 'string' }, field: { type: 'string' }, fieldBase64: { type: 'string' }, member: { type: 'string' }, memberBase64: { type: 'string' }, cursor: { type: 'string' }, offset: { type: 'string' }, count: { type: 'integer' }, bytes: { type: 'integer' }, match: { type: 'string' }, start: { type: 'string' }, end: { type: 'string' }, direction: { type: 'string' } },
43
+ output, timeoutMs: 15000, finalizeContent: reader.finalizeDelivery,
44
+ async execute(args, exec) { const session = owner(exec); return reader.withBudget(session, exec.signal, stage => { strict(args, ['key', 'keyBase64', 'field', 'fieldBase64', 'member', 'memberBase64', 'cursor', 'offset', 'count', 'bytes', 'match', 'start', 'end', 'direction']); return reader.read(session, args, exec.signal, stage); }, exec); },
45
+ }));
46
+ ctx.tools.register(defineTool({
47
+ name: 'redis_viewer_filter_hash', description: '首次查询须等待 DSH 原生范围确认;拒绝或取消后先澄清,不得自动重试或改用其他工具绕过。仅在用户明确指定当前 DB 的 Key MATCH 范围、Hash 字段和目标值时调用。MATCH 过滤候选名称,不保证 Redis 避免遍历整个当前 DB 的键空间;COUNT 是工作量提示而非硬上限。每次最多检查 10 个候选,只返回字段值与目标值按 UTF-8 字节完全相等的 Key,不返回其他值;结果包含本批各状态数量、错误及不透明 cursor;notHash 表示首次检查时不是 Hash,typeChanged 表示读取期间观察到类型变化。继续时保持 match、field 和 equals 不变。scanComplete 只表示扫描结束;跨批可能重复,SCAN 和逐项读取不是一致性快照。不得据部分结果声称全库统计,不跨 DB 或连接。',
48
+ parameters: hashFilterParameters, output, timeoutMs: 15000, finalizeContent: reader.finalizeDelivery,
49
+ async execute(args, exec) { const session = owner(exec); assertQueryScope(exec); return reader.withBudget(session, exec.signal, stage => reader.filterHash(session, args, exec.signal, stage), exec); },
50
+ }));
51
+ ctx.tools.register(defineTool({
52
+ name: 'redis_viewer_timeseries', description: '用户明确给出当前 DB 的 TimeSeries Key 和时间范围时调用;key/keyBase64 选一个,from 和 to 是包含两端的 Unix 毫秒时间戳十进制字符串,count 为每批最多 100 个样本,默认 100。使用 TS.RANGE 读取并通过 TYPE 检查类型;不聚合、不跨 Key。返回时间与值的原始字符串,以及可表示范围内由毫秒时间戳换算的 timestampUtc;超出日期范围时该字段为 null。仅 state 为 value 且 cursor 非空时可续读,并保持 Key、from、to 和 count 不变。续读返回非 value 状态时旧游标失效,须从原范围重新查询;取消或未收到结果时游标状态不确定。complete 仅指 TS.RANGE 可见结果;压缩序列省略最新未闭合桶,已关闭桶可能包含结束时间后的原始样本。多批不是快照。',
53
+ parameters: { key: { type: 'string' }, keyBase64: { type: 'string' }, from: { type: 'string', required: true }, to: { type: 'string', required: true }, count: { type: 'integer' }, cursor: { type: 'string' } }, output, timeoutMs: 15000, finalizeContent: reader.finalizeDelivery,
54
+ async execute(args, exec) { const session = owner(exec); return reader.withBudget(session, exec.signal, async (stage) => { strict(args, ['key', 'keyBase64', 'from', 'to', 'count', 'cursor']); const page = await reader.prepareTimeSeries(session, args, exec.signal); stage(page); return page.result; }, exec); },
55
+ }));
56
+ ctx.tools.register(defineTool({
57
+ name: 'redis_viewer_json_path', description: '仅在用户明确指定 RedisJSON Key 和以 $ 开头的 JSONPath 时调用;key 与 keyBase64 选一个,path 必填,不自行扩大为根路径或通配符。使用一个 JSON.GET 读取并通过 TYPE 检查类型,结果 matchesJson 是 Redis 返回的 JSON 数组原文:[] 表示没有匹配,[null] 表示匹配到 null。大整数保持原文。查询可能遍历或返回整个子树,Redis 无服务端分页;超限不返回部分 JSON。单次采样不是快照,模块不可用、权限及类型不符应分别说明。',
58
+ parameters: { key: { type: 'string' }, keyBase64: { type: 'string' }, path: { type: 'string', required: true } }, output, timeoutMs: 15000,
59
+ async execute(args, exec) { const session = owner(exec); return reader.withBudget(session, exec.signal, () => { strict(args, ['key', 'keyBase64', 'path']); return reader.jsonPath(session, args, exec.signal); }); },
60
+ }));
61
+ ctx.tools.register(defineTool({
62
+ name: 'redis_viewer_geo', description: '仅在用户明确询问地理位置或距离时,指定当前 DB 的 key/keyBase64 与 member/memberBase64。查询两成员距离时另指定 other/otherBase64,unit 可为 m、km、ft、mi,默认 m;不提供第二成员则只读第一成员坐标。使用 GEOPOS 或 GEODIST 读取并通过 TYPE 检查类型;不搜索、修改或选择 Key。结果 geoIndexVerified 为 false:ZSet 类型不能证明数据由 GEO 写入,需用户确认其用途;坐标有编码误差,距离按球形地球近似,单次结果不是快照。',
63
+ parameters: { key: { type: 'string' }, keyBase64: { type: 'string' }, member: { type: 'string' }, memberBase64: { type: 'string' }, other: { type: 'string' }, otherBase64: { type: 'string' }, unit: { type: 'string' } }, output, timeoutMs: 15000,
64
+ async execute(args, exec) { const session = owner(exec); return reader.withBudget(session, exec.signal, () => { strict(args, ['key', 'keyBase64', 'member', 'memberBase64', 'other', 'otherBase64', 'unit']); return reader.geo(session, args, exec.signal); }); },
65
+ }));
66
+ ctx.tools.register(defineTool({
67
+ name: 'redis_viewer_bitmap', description: '用户明确询问 Bitmap 位时,指定当前 DB 的 key 或 keyBase64、从零开始的位 offset 和 count(1 到 1024)。只返回该范围的 0/1 位,不返回原始字节;超出 String 长度的位按 Redis 语义为 0,Key 不存在单独报告。不能从单次采样推断业务含义或历史。',
68
+ parameters: { key: { type: 'string' }, keyBase64: { type: 'string' }, offset: { type: 'string', required: true }, count: { type: 'integer', required: true } }, output, timeoutMs: 15000,
69
+ async execute(args, exec) { const session = owner(exec); return reader.withBudget(session, exec.signal, () => { strict(args, ['key', 'keyBase64', 'offset', 'count']); return reader.bitmap(session, args, exec.signal); }); },
70
+ }));
71
+ ctx.tools.register(defineTool({
72
+ name: 'redis_viewer_memory', description: '只读估计当前对话连接、当前 DB 中一个明确 Key 的内存占用。提供 key 或 keyBase64 中恰好一个;不需要侧栏选择。MEMORY USAGE 的 SAMPLES 5 是请求参数而非实际采样数量,嵌套值可能使用采样估计,实际数量和误差未知;结果包含该 Key 与值的分配及管理开销,可能包含内部分配碎片,不代表服务器总内存。bytes 为十进制字符串;不推断未读取的 Key 类型。Key 不存在、命令不可用、权限不足和读取失败分别报告,不读取值、不跨库。' + reportable,
73
+ parameters: { key: { type: 'string' }, keyBase64: { type: 'string' } }, output, timeoutMs: 15000, finalizeContent: reader.finalizeDelivery,
74
+ async execute(args, exec) { const session = owner(exec); return diagnostic(session, exec, 'memory', () => { strict(args, ['key', 'keyBase64']); return reader.memoryUsage(session, args, exec.signal); }); },
75
+ }));
76
+ ctx.tools.register(defineTool({
77
+ name: 'redis_viewer_compare_strings', description: '仅在用户明确给出当前 DB 的两个 String Key 并要求比较时使用。左侧 left/leftBase64 与右侧 right/rightBase64 各选一个,Base64 用于二进制 Key。每侧最多比较前 4096 字节,不返回原始值。comparison 为 equal、different、undetermined 或 unavailable。长度或前缀不同可判断不同;前缀相同但有截断只能说无法判定。两次采样有各自时间,并非原子快照;不存在、类型不符、权限失败分别在两侧报告。' + reportable,
78
+ parameters: { left: { type: 'string' }, leftBase64: { type: 'string' }, right: { type: 'string' }, rightBase64: { type: 'string' } }, output, timeoutMs: 15000, finalizeContent: reader.finalizeDelivery,
79
+ async execute(args, exec) { const session = owner(exec); return diagnostic(session, exec, 'compare_strings', () => { strict(args, ['left', 'leftBase64', 'right', 'rightBase64']); return reader.compareStrings(session, args, exec.signal); }); },
80
+ }));
81
+ ctx.tools.register(defineTool({
82
+ name: 'redis_viewer_slowlog', description: '在用户询问慢查询时,只读取得当前连接的 Redis 服务器最近慢日志,count 范围 1 到 10,默认 10。返回记录 ID、Unix 秒、由插件计算的事件 UTC 时间 timestampUtc、执行耗时微秒和安全的命令名;timestampUtc 为 null 表示原始秒数超出日期可表示范围,sampledAt 是查询时间而非事件时间。不返回命令参数、客户端地址或名称。慢日志是服务器范围而非当前 DB,执行耗时不含网络,空结果不代表历史或当前绝无慢查询;权限不足和读取失败会明确报告。' + reportable,
83
+ parameters: { count: { type: 'integer' } }, output, timeoutMs: 15000, finalizeContent: reader.finalizeDelivery,
84
+ async execute(args, exec) { const session = owner(exec); return diagnostic(session, exec, 'slowlog', () => { strict(args, ['count']); return reader.slowLog(session, args.count ?? 10, exec.signal); }); },
85
+ }));
86
+ ctx.tools.register(defineTool({
87
+ name: 'redis_viewer_overview', description: '按用户问题只读查看当前 Redis 服务器一个概况类别:server(版本和运行时长)、memory(内存)、clients(连接数量)、stats(命令与命中等计数)。section 必须明确为其中一种,数值保留字符串精度;只返回固定白名单字段,不返回 INFO 原文。scope 为服务器范围,缺少字段用 partial 和 missing 表示,不能以单次采样推断变化趋势或故障原因。' + reportable,
88
+ parameters: { section: { type: 'string', required: true } }, output, timeoutMs: 15000, finalizeContent: reader.finalizeDelivery,
89
+ async execute(args, exec) { const session = owner(exec); return diagnostic(session, exec, 'overview', () => { strict(args, ['section']); return reader.overview(session, args.section, exec.signal); }); },
90
+ }));
91
+ ctx.tools.register(defineTool({
92
+ name: 'redis_viewer_clients', description: '仅在用户询问连接明细时只读采样当前 Redis 服务器客户端。最多返回 20 个连接的 ID、连接时长、空闲秒数、DB 和标志,不返回客户端地址、名称、用户名或命令;当前服务器连接信息仍包含在 connection 中。totalCount 是收到的总数,complete 为 false 表示只展示部分。CLIENT LIST 是服务器范围且无服务端分页,会遍历所有连接;超大响应和权限不足明确报错。单次采样不能代表趋势或断言故障原因。' + reportable,
93
+ parameters: {}, output, timeoutMs: 15000, finalizeContent: reader.finalizeDelivery,
94
+ async execute(args, exec) { const session = owner(exec); return diagnostic(session, exec, 'clients', () => { strict(args, []); return reader.clients(session, exec.signal); }); },
95
+ }));
96
+ ctx.tools.register(defineTool({
97
+ name: 'redis_viewer_stream_groups', description: '用户询问 Stream 消费组或消息积压时,按明确 key 或 keyBase64 只读 XINFO GROUPS 并通过 TYPE 检查类型。返回每组 pending(已投递未确认)和 lag(未投递,可能未知),以及消费人数和最后投递 ID;不读取消息,不确认或推进消费。最多输出 20 个组,complete 为 false 表示只返回部分;Redis 不能服务端分页,超大响应会明确失败。采样不是一致性快照,不能单凭一次计数推断积压原因或趋势。' + reportable,
98
+ parameters: { key: { type: 'string' }, keyBase64: { type: 'string' } }, output, timeoutMs: 15000, finalizeContent: reader.finalizeDelivery,
99
+ async execute(args, exec) { const session = owner(exec); return diagnostic(session, exec, 'stream_groups', () => { strict(args, ['key', 'keyBase64']); return reader.streamGroups(session, args, exec.signal); }); },
100
+ }));
101
+ ctx.tools.register(defineTool({
102
+ name: 'redis_viewer_select_db', description: '仅在用户明确要求切换DB时使用:切换当前对话已连接Redis的数据库,并让侧栏同步。结果的 requestedDb 是请求目标,connection 是实际状态,sampledAt 是本次状态时间。' + connectionViewMeaning + '普通查询必须沿用当前DB,不能为了搜索自行切库;不会连接其他服务器或写入Redis数据。',
103
+ parameters: { db: { type: 'integer', required: true, description: '用户明确要求的DB编号,0到65535。' } }, output, timeoutMs: 15000,
104
+ async execute(args, exec) { const session = owner(exec); return reader.withBudget(session, exec.signal, () => { strict(args, ['db']); return reader.selectDatabase(session, args.db, exec.signal); }); },
105
+ }));
106
+ }
@@ -0,0 +1,10 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { UiAction } from '../domain.js';
3
+ import type { UiActionCoordinator } from './ui-action-coordinator.js';
4
+ import type { RedisAiReader } from './ai-reader.js';
5
+ /** The session comes from DSH, never from model arguments. */
6
+ export declare function registerRedisUiTools(ctx: Context, actions: UiActionCoordinator<UiAction>): void;
7
+ /** Refresh a confirmed current selection once; never enable periodic refresh. */
8
+ export declare function registerRedisRefreshTool(ctx: Context, reader: RedisAiReader, actions: UiActionCoordinator<UiAction>): void;
9
+ /** A format action changes only the currently visible value preview. */
10
+ export declare function registerRedisFormatTool(ctx: Context, reader: RedisAiReader, actions: UiActionCoordinator<UiAction>): void;
@@ -0,0 +1,72 @@
1
+ import { defineTool } from '@deepseek-ai/dsh-tools';
2
+ import { ConnectionFailure } from "./connection-service.js";
3
+ import { PREVIEW_FORMATS } from "../domain.js";
4
+ /** The session comes from DSH, never from model arguments. */
5
+ export function registerRedisUiTools(ctx, actions) {
6
+ ctx.tools.register(defineTool({
7
+ name: 'redis_viewer_show',
8
+ description: '仅在用户要求显示 Redis 面板时调用:请求在当前对话打开 Redis 侧栏;只有界面确认可见后才返回 applied。没有可用客户端或无法确认时,请用户手动打开。',
9
+ parameters: {},
10
+ output: { schema: { type: 'json' }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
11
+ timeoutMs: 15000,
12
+ async execute(args, exec) {
13
+ exec.signal.throwIfAborted();
14
+ if (exec.agent === undefined)
15
+ throw new Error('Redis 工具调用缺少有效的 DSH 对话身份。');
16
+ if (Object.keys(args).length !== 0)
17
+ throw new Error('Redis 工具包含不支持的参数。');
18
+ const outcome = await actions.dispatch(exec.agent.session.id, { kind: 'show' }, null, 0, () => true, exec.signal);
19
+ return { outcome, message: outcome === 'applied' ? '当前对话的 Redis 面板已确认可见。' : outcome === 'no_receiver' ? '请在当前对话手动打开 Redis 侧栏后重试。' : outcome === 'ambiguous' ? '当前对话有多个可接收的界面,请只保留一个后重试。' : '无法确认 Redis 面板可见,请检查当前侧栏后重试。' };
20
+ },
21
+ }));
22
+ }
23
+ /** Refresh a confirmed current selection once; never enable periodic refresh. */
24
+ export function registerRedisRefreshTool(ctx, reader, actions) {
25
+ ctx.tools.register(defineTool({
26
+ name: 'redis_viewer_refresh', description: '仅在用户明确要求刷新当前 Redis 面板选中的 Key 时调用。刷新会从 Redis 读取当前查看范围并更新预览,不修改数据、不自动开启周期刷新;本工具结果只返回界面回执,不返回读到的值,不能据此声称没有读取值。只有对应读取结果渲染且选择重新同步后才返回 applied。disconnected 表示界面动作通道断开,不能据此判断 Redis 连接已断开;其他未确认结果也不能证明读取未发生或命令已撤回。按实际回执说明,不能推测超时或失败的根因。',
27
+ parameters: {}, output: { schema: { type: 'json' }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] }, timeoutMs: 15000,
28
+ async execute(args, exec) {
29
+ exec.signal.throwIfAborted();
30
+ if (exec.agent === undefined)
31
+ throw new Error('Redis 工具调用缺少有效的 DSH 对话身份。');
32
+ if (Object.keys(args).length !== 0)
33
+ throw new Error('Redis 工具包含不支持的参数。');
34
+ const session = exec.agent.session.id;
35
+ return reader.withBudget(session, exec.signal, async () => {
36
+ const prepared = await reader.prepareUiSelection(session, exec.signal).catch((error) => { if (error instanceof ConnectionFailure && error.code === 'stale')
37
+ return null; throw error; });
38
+ if (prepared === null)
39
+ return { outcome: 'stale', message: '连接或界面选择已变化,请检查面板。' };
40
+ const outcome = await actions.dispatch(session, { kind: 'refresh', target: prepared.target, keyBase64: prepared.keyBase64 }, null, prepared.revision, prepared.current, exec.signal);
41
+ // A UI receipt is not a Redis connection-status sample or proof that no read was sent.
42
+ const message = outcome === 'applied'
43
+ ? '已确认当前面板完成当前查看范围的一次 Redis 只读读取并显示结果;本工具回执不包含读到的值。'
44
+ : `${outcome === 'disconnected' ? '界面动作通道已断开;此回执不代表 Redis 连接状态。' : ''}未能确认刷新结果;读取可能已经发出,不能断言未读取值或命令已撤回。请检查当前面板。`;
45
+ return { outcome, message };
46
+ });
47
+ },
48
+ }));
49
+ }
50
+ /** A format action changes only the currently visible value preview. */
51
+ export function registerRedisFormatTool(ctx, reader, actions) {
52
+ ctx.tools.register(defineTool({
53
+ name: 'redis_viewer_format', description: '仅在用户明确要求改变当前 Redis 面板已选中值的预览格式时调用。format 为 text、json、hex 或 base64;只改变界面,不修改 Redis 数据。只有目标预览已显示对应格式且格式化成功才返回 applied;当前没有可见值、JSON 无效或被截断、界面/选择变化时不能声称成功。',
54
+ parameters: { format: { type: 'string', required: true } }, output: { schema: { type: 'json' }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] }, timeoutMs: 15000,
55
+ async execute(args, exec) {
56
+ exec.signal.throwIfAborted();
57
+ if (exec.agent === undefined)
58
+ throw new Error('Redis 工具调用缺少有效的 DSH 对话身份。');
59
+ if (Object.keys(args).some(key => key !== 'format') || !PREVIEW_FORMATS.some(value => value === args.format))
60
+ throw new Error('预览格式仅支持 text、json、hex 或 base64。');
61
+ const session = exec.agent.session.id, format = args.format;
62
+ return reader.withBudget(session, exec.signal, async () => {
63
+ const prepared = await reader.prepareUiSelection(session, exec.signal).catch((error) => { if (error instanceof ConnectionFailure && error.code === 'stale')
64
+ return null; throw error; });
65
+ if (prepared === null)
66
+ return { outcome: 'stale', message: '连接或界面选择已变化,请检查面板。' };
67
+ const outcome = await actions.dispatch(session, { kind: 'setFormat', keyBase64: prepared.keyBase64, format }, prepared.target, prepared.revision, prepared.sameRevision, exec.signal);
68
+ return { outcome, format, message: outcome === 'applied' ? '已确认当前值按指定格式显示。' : '未能确认指定格式显示,请检查当前面板和值。' };
69
+ });
70
+ },
71
+ }));
72
+ }
@@ -0,0 +1,12 @@
1
+ import type { BytePrefix } from '../domain.js';
2
+ export declare const MAX_AI_VALUE_BYTES = 4096;
3
+ /** Decode complete UTF-8 only; binary values retain their original bytes. */
4
+ export declare function aiText(bytes: Buffer): string | null;
5
+ /** Values may be prefixes, but field and member identities never are. */
6
+ export declare function aiValue(bytes: BytePrefix): {
7
+ base64: string;
8
+ text: string | null;
9
+ byteLength: number;
10
+ fullByteLength: number;
11
+ complete: boolean;
12
+ };
@@ -0,0 +1,15 @@
1
+ export const MAX_AI_VALUE_BYTES = 4096;
2
+ /** Decode complete UTF-8 only; binary values retain their original bytes. */
3
+ export function aiText(bytes) {
4
+ try {
5
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
6
+ }
7
+ catch {
8
+ return null;
9
+ }
10
+ }
11
+ /** Values may be prefixes, but field and member identities never are. */
12
+ export function aiValue(bytes) {
13
+ const raw = Buffer.from(bytes.base64, 'base64').subarray(0, MAX_AI_VALUE_BYTES);
14
+ return { base64: raw.toString('base64'), text: aiText(raw), byteLength: raw.length, fullByteLength: bytes.fullByteLength, complete: raw.length === bytes.fullByteLength };
15
+ }
@@ -0,0 +1,5 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { RedisAiReader } from './ai-reader.js';
3
+ import type { RedisAiWriter } from './ai-writer.js';
4
+ /** Use committed native Session events, never a model-supplied session or turn. */
5
+ export declare function registerRedisWriteTools(ctx: Context, reader: RedisAiReader, writer: RedisAiWriter): void;