@mogragsigma/dsh-dual-host-plugin 0.0.0-stage → 0.33.2
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/LICENSE +58 -0
- package/LICENSE.en.md +94 -0
- package/README.md +88 -2
- package/bundle/ASSET_NOTICE.md +19 -0
- package/bundle/LICENSE +58 -0
- package/bundle/LICENSE.en.md +94 -0
- package/bundle/README.md +75 -0
- package/bundle/THIRD_PARTY_NOTICES.md +94 -0
- package/bundle/a2a-dispatches.js +38 -0
- package/bundle/a2a-endpoint.js +112 -0
- package/bundle/a2a-tools.js +11 -0
- package/bundle/a2a-worker.js +63 -0
- package/bundle/approval-auth.js +5 -0
- package/bundle/approval-chat.js +150 -0
- package/bundle/approval-feishu.js +52 -0
- package/bundle/approval-guidance.js +68 -0
- package/bundle/approval-http.js +8 -0
- package/bundle/approval-ledger.js +142 -0
- package/bundle/approval-local-relay.js +86 -0
- package/bundle/approval-receipts.js +62 -0
- package/bundle/approval-reference.js +33 -0
- package/bundle/approval-semantic-model.js +26 -0
- package/bundle/approval-semantics.js +51 -0
- package/bundle/approval-ui/app.js +1 -0
- package/bundle/approval-ui/index.html +1 -0
- package/bundle/approval-ui/style.css +1 -0
- package/bundle/approval-workbench.js +45 -0
- package/bundle/artifact-media.js +34 -0
- package/bundle/bounded-text.js +44 -0
- package/bundle/compatibility.json +980 -0
- package/bundle/cordis.patch.yml +5 -0
- package/bundle/delivery-approval.js +133 -0
- package/bundle/delivery-artifacts.js +52 -0
- package/bundle/delivery-commit.js +125 -0
- package/bundle/delivery-contract.js +42 -0
- package/bundle/delivery-git-read.js +217 -0
- package/bundle/delivery-index.js +23 -0
- package/bundle/delivery-journal.js +207 -0
- package/bundle/delivery-object-plan.js +138 -0
- package/bundle/delivery-preview.js +153 -0
- package/bundle/delivery-process-receipts.js +90 -0
- package/bundle/delivery-process.js +46 -0
- package/bundle/delivery-process.py +228 -0
- package/bundle/delivery-push-approval.js +89 -0
- package/bundle/delivery-push-plan.js +98 -0
- package/bundle/delivery-push-recovery.js +32 -0
- package/bundle/delivery-push.js +83 -0
- package/bundle/delivery-recovery.js +143 -0
- package/bundle/delivery-runtime.js +182 -0
- package/bundle/delivery-ssh.js +64 -0
- package/bundle/delivery-state.js +106 -0
- package/bundle/development-attention.js +35 -0
- package/bundle/development-bridge.js +136 -0
- package/bundle/development-command-review.js +110 -0
- package/bundle/development-container.js +110 -0
- package/bundle/development-contract.js +17 -0
- package/bundle/development-files.js +101 -0
- package/bundle/development-gate.js +236 -0
- package/bundle/development-model-budget.js +48 -0
- package/bundle/development-peer.js +155 -0
- package/bundle/development-plan.js +43 -0
- package/bundle/development-reconciliation.js +62 -0
- package/bundle/development-review.js +81 -0
- package/bundle/development-rules/AGENTS.md +51 -0
- package/bundle/development-runtime.js +68 -0
- package/bundle/development-source.js +48 -0
- package/bundle/development-test-runner.js +13 -0
- package/bundle/development-tools.js +45 -0
- package/bundle/development-worker-review.js +110 -0
- package/bundle/development-worker.js +68 -0
- package/bundle/development-workspace.js +54 -0
- package/bundle/diagnostics.js +78 -0
- package/bundle/distribution-lock.json +773 -0
- package/bundle/drained-process.js +26 -0
- package/bundle/durable-inbox.js +294 -0
- package/bundle/feishu-policy.js +24 -0
- package/bundle/gateway-maintenance.js +55 -0
- package/bundle/global-rules/AGENTS.md +83 -0
- package/bundle/im-delivery.js +60 -0
- package/bundle/index.js +445 -0
- package/bundle/intervention-actions.js +135 -0
- package/bundle/intervention-job-control.js +28 -0
- package/bundle/intervention-state.js +43 -0
- package/bundle/job-version.js +15 -0
- package/bundle/legacy-feishu-adapter.js +89 -0
- package/bundle/link-contract.js +80 -0
- package/bundle/maintenance-process-identity.js +93 -0
- package/bundle/model-selection.js +71 -0
- package/bundle/native-context.js +14 -0
- package/bundle/native-entry-admission.js +2 -0
- package/bundle/native-entry.js +58 -0
- package/bundle/native-file-reference.js +32 -0
- package/bundle/native-owner-origin.js +12 -0
- package/bundle/native-rules/AGENTS.md +199 -0
- package/bundle/native-tools.js +108 -0
- package/bundle/notification-artifacts.js +70 -0
- package/bundle/notification-contract.js +29 -0
- package/bundle/notification-defaults.js +81 -0
- package/bundle/notification-discovery.js +65 -0
- package/bundle/notification-endpoint.js +54 -0
- package/bundle/notification-feishu.js +51 -0
- package/bundle/notification-media-endpoint.js +94 -0
- package/bundle/notification-review.js +27 -0
- package/bundle/notification-targets.js +54 -0
- package/bundle/onboarding-activity.js +66 -0
- package/bundle/onboarding-agent-hold.js +94 -0
- package/bundle/onboarding-boundary.js +20 -0
- package/bundle/onboarding-cloud-contract.js +29 -0
- package/bundle/onboarding-cloud-file-review.js +58 -0
- package/bundle/onboarding-cloud-files.js +100 -0
- package/bundle/onboarding-cloud-im.js +34 -0
- package/bundle/onboarding-cloud-model-probe.js +53 -0
- package/bundle/onboarding-cloud-models.js +68 -0
- package/bundle/onboarding-cloud-operation.js +276 -0
- package/bundle/onboarding-cloud-package.js +38 -0
- package/bundle/onboarding-cloud-repositories.js +89 -0
- package/bundle/onboarding-cloud-retirement.js +59 -0
- package/bundle/onboarding-cloud-task-runtime.js +90 -0
- package/bundle/onboarding-cloud-web.js +85 -0
- package/bundle/onboarding-cloud.js +110 -0
- package/bundle/onboarding-coordinated-hold.js +94 -0
- package/bundle/onboarding-exclusive-rename.js +16 -0
- package/bundle/onboarding-existing-host.js +63 -0
- package/bundle/onboarding-existing-setup.js +123 -0
- package/bundle/onboarding-file-contract.js +31 -0
- package/bundle/onboarding-file-review-contract.js +38 -0
- package/bundle/onboarding-file-transfer.js +133 -0
- package/bundle/onboarding-handoff-remote.js +98 -0
- package/bundle/onboarding-handoff.js +112 -0
- package/bundle/onboarding-host-stop-observation.js +44 -0
- package/bundle/onboarding-host.js +254 -0
- package/bundle/onboarding-identity.js +9 -0
- package/bundle/onboarding-im-maintenance-native.js +30 -0
- package/bundle/onboarding-im-maintenance.js +70 -0
- package/bundle/onboarding-im.js +31 -0
- package/bundle/onboarding-inspection-guard.js +15 -0
- package/bundle/onboarding-install-fs.js +58 -0
- package/bundle/onboarding-installer.js +157 -0
- package/bundle/onboarding-local-pair-native.js +21 -0
- package/bundle/onboarding-local-pair.js +99 -0
- package/bundle/onboarding-maintenance-fs.js +69 -0
- package/bundle/onboarding-maintenance-plan.js +213 -0
- package/bundle/onboarding-maintenance-record.js +169 -0
- package/bundle/onboarding-maintenance.js +163 -0
- package/bundle/onboarding-model-probe.js +119 -0
- package/bundle/onboarding-models.js +107 -0
- package/bundle/onboarding-native-host.js +101 -0
- package/bundle/onboarding-native-probe.js +56 -0
- package/bundle/onboarding-native-runner.js +29 -0
- package/bundle/onboarding-node-bootstrap.py +678 -0
- package/bundle/onboarding-node.js +77 -0
- package/bundle/onboarding-notification-defaults.js +93 -0
- package/bundle/onboarding-package-source.js +33 -0
- package/bundle/onboarding-paths.js +58 -0
- package/bundle/onboarding-peer-binding.js +61 -0
- package/bundle/onboarding-peer-contract.js +12 -0
- package/bundle/onboarding-plugin-repair.js +116 -0
- package/bundle/onboarding-plugin-version.js +143 -0
- package/bundle/onboarding-remote-control.js +140 -0
- package/bundle/onboarding-remote-probe.js +40 -0
- package/bundle/onboarding-repositories.js +88 -0
- package/bundle/onboarding-repository.js +49 -0
- package/bundle/onboarding-runtime-activation.js +83 -0
- package/bundle/onboarding-runtime-artifacts-client.js +87 -0
- package/bundle/onboarding-runtime-artifacts.js +126 -0
- package/bundle/onboarding-runtime-extension.js +400 -0
- package/bundle/onboarding-runtime-inventory.js +88 -0
- package/bundle/onboarding-runtime-program.js +42 -0
- package/bundle/onboarding-runtime-reclaim-client.js +94 -0
- package/bundle/onboarding-runtime-reclaim-worker.js +63 -0
- package/bundle/onboarding-runtime-reclaim.js +132 -0
- package/bundle/onboarding-runtime-repair-client.js +50 -0
- package/bundle/onboarding-runtime-repair.js +88 -0
- package/bundle/onboarding-runtime-stop.js +90 -0
- package/bundle/onboarding-runtime-uninstall-client.js +88 -0
- package/bundle/onboarding-runtime-uninstall.js +167 -0
- package/bundle/onboarding-runtime-version-client.js +138 -0
- package/bundle/onboarding-runtime-version.js +145 -0
- package/bundle/onboarding-schema.js +42 -0
- package/bundle/onboarding-self-disable.js +3 -0
- package/bundle/onboarding-self-lifecycle.js +95 -0
- package/bundle/onboarding-self-maintenance.js +52 -0
- package/bundle/onboarding-self-remove.js +3 -0
- package/bundle/onboarding-self-stop.js +85 -0
- package/bundle/onboarding-ssh-forward.js +48 -0
- package/bundle/onboarding-ssh.js +105 -0
- package/bundle/onboarding-state.js +95 -0
- package/bundle/onboarding-task-runtime-contract.js +38 -0
- package/bundle/onboarding-task-runtime-native.js +80 -0
- package/bundle/onboarding-task-runtime.js +66 -0
- package/bundle/onboarding-token-plan.js +52 -0
- package/bundle/onboarding-version-activation-client.js +48 -0
- package/bundle/onboarding-version-candidate.js +96 -0
- package/bundle/onboarding-version-repair.js +128 -0
- package/bundle/package-lock.json +773 -0
- package/bundle/package.json +99 -0
- package/bundle/peer-file-fs.js +62 -0
- package/bundle/peer-file-migration.js +59 -0
- package/bundle/peer-file-review.js +107 -0
- package/bundle/peer-files.js +157 -0
- package/bundle/peer-mailbox.js +75 -0
- package/bundle/protocol.js +17 -0
- package/bundle/recovery.js +40 -0
- package/bundle/repository-catalog.js +85 -0
- package/bundle/repository-gitee.js +76 -0
- package/bundle/repository-managed.js +46 -0
- package/bundle/repository-writer.js +43 -0
- package/bundle/rules/AGENTS.md +22 -0
- package/bundle/runtime-im-lock.json +11577 -0
- package/bundle/runtime-im-package.json +18 -0
- package/bundle/runtime-lock.json +10152 -0
- package/bundle/runtime-package.json +17 -0
- package/bundle/scheduler-migration.js +45 -0
- package/bundle/search-contract.js +19 -0
- package/bundle/skills/dsh-dual-end/SKILL.md +12 -0
- package/bundle/skills/task-a2a/SKILL.md +55 -0
- package/bundle/skills/task-a2a-worker/SKILL.md +23 -0
- package/bundle/skills/task-approval/SKILL.md +128 -0
- package/bundle/skills/task-artifacts/SKILL.md +46 -0
- package/bundle/skills/task-development/SKILL.md +144 -0
- package/bundle/skills/task-diagnostics/SKILL.md +41 -0
- package/bundle/skills/task-direct-link/SKILL.md +143 -0
- package/bundle/skills/task-file-transfer/SKILL.md +107 -0
- package/bundle/skills/task-handoff/SKILL.md +23 -0
- package/bundle/skills/task-intake/SKILL.md +13 -0
- package/bundle/skills/task-notify/SKILL.md +102 -0
- package/bundle/skills/task-onboarding/SKILL.md +708 -0
- package/bundle/skills/task-recovery/SKILL.md +54 -0
- package/bundle/skills/task-repository/SKILL.md +145 -0
- package/bundle/skills/task-research/SKILL.md +43 -0
- package/bundle/skills/task-schedule/SKILL.md +79 -0
- package/bundle/skills/task-sidebar/SKILL.md +122 -0
- package/bundle/skills/task-workbench/SKILL.md +30 -0
- package/bundle/skills/task-worker/SKILL.md +88 -0
- package/bundle/source-search.js +89 -0
- package/bundle/source-web.js +17 -0
- package/bundle/ssh-connector.js +24 -0
- package/bundle/store.js +102 -0
- package/bundle/task-a2a.js +298 -0
- package/bundle/task-artifacts.js +179 -0
- package/bundle/task-board-a2a.js +55 -0
- package/bundle/task-board-development.js +83 -0
- package/bundle/task-board-planning.js +84 -0
- package/bundle/task-board.js +132 -0
- package/bundle/task-branch.js +2 -0
- package/bundle/task-catalog.js +77 -0
- package/bundle/task-context.js +40 -0
- package/bundle/task-envelope.js +96 -0
- package/bundle/task-interventions.js +54 -0
- package/bundle/task-jobs.js +156 -0
- package/bundle/task-notifications.js +132 -0
- package/bundle/task-results.js +16 -0
- package/bundle/task-scheduler.js +77 -0
- package/bundle/task-sources.js +101 -0
- package/bundle/task-trigger-time.js +46 -0
- package/bundle/task-triggers.js +157 -0
- package/bundle/task-worker.js +73 -0
- package/bundle/task-workflows.js +117 -0
- package/bundle/tools.js +13 -0
- package/bundle/workbench-assets/asset-provenance.json +26 -0
- package/bundle/workbench-assets/whale-ui-states.png +0 -0
- package/bundle/workbench-client.js +811 -0
- package/bundle/workbench-decisions.js +48 -0
- package/bundle/workbench-host.js +122 -0
- package/bundle/workbench-im-identity.js +51 -0
- package/bundle/workbench-proxy.js +127 -0
- package/bundle/worker-rules/AGENTS.md +84 -0
- package/bundle/worker-tools.js +13 -0
- package/compatibility.json +980 -0
- package/cordis.patch.yml +3 -0
- package/package.json +57 -4
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import {validateSearch,taskExecutor} from './search-contract.js';
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {parseEnvelope} from './task-envelope.js';
|
|
4
|
+
import {newCloudPolicy,validPolicy,validSources,validReferences,validSuggestions} from './task-context.js';
|
|
5
|
+
const hash=x=>createHash('sha256').update(x).digest('hex');
|
|
6
|
+
const json=JSON.stringify;
|
|
7
|
+
const text=(v,n,code)=>{if(typeof v!=='string'||!v.trim()||v.length>n)throw Error(code);return v;};
|
|
8
|
+
export class TaskCatalog {
|
|
9
|
+
constructor(store){
|
|
10
|
+
this.store=store;this.db=store.db;
|
|
11
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS task_catalog(task_id TEXT PRIMARY KEY,title TEXT NOT NULL,spec_revision INTEGER NOT NULL,legacy INTEGER NOT NULL);
|
|
12
|
+
CREATE TABLE IF NOT EXISTS task_revisions(task_id TEXT,revision INTEGER,title TEXT,goal TEXT,source TEXT,created INTEGER,PRIMARY KEY(task_id,revision));
|
|
13
|
+
CREATE TABLE IF NOT EXISTS task_catalog_events(event_id TEXT PRIMARY KEY,fingerprint TEXT NOT NULL,result TEXT NOT NULL);`);
|
|
14
|
+
}
|
|
15
|
+
ensure(id){
|
|
16
|
+
this.store.task(id);let c=this.db.prepare('SELECT * FROM task_catalog WHERE task_id=?').get(id);if(c)return c;
|
|
17
|
+
const first=this.db.prepare('SELECT * FROM ingress WHERE task_id=? ORDER BY rowid LIMIT 1').get(id);if(!first)throw Error('TASK_NOT_FOUND');
|
|
18
|
+
const e=parseEnvelope(first.goal),title=(e?.title??e?.entry_interpretation??first.goal).trim().slice(0,120)||'未命名历史任务';
|
|
19
|
+
this.db.prepare('INSERT OR IGNORE INTO task_revisions VALUES (?,1,?,?,?,?)').run(id,title,first.goal,json({kind:'initial-ingress',ingress_id:first.id}),Date.now());
|
|
20
|
+
this.db.prepare('INSERT OR IGNORE INTO task_catalog VALUES (?,?,1,?)').run(id,title,e?0:1);
|
|
21
|
+
return this.db.prepare('SELECT * FROM task_catalog WHERE task_id=?').get(id);
|
|
22
|
+
}
|
|
23
|
+
head(id){const c=this.ensure(id);return {...c,...this.db.prepare('SELECT goal,source,created FROM task_revisions WHERE task_id=? AND revision=?').get(id,c.spec_revision)};}
|
|
24
|
+
view(id){
|
|
25
|
+
const h=this.head(id),e=parseEnvelope(h.goal);
|
|
26
|
+
return {task_id:id,title:h.title,spec_revision:h.spec_revision,legacy_readonly:!!h.legacy,intent:e?.intent??'legacy',model_policy:e?.model_policy??null,request:e,
|
|
27
|
+
references:e?.task_context?.references??[],split_suggestions:e?.task_context?.split_suggestions??[],
|
|
28
|
+
revisions:this.db.prepare('SELECT revision,title,source,created,goal FROM task_revisions WHERE task_id=? ORDER BY revision').all(id).map(({goal,...x})=>{const e=parseEnvelope(goal);return {...x,source:JSON.parse(x.source),intent:e?.intent??'legacy',model_policy:e?.model_policy??null};})};
|
|
29
|
+
}
|
|
30
|
+
find({query='',limit=20,after=0}={}){
|
|
31
|
+
if(typeof query!=='string'||query.length>120||!Number.isInteger(limit)||limit<1||limit>50||!Number.isInteger(after)||after<0)throw Error('INVALID_CATALOG_QUERY');
|
|
32
|
+
// Lazy migration leaves every historical task/ingress row intact.
|
|
33
|
+
for(const {id} of this.db.prepare('SELECT id FROM tasks').all())this.ensure(id);
|
|
34
|
+
const q=query.normalize('NFKC').trim().toLocaleLowerCase();
|
|
35
|
+
const all=this.db.prepare('SELECT task_id,title,spec_revision,legacy FROM task_catalog ORDER BY task_id').all().filter(x=>this.db.prepare('SELECT title FROM task_revisions WHERE task_id=?').all(x.task_id).some(r=>r.title.normalize('NFKC').toLocaleLowerCase().includes(q)));
|
|
36
|
+
const items=all.slice(after,after+limit).map(x=>{const h=this.head(x.task_id),e=parseEnvelope(h.goal);return {task_id:x.task_id,title:x.title,spec_revision:x.spec_revision,legacy_readonly:!!x.legacy,intent:e?.intent??'legacy',model_policy:e?.model_policy??null};});
|
|
37
|
+
return {items,total:all.length,next_cursor:after+limit<all.length?after+limit:null,requires_clarification:!!q&&all.length>1};
|
|
38
|
+
}
|
|
39
|
+
amend(node,a,assertQuiescent){
|
|
40
|
+
if(!a||!['local','cloud'].includes(node)||!Number.isInteger(a.expected_revision)||a.expected_revision<1)throw Error('INVALID_TASK_REVISION');
|
|
41
|
+
text(a.event_id,256,'INVALID_UPDATE_EVENT');text(a.task_id,128,'TASK_NOT_FOUND');text(a.summary,2000,'INVALID_GOAL');
|
|
42
|
+
const sources=validSources(a.sources);if(!sources.length||sources.some(s=>s.role!==node))throw Error('CONTEXT_ORIGIN_MISMATCH');
|
|
43
|
+
if(!['register','plan'].includes(a.intent))throw Error('TASK_INTENT_REQUIRED');
|
|
44
|
+
const policy=a.model_policy==null?null:validPolicy(a.model_policy);if(a.intent==='plan'&&!policy)throw Error('MODEL_POLICY_REQUIRED');
|
|
45
|
+
const title=a.title===undefined?undefined:text(a.title,120,'INVALID_TASK_TITLE');
|
|
46
|
+
const changes={task_id:a.task_id,expected_revision:a.expected_revision,summary:a.summary,sources,title,intent:a.intent,model_policy:policy,
|
|
47
|
+
references:a.references??[],split_suggestions:a.split_suggestions,...(a.search?{search:a.search}:{}),...(a.notification_contract?{notification_contract:a.notification_contract}:{})};
|
|
48
|
+
if(a.references!==undefined&&!Array.isArray(a.references))throw Error('REFERENCE_LIMIT');
|
|
49
|
+
if(a.split_suggestions!==undefined)validSuggestions(a.split_suggestions);
|
|
50
|
+
const fp=hash(json({node,...changes}));
|
|
51
|
+
return this.store.tx(()=>{
|
|
52
|
+
const old=this.db.prepare('SELECT * FROM task_catalog_events WHERE event_id=?').get(a.event_id);
|
|
53
|
+
if(old){if(old.fingerprint!==fp)throw Error('UPDATE_EVENT_CONFLICT');return JSON.parse(old.result);}
|
|
54
|
+
const h=this.head(a.task_id);if(h.spec_revision!==a.expected_revision)throw Error('TASK_REVISION_CONFLICT');
|
|
55
|
+
if(h.legacy)throw Error('LEGACY_TASK_READONLY');
|
|
56
|
+
if(this.store.task(a.task_id).blocked)throw Error('NEEDS_REVIEW');assertQuiescent(a.task_id);
|
|
57
|
+
const e=parseEnvelope(h.goal),prior=e.task_context?.sources??[{role:e.origin.role,session_id:e.origin.session_id,message_id:e.origin.message_id,text:e.request_text,sha256:e.origin.request_sha256}];
|
|
58
|
+
const merged=[...prior];
|
|
59
|
+
for(const s of sources){const known=merged.find(x=>x.role===s.role&&x.session_id===s.session_id&&x.message_id===s.message_id);if(known){if(known.sha256!==s.sha256)throw Error('INVALID_CONTEXT_SOURCE');}else merged.push(s);}
|
|
60
|
+
validSources(merged);
|
|
61
|
+
const refs=validReferences([...new Map([...(e.task_context?.references??[]),...(a.references??[])].map(r=>[(r.host??'')+':'+r.uri,r])).values()],merged);
|
|
62
|
+
const suggestions=a.split_suggestions===undefined?(e.task_context?.split_suggestions??[]):validSuggestions(a.split_suggestions);
|
|
63
|
+
const search=validateSearch(a.search??null,sources);
|
|
64
|
+
if(a.notification_contract!==undefined&&a.notification_contract!==1)throw Error('INVALID_TASK_ENVELOPE');
|
|
65
|
+
const notify=a.notification_contract??e.notification_contract;
|
|
66
|
+
const revision=h.spec_revision+1,next={...e,...(notify?{notification_contract:notify}:{}),search,executor:taskExecutor({search,notification_contract:notify}),title:title??h.title,entry_interpretation:a.summary,intent:a.intent,model_policy:policy?newCloudPolicy(policy):null,
|
|
67
|
+
task_context:{schema:'dsh-task-context-v1',spec_revision:revision,sources:merged,references:refs,split_suggestions:suggestions}};
|
|
68
|
+
const goal=json(next);if(goal.length>12000)throw Error('CONTEXT_LIMIT');
|
|
69
|
+
const source=json({kind:'direct-user-amendment',role:node,messages:sources.map(s=>({session_id:s.session_id,message_id:s.message_id,sha256:s.sha256})),summary:a.summary});
|
|
70
|
+
this.db.prepare('INSERT INTO task_revisions VALUES (?,?,?,?,?,?)').run(a.task_id,revision,next.title,goal,source,Date.now());
|
|
71
|
+
this.db.prepare('UPDATE task_catalog SET title=?,spec_revision=? WHERE task_id=?').run(next.title,revision,a.task_id);
|
|
72
|
+
const result={task_id:a.task_id,title:next.title,spec_revision:revision,intent:a.intent,model_policy:next.model_policy,status:'revised',execution:'not_scheduled',development:false,publish:false};
|
|
73
|
+
this.db.prepare('INSERT INTO task_catalog_events VALUES (?,?,?)').run(a.event_id,fp,json(result));
|
|
74
|
+
this.store.log('task-revised',{task_id:a.task_id,spec_revision:revision,node,event_id:a.event_id});return result;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
const hash=x=>createHash('sha256').update(x).digest('hex');
|
|
3
|
+
const text=(v,n,code)=>{if(typeof v!=='string'||!v.trim()||v.length>n)throw Error(code);return v;};
|
|
4
|
+
export function validPolicy(p){
|
|
5
|
+
if(!p||typeof p!=='object'||Array.isArray(p)||Object.keys(p).some(k=>!['provider','model','reasoningEffort'].includes(k)))throw Error('INVALID_MODEL_POLICY');
|
|
6
|
+
for(const k of ['provider','model'])text(p[k],128,'MODEL_POLICY_REQUIRED');
|
|
7
|
+
if(p.reasoningEffort!==undefined)text(p.reasoningEffort,64,'INVALID_MODEL_POLICY');
|
|
8
|
+
return {provider:p.provider,model:p.model,...(p.reasoningEffort!==undefined?{reasoningEffort:p.reasoningEffort}:{})};
|
|
9
|
+
}
|
|
10
|
+
// Only new managed cloud revisions use this default; never apply on historical reads.
|
|
11
|
+
export function newCloudPolicy(p){const policy=validPolicy(p);return {...policy,reasoningEffort:policy.reasoningEffort??'high'};}
|
|
12
|
+
export function validSources(sources){
|
|
13
|
+
if(!Array.isArray(sources)||sources.length>16)throw Error('CONTEXT_LIMIT');
|
|
14
|
+
const seen=new Set();
|
|
15
|
+
for(const s of sources){
|
|
16
|
+
if(!s||!['local','cloud'].includes(s.role))throw Error('INVALID_CONTEXT_SOURCE');
|
|
17
|
+
for(const k of ['message_id','session_id'])text(s[k],256,'INVALID_CONTEXT_SOURCE');
|
|
18
|
+
text(s.text,8000,'REQUEST_SIZE_UNSUPPORTED');
|
|
19
|
+
if(s.sha256!==hash(s.text)||seen.has(s.role+':'+s.session_id+':'+s.message_id))throw Error('INVALID_CONTEXT_SOURCE');
|
|
20
|
+
seen.add(s.role+':'+s.session_id+':'+s.message_id);
|
|
21
|
+
}
|
|
22
|
+
return sources.map(s=>({role:s.role,session_id:s.session_id,message_id:s.message_id,text:s.text,sha256:s.sha256}));
|
|
23
|
+
}
|
|
24
|
+
export function validReferences(refs,sources){
|
|
25
|
+
if(!Array.isArray(refs)||refs.length>12)throw Error('REFERENCE_LIMIT');
|
|
26
|
+
return refs.map(r=>{
|
|
27
|
+
if(!r||!['url','file-reference'].includes(r.kind))throw Error('UNSUPPORTED_REFERENCE');
|
|
28
|
+
text(r.title,120,'INVALID_REFERENCE');text(r.uri,1000,'INVALID_REFERENCE');
|
|
29
|
+
if(!sources.some(s=>s.text.includes(r.uri)))throw Error('REFERENCE_NOT_IN_USER_CONTEXT');
|
|
30
|
+
if(r.kind==='url'){
|
|
31
|
+
let u;try{u=new URL(r.uri);}catch{throw Error('INVALID_REFERENCE');}
|
|
32
|
+
if(u.protocol!=='https:'||u.username||u.password)throw Error('UNSUPPORTED_REFERENCE');
|
|
33
|
+
}else if(!['local','cloud'].includes(r.host)||!r.uri.startsWith('/')||r.uri.includes('\0'))throw Error('INVALID_REFERENCE');
|
|
34
|
+
return {kind:r.kind,title:r.title,uri:r.uri,...(r.kind==='file-reference'?{host:r.host}:{}),availability:'unverified',content_read:false};
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
export function validSuggestions(items){
|
|
38
|
+
if(!Array.isArray(items)||items.length>6)throw Error('SPLIT_LIMIT');
|
|
39
|
+
return items.map(x=>({title:text(x.title,120,'INVALID_SPLIT'),summary:text(x.summary,500,'INVALID_SPLIT'),status:'suggestion_only'}));
|
|
40
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// The native Host owns request provenance. Model-written summaries are not the source.
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {validateSearch,searchExecutor,taskExecutor} from './search-contract.js';
|
|
4
|
+
import {newCloudPolicy,validSources,validReferences,validSuggestions} from './task-context.js';
|
|
5
|
+
const hash=text=>createHash('sha256').update(text).digest('hex');
|
|
6
|
+
export const envelopeVersion='dsh-native-task-v1';
|
|
7
|
+
export function identity(role){
|
|
8
|
+
if(!['local','cloud'].includes(role))throw Error('INVALID_DEPLOYMENT');
|
|
9
|
+
return {role,name:role==='local'?'本地大肥鱼':'云端大肥鱼',peer_role:role==='local'?'cloud':'local',
|
|
10
|
+
peer_name:role==='local'?'云端大肥鱼':'本地大肥鱼',session_role:'entry',worker_host:'cloud',worker_capability:'readonly-plan',development:false,publish:false};
|
|
11
|
+
}
|
|
12
|
+
export function currentHumanRequest(agent){
|
|
13
|
+
const messages=agent.session?.deriveMessages?.();
|
|
14
|
+
if(!Array.isArray(messages))throw Error('HUMAN_REQUEST_UNAVAILABLE');
|
|
15
|
+
const m=messages.findLast(x=>x.role==='user'&&x.source?.kind==='user');
|
|
16
|
+
if(!m||typeof m.id!=='string'||!m.id)throw Error('HUMAN_REQUEST_UNAVAILABLE');
|
|
17
|
+
if(!Array.isArray(m.content)||m.content.some(x=>x.type!=='text'))throw Error('TEXT_TASK_REQUIRED');
|
|
18
|
+
const text=m.content.map(x=>x.text).join('\n');
|
|
19
|
+
if(!text.trim()||text.length>8000)throw Error('REQUEST_SIZE_UNSUPPORTED');
|
|
20
|
+
return {message_id:m.id,text,sha256:hash(text)};
|
|
21
|
+
}
|
|
22
|
+
export function selectedHumanContext(agent,role,ids=[]){
|
|
23
|
+
const current=currentHumanRequest(agent);
|
|
24
|
+
if(!Array.isArray(ids)||ids.length>6||new Set(ids).size!==ids.length||ids.some(x=>typeof x!=='string'))throw Error('CONTEXT_SELECTION_INVALID');
|
|
25
|
+
const messages=agent.session.deriveMessages();
|
|
26
|
+
const selected=ids.filter(id=>id!==current.message_id).sort((a,b)=>messages.findIndex(x=>x.id===a)-messages.findIndex(x=>x.id===b)).map(id=>{
|
|
27
|
+
const m=messages.find(x=>x.id===id&&x.role==='user'&&x.source?.kind==='user');
|
|
28
|
+
if(!m)throw Error('CONTEXT_SELECTION_INVALID');
|
|
29
|
+
return currentHumanRequest({session:{deriveMessages:()=>[m]}});
|
|
30
|
+
});
|
|
31
|
+
return validSources([...selected,current].map(s=>({role,session_id:agent.id,...s})));
|
|
32
|
+
}
|
|
33
|
+
export function makeEnvelope(agent,role,args){
|
|
34
|
+
identity(role);
|
|
35
|
+
if(args.target!=='cloud')throw Error('UNSUPPORTED_TASK_TARGET');
|
|
36
|
+
if(!['register','plan'].includes(args.intent))throw Error('TASK_INTENT_REQUIRED');
|
|
37
|
+
if(typeof args.goal!=='string'||!args.goal.trim()||args.goal.length>2000)throw Error('INVALID_GOAL');
|
|
38
|
+
const inputPolicy=args.model_policy??null;
|
|
39
|
+
const policy=inputPolicy?newCloudPolicy(inputPolicy):null;
|
|
40
|
+
if(args.intent==='plan'&&(!policy||typeof policy.provider!=='string'||!policy.provider||typeof policy.model!=='string'||!policy.model))throw Error('MODEL_POLICY_REQUIRED');
|
|
41
|
+
if(policy&&(Object.keys(inputPolicy).some(k=>!['provider','model','reasoningEffort'].includes(k))||
|
|
42
|
+
[policy.provider,policy.model].some(v=>typeof v!=='string'||!v||v.length>200)||
|
|
43
|
+
(policy.reasoningEffort!==undefined&&(typeof policy.reasoningEffort!=='string'||policy.reasoningEffort.length>64))))throw Error('INVALID_MODEL_POLICY');
|
|
44
|
+
const request=currentHumanRequest(agent);
|
|
45
|
+
const envelope={schema:envelopeVersion,origin:{role,session_id:agent.id,message_id:request.message_id,request_sha256:request.sha256},
|
|
46
|
+
request_text:request.text,entry_interpretation:args.goal,target:'cloud',executor:'independent-readonly-worker',intent:args.intent,model_policy:policy};
|
|
47
|
+
if(args.notification_contract!==undefined){if(args.notification_contract!==1)throw Error('INVALID_TASK_ENVELOPE');envelope.notification_contract=1;envelope.executor=taskExecutor(envelope);}
|
|
48
|
+
if(args.title!==undefined){if(typeof args.title!=='string'||!args.title.trim()||args.title.length>120)throw Error('INVALID_TASK_TITLE');envelope.title=args.title;}
|
|
49
|
+
if(args.search||args.context_message_ids?.length||args.references?.length||args.split_suggestions?.length){
|
|
50
|
+
const sources=selectedHumanContext(agent,role,args.context_message_ids);
|
|
51
|
+
envelope.task_context={schema:'dsh-task-context-v1',spec_revision:1,sources,references:validReferences(args.references??[],sources),split_suggestions:validSuggestions(args.split_suggestions??[])};
|
|
52
|
+
}
|
|
53
|
+
if(args.search){envelope.search=validateSearch(args.search,envelope.task_context.sources);envelope.executor=taskExecutor(envelope);}
|
|
54
|
+
const goal=JSON.stringify(envelope);
|
|
55
|
+
if(goal.length>12000)throw Error('REQUEST_SIZE_UNSUPPORTED');
|
|
56
|
+
return {goal,request,ingress_id:'native:'+role+':'+hash(agent.id+':'+request.message_id),task_key:args.task_key??'task-'+hash(role+':'+agent.id+':'+request.message_id).slice(0,24)};
|
|
57
|
+
}
|
|
58
|
+
export function parseEnvelope(goal){
|
|
59
|
+
let value;try{value=JSON.parse(goal);}catch{return null;}
|
|
60
|
+
if(value?.schema!==envelopeVersion)return null;
|
|
61
|
+
if(!value.origin||!['local','cloud'].includes(value.origin.role)||typeof value.request_text!=='string'||
|
|
62
|
+
hash(value.request_text)!==value.origin.request_sha256||value.target!=='cloud'||!['independent-readonly-worker',searchExecutor,'independent-readonly-notify-worker','independent-readonly-search-notify-worker'].includes(value.executor)||
|
|
63
|
+
!['register','plan'].includes(value.intent))throw Error('INVALID_TASK_ENVELOPE');
|
|
64
|
+
if(value.intervention_context){const c=value.intervention_context;if(c.schema!==1||c.scope!=='saved-materials-only'||typeof c.parent_job_id!=='string'||typeof c.original_request!=='string'||typeof c.opinion!=='string'||!c.materials||value.search||value.task_context?.references?.length||value.intent!=='plan'||value.notification_contract)throw Error('INVALID_TASK_ENVELOPE');}
|
|
65
|
+
if(value.title!==undefined&&(typeof value.title!=='string'||!value.title.trim()||value.title.length>120))throw Error('INVALID_TASK_TITLE');
|
|
66
|
+
if(value.task_context){
|
|
67
|
+
const c=value.task_context;
|
|
68
|
+
if(c.schema!=='dsh-task-context-v1'||!Number.isInteger(c.spec_revision)||c.spec_revision<1)throw Error('INVALID_TASK_ENVELOPE');
|
|
69
|
+
validSources(c.sources);validReferences(c.references,c.sources);validSuggestions(c.split_suggestions);
|
|
70
|
+
if(!c.sources.some(s=>s.role===value.origin.role&&s.session_id===value.origin.session_id&&s.message_id===value.origin.message_id&&s.sha256===value.origin.request_sha256))throw Error('INVALID_TASK_ENVELOPE');
|
|
71
|
+
}
|
|
72
|
+
if(value.search){validateSearch(value.search,value.task_context?.sources??[]);}
|
|
73
|
+
if(value.notification_contract!==undefined&&value.notification_contract!==1||value.executor!==taskExecutor(value))throw Error('INVALID_TASK_ENVELOPE');
|
|
74
|
+
return value;
|
|
75
|
+
}
|
|
76
|
+
export function assertScheduleEnvelope(goal,policy){
|
|
77
|
+
const e=parseEnvelope(goal);if(!e)return;
|
|
78
|
+
if(e.intent!=='plan')throw Error('TASK_REGISTER_ONLY');
|
|
79
|
+
const p=e.model_policy;
|
|
80
|
+
if(!p||!policy||p.provider!==policy.provider||p.model!==policy.model||p.reasoningEffort!==policy.reasoningEffort)throw Error('TASK_MODEL_POLICY_MISMATCH');
|
|
81
|
+
}
|
|
82
|
+
// Omitted dispatch effort inherits the persisted revision, not today's default.
|
|
83
|
+
// Explicit mismatches still fail, and legacy requests keep their original fingerprints.
|
|
84
|
+
export function schedulePolicy(goal,input){
|
|
85
|
+
const stored=parseEnvelope(goal)?.model_policy;
|
|
86
|
+
const policy=input&&input.reasoningEffort===undefined&&stored?.reasoningEffort!==undefined?{...input,reasoningEffort:stored.reasoningEffort}:input;
|
|
87
|
+
assertScheduleEnvelope(goal,policy);return policy;
|
|
88
|
+
}
|
|
89
|
+
export function sameNativeTask(a,b){
|
|
90
|
+
const left=parseEnvelope(a),right=parseEnvelope(b);
|
|
91
|
+
if(!left&&!right)return true; // Retain legacy multi-ingress semantics; no history rewrite.
|
|
92
|
+
if(!left||!right)return false;
|
|
93
|
+
return left.request_text===right.request_text&&left.intent===right.intent&&
|
|
94
|
+
JSON.stringify(left.model_policy)===JSON.stringify(right.model_policy)&&left.target===right.target&&
|
|
95
|
+
left.notification_contract===right.notification_contract&&left.title===right.title&&JSON.stringify(left.task_context)===JSON.stringify(right.task_context)&&JSON.stringify(left.search??null)===JSON.stringify(right.search??null);
|
|
96
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {interventionFacts} from './intervention-state.js';
|
|
3
|
+
const digest=x=>createHash('sha256').update(JSON.stringify(x)).digest('hex');
|
|
4
|
+
// Own observation ledger, not a second approval or scheduler state machine.
|
|
5
|
+
// No user-supplied source snapshots, decisions, retries or state-control APIs.
|
|
6
|
+
export class TaskInterventions {
|
|
7
|
+
constructor(store,now=Date.now){
|
|
8
|
+
this.store=store;this.db=store.db;this.now=now;
|
|
9
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS task_interventions(id TEXT PRIMARY KEY,task_id TEXT NOT NULL,source_kind TEXT NOT NULL,source_id TEXT NOT NULL,source_revision INTEGER,version INTEGER NOT NULL,lifecycle TEXT NOT NULL,body TEXT NOT NULL,fingerprint TEXT NOT NULL,created INTEGER NOT NULL,updated INTEGER NOT NULL,last_seen INTEGER NOT NULL,observation TEXT NOT NULL);
|
|
10
|
+
CREATE TABLE IF NOT EXISTS task_intervention_observations(task_id TEXT PRIMARY KEY,observed_at INTEGER NOT NULL,source_revision INTEGER);
|
|
11
|
+
CREATE INDEX IF NOT EXISTS task_interventions_task ON task_interventions(task_id,lifecycle,updated);
|
|
12
|
+
CREATE TABLE IF NOT EXISTS task_intervention_events(seq INTEGER PRIMARY KEY AUTOINCREMENT,item_id TEXT NOT NULL,version INTEGER NOT NULL,event TEXT NOT NULL,body TEXT NOT NULL,created INTEGER NOT NULL,UNIQUE(item_id,version));`);
|
|
13
|
+
}
|
|
14
|
+
observe(item,at=this.now()){
|
|
15
|
+
if(!item||typeof item.task_id!=='string'||!Number.isFinite(at))throw Error('INTERVENTION_SOURCE_INVALID');
|
|
16
|
+
const facts=interventionFacts(item,at);
|
|
17
|
+
return this.store.tx(()=>{
|
|
18
|
+
this.store.task(item.task_id);
|
|
19
|
+
const revision=this.db.prepare('SELECT spec_revision FROM task_catalog WHERE task_id=?').get(item.task_id)?.spec_revision??null;
|
|
20
|
+
if(revision!==item.spec_revision)throw Error('INTERVENTION_SOURCE_CHANGED');
|
|
21
|
+
const seen=new Set();
|
|
22
|
+
const put=(id,old,fact,event,observation)=>{
|
|
23
|
+
const body=JSON.stringify(fact),fp=digest(fact),version=(old?.version??0)+1;
|
|
24
|
+
if(old?.fingerprint===fp&&old.observation===observation){this.db.prepare('UPDATE task_interventions SET last_seen=? WHERE id=?').run(at,id);return;}
|
|
25
|
+
this.db.prepare('INSERT INTO task_interventions VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET version=excluded.version,lifecycle=excluded.lifecycle,body=excluded.body,fingerprint=excluded.fingerprint,updated=excluded.updated,last_seen=excluded.last_seen,observation=excluded.observation').run(id,item.task_id,fact.source_kind,fact.source_id,fact.source_revision,version,fact.lifecycle,body,fp,old?.created??at,at,observation==='seen'?at:old.last_seen,observation);
|
|
26
|
+
this.db.prepare('INSERT INTO task_intervention_events(item_id,version,event,body,created) VALUES (?,?,?,?,?)').run(id,version,event,body,at);
|
|
27
|
+
};
|
|
28
|
+
for(const fact of facts){
|
|
29
|
+
if(typeof fact.source_id!=='string')continue;
|
|
30
|
+
const id='intervention-'+digest([item.task_id,fact.source_kind,fact.source_id,fact.source_revision]),old=this.db.prepare('SELECT * FROM task_interventions WHERE id=?').get(id);seen.add(id);
|
|
31
|
+
if(!old&&fact.lifecycle!=='open')continue;
|
|
32
|
+
put(id,old,fact,!old?'observed':old.lifecycle!==fact.lifecycle?'source_state_changed':'source_updated','seen');
|
|
33
|
+
}
|
|
34
|
+
// Bounded source windows / missing subsystems are not completion evidence.
|
|
35
|
+
for(const old of this.db.prepare("SELECT * FROM task_interventions WHERE task_id=? AND lifecycle IN ('open','unverified')").all(item.task_id))if(!seen.has(old.id)&&old.observation!=='not_in_latest_window'){
|
|
36
|
+
const fact={...JSON.parse(old.body),lifecycle:'unverified',next:'本次未读取到原记录;刷新或核对原来源,不重复批准或重试。'};
|
|
37
|
+
put(old.id,old,fact,'source_not_observed','not_in_latest_window');
|
|
38
|
+
}
|
|
39
|
+
this.db.prepare('INSERT INTO task_intervention_observations VALUES (?,?,?) ON CONFLICT(task_id) DO UPDATE SET observed_at=excluded.observed_at,source_revision=excluded.source_revision').run(item.task_id,at,item.spec_revision);
|
|
40
|
+
return this.view(item.task_id);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
view(task){
|
|
44
|
+
this.store.task(task);
|
|
45
|
+
const rows=this.db.prepare("SELECT * FROM task_interventions WHERE task_id=? ORDER BY CASE WHEN lifecycle IN ('open','unverified') THEN 0 ELSE 1 END,updated DESC,id LIMIT 100").all(task);
|
|
46
|
+
const total=this.db.prepare('SELECT count(*) n FROM task_interventions WHERE task_id=?').get(task).n;
|
|
47
|
+
const observed=this.db.prepare('SELECT observed_at,source_revision FROM task_intervention_observations WHERE task_id=?').get(task);
|
|
48
|
+
return {schema:1,initialized:!!observed,last_observed_at:observed?.observed_at??null,observed_revision:observed?.source_revision??null,authority:'cloud_observation_ledger',is_authorization:false,grants_execution:false,display_limit:100,total,has_more:total>rows.length,
|
|
49
|
+
items:rows.map(r=>({...JSON.parse(r.body),
|
|
50
|
+
handling:this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='intervention_operations'").get()?this.db.prepare('SELECT id,plan,state,result,created FROM intervention_operations WHERE intervention_id=? ORDER BY rowid DESC LIMIT 8').all(r.id).map(o=>({id:o.id,action:JSON.parse(o.plan).action,text:JSON.parse(o.plan).text,state:o.state,result:o.result?JSON.parse(o.result):null,created:o.created})):[],id:r.id,version:r.version,created:r.created,updated:r.updated,last_seen:r.last_seen,observation:r.observation,
|
|
51
|
+
events:this.db.prepare('SELECT version,event,body,created FROM task_intervention_events WHERE item_id=? ORDER BY version DESC LIMIT 20').all(r.id).map(e=>({version:e.version,event:e.event,created:e.created,lifecycle:JSON.parse(e.body).lifecycle,user_opinion:JSON.parse(e.body).user_opinion,result:JSON.parse(e.body).result})),events_total:r.version})),
|
|
52
|
+
active_total:this.db.prepare("SELECT count(*) n FROM task_interventions WHERE task_id=? AND lifecycle IN ('open','unverified')").get(task).n};
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import {parseEnvelope} from './task-envelope.js';
|
|
2
|
+
import {DatabaseSync} from 'node:sqlite';
|
|
3
|
+
import {mkdirSync,chmodSync} from 'node:fs';
|
|
4
|
+
import {join} from 'node:path';
|
|
5
|
+
import {randomUUID,createHash} from 'node:crypto';
|
|
6
|
+
import {supportedJobVersions,requiredJobVersion} from './job-version.js';
|
|
7
|
+
export const digest=x=>createHash('sha256').update(JSON.stringify(x)).digest('hex');
|
|
8
|
+
const json=x=>JSON.stringify(x);
|
|
9
|
+
export class TaskJobs {
|
|
10
|
+
constructor(root,now=Date.now){
|
|
11
|
+
this.now=now;mkdirSync(root,{recursive:true,mode:0o700});this.file=join(root,'jobs.sqlite');this.db=new DatabaseSync(this.file);chmodSync(this.file,0o600);
|
|
12
|
+
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
|
|
13
|
+
CREATE TABLE IF NOT EXISTS jobs(id TEXT PRIMARY KEY,trigger_id TEXT UNIQUE,fingerprint TEXT,task_id TEXT,kind TEXT,goal TEXT,policy TEXT,status TEXT,due INTEGER,checkpoint TEXT,proposal TEXT,proposal_hash TEXT,approved_by TEXT,approval_event TEXT,attempts INTEGER DEFAULT 0,max_runs INTEGER,claim TEXT,version TEXT,created INTEGER,error TEXT);
|
|
14
|
+
CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,job_id TEXT,claim TEXT,session_id TEXT,status TEXT,started INTEGER,finished INTEGER,error TEXT);
|
|
15
|
+
CREATE TABLE IF NOT EXISTS controls(event_id TEXT PRIMARY KEY,fingerprint TEXT,result TEXT);
|
|
16
|
+
CREATE TABLE IF NOT EXISTS job_notifications(id TEXT PRIMARY KEY,text TEXT,delivered INTEGER DEFAULT 0);
|
|
17
|
+
CREATE TABLE IF NOT EXISTS job_inputs(event_id TEXT PRIMARY KEY,fingerprint TEXT,job_id TEXT,question_run_id TEXT,source TEXT,at INTEGER);
|
|
18
|
+
CREATE TABLE IF NOT EXISTS job_events(seq INTEGER PRIMARY KEY AUTOINCREMENT,job_id TEXT,type TEXT,data TEXT,at INTEGER);`);
|
|
19
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS worker_model_reservations(id TEXT PRIMARY KEY,job_id TEXT NOT NULL,run_id TEXT NOT NULL,claim TEXT NOT NULL,purpose TEXT NOT NULL,provider TEXT NOT NULL,model TEXT NOT NULL,reasoning TEXT,max_tokens INTEGER NOT NULL,created INTEGER NOT NULL);
|
|
20
|
+
CREATE INDEX IF NOT EXISTS worker_budget_by_run ON worker_model_reservations(run_id);`);
|
|
21
|
+
}
|
|
22
|
+
tx(fn){this.db.exec('BEGIN IMMEDIATE');try{const r=fn();this.db.exec('COMMIT');return r;}catch(e){this.db.exec('ROLLBACK');throw e;}}
|
|
23
|
+
event(id,type,data={}){this.db.prepare('INSERT INTO job_events(job_id,type,data,at) VALUES (?,?,?,?)').run(id,type,json(data),this.now());}
|
|
24
|
+
get(id){const j=this.db.prepare('SELECT * FROM jobs WHERE id=?').get(id);if(!j)throw Error('JOB_NOT_FOUND');return j;}
|
|
25
|
+
list(task_id){return this.db.prepare('SELECT id,task_id,kind,status,due,checkpoint,proposal,proposal_hash,attempts,max_runs,error FROM jobs WHERE task_id=? ORDER BY created,id').all(task_id);}
|
|
26
|
+
enqueue({task_id,trigger_id,kind='plan',goal,policy={},due,delay_seconds=0,max_runs=4,version='0.5.0'}){
|
|
27
|
+
if(!supportedJobVersions.has(version)||['0.21.0','0.22.0'].includes(version)&&kind!=='development'||version!=='0.5.0'&&kind!=='plan'&&!(['0.19.2','0.21.0','0.22.0'].includes(version)&&kind==='development'))throw Error('INVALID_JOB_VERSION');
|
|
28
|
+
const requestedVersion=version;
|
|
29
|
+
version=requiredJobVersion({kind,goal,version});
|
|
30
|
+
const requestedDue=due??null;
|
|
31
|
+
if(!Number.isInteger(delay_seconds)||delay_seconds<0||delay_seconds>366*86400)throw Error('INVALID_JOB');
|
|
32
|
+
due??=this.now()+delay_seconds*1000;
|
|
33
|
+
if(typeof task_id!=='string'||!task_id||typeof trigger_id!=='string'||!trigger_id||trigger_id.length>256||!['plan','development','test.checkpoint'].includes(kind)||typeof goal!=='string'||!goal.trim()||goal.length>12000||!Number.isSafeInteger(due)||due<0||due>this.now()+366*86400000||!Number.isInteger(max_runs)||max_runs<1||max_runs>10)throw Error('INVALID_JOB');
|
|
34
|
+
if(!policy||typeof policy!=='object'||Array.isArray(policy)||Object.keys(policy).some(k=>!['provider','model','reasoningEffort'].includes(k))||Object.values(policy).some(v=>typeof v!=='string'||!v||v.length>128))throw Error('INVALID_MODEL_POLICY');
|
|
35
|
+
const fingerprint=v=>digest({task_id,kind,goal,policy,requestedDue,delay_seconds,max_runs,...(v!=='0.5.0'?{version:v}:{})}),fp=fingerprint(version);
|
|
36
|
+
return this.tx(()=>{const old=this.db.prepare('SELECT * FROM jobs WHERE trigger_id=?').get(trigger_id);if(old){
|
|
37
|
+
// Finish linking an identically prepared OLD occurrence without upgrading its authority/version.
|
|
38
|
+
// claim() will hold it; an upgrade must not stall every unrelated task on TRIGGER_CONFLICT.
|
|
39
|
+
const legacyReplay=requestedVersion!==version&&old.version===requestedVersion&&old.fingerprint===fingerprint(requestedVersion);
|
|
40
|
+
if(old.fingerprint!==fp&&!legacyReplay)throw Error('TRIGGER_CONFLICT');return old;}
|
|
41
|
+
const id='job-'+randomUUID();this.db.prepare('INSERT INTO jobs(id,trigger_id,fingerprint,task_id,kind,goal,policy,status,due,checkpoint,max_runs,version,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,trigger_id,fp,task_id,kind,goal,json(policy),kind==='development'?'waiting_approval':'queued',due,'{}',max_runs,version,this.now());this.event(id,'enqueued');return this.get(id);});
|
|
42
|
+
}
|
|
43
|
+
// Must be called only after acquiring exclusive process ownership of the scheduler.
|
|
44
|
+
recover(replaySafe){return this.tx(()=>{for(const j of this.db.prepare("SELECT * FROM jobs WHERE status='running'").all()){
|
|
45
|
+
const status=supportedJobVersions.has(j.version)&&requiredJobVersion(j)===j.version&&replaySafe.has(j.kind)&&j.attempts<j.max_runs?'queued':'needs_review';
|
|
46
|
+
this.db.prepare('UPDATE jobs SET status=?,claim=NULL,error=? WHERE id=?').run(status,'HOST_RESTARTED',j.id);
|
|
47
|
+
this.db.prepare("UPDATE runs SET status='interrupted',finished=?,error='HOST_RESTARTED' WHERE job_id=? AND status='running'").run(this.now(),j.id);this.event(j.id,'recovered',{status});
|
|
48
|
+
} });}
|
|
49
|
+
claim(available,replaySafe,canClaim=()=>true){return this.tx(()=>{
|
|
50
|
+
for(const j of this.db.prepare("SELECT * FROM jobs WHERE status IN ('queued','waiting') AND due<=? ORDER BY due,created,id").all(this.now())){
|
|
51
|
+
if(!supportedJobVersions.has(j.version)){this.db.prepare("UPDATE jobs SET status='needs_review',error='VERSION_MISMATCH' WHERE id=?").run(j.id);continue;}
|
|
52
|
+
if(requiredJobVersion(j)!==j.version){this.db.prepare("UPDATE jobs SET status='needs_review',error='SOURCE_JOB_VERSION_REQUIRED' WHERE id=?").run(j.id);continue;}
|
|
53
|
+
if(j.kind==='development'&&!j.approved_by){this.db.prepare("UPDATE jobs SET status='waiting_approval' WHERE id=?").run(j.id);continue;}
|
|
54
|
+
if(!available.has(j.kind)){this.db.prepare("UPDATE jobs SET status='waiting_capability',error='CAPABILITY_UNAVAILABLE' WHERE id=?").run(j.id);continue;}
|
|
55
|
+
if(j.attempts>=j.max_runs){this.db.prepare("UPDATE jobs SET status='needs_review',error='RUN_BUDGET_EXHAUSTED' WHERE id=?").run(j.id);continue;}
|
|
56
|
+
if(this.db.prepare("SELECT 1 FROM jobs WHERE task_id=? AND status='running'").get(j.task_id))continue;
|
|
57
|
+
try{if(!canClaim(j))continue;}catch(e){this.db.prepare("UPDATE jobs SET status='needs_review',error=? WHERE id=?").run(/^DEVELOPMENT_[A-Z_]+$/.test(e.message)?e.message:'DEVELOPMENT_ADMISSION_FAILED',j.id);continue;}
|
|
58
|
+
const claim=randomUUID(),run_id='run-'+randomUUID(),session_id='task-worker-'+randomUUID();
|
|
59
|
+
this.db.prepare("UPDATE jobs SET status='running',claim=?,attempts=attempts+1,error=NULL WHERE id=?").run(claim,j.id);
|
|
60
|
+
this.db.prepare("INSERT INTO runs(id,job_id,claim,session_id,status,started) VALUES (?,?,?,?,'running',?)").run(run_id,j.id,claim,session_id,this.now());
|
|
61
|
+
this.event(j.id,'started',{run_id,session_id,replaySafe:replaySafe.has(j.kind)});return {...this.get(j.id),run_id,session_id};
|
|
62
|
+
}return null;
|
|
63
|
+
});}
|
|
64
|
+
assertClaim(id,claim){const j=this.get(id);if(j.status!=='running'||j.claim!==claim)throw Error('STALE_JOB_CLAIM');return j;}
|
|
65
|
+
// Reserve before actual dispatch. Failed/unknown dispatches are never refunded, including after restart.
|
|
66
|
+
// This is accounting, NOT permission to invoke a search provider or to change the task policy.
|
|
67
|
+
reserveModelRequest(job,request){
|
|
68
|
+
if(!request||Object.keys(request).some(k=>!['purpose','provider','model','reasoningEffort','maxTokens'].includes(k))||!['worker','search'].includes(request.purpose)||request.maxTokens!==2048||
|
|
69
|
+
['provider','model'].some(k=>typeof request[k]!=='string'||!request[k]||request[k].length>128)||request.reasoningEffort!==undefined&&(typeof request.reasoningEffort!=='string'||!request.reasoningEffort||request.reasoningEffort.length>64))throw Error('WORKER_MODEL_RESERVATION_INVALID');
|
|
70
|
+
return this.tx(()=>{
|
|
71
|
+
const current=this.assertClaim(job.id,job.claim),policy=request.purpose==='search'?parseEnvelope(current.goal)?.search?.model_policy:JSON.parse(current.policy);
|
|
72
|
+
if(current.kind!=='plan'||!this.db.prepare("SELECT 1 FROM runs WHERE id=? AND job_id=? AND claim=? AND status='running'").get(job.run_id,job.id,job.claim))throw Error('WORKER_MODEL_RUN_MISMATCH');
|
|
73
|
+
if(!policy?.provider||!policy?.model||request.provider!==policy.provider||request.model!==policy.model||
|
|
74
|
+
(request.purpose==='worker'&&policy.reasoningEffort!==undefined&&request.reasoningEffort!==policy.reasoningEffort)||
|
|
75
|
+
(request.purpose==='search'&&request.reasoningEffort!=='disabled'))throw Error('WORKER_MODEL_ROUTE_MISMATCH');
|
|
76
|
+
if(request.purpose==='search'&&this.db.prepare("SELECT count(*) n FROM worker_model_reservations WHERE run_id=? AND purpose='search'").get(job.run_id).n>=parseEnvelope(current.goal).search.max_requests)throw Error('WORKER_REQUEST_BUDGET');
|
|
77
|
+
const used=this.db.prepare('SELECT count(*) n FROM worker_model_reservations WHERE run_id=?').get(job.run_id).n;
|
|
78
|
+
if(used>=6)throw Error('WORKER_REQUEST_BUDGET');
|
|
79
|
+
const id='model-reservation-'+randomUUID();
|
|
80
|
+
this.db.prepare('INSERT INTO worker_model_reservations VALUES (?,?,?,?,?,?,?,?,?,?)').run(id,job.id,job.run_id,job.claim,request.purpose,request.provider,request.model,request.reasoningEffort??null,request.maxTokens,this.now());
|
|
81
|
+
return {id,used:used+1,limit:6,purpose:request.purpose,state:'reserved_not_proof_of_provider_success'};
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
finish(job,result){return this.tx(()=>{
|
|
85
|
+
const j=this.assertClaim(job.id,job.claim);
|
|
86
|
+
if(!result||!['checkpoint','proposal','done','input'].includes(result.outcome)||typeof result.summary!=='string'||!result.summary.trim()||result.summary.length>4000)throw Error('INVALID_CHECKPOINT');
|
|
87
|
+
let status='completed',due=j.due,proposal=null,ph=null;
|
|
88
|
+
if(result.outcome==='checkpoint'){
|
|
89
|
+
if(!Number.isInteger(result.delay_seconds)||result.delay_seconds<1||result.delay_seconds>366*86400)throw Error('INVALID_NEXT_RUN');
|
|
90
|
+
status=j.attempts>=j.max_runs?'needs_review':'waiting';due=this.now()+result.delay_seconds*1000;
|
|
91
|
+
}
|
|
92
|
+
if(result.outcome==='input'){
|
|
93
|
+
if(j.kind!=='plan'||typeof result.question!=='string'||!result.question.trim()||result.question.length>2000)throw Error('INVALID_INPUT_REQUEST');
|
|
94
|
+
status=j.attempts>=j.max_runs?'needs_review':'waiting_input';
|
|
95
|
+
this.db.prepare("UPDATE jobs SET version=CASE WHEN version IN ('0.17.1','0.18.0','0.18.1','0.18.2','0.18.3','0.19.0','0.19.1') THEN version ELSE '0.17.0' END WHERE id=?").run(j.id);
|
|
96
|
+
}
|
|
97
|
+
if(result.outcome==='proposal'){
|
|
98
|
+
if(typeof result.proposal!=='string'||!result.proposal.trim()||result.proposal.length>8000)throw Error('INVALID_PROPOSAL');
|
|
99
|
+
proposal=result.proposal;ph=digest({job_id:j.id,task_id:j.task_id,goal:j.goal,policy:JSON.parse(j.policy),proposal});status='waiting_approval';
|
|
100
|
+
}
|
|
101
|
+
this.db.prepare('UPDATE jobs SET status=?,due=?,checkpoint=?,proposal=?,proposal_hash=?,claim=NULL,error=? WHERE id=?').run(status,due,json({summary:result.summary,...(result.outcome==='input'?{question:result.question,question_run_id:job.run_id}:{})}),proposal,ph,status==='needs_review'?'RUN_BUDGET_EXHAUSTED':null,j.id);
|
|
102
|
+
this.db.prepare("UPDATE runs SET status='completed',finished=? WHERE id=? AND claim=?").run(this.now(),job.run_id,job.claim);this.event(j.id,'checkpoint',{status,run_id:job.run_id,summary:result.summary,...(result.outcome==='input'?{question:result.question}:{})});
|
|
103
|
+
if(j.kind!=='test.checkpoint'&&status!=='waiting'&&parseEnvelope(j.goal)?.notification_contract!==1){
|
|
104
|
+
const text=j.version==='0.22.0'?'DSH 方案约束开发批次:'+status+'\n'+result.summary+'\n提交、推送、发布、部署未执行;模型报告不代替安全交接和成果核验。':status==='waiting_approval'?'DSH 只读规划完成,等待开发审批。任务 '+j.task_id+'\n'+result.summary+'\n方案:'+proposal+'\n当前可信开发审批入口尚未开放;请按任务名称查询方案。旧 /approve 测试命令已退役。此通知不授权开发或写入仓库。':'DSH 规划批次 '+j.id+':'+status+'\n'+result.summary+'\n这不表示整个长期任务已完成。';
|
|
105
|
+
this.db.prepare('INSERT OR IGNORE INTO job_notifications(id,text) VALUES (?,?)').run('job-result:'+job.run_id,text);
|
|
106
|
+
}
|
|
107
|
+
return this.get(j.id);
|
|
108
|
+
});}
|
|
109
|
+
fail(job,code,attention){return this.tx(()=>{const j=this.get(job.id);if(j.claim!==job.claim||j.status!=='running')return;
|
|
110
|
+
const valid=j.kind==='development'&&j.version==='0.22.0'&&attention?.schema===1&&attention.run_id===job.run_id&&attention.grants_execution===false&&
|
|
111
|
+
typeof attention.summary==='string'&&attention.summary.length>0&&attention.summary.length<=1200&&typeof attention.question==='string'&&attention.question.length>0&&attention.question.length<=700;
|
|
112
|
+
const detail=valid?{summary:attention.summary,question:attention.question}:{};
|
|
113
|
+
if(valid)this.db.prepare('UPDATE jobs SET checkpoint=? WHERE id=?').run(json({...detail,development_attention:{run_id:job.run_id,grants_execution:false}}),job.id);
|
|
114
|
+
this.db.prepare("UPDATE jobs SET status='needs_review',error=?,claim=NULL WHERE id=?").run(code,j.id);this.db.prepare("UPDATE runs SET status='failed',finished=?,error=? WHERE id=?").run(this.now(),code,job.run_id);this.event(j.id,'failed',{code,run_id:job.run_id,...detail});if(j.kind!=='test.checkpoint'&&parseEnvelope(j.goal)?.notification_contract!==1)this.db.prepare('INSERT OR IGNORE INTO job_notifications(id,text) VALUES (?,?)').run('job-failed:'+job.run_id,'DSH 批次 '+j.id+' 待核对:'+code+(valid?'\n'+detail.summary+'\n'+detail.question:'')+(j.version==='0.22.0'?';保留原审批、已发生操作与预算,不自动重试或交付。':',未授权开发。'));
|
|
115
|
+
});}
|
|
116
|
+
control({id,action,event_id,actor,proposal_hash}){
|
|
117
|
+
if(!['pause','resume','cancel','approve'].includes(action)||typeof event_id!=='string'||!event_id||event_id.length>256||typeof actor!=='string'||!actor||actor.length>128)throw Error('INVALID_CONTROL');
|
|
118
|
+
return this.tx(()=>{
|
|
119
|
+
const fp=digest({id,action,actor,proposal_hash}),old=this.db.prepare('SELECT * FROM controls WHERE event_id=?').get(event_id);
|
|
120
|
+
if(old){if(old.fingerprint!==fp)throw Error('CONTROL_CONFLICT');return JSON.parse(old.result);}
|
|
121
|
+
const j=this.get(id);let status;
|
|
122
|
+
if(action==='approve'){
|
|
123
|
+
if(j.status!=='waiting_approval'||!j.proposal_hash||proposal_hash!==j.proposal_hash)throw Error('APPROVAL_SCOPE_MISMATCH');
|
|
124
|
+
// No development adapter is shipped in this release. Approval never implies execution.
|
|
125
|
+
status='waiting_capability';this.db.prepare('UPDATE jobs SET approved_by=?,approval_event=?,status=?,error=? WHERE id=?').run(actor,event_id,status,'DEVELOPMENT_ADAPTER_NOT_ENABLED',id);
|
|
126
|
+
}else if(action==='resume'){
|
|
127
|
+
if(j.status!=='paused')throw Error('RESUME_NOT_ALLOWED');
|
|
128
|
+
const pause=this.db.prepare("SELECT data FROM job_events WHERE job_id=? AND type='pause' ORDER BY seq DESC LIMIT 1").get(id);
|
|
129
|
+
status=pause&&JSON.parse(pause.data).from_status==='waiting_input'?'waiting_input':'queued';this.db.prepare('UPDATE jobs SET status=?,due=?,claim=NULL WHERE id=?').run(status,this.now(),id);
|
|
130
|
+
}else{
|
|
131
|
+
if(['completed','cancelled'].includes(j.status))throw Error('CONTROL_NOT_ALLOWED');
|
|
132
|
+
if(action==='pause'&&!['queued','waiting','running','paused','waiting_input'].includes(j.status))throw Error('CONTROL_NOT_ALLOWED');
|
|
133
|
+
// Invalidates every delayed tool/report before signalling the active agent.
|
|
134
|
+
status=action==='pause'?'paused':'cancelled';this.db.prepare('UPDATE jobs SET status=?,claim=NULL WHERE id=?').run(status,id);
|
|
135
|
+
this.db.prepare("UPDATE runs SET status='cancelled',finished=? WHERE job_id=? AND status='running'").run(this.now(),id);
|
|
136
|
+
}
|
|
137
|
+
const result={id,status};this.db.prepare('INSERT INTO controls VALUES (?,?,?)').run(event_id,fp,json(result));this.event(id,action,{actor,event_id,...(action==='pause'?{from_status:j.status==='paused'?(JSON.parse(this.db.prepare("SELECT data FROM job_events WHERE job_id=? AND type='pause' ORDER BY seq DESC LIMIT 1").get(id)?.data??'{}').from_status??'queued'):j.status}:{})});return result;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
inputs(id){return this.db.prepare('SELECT event_id,question_run_id,source,at FROM job_inputs WHERE job_id=? ORDER BY at,event_id').all(id).map(x=>({...x,source:JSON.parse(x.source)}));}
|
|
141
|
+
answer({id,question_run_id,event_id,source}){
|
|
142
|
+
if(typeof event_id!=='string'||!event_id||event_id.length>256||!Array.isArray(source)||!source.length||json(source).length>12000)throw Error('SCHEDULER_INPUT_INVALID');
|
|
143
|
+
return this.tx(()=>{
|
|
144
|
+
const fp=digest({id,question_run_id,source}),old=this.db.prepare('SELECT * FROM job_inputs WHERE event_id=?').get(event_id);
|
|
145
|
+
if(old){if(old.fingerprint!==fp)throw Error('SCHEDULER_EVENT_CONFLICT');return {id,status:this.get(id).status,recorded:true};}
|
|
146
|
+
const j=this.get(id),checkpoint=JSON.parse(j.checkpoint);
|
|
147
|
+
if(j.kind!=='plan'||j.status!=='waiting_input'||checkpoint.question_run_id!==question_run_id)throw Error('SCHEDULER_INPUT_STALE');
|
|
148
|
+
if(j.attempts>=j.max_runs)throw Error('SCHEDULER_INPUT_BUDGET_EXHAUSTED');
|
|
149
|
+
if(this.db.prepare('SELECT count(*) AS n FROM job_inputs WHERE job_id=?').get(id).n>=9)throw Error('SCHEDULER_INPUT_BUDGET_EXHAUSTED');
|
|
150
|
+
this.db.prepare('INSERT INTO job_inputs VALUES (?,?,?,?,?,?)').run(event_id,fp,id,question_run_id,json(source),this.now());
|
|
151
|
+
this.db.prepare("UPDATE jobs SET status='queued',due=?,claim=NULL WHERE id=?").run(this.now(),id);this.event(id,'input_received',{event_id,question_run_id});
|
|
152
|
+
return {id,status:'queued',recorded:true};
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
close(){this.db.close();}
|
|
156
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import {NotificationDefaults} from './notification-defaults.js';
|
|
2
|
+
import {NotificationArtifacts} from './notification-artifacts.js';
|
|
3
|
+
import {parseEnvelope} from './task-envelope.js';
|
|
4
|
+
import {randomUUID} from 'node:crypto';
|
|
5
|
+
import {targets,policy,digest,json,text,outcome} from './notification-contract.js';
|
|
6
|
+
import {NotificationReview} from './notification-review.js';
|
|
7
|
+
import {NotificationDiscovery} from './notification-discovery.js';
|
|
8
|
+
import {NotificationTargets} from './notification-targets.js';
|
|
9
|
+
import {NotificationEndpoint} from './notification-endpoint.js';
|
|
10
|
+
import {validSources} from './task-context.js';
|
|
11
|
+
import {tx} from './recovery.js';
|
|
12
|
+
const terminal=new Set(['accepted','needs_review','cancelled']);
|
|
13
|
+
const current=(db,id)=>db.prepare('SELECT * FROM notification_bindings WHERE task_id=?').get(id);
|
|
14
|
+
const humanEvent=(type,data)=>type==='failed'?['attention','本批次失败/待核对']:type==='checkpoint'?(data.status==='completed'?['result','本批次完成']:['waiting_approval','waiting_input','needs_review'].includes(data.status)?['attention','需要你处理']:['progress','批次检查点已保存']):({enqueued:['progress','执行已排队'],started:['progress','本批次开始'],pause:['progress','已请求暂停(不代表排空)'],resume:['progress','已请求恢复'],cancel:['result','已请求取消(不代表排空)']})[type];
|
|
15
|
+
export class TaskNotifications {
|
|
16
|
+
constructor(g,config=[]){
|
|
17
|
+
this.g=g;this.db=g.db;this.config=new Map(targets(config).map(t=>[t.key,t]));this.endpoint=new NotificationEndpoint(g,config);this.lastError=null;
|
|
18
|
+
this.discovery=new NotificationDiscovery(g,()=>this.endpoint.service());this.registry=new NotificationTargets(this);this.defaults=new NotificationDefaults(this);
|
|
19
|
+
if(!g.store)return;this.review=new NotificationReview(g);
|
|
20
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS notification_tasks(task_id TEXT PRIMARY KEY,start_seq INTEGER NOT NULL,created INTEGER NOT NULL);
|
|
21
|
+
CREATE TABLE IF NOT EXISTS notification_bindings(task_id TEXT PRIMARY KEY,revision INTEGER NOT NULL,task_revision INTEGER NOT NULL,target_key TEXT,route_hash TEXT,policy TEXT,state TEXT NOT NULL,source TEXT NOT NULL,created INTEGER NOT NULL,start_seq INTEGER NOT NULL);
|
|
22
|
+
CREATE TABLE IF NOT EXISTS notification_binding_events(event_id TEXT PRIMARY KEY,fingerprint TEXT NOT NULL,result TEXT NOT NULL);
|
|
23
|
+
CREATE TABLE IF NOT EXISTS task_notification_events(id TEXT PRIMARY KEY,task_id TEXT NOT NULL,category TEXT NOT NULL,at INTEGER NOT NULL,disposition TEXT NOT NULL,delivery_id TEXT);
|
|
24
|
+
CREATE TABLE IF NOT EXISTS task_notifications(id TEXT PRIMARY KEY,task_id TEXT NOT NULL,binding_revision INTEGER NOT NULL,target_key TEXT NOT NULL,host TEXT NOT NULL,route_hash TEXT NOT NULL,category TEXT NOT NULL,text TEXT NOT NULL,state TEXT NOT NULL,due INTEGER NOT NULL,created INTEGER NOT NULL,lease TEXT,payload TEXT,result TEXT,message_id TEXT,error TEXT);
|
|
25
|
+
CREATE TABLE IF NOT EXISTS notification_meta(singleton INTEGER PRIMARY KEY,cursor INTEGER NOT NULL);`);
|
|
26
|
+
if(!this.db.prepare('PRAGMA table_info(task_notifications)').all().some(c=>c.name==='dispatched_at'))this.db.exec('ALTER TABLE task_notifications ADD COLUMN dispatched_at INTEGER');
|
|
27
|
+
this.media=new NotificationArtifacts(this);
|
|
28
|
+
this.db.prepare('INSERT OR IGNORE INTO notification_meta VALUES (1,?)').run(g.scheduler?.jobs.db.prepare('SELECT coalesce(max(seq),0) n FROM job_events').get().n??0);
|
|
29
|
+
}
|
|
30
|
+
track(task){if(!this.g.store)return;const inserted=this.db.prepare('INSERT OR IGNORE INTO notification_tasks VALUES (?,?,?)').run(task,this.g.scheduler?.jobs.db.prepare('SELECT coalesce(max(seq),0) n FROM job_events').get().n??0,this.g.now());if(inserted.changes)this.defaults.capture(task);}
|
|
31
|
+
ownsLegacyNotice(id){
|
|
32
|
+
if(!this.g.scheduler)return false;const run=/^job-(?:result|failed):(.+)$/.exec(id)?.[1];if(!run)return false;
|
|
33
|
+
const j=this.g.scheduler.jobs.db.prepare('SELECT j.task_id FROM runs r JOIN jobs j ON j.id=r.job_id WHERE r.id=?').get(run);
|
|
34
|
+
const track=j&&this.db.prepare('SELECT * FROM notification_tasks WHERE task_id=?').get(j.task_id);
|
|
35
|
+
return !!track&&!!this.g.scheduler.jobs.db.prepare("SELECT 1 FROM job_events WHERE seq>? AND json_extract(data,'$.run_id')=? AND type IN ('checkpoint','failed')").get(track.start_seq,run);
|
|
36
|
+
}
|
|
37
|
+
inventory(){return {items:[...this.config.values()].map(t=>({key:t.key,label:t.label,host:t.host,route_hash:t.route_hash,configured:true,publication:this.registry.publication(t.key),receipt_mode:t.route.receipt_mode,capability:t.host===this.g.c.role?this.endpoint.capabilities(t):{text_checked:'requires_peer_validation',files:false,images:false},consent:false})),historical_delivery:'unchanged unless explicitly adopted',no_default_recipient:!this.defaults.current()?.enabled,default_policy:this.defaults.view()};}
|
|
38
|
+
valid(b){
|
|
39
|
+
const t=b&&this.config.get(b.target_key);return !!b&&b.state==='enabled'&&this.defaults.valid(b)&&t?.route_hash===b.route_hash&&this.g.catalog.head(b.task_id).spec_revision===b.task_revision;
|
|
40
|
+
}
|
|
41
|
+
bind(node,a){
|
|
42
|
+
if(!a||!['local','cloud'].includes(node)||!text(a.event_id)||!text(a.task_id)||!Number.isInteger(a.expected_revision)||!Number.isInteger(a.expected_binding_revision)||a.expected_binding_revision<0||!['set','disable'].includes(a.action))throw Error('NOTIFICATION_BINDING_INVALID');
|
|
43
|
+
const sources=validSources(a.sources);if(!sources.length||sources.some(s=>s.role!==node)||!text(a.authorization_quote,2000)||!sources.some(s=>s.text.includes(a.authorization_quote)))throw Error('NOTIFICATION_DIRECT_USER_REQUIRED');
|
|
44
|
+
const target=a.action==='set'?this.config.get(a.target_key):null;if(a.action==='set'&&(!target||!a.authorization_quote.includes(target.label)))throw Error('NOTIFICATION_TARGET_NOT_AUTHORIZED');
|
|
45
|
+
const p=a.action==='set'?policy(a.policy):null,fp=digest({node,...a,sources,policy:p});
|
|
46
|
+
return tx(this.db,()=>{
|
|
47
|
+
const old=this.db.prepare('SELECT * FROM notification_binding_events WHERE event_id=?').get(a.event_id);if(old){if(old.fingerprint!==fp)throw Error('NOTIFICATION_EVENT_CONFLICT');return JSON.parse(old.result);}
|
|
48
|
+
const h=this.g.catalog.head(a.task_id),b=current(this.db,a.task_id);if(parseEnvelope(h.goal)?.notification_contract!==1)throw Error('NOTIFICATION_TASK_UPGRADE_REQUIRED');if(h.legacy||h.spec_revision!==a.expected_revision||(b?.revision??0)!==a.expected_binding_revision)throw Error('NOTIFICATION_REVISION_CONFLICT');
|
|
49
|
+
// A new task can explicitly opt out before its scheduled default is inherited.
|
|
50
|
+
this.track(a.task_id);const revision=(b?.revision??0)+1;
|
|
51
|
+
this.db.prepare('INSERT OR REPLACE INTO notification_bindings VALUES (?,?,?,?,?,?,?,?,?,?)').run(a.task_id,revision,h.spec_revision,target?.key??null,target?.route_hash??null,p?json(p):null,a.action==='set'?'enabled':'disabled',json({node,sources,authorization_quote:a.authorization_quote}),this.g.now(),this.g.scheduler?.jobs.db.prepare('SELECT coalesce(max(seq),0) n FROM job_events').get().n??0);
|
|
52
|
+
this.db.prepare("UPDATE task_notifications SET state='cancelled',error='NOTIFICATION_AUTHORIZATION_ENDED' WHERE task_id=? AND state IN ('queued','leased')").run(a.task_id);
|
|
53
|
+
const result={task_id:a.task_id,binding_revision:revision,state:a.action==='set'?'enabled':'disabled',target:target?{key:target.key,label:target.label,host:target.host,receipt_mode:target.route.receipt_mode}:null,policy:p,applies_to:'future events only',inflight_cannot_be_recalled:true};
|
|
54
|
+
this.db.prepare('INSERT INTO notification_binding_events VALUES (?,?,?)').run(a.event_id,fp,json(result));return result;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
render(job,event,label){
|
|
58
|
+
const h=this.g.catalog.head(job.task_id),data=JSON.parse(event.data),p=JSON.parse(job.policy),artifacts=this.g.artifacts?.list(job.task_id).items.filter(a=>a.run_id===(data.run_id??null)).slice(0,3)??[];
|
|
59
|
+
return ['【DSH 任务通知 · 状态快照】','任务:'+JSON.stringify(h.title),label,'记录时间:'+new Date(event.at).toISOString(),`任务指定模型:${p.provider??'未指定'} / ${p.model??'未指定'}${p.reasoningEffort?' / '+p.reasoningEffort:''}`,data.summary?'结果摘要:'+JSON.stringify(data.summary.slice(0,1200)):null,data.question?(event.type==='failed'?'需要你的决定:':'待补充:')+JSON.stringify(data.question.slice(0,700)):null,data.code?'错误:'+(/^[A-Z_]{1,90}$/.test(data.code)?data.code:'WORKER_FAILED'):null,data.code==='WORKER_MODEL_OUTPUT_LIMIT'?'原因:本次模型输出额度已耗尽(含思考);本批次未完成,已停止且未自动重试、增加预算或更换模型。':null,...artifacts.map(a=>'成果介绍:'+JSON.stringify({name:a.name,introduction:a.description??'暂无介绍',state:a.state})),artifacts.length?'成果入口:在本项目工作台按任务名称查看 Gitee 页面或执行会话;本条暂未提供手机可访问链接。':null,'这是批次/任务状态通知,不是审批凭据,不表示整个长期目标已完成;平台接受也不代表你已阅读。'].filter(Boolean).join('\n').slice(0,8000);
|
|
60
|
+
}
|
|
61
|
+
collect(){
|
|
62
|
+
if(!this.g.scheduler)return;const jobs=this.g.scheduler.jobs.db,cursor=this.db.prepare('SELECT cursor FROM notification_meta WHERE singleton=1').get().cursor;
|
|
63
|
+
for(const e of jobs.prepare('SELECT * FROM job_events WHERE seq>? ORDER BY seq LIMIT 100').all(cursor)){
|
|
64
|
+
const job=this.g.scheduler.jobs.get(e.job_id),track=this.db.prepare('SELECT * FROM notification_tasks WHERE task_id=?').get(job.task_id),parts=humanEvent(e.type,JSON.parse(e.data));
|
|
65
|
+
tx(this.db,()=>{
|
|
66
|
+
if(track&&e.seq>track.start_seq&&parts){
|
|
67
|
+
const [category,label]=parts,b=current(this.db,job.task_id),id='notification-event-'+e.seq;let disposition='no_authorized_target',deliveryId=null;
|
|
68
|
+
if(this.valid(b)&&e.seq>b.start_seq&&JSON.parse(b.policy).events.includes(category)){
|
|
69
|
+
const n=this.db.prepare("SELECT count(*) n FROM task_notifications n WHERE task_id=? AND (state IN ('queued','leased','dispatching') OR state='needs_review' AND coalesce((SELECT json_extract(record,'$.state') FROM notification_reviews WHERE notification_id=n.id ORDER BY revision DESC LIMIT 1),'open')<>'closed')").get(job.task_id).n;
|
|
70
|
+
if(n>=200)disposition='queue_limit';else{
|
|
71
|
+
this.db.prepare("UPDATE task_notifications SET state='cancelled',error='NOTIFICATION_SUPERSEDED_SNAPSHOT' WHERE task_id=? AND binding_revision=? AND category='progress' AND state IN ('queued','leased')").run(job.task_id,b.revision);
|
|
72
|
+
let due=this.g.now();if(category==='progress'){const last=this.db.prepare("SELECT max(dispatched_at) n FROM task_notifications WHERE task_id=? AND binding_revision=? AND category='progress' AND state IN ('accepted','dispatching')").get(job.task_id,b.revision).n;if(last!=null)due=Math.max(due,last+JSON.parse(b.policy).progress_interval_seconds*1000);}
|
|
73
|
+
deliveryId='notification-'+randomUUID();const target=this.config.get(b.target_key);
|
|
74
|
+
this.db.prepare("INSERT INTO task_notifications(id,task_id,binding_revision,target_key,host,route_hash,category,text,state,due,created) VALUES (?,?,?,?,?,?,?,?,'queued',?,?)").run(deliveryId,job.task_id,b.revision,b.target_key,target.host,b.route_hash,category,this.render(job,e,label),due,this.g.now());disposition='queued';
|
|
75
|
+
}
|
|
76
|
+
}else if(b)disposition=this.valid(b)?(e.seq<=b.start_seq?'before_authorization':'event_not_selected'):'authorization_stale_or_disabled';
|
|
77
|
+
this.db.prepare('INSERT OR IGNORE INTO task_notification_events VALUES (?,?,?,?,?,?)').run(id,job.task_id,category,e.at,disposition,deliveryId);
|
|
78
|
+
}
|
|
79
|
+
this.db.prepare('UPDATE notification_meta SET cursor=? WHERE singleton=1').run(e.seq);
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
lease(node){
|
|
84
|
+
if(!['local','cloud'].includes(node))throw Error('NOTIFICATION_ROLE_DENIED');
|
|
85
|
+
return tx(this.db,()=>{
|
|
86
|
+
const items=[];for(const r of this.db.prepare("SELECT * FROM task_notifications WHERE host=? AND state IN ('queued','leased','dispatching') AND due<=? ORDER BY rowid LIMIT 10").all(node,this.g.now())){
|
|
87
|
+
const b=current(this.db,r.task_id);if(r.state!=='dispatching'&&(!this.valid(b)||b.revision!==r.binding_revision)){this.db.prepare("UPDATE task_notifications SET state='cancelled',error='NOTIFICATION_AUTHORIZATION_ENDED' WHERE id=?").run(r.id);continue;}
|
|
88
|
+
if(r.category==='progress'&&r.state!=='dispatching'){
|
|
89
|
+
const last=this.db.prepare("SELECT max(dispatched_at) n FROM task_notifications WHERE task_id=? AND binding_revision=? AND category='progress' AND state IN ('accepted','dispatching') AND id<>?").get(r.task_id,r.binding_revision,r.id).n;
|
|
90
|
+
if(last!=null){const due=Math.max(r.due,last+JSON.parse(b.policy).progress_interval_seconds*1000);if(due>this.g.now()){this.db.prepare('UPDATE task_notifications SET due=? WHERE id=?').run(due,r.id);continue;}}
|
|
91
|
+
}
|
|
92
|
+
let payload=r.payload?JSON.parse(r.payload):null;if(!payload){payload={id:r.id,lease:randomUUID(),task_id:r.task_id,binding_revision:r.binding_revision,target_key:r.target_key,route_hash:r.route_hash,text:r.text,created:r.created};this.db.prepare("UPDATE task_notifications SET state='leased',lease=?,payload=? WHERE id=?").run(payload.lease,json(payload),r.id);}
|
|
93
|
+
items.push(payload);
|
|
94
|
+
}return {items};
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
row(node,a){const r=this.db.prepare('SELECT * FROM task_notifications WHERE id=?').get(a.id);if(!r||r.host!==node||r.lease!==a.lease||!r.lease)throw Error('NOTIFICATION_LEASE_MISMATCH');return r;}
|
|
98
|
+
authorize(node,a){
|
|
99
|
+
return tx(this.db,()=>{const r=this.row(node,a),b=current(this.db,r.task_id);if(!['leased','dispatching'].includes(r.state)||!this.valid(b)||b.revision!==r.binding_revision)return {allowed:false};this.db.prepare("UPDATE task_notifications SET state='dispatching',dispatched_at=coalesce(dispatched_at,?) WHERE id=?").run(this.g.now(),r.id);return {allowed:true,meaning:'dispatch boundary; later revocation cannot recall an external send'};});
|
|
100
|
+
}
|
|
101
|
+
waiting(node,a,media=false){
|
|
102
|
+
if(!/^NOTIFICATION_[A-Z_]{1,80}$/.test(a.reason??'')||!Number.isSafeInteger(a.retry_after_ms)||a.retry_after_ms<1000||a.retry_after_ms>300000||typeof a.safe_before_send!=='boolean')throw Error('NOTIFICATION_RECEIPT_INVALID');
|
|
103
|
+
const r=this.row(node,a);if((r.category==='artifact')!==media)throw Error('NOTIFICATION_RECEIPT_INVALID');if(r.result||terminal.has(r.state))return {recorded:false};
|
|
104
|
+
this.db.prepare('UPDATE task_notifications SET state=?,error=?,due=?,dispatched_at=? WHERE id=?').run(a.safe_before_send?'leased':r.state,a.reason,this.g.now()+a.retry_after_ms,a.safe_before_send?null:r.dispatched_at,r.id);return {recorded:true};
|
|
105
|
+
}
|
|
106
|
+
ack(node,a){
|
|
107
|
+
const value=outcome(a.result);return tx(this.db,()=>{const r=this.row(node,a);if(r.result){if(r.result!==json(value))throw Error('NOTIFICATION_RECEIPT_CONFLICT');return {recorded:true};}
|
|
108
|
+
if(value.state==='accepted'&&!['dispatching','media_dispatching'].includes(r.state))throw Error('NOTIFICATION_DISPATCH_REQUIRED');
|
|
109
|
+
this.db.prepare('UPDATE task_notifications SET state=?,result=?,message_id=?,error=? WHERE id=?').run(value.state,json(value),value.message_id??null,value.error??null,r.id);return {recorded:true};});
|
|
110
|
+
}
|
|
111
|
+
status(task){
|
|
112
|
+
this.g.store.task(task);const b=current(this.db,task);return {task_id:task,managed:!!this.db.prepare('SELECT 1 FROM notification_tasks WHERE task_id=?').get(task),binding:b?{source:JSON.parse(b.source).kind==='onboarding_default'?'onboarding_default':'explicit_task',revision:b.revision,task_revision:b.task_revision,state:b.state,effective:this.valid(b),target:this.config.get(b.target_key)?{key:b.target_key,label:this.config.get(b.target_key).label,host:this.config.get(b.target_key).host}:null,policy:b.policy?JSON.parse(b.policy):null}:null,deliveries:this.db.prepare('SELECT id,category,state,host,created,due,message_id,error,result FROM task_notifications WHERE task_id=? ORDER BY rowid DESC LIMIT 20').all(task).map(({result,...r})=>({...r,...(r.category==='artifact'?{artifact_delivery:this.media.dto(r.id)}:{}),review:this.review.summary(r.id),proof:result?JSON.parse(result).proof??null:null,waiting_reason:r.error??(['queued','media_queued'].includes(r.state)?(r.host==='local'?'NOTIFICATION_AWAITING_LOCAL_ENDPOINT':'NOTIFICATION_AWAITING_CLOUD_ENDPOINT'):['leased','media_leased'].includes(r.state)?'NOTIFICATION_ENDPOINT_PROCESSING':['dispatching','media_dispatching'].includes(r.state)?'NOTIFICATION_WAITING_FOR_RECEIPT':null)})),events:this.db.prepare('SELECT category,at,disposition FROM task_notification_events WHERE task_id=? ORDER BY rowid DESC LIMIT 10').all(task),meaning:'platform acceptance is not read receipt or execution approval'};
|
|
113
|
+
}
|
|
114
|
+
call(method,a,node){if(method==='notification_default_peer_discover'||method==='notification_default_peer_candidate')return this.defaults.inspectPeer(node,a,method==='notification_default_peer_candidate');if(method==='notification_default_publish')return this.defaults.publish(node,a);if(method==='notification_default_status')return this.defaults.view();if(method==='notification_media_wait'){if(a.safe_before_send!==false)throw Error('NOTIFICATION_RECEIPT_INVALID');return this.waiting(node,a,true);}if(method.startsWith('notification_media_')||method.startsWith('notification_artifact_'))return this.media.call(method,a,node);if(method==='notification_reconcile')return this.review.record(node,a);if(method==='notification_discover'){if(!a||Object.keys(a).some(k=>k!=='host')||a.host!==this.g.c.role)throw Error('NOTIFICATION_DISCOVERY_WRONG_HOST');return this.discovery.inspect();}if(method==='notification_target_add')return this.registry.add(node,a);if(method==='notification_target_publish')return this.registry.receive(node,a);if(method==='notification_targets')return this.inventory();if(method==='notification_bind')return this.bind(node,a);if(method==='notification_status')return this.status(a.task_id);if(method==='notification_pull')return this.lease(node);if(method==='notification_validate')return this.authorize(node,a);if(method==='notification_ack')return this.ack(node,a);if(method==='notification_wait')return this.waiting(node,a);throw Error('METHOD_DENIED');}
|
|
115
|
+
async artifactAccess(a){return this.g.maintenance?this.g.maintenance.run('notification_access',()=>this.artifactAccessCore(a)):this.artifactAccessCore(a);}
|
|
116
|
+
async artifactAccessCore(a){const r=await this.g.call('notification_artifact_access',a);return r.message_state==='needs_sender_host_check'&&r.sender_host===this.g.c.role?{...r,...await this.endpoint.media.access(a.notification_id,a.task_id)}:r;}
|
|
117
|
+
async tick(){
|
|
118
|
+
if(this.g.closed||this.g.maintenance?.blocked)return;
|
|
119
|
+
try{
|
|
120
|
+
await this.defaultSource?.();
|
|
121
|
+
await this.registry.sync();
|
|
122
|
+
if(this.g.store)this.collect();
|
|
123
|
+
// Avoid unrelated RPC traffic unless this endpoint is explicitly configured for notification delivery.
|
|
124
|
+
if(!this.endpoint.targets.size)return;
|
|
125
|
+
const batch=await this.g.call('notification_pull',{});
|
|
126
|
+
for(const e of batch.items){if(this.g.closed)break;const result=await this.endpoint.execute(e,a=>this.g.call('notification_validate',a));if(terminal.has(result.state))await this.g.call('notification_ack',{id:e.id,lease:e.lease,result});else if(result.state==='waiting')await this.g.call('notification_wait',{id:e.id,lease:e.lease,reason:result.reason,retry_after_ms:Math.max(1000,Math.min(300000,(result.next_at??this.g.now()+10000)-this.g.now())),safe_before_send:result.reason!=='NOTIFICATION_IN_FLIGHT'});}
|
|
127
|
+
await this.endpoint.media.tick();
|
|
128
|
+
this.lastError=this.endpoint.media.lastError;
|
|
129
|
+
}catch(e){this.lastError=/^(NOTIFICATION_|CAPABILITY_|PROTOCOL_|COORDINATOR_)[A-Z_]+$/.test(e.message)?e.message:'NOTIFICATION_TRANSPORT_UNAVAILABLE';}
|
|
130
|
+
}
|
|
131
|
+
async close(){await this.endpoint.close();}
|
|
132
|
+
}
|