@tano.page/protocol 0.14.0 → 0.16.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 (39) hide show
  1. package/manifest.schema.json +448 -0
  2. package/package.json +21 -4
  3. package/src/appearance.ts +19 -4
  4. package/src/assistant.ts +35 -4
  5. package/src/domain/agent-identities.ts +110 -0
  6. package/src/domain/agent-inbox.ts +148 -0
  7. package/src/domain/assistant-completion.ts +61 -0
  8. package/src/domain/assistant-engine.ts +614 -0
  9. package/src/domain/assistant-execution.ts +43 -0
  10. package/src/domain/assistant-files.ts +19 -0
  11. package/src/domain/assistant-history.ts +90 -0
  12. package/src/domain/assistant-language.ts +112 -0
  13. package/src/domain/assistant-prompts.ts +70 -0
  14. package/src/domain/assistant-structures.ts +179 -0
  15. package/src/domain/assistant-task-prompts.json +39 -0
  16. package/src/domain/assistant-tasks.ts +114 -0
  17. package/src/domain/locales/de-DE.json +129 -0
  18. package/src/domain/locales/en-US.json +129 -0
  19. package/src/domain/locales/es-ES.json +129 -0
  20. package/src/domain/locales/ja-JP.json +129 -0
  21. package/src/domain/locales/zh-CN.json +129 -0
  22. package/src/domain/locales/zh-TW.json +129 -0
  23. package/src/domain/plugin-data.ts +175 -0
  24. package/src/domain/plugin-sdk.ts +300 -0
  25. package/src/domain/untrusted-data.ts +17 -0
  26. package/src/domain/workspace-comments.ts +148 -0
  27. package/src/extensions.ts +1100 -19
  28. package/src/frontmatter.ts +60 -1
  29. package/src/index.ts +3 -0
  30. package/src/object-types.ts +30 -20
  31. package/src/objects.ts +3 -4
  32. package/src/plan-item.ts +78 -0
  33. package/src/plugin-archive.ts +395 -0
  34. package/src/plugin-compat.ts +156 -0
  35. package/src/plugins.ts +12 -0
  36. package/src/relations.ts +1 -5
  37. package/src/task-repeat.ts +55 -8
  38. package/src/task-review.ts +11 -2
  39. package/src/view-engine.ts +1 -1
