Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ __pycache__/
.DS_Store

.netlify/

plugin/node_modules/
plugin/.vercel/
50 changes: 50 additions & 0 deletions plugin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Draw One · ChatGPT Plugin 私人測試版

只使用產品既有的 260 支籤與來源欄位。沒有 AI 解讀、神諭、反思對話、付費功能或私有研究內容。

## 啟動與檢查

Node.js 22 或以上。從本目錄執行:

```sh
npm ci
npm run build
npm test
npm start
```

本機 MCP:`http://127.0.0.1:8787/mcp`。`npm run build` 先跑原有 fail-closed 建置,再以固定欄位白名單產生公開籤池與最小報告,並複製抽籤規則;啟動時再次核對籤池 SHA-256。資料改動後必須重新建置。

## 資料與隱私

問題留在 widget 的 browser localStorage(空白問題使用 sessionStorage),沿用產品 `draw-policy.js` 的一事一籤與跨籤系不重抽規則。問題不送往 MCP;伺服器不保存使用者資料。ChatGPT 中使用者自己輸入的對話仍由 ChatGPT 處理。MCP 工具結果會提供籤詩原文、版本名稱與核對狀態給 ChatGPT;不提供 source_locator、edition_id、source_file、source_sha256、研究定位與校勘帳本。

此版本沒有帳號或跨装置同步;不同裝置、儲存分區或清除資料後不共享綁定。若宿主禁用瀏覽器儲存,只能保留當次 widget 的記憶體綁定,介面會提示。抽籤工具 `draw_one_slip` 與取回工具 `get_draw_one_slip` 設為 app-only;模型使用 `open_draw_one_temple` 開啟介面,使用者自行按抽籤。

工具保留 `VERIFIED`、`PROBABLE`,介面顯示「已對勘/待複核」,不把抄錄狀態轉成神明或預言的可信度。`interpretation` 保持 null,Astra 未審核的反思文字不接入。

## 部署與 ChatGPT 接入

部署只上傳本 `plugin/` 目錄到獨立 Node.js Vercel 專案,使用 `api/mcp.mjs` 與 `vercel.json`。不要更動原網站專案或 production 分支;不要上傳整個 repo 或私有研究。

需要一個 ChatGPT 能存取的 HTTPS `/mcp` 端點;Vercel 登入保護的 preview URL 不能直接供 ChatGPT 使用。測試端點僅提供既有公開籤資料,沒有帳號或秘密資料,沒有認證。

取得 HTTPS URL 後,在 ChatGPT Settings → Security and login 開啟 Developer mode,到 Plugins 加入 MCP 連線。名稱 Draw One,描述「抽一支籤,閱讀原文、版本與來源狀態」。開新對話選用 Plugin,輸入「開啟 Draw One」。

官方接入:https://developers.openai.com/plugins/build/app-quickstart

## 驗證邊界

MCP HTTP 測試可在本機完成。真正 ChatGPT iframe、host bridge、儲存分區及工具 app-only 限制必須在 ChatGPT 測一次後才能宣稱完成接入。公開目錄提交、隱私政策與正式發布另行審閱。

## 已部署的測試端點(2026-10-03)

`https://draw-one-plugin-mvp.vercel.app/mcp` 已以外部 SDK 完成三籤系的工具探索與抽籤測試。獨立 Vercel 專案為 `draw-one-plugin-mvp`,首次部署由 Vercel 指派為該專案的 production;它不是原 Draw One 網站,也不是公開目錄發布。公開提交仍需身份、政策頁、支援頁、圖示、5+3測試案例、影片與域名驗證。

## 原版宮廟、籤紙與分享(2026-10-03 修正)

`build-arrival.mjs` 從 `paper/arrival.html` 直接建置 MCP widget,內嵌原版 `assets/slip.css` 與 `assets/slip-render.js`,保留山門、天氣票、轉身廟埕、三殿、向上抽籤、取紙、私人籤簿、筆記與帶走籤紙。僅改宿主/資料接縫;原網站檔案不動。抽籤明確手勢呼叫 app-only MCP,問題與笔記留在本機。

分享圖只包含原籤紙與日期節氣,不包含問題與筆記。圖片備妥後,由使用者再次點儲存或分享,以保留宿主要求的明確操作;宿主可能限制下載/原生分享。長簽條輸出量測避免頂端裁切。

