shennian 0.3.86 → 0.4.0

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 (98) hide show
  1. package/README.md +3 -2
  2. package/dist/bin/shennian.js +1 -1
  3. package/dist/publish-build-manifest.json +32 -27
  4. package/dist/src/agents/adapter.js +1 -19
  5. package/dist/src/agents/claude-managed-permissions.js +1 -248
  6. package/dist/src/agents/claude.js +8 -393
  7. package/dist/src/agents/codex-managed-permissions.js +1 -294
  8. package/dist/src/agents/codex-managed-room-tools.js +1 -249
  9. package/dist/src/agents/codex-utils.js +7 -200
  10. package/dist/src/agents/codex.d.ts +7 -1
  11. package/dist/src/agents/codex.js +17 -1352
  12. package/dist/src/agents/config-status.js +1 -226
  13. package/dist/src/agents/cursor-managed-permissions.js +2 -299
  14. package/dist/src/agents/cursor.js +1 -314
  15. package/dist/src/agents/custom.js +4 -418
  16. package/dist/src/agents/external-channel-instructions.js +11 -94
  17. package/dist/src/agents/gemini.js +1 -180
  18. package/dist/src/agents/manager.js +18 -250
  19. package/dist/src/agents/model-registry/cache.js +1 -37
  20. package/dist/src/agents/model-registry/discovery.js +2 -188
  21. package/dist/src/agents/model-registry/parsers.js +4 -521
  22. package/dist/src/agents/model-registry/runner.js +1 -30
  23. package/dist/src/agents/model-registry/service.js +1 -115
  24. package/dist/src/agents/model-registry/types.js +1 -8
  25. package/dist/src/agents/model-registry.js +1 -19
  26. package/dist/src/agents/native-capabilities.js +1 -237
  27. package/dist/src/agents/openclaw.js +2 -293
  28. package/dist/src/agents/opencode-managed-permissions.js +2 -187
  29. package/dist/src/agents/opencode.js +1 -298
  30. package/dist/src/agents/platform-instructions.js +17 -46
  31. package/dist/src/agents/runtime-compatibility.js +1 -44
  32. package/dist/src/agents/workbuddy-managed-permissions.js +2 -329
  33. package/dist/src/agents/workbuddy.js +3 -444
  34. package/dist/src/commands/logout.d.ts +3 -0
  35. package/dist/src/commands/logout.js +1 -0
  36. package/dist/src/daemon-ipc/paths.js +1 -1
  37. package/dist/src/fs/boundary.js +1 -185
  38. package/dist/src/fs/handler.js +1 -130
  39. package/dist/src/fs/security.js +1 -32
  40. package/dist/src/fs/text-decoder.js +1 -110
  41. package/dist/src/index.js +3 -587
  42. package/dist/src/manager/prompt.js +29 -34
  43. package/dist/src/manager/registry.js +1 -317
  44. package/dist/src/manager/retired-external-channel-compat.js +1 -40
  45. package/dist/src/manager/runtime.js +23 -1514
  46. package/dist/src/native-fusion/codex-parser.d.ts +3 -1
  47. package/dist/src/native-fusion/codex-parser.js +4 -660
  48. package/dist/src/native-fusion/codex-user-input.js +5 -102
  49. package/dist/src/native-fusion/config.js +1 -5
  50. package/dist/src/native-fusion/file-watcher.js +1 -191
  51. package/dist/src/native-fusion/local-repository.js +2 -569
  52. package/dist/src/native-fusion/opencode-parser.js +3 -130
  53. package/dist/src/native-fusion/parser-common.d.ts +6 -1
  54. package/dist/src/native-fusion/parser-common.js +4 -4
  55. package/dist/src/native-fusion/parsers.d.ts +4 -2
  56. package/dist/src/native-fusion/parsers.js +3 -140
  57. package/dist/src/native-fusion/service.js +2 -739
  58. package/dist/src/native-fusion/session-header.js +2 -101
  59. package/dist/src/native-fusion/state.js +2 -104
  60. package/dist/src/native-fusion/types.js +1 -1
  61. package/dist/src/personal-sync/machine-authority.js +1 -34
  62. package/dist/src/room/activation-audit.js +2 -45
  63. package/dist/src/room/activation-policy.js +1 -30
  64. package/dist/src/room/activation-service.js +8 -408
  65. package/dist/src/room/invite-bootstrap.js +1 -156
  66. package/dist/src/room/managed-prompt-composer.d.ts +1 -1
  67. package/dist/src/room/managed-prompt-composer.js +17 -16
  68. package/dist/src/room/managed-room-binding.js +1 -167
  69. package/dist/src/room/managed-room-ipc.d.ts +4 -0
  70. package/dist/src/room/managed-room-ipc.js +2 -2
  71. package/dist/src/room/mirror-sync-service.d.ts +1 -0
  72. package/dist/src/room/mirror-sync-service.js +1 -183
  73. package/dist/src/room/room-binding-client.js +1 -151
  74. package/dist/src/session/archive-zip.js +1 -220
  75. package/dist/src/session/deletion-sync-state.js +2 -136
  76. package/dist/src/session/handlers/agent-capabilities.js +1 -14
  77. package/dist/src/session/handlers/agent-config.js +1 -150
  78. package/dist/src/session/handlers/agents.js +1 -55
  79. package/dist/src/session/handlers/chat.js +2 -1030
  80. package/dist/src/session/handlers/control.js +1 -61
  81. package/dist/src/session/handlers/fs.js +1 -594
  82. package/dist/src/session/handlers/message-status.js +1 -15
  83. package/dist/src/session/handlers/remote-access.js +1 -43
  84. package/dist/src/session/handlers/room-managed.js +1 -101
  85. package/dist/src/session/handlers/session-refresh.js +1 -35
  86. package/dist/src/session/handlers/title.js +1 -79
  87. package/dist/src/session/handlers/tool-detail.js +1 -149
  88. package/dist/src/session/handlers/voice-window.js +1 -62
  89. package/dist/src/session/history-subscriptions.js +1 -470
  90. package/dist/src/session/manager.d.ts +1 -0
  91. package/dist/src/session/manager.js +1 -658
  92. package/dist/src/session/native-cleanup-outbox.js +2 -287
  93. package/dist/src/session/native-session-lifecycle.js +6 -327
  94. package/dist/src/session/queue.d.ts +8 -0
  95. package/dist/src/session/queue.js +6 -6
  96. package/dist/src/upgrade/scheduler.js +1 -126
  97. package/node_modules/@shennian/wire/dist/agent-workspace.js +2 -2
  98. package/package.json +1 -1
