@peer-agent/runtime-core 0.1.0-rc.4 → 0.1.0-rc.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context-accounting-pipeline.d.ts +14 -2
- package/dist/context-accounting-pipeline.js +43 -24
- package/dist/context-compaction.d.ts +1 -0
- package/dist/context-compaction.js +1 -1
- package/dist/contracts.d.ts +3 -0
- package/dist/conversation-history-projector.d.ts +11 -1
- package/dist/conversation-history-projector.js +60 -17
- package/dist/evidence.js +1 -0
- package/dist/goal-idempotency.d.ts +2 -0
- package/dist/goal-idempotency.js +5 -0
- package/dist/goal-tool-contracts.d.ts +225 -0
- package/dist/goal-tool-contracts.js +297 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/input-prediction.d.ts +40 -0
- package/dist/input-prediction.js +118 -0
- package/dist/microcompact.d.ts +15 -1
- package/dist/microcompact.js +108 -2
- package/dist/project-input-recovery.d.ts +35 -0
- package/dist/project-input-recovery.js +190 -0
- package/dist/resource-edit-state.d.ts +101 -0
- package/dist/resource-edit-state.js +179 -0
- package/package.json +2 -2
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type InputDraftValue, type LocalInputSurface, type ProjectAgentSubmitInputResult, type ProjectInputDraftSnapshot, type ProjectInputRecoveryPort, type UnconfirmedProjectInput } from '@peer-agent/protocol';
|
|
2
|
+
export interface InputRecoveryView extends ProjectInputDraftSnapshot {
|
|
3
|
+
readonly ready: boolean;
|
|
4
|
+
readonly error: string | null;
|
|
5
|
+
readonly sending: readonly string[];
|
|
6
|
+
readonly received: readonly UnconfirmedProjectInput[];
|
|
7
|
+
}
|
|
8
|
+
/** Presentation continuity only; ports own storage and the existing governed input queue. */
|
|
9
|
+
export declare function createProjectInputRecovery({ workspaceId, surface, port, createId, now, receiptTimeoutMs }: {
|
|
10
|
+
workspaceId: string;
|
|
11
|
+
surface: LocalInputSurface;
|
|
12
|
+
port: ProjectInputRecoveryPort;
|
|
13
|
+
createId: () => string;
|
|
14
|
+
now?: () => string;
|
|
15
|
+
receiptTimeoutMs?: number;
|
|
16
|
+
}): {
|
|
17
|
+
getSnapshot: () => InputRecoveryView;
|
|
18
|
+
subscribe(fn: () => void): () => void;
|
|
19
|
+
load: () => Promise<boolean>;
|
|
20
|
+
edit: (patch: Partial<InputDraftValue>) => void;
|
|
21
|
+
flush: () => Promise<boolean>;
|
|
22
|
+
acknowledge: (ids: readonly string[]) => void;
|
|
23
|
+
send: (options?: {
|
|
24
|
+
text?: string;
|
|
25
|
+
quoteRefs?: readonly string[];
|
|
26
|
+
answerTo?: string;
|
|
27
|
+
useDraft?: boolean;
|
|
28
|
+
}) => Promise<ProjectAgentSubmitInputResult>;
|
|
29
|
+
observeReceived(ids: readonly string[]): void;
|
|
30
|
+
retry(inputId: string): Promise<ProjectAgentSubmitInputResult> | Promise<{
|
|
31
|
+
ok: boolean;
|
|
32
|
+
code: string;
|
|
33
|
+
}>;
|
|
34
|
+
};
|
|
35
|
+
export type ProjectInputRecovery = ReturnType<typeof createProjectInputRecovery>;
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { encodeResourceFeedbackTransport, normalizeResourceFeedbackList, emptyInputDraft, projectInputWasReceived } from '@peer-agent/protocol';
|
|
2
|
+
/** Presentation continuity only; ports own storage and the existing governed input queue. */
|
|
3
|
+
export function createProjectInputRecovery({ workspaceId, surface, port, createId, now = () => new Date().toISOString(), receiptTimeoutMs = 30_000 }) {
|
|
4
|
+
const address = { workspaceId, surface };
|
|
5
|
+
let view = { revision: 0, draft: emptyInputDraft(), pending: [], ready: false, error: null, sending: [], received: [] };
|
|
6
|
+
let changed = 0, saved = 0;
|
|
7
|
+
let earlyEdits = null;
|
|
8
|
+
let writing = null, loading = null;
|
|
9
|
+
const listeners = new Set(), storedAttachments = new Map(), active = new Map();
|
|
10
|
+
const publish = (patch) => { view = { ...view, ...patch }; for (const fn of listeners)
|
|
11
|
+
fn(); };
|
|
12
|
+
async function load() {
|
|
13
|
+
if (loading)
|
|
14
|
+
return loading;
|
|
15
|
+
loading = (async () => {
|
|
16
|
+
try {
|
|
17
|
+
const result = await port.read(address);
|
|
18
|
+
if (!result.ok) {
|
|
19
|
+
publish({ error: result.code });
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
for (const item of [...result.snapshot.draft.attachments, ...result.snapshot.pending.flatMap(item => item.attachments)])
|
|
23
|
+
storedAttachments.set(item.id, item);
|
|
24
|
+
publish({ ...result.snapshot, draft: earlyEdits ? { ...result.snapshot.draft, ...earlyEdits } : result.snapshot.draft, ready: true, error: null });
|
|
25
|
+
if (earlyEdits) {
|
|
26
|
+
earlyEdits = null;
|
|
27
|
+
changed++;
|
|
28
|
+
void flush();
|
|
29
|
+
}
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
publish({ error: 'DRAFT_UNAVAILABLE' });
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
loading = null;
|
|
38
|
+
}
|
|
39
|
+
})();
|
|
40
|
+
return loading;
|
|
41
|
+
}
|
|
42
|
+
async function flush() {
|
|
43
|
+
if (!view.ready)
|
|
44
|
+
return false;
|
|
45
|
+
if (writing)
|
|
46
|
+
return writing;
|
|
47
|
+
writing = (async () => {
|
|
48
|
+
while (saved !== changed) {
|
|
49
|
+
const version = changed, state = view;
|
|
50
|
+
const all = [...state.draft.attachments, ...state.pending.flatMap(item => item.attachments)];
|
|
51
|
+
const uploads = [...new Map(all.filter(item => storedAttachments.get(item.id) !== item).map(item => [item.id, item])).values()];
|
|
52
|
+
const { attachments, ...draft } = state.draft;
|
|
53
|
+
try {
|
|
54
|
+
const result = await port.write({ ...address, revision: state.revision,
|
|
55
|
+
draft: { ...draft, attachmentIds: attachments.map(item => item.id) },
|
|
56
|
+
pending: state.pending.map(({ attachments, ...input }) => ({ ...input, attachmentIds: attachments.map(item => item.id) })), uploads });
|
|
57
|
+
if (!result.ok) {
|
|
58
|
+
publish({ error: result.code });
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
saved = version;
|
|
62
|
+
storedAttachments.clear();
|
|
63
|
+
for (const item of all)
|
|
64
|
+
storedAttachments.set(item.id, item);
|
|
65
|
+
publish({ revision: result.revision, error: null });
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
publish({ error: 'DRAFT_SAVE_FAILED' });
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return true;
|
|
73
|
+
})().finally(() => { writing = null; });
|
|
74
|
+
return writing;
|
|
75
|
+
}
|
|
76
|
+
function edit(patch) {
|
|
77
|
+
if (patch.resourceFeedback !== undefined) {
|
|
78
|
+
const rows = normalizeResourceFeedbackList(patch.resourceFeedback);
|
|
79
|
+
if (!rows || rows.some(row => row.recipient.workspaceId !== workspaceId)) {
|
|
80
|
+
publish({ error: 'INVALID_RESOURCE_FEEDBACK' });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
patch = { ...patch, resourceFeedback: rows };
|
|
84
|
+
}
|
|
85
|
+
if (!view.ready)
|
|
86
|
+
earlyEdits = { ...earlyEdits, ...patch };
|
|
87
|
+
changed++;
|
|
88
|
+
publish({ draft: { ...view.draft, ...patch } });
|
|
89
|
+
if (view.ready)
|
|
90
|
+
void flush();
|
|
91
|
+
}
|
|
92
|
+
function acknowledge(ids) {
|
|
93
|
+
const pending = view.pending.filter(item => !ids.includes(item.inputId));
|
|
94
|
+
if (pending.length === view.pending.length)
|
|
95
|
+
return;
|
|
96
|
+
const received = [...view.received, ...view.pending.filter(item => ids.includes(item.inputId))];
|
|
97
|
+
changed++;
|
|
98
|
+
publish({ pending, received });
|
|
99
|
+
void flush();
|
|
100
|
+
}
|
|
101
|
+
function dispatch(input) {
|
|
102
|
+
const running = active.get(input.inputId);
|
|
103
|
+
if (running)
|
|
104
|
+
return running;
|
|
105
|
+
const job = (async () => {
|
|
106
|
+
publish({ sending: [...view.sending, input.inputId] });
|
|
107
|
+
try {
|
|
108
|
+
if (!await flush())
|
|
109
|
+
return { ok: false, code: view.error || 'DRAFT_SAVE_FAILED' };
|
|
110
|
+
// This deadline ends the presentation wait, never the host operation. A late
|
|
111
|
+
// factual receipt still reconciles the original envelope without resending.
|
|
112
|
+
const submitted = port.submit({ ...address, ...input }).then(result => {
|
|
113
|
+
if (projectInputWasReceived(result, workspaceId, input.inputId)) {
|
|
114
|
+
acknowledge([input.inputId]);
|
|
115
|
+
return result;
|
|
116
|
+
}
|
|
117
|
+
return { ok: false, code: result.code || 'INPUT_OUTCOME_UNKNOWN' };
|
|
118
|
+
}).catch(() => ({ ok: false, code: 'INPUT_OUTCOME_UNKNOWN' }));
|
|
119
|
+
let timer;
|
|
120
|
+
try {
|
|
121
|
+
return await Promise.race([submitted, new Promise(resolve => {
|
|
122
|
+
timer = setTimeout(() => resolve({ ok: false, code: 'INPUT_OUTCOME_UNKNOWN' }), receiptTimeoutMs);
|
|
123
|
+
})]);
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return { ok: false, code: 'INPUT_OUTCOME_UNKNOWN' };
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
active.delete(input.inputId);
|
|
134
|
+
publish({ sending: view.sending.filter(id => id !== input.inputId) });
|
|
135
|
+
}
|
|
136
|
+
})();
|
|
137
|
+
active.set(input.inputId, job);
|
|
138
|
+
return job;
|
|
139
|
+
}
|
|
140
|
+
async function send(options = {}) {
|
|
141
|
+
if (!view.ready && !await load())
|
|
142
|
+
return { ok: false, code: view.error || 'DRAFT_UNAVAILABLE' };
|
|
143
|
+
const useDraft = options.useDraft !== false, draft = view.draft;
|
|
144
|
+
const text = (options.text ?? draft.text).trim(), attachments = useDraft ? draft.attachments : [];
|
|
145
|
+
if (useDraft && options.text !== undefined && text !== draft.text.trim())
|
|
146
|
+
return { ok: false, code: 'INPUT_CHANGED' };
|
|
147
|
+
const resourceFeedback = useDraft ? normalizeResourceFeedbackList(draft.resourceFeedback) : [];
|
|
148
|
+
if (!resourceFeedback)
|
|
149
|
+
return { ok: false, code: 'INVALID_RESOURCE_FEEDBACK' };
|
|
150
|
+
if (!text && !attachments.length && !resourceFeedback.some(row => row.resource.kind === 'interactive'))
|
|
151
|
+
return { ok: false, code: 'INVALID_INPUT' };
|
|
152
|
+
if (!useDraft && options.answerTo) {
|
|
153
|
+
const existing = view.pending.find(item => item.answerTo === options.answerTo);
|
|
154
|
+
if (existing)
|
|
155
|
+
return existing.text === text ? dispatch(existing) : { ok: false, code: 'INPUT_PENDING_ANSWER' };
|
|
156
|
+
}
|
|
157
|
+
if (view.pending.length >= 32)
|
|
158
|
+
return { ok: false, code: 'DRAFT_LIMIT' };
|
|
159
|
+
if (resourceFeedback.some(item => item.recipient.workspaceId !== workspaceId))
|
|
160
|
+
return { ok: false, code: 'RESOURCE_FEEDBACK_RECIPIENT_CHANGED' };
|
|
161
|
+
try {
|
|
162
|
+
encodeResourceFeedbackTransport(resourceFeedback, attachments);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
return { ok: false, code: error.code ?? 'INVALID_RESOURCE_FEEDBACK' };
|
|
166
|
+
}
|
|
167
|
+
const input = { inputId: createId(), text, attachments, ...(resourceFeedback.length ? { resourceFeedback } : {}), createdAt: now(), quoteRefs: options.quoteRefs ?? [],
|
|
168
|
+
...(options.answerTo ? { answerTo: options.answerTo } : {}) };
|
|
169
|
+
changed++;
|
|
170
|
+
publish({ pending: [...view.pending, input], ...(useDraft ? { draft: emptyInputDraft() } : {}) });
|
|
171
|
+
return dispatch(input);
|
|
172
|
+
}
|
|
173
|
+
return {
|
|
174
|
+
getSnapshot: () => view,
|
|
175
|
+
subscribe(fn) { listeners.add(fn); return () => { listeners.delete(fn); }; },
|
|
176
|
+
load, edit, flush, acknowledge, send,
|
|
177
|
+
observeReceived(ids) {
|
|
178
|
+
const pending = view.pending.filter(item => !ids.includes(item.inputId));
|
|
179
|
+
const received = view.received.filter(item => !ids.includes(item.inputId));
|
|
180
|
+
if (pending.length !== view.pending.length) {
|
|
181
|
+
changed++;
|
|
182
|
+
publish({ pending, received });
|
|
183
|
+
void flush();
|
|
184
|
+
}
|
|
185
|
+
else if (received.length !== view.received.length)
|
|
186
|
+
publish({ received });
|
|
187
|
+
},
|
|
188
|
+
retry(inputId) { const input = view.pending.find(item => item.inputId === inputId); return input ? dispatch(input) : Promise.resolve({ ok: false, code: 'INPUT_NOT_PENDING' }); },
|
|
189
|
+
};
|
|
190
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { type ResourceEditTarget, type ResourceTextDraft, type ResourceEditWriter, type ResourceEditOperation, type ResourceEditReceipt } from '@peer-agent/protocol';
|
|
2
|
+
/** No filesystem, permission, runner, tool or Evidence creation ports. Host facts enter explicitly. */
|
|
3
|
+
export interface ResourceEditState {
|
|
4
|
+
readonly schemaVersion: 1;
|
|
5
|
+
readonly workspaceId: string;
|
|
6
|
+
readonly hostEpoch: string;
|
|
7
|
+
readonly revision: number;
|
|
8
|
+
readonly drafts: readonly ResourceTextDraft[];
|
|
9
|
+
readonly operations: readonly ResourceEditOperation[];
|
|
10
|
+
readonly retiredOperations: readonly ResourceEditOperation[];
|
|
11
|
+
readonly writerSequence: number;
|
|
12
|
+
readonly writers: readonly {
|
|
13
|
+
readonly draftId: string;
|
|
14
|
+
readonly writer: ResourceEditWriter;
|
|
15
|
+
}[];
|
|
16
|
+
}
|
|
17
|
+
export interface ResourceEditPorts {
|
|
18
|
+
readonly hashText: (text: string) => string;
|
|
19
|
+
readonly now: () => string;
|
|
20
|
+
}
|
|
21
|
+
export type ResourceEditEvent = {
|
|
22
|
+
readonly type: 'open';
|
|
23
|
+
readonly id: string;
|
|
24
|
+
readonly target: ResourceEditTarget;
|
|
25
|
+
readonly baseText: string;
|
|
26
|
+
} | {
|
|
27
|
+
readonly type: 'acquire';
|
|
28
|
+
readonly draftId: string;
|
|
29
|
+
readonly writer: Omit<ResourceEditWriter, 'lease'>;
|
|
30
|
+
readonly takeover?: boolean;
|
|
31
|
+
} | {
|
|
32
|
+
readonly type: 'release';
|
|
33
|
+
readonly draftId: string;
|
|
34
|
+
readonly writer: ResourceEditWriter;
|
|
35
|
+
} | {
|
|
36
|
+
readonly type: 'edit';
|
|
37
|
+
readonly draftId: string;
|
|
38
|
+
readonly revision: number;
|
|
39
|
+
readonly writer: ResourceEditWriter;
|
|
40
|
+
readonly text: string;
|
|
41
|
+
} | {
|
|
42
|
+
readonly type: 'discard';
|
|
43
|
+
readonly draftId: string;
|
|
44
|
+
readonly revision: number;
|
|
45
|
+
readonly writer: ResourceEditWriter;
|
|
46
|
+
} | {
|
|
47
|
+
readonly type: 'reserve';
|
|
48
|
+
readonly requestId: string;
|
|
49
|
+
readonly draftId: string;
|
|
50
|
+
readonly revision: number;
|
|
51
|
+
readonly writer: ResourceEditWriter;
|
|
52
|
+
readonly providerId: string;
|
|
53
|
+
readonly proposedVersion: string;
|
|
54
|
+
} | {
|
|
55
|
+
readonly type: 'archive';
|
|
56
|
+
readonly requestId: string;
|
|
57
|
+
} | {
|
|
58
|
+
readonly type: 'start';
|
|
59
|
+
readonly requestId: string;
|
|
60
|
+
readonly payloadHash: string;
|
|
61
|
+
} | {
|
|
62
|
+
readonly type: 'withdraw';
|
|
63
|
+
readonly requestId: string;
|
|
64
|
+
readonly payloadHash: string;
|
|
65
|
+
} | {
|
|
66
|
+
readonly type: 'uncertain';
|
|
67
|
+
readonly requestId: string;
|
|
68
|
+
readonly payloadHash: string;
|
|
69
|
+
} | {
|
|
70
|
+
readonly type: 'settle';
|
|
71
|
+
readonly requestId: string;
|
|
72
|
+
readonly receipt: ResourceEditReceipt;
|
|
73
|
+
};
|
|
74
|
+
export type ResourceEditTransition = {
|
|
75
|
+
readonly ok: false;
|
|
76
|
+
readonly code: string;
|
|
77
|
+
} | {
|
|
78
|
+
readonly ok: true;
|
|
79
|
+
readonly state: ResourceEditState;
|
|
80
|
+
readonly persist: boolean;
|
|
81
|
+
/** execute only marks a fresh journal transition; persist it, then use the governed runtime. It is never a grant. */
|
|
82
|
+
readonly value: {
|
|
83
|
+
readonly draft?: ResourceTextDraft;
|
|
84
|
+
readonly writer?: ResourceEditWriter;
|
|
85
|
+
readonly operation?: ResourceEditOperation;
|
|
86
|
+
readonly execute?: boolean;
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
export declare function resourceEditOperationPayload(op: Pick<ResourceEditOperation, 'draftId' | 'draftRevision' | 'target' | 'providerId' | 'proposedVersion'>): string;
|
|
90
|
+
export declare function emptyResourceEditState(workspaceId: string, hostEpoch: string): ResourceEditState;
|
|
91
|
+
/** Hydrated durable intent. Writer handles are deliberately absent from the persisted shape. */
|
|
92
|
+
export declare function resourceEditManifest(state: ResourceEditState): {
|
|
93
|
+
schemaVersion: 1;
|
|
94
|
+
workspaceId: string;
|
|
95
|
+
revision: number;
|
|
96
|
+
drafts: readonly ResourceTextDraft[];
|
|
97
|
+
operations: readonly ResourceEditOperation[];
|
|
98
|
+
retiredOperations: readonly ResourceEditOperation[];
|
|
99
|
+
};
|
|
100
|
+
export declare function recoverResourceEditState(raw: unknown, workspaceId: string, hostEpoch: string, hashText: ResourceEditPorts['hashText']): ResourceEditState | undefined;
|
|
101
|
+
export declare function reduceResourceEdit(state: ResourceEditState, event: ResourceEditEvent, ports: ResourceEditPorts): ResourceEditTransition;
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { normalizeResourceEditTarget, normalizeResourceTextDraft, normalizeResourceEditWriter, normalizeResourceEditReceipt, normalizeResourceEditOperation, resourceEditToken, resourceEditDigest, validResourceEditText, RESOURCE_TEXT_DRAFT_LIMIT, RESOURCE_EDIT_OPERATION_LIMIT, } from '@peer-agent/protocol';
|
|
2
|
+
const fail = (code) => ({ ok: false, code });
|
|
3
|
+
const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
4
|
+
const clone = (value) => structuredClone(value);
|
|
5
|
+
const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
6
|
+
export function resourceEditOperationPayload(op) {
|
|
7
|
+
return JSON.stringify({ draftId: op.draftId, draftRevision: op.draftRevision, target: op.target, providerId: op.providerId, proposedVersion: op.proposedVersion });
|
|
8
|
+
}
|
|
9
|
+
export function emptyResourceEditState(workspaceId, hostEpoch) {
|
|
10
|
+
if (!resourceEditToken(workspaceId) || !resourceEditToken(hostEpoch))
|
|
11
|
+
throw TypeError('INVALID_RESOURCE_EDIT_SCOPE');
|
|
12
|
+
return { schemaVersion: 1, workspaceId, hostEpoch, revision: 0, drafts: [], operations: [], retiredOperations: [], writers: [], writerSequence: 0 };
|
|
13
|
+
}
|
|
14
|
+
/** Hydrated durable intent. Writer handles are deliberately absent from the persisted shape. */
|
|
15
|
+
export function resourceEditManifest(state) {
|
|
16
|
+
return clone({ schemaVersion: state.schemaVersion, workspaceId: state.workspaceId, revision: state.revision, drafts: state.drafts, operations: state.operations, retiredOperations: state.retiredOperations });
|
|
17
|
+
}
|
|
18
|
+
export function recoverResourceEditState(raw, workspaceId, hostEpoch, hashText) {
|
|
19
|
+
if (!resourceEditToken(workspaceId) || !resourceEditToken(hostEpoch) || !object(raw) || Object.keys(raw).some(key => !['schemaVersion', 'workspaceId', 'revision', 'drafts', 'operations', 'retiredOperations'].includes(key))
|
|
20
|
+
|| raw.schemaVersion !== 1 || raw.workspaceId !== workspaceId || !Number.isSafeInteger(raw.revision) || Number(raw.revision) < 0
|
|
21
|
+
|| !Array.isArray(raw.drafts) || raw.drafts.length > RESOURCE_TEXT_DRAFT_LIMIT || !Array.isArray(raw.operations) || raw.operations.length > RESOURCE_EDIT_OPERATION_LIMIT
|
|
22
|
+
|| raw.retiredOperations !== undefined && (!Array.isArray(raw.retiredOperations) || raw.retiredOperations.length > 1024))
|
|
23
|
+
return;
|
|
24
|
+
const drafts = raw.drafts.map(normalizeResourceTextDraft), operations = raw.operations.map(normalizeResourceEditOperation);
|
|
25
|
+
const retired = (raw.retiredOperations ?? []).map(normalizeResourceEditOperation);
|
|
26
|
+
const all = [...operations, ...retired];
|
|
27
|
+
if (drafts.some(d => !d || d.target.recipient.workspaceId !== workspaceId || hashText(d.baseText) !== d.target.base.contentVersion)
|
|
28
|
+
|| retired.some(op => !op || op.phase !== 'settled')
|
|
29
|
+
|| all.some(op => !op || op.target.recipient.workspaceId !== workspaceId || hashText(resourceEditOperationPayload(op)) !== op.payloadHash)
|
|
30
|
+
|| new Set(drafts.map(d => d?.id)).size !== drafts.length || new Set(drafts.map(d => JSON.stringify(d?.target))).size !== drafts.length
|
|
31
|
+
|| new Set(all.map(op => op?.requestId)).size !== all.length)
|
|
32
|
+
return;
|
|
33
|
+
for (const op of all) {
|
|
34
|
+
const draft = drafts.find(d => d.id === op.draftId);
|
|
35
|
+
if (draft && (!equal(draft.target, op.target) || draft.revision < op.draftRevision)
|
|
36
|
+
|| all.some(other => other.draftId === op.draftId && !equal(other.target, op.target)))
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
// A retained running journal is uncertainty, never an invitation to execute again.
|
|
40
|
+
return { ...emptyResourceEditState(workspaceId, hostEpoch), revision: Number(raw.revision), drafts: drafts,
|
|
41
|
+
retiredOperations: retired,
|
|
42
|
+
operations: operations.map(op => op.phase === 'running' && op.hostEpoch !== hostEpoch ? { ...op, phase: 'uncertain' } : op) };
|
|
43
|
+
}
|
|
44
|
+
export function reduceResourceEdit(state, event, ports) {
|
|
45
|
+
const at = ports.now();
|
|
46
|
+
if (!Number.isFinite(Date.parse(at)))
|
|
47
|
+
return fail('INVALID_RESOURCE_EDIT_TIME');
|
|
48
|
+
const timestamp = new Date(at).toISOString();
|
|
49
|
+
const finish = (next, value, persist = true) => {
|
|
50
|
+
if (persist && !Number.isSafeInteger(state.revision + 1))
|
|
51
|
+
return fail('RESOURCE_EDIT_REVISION_LIMIT');
|
|
52
|
+
return { ok: true, state: clone({ ...next, revision: persist ? state.revision + 1 : state.revision }), persist, value: clone(value) };
|
|
53
|
+
};
|
|
54
|
+
if (event.type === 'open') {
|
|
55
|
+
const target = normalizeResourceEditTarget(event.target);
|
|
56
|
+
if (!resourceEditToken(event.id) || !target || target.recipient.workspaceId !== state.workspaceId || !validResourceEditText(event.baseText)
|
|
57
|
+
|| ports.hashText(event.baseText) !== target.base.contentVersion)
|
|
58
|
+
return fail('INVALID_RESOURCE_EDIT_DRAFT');
|
|
59
|
+
const same = state.drafts.find(d => equal(d.target, target)), withId = state.drafts.find(d => d.id === event.id);
|
|
60
|
+
if (withId && !equal(withId.target, target))
|
|
61
|
+
return fail('RESOURCE_EDIT_ID_CONFLICT');
|
|
62
|
+
if (!withId && [...state.operations, ...state.retiredOperations].some(op => op.draftId === event.id))
|
|
63
|
+
return fail('RESOURCE_EDIT_ID_CONFLICT');
|
|
64
|
+
if (same)
|
|
65
|
+
return finish(state, { draft: same }, false);
|
|
66
|
+
if (state.drafts.length >= RESOURCE_TEXT_DRAFT_LIMIT)
|
|
67
|
+
return fail('RESOURCE_EDIT_DRAFT_LIMIT');
|
|
68
|
+
const draft = { id: event.id, target, baseText: event.baseText, text: event.baseText, revision: 0, createdAt: timestamp, updatedAt: timestamp };
|
|
69
|
+
return finish({ ...state, drafts: [...state.drafts, draft] }, { draft });
|
|
70
|
+
}
|
|
71
|
+
if (event.type === 'archive') {
|
|
72
|
+
const op = state.operations.find(row => row.requestId === event.requestId);
|
|
73
|
+
if (!op)
|
|
74
|
+
return state.retiredOperations.some(row => row.requestId === event.requestId) ? finish(state, {}, false) : fail('RESOURCE_EDIT_OPERATION_MISSING');
|
|
75
|
+
if (op.phase !== 'settled')
|
|
76
|
+
return fail('RESOURCE_EDIT_OPERATION_PENDING');
|
|
77
|
+
if (state.retiredOperations.length >= 1024)
|
|
78
|
+
return fail('RESOURCE_EDIT_HISTORY_LIMIT');
|
|
79
|
+
return finish({ ...state, operations: state.operations.filter(row => row !== op), retiredOperations: [...state.retiredOperations, op] }, { operation: op });
|
|
80
|
+
}
|
|
81
|
+
if (event.type === 'start' || event.type === 'settle' || event.type === 'uncertain' || event.type === 'withdraw') {
|
|
82
|
+
const op = [...state.operations, ...state.retiredOperations].find(op => op.requestId === event.requestId);
|
|
83
|
+
if (!op)
|
|
84
|
+
return fail('RESOURCE_EDIT_OPERATION_MISSING');
|
|
85
|
+
if (event.type === 'withdraw') {
|
|
86
|
+
if (event.payloadHash !== op.payloadHash)
|
|
87
|
+
return fail('RESOURCE_EDIT_ID_CONFLICT');
|
|
88
|
+
if (op.phase === 'settled')
|
|
89
|
+
return finish(state, { operation: op }, false);
|
|
90
|
+
if (op.phase !== 'prepared')
|
|
91
|
+
return fail('RESOURCE_EDIT_OPERATION_PENDING');
|
|
92
|
+
const operation = { ...op, phase: 'settled', receipt: { outcome: 'cancelled' }, updatedAt: timestamp };
|
|
93
|
+
return finish({ ...state, operations: state.operations.map(row => row === op ? operation : row) }, { operation });
|
|
94
|
+
}
|
|
95
|
+
if (event.type === 'uncertain') {
|
|
96
|
+
if (event.payloadHash !== op.payloadHash)
|
|
97
|
+
return fail('RESOURCE_EDIT_ID_CONFLICT');
|
|
98
|
+
if (op.phase === 'prepared')
|
|
99
|
+
return fail('RESOURCE_EDIT_NOT_STARTED');
|
|
100
|
+
if (op.phase === 'settled' || op.phase === 'uncertain')
|
|
101
|
+
return finish(state, { operation: op }, false);
|
|
102
|
+
const operation = { ...op, phase: 'uncertain', updatedAt: timestamp };
|
|
103
|
+
return finish({ ...state, operations: state.operations.map(row => row === op ? operation : row) }, { operation });
|
|
104
|
+
}
|
|
105
|
+
if (event.type === 'start') {
|
|
106
|
+
if (event.payloadHash !== op.payloadHash)
|
|
107
|
+
return fail('RESOURCE_EDIT_ID_CONFLICT');
|
|
108
|
+
if (op.phase === 'uncertain' || op.phase === 'running' && op.hostEpoch !== state.hostEpoch)
|
|
109
|
+
return fail('RESOURCE_EDIT_RESULT_UNCERTAIN');
|
|
110
|
+
if (op.phase !== 'prepared')
|
|
111
|
+
return finish(state, { operation: op, execute: false }, false);
|
|
112
|
+
const operation = { ...op, phase: 'running', hostEpoch: state.hostEpoch, updatedAt: timestamp };
|
|
113
|
+
return finish({ ...state, operations: state.operations.map(row => row === op ? operation : row) }, { operation, execute: true });
|
|
114
|
+
}
|
|
115
|
+
const receipt = normalizeResourceEditReceipt(event.receipt);
|
|
116
|
+
if (!receipt || receipt.outcome === 'applied' && receipt.observedVersion !== op.proposedVersion)
|
|
117
|
+
return fail('INVALID_RESOURCE_EDIT_RECEIPT');
|
|
118
|
+
if (op.phase === 'settled')
|
|
119
|
+
return equal(op.receipt, receipt) ? finish(state, { operation: op }, false) : fail('RESOURCE_EDIT_RECEIPT_CONFLICT');
|
|
120
|
+
if (op.phase === 'prepared')
|
|
121
|
+
return fail('RESOURCE_EDIT_NOT_STARTED');
|
|
122
|
+
const operation = { ...op, phase: 'settled', receipt, updatedAt: timestamp };
|
|
123
|
+
// A previous revision's success cannot clear or rebase text entered later.
|
|
124
|
+
return finish({ ...state, operations: state.operations.map(row => row === op ? operation : row) }, { operation });
|
|
125
|
+
}
|
|
126
|
+
const draft = state.drafts.find(d => d.id === event.draftId);
|
|
127
|
+
if (!draft)
|
|
128
|
+
return fail('RESOURCE_EDIT_DRAFT_MISSING');
|
|
129
|
+
const binding = state.writers.find(item => item.draftId === draft.id);
|
|
130
|
+
if (event.type === 'acquire') {
|
|
131
|
+
if (event.takeover !== undefined && typeof event.takeover !== 'boolean' || !Number.isSafeInteger(state.writerSequence + 1))
|
|
132
|
+
return fail('INVALID_RESOURCE_EDIT_WRITER');
|
|
133
|
+
const writer = normalizeResourceEditWriter({ ...event.writer, lease: state.writerSequence + 1 });
|
|
134
|
+
if (!writer)
|
|
135
|
+
return fail('INVALID_RESOURCE_EDIT_WRITER');
|
|
136
|
+
if (binding && equal({ ...binding.writer, lease: 0 }, { ...writer, lease: 0 }))
|
|
137
|
+
return finish(state, { writer: binding.writer, draft }, false);
|
|
138
|
+
if (binding && !event.takeover)
|
|
139
|
+
return fail('RESOURCE_EDIT_WRITER_BUSY');
|
|
140
|
+
return finish({ ...state, writerSequence: writer.lease, writers: [...state.writers.filter(item => item.draftId !== draft.id), { draftId: draft.id, writer }] }, { writer, draft }, false);
|
|
141
|
+
}
|
|
142
|
+
if (!binding || !equal(binding.writer, normalizeResourceEditWriter(event.writer)))
|
|
143
|
+
return fail('RESOURCE_EDIT_STALE_WRITER');
|
|
144
|
+
if (event.type === 'release')
|
|
145
|
+
return finish({ ...state, writers: state.writers.filter(item => item !== binding) }, {}, false);
|
|
146
|
+
if (event.type === 'reserve') {
|
|
147
|
+
if (!resourceEditToken(event.requestId) || !resourceEditToken(event.providerId) || !resourceEditDigest(event.proposedVersion))
|
|
148
|
+
return fail('INVALID_RESOURCE_EDIT_OPERATION');
|
|
149
|
+
const prior = [...state.operations, ...state.retiredOperations].find(op => op.requestId === event.requestId);
|
|
150
|
+
if (prior)
|
|
151
|
+
return prior.draftId === draft.id && prior.draftRevision === event.revision && prior.providerId === event.providerId && prior.proposedVersion === event.proposedVersion && equal(prior.target, draft.target)
|
|
152
|
+
? finish(state, { operation: prior, execute: false }, false) : fail('RESOURCE_EDIT_ID_CONFLICT');
|
|
153
|
+
if (state.operations.some(op => op.phase !== 'settled' && (op.target.base.resourceId === draft.target.base.resourceId || op.target.reference.path === draft.target.reference.path)
|
|
154
|
+
&& (op.phase !== 'uncertain' || op.draftId === draft.id || op.target.base.contentVersion === draft.target.base.contentVersion)))
|
|
155
|
+
return fail('RESOURCE_EDIT_OPERATION_PENDING');
|
|
156
|
+
if (draft.revision !== event.revision)
|
|
157
|
+
return fail('RESOURCE_EDIT_DRAFT_CONFLICT');
|
|
158
|
+
if (ports.hashText(draft.text) !== event.proposedVersion)
|
|
159
|
+
return fail('RESOURCE_EDIT_PAYLOAD_CHANGED');
|
|
160
|
+
if (state.operations.length >= RESOURCE_EDIT_OPERATION_LIMIT)
|
|
161
|
+
return fail('RESOURCE_EDIT_OPERATION_LIMIT');
|
|
162
|
+
const payload = { draftId: draft.id, draftRevision: draft.revision, target: draft.target, providerId: event.providerId, proposedVersion: event.proposedVersion };
|
|
163
|
+
const operation = { ...payload, requestId: event.requestId, payloadHash: ports.hashText(resourceEditOperationPayload(payload)), phase: 'prepared', createdAt: timestamp, updatedAt: timestamp };
|
|
164
|
+
return finish({ ...state, operations: [...state.operations, operation] }, { operation, execute: false });
|
|
165
|
+
}
|
|
166
|
+
if (draft.revision !== event.revision)
|
|
167
|
+
return fail('RESOURCE_EDIT_DRAFT_CONFLICT');
|
|
168
|
+
if (event.type === 'discard') {
|
|
169
|
+
if (state.operations.some(op => op.draftId === draft.id && op.phase !== 'settled'))
|
|
170
|
+
return fail('RESOURCE_EDIT_OPERATION_PENDING');
|
|
171
|
+
return finish({ ...state, drafts: state.drafts.filter(row => row !== draft), writers: state.writers.filter(item => item !== binding) }, {});
|
|
172
|
+
}
|
|
173
|
+
if (!validResourceEditText(event.text) || !Number.isSafeInteger(draft.revision + 1))
|
|
174
|
+
return fail('INVALID_RESOURCE_EDIT_TEXT');
|
|
175
|
+
if (event.text === draft.text)
|
|
176
|
+
return finish(state, { draft }, false);
|
|
177
|
+
const changed = { ...draft, text: event.text, revision: draft.revision + 1, updatedAt: timestamp };
|
|
178
|
+
return finish({ ...state, drafts: state.drafts.map(row => row === draft ? changed : row) }, { draft: changed });
|
|
179
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@peer-agent/runtime-core",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.41",
|
|
4
4
|
"description": "Host-neutral capability, permission, projection, and Evidence primitives for Peer Agent runtimes.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"LICENSE"
|
|
39
39
|
],
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@peer-agent/protocol": "0.1.0-rc.
|
|
41
|
+
"@peer-agent/protocol": "0.1.0-rc.41"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"typescript": "^5.9.3"
|