Noto Serif TC 所需公開字形已內嵌,附 OFL 授權;原 TC 缺的單一字形「幷」以 Noto Serif SC 補齊(僅該字);介面與分享產圖不再向 Google Fonts 發送請求。CSP 的 connectDomains/resourceDomains 都為空。沒有載入歷史解曰/私有研究或 Astra 反思。
1 change: 1 addition & 0 deletions plugin/api/mcp.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { handler as default } from '../server.mjs';
89 changes: 89 additions & 0 deletions plugin/build-arrival.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import {readFileSync,writeFileSync} from 'node:fs';
const root=new URL('../',import.meta.url),read=p=>readFileSync(new URL(p,root),'utf8');
let html=read('paper/arrival.html');
html=html.replace('<link rel="preconnect" href="https://fonts.googleapis.com" />','');
html=html.replace(/<link href="https:\/\/fonts.googleapis.com[^>]+>/,()=>'<style>'+read('plugin/data/slip-fonts.css')+'</style>');
html=html.replace('<link rel="stylesheet" href="../assets/slip.css?v=3" />','<style>'+read('assets/slip.css')+'</style>');
for(const [file,body] of [['oracles.draw-pool.js',read('plugin/data/oracles.draw-pool.js')],['draw-policy.js',read('assets/draw-policy.js')],['slip-render.js',read('assets/slip-render.js')]]) html=html.replace(`<script src="../assets/${file}?v=3"></script>`,()=>'<script>'+body.replaceAll('</script','<\\/script')+'</script>');
html=html.replace(/<script src="\.\.\/assets\/(interpretation-pool\.guanyin|jieyue-guard)\.js\?v=1"><\/script>\n/g,'');
const bridge=`<script>
window.DRAW_ONE_HOST=(function(){let seq=0;let capabilities={};const pending=new Map();
const rpc=(method,params)=>new Promise((resolve,reject)=>{const id=++seq;const timer=setTimeout(()=>{pending.delete(id);reject(Error('連線逾時,請稍後再試。'));},20000);pending.set(id,{resolve,reject,timer});parent.postMessage({jsonrpc:'2.0',id,method,params},'*');});
addEventListener('message',e=>{if(e.source!==parent||e.data?.jsonrpc!=='2.0')return;const m=e.data,p=pending.get(m.id);if(p){clearTimeout(p.timer);pending.delete(m.id);m.error?p.reject(Error('連線失敗,請稍後再試。')):p.resolve(m.result);}});
const ready=rpc('ui/initialize',{appInfo:{name:'draw-one',version:'0.1.0'},appCapabilities:{},protocolVersion:'2026-01-26'}).then(r=>{capabilities=r.hostCapabilities??{};parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/initialized',params:{}},'*');});
ready.catch(()=>{});
return{ready,canDownload:()=>Boolean(capabilities.downloadFile),download:contents=>rpc('ui/download-file',{contents}),async tool(name,args){await ready;const r=await rpc('tools/call',{name,arguments:args});if(r.isError||!r.structuredContent)throw Error('暫時無法取得籤詩。');return r.structuredContent;}};})();
</script>`;
html=html.replace('<script>\n/* ==================== sound-layer:begin',()=>bridge+'\n<script>\n/* ==================== sound-layer:begin');
const start=html.indexOf(' function completeDraw() {'),end=html.indexOf('\n $("jieyueToggle")',start);
if(start<0||end<0)throw Error('Arrival draw seam changed');
html=html.slice(0,start)+` let hostDrawing = false;
async function completeDraw() {
if(hostDrawing) return;
hostDrawing=true;
const question=$("question").value, corpusId=currentHall.corpusId;
try {
const bound=window.DRAW_POLICY.peekBinding({question});
const result=bound ? await window.DRAW_ONE_HOST.tool('get_draw_one_slip',{entry_id:bound.entryId}) : await window.DRAW_ONE_HOST.tool('draw_one_slip',{corpus_id:corpusId});
if(bound) currentResolved={entryId:bound.entryId,repeated:true};
else currentResolved=window.DRAW_POLICY.resolveDraw({question,corpusId,drawFn:()=>result.entry});
const entry=POOL.entries.find(e=>e.id===currentResolved.entryId);
if(!entry)throw Error('找不到這支籤。');
if (navigator.vibrate) navigator.vibrate(16);
window.ARRIVAL_SOUND?.stickOut();
$("tubeStage").style.display="none";
$("stickLabel").textContent=window.SLIP_RENDER.tabText(entry);
$("stickStage").style.display="flex";
$("stickStage").scrollIntoView({behavior:reduceMotion?"auto":"smooth",block:"center"});
}catch(error){$("presentQ").textContent=error.message+' 請稍後再試。';resetStick();}
finally{hostDrawing=false;}
}
`+html.slice(end);
html=html.replace('<textarea id="question" rows="1"','<textarea id="question" maxlength="2000" rows="1"');
// Preserve notes during this opening when browser storage is unavailable.
html=html.replace(' const store = {', ' const localMemory=new Map();\n const store = {');
html=html.replace('get: (k, f) => { try {', 'get: (k, f) => { if(localMemory.has(k))return localMemory.get(k); try {');
html=html.replace('catch { return f; } },','catch { return localMemory.get(k) ?? f; } },');
html=html.replace('set: (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} },','set: (k, v) => { localMemory.set(k,v); try { localStorage.setItem(k, JSON.stringify(v)); } catch {} },');
html=html.replace(' renderJieyue(entry);',' if($("sharePreview")) $("sharePreview").hidden=true;\n renderJieyue(entry);');
html=html.replace('<div class="ask-label">今天想問什麼</div>', '<div class="ask-label">今天想問什麼</div><p id="localPrivacy" style="font-size:11px;line-height:1.7;color:var(--ink-soft)">問題與籤簿留在本機,不傳送到抽籤服務。</p>');
// Local font bytes are shared by the page and exported SVG; no external fetch.
const fontStart=html.indexOf(' async function inlineFontCss(text) {');
const fontEnd=html.indexOf(' async function renderTakeawayPng',fontStart);
if(fontStart<0||fontEnd<0)throw Error('Font export seam changed');
html=html.slice(0,fontStart)+' async function inlineFontCss() { return '+JSON.stringify(read('plugin/data/slip-fonts.css'))+'; }\n'+html.slice(fontEnd);
// Export must include the full protruding label even for long Chinese numbers.
html=html.replace(' window.SLIP_RENDER.mountSlip(art, entry);', ' await document.fonts.ready;\n window.SLIP_RENDER.mountSlip(art, entry);\n const labelTop=art.querySelector(".slip-tab").getBoundingClientRect().top-art.getBoundingClientRect().top;\n if(labelTop<10) art.style.paddingTop=(parseFloat(getComputedStyle(art).paddingTop)+10-labelTop)+"px";');
html=html.replace('<textarea id="noteInput"', '<textarea id="noteInput" maxlength="2000"');
// Clipboard fallback remains user-controlled and contains only public slip text.
html=html.replace(' $("copyBtn").textContent = "複製失敗";', ' $("copyBtn").textContent = "請選取籤文複製";\n let output=document.getElementById("copySlipText");if(!output){output=document.createElement("textarea");output.id="copySlipText";output.readOnly=true;output.style.cssText="width:100%;min-height:160px;margin-top:12px";output.setAttribute("aria-label","可複製的籤文,不含私人問題或筆記");$("takeawayZone").appendChild(output);}output.value=text;output.hidden=false;output.focus();output.select();');
html=html.replace(' if($("sharePreview")) $("sharePreview").hidden=true;', ' if($("sharePreview")) $("sharePreview").hidden=true;\n if($("copySlipText")) $("copySlipText").hidden=true;');
// Explicit save/share gesture for host user-activation limits.
html=html.replace('<button class="takeaway-btn" id="copyBtn">複製籤文</button>', '<button class="takeaway-btn" id="copyBtn">複製籤文</button><div id="sharePreview" hidden><img id="shareImage" alt="可帶走的籤紙,只有籤詩與版記" style="width:100%;max-width:360px"><a id="saveImage" class="takeaway-btn" download="draw-one-slip.png">儲存籤紙圖片</a><button id="shareImageBtn" class="takeaway-btn" hidden>分享籤紙圖片</button><p style="font-size:12px;line-height:1.8">分享不包含問題與筆記。若宿主限制下載,可長按圖片儲存。</p></div>');
const shareStart=html.indexOf(' if (navigator.canShare?.({ files: [file] })) {');
const shareEnd=html.indexOf(' btn.textContent = orig;',shareStart);
if(shareStart<0||shareEnd<0)throw Error('Share seam changed');
html=html.slice(0,shareStart)+` if(window.drawOneShareUrl) URL.revokeObjectURL(window.drawOneShareUrl);
const url=URL.createObjectURL(blob);window.drawOneShareUrl=url;
$("shareImage").src=url;$("saveImage").href=url;$("sharePreview").hidden=false;
$("saveImage").onclick=async event=>{
if(!window.DRAW_ONE_HOST.canDownload())return;
event.preventDefault();
try{
const bytes=new Uint8Array(await blob.arrayBuffer());let binary="";
for(let i=0;i<bytes.length;i+=0x8000)binary+=String.fromCharCode(...bytes.subarray(i,i+0x8000));
const exported=await window.DRAW_ONE_HOST.download([{type:"resource",resource:{uri:"file:///draw-one-slip.png",mimeType:"image/png",blob:btoa(binary)}}]);
$("saveImage").textContent=exported.isError?"未儲存,可再試一次":"已交給宿主儲存";
}catch{$("saveImage").textContent="宿主未提供下載,可長按圖片儲存";}
};
$("shareImageBtn").hidden=!navigator.canShare?.({files:[file]});
$("shareImageBtn").onclick=async()=>{try{await navigator.share({files:[file]});}catch(e){if(e.name!=="AbortError")$("shareImageBtn").textContent="請改用儲存圖片";}};
$("sharePreview").scrollIntoView({block:"nearest",behavior:reduceMotion?"auto":"smooth"});
`+html.slice(shareEnd);
html=html.replace('</body>',`<script>
const enter=document.getElementById('enterBtn');enter.disabled=true;
try{localStorage.setItem('drawone.storage-check','1');localStorage.removeItem('drawone.storage-check');}catch{document.getElementById('localPrivacy').textContent='目前宿主無法保存資料;問題、籤與筆記只保留在這次開啟中。';}
window.DRAW_ONE_HOST.ready.then(()=>{enter.disabled=false;}).catch(()=>{enter.textContent='連接未完成,請重新開啟';});
</script></body>`);
writeFileSync(new URL('public/widget.html',import.meta.url),html);
console.log('Original Arrival + Slip bundled; public pool only; MCP draw bridge.');
19 changes: 19 additions & 0 deletions plugin/build.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { execFileSync } from 'node:child_process';
import { copyFileSync,mkdirSync,readFileSync,writeFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
const root=new URL('../',import.meta.url);
execFileSync(process.execPath,['scripts/build-draw-pool.mjs'],{cwd:root,stdio:'inherit'});
const data=new URL('data/',import.meta.url);
mkdirSync(data,{recursive:true});
const raw=readFileSync(new URL('assets/oracles.draw-pool.js',root),'utf8');
const canonical=JSON.parse(raw.slice(raw.indexOf('{'),raw.lastIndexOf('}')+1));
// Explicit public projection: reviewed poems and edition/status only.
const pool={schema:canonical.schema,content_version:canonical.content_version,
corpora:canonical.corpora.map(c=>({corpus_id:c.corpus_id,deity_tradition:c.deity_tradition,edition_title:c.edition_title,slip_count:c.slip_count})),
entries:canonical.entries.map(e=>({id:e.id,corpus_id:e.corpus_id,deity_tradition:e.deity_tradition,slip_number:e.slip_number,original_slip_label:e.original_slip_label,historical_text:{poem_text:e.historical_text.poem_text},provenance:{edition_title:e.provenance.edition_title,transcription_status:e.provenance.transcription_status},interpretation:null}))};
const artifact='window.DRAW_POOL = '+JSON.stringify(pool,null,2)+';\n';
writeFileSync(new URL('oracles.draw-pool.js',data),artifact);
writeFileSync(new URL('draw-pool.report.json',data),JSON.stringify({status:'PASSED',content_version:pool.content_version,total_entries:pool.entries.length,pool_sha256:createHash('sha256').update(artifact).digest('hex')},null,2)+'\n');
copyFileSync(new URL('assets/draw-policy.js',root),new URL('draw-policy.js',data));

await import('./build-arrival.mjs');
94 changes: 94 additions & 0 deletions plugin/data/Noto-Serif-TC-OFL.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
Copyright 2012 Google Inc. All Rights Reserved.

This Font Software is licensed under the SIL Open Font License,
Version 1.1.

This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL

-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to
provide a free and open framework in which fonts may be shared and
improved in partnership with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software
components as distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to,
deleting, or substituting -- in part or in whole -- any of the
components of the Original Version, by changing formats or by porting
the Font Software to a new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed,
modify, redistribute, and sell modified and unmodified copies of the
Font Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created using
the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Loading
Loading