@@ -1,151 +1 @@
1
- // @arch docs/features/network-rooms/multi-session-client-and-room-panel.md#32-每次调用都必须带可信调用上下文
2
- // @test src/__tests__/room-binding-client.test.ts
3
- import { HttpRoomActionClient } from './room-action-client.js';
4
- export class RoomBindingHttpError extends Error {
5
- code;
6
- constructor(code, message) {
7
- super(message);
8
- this.code = code;
9
- this.name = 'RoomBindingHttpError';
10
- }
11
- }
12
- export class HttpRoomBindingClient {
13
- fetchImpl;
14
- baseUrl;
15
- actionClient;
16
- constructor(serverUrl, fetchImpl = fetch) {
17
- this.fetchImpl = fetchImpl;
18
- this.baseUrl = serverUrl.replace(/\/+$/, '');
19
- this.actionClient = new HttpRoomActionClient(serverUrl, fetchImpl);
20
- }
21
- status = (target) => this.actionClient.status(target);
22
- getAttachmentCapability = (target) => this.actionClient.getAttachmentCapability(target);
23
- initializeAttachment = (target) => this.actionClient.initializeAttachment(target);
24
- completeAttachment = (target) => this.actionClient.completeAttachment(target);
25
- createRoom = (input) => this.actionClient.createRoom(input);
26
- createOperatorRoom = (input) => this.actionClient.createOperatorRoom(input);
27
- resolveNativeSession = (input) => this.actionClient.resolveNativeSession(input);
28
- joinRoom = (input) => this.actionClient.joinRoom(input);
29
- read = (target) => this.actionClient.read(target);
30
- send = (target) => this.actionClient.send(target);
31
- mode = (target) => this.actionClient.mode(target);
32
- pause = (target) => this.actionClient.pause(target);
33
- async create(input) {
34
- let response;
35
- try {
36
- response = await this.fetchImpl(`${this.baseUrl}/api/rooms/${encodeURIComponent(input.roomId)}/bindings`, {
37
- method: 'POST',
38
- headers: {
39
- authorization: `Bearer ${input.machineToken}`,
40
- 'content-type': 'application/json',
41
- },
42
- body: JSON.stringify({
43
- bindingIntentId: input.bindingIntentId,
44
- agentIdentityId: input.agentIdentityId,
45
- nianSessionId: input.nianSessionId,
46
- runtimeAdapter: input.runtimeAdapter,
47
- sessionRegistryKey: input.sessionRegistryKey,
48
- activationCapability: input.activationCapability,
49
- activationMode: input.activationMode,
50
- }),
51
- signal: AbortSignal.timeout(10_000),
52
- });
53
- }
54
- catch {
55
- throw new RoomBindingHttpError('room_binding_server_unavailable', 'Shennian Room service is unavailable.');
56
- }
57
- if (!response.ok) {
58
- let code = `room_binding_http_${response.status}`;
59
- try {
60
- const body = (await response.json());
61
- if (typeof body.error === 'string' && /^[a-z0-9_-]{1,80}$/.test(body.error))
62
- code = body.error;
63
- }
64
- catch { }
65
- throw new RoomBindingHttpError(code, 'Shennian Room binding request failed.');
66
- }
67
- let body;
68
- try {
69
- body = await response.json();
70
- }
71
- catch {
72
- throw new RoomBindingHttpError('invalid_room_binding_response', 'Invalid Room binding response.');
73
- }
74
- return validateResponse(body, input);
75
- }
76
- async restart(input) {
77
- let response;
78
- try {
79
- response = await this.fetchImpl(`${this.baseUrl}/api/rooms/${encodeURIComponent(input.roomId)}/bindings/${encodeURIComponent(input.bindingId)}/session`, {
80
- method: 'PATCH',
81
- headers: {
82
- authorization: `Bearer ${input.machineToken}`,
83
- 'content-type': 'application/json',
84
- },
85
- body: JSON.stringify({
86
- agentIdentityId: input.agentIdentityId,
87
- previousNianSessionId: input.previousNianSessionId,
88
- nianSessionId: input.nianSessionId,
89
- runtimeAdapter: input.runtimeAdapter,
90
- sessionRegistryKey: input.sessionRegistryKey,
91
- }),
92
- signal: AbortSignal.timeout(10_000),
93
- });
94
- }
95
- catch {
96
- throw new RoomBindingHttpError('room_binding_server_unavailable', 'Shennian Room service is unavailable.');
97
- }
98
- const body = await response.json().catch(() => null);
99
- if (!response.ok) {
100
- const code = body && typeof body.error === 'string' && /^[a-z0-9_-]{1,80}$/.test(body.error)
101
- ? body.error
102
- : `room_binding_http_${response.status}`;
103
- throw new RoomBindingHttpError(code, 'Shennian Room restart request failed.');
104
- }
105
- const result = body;
106
- if (!result?.binding ||
107
- result.binding.id !== input.bindingId ||
108
- result.binding.roomId !== input.roomId ||
109
- result.binding.agentIdentityId !== input.agentIdentityId ||
110
- result.binding.nianSessionId !== input.nianSessionId ||
111
- result.binding.runtimeAdapter !== input.runtimeAdapter ||
112
- typeof result.binding.agentMembershipId !== 'string' ||
113
- typeof result.resumeSequence !== 'string' ||
114
- !/^(0|[1-9]\d{0,19})$/.test(result.resumeSequence) ||
115
- typeof result.idempotent !== 'boolean') {
116
- throw new RoomBindingHttpError('invalid_room_binding_response', 'Invalid Room restart response.');
117
- }
118
- return {
119
- binding: result.binding,
120
- resumeSequence: result.resumeSequence,
121
- idempotent: result.idempotent,
122
- };
123
- }
124
- }
125
- function validateResponse(value, input) {
126
- if (!value || typeof value !== 'object') {
127
- throw new RoomBindingHttpError('invalid_room_binding_response', 'Invalid Room binding response.');
128
- }
129
- const object = value;
130
- const binding = object.binding;
131
- if (!binding ||
132
- typeof binding.id !== 'string' ||
133
- typeof binding.agentMembershipId !== 'string' ||
134
- binding.roomId !== input.roomId ||
135
- binding.agentIdentityId !== input.agentIdentityId ||
136
- binding.nianSessionId !== input.nianSessionId ||
137
- binding.runtimeAdapter !== input.runtimeAdapter ||
138
- binding.activationCapability !== input.activationCapability ||
139
- !matchesRequestedActivationMode(binding.activationMode, input) ||
140
- !['pending_approval', 'active', 'paused', 'detached'].includes(binding.status ?? '') ||
141
- typeof object.idempotent !== 'boolean') {
142
- throw new RoomBindingHttpError('invalid_room_binding_response', 'Room binding response does not match the request.');
143
- }
144
- return { binding: binding, idempotent: object.idempotent };
145
- }
146
- function matchesRequestedActivationMode(responseMode, input) {
147
- if (input.activationCapability === 'managed' && input.activationMode === 'auto_follow') {
148
- return responseMode === 'auto_follow' || responseMode === 'mention_only';
149
- }
150
- return responseMode === input.activationMode;
151
- }
1
+ import{HttpRoomActionClient as r}from"./room-action-client.js";class a extends Error{code;constructor(e,n){super(n),this.code=e,this.name="RoomBindingHttpError"}}class l{fetchImpl;baseUrl;actionClient;constructor(e,n=fetch){this.fetchImpl=n,this.baseUrl=e.replace(/\/+$/,""),this.actionClient=new r(e,n)}status=e=>this.actionClient.status(e);getAttachmentCapability=e=>this.actionClient.getAttachmentCapability(e);initializeAttachment=e=>this.actionClient.initializeAttachment(e);completeAttachment=e=>this.actionClient.completeAttachment(e);createRoom=e=>this.actionClient.createRoom(e);createOperatorRoom=e=>this.actionClient.createOperatorRoom(e);resolveNativeSession=e=>this.actionClient.resolveNativeSession(e);joinRoom=e=>this.actionClient.joinRoom(e);read=e=>this.actionClient.read(e);send=e=>this.actionClient.send(e);mode=e=>this.actionClient.mode(e);pause=e=>this.actionClient.pause(e);async create(e){let n;try{n=await this.fetchImpl(`${this.baseUrl}/api/rooms/${encodeURIComponent(e.roomId)}/bindings`,{method:"POST",headers:{authorization:`Bearer ${e.machineToken}`,"content-type":"application/json"},body:JSON.stringify({bindingIntentId:e.bindingIntentId,agentIdentityId:e.agentIdentityId,nianSessionId:e.nianSessionId,runtimeAdapter:e.runtimeAdapter,sessionRegistryKey:e.sessionRegistryKey,activationCapability:e.activationCapability,activationMode:e.activationMode}),signal:AbortSignal.timeout(1e4)})}catch{throw new a("room_binding_server_unavailable","Shennian Room service is unavailable.")}if(!n.ok){let i=`room_binding_http_${n.status}`;try{const s=await n.json();typeof s.error=="string"&&/^[a-z0-9_-]{1,80}$/.test(s.error)&&(i=s.error)}catch{}throw new a(i,"Shennian Room binding request failed.")}let t;try{t=await n.json()}catch{throw new a("invalid_room_binding_response","Invalid Room binding response.")}return d(t,e)}async restart(e){let n;try{n=await this.fetchImpl(`${this.baseUrl}/api/rooms/${encodeURIComponent(e.roomId)}/bindings/${encodeURIComponent(e.bindingId)}/session`,{method:"PATCH",headers:{authorization:`Bearer ${e.machineToken}`,"content-type":"application/json"},body:JSON.stringify({agentIdentityId:e.agentIdentityId,previousNianSessionId:e.previousNianSessionId,nianSessionId:e.nianSessionId,runtimeAdapter:e.runtimeAdapter,sessionRegistryKey:e.sessionRegistryKey}),signal:AbortSignal.timeout(1e4)})}catch{throw new a("room_binding_server_unavailable","Shennian Room service is unavailable.")}const t=await n.json().catch(()=>null);if(!n.ok){const s=t&&typeof t.error=="string"&&/^[a-z0-9_-]{1,80}$/.test(t.error)?t.error:`room_binding_http_${n.status}`;throw new a(s,"Shennian Room restart request failed.")}const i=t;if(!i?.binding||i.binding.id!==e.bindingId||i.binding.roomId!==e.roomId||i.binding.agentIdentityId!==e.agentIdentityId||i.binding.nianSessionId!==e.nianSessionId||i.binding.runtimeAdapter!==e.runtimeAdapter||typeof i.binding.agentMembershipId!="string"||typeof i.resumeSequence!="string"||!/^(0|[1-9]\d{0,19})$/.test(i.resumeSequence)||typeof i.idempotent!="boolean")throw new a("invalid_room_binding_response","Invalid Room restart response.");return{binding:i.binding,resumeSequence:i.resumeSequence,idempotent:i.idempotent}}}function d(o,e){if(!o||typeof o!="object")throw new a("invalid_room_binding_response","Invalid Room binding response.");const n=o,t=n.binding;if(!t||typeof t.id!="string"||typeof t.agentMembershipId!="string"||t.roomId!==e.roomId||t.agentIdentityId!==e.agentIdentityId||t.nianSessionId!==e.nianSessionId||t.runtimeAdapter!==e.runtimeAdapter||t.activationCapability!==e.activationCapability||!c(t.activationMode,e)||!["pending_approval","active","paused","detached"].includes(t.status??"")||typeof n.idempotent!="boolean")throw new a("invalid_room_binding_response","Room binding response does not match the request.");return{binding:t,idempotent:n.idempotent}}function c(o,e){return e.activationCapability==="managed"&&e.activationMode==="auto_follow"?o==="auto_follow"||o==="mention_only":o===e.activationMode}export{l as HttpRoomBindingClient,a as RoomBindingHttpError};
@@ -1,220 +1 @@
1
- // @arch docs/features/file-management-enhancements.md#文件夹打包下载
2
- // @test src/__tests__/archive-zip.test.ts
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- const DEFAULT_MAX_FILES = 5000;
6
- const DEFAULT_MAX_TOTAL_SIZE = 1024 * 1024 * 1024;
7
- const ZIP_VERSION_NEEDED = 20;
8
- const ZIP_UTF8_FLAG = 0x0800;
9
- const ZIP_STORE_METHOD = 0;
10
- const CHUNK_SIZE = 1024 * 1024;
11
- const crcTable = new Uint32Array(256);
12
- for (let index = 0; index < 256; index += 1) {
13
- let value = index;
14
- for (let bit = 0; bit < 8; bit += 1) {
15
- value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
16
- }
17
- crcTable[index] = value >>> 0;
18
- }
19
- function updateCrc32(crc, buffer) {
20
- let next = crc;
21
- for (let index = 0; index < buffer.length; index += 1) {
22
- next = crcTable[(next ^ buffer[index]) & 0xff] ^ (next >>> 8);
23
- }
24
- return next >>> 0;
25
- }
26
- function dosDateTime(mtimeMs) {
27
- const date = new Date(mtimeMs || Date.now());
28
- const year = Math.max(1980, Math.min(2107, date.getFullYear()));
29
- return {
30
- date: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),
31
- time: (date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2),
32
- };
33
- }
34
- function writeUInt32(buffer, value, offset) {
35
- buffer.writeUInt32LE(value >>> 0, offset);
36
- }
37
- function writeLocalHeader(fd, entry) {
38
- const name = Buffer.from(entry.name, 'utf8');
39
- const { date, time } = dosDateTime(entry.mtimeMs);
40
- const header = Buffer.alloc(30);
41
- writeUInt32(header, 0x04034b50, 0);
42
- header.writeUInt16LE(ZIP_VERSION_NEEDED, 4);
43
- header.writeUInt16LE(ZIP_UTF8_FLAG, 6);
44
- header.writeUInt16LE(ZIP_STORE_METHOD, 8);
45
- header.writeUInt16LE(time, 10);
46
- header.writeUInt16LE(date, 12);
47
- writeUInt32(header, entry.crc32, 14);
48
- writeUInt32(header, entry.size, 18);
49
- writeUInt32(header, entry.size, 22);
50
- header.writeUInt16LE(name.length, 26);
51
- header.writeUInt16LE(0, 28);
52
- fs.writeSync(fd, header);
53
- fs.writeSync(fd, name);
54
- }
55
- function writeCentralDirectoryHeader(fd, entry) {
56
- const name = Buffer.from(entry.name, 'utf8');
57
- const { date, time } = dosDateTime(entry.mtimeMs);
58
- const header = Buffer.alloc(46);
59
- writeUInt32(header, 0x02014b50, 0);
60
- header.writeUInt16LE(0x031e, 4);
61
- header.writeUInt16LE(ZIP_VERSION_NEEDED, 6);
62
- header.writeUInt16LE(ZIP_UTF8_FLAG, 8);
63
- header.writeUInt16LE(ZIP_STORE_METHOD, 10);
64
- header.writeUInt16LE(time, 12);
65
- header.writeUInt16LE(date, 14);
66
- writeUInt32(header, entry.crc32, 16);
67
- writeUInt32(header, entry.size, 20);
68
- writeUInt32(header, entry.size, 24);
69
- header.writeUInt16LE(name.length, 28);
70
- header.writeUInt16LE(0, 30);
71
- header.writeUInt16LE(0, 32);
72
- header.writeUInt16LE(0, 34);
73
- header.writeUInt16LE(0, 36);
74
- writeUInt32(header, entry.isDir ? 0x10 : 0, 38);
75
- writeUInt32(header, entry.offset, 42);
76
- fs.writeSync(fd, header);
77
- fs.writeSync(fd, name);
78
- }
79
- function writeEndOfCentralDirectory(fd, entryCount, centralSize, centralOffset) {
80
- const header = Buffer.alloc(22);
81
- writeUInt32(header, 0x06054b50, 0);
82
- header.writeUInt16LE(0, 4);
83
- header.writeUInt16LE(0, 6);
84
- header.writeUInt16LE(entryCount, 8);
85
- header.writeUInt16LE(entryCount, 10);
86
- writeUInt32(header, centralSize, 12);
87
- writeUInt32(header, centralOffset, 16);
88
- header.writeUInt16LE(0, 20);
89
- fs.writeSync(fd, header);
90
- }
91
- function normalizeZipName(relativePath, isDir) {
92
- const normalized = relativePath.split(path.sep).join('/');
93
- return isDir && !normalized.endsWith('/') ? `${normalized}/` : normalized;
94
- }
95
- function collectEntries(sourceDir, options) {
96
- const sourceStat = fs.statSync(sourceDir);
97
- const rootName = normalizeZipName(path.basename(sourceDir) || 'folder', true);
98
- const entries = [{
99
- name: rootName,
100
- sourcePath: null,
101
- crc32: 0,
102
- size: 0,
103
- isDir: true,
104
- mtimeMs: sourceStat.mtimeMs,
105
- }];
106
- let fileCount = 0;
107
- let totalSize = 0;
108
- const visit = (dirPath) => {
109
- const raw = fs.readdirSync(dirPath, { withFileTypes: true });
110
- for (const dirent of raw) {
111
- const fullPath = path.join(dirPath, dirent.name);
112
- const relative = path.relative(sourceDir, fullPath);
113
- if (!relative || relative.startsWith('..') || path.isAbsolute(relative))
114
- continue;
115
- const stat = fs.lstatSync(fullPath);
116
- if (stat.isSymbolicLink())
117
- continue;
118
- if (stat.isDirectory()) {
119
- entries.push({
120
- name: path.posix.join(rootName, normalizeZipName(relative, true)),
121
- sourcePath: null,
122
- crc32: 0,
123
- size: 0,
124
- isDir: true,
125
- mtimeMs: stat.mtimeMs,
126
- });
127
- visit(fullPath);
128
- continue;
129
- }
130
- if (!stat.isFile())
131
- continue;
132
- fileCount += 1;
133
- if (fileCount > options.maxFiles)
134
- throw new Error(`Too many files: ${fileCount}`);
135
- totalSize += stat.size;
136
- if (totalSize > options.maxTotalSize) {
137
- throw new Error(`Folder too large: ${totalSize} bytes`);
138
- }
139
- entries.push({
140
- name: path.posix.join(rootName, normalizeZipName(relative, false)),
141
- sourcePath: fullPath,
142
- crc32: computeFileCrc32(fullPath),
143
- size: stat.size,
144
- isDir: false,
145
- mtimeMs: stat.mtimeMs,
146
- });
147
- }
148
- };
149
- visit(sourceDir);
150
- return entries;
151
- }
152
- function computeFileCrc32(filePath) {
153
- const fd = fs.openSync(filePath, 'r');
154
- const buffer = Buffer.alloc(CHUNK_SIZE);
155
- let crc = 0xffffffff;
156
- try {
157
- while (true) {
158
- const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, null);
159
- if (bytesRead <= 0)
160
- break;
161
- crc = updateCrc32(crc, buffer.subarray(0, bytesRead));
162
- }
163
- }
164
- finally {
165
- fs.closeSync(fd);
166
- }
167
- return (crc ^ 0xffffffff) >>> 0;
168
- }
169
- function writeFileData(fd, filePath) {
170
- const sourceFd = fs.openSync(filePath, 'r');
171
- const buffer = Buffer.alloc(CHUNK_SIZE);
172
- try {
173
- while (true) {
174
- const bytesRead = fs.readSync(sourceFd, buffer, 0, buffer.length, null);
175
- if (bytesRead <= 0)
176
- break;
177
- fs.writeSync(fd, buffer.subarray(0, bytesRead));
178
- }
179
- }
180
- finally {
181
- fs.closeSync(sourceFd);
182
- }
183
- }
184
- export function createZipArchive(sourceDir, outputPath, options = {}) {
185
- const sourceStat = fs.statSync(sourceDir);
186
- if (!sourceStat.isDirectory())
187
- throw new Error('Not a directory');
188
- const limits = {
189
- maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,
190
- maxTotalSize: options.maxTotalSize ?? DEFAULT_MAX_TOTAL_SIZE,
191
- };
192
- const scanned = collectEntries(sourceDir, limits);
193
- const zipEntries = [];
194
- let fileCount = 0;
195
- let totalSize = 0;
196
- fs.mkdirSync(path.dirname(outputPath), { recursive: true });
197
- const fd = fs.openSync(outputPath, 'w');
198
- try {
199
- for (const entry of scanned) {
200
- const offset = fs.fstatSync(fd).size;
201
- const nextEntry = { ...entry, offset };
202
- writeLocalHeader(fd, nextEntry);
203
- if (nextEntry.sourcePath) {
204
- writeFileData(fd, nextEntry.sourcePath);
205
- fileCount += 1;
206
- totalSize += nextEntry.size;
207
- }
208
- zipEntries.push(nextEntry);
209
- }
210
- const centralOffset = fs.fstatSync(fd).size;
211
- for (const entry of zipEntries)
212
- writeCentralDirectoryHeader(fd, entry);
213
- const centralSize = fs.fstatSync(fd).size - centralOffset;
214
- writeEndOfCentralDirectory(fd, zipEntries.length, centralSize, centralOffset);
215
- }
216
- finally {
217
- fs.closeSync(fd);
218
- }
219
- return { outputPath, fileCount, totalSize };
220
- }
1
+ import c from"node:fs";import u from"node:path";const p=5e3,M=1024*1024*1024,L=20,U=2048,h=0,x=1024*1024,z=new Uint32Array(256);for(let i=0;i<256;i+=1){let t=i;for(let n=0;n<8;n+=1)t=t&1?3988292384^t>>>1:t>>>1;z[i]=t>>>0}function F(i,t){let n=i;for(let o=0;o<t.length;o+=1)n=z[(n^t[o])&255]^n>>>8;return n>>>0}function b(i){const t=new Date(i||Date.now());return{date:Math.max(1980,Math.min(2107,t.getFullYear()))-1980<<9|t.getMonth()+1<<5|t.getDate(),time:t.getHours()<<11|t.getMinutes()<<5|Math.floor(t.getSeconds()/2)}}function s(i,t,n){i.writeUInt32LE(t>>>0,n)}function D(i,t){const n=Buffer.from(t.name,"utf8"),{date:o,time:r}=b(t.mtimeMs),e=Buffer.alloc(30);s(e,67324752,0),e.writeUInt16LE(L,4),e.writeUInt16LE(U,6),e.writeUInt16LE(h,8),e.writeUInt16LE(r,10),e.writeUInt16LE(o,12),s(e,t.crc32,14),s(e,t.size,18),s(e,t.size,22),e.writeUInt16LE(n.length,26),e.writeUInt16LE(0,28),c.writeSync(i,e),c.writeSync(i,n)}function T(i,t){const n=Buffer.from(t.name,"utf8"),{date:o,time:r}=b(t.mtimeMs),e=Buffer.alloc(46);s(e,33639248,0),e.writeUInt16LE(798,4),e.writeUInt16LE(L,6),e.writeUInt16LE(U,8),e.writeUInt16LE(h,10),e.writeUInt16LE(r,12),e.writeUInt16LE(o,14),s(e,t.crc32,16),s(e,t.size,20),s(e,t.size,24),e.writeUInt16LE(n.length,28),e.writeUInt16LE(0,30),e.writeUInt16LE(0,32),e.writeUInt16LE(0,34),e.writeUInt16LE(0,36),s(e,t.isDir?16:0,38),s(e,t.offset,42),c.writeSync(i,e),c.writeSync(i,n)}function g(i,t,n,o){const r=Buffer.alloc(22);s(r,101010256,0),r.writeUInt16LE(0,4),r.writeUInt16LE(0,6),r.writeUInt16LE(t,8),r.writeUInt16LE(t,10),s(r,n,12),s(r,o,16),r.writeUInt16LE(0,20),c.writeSync(i,r)}function d(i,t){const n=i.split(u.sep).join("/");return t&&!n.endsWith("/")?`${n}/`:n}function _(i,t){const n=c.statSync(i),o=d(u.basename(i)||"folder",!0),r=[{name:o,sourcePath:null,crc32:0,size:0,isDir:!0,mtimeMs:n.mtimeMs}];let e=0,m=0;const E=S=>{const a=c.readdirSync(S,{withFileTypes:!0});for(const I of a){const w=u.join(S,I.name),f=u.relative(i,w);if(!f||f.startsWith("..")||u.isAbsolute(f))continue;const l=c.lstatSync(w);if(!l.isSymbolicLink()){if(l.isDirectory()){r.push({name:u.posix.join(o,d(f,!0)),sourcePath:null,crc32:0,size:0,isDir:!0,mtimeMs:l.mtimeMs}),E(w);continue}if(l.isFile()){if(e+=1,e>t.maxFiles)throw new Error(`Too many files: ${e}`);if(m+=l.size,m>t.maxTotalSize)throw new Error(`Folder too large: ${m} bytes`);r.push({name:u.posix.join(o,d(f,!1)),sourcePath:w,crc32:A(w),size:l.size,isDir:!1,mtimeMs:l.mtimeMs})}}}};return E(i),r}function A(i){const t=c.openSync(i,"r"),n=Buffer.alloc(x);let o=4294967295;try{for(;;){const r=c.readSync(t,n,0,n.length,null);if(r<=0)break;o=F(o,n.subarray(0,r))}}finally{c.closeSync(t)}return(o^4294967295)>>>0}function B(i,t){const n=c.openSync(t,"r"),o=Buffer.alloc(x);try{for(;;){const r=c.readSync(n,o,0,o.length,null);if(r<=0)break;c.writeSync(i,o.subarray(0,r))}}finally{c.closeSync(n)}}function C(i,t,n={}){if(!c.statSync(i).isDirectory())throw new Error("Not a directory");const r={maxFiles:n.maxFiles??p,maxTotalSize:n.maxTotalSize??M},e=_(i,r),m=[];let E=0,S=0;c.mkdirSync(u.dirname(t),{recursive:!0});const a=c.openSync(t,"w");try{for(const f of e){const l=c.fstatSync(a).size,y={...f,offset:l};D(a,y),y.sourcePath&&(B(a,y.sourcePath),E+=1,S+=y.size),m.push(y)}const I=c.fstatSync(a).size;for(const f of m)T(a,f);const w=c.fstatSync(a).size-I;g(a,m.length,w,I)}finally{c.closeSync(a)}return{outputPath:t,fileCount:E,totalSize:S}}export{C as createZipArchive};
@@ -1,136 +1,2 @@
1
- // @arch docs/architecture/data-sync.md#删除闭环
2
- // @test src/__tests__/session-deletion-sync.test.ts
3
- import crypto from 'node:crypto';
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
- import { resolvePersonalSyncV1Path } from '../personal-sync/paths.js';
7
- import { getDaemonInstallationId } from '../personal-sync/identity.js';
8
- import { recordPersonalSyncLocalMetric } from '../personal-sync/metrics.js';
9
- export class DeletionSyncTerminalError extends Error {
10
- code;
11
- retryable = false;
12
- constructor(code) {
13
- super(`session deletion sync stopped: ${code}`);
14
- this.code = code;
15
- this.name = 'DeletionSyncTerminalError';
16
- }
17
- }
18
- export class DeletionSyncRetryWaitError extends Error {
19
- retryAfterMs;
20
- retryable = true;
21
- constructor(retryAfterMs) {
22
- super(`session deletion sync retry delayed by ${retryAfterMs}ms`);
23
- this.retryAfterMs = retryAfterMs;
24
- this.name = 'DeletionSyncRetryWaitError';
25
- }
26
- }
27
- export function readDeletionSyncRevision() {
28
- return readState().lastAppliedRevision;
29
- }
30
- function readState() {
31
- const file = stateFile();
32
- if (!fs.existsSync(file))
33
- return {
34
- schemaVersion: 1,
35
- daemonInstallationId: getDaemonInstallationId(),
36
- lastAppliedRevision: 0,
37
- updatedAt: new Date(0).toISOString(),
38
- };
39
- const state = JSON.parse(fs.readFileSync(file, 'utf8'));
40
- if (state.schemaVersion !== 1
41
- || state.daemonInstallationId !== getDaemonInstallationId()
42
- || !Number.isSafeInteger(state.lastAppliedRevision)
43
- || state.lastAppliedRevision < 0)
44
- throw new Error('invalid deletion sync state');
45
- return state;
46
- }
47
- export function writeDeletionSyncRevision(revision) {
48
- if (!Number.isSafeInteger(revision) || revision < 0)
49
- throw new Error('invalid deletion sync revision');
50
- const current = readDeletionSyncRevision();
51
- if (revision < current)
52
- throw new Error('deletion sync revision cannot move backwards');
53
- if (revision === current)
54
- return;
55
- atomicWriteJson(stateFile(), {
56
- ...readState(),
57
- lastAppliedRevision: revision,
58
- updatedAt: new Date().toISOString(),
59
- });
60
- }
61
- export function assertDeletionSyncRunnable(now = Date.now()) {
62
- const state = readState();
63
- if (state.terminalCode)
64
- throw new DeletionSyncTerminalError(state.terminalCode);
65
- if (state.nextAttemptAt) {
66
- const remaining = Date.parse(state.nextAttemptAt) - now;
67
- if (remaining > 0)
68
- throw new DeletionSyncRetryWaitError(remaining);
69
- }
70
- }
71
- export function recordDeletionSyncFailure(input) {
72
- const state = readState();
73
- const attempts = (state.retryAttempts ?? 0) + 1;
74
- const now = input.now ?? Date.now();
75
- if (!input.retryable || attempts >= (input.maxAttempts ?? 8)) {
76
- atomicWriteJson(stateFile(), {
77
- ...state, retryAttempts: attempts, nextAttemptAt: null,
78
- terminalCode: input.code, updatedAt: new Date(now).toISOString(),
79
- });
80
- recordPersonalSyncLocalMetric('permanentStops');
81
- throw new DeletionSyncTerminalError(input.code);
82
- }
83
- const delay = Math.min(5_000 * 2 ** Math.max(0, attempts - 1), 6 * 60 * 60 * 1_000);
84
- const jitter = Math.round(delay * 0.2 * (Math.random() * 2 - 1));
85
- const retryAfterMs = delay + jitter;
86
- atomicWriteJson(stateFile(), {
87
- ...state, retryAttempts: attempts, terminalCode: null,
88
- nextAttemptAt: new Date(now + retryAfterMs).toISOString(),
89
- updatedAt: new Date(now).toISOString(),
90
- });
91
- recordPersonalSyncLocalMetric('transientRetries');
92
- throw new DeletionSyncRetryWaitError(retryAfterMs);
93
- }
94
- export function clearDeletionSyncFailure() {
95
- const state = readState();
96
- if (!state.retryAttempts && !state.nextAttemptAt && !state.terminalCode)
97
- return;
98
- atomicWriteJson(stateFile(), {
99
- ...state, retryAttempts: 0, nextAttemptAt: null, terminalCode: null,
100
- updatedAt: new Date().toISOString(),
101
- });
102
- }
103
- function stateFile() {
104
- return resolvePersonalSyncV1Path('deletion-sync-state.json');
105
- }
106
- function atomicWriteJson(file, value) {
107
- const directory = path.dirname(file);
108
- fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
109
- const temp = `${file}.tmp-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
110
- let fd;
111
- try {
112
- fd = fs.openSync(temp, 'wx', 0o600);
113
- fs.writeFileSync(fd, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
114
- fs.fsyncSync(fd);
115
- fs.closeSync(fd);
116
- fd = undefined;
117
- fs.renameSync(temp, file);
118
- if (process.platform !== 'win32') {
119
- const directoryFd = fs.openSync(directory, 'r');
120
- try {
121
- fs.fsyncSync(directoryFd);
122
- }
123
- finally {
124
- fs.closeSync(directoryFd);
125
- }
126
- }
127
- }
128
- finally {
129
- if (fd !== undefined)
130
- fs.closeSync(fd);
131
- try {
132
- fs.unlinkSync(temp);
133
- }
134
- catch { }
135
- }
136
- }
1
+ import f from"node:crypto";import n from"node:fs";import u from"node:path";import{resolvePersonalSyncV1Path as A}from"../personal-sync/paths.js";import{getDaemonInstallationId as m}from"../personal-sync/identity.js";import{recordPersonalSyncLocalMetric as y}from"../personal-sync/metrics.js";class p extends Error{code;retryable=!1;constructor(e){super(`session deletion sync stopped: ${e}`),this.code=e,this.name="DeletionSyncTerminalError"}}class S extends Error{retryAfterMs;retryable=!0;constructor(e){super(`session deletion sync retry delayed by ${e}ms`),this.retryAfterMs=e,this.name="DeletionSyncRetryWaitError"}}function w(){return s().lastAppliedRevision}function s(){const t=a();if(!n.existsSync(t))return{schemaVersion:1,daemonInstallationId:m(),lastAppliedRevision:0,updatedAt:new Date(0).toISOString()};const e=JSON.parse(n.readFileSync(t,"utf8"));if(e.schemaVersion!==1||e.daemonInstallationId!==m()||!Number.isSafeInteger(e.lastAppliedRevision)||e.lastAppliedRevision<0)throw new Error("invalid deletion sync state");return e}function v(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("invalid deletion sync revision");const e=w();if(t<e)throw new Error("deletion sync revision cannot move backwards");t!==e&&l(a(),{...s(),lastAppliedRevision:t,updatedAt:new Date().toISOString()})}function E(t=Date.now()){const e=s();if(e.terminalCode)throw new p(e.terminalCode);if(e.nextAttemptAt){const r=Date.parse(e.nextAttemptAt)-t;if(r>0)throw new S(r)}}function b(t){const e=s(),r=(e.retryAttempts??0)+1,i=t.now??Date.now();if(!t.retryable||r>=(t.maxAttempts??8))throw l(a(),{...e,retryAttempts:r,nextAttemptAt:null,terminalCode:t.code,updatedAt:new Date(i).toISOString()}),y("permanentStops"),new p(t.code);const o=Math.min(5e3*2**Math.max(0,r-1),360*60*1e3),c=Math.round(o*.2*(Math.random()*2-1)),d=o+c;throw l(a(),{...e,retryAttempts:r,terminalCode:null,nextAttemptAt:new Date(i+d).toISOString(),updatedAt:new Date(i).toISOString()}),y("transientRetries"),new S(d)}function O(){const t=s();!t.retryAttempts&&!t.nextAttemptAt&&!t.terminalCode||l(a(),{...t,retryAttempts:0,nextAttemptAt:null,terminalCode:null,updatedAt:new Date().toISOString()})}function a(){return A("deletion-sync-state.json")}function l(t,e){const r=u.dirname(t);n.mkdirSync(r,{recursive:!0,mode:448});const i=`${t}.tmp-${process.pid}-${f.randomBytes(6).toString("hex")}`;let o;try{if(o=n.openSync(i,"wx",384),n.writeFileSync(o,`${JSON.stringify(e,null,2)}
2
+ `,"utf8"),n.fsyncSync(o),n.closeSync(o),o=void 0,n.renameSync(i,t),process.platform!=="win32"){const c=n.openSync(r,"r");try{n.fsyncSync(c)}finally{n.closeSync(c)}}}finally{o!==void 0&&n.closeSync(o);try{n.unlinkSync(i)}catch{}}}export{S as DeletionSyncRetryWaitError,p as DeletionSyncTerminalError,E as assertDeletionSyncRunnable,O as clearDeletionSyncFailure,w as readDeletionSyncRevision,b as recordDeletionSyncFailure,v as writeDeletionSyncRevision};
@@ -1,14 +1 @@
1
- // @arch docs/features/agent-native-capabilities.md
2
- // @test src/__tests__/native-capabilities.test.ts
3
- import { isNativeCapabilityProvider, listAgentNativeCapabilities } from '../../agents/native-capabilities.js';
4
- export async function handleAgentCapabilitiesList(runtime, req) {
5
- const agentType = typeof req.params.agentType === 'string' ? req.params.agentType : '';
6
- const workDir = typeof req.params.workDir === 'string' ? req.params.workDir : process.cwd();
7
- const supported = isNativeCapabilityProvider(agentType);
8
- const payload = {
9
- supported,
10
- agentType,
11
- capabilities: supported ? listAgentNativeCapabilities({ agentType, workDir }) : [],
12
- };
13
- runtime.client.sendRes({ type: 'res', id: req.id, ok: true, payload });
14
- }
1
+ import{isNativeCapabilityProvider as o,listAgentNativeCapabilities as n}from"../../agents/native-capabilities.js";async function c(s,t){const i=typeof t.params.agentType=="string"?t.params.agentType:"",e=typeof t.params.workDir=="string"?t.params.workDir:process.cwd(),a=o(i),p={supported:a,agentType:i,capabilities:a?n({agentType:i,workDir:e}):[]};s.client.sendRes({type:"res",id:t.id,ok:!0,payload:p})}export{c as handleAgentCapabilitiesList};