@@ -0,0 +1,110 @@
1
+ import type { AssistantTransport } from '../assistant';
2
+ import { isAgentPerson, type AgentBinding } from '../mentions';
3
+ import { parseObject } from '../objects';
4
+ import type { WorkspaceAdapter } from '../types';
5
+ import { objectDirectory } from '../workspace-paths';
6
+ import { AgentTaskQueue } from './agent-inbox';
7
+
8
+ /** Reserve the binding before creating its portable identity, allowing crash-safe repair. */
9
+ export async function ensureAgentIdentities(
10
+ workspaceId: string,
11
+ adapter: Pick<WorkspaceAdapter, 'refresh' | 'read' | 'write' | 'create' | 'reserveObjectId'>,
12
+ transport: Pick<AssistantTransport, 'inbox' | 'connections' | 'models' | 'hostedInbox'>,
13
+ signal?: AbortSignal,
14
+ ) {
15
+ const errors: string[] = [];
16
+ if (!transport.inbox || !adapter.reserveObjectId) return errors;
17
+ const queue = new AgentTaskQueue(transport.inbox);
18
+ const connections = await transport.connections();
19
+ for (const connection of connections) {
20
+ if (connection.platformProvider && transport.hostedInbox) continue;
21
+ try {
22
+ signal?.throwIfAborted();
23
+ const inbox = await transport.inbox.load(workspaceId);
24
+ let binding = inbox.bindings.find((item) => item.connectionId === connection.id);
25
+ if (!binding) {
26
+ let models: string[] = [];
27
+ try {
28
+ models = await transport.models(
29
+ connection.id,
30
+ signal ? AbortSignal.any([signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(30_000),
31
+ );
32
+ } catch (reason) {
33
+ errors.push(`${connection.name} · ${String(reason)}`);
34
+ }
35
+ signal?.throwIfAborted();
36
+ const workspace = await adapter.refresh();
37
+ if (workspace.id !== workspaceId || workspace.readOnly) return errors;
38
+ const personId = await adapter.reserveObjectId(inbox.bindings.map((item) => item.personId));
39
+ const candidate: AgentBinding = {
40
+ personId,
41
+ connectionId: connection.id,
42
+ model: models[0] ?? '',
43
+ enabled: true,
44
+ };
45
+ binding = await queue.update(workspaceId, (current) => {
46
+ const existing = current.bindings.find((item) => item.connectionId === connection.id);
47
+ if (existing) return { ...existing };
48
+ current.bindings.push(candidate);
49
+ return candidate;
50
+ });
51
+ }
52
+ const workspace = await adapter.refresh();
53
+ signal?.throwIfAborted();
54
+ if (workspace.id !== workspaceId || workspace.readOnly) return errors;
55
+ const path = `${objectDirectory}/${binding.personId}.tano.json`;
56
+ if (workspace.files.some((file) => file.path === path)) {
57
+ const object = parseObject((await adapter.read(path)).content);
58
+ if (object.id !== binding.personId || !isAgentPerson(object))
59
+ throw new Error('机器人身份与已有对象冲突');
60
+ if (!binding.provisioned) {
61
+ await queue.update(workspaceId, current => {
62
+ const saved = current.bindings.find(item => item.personId === binding!.personId);
63
+ if (saved) saved.provisioned = true;
64
+ });
65
+ }
66
+ continue;
67
+ }
68
+ if (binding.provisioned) {
69
+ await queue.update(workspaceId, current => {
70
+ const saved = current.bindings.find(item => item.personId === binding!.personId);
71
+ if (saved) saved.enabled = false;
72
+ });
73
+ errors.push(`${connection.name} · 机器人身份文件已移除,请从文件历史恢复后重新启用`);
74
+ continue;
75
+ }
76
+ const object = {
77
+ version: 1,
78
+ id: binding.personId,
79
+ type: 'person',
80
+ name: connection.name,
81
+ description: '',
82
+ archived: false,
83
+ properties: { memberKind: 'agent' },
84
+ };
85
+ try {
86
+ await adapter.create(path, JSON.stringify(object, null, 2) + '\n');
87
+ } catch (error) {
88
+ const current = await adapter.refresh();
89
+ if (!current.files.some((file) => file.path === path)) throw error;
90
+ const saved = parseObject((await adapter.read(path)).content);
91
+ if (saved.id !== binding.personId || !isAgentPerson(saved)) throw error;
92
+ }
93
+ await queue.update(workspaceId, current => {
94
+ const saved = current.bindings.find(item => item.personId === binding!.personId);
95
+ if (saved) saved.provisioned = true;
96
+ });
97
+ } catch (reason) {
98
+ errors.push(`${connection.name} · ${String(reason)}`);
99
+ }
100
+ }
101
+ await queue.update(workspaceId, (inbox) => {
102
+ for (const binding of inbox.bindings) {
103
+ if (!connections.some((connection) => connection.id === binding.connectionId) ||
104
+ (transport.hostedInbox && connections.some(connection => connection.id === binding.connectionId && connection.platformProvider))) {
105
+ binding.enabled = false;
106
+ }
107
+ }
108
+ });
109
+ return errors;
110
+ }
@@ -0,0 +1,148 @@
1
+ import { isAssistantModelId } from '../assistant';
2
+ import type { AgentInbox, AgentInboxStorage, AgentTask, MentionEvent, MentionSource } from '../mentions';
3
+
4
+ /** All transitions use the host's CAS, including claims from another window/device. */
5
+ export class AgentTaskQueue {
6
+ constructor(private readonly storage: AgentInboxStorage, private readonly now = Date.now) {}
7
+
8
+ async update<T>(workspaceId: string, change: (inbox: AgentInbox) => T): Promise<T> {
9
+ for (let attempt = 0; attempt < 12; attempt++) {
10
+ const current = await this.storage.load(workspaceId);
11
+ const next = structuredClone(current);
12
+ const result = change(next);
13
+ if (JSON.stringify(current) === JSON.stringify(next)) return result;
14
+ next.revision = current.revision + 1;
15
+ if (await this.storage.compareExchange(next, current.revision)) return result;
16
+ }
17
+ throw new Error('机器人收件箱正在其他窗口更新,请稍后重试');
18
+ }
19
+
20
+ /** Supply a complete, committed snapshot of this source, including an empty deleted source. */
21
+ async reconcile(workspaceId: string, source: Pick<MentionSource, 'kind' | 'fileId'>, events: MentionEvent[],
22
+ accept: (event: MentionEvent) => boolean = () => true) {
23
+ if (events.some(event => event.workspaceId !== workspaceId || event.source.fileId !== source.fileId || event.source.kind !== source.kind) ||
24
+ new Set(events.map(event => event.id)).size !== events.length) throw new Error('提及事件来源无效');
25
+ await this.update(workspaceId, inbox => {
26
+ const now = this.now();
27
+ for (const event of events) {
28
+ if (!accept(event)) continue;
29
+ const binding = inbox.bindings.find(item => item.personId === event.personId);
30
+ if (!binding) continue;
31
+ const task = inbox.tasks.find(item => item.event.id === event.id && item.event.personId === event.personId);
32
+ if (task) {
33
+ if (task.status === 'queued' && !task.continuation && task.event.revision !== event.revision) {
34
+ task.event = structuredClone(event);
35
+ task.updatedAt = now;
36
+ if (event.source.kind === 'document') task.readyAt = now + 2000;
37
+ }
38
+ continue;
39
+ }
40
+ inbox.tasks.push({ id: crypto.randomUUID(), event: structuredClone(event), binding: { ...binding },
41
+ status: 'queued', sessionId: crypto.randomUUID(), createdAt: now, updatedAt: now, attempts: 0,
42
+ ...(event.source.kind === 'document' ? { readyAt: now + 2000 } : {}) });
43
+ }
44
+ for (const task of inbox.tasks) {
45
+ if (task.event.source.kind !== source.kind || task.event.source.fileId !== source.fileId ||
46
+ !['queued', 'running', 'waiting'].includes(task.status)) continue;
47
+ if (!events.some(event => event.id === task.event.id && event.personId === task.event.personId)) {
48
+ task.status = 'cancelled'; task.updatedAt = now;
49
+ task.error = '原提及已移除'; delete task.claim;
50
+ }
51
+ }
52
+ });
53
+ }
54
+
55
+ async claim(workspaceId: string, owner: string, leaseMs = 60_000): Promise<AgentTask | undefined> {
56
+ if (!owner || !Number.isFinite(leaseMs) || leaseMs < 1000) throw new Error('任务租约无效');
57
+ return this.update(workspaceId, inbox => {
58
+ const now = this.now();
59
+ for (const task of inbox.tasks) {
60
+ if (task.status === 'running' && (!task.claim || task.claim.until <= now)) {
61
+ task.status = 'uncertain'; task.error = '执行进程中断,请核对操作回执';
62
+ task.updatedAt = now; delete task.claim;
63
+ }
64
+ }
65
+ const busy = new Set(inbox.tasks.filter(task => task.status === 'running').map(task => task.binding.personId));
66
+ const firstQueued = new Map<string, AgentTask>();
67
+ for (const item of inbox.tasks) if (item.status === 'queued' && !firstQueued.has(item.binding.personId)) firstQueued.set(item.binding.personId, item);
68
+ const task = [...firstQueued.values()].find(item => (item.readyAt ?? 0) <= now && isAssistantModelId(item.binding.model) && !busy.has(item.binding.personId) &&
69
+ inbox.bindings.some(binding => binding.personId === item.binding.personId && binding.enabled && binding.connectionId === item.binding.connectionId));
70
+ if (!task) return;
71
+ task.status = 'running'; task.attempts++; task.updatedAt = now;
72
+ task.claim = { owner, token: crypto.randomUUID(), until: now + leaseMs };
73
+ return structuredClone(task);
74
+ });
75
+ }
76
+
77
+ async renew(workspaceId: string, taskId: string, token: string, leaseMs = 60_000) {
78
+ if (!Number.isFinite(leaseMs) || leaseMs < 1000) throw new Error('任务租约无效');
79
+ await this.update(workspaceId, inbox => {
80
+ const task = this.owned(inbox, taskId, token);
81
+ task.claim!.until = this.now() + leaseMs;
82
+ });
83
+ }
84
+
85
+ async recordResult(workspaceId: string, taskId: string, token: string, body: string,
86
+ outcome: 'succeeded' | 'waiting' | 'uncertain' = 'succeeded') {
87
+ if (!body.trim() || body.length > 20_000) throw new Error('机器人回复长度无效');
88
+ return this.update(workspaceId, inbox => {
89
+ const task = this.owned(inbox, taskId, token);
90
+ task.result ??= { messageId: crypto.randomUUID(), body, outcome };
91
+ task.updatedAt = this.now();
92
+ return { ...task.result };
93
+ });
94
+ }
95
+
96
+ async settle(workspaceId: string, taskId: string, token: string,
97
+ status: 'succeeded' | 'failed' | 'waiting' | 'uncertain', error?: string) {
98
+ await this.update(workspaceId, inbox => {
99
+ const task = this.owned(inbox, taskId, token);
100
+ if (status === 'succeeded' && !task.result) throw new Error('任务尚未记录回复');
101
+ task.status = status; task.error = error; task.updatedAt = this.now(); delete task.claim;
102
+ });
103
+ }
104
+
105
+ async cancel(workspaceId: string, taskId: string) {
106
+ await this.update(workspaceId, inbox => {
107
+ const task = inbox.tasks.find(item => item.id === taskId);
108
+ if (!task || !['queued', 'running', 'waiting'].includes(task.status)) return;
109
+ task.status = 'cancelled'; task.updatedAt = this.now(); delete task.claim;
110
+ });
111
+ }
112
+
113
+ async resume(workspaceId: string, taskId: string, reply: NonNullable<AgentTask['continuation']>, questionId: string) {
114
+ await this.update(workspaceId, inbox => {
115
+ const task = inbox.tasks.find(item => item.id === taskId);
116
+ if (!task || task.status !== 'waiting' || task.result?.messageId !== questionId) return;
117
+ task.continuation = { ...reply };
118
+ task.status = 'queued'; task.updatedAt = this.now();
119
+ delete task.result; delete task.error;
120
+ });
121
+ }
122
+
123
+ async retry(workspaceId: string, taskId: string, updatedAt: number) {
124
+ await this.update(workspaceId, inbox => {
125
+ const task = inbox.tasks.find(task => task.id === taskId);
126
+ if (!task || task.updatedAt !== updatedAt || !(task.status === 'failed' || task.status === 'uncertain' && task.result))
127
+ throw new Error('任务已变化或执行结果待核对,请先查看执行记录');
128
+ task.status = 'queued'; task.updatedAt = this.now(); delete task.error;
129
+ });
130
+ }
131
+
132
+ /** Only the runner may release a claim before entering its persisted execution path. */
133
+ async releaseUnstarted(workspaceId: string, taskId: string, token: string) {
134
+ await this.update(workspaceId, inbox => {
135
+ const task = this.owned(inbox, taskId, token);
136
+ task.status = 'queued'; task.updatedAt = this.now(); delete task.claim;
137
+ });
138
+ }
139
+
140
+ private owned(inbox: AgentInbox, taskId: string, token: string): AgentTask {
141
+ const task = inbox.tasks.find(item => item.id === taskId);
142
+ if (!task || task.status !== 'running' || task.claim?.token !== token || task.claim.until <= this.now())
143
+ throw new Error('任务执行权已失效');
144
+ if (!inbox.bindings.some(binding => binding.personId === task.binding.personId && binding.enabled &&
145
+ binding.connectionId === task.binding.connectionId)) throw new Error('机器人连接已停用或更换');
146
+ return task;
147
+ }
148
+ }
@@ -0,0 +1,61 @@
1
+ import type { AssistantActivity, AssistantTerminationReason } from '../assistant';
2
+
3
+ export type AssistantTextPhase = Extract<AssistantActivity, { kind: 'text' }>['phase'];
4
+ export type AssistantTextSegment = { start: number; end: number; phase: AssistantTextPhase };
5
+
6
+ export class AssistantRunError extends Error {
7
+ constructor(public reason: AssistantTerminationReason, message: string) { super(message); }
8
+ }
9
+
10
+ export function responsePhase(value: unknown): AssistantTextPhase | undefined {
11
+ if (value === 'commentary' || value === 'partial_answer') return 'working';
12
+ if (value === 'final_answer') return 'answer';
13
+ return undefined;
14
+ }
15
+
16
+ const markers = [
17
+ { prefix: '[[tano:progress]]', phase: 'working' },
18
+ { prefix: '[[tano:final]]', phase: 'answer' },
19
+ ] as const;
20
+
21
+ /** Only an exact leading protocol marker is interpreted; ordinary prose is never guessed. */
22
+ export class AssistantTextDecoder {
23
+ private buffer = '';
24
+ private started = false;
25
+ private afterMarker = false;
26
+ phase: AssistantTextPhase = 'pending';
27
+ constructor(private emit: (text: string, phase: AssistantTextPhase) => void) {}
28
+ push(text: string, nativePhase?: AssistantTextPhase) {
29
+ if (nativePhase) this.phase = nativePhase;
30
+ if (this.started && !this.afterMarker) { this.emit(text, this.phase); return; }
31
+ this.buffer += text;
32
+ if (!this.started) {
33
+ const marker = markers.find(marker => this.buffer.startsWith(marker.prefix));
34
+ if (marker) {
35
+ this.phase = nativePhase ?? marker.phase;
36
+ this.buffer = this.buffer.slice(marker.prefix.length);
37
+ this.afterMarker = true;
38
+ } else if (markers.some(marker => marker.prefix.startsWith(this.buffer))) return;
39
+ this.started = true;
40
+ }
41
+ if (this.afterMarker) {
42
+ if (!this.buffer || this.buffer === '\r') return;
43
+ this.buffer = this.buffer.replace(/^\r?\n/, '');
44
+ this.afterMarker = false;
45
+ }
46
+ if (this.buffer) this.emit(this.buffer, this.phase);
47
+ this.buffer = '';
48
+ }
49
+ finish() {
50
+ if (!this.started && this.buffer) throw new AssistantRunError('incomplete', '模型的回答阶段标记未完整返回');
51
+ if (this.buffer) this.emit(this.buffer, this.phase);
52
+ this.buffer = '';
53
+ }
54
+ }
55
+
56
+ export function decodeAssistantText(text: string, phase?: AssistantTextPhase) {
57
+ let content = '';
58
+ const decoder = new AssistantTextDecoder(value => { content += value; });
59
+ decoder.push(text, phase); decoder.finish();
60
+ return { content, phase: phase ?? decoder.phase };
61
+ }