@tocca-systems/twp-cli 0.156.0 → 0.157.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.public.md +20 -0
  2. package/README.md +48 -6
  3. package/dist/{agent-K5CM2ADZ.js → agent-4WDXNDAE.js} +2 -2
  4. package/dist/{api-command-P4PDKC6C.js → api-command-CJAM6OAW.js} +2 -2
  5. package/dist/{app-RHL2RZNY.js → app-DCYPYYNJ.js} +4 -4
  6. package/dist/auto-update-TGFTGKZ7.js +4 -0
  7. package/dist/{auto-update-worker-TN322W34.js → auto-update-worker-KOEK5UOF.js} +1 -1
  8. package/dist/{brief-R2VU6PZG.js → brief-3HZF4XP4.js} +3 -3
  9. package/dist/{chunk-CH6QU76P.js → chunk-2ZATYMAP.js} +9 -8
  10. package/dist/chunk-3WPPJAUV.js +11 -0
  11. package/dist/{chunk-XAELSVIW.js → chunk-5Y7J67GZ.js} +1 -1
  12. package/dist/{chunk-6NJSB2SM.js → chunk-BYVLEHIR.js} +2 -2
  13. package/dist/chunk-E5UWM6RN.js +16 -0
  14. package/dist/{chunk-XYCZIUWI.js → chunk-HKRXWMFL.js} +10 -10
  15. package/dist/chunk-NS5IXKNS.js +87 -0
  16. package/dist/{chunk-LUDJADHM.js → chunk-O5MM2H7Y.js} +1 -1
  17. package/dist/{chunk-X2C2UVJA.js → chunk-OC3ZWSLV.js} +114 -99
  18. package/dist/{chunk-II7WTCSK.js → chunk-PPFOHHCG.js} +1 -1
  19. package/dist/{chunk-IH2VB7DE.js → chunk-TEIPWYN5.js} +1 -1
  20. package/dist/{chunk-K2IBOGCW.js → chunk-UFYPNT63.js} +1 -1
  21. package/dist/{chunk-WFONEPVZ.js → chunk-USCXNODU.js} +1 -1
  22. package/dist/cli.js +15 -15
  23. package/dist/{commands-CS3NQGRL.js → commands-AMDDRNK5.js} +1 -1
  24. package/dist/{commands-AX5NY7CE.js → commands-HCCNBFET.js} +4 -4
  25. package/dist/{commands-XSYIAAWN.js → commands-ZDUMIOPM.js} +1 -1
  26. package/dist/{company-IBFYPT24.js → company-GRSSG4SL.js} +2 -2
  27. package/dist/{contract-R6LTDOSM.js → contract-AREETV45.js} +2 -2
  28. package/dist/{corporate-BFCZA2SM.js → corporate-ZQJNHB6V.js} +2 -2
  29. package/dist/{estimate-SMPPKNDS.js → estimate-T574Z36D.js} +2 -2
  30. package/dist/{github-U3LQ2EMQ.js → github-7JKUASZV.js} +1 -1
  31. package/dist/{github-git-BFY5LRO4.js → github-git-GNLFJ62J.js} +2 -2
  32. package/dist/{invoice-O2WWX5G5.js → invoice-IX5FU4TI.js} +2 -2
  33. package/dist/{leave-2MTVFD5J.js → leave-GLDEWTN3.js} +2 -2
  34. package/dist/{media-TR4DPGIL.js → media-MW4ODRIA.js} +2 -2
  35. package/dist/oneshot-2EGSVWYY.js +81 -0
  36. package/dist/{purchase-ECXYTHDQ.js → purchase-XEGPTJTC.js} +2 -2
  37. package/dist/{registry-2SFZPFCO.js → registry-AUKMFLAC.js} +1 -1
  38. package/dist/{run-GIXUKZEL.js → run-4IJVCICM.js} +2 -2
  39. package/dist/{sales-ai-review-KGENFLSE.js → sales-ai-review-CY7Q5INT.js} +2 -2
  40. package/dist/{sales-master-MRUDSFL3.js → sales-master-G3YBPLM4.js} +1 -1
  41. package/dist/{update-76KTMGPX.js → update-CYCZAQEL.js} +1 -1
  42. package/dist/{user-UMZPKXZN.js → user-U2ZYY5HL.js} +1 -1
  43. package/dist/{worker-agent-5V3NJUWK.js → worker-agent-HRLO7WMJ.js} +2 -2
  44. package/dist/{workflow-VRC7KPHT.js → workflow-KKFOS44P.js} +2 -2
  45. package/package.json +1 -1
  46. package/dist/auto-update-FXXQHBV5.js +0 -4
  47. package/dist/chunk-CASLLD23.js +0 -78
  48. package/dist/chunk-ITFO5GPX.js +0 -9
  49. package/dist/chunk-UQP47QOV.js +0 -15
  50. package/dist/oneshot-MI5TBYKH.js +0 -46
@@ -1,9 +1,9 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{inspectCaseDocumentFile}from"./chunk-LUDJADHM.js";import{FORCE_FLAG,OUT_FLAG,REV_FLAG,revOf,singleId,uploadStaged}from"./chunk-XAELSVIW.js";import"./chunk-TW4KANHY.js";import{purchaseNoRuleResource}from"./chunk-C5DVOHEN.js";import{salesAdminForbidden}from"./chunk-4JVYGPUT.js";import"./chunk-OMW6BBAY.js";import"./chunk-ITTQEOIF.js";import"./chunk-GNSZOYBQ.js";import{purchasePdfOperation}from"./chunk-HIIEA3AN.js";import{featureLicenseGuidance,
3
+ import{inspectCaseDocumentFile}from"./chunk-O5MM2H7Y.js";import{FORCE_FLAG,OUT_FLAG,REV_FLAG,revOf,singleId,uploadStaged}from"./chunk-5Y7J67GZ.js";import"./chunk-TW4KANHY.js";import{purchaseNoRuleResource}from"./chunk-C5DVOHEN.js";import{salesAdminForbidden}from"./chunk-4JVYGPUT.js";import"./chunk-OMW6BBAY.js";import"./chunk-ITTQEOIF.js";import"./chunk-GNSZOYBQ.js";import{purchasePdfOperation}from"./chunk-HIIEA3AN.js";import{featureLicenseGuidance,
4
4
  licenseForbidden}from"./chunk-N3UDILK7.js";import{createFlags,fieldBody,hasAnyField,updateFlags}from"./chunk-RJRQ6EAH.js";import{booleanText,boundedText,isoDate}from"./chunk-CHT6EP5C.js";import{readBody}from"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import{repeatedValues}from"./chunk-6NHLWYI2.js";import{SALES_PURCHASES_PATH,SALES_PURCHASE_AI_MAPPINGS_PATH,isExactNumericId,resolveNamed}from"./chunk-QLH5IJQV.js";import{
5
5
  ApiError}from"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import{LIST_PAGING_HELP,PAGE_NUMBER_LIST_FLAGS,PAGE_NUMBER_PAGING_HELP,STABLE_PAGE_ORDER,nonEmpty,pageNumberPaging,pageNumberQuery,pageRangeNotes}from"./chunk-TDO6V3ZW.js";import{requireResolved,withResolved}from"./chunk-7DCWZ2NF.js";import{acknowledgement,isRecord,pick}from"./chunk-HCTPCUST.js";import{ApiResponseError,
6
- UsageError}from"./chunk-STILP3Z6.js";import"./chunk-RMFLTSOV.js";import{NotLoggedInError,SessionExpiredError}from"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var PATH=SALES_PURCHASE_AI_MAPPINGS_PATH;var LABEL="\u4ED5\u5165AI\u30DE\u30C3\u30D4\u30F3\u30B0";var SOURCE_LABEL_MAX_CHARS=255;var NOTE_MAX_CHARS=1e3;var SORT_MAX=2147483647;var LIST_COLUMNS=["id","source_label","target_field","target_field_label","company_name","is_active","sort_order"];var GET_COLUMNS=[...LIST_COLUMNS,"company_id","note"];var MEMBER_FORBIDDEN=licenseForbidden(featureLicenseGuidance("\u8CA9\u58F2\u7BA1\u7406"));var ADMIN_FORBIDDEN=salesAdminForbidden(`${LABEL}\u306E\u524A\u9664`);
6
+ UsageError}from"./chunk-STILP3Z6.js";import"./chunk-RMFLTSOV.js";import{NotLoggedInError,SessionExpiredError}from"./chunk-3WPPJAUV.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var PATH=SALES_PURCHASE_AI_MAPPINGS_PATH;var LABEL="\u4ED5\u5165AI\u30DE\u30C3\u30D4\u30F3\u30B0";var SOURCE_LABEL_MAX_CHARS=255;var NOTE_MAX_CHARS=1e3;var SORT_MAX=2147483647;var LIST_COLUMNS=["id","source_label","target_field","target_field_label","company_name","is_active","sort_order"];var GET_COLUMNS=[...LIST_COLUMNS,"company_id","note"];var MEMBER_FORBIDDEN=licenseForbidden(featureLicenseGuidance("\u8CA9\u58F2\u7BA1\u7406"));var ADMIN_FORBIDDEN=salesAdminForbidden(`${LABEL}\u306E\u524A\u9664`);
7
7
  function usageOf(op){return`twp purchase ai-mapping ${op} help`}function text(value){return typeof value==="string"||typeof value==="number"?String(value):""}function envelope(body,what){if(!isRecord(body)||body["result"]!==true)throw new ApiResponseError(`${what}\u306E\u5FDC\u7B54\u306E\u5F62\u304C\u60F3\u5B9A\u3068\u9055\u3044\u307E\u3059\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`);return body}function recordOf(body){const data=envelope(body,LABEL)["da\
8
8
  ta"];if(!isRecord(data)||typeof data["id"]!=="string")throw new ApiResponseError(`${LABEL}\u306E\u5FDC\u7B54\u306B data.id \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`);return data}function serverMessage(body){const message=isRecord(body)?body["message"]:void 0;return typeof message==="string"&&message!==""?[message]:[]}function idArg(input,op){const[raw,...rest]=input.args;const id=raw?.trim()??"";if(id==="")throw new UsageError(
9
9
  `${LABEL}\u306E ID \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`,usageOf(op));if(rest.length>0)throw new UsageError(`\u4F59\u5206\u306A\u5F15\u6570\u304C\u3042\u308A\u307E\u3059: ${rest.join(" ")}`,usageOf(op));if(!isExactNumericId(id))throw new UsageError(`${LABEL}\u306E ID \u306F\u5148\u982D\u306B 0 \u3092\u4ED8\u3051\u306A\u3044\u6570\u5B57\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${id}`,"ID \u306F twp purchase ai-mapping list \u306E id \u5217\u3067\u3059\u3002");return id}
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{loadDomain}from"./chunk-XYCZIUWI.js";import"./chunk-VSJBJXZO.js";export{loadDomain};
3
+ import{loadDomain}from"./chunk-HKRXWMFL.js";import"./chunk-VSJBJXZO.js";export{loadDomain};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{CURATED_PAGING_VOCABULARY,PAGING_RETRY_WAIT_SECONDS,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,pagingClock,reportError,requiresYes,resolvePaging,runDomain}from"./chunk-6NJSB2SM.js";import"./chunk-XYCZIUWI.js";import"./chunk-PAJAEUPA.js";import"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";
4
- import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-TDO6V3ZW.js";import"./chunk-HCTPCUST.js";import"./chunk-STILP3Z6.js";import"./chunk-TZL2342W.js";import"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-F3UL5POS.js";import"./chunk-OKATZ4SN.js";
3
+ import{CURATED_PAGING_VOCABULARY,PAGING_RETRY_WAIT_SECONDS,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,pagingClock,reportError,requiresYes,resolvePaging,runDomain}from"./chunk-BYVLEHIR.js";import"./chunk-HKRXWMFL.js";import"./chunk-PAJAEUPA.js";import"./chunk-P4QSPSOQ.js";import"./chunk-Q3B65OFC.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";
4
+ import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-TDO6V3ZW.js";import"./chunk-HCTPCUST.js";import"./chunk-STILP3Z6.js";import"./chunk-TZL2342W.js";import"./chunk-3WPPJAUV.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-F3UL5POS.js";import"./chunk-OKATZ4SN.js";
5
5
  import"./chunk-RKBUJKI5.js";import"./chunk-UREA4ZIG.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";export{CURATED_PAGING_VOCABULARY,PAGING_RETRY_WAIT_SECONDS,buildPrepareContext,checkOutTarget,exitCodeFor,fetchAllPages,outputValue,pagingClock,reportError,requiresYes,resolvePaging,runDomain};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{CRITERION_RE,WAIT_POLL_INTERVAL_MS,aiReviewReasonDomain,checkCounts,checksOf,contractAiReviewResources,envelope,estimateAiReviewResources,hasReferencedReason,invoiceAiReviewResources,reasonsMap,reviewOf,withoutResult}from"./chunk-IH2VB7DE.js";import"./chunk-HIIEA3AN.js";import"./chunk-N3UDILK7.js";import"./chunk-CHT6EP5C.js";import"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";
4
- import"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-TDO6V3ZW.js";import"./chunk-7DCWZ2NF.js";import"./chunk-HCTPCUST.js";import"./chunk-STILP3Z6.js";import"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";
3
+ import{CRITERION_RE,WAIT_POLL_INTERVAL_MS,aiReviewReasonDomain,checkCounts,checksOf,contractAiReviewResources,envelope,estimateAiReviewResources,hasReferencedReason,invoiceAiReviewResources,reasonsMap,reviewOf,withoutResult}from"./chunk-TEIPWYN5.js";import"./chunk-HIIEA3AN.js";import"./chunk-N3UDILK7.js";import"./chunk-CHT6EP5C.js";import"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";
4
+ import"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-TDO6V3ZW.js";import"./chunk-7DCWZ2NF.js";import"./chunk-HCTPCUST.js";import"./chunk-STILP3Z6.js";import"./chunk-3WPPJAUV.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";
5
5
  import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";export{CRITERION_RE,WAIT_POLL_INTERVAL_MS,aiReviewReasonDomain,checkCounts,checksOf,contractAiReviewResources,envelope,estimateAiReviewResources,hasReferencedReason,invoiceAiReviewResources,reasonsMap,reviewOf,withoutResult};
@@ -2,7 +2,7 @@ import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
3
  import{salesAdminForbidden}from"./chunk-4JVYGPUT.js";import"./chunk-OMW6BBAY.js";import{inspectLocalFile,isCommitted,issued}from"./chunk-ITTQEOIF.js";import{checkUploadQuota}from"./chunk-GNSZOYBQ.js";import{featureLicenseGuidance,licenseForbidden}from"./chunk-N3UDILK7.js";import{boundedText,isoDate}from"./chunk-CHT6EP5C.js";import{readBody}from"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import{repeatedValues}from"./chunk-6NHLWYI2.js";
4
4
  import{SALES_BUSINESS_PLACES_PATH,SALES_PAYEES_PATH,SALES_SEAL_IMPRESSIONS_PATH,isExactNumericId}from"./chunk-QLH5IJQV.js";import{ApiError}from"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import{LIST_PAGING_HELP,PAGE_NUMBER_LIST_FLAGS,nonEmpty,pageNumberPaging,pageNumberQuery,pageRangeNotes}from"./chunk-TDO6V3ZW.js";import{requireResolved,withResolved}from"./chunk-7DCWZ2NF.js";
5
- import{acknowledgement,isRecord,pick}from"./chunk-HCTPCUST.js";import{ApiResponseError,UsageError}from"./chunk-STILP3Z6.js";import"./chunk-RMFLTSOV.js";import{NotLoggedInError,SessionExpiredError}from"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";import fs from"fs";import path from"path";var SORT_MAX=2147483647;var SALES_FORBIDDEN=licenseForbidden(featureLicenseGuidance("\u8CA9\u58F2\u7BA1\u7406"));function envelope(body,what){if(!isRecord(body)||body["result"]!==true)throw new ApiResponseError(`${what}\u306E\u5FDC\u7B54\u306E\u5F62\u304C\u60F3\u5B9A\u3068\u9055\u3044\u307E\u3059\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`);return body}function recordOf(body,what){const data=envelope(body,what)["data"];if(!isRecord(data)||typeof data["id"]!==
5
+ import{acknowledgement,isRecord,pick}from"./chunk-HCTPCUST.js";import{ApiResponseError,UsageError}from"./chunk-STILP3Z6.js";import"./chunk-RMFLTSOV.js";import{NotLoggedInError,SessionExpiredError}from"./chunk-3WPPJAUV.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";import fs from"fs";import path from"path";var SORT_MAX=2147483647;var SALES_FORBIDDEN=licenseForbidden(featureLicenseGuidance("\u8CA9\u58F2\u7BA1\u7406"));function envelope(body,what){if(!isRecord(body)||body["result"]!==true)throw new ApiResponseError(`${what}\u306E\u5FDC\u7B54\u306E\u5F62\u304C\u60F3\u5B9A\u3068\u9055\u3044\u307E\u3059\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`);return body}function recordOf(body,what){const data=envelope(body,what)["data"];if(!isRecord(data)||typeof data["id"]!==
6
6
  "string")throw new ApiResponseError(`${what}\u306E\u5FDC\u7B54\u306B data.id \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`);return data}function serverMessage(body){const message=isRecord(body)?body["message"]:void 0;return typeof message==="string"&&message!==""?[message]:[]}function text(value){return typeof value==="string"||typeof value==="number"?String(value):""}function maskDigitRuns(value){return value.replace(/[0-90-9]{4,}/g,
7
7
  run=>{const chars=Array.from(run);return"*".repeat(chars.length-4)+chars.slice(-4).join("")})}var SORT_FIELD={kind:"sort",flag:"--sort",key:"sort",summary:"\u8868\u793A\u9806\uFF080 \u4EE5\u4E0A\u306E\u6574\u6570\u30FB\u5C0F\u3055\u3044\u307B\u3069\u4E0A\uFF09"};function fieldFlags(fields){return fields.map(field=>({name:field.flag,summary:field.summary,takesValue:true,placeholder:field.kind==="date"?"<YYYY-MM-DD>":field.kind==="sort"?"<\u6574\u6570>":`<${field.label}>`}))}function sortValue(flag,raw){
8
8
  const trimmed=raw.trim();const value=/^\d+$/.test(trimmed)?Number(trimmed):Number.NaN;if(!Number.isSafeInteger(value)||value>SORT_MAX){throw new UsageError(`${flag} \u306F 0 \u4EE5\u4E0A ${SORT_MAX} \u4EE5\u4E0B\u306E\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${raw}`)}return value}function fieldBody(input,fields){const body={};for(const field of fields){const raw=input.flags.get(field.flag);if(raw===void 0)continue;if(field.kind==="text")body[field.key]=boundedText(input,
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{fetchLatestVersion,isBehindLatest,runUpdate}from"./chunk-II7WTCSK.js";import"./chunk-CASLLD23.js";import"./chunk-D233KKXW.js";import"./chunk-PMOUHEJQ.js";import"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-CH6QU76P.js";import"./chunk-DXXFUNYN.js";import"./chunk-5WGOHFAS.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";export{fetchLatestVersion,isBehindLatest,runUpdate};
3
+ import{fetchLatestVersion,isBehindLatest,runUpdate}from"./chunk-PPFOHHCG.js";import"./chunk-NS5IXKNS.js";import"./chunk-D233KKXW.js";import"./chunk-PMOUHEJQ.js";import"./chunk-3WPPJAUV.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-2ZATYMAP.js";import"./chunk-DXXFUNYN.js";import"./chunk-5WGOHFAS.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";export{fetchLatestVersion,isBehindLatest,runUpdate};
@@ -3,7 +3,7 @@ const require = __twpCreateRequire(import.meta.url);
3
3
  import{ASSIGNED_PROJECT_COLUMNS,assignedProjectItems}from"./chunk-ODN76U2K.js";import{FISCAL_YEAR_FLAG,fiscalYear,skillNames}from"./chunk-R55F5ETH.js";import{OJT_ADMIN_NOTE}from"./chunk-LPEULVUC.js";import{LICENSE_FEATURE_NAMES,levelHoldsSeat,permissionMovesSeat,readLicenses}from"./chunk-YZTEIEDV.js";import"./chunk-C7VKBEVU.js";import{CONCURRENCY,allowedIpText,exportOperation,mapPool,pacedSender}from"./chunk-ZEN45YS7.js";import{readCsvFileText}from"./chunk-OMW6BBAY.js";
4
4
  import"./chunk-Q3B65OFC.js";import"./chunk-YICGF2NP.js";import{inspectLocalFile,isCommitted,issued}from"./chunk-ITTQEOIF.js";import{infoNote}from"./chunk-TYO6THPW.js";import{checkUploadQuota}from"./chunk-GNSZOYBQ.js";import"./chunk-UJOCIJ3V.js";import"./chunk-3ROQH6W7.js";import{USER_REF_FLAG,USER_REF_HELP,prepareUser,userPath}from"./chunk-O756DX6D.js";import{createFlags,fieldBody,hasAnyField,resolveRefFields,updateFlags}from"./chunk-RJRQ6EAH.js";
5
5
  import"./chunk-YLF4S4MC.js";import{booleanText,boundedText,isoDate,isoDateValue}from"./chunk-CHT6EP5C.js";import"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import{repeatedValues}from"./chunk-6NHLWYI2.js";import{DEPARTMENTS_PATH,ORG_MASTER_LIMIT,POSITIONS_PATH}from"./chunk-QLH5IJQV.js";import{ApiError}from"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import{ResolveError,isSafePathSegment}from"./chunk-HVZUXLQ4.js";
6
- import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger,shellQuote}from"./chunk-TDO6V3ZW.js";import{requireResolved,singleRef,withResolved}from"./chunk-7DCWZ2NF.js";import{isRecord,pick}from"./chunk-HCTPCUST.js";import{ApiRejectedError,ApiResponseError,UsageError}from"./chunk-STILP3Z6.js";import"./chunk-RMFLTSOV.js";import{NotLoggedInError,SessionExpiredError}from"./chunk-ITFO5GPX.js";
6
+ import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import{LIST_FLAGS,LIST_PAGING_HELP,envelopePaging,nonEmpty,positiveInteger,shellQuote}from"./chunk-TDO6V3ZW.js";import{requireResolved,singleRef,withResolved}from"./chunk-7DCWZ2NF.js";import{isRecord,pick}from"./chunk-HCTPCUST.js";import{ApiRejectedError,ApiResponseError,UsageError}from"./chunk-STILP3Z6.js";import"./chunk-RMFLTSOV.js";import{NotLoggedInError,SessionExpiredError}from"./chunk-3WPPJAUV.js";
7
7
  import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";import fs2 from"fs";import{isIP}from"net";var ASSIGNMENT_COLUMNS=["id","department_name","position_name","start_date","end_date","is_primary","is_current","is_approval_route","effective_status"];function assignmentRows(body){const response=isRecord(body)&&"response"in body?body["response"]:body;const list=isRecord(response)?response["list"]:void 0;if(!Array.isArray(list)){throw new ApiResponseError("\u6240\u5C5E\u4E00\u89A7\u306E\u5FDC\u7B54\u306B list \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}
8
8
  return list}async function nameMap(ctx,path2,label2){try{const body=await ctx.send({method:"GET",path:path2,query:{limit:ORG_MASTER_LIMIT}});const list=isRecord(body)?body["list"]:void 0;if(!Array.isArray(list))throw new Error(`${label2}\u4E00\u89A7\u306E\u5FDC\u7B54\u306B list \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093`);const count=isRecord(body)?body["count"]:void 0;if(typeof count==="number"&&count>list.length){ctx.warn(`${label2}\u4E00\u89A7\u304C ${count} \u4EF6\u4E2D ${list.length} \
9
9
  \u4EF6\u3067\u5207\u308A\u8A70\u3081\u3089\u308C\u305F\u305F\u3081\u3001\u4E00\u90E8\u306E${label2}\u540D\u306F\u7A7A\u6B04\u3067\u3059\u3002ID \u306F --output json \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059\u3002`)}const map={};for(const row of list){if(isRecord(row)&&typeof row["id"]==="string"&&typeof row["name"]==="string"){map[row["id"]]=row["name"]}}return map}catch(err){ctx.warn(`${label2}\u540D\u3092\u53D6\u5F97\u3067\u304D\u306A\u304B\u3063\u305F\u305F\u3081\u3001${label2}\u540D\u306E\u5217\u306F\u7A7A\u6B04\u3067\u3059\uFF08${err.
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{SCHEDULE_HELP,parseSchedule,readRunStatus,workerAgentDomain}from"./chunk-WFONEPVZ.js";import"./chunk-3EFJQDC4.js";import"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-TDO6V3ZW.js";
4
- import"./chunk-7DCWZ2NF.js";import"./chunk-HCTPCUST.js";import"./chunk-STILP3Z6.js";import"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";export{SCHEDULE_HELP,parseSchedule,readRunStatus,workerAgentDomain};
3
+ import{SCHEDULE_HELP,parseSchedule,readRunStatus,workerAgentDomain}from"./chunk-USCXNODU.js";import"./chunk-3EFJQDC4.js";import"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-TDO6V3ZW.js";
4
+ import"./chunk-7DCWZ2NF.js";import"./chunk-HCTPCUST.js";import"./chunk-STILP3Z6.js";import"./chunk-3WPPJAUV.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";export{SCHEDULE_HELP,parseSchedule,readRunStatus,workerAgentDomain};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{applyConditionLabel,applyInstancePlan,createInstancePlan,describeBlockedReason,formColumns,parseInstanceContent,workflowDomain,writtenInstance}from"./chunk-K2IBOGCW.js";import"./chunk-IH2VB7DE.js";import"./chunk-HIIEA3AN.js";import"./chunk-N3UDILK7.js";import"./chunk-CHT6EP5C.js";import"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";
4
- import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-TDO6V3ZW.js";import"./chunk-7DCWZ2NF.js";import"./chunk-HCTPCUST.js";import"./chunk-STILP3Z6.js";import"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";
3
+ import{applyConditionLabel,applyInstancePlan,createInstancePlan,describeBlockedReason,formColumns,parseInstanceContent,workflowDomain,writtenInstance}from"./chunk-UFYPNT63.js";import"./chunk-TEIPWYN5.js";import"./chunk-HIIEA3AN.js";import"./chunk-N3UDILK7.js";import"./chunk-CHT6EP5C.js";import"./chunk-V5WDGX4S.js";import"./chunk-W4NLJ2YK.js";import"./chunk-BD7O73GK.js";import"./chunk-6NHLWYI2.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";
4
+ import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";import"./chunk-SBRTBKEZ.js";import"./chunk-TDO6V3ZW.js";import"./chunk-7DCWZ2NF.js";import"./chunk-HCTPCUST.js";import"./chunk-STILP3Z6.js";import"./chunk-3WPPJAUV.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-OKATZ4SN.js";import"./chunk-NHYMHCAT.js";
5
5
  import"./chunk-VSJBJXZO.js";export{applyConditionLabel,applyInstancePlan,createInstancePlan,describeBlockedReason,formColumns,parseInstanceContent,workflowDomain,writtenInstance};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tocca-systems/twp-cli",
3
- "version": "0.156.0",
3
+ "version": "0.157.0",
4
4
  "description": "TWP CLI — Tocca Working Platform の CLI 型統合インターフェース(AIエージェントハーネス)",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,4 +0,0 @@
1
- import { createRequire as __twpCreateRequire } from 'node:module';
2
- const require = __twpCreateRequire(import.meta.url);
3
- import{CHECK_INTERVAL_MS,DISABLE_ENV,PARENT_PID_ENV,WORKER_ENV,autoUpdateDisabledReason,classifyInstall,describeAutoUpdate,isCheckDue,listRegisteredPids,lockFilePath,onStartup,pickNotice,readUpdateState,registerRunning,resolveCliPath,runDirPath,sameNpmPath,stateFilePath,workerEnv,writeUpdateState}from"./chunk-CH6QU76P.js";import"./chunk-DXXFUNYN.js";import"./chunk-5WGOHFAS.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";import"./chunk-NHYMHCAT.js";
4
- import"./chunk-VSJBJXZO.js";export{CHECK_INTERVAL_MS,DISABLE_ENV,PARENT_PID_ENV,WORKER_ENV,autoUpdateDisabledReason,classifyInstall,describeAutoUpdate,isCheckDue,listRegisteredPids,lockFilePath,onStartup,pickNotice,readUpdateState,registerRunning,resolveCliPath,runDirPath,sameNpmPath,stateFilePath,workerEnv,writeUpdateState};
@@ -1,78 +0,0 @@
1
- import { createRequire as __twpCreateRequire } from 'node:module';
2
- const require = __twpCreateRequire(import.meta.url);
3
- import{isTrustworthyCacheFile,writePrivateFileAtomic}from"./chunk-D233KKXW.js";import{AuthSession}from"./chunk-ITFO5GPX.js";import{loadCredentials,withFileLock}from"./chunk-GWVREACM.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{parseVersionCore}from"./chunk-DXXFUNYN.js";import{effectiveApiUrl,effectiveRelayUrl,resolveConfiguredModel,resolveProfile}from"./chunk-EDF4U5BT.js";import{ensureTwpHome,twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";function blockLength(block){if(block.type==="text")return block.text.length;if(block.type==="tool_result")return block.content.length;return block.name.length+JSON.stringify(block.input).length}function emptyUsage(){return{inputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,outputTokens:0}}import fs from"fs";import path from"path";var MODELS=[{id:"claude-opus-5",label:"Claude Opus 5",note:"\u6700\u3082\u9AD8\u6027\u80FD\u3002\u65E2\u5B9A"},{id:"claude-sonnet-5",label:"Claude Sonnet 5",note:"\u30D0\u30E9\u30F3\u30B9\u578B"},{id:"claude-haiku-4-5",label:"Claude Haiku 4.5",note:"\u9AD8\u901F\u30FB\u4F4E\u30B3\u30B9\u30C8"}];var DEFAULT_MODEL="claude-opus-5";function isSafeModelId(id){return/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(id)}function modelLabel(id){const known=MODELS.find(m=>m.id===id);if(known)return known.label;
4
- return prettifyClaudeId(id)??stripTerminalControls(id).slice(0,128)}function prettifyClaudeId(id){const match=/^claude-([a-z]+)((?:-\d+)+)$/.exec(id);if(!match)return null;const family=match[1]??"";const version=(match[2]??"").replace(/^-/,"").split("-").join(".");return`Claude ${family.charAt(0).toUpperCase()}${family.slice(1)} ${version}`}function modelNote(id){return MODELS.find(m=>m.id===id)?.note??""}function toModelInfos(ids){return ids.map(id=>({id,label:modelLabel(id),note:modelNote(id)}))}var anthropicAdapter={protocol:"anthropic",streamPath:"/api/cli/v1/messages/stream",toRequestBody,decode};function toRequestBody(request){const explicitCache=request.promptCache==="explicit";const messages=request.messages.map((m,i)=>({role:m.role,content:m.content.map((block,j)=>{const isLastBlockOfLastMessage=i===request.messages.length-1&&j===m.content.length-1;return explicitCache&&isLastBlockOfLastMessage&&m.role==="user"?{...block,cache_control:{type:"ephemeral"}}:block})}));return{model:request.
5
- model,max_tokens:request.maxTokens,...request.system!==void 0?{system:request.system}:{},...request.tools&&request.tools.length>0?{tools:request.tools}:{},messages}}function decode(ev){const parsed=safeJson(ev.data);if(!parsed)return[];const type=typeof parsed["type"]==="string"?parsed["type"]:ev.event;if(type==="message_start"){const message=parsed["message"];return usageEvent(message?.usage)}if(type==="content_block_start"){const block=parsed["content_block"];const index=numberOr(parsed["index"],
6
- -1);if(block?.type==="tool_use"&&typeof block.id==="string"&&typeof block.name==="string"){const seeded=block.input;const initial=typeof seeded==="object"&&seeded!==null&&!Array.isArray(seeded)?JSON.stringify(seeded):"";return[{kind:"tool_start",index,id:block.id,name:block.name,initialJson:initial==="{}"?"":initial}]}return[]}if(type==="content_block_delta"){const delta=parsed["delta"];if(delta?.type==="text_delta"&&typeof delta.text==="string"&&delta.text!==""){return[{kind:"text",delta:delta.
7
- text}]}if(delta?.type==="input_json_delta"&&typeof delta.partial_json==="string"){return[{kind:"tool_delta",index:numberOr(parsed["index"],-1),json:delta.partial_json}]}return[]}if(type==="content_block_stop"){return[{kind:"tool_end",index:numberOr(parsed["index"],-1)}]}if(type==="message_delta"){const out=usageEvent(parsed["usage"]);const delta=parsed["delta"];if(typeof delta?.stop_reason==="string")out.push({kind:"stop",reason:delta.stop_reason});return out}if(type==="error"){const err=parsed["\
8
- error"];return[{kind:"error",message:typeof err?.message==="string"?err.message:"\u30B9\u30C8\u30EA\u30FC\u30E0\u304C\u4E2D\u65AD\u3055\u308C\u307E\u3057\u305F"}]}return[]}function usageEvent(source){if(typeof source!=="object"||source===null)return[];const raw=source;const usage={};const pick=(key,field)=>{const v=raw[key];if(typeof v==="number"&&Number.isFinite(v))usage[field]=v};pick("input_tokens","inputTokens");pick("cache_read_input_tokens","cacheReadTokens");pick("cache_creation_input_tok\
9
- ens","cacheWriteTokens");pick("output_tokens","outputTokens");return[{kind:"usage",usage}]}function numberOr(value,fallback){return typeof value==="number"&&Number.isFinite(value)?value:fallback}function safeJson(text){try{const parsed=JSON.parse(text);return typeof parsed==="object"&&parsed!==null?parsed:null}catch{return null}}import{randomUUID}from"crypto";var geminiAdapter={protocol:"gemini",streamPath:"/api/cli/v1/gemini/stream",toRequestBody:toRequestBody2,decode:decode2};var thoughtSignatures=new Map;var SKIP_THOUGHT_SIGNATURE="skip_thought_signature_validator";var MAX_SIGNATURES=2e3;function rememberSignature(id,signature,model){if(thoughtSignatures.size>=MAX_SIGNATURES){const oldest=thoughtSignatures.keys().next();if(!oldest.done)thoughtSignatures.delete(oldest.value)}thoughtSignatures.set(id,{signature,model})}
10
- function signatureFor(id,model){const saved=thoughtSignatures.get(id);return saved!==void 0&&saved.model===model?saved.signature:SKIP_THOUGHT_SIGNATURE}var currentModel="";var nextToolIndex=0;function toRequestBody2(request){currentModel=request.model;const toolNames=new Map;for(const message of request.messages){for(const block of message.content){if(block.type==="tool_use")toolNames.set(block.id,block.name)}}const tools=request.tools&&request.tools.length>0?request.tools:void 0;return{model:request.model,contents:request.messages.map(message=>toContent(message,toolNames,request.model)),...request.system!==void 0&&request.system!==""?{systemInstruction:{parts:[{text:request.
11
- system}]}}:{},...tools?{tools:[{functionDeclarations:tools.map(tool=>({name:tool.name,description:tool.description,parametersJsonSchema:tool.input_schema}))}]}:{},generationConfig:{maxOutputTokens:request.maxTokens}}}function toContent(message,toolNames,model){const parts=[];for(const block of message.content){if(block.type==="text"){if(block.text!=="")parts.push({text:block.text})}else if(block.type==="tool_use"){parts.push({functionCall:{id:block.id,name:block.name,args:block.input},thoughtSignature:signatureFor(
12
- block.id,model)})}else{parts.push({functionResponse:{id:block.tool_use_id,name:toolNames.get(block.tool_use_id)??"unknown",response:block.is_error===true?{error:block.content}:{output:block.content}}})}}if(parts.length===0)parts.push({text:" "});return{role:message.role==="assistant"?"model":"user",parts}}function decode2(ev){const parsed=safeJson2(ev.data);if(!parsed){return ev.event==="error"?[{kind:"error",message:ev.data.trim()||"\u30B9\u30C8\u30EA\u30FC\u30E0\u304C\u4E2D\u65AD\u3055\u308C\u307E\u3057\u305F"}]:
13
- []}if(ev.event==="error"||typeof parsed["error"]==="object"&&parsed["error"]!==null){const err=parsed["error"];return[{kind:"error",message:typeof err?.message==="string"?err.message:"\u30B9\u30C8\u30EA\u30FC\u30E0\u304C\u4E2D\u65AD\u3055\u308C\u307E\u3057\u305F"}]}const out=[];const candidates=Array.isArray(parsed["candidates"])?parsed["candidates"]:[];const candidate=candidates[0];const parts=Array.isArray(candidate?.content?.parts)?candidate.content.parts:[];for(const raw of parts){if(typeof raw!==
14
- "object"||raw===null)continue;const part=raw;if(part.functionCall&&typeof part.functionCall.name==="string"){const id=typeof part.functionCall.id==="string"&&part.functionCall.id!==""?part.functionCall.id:`gemini_${randomUUID()}`;if(typeof part.thoughtSignature==="string"&&part.thoughtSignature!==""){rememberSignature(id,part.thoughtSignature,currentModel)}const args=part.functionCall.args;const index=nextToolIndex++;out.push({kind:"tool_start",index,id,name:part.functionCall.name,initialJson:typeof args===
15
- "object"&&args!==null&&!Array.isArray(args)?JSON.stringify(args):""});out.push({kind:"tool_end",index});continue}if(typeof part.text==="string"&&part.text!==""&&part.thought!==true){out.push({kind:"text",delta:part.text})}}const usage=usageOf(parsed["usageMetadata"]);if(usage)out.push({kind:"usage",usage});const feedback=parsed["promptFeedback"];if(typeof feedback?.blockReason==="string"&&feedback.blockReason!==""){out.push({kind:"error",message:`Gemini \u304C\u8981\u6C42\u3092\u62D2\u5426\u3057\u307E\u3057\u305F: ${feedback.
16
- blockReason}`})}if(typeof candidate?.finishReason==="string"&&candidate.finishReason!==""){const reason=candidate.finishReason;out.push({kind:"stop",reason:stopReasonOf(reason)});if(!NORMAL_FINISH_REASONS.has(reason)){out.push({kind:"error",message:`Gemini \u304C\u5FDC\u7B54\u3092\u6253\u3061\u5207\u308A\u307E\u3057\u305F: ${reason}`})}}return out}var NORMAL_FINISH_REASONS=new Set(["STOP","MAX_TOKENS","FINISH_REASON_UNSPECIFIED"]);function usageOf(source){if(typeof source!=="object"||source===null)
17
- return null;const raw=source;const num=key=>{const v=raw[key];return typeof v==="number"&&Number.isFinite(v)?Math.max(0,v):null};const prompt=num("promptTokenCount");const candidates=num("candidatesTokenCount");if(prompt===null&&candidates===null)return null;const usage={};if(prompt!==null){const cached=Math.min(num("cachedContentTokenCount")??0,prompt);usage.inputTokens=prompt-cached;usage.cacheReadTokens=cached;usage.cacheWriteTokens=0}if(candidates!==null||num("thoughtsTokenCount")!==null){usage.
18
- outputTokens=(candidates??0)+(num("thoughtsTokenCount")??0)}return usage}function stopReasonOf(finishReason){if(finishReason==="STOP")return"end_turn";if(finishReason==="MAX_TOKENS")return"max_tokens";return finishReason.toLowerCase()}function safeJson2(text){try{const parsed=JSON.parse(text);return typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:null}catch{return null}}var openAiChatAdapter={protocol:"openai-chat",streamPath:"/api/cli/v1/chat/completions",toRequestBody:toRequestBody3,decode:decode3};function toRequestBody3(request){const hasTools=request.tools!==void 0&&request.tools.length>0;return{model:request.model,max_completion_tokens:request.maxTokens,messages:[...request.system!==void 0?[{role:"system",content:request.system}]:[],...request.messages.flatMap(toOpenAiMessages)],...hasTools?{tools:request.tools.map(tool=>({type:"function",function:{name:tool.
19
- name,description:tool.description,parameters:tool.input_schema}}))}:{},reasoning_effort:"none",stream_options:{include_usage:true}}}function toOpenAiMessages(message){const text=message.content.filter(block=>block.type==="text").map(block=>block.type==="text"?block.text:"").join("");if(message.role==="assistant"){const toolCalls=message.content.flatMap(block=>block.type==="tool_use"?[{id:block.id,type:"function",function:{name:block.name,arguments:JSON.stringify(block.input)}}]:[]);return[{role:"\
20
- assistant",content:text===""?null:text,...toolCalls.length>0?{tool_calls:toolCalls}:{}}]}const toolResults=message.content.flatMap(block=>block.type==="tool_result"?[{role:"tool",tool_call_id:block.tool_use_id,content:block.is_error===true?`[tool error] ${block.content}`:block.content}]:[]);return[...toolResults,...text!==""||toolResults.length===0?[{role:"user",content:text}]:[]]}var STOP_REASONS={tool_calls:"tool_use",stop:"end_turn",length:"max_tokens"};function decode3(ev){if(ev.data.trim()===
21
- "[DONE]")return[];const parsed=safeJson3(ev.data);if(!parsed)return[];if(parsed["error"]!==void 0&&parsed["error"]!==null){const raw=parsed["error"];const message=typeof raw==="string"?raw:raw.message;return[{kind:"error",message:typeof message==="string"&&message!==""?message:"\u30B9\u30C8\u30EA\u30FC\u30E0\u304C\u4E2D\u65AD\u3055\u308C\u307E\u3057\u305F"}]}const out=[];const choices=Array.isArray(parsed["choices"])?parsed["choices"]:[];const choice=choices[0];if(choice&&typeof choice.delta==="\
22
- object"&&choice.delta!==null){const delta=choice.delta;if(typeof delta.content==="string"&&delta.content!==""){out.push({kind:"text",delta:delta.content})}if(typeof delta.refusal==="string"&&delta.refusal!==""){out.push({kind:"text",delta:delta.refusal})}if(Array.isArray(delta.tool_calls)){for(const call of delta.tool_calls){const index=typeof call["index"]==="number"?call["index"]:-1;const fn=call["function"]??{};const args=typeof fn.arguments==="string"?fn.arguments:"";if(typeof call["id"]==="\
23
- string"&&typeof fn.name==="string"){out.push({kind:"tool_start",index,id:call["id"],name:fn.name,initialJson:args})}else if(args!==""){out.push({kind:"tool_delta",index,json:args})}}}}if(choice&&typeof choice.finish_reason==="string"){out.push({kind:"stop",reason:STOP_REASONS[choice.finish_reason]??choice.finish_reason})}out.push(...usageEvent2(parsed["usage"]));return out}function usageEvent2(source){if(typeof source!=="object"||source===null)return[];const raw=source;const prompt=raw["prompt_t\
24
- okens"];const completion=raw["completion_tokens"];if(typeof prompt!=="number"||typeof completion!=="number")return[];const details=typeof raw["prompt_tokens_details"]==="object"&&raw["prompt_tokens_details"]!==null?raw["prompt_tokens_details"]:{};const count=value=>typeof value==="number"&&Number.isFinite(value)?Math.max(0,value):0;const total=Math.max(0,prompt);const cacheReadTokens=Math.min(count(details["cached_tokens"]),total);const cacheWriteTokens=Math.min(count(details["cache_write_tokens"]),
25
- total-cacheReadTokens);const usage={inputTokens:total-cacheReadTokens-cacheWriteTokens,cacheReadTokens,cacheWriteTokens,outputTokens:Math.max(0,completion)};return[{kind:"usage",usage}]}function safeJson3(text){try{const parsed=JSON.parse(text);return typeof parsed==="object"&&parsed!==null?parsed:null}catch{return null}}var openAiResponsesAdapter={protocol:"openai-responses",streamPath:"/api/cli/v1/responses",toRequestBody:toRequestBody4,decode:decode4};var reasoningByCall=new Map;var MAX_REASONING_ENTRIES=2e3;var pendingReasoning=[];var currentModel2="";var sawFunctionCall=false;function rememberReasoning(callId,items,model){if(reasoningByCall.size>=MAX_REASONING_ENTRIES){const oldest=reasoningByCall.keys().next();if(!oldest.done)reasoningByCall.delete(oldest.value)}reasoningByCall.set(callId,{items,model})}function toRequestBody4(request){currentModel2=request.model;pendingReasoning=[];sawFunctionCall=false;const hasTools=request.tools!==void 0&&request.tools.length>0;return{model:request.model,max_output_tokens:request.maxTokens,...request.system!==void 0&&request.system!==
26
- ""?{instructions:request.system}:{},input:request.messages.flatMap(message=>toInputItems(message,request.model)),...hasTools?{tools:request.tools.map(tool=>({type:"function",name:tool.name,description:tool.description,parameters:tool.input_schema,strict:false}))}:{},include:["reasoning.encrypted_content"]}}function toInputItems(message,model){const text=message.content.filter(block=>block.type==="text").map(block=>block.type==="text"?block.text:"").join("");if(message.role==="assistant"){const calls=message.
27
- content.flatMap(block=>block.type==="tool_use"?[block]:[]);const reasoningOf=id=>{const saved=reasoningByCall.get(id);return saved!==void 0&&saved.model===model?saved.items:[]};return[...calls.length>0?reasoningOf(calls[0].id):[],...text!==""?[{role:"assistant",content:text}]:[],...calls.flatMap((block,i)=>[...i>0?reasoningOf(block.id):[],{type:"function_call",call_id:block.id,name:block.name,arguments:JSON.stringify(block.input)}])]}const outputs=message.content.flatMap(block=>block.type==="too\
28
- l_result"?[{type:"function_call_output",call_id:block.tool_use_id,output:block.is_error===true?`[tool error] ${block.content}`:block.content}]:[]);return[...outputs,...text!==""||outputs.length===0?[{role:"user",content:text}]:[]]}function decode4(ev){const parsed=safeJson4(ev.data);if(!parsed){return ev.event==="error"?[{kind:"error",message:ev.data.trim()||"\u30B9\u30C8\u30EA\u30FC\u30E0\u304C\u4E2D\u65AD\u3055\u308C\u307E\u3057\u305F"}]:[]}const type=typeof parsed["type"]==="string"?parsed["t\
29
- ype"]:ev.event;if(ev.event==="error"||type==="error"){return[{kind:"error",message:errorMessageOf(parsed)}]}switch(type){case"response.output_text.delta":case"response.refusal.delta":{const delta=parsed["delta"];return typeof delta==="string"&&delta!==""?[{kind:"text",delta}]:[]}case"response.output_item.done":return outputItemDone(parsed);case"response.completed":case"response.incomplete":case"response.failed":return terminal(type,parsed["response"]);default:return[]}}function outputItemDone(event){
30
- const item=event["item"];if(typeof item!=="object"||item===null)return[];const record=item;if(record["type"]==="reasoning"){pendingReasoning.push(record);return[]}if(record["type"]!=="function_call")return[];const callId=record["call_id"];const name=record["name"];if(typeof callId!=="string"||callId===""||typeof name!=="string"||name==="")return[];sawFunctionCall=true;if(pendingReasoning.length>0){rememberReasoning(callId,pendingReasoning,currentModel2);pendingReasoning=[]}const index=typeof event["\
31
- output_index"]==="number"?event["output_index"]:0;const args=typeof record["arguments"]==="string"?record["arguments"]:"";return[{kind:"tool_start",index,id:callId,name,initialJson:args},{kind:"tool_end",index}]}function terminal(type,response){const record=typeof response==="object"&&response!==null?response:{};const out=[...usageEvent3(record["usage"])];if(type==="response.completed"){out.push({kind:"stop",reason:sawFunctionCall?"tool_use":"end_turn"});return out}if(type==="response.incomplete"){
32
- const details=record["incomplete_details"];const reason=typeof details?.reason==="string"?details.reason:"incomplete";if(reason==="max_output_tokens"){out.push({kind:"stop",reason:"max_tokens"})}else{out.push({kind:"stop",reason});out.push({kind:"error",message:`OpenAI \u304C\u5FDC\u7B54\u3092\u6253\u3061\u5207\u308A\u307E\u3057\u305F: ${reason}`})}return out}out.push({kind:"error",message:errorMessageOf(record)});return out}function errorMessageOf(source){const raw=source["error"];const nested=typeof raw===
33
- "string"?raw:raw?.message;const message=typeof nested==="string"&&nested!==""?nested:source["message"];return typeof message==="string"&&message!==""?message:"\u30B9\u30C8\u30EA\u30FC\u30E0\u304C\u4E2D\u65AD\u3055\u308C\u307E\u3057\u305F"}function usageEvent3(source){if(typeof source!=="object"||source===null)return[];const raw=source;const input=raw["input_tokens"];const output=raw["output_tokens"];if(typeof input!=="number"||typeof output!=="number")return[];const details=typeof raw["input_tok\
34
- ens_details"]==="object"&&raw["input_tokens_details"]!==null?raw["input_tokens_details"]:{};const count=value=>typeof value==="number"&&Number.isFinite(value)?Math.max(0,value):0;const total=Math.max(0,input);const cacheReadTokens=Math.min(count(details["cached_tokens"]),total);const cacheWriteTokens=Math.min(count(details["cache_write_tokens"]),total-cacheReadTokens);const usage={inputTokens:total-cacheReadTokens-cacheWriteTokens,cacheReadTokens,cacheWriteTokens,outputTokens:Math.max(0,output)};
35
- return[{kind:"usage",usage}]}function safeJson4(text){try{const parsed=JSON.parse(text);return typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:null}catch{return null}}var ADAPTERS={anthropic:anthropicAdapter,"openai-chat":openAiChatAdapter,"openai-responses":openAiResponsesAdapter,gemini:geminiAdapter};var PROTOCOLS_HEADER="X-TWP-CLI-Protocols";function supportedProtocols(){return Object.keys(ADAPTERS)}function isModelProtocol(value){return value==="anthropic"||value==="openai-chat"||value==="openai-responses"||value==="gemini"}function adapterFor(protocol){return ADAPTERS[protocol]??null}var DEFAULT_PROVIDER="anthropic";function effectiveModelSpec(spec){return{provider:spec?.provider??DEFAULT_PROVIDER,protocol:spec?.protocol??"anthropic",contextWindow:spec?.contextWindow??null,maxOutputTokens:spec?.maxOutputTokens??null,tools:spec?.capabilities?.tools??true,promptCache:spec?.capabilities?.promptCache??"explicit"}}var PROVIDER_PATTERN=/^[a-z0-9-]{1,32}$/;function positiveInt(value){return typeof value==="number"&&Number.isInteger(value)&&value>0?value:void 0}function parseModelSpec(id,raw){
36
- const spec={id};if(typeof raw!=="object"||raw===null)return spec;const r=raw;if(typeof r["provider"]==="string"&&PROVIDER_PATTERN.test(r["provider"]))spec.provider=r["provider"];if(isModelProtocol(r["protocol"]))spec.protocol=r["protocol"];const contextWindow=positiveInt(r["context_window"]);if(contextWindow!==void 0)spec.contextWindow=contextWindow;const maxOutputTokens=positiveInt(r["max_output_tokens"]);if(maxOutputTokens!==void 0)spec.maxOutputTokens=maxOutputTokens;const caps=r["capabilitie\
37
- s"];if(typeof caps==="object"&&caps!==null){const c=caps;const capabilities={};if(typeof c["tools"]==="boolean")capabilities.tools=c["tools"];const cache=c["prompt_cache"];if(cache==="explicit"||cache==="automatic"||cache==="none")capabilities.promptCache=cache;if(Object.keys(capabilities).length>0)spec.capabilities=capabilities}return spec}function toWireSpec(spec){return{id:spec.id,...spec.provider!==void 0?{provider:spec.provider}:{},...spec.protocol!==void 0?{protocol:spec.protocol}:{},...spec.
38
- contextWindow!==void 0?{context_window:spec.contextWindow}:{},...spec.maxOutputTokens!==void 0?{max_output_tokens:spec.maxOutputTokens}:{},...spec.capabilities!==void 0?{capabilities:{...spec.capabilities.tools!==void 0?{tools:spec.capabilities.tools}:{},...spec.capabilities.promptCache!==void 0?{prompt_cache:spec.capabilities.promptCache}:{}}}:{}}}function modelCachePath(env=process.env){return path.join(twpHomeDir(env),"models.json")}function modelCacheLockPath(env=process.env){return path.join(twpHomeDir(env),"models.lock")}function builtinCatalog(){return{ids:MODELS.map(m=>m.id),source:"builtin",fetchedAt:null,minSupportedVersion:null}}function readCacheFile(env){const file=modelCachePath(env);if(!isTrustworthyCacheFile(file)){return{version:1,entries:{}}}const parsed=JSON.parse(fs.readFileSync(file,"utf8"));if(!parsed||typeof parsed!==
39
- "object"||typeof parsed.entries!=="object"||parsed.entries===null){return{version:1,entries:{}}}return parsed}function readFloor(entry){const raw=entry.min_supported_version;return typeof raw==="string"&&parseVersionCore(raw)!==null?raw.trim():null}function loadCachedVersionFloor(profile,relayUrl,env=process.env){try{const entry=readCacheFile(env).entries?.[profile];if(!entry||entry.relay_url!==relayUrl)return{minSupportedVersion:null,fetchedAt:null};return{minSupportedVersion:readFloor(entry),fetchedAt:typeof entry.
40
- fetched_at==="string"?entry.fetched_at:null}}catch{return{minSupportedVersion:null,fetchedAt:null}}}function loadCachedCatalog(profile,relayUrl,env=process.env){try{const parsed=readCacheFile(env).entries?.[profile];if(!parsed||parsed.relay_url!==relayUrl)return null;const ids=Array.isArray(parsed.models)?parsed.models.filter(id=>typeof id==="string"&&isSafeModelId(id)):[];if(ids.length===0)return null;const specById=new Map;if(Array.isArray(parsed.specs)){for(const raw of parsed.specs){const id=typeof raw===
41
- "object"&&raw!==null?raw.id:void 0;if(typeof id==="string"&&ids.includes(id))specById.set(id,raw)}}return{ids,models:ids.map(id=>parseModelSpec(id,specById.get(id))),source:"cache",fetchedAt:typeof parsed.fetched_at==="string"?parsed.fetched_at:null,minSupportedVersion:readFloor(parsed)}}catch{return null}}async function saveCatalog(profile,relayUrl,ids,minSupportedVersion,env=process.env,now=Date.now,specs=[]){try{ensureTwpHome(env);await withFileLock(modelCacheLockPath(env),async()=>{let file;
42
- try{file=readCacheFile(env)}catch{file={version:1,entries:{}}}const entries={...file.entries??{}};entries[profile]={relay_url:relayUrl,fetched_at:new Date(now()).toISOString(),models:ids,specs:specs.map(toWireSpec),min_supported_version:minSupportedVersion};writePrivateFileAtomic(modelCachePath(env),`${JSON.stringify({version:1,entries},null,2)}
43
- `)})}catch{}}async function loadCatalog(client,profile,relayUrl,env=process.env){try{const{ids,models,minSupportedVersion}=await client.fetchModelCatalog();await saveCatalog(profile,relayUrl,ids,minSupportedVersion,env,Date.now,models);return{ids,models,source:"server",fetchedAt:new Date().toISOString(),minSupportedVersion}}catch{return loadCachedCatalog(profile,relayUrl,env)??builtinCatalog()}}function pickModel(catalog,configured){const fallback=catalog.ids[0]??MODELS[0]?.id??DEFAULT_MODEL;if(!configured||
44
- configured==="")return{model:fallback};if(catalog.ids.includes(configured))return{model:configured};if(catalog.source==="builtin"){return{model:configured,warning:`\u30E2\u30C7\u30EB\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u306A\u304B\u3063\u305F\u305F\u3081\u3001\u6307\u5B9A\u3055\u308C\u305F ${configured} \u3092\u305D\u306E\u307E\u307E\u4F7F\u3044\u307E\u3059\uFF08\u5229\u7528\u3067\u304D\u306A\u3044\u5834\u5408\u306F\u30EA\u30EC\u30FC\u304C 400 \u3092\u8FD4\u3057\u307E\u3059\uFF09`}}return{
45
- model:fallback,warning:`${configured} \u306F\u5229\u7528\u3067\u304D\u306A\u3044\u305F\u3081 ${fallback} \u3092\u4F7F\u3044\u307E\u3059\uFF08\u5229\u7528\u53EF\u80FD: ${catalog.ids.join(" / ")}\uFF09`}}function specFor(catalog,id){return effectiveModelSpec(catalog.models?.find(m=>m.id===id))}function classifyModelSwitch(catalog,from,to){if(from===to)return"same";const a=specFor(catalog,from);const b=specFor(catalog,to);return a.provider===b.provider&&a.protocol===b.protocol?"keep":"new_conversat\
46
- ion"}var MAX_EVENT_BYTES=8*1024*1024;var SseBufferOverflowError=class extends Error{constructor(limit){super(`SSE \u306E\u30A4\u30D9\u30F3\u30C8\u5883\u754C\uFF08\u7A7A\u884C\uFF09\u304C ${limit} \u30D0\u30A4\u30C8\u4EE5\u5185\u306B\u73FE\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u4E0A\u6D41\u306E\u5FDC\u7B54\u304C\u58CA\u308C\u3066\u3044\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002`)}};var SseParser=class{constructor(maxEventBytes=MAX_EVENT_BYTES){this.maxEventBytes=maxEventBytes}maxEventBytes;buffer="";pendingCr=false;push(chunk){
47
- let pending=this.pendingCr?`\r${chunk}`:chunk;this.pendingCr=pending.endsWith("\r");if(this.pendingCr)pending=pending.slice(0,-1);this.buffer+=pending.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(this.buffer.length>this.maxEventBytes){this.buffer="";this.pendingCr=false;throw new SseBufferOverflowError(this.maxEventBytes)}const events=[];for(;;){const boundary=this.buffer.indexOf("\n\n");if(boundary===-1)break;const block=this.buffer.slice(0,boundary);this.buffer=this.buffer.slice(boundary+2);const parsed=parseBlock(
48
- block);if(parsed)events.push(parsed)}return events}flush(){const rest=(this.pendingCr?`${this.buffer}
49
- `:this.buffer).trim();this.buffer="";this.pendingCr=false;if(rest==="")return[];const parsed=parseBlock(rest);return parsed?[parsed]:[]}};function parseBlock(block){let event="message";const data=[];for(const line of block.split("\n")){if(line.startsWith(":"))continue;const colon=line.indexOf(":");const field=colon===-1?line:line.slice(0,colon);let value=colon===-1?"":line.slice(colon+1);if(value.startsWith(" "))value=value.slice(1);if(field==="event")event=value;else if(field==="data")data.push(
50
- value)}if(data.length===0)return null;return{event,data:data.join("\n")}}var RelayError=class extends Error{constructor(kind,message,status){super(message);this.kind=kind;this.status=status;this.name="RelayError"}kind;status};var MODELS_TIMEOUT_MS=5e3;var RelayClient=class{constructor(relayUrl,session,fetchImpl=httpFetch,cliVersion="0.0.0-dev"){this.relayUrl=relayUrl;this.session=session;this.fetchImpl=fetchImpl;this.cliVersion=cliVersion}relayUrl;session;fetchImpl;cliVersion;async fetchModelCatalog(){const res=await this.send("GET","/api/cli/v1/models",void 0,AbortSignal.
51
- timeout(MODELS_TIMEOUT_MS));const body=await res.json().catch(()=>null);const models=(Array.isArray(body?.models)?body.models:[]).filter(m=>{const id=typeof m==="object"&&m!==null?m.id:void 0;return typeof id==="string"&&isSafeModelId(id)}).map(m=>parseModelSpec(m.id,m));const ids=models.map(m=>m.id);if(ids.length===0){throw new RelayError("upstream","\u30E2\u30C7\u30EB\u4E00\u89A7\u304C\u7A7A\u3067\u3057\u305F\uFF08\u30EA\u30EC\u30FC\u306E\u8A2D\u5B9A\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\uFF09")}
52
- const floor=body?.min_supported_version;const minSupportedVersion=typeof floor==="string"&&parseVersionCore(floor)!==null?floor.trim():null;return{ids,models,minSupportedVersion}}async stream(request,hooks){const protocol=request.protocol??"anthropic";const adapter=adapterFor(protocol);if(!adapter){throw new RelayError("validation",`\u30E2\u30C7\u30EB ${request.model} \u306F ${protocol} \u30D7\u30ED\u30C8\u30B3\u30EB\u306E\u305F\u3081\u3001\u3053\u306E\u7248\u306E twp \u3067\u306F\u5229\u7528\u3067\u304D\u307E\u305B\u3093\uFF08twp \u3092\u66F4\u65B0\u3057\u3066\u304F\u3060\u3055\u3044\uFF09`)}
53
- let res;try{res=await this.send("POST",adapter.streamPath,adapter.toRequestBody({model:request.model,maxTokens:request.maxTokens,...request.system!==void 0?{system:request.system}:{},messages:request.messages,...request.tools!==void 0?{tools:request.tools}:{},promptCache:request.promptCache??"explicit"}),hooks.signal)}catch(err){if(isAbortError(err)||hooks.signal?.aborted===true){return{text:"",usage:emptyUsage(),toolUses:[],stopReason:null,aborted:true,upstreamError:null}}throw err}const body=res.
54
- body;if(!body){throw new RelayError("upstream","\u30EA\u30EC\u30FC\u304C\u5FDC\u7B54\u672C\u6587\u3092\u8FD4\u3057\u307E\u305B\u3093\u3067\u3057\u305F")}const parser=new SseParser;const decoder=new TextDecoder;const usage=emptyUsage();let text="";let stopReason=null;let streamError=null;const reader=body.getReader();const building=new Map;const toolUses=[];const finalizeBlock=index=>{const pending=building.get(index);if(!pending)return;building.delete(index);const input=pending.json.trim()===""?
55
- {}:safeJson5(pending.json);if(input===null){streamError=`\u30C4\u30FC\u30EB ${pending.name} \u306E\u5F15\u6570\u3092\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F`;return}toolUses.push({type:"tool_use",id:pending.id,name:pending.name,input})};const apply=ev=>{switch(ev.kind){case"usage":Object.assign(usage,ev.usage);return;case"text":text+=ev.delta;hooks.onTextDelta(ev.delta);return;case"tool_start":building.set(ev.index,{id:ev.id,name:ev.name,json:ev.initialJson});return;case"tool\
56
- _delta":{const pending=building.get(ev.index);if(pending)pending.json+=ev.json;return}case"tool_end":finalizeBlock(ev.index);return;case"stop":stopReason=ev.reason;return;case"error":streamError=ev.message;return}};const handle=events=>{for(const ev of events){for(const neutral of adapter.decode(ev))apply(neutral)}};const onAbort=()=>{void reader.cancel().catch(()=>void 0)};if(hooks.signal){if(hooks.signal.aborted)onAbort();else hooks.signal.addEventListener("abort",onAbort,{once:true})}try{for(;;){
57
- const{done,value}=await reader.read();if(done)break;handle(parser.push(decoder.decode(value,{stream:true})))}handle(parser.flush())}catch(err){if(err instanceof SseBufferOverflowError){streamError=err.message}else if(!isAbortError(err)&&hooks.signal?.aborted!==true){throw new RelayError("network",`\u30B9\u30C8\u30EA\u30FC\u30E0\u304C\u5207\u65AD\u3055\u308C\u307E\u3057\u305F: ${errorMessage(err)}`)}}finally{hooks.signal?.removeEventListener("abort",onAbort);void reader.cancel().catch(()=>void 0)}
58
- for(const index of[...building.keys()])finalizeBlock(index);return{text,usage,toolUses,stopReason,aborted:hooks.signal?.aborted===true,upstreamError:streamError===null?null:stripTerminalControls(streamError)}}async send(method,path2,body,signal){let token;try{token=await this.session.getAccessToken()}catch(err){throw new RelayError("not_logged_in",errorMessage(err))}let res=await this.fetchOrThrow(method,path2,token,body,signal);if(res.status===401){try{token=await this.session.refresh(token)}catch(err){
59
- throw new RelayError("not_logged_in",errorMessage(err))}res=await this.fetchOrThrow(method,path2,token,body,signal)}if(!res.ok)throw await toRelayError(res);return res}async fetchOrThrow(method,path2,token,body,signal){try{return await this.fetchImpl(`${this.relayUrl}${path2}`,{method,headers:{Accept:body===void 0?"application/json":"text/event-stream, application/json",Authorization:`Bearer ${token}`,"User-Agent":`twp-cli/${this.cliVersion}`,[PROTOCOLS_HEADER]:supportedProtocols().join(","),...body!==
60
- void 0?{"Content-Type":"application/json"}:{}},...body!==void 0?{body:JSON.stringify(body)}:{},...signal?{signal}:{}})}catch(err){if(isAbortError(err))throw err;throw new RelayError("network",`\u30E2\u30C7\u30EB\u53D6\u6B21\u30B5\u30FC\u30D0\u306B\u63A5\u7D9A\u3067\u304D\u307E\u305B\u3093\uFF08${this.relayUrl}\uFF09: ${errorMessage(err)}`)}}};async function toRelayError(res){const body=await res.json().catch(()=>null);const nested=typeof body?.error==="object"&&body.error!==null?body.error:void 0;
61
- const message=stripTerminalControls(body?.message??nested?.message??`HTTP ${res.status}`);if(res.status===401){return new RelayError("unauthorized","\u30E2\u30C7\u30EB\u53D6\u6B21\u306E\u8A8D\u8A3C\u306B\u5931\u6557\u3057\u307E\u3057\u305F\u3002`twp login`\uFF08\u30D6\u30E9\u30A6\u30B6\u59D4\u8B72\uFF09\u307E\u305F\u306F `twp login --password` \u3067\u30ED\u30B0\u30A4\u30F3\u3057\u76F4\u3057\u3066\u304F\u3060\u3055\u3044\uFF08`twp login --token` \u3067\u4FDD\u5B58\u3057\u305F\u901A\u5E38\u30C8\u30FC\u30AF\u30F3\u306F\u30E2\u30C7\u30EB\u53D6\u6B21\u306B\u306F\u4F7F\u3048\u307E\u305B\u3093\uFF09\u3002",
62
- 401)}if(res.status===403){return new RelayError("cli_disabled",message,403)}if(res.status===429){return new RelayError("rate_limit",message,429)}if(res.status===400){const detail=body?.details;if(Array.isArray(detail?.allowed_models)){return new RelayError("model_not_allowed",`${message}
63
- \u5229\u7528\u3067\u304D\u308B\u30E2\u30C7\u30EB: ${detail.allowed_models.join(" / ")}`,400)}return new RelayError("validation",message,400)}if(res.status===413){return new RelayError("validation","\u9001\u4FE1\u3059\u308B\u4F1A\u8A71\u304C\u5927\u304D\u3059\u304E\u3066\u30E2\u30C7\u30EB\u53D6\u6B21\u30B5\u30FC\u30D0\u304C\u53D7\u3051\u4ED8\u3051\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u4E0A\u9650 4MiB\uFF09\u3002`/clear` \u3067\u5C65\u6B74\u3092\u6D88\u3059\u304B\u3001\u8CBC\u308A\u4ED8\u3051\u305F\u5185\u5BB9\u30FB\u8AAD\u307F\u8FBC\u3080\u30D5\u30A1\u30A4\u30EB\u3092\u5C0F\u3055\u304F\u3057\u3066\u3084\u308A\u76F4\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
64
- 413)}if(res.status===503){return new RelayError("unavailable",message,503)}return new RelayError("upstream",message,res.status)}function safeJson5(text){try{const parsed=JSON.parse(text);return typeof parsed==="object"&&parsed!==null?parsed:null}catch{return null}}function isAbortError(err){return err instanceof Error&&(err.name==="AbortError"||err.name==="TimeoutError")}function errorMessage(err){return err instanceof Error?err.message:String(err)}var DEFAULT_CONTEXT_WINDOW_TOKENS=2e5;var DEFAULT_MAX_TOKENS=8192;var TRIM_THRESHOLD=.8;var RELAY_BODY_LIMIT_BYTES=4*1024*1024;var BODY_SAFETY_MARGIN_BYTES=256*1024;var DEFAULT_MAX_HISTORY_BYTES=RELAY_BODY_LIMIT_BYTES-BODY_SAFETY_MARGIN_BYTES;var ContextManager=class{constructor(defaultContextWindowTokens=DEFAULT_CONTEXT_WINDOW_TOKENS){this.defaultContextWindowTokens=defaultContextWindowTokens;this.contextWindowTokens=defaultContextWindowTokens}defaultContextWindowTokens;messages=[];totals=emptyUsage();turns=0;lastPromptTokens=0;pendingChars=0;droppedMessages=0;pinnedHead=false;historyTail=null;currentUser=null;contextWindowTokens;setContextWindow(tokens){
65
- this.contextWindowTokens=tokens!==null&&tokens>0?tokens:this.defaultContextWindowTokens}addUser(text){this.pendingChars+=text.length;const last=this.messages[this.messages.length-1];if(last?.role==="user"){last.content.push({type:"text",text});this.currentUser=last;return}const message={role:"user",content:[{type:"text",text}]};this.messages.push(message);this.currentUser=message}restoreHistory(messages){if(this.messages.length>0){throw new Error("\u5C65\u6B74\u306F\u6700\u521D\u306E\u30E6\u30FC\u30B6\u30FC\u30BF\u30FC\u30F3\u3088\u308A\u524D\u306B\u3060\u3051\u7A4D\u3081\u307E\u3059")}
66
- let skippedLeadingAssistant=0;for(const m of messages){if(m.content==="")continue;const last=this.messages[this.messages.length-1];if(last===void 0&&m.role==="assistant"){skippedLeadingAssistant+=1;continue}if(last?.role===m.role){last.content.push({type:"text",text:m.content})}else{this.messages.push({role:m.role,content:[{type:"text",text:m.content}]})}this.pendingChars+=m.content.length}this.pinnedHead=this.messages.length>0;const tail=this.messages[this.messages.length-1];this.historyTail=tail?.
67
- role==="user"?{message:tail,blocks:tail.content.length}:null;return{messages:this.messages.length,skippedLeadingAssistant}}addToolExchange(assistantText,toolUses,results){if(toolUses.length===0)return;const blocks=[];if(assistantText.trim()!=="")blocks.push({type:"text",text:assistantText});blocks.push(...toolUses);this.messages.push({role:"assistant",content:blocks});this.messages.push({role:"user",content:results});this.pendingChars+=blocks.reduce((n,b)=>n+blockLength(b),0);this.pendingChars+=
68
- results.reduce((n,b)=>n+blockLength(b),0)}completeTurn(assistantText){const text=assistantText.trim();if(text===""){const last=this.messages[this.messages.length-1];if(last?.role==="user"&&!hasToolResult(last)){const tail=this.historyTail;if(tail!==null&&tail.message===last&&last.content.length>tail.blocks){const removed=last.content.splice(tail.blocks);this.pendingChars=Math.max(0,this.pendingChars-removed.reduce((n,b)=>n+blockLength(b),0))}else{this.messages.pop();this.pendingChars=Math.max(0,
69
- this.pendingChars-lengthOf(last))}}return false}this.messages.push({role:"assistant",content:[{type:"text",text:assistantText}]});this.pendingChars+=assistantText.length;this.turns+=1;this.historyTail=null;return true}applyUsage(usage){this.totals={inputTokens:this.totals.inputTokens+usage.inputTokens,cacheReadTokens:this.totals.cacheReadTokens+usage.cacheReadTokens,cacheWriteTokens:this.totals.cacheWriteTokens+usage.cacheWriteTokens,outputTokens:this.totals.outputTokens+usage.outputTokens};const prompt=usage.
70
- inputTokens+usage.cacheReadTokens+usage.cacheWriteTokens;if(prompt>0){this.lastPromptTokens=prompt;this.pendingChars=0}}history(){return this.messages.map(m=>({role:m.role,content:m.content.map(copyBlock)}))}isEmpty(){return this.messages.length===0}clear(){this.messages=[];this.totals=emptyUsage();this.turns=0;this.lastPromptTokens=0;this.pendingChars=0;this.droppedMessages=0;this.pinnedHead=false;this.historyTail=null;this.currentUser=null}trimToFit(maxTokens=DEFAULT_MAX_TOKENS,maxHistoryBytes=DEFAULT_MAX_HISTORY_BYTES){
71
- const limit=Math.max(1,Math.floor((this.contextWindowTokens-maxTokens)*TRIM_THRESHOLD));let dropped=0;let bytes=this.messages.reduce((sum,m)=>sum+bytesOf(m),0);const over=()=>this.estimatedPromptTokens()>limit||bytes>maxHistoryBytes;const dropAt=index=>{const[removed]=this.messages.splice(index,1);if(!removed)return;this.lastPromptTokens=Math.max(0,this.lastPromptTokens-Math.ceil(lengthOf(removed)/4));bytes-=bytesOf(removed);dropped+=1};if(this.pinnedHead){const current=()=>{const tracked=this.currentUser===
72
- null?-1:this.messages.indexOf(this.currentUser);if(tracked>0)return tracked;for(let i=this.messages.length-1;i>0;i--){const m=this.messages[i];if(m?.role==="user"&&!hasToolResult(m))return i}return 0};while(over()&&this.messages[1]?.role==="assistant"&&current()>2){dropAt(1);dropAt(1)}while(over()){const cur=current();if(this.messages.length-cur<4||this.messages[cur+1]?.role!=="assistant")break;dropAt(cur+1);dropAt(cur+1)}if(over())this.pinnedHead=false}while((this.estimatedPromptTokens()>limit||
73
- bytes>maxHistoryBytes)&&this.messages.length>1){const removed=this.messages.shift();if(!removed)break;const removedTokens=Math.ceil(lengthOf(removed)/4);this.lastPromptTokens=Math.max(0,this.lastPromptTokens-removedTokens);bytes-=bytesOf(removed);dropped+=1}while(this.messages.length>0){const head2=this.messages[0];if(!head2)break;const orphanResult=hasToolResult(head2)&&this.messages.length>1;if(head2.role!=="assistant"&&!orphanResult)break;this.messages.shift();this.lastPromptTokens=Math.max(0,
74
- this.lastPromptTokens-Math.ceil(lengthOf(head2)/4));dropped+=1}const head=this.messages[0];if(head&&hasToolResult(head)){const before=lengthOf(head);const kept=head.content.filter(block=>block.type!=="tool_result");head.content=kept.length>0?kept:[{type:"text",text:"\uFF08\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u4E0A\u9650\u306E\u305F\u3081\u3001\u76F4\u524D\u306E\u30C4\u30FC\u30EB\u5B9F\u884C\u7D50\u679C\u306F\u5C65\u6B74\u304B\u3089\u5916\u308C\u307E\u3057\u305F\uFF09"}];const freed=before-lengthOf(
75
- head);this.lastPromptTokens=Math.max(0,this.lastPromptTokens-Math.ceil(freed/4));this.pendingChars=Math.max(0,this.pendingChars-freed);dropped+=1}this.droppedMessages+=dropped;return dropped}estimatedPromptTokens(){if(this.lastPromptTokens===0){return Math.ceil(this.totalChars()/4)}return this.lastPromptTokens+Math.ceil(this.pendingChars/4)}snapshot(){const used=this.estimatedPromptTokens();const remaining=Math.round((this.contextWindowTokens-used)/this.contextWindowTokens*100);return{totals:{...this.
76
- totals},turns:this.turns,lastPromptTokens:this.lastPromptTokens,remainingPercent:Math.max(0,Math.min(100,remaining)),contextWindowTokens:this.contextWindowTokens,droppedMessages:this.droppedMessages}}totalChars(){return this.messages.reduce((sum,m)=>sum+lengthOf(m),0)}};function bytesOf(message){return Buffer.byteLength(JSON.stringify(message),"utf8")+1}function lengthOf(message){return message.content.reduce((sum,block)=>sum+blockLength(block),0)}function copyBlock(block){return block.type==="t\
77
- ool_use"?{...block,input:{...block.input}}:{...block}}function hasToolResult(message){return message.content.some(block=>block.type==="tool_result")}function formatContextRemaining(snapshot){return`\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u6B8B\u91CF: ${snapshot.remainingPercent}%\uFF08\u7A93 ${snapshot.contextWindowTokens.toLocaleString("en-US")} tok \u306E\u6982\u7B97\uFF09`}function createRuntime(opts){const env=opts.env??process.env;const cwd=opts.cwd??process.cwd();const profile=resolveProfile(opts.profile,env,cwd);const creds=loadCredentials(profile.name,env);const apiUrl=effectiveApiUrl(profile,creds?.api_url,env);const relayUrl=effectiveRelayUrl(profile,creds?.relay_url,env);const session=new AuthSession(profile.name,apiUrl,env);const client=new RelayClient(relayUrl,session,httpFetch,opts.cliVersion);const configured=resolveConfiguredModel(opts.model,profile.name,
78
- env,cwd);return{profileName:profile.name,apiUrl,relayUrl,client,session,context:new ContextManager,loggedIn:creds!==null,configuredModel:configured?.model??null,loadCatalog:()=>loadCatalog(client,profile.name,relayUrl,env),loadCachedFloor:()=>loadCachedVersionFloor(profile.name,relayUrl,env),loadCachedCatalog:()=>loadCachedCatalog(profile.name,relayUrl,env)}}export{emptyUsage,DEFAULT_MAX_TOKENS,DEFAULT_MAX_HISTORY_BYTES,formatContextRemaining,modelLabel,toModelInfos,effectiveModelSpec,builtinCatalog,loadCachedCatalog,pickModel,specFor,classifyModelSwitch,RelayError,createRuntime};
@@ -1,9 +0,0 @@
1
- import { createRequire as __twpCreateRequire } from 'node:module';
2
- const require = __twpCreateRequire(import.meta.url);
3
- import{loadCredentials,saveCredentialsUnlocked,withCredentialsLock}from"./chunk-GWVREACM.js";import{httpFetch}from"./chunk-J7QYPKVK.js";var NotLoggedInError=class extends Error{constructor(profile){super(`\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u300C${profile}\u300D\u306F\u30ED\u30B0\u30A4\u30F3\u3057\u3066\u3044\u307E\u305B\u3093\u3002twp login \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}};var SessionExpiredError=class extends Error{constructor(profile){super(`\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u300C${profile}\u300D\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u5931\u52B9\u3057\u307E\u3057\u305F\uFF08refresh token \u304C\u7121\u52B9\uFF09\u3002twp login \u3067\u30ED\u30B0\u30A4\u30F3\u3057\u76F4\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}};
4
- var EXPIRY_MARGIN_MS=6e4;var AuthSession=class{constructor(profile,apiUrl,env=process.env,fetchImpl=httpFetch,now=Date.now){this.profile=profile;this.apiUrl=apiUrl;this.env=env;this.fetchImpl=fetchImpl;this.now=now}profile;apiUrl;env;fetchImpl;now;refreshInFlight=null;loadOrThrow(){const creds=loadCredentials(this.profile,this.env);if(!creds)throw new NotLoggedInError(this.profile);return creds}async getAccessToken(){const creds=this.loadOrThrow();if(!this.isExpiring(creds))return creds.token;if(!creds.
5
- refresh_token){if(this.isExpired(creds))throw new SessionExpiredError(this.profile);return creds.token}return this.refresh(creds.token)}refresh(usedToken){if(this.refreshInFlight)return this.refreshInFlight;this.refreshInFlight=this.refreshLocked(usedToken).finally(()=>{this.refreshInFlight=null});return this.refreshInFlight}async refreshLocked(usedToken){return withCredentialsLock(this.env,async()=>{const onDisk=this.loadOrThrow();if(onDisk.token!==usedToken&&!this.isExpiring(onDisk))return onDisk.
6
- token;if(!onDisk.refresh_token)throw new SessionExpiredError(this.profile);const result=await this.callRefreshApi(onDisk.refresh_token);if(result.ok){this.persist(onDisk,result.body);return result.body.token}const reread=this.loadOrThrow();if(reread.refresh_token&&reread.refresh_token!==onDisk.refresh_token){const retry=await this.callRefreshApi(reread.refresh_token);if(retry.ok){this.persist(reread,retry.body);return retry.body.token}}throw new SessionExpiredError(this.profile)})}async callRefreshApi(refreshToken){
7
- const res=await this.fetchImpl(`${this.apiUrl}/api/v2/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({refresh_token:refreshToken})});const body=await res.json().then(parsed=>parsed,()=>null);if(res.ok&&body?.result&&typeof body.token==="string"){return{ok:true,body}}return{ok:false}}persist(prev,body){saveCredentialsUnlocked(this.profile,{...prev,token:body.token,token_expires_at:body.token_expires_at??null,refresh_token:body.
8
- refresh_token??prev.refresh_token,refresh_token_expires_at:body.refresh_token_expires_at??prev.refresh_token_expires_at,user:body.user??prev.user,saved_at:new Date(this.now()).toISOString()},this.env)}isExpiring(creds){if(!creds.token_expires_at)return false;const at=Date.parse(creds.token_expires_at);return Number.isFinite(at)&&at-this.now()<EXPIRY_MARGIN_MS}isExpired(creds){if(!creds.token_expires_at)return false;const at=Date.parse(creds.token_expires_at);return Number.isFinite(at)&&at<=this.
9
- now()}};export{NotLoggedInError,SessionExpiredError,AuthSession};
@@ -1,15 +0,0 @@
1
- import { createRequire as __twpCreateRequire } from 'node:module';
2
- const require = __twpCreateRequire(import.meta.url);
3
- import{configReadDirs}from"./chunk-RZVI6PMW.js";import{constants as fsConstants,lstatSync,readlinkSync,realpathSync,statSync}from"fs";import{open}from"fs/promises";import{homedir}from"os";import{dirname,isAbsolute,relative,resolve,sep}from"path";var PathDeniedError=class extends Error{constructor(message){super(message);this.name="PathDeniedError"}};function resolveToolPath(input,cwd,home=homedir()){if(typeof input!=="string"||input.trim()===""){throw new PathDeniedError("path must be a non-empty string")}const expanded=expandHome(input,home);const abs=isAbsolute(expanded)?resolve(expanded):resolve(cwd,expanded);const root=realOrSelf(resolve(cwd));assertInside(abs,resolve(cwd),input);assertNotSecret(abs,home,process.env,input);assertNotGitMetadata(
4
- abs,resolve(cwd),input);const real=realOrSelf(abs);if(real!==abs){assertInside(real,root,input);assertNotSecret(real,home,process.env,input);assertNotGitMetadata(real,root,input)}assertPlainEntry(real,input);return abs}function realToolPath(input,cwd,home=homedir()){return realOrSelf(resolveToolPath(input,cwd,home))}function assertInside(target,root,reported){const rel=relative(root,target);const outside=rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel);if(outside){throw new PathDeniedError(
5
- `path escapes the working directory (${reported}). Only paths under the working directory can be accessed.`)}}function gitMetadataReason(absPath,root){const rel=relative(root,absPath);if(rel===""||rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel))return null;return rel.toLowerCase().split(sep).includes(".git")?"git metadata (.git) is denied; use the git tool to inspect history":null}function assertNotGitMetadata(absPath,root,reported){const reason=gitMetadataReason(absPath,root);if(reason!==
6
- null)throw new PathDeniedError(`refusing to access ${reported}: ${reason}`)}function assertPlainEntry(real,reported){let info;try{info=statSync(real)}catch{return}const reason=plainEntryReason(info);if(reason!==null)throw new PathDeniedError(`refusing to access ${reported}: ${reason}`)}function plainEntryReason(info){if(info.isDirectory())return null;if(!info.isFile())return"not a regular file (FIFO, socket and device files are denied)";if(info.nlink>1)return"hard links are denied (the file has \
7
- another name that may be outside the working directory)";return null}function specialFileReason(absPath){try{return plainEntryReason(statSync(absPath))}catch{return null}}var O_NONBLOCK=fsConstants.O_NONBLOCK??0;async function openPlainFile(absPath,reported,mode){const flags=mode==="write"?fsConstants.O_RDWR|fsConstants.O_CREAT|O_NONBLOCK:mode==="update"?fsConstants.O_RDWR|O_NONBLOCK:fsConstants.O_RDONLY|O_NONBLOCK;let handle;try{handle=await open(absPath,flags,438)}catch(err){if(err.code==="ENO\
8
- ENT"&&mode!=="write")return null;throw err}try{const info=await handle.stat();if(info.isDirectory())throw Object.assign(new Error(`${reported} is a directory`),{code:"EISDIR"});const reason=plainEntryReason(info);if(reason!==null)throw new PathDeniedError(`refusing to access ${reported}: ${reason}`)}catch(err){await handle.close();throw err}return handle}async function replaceContent(handle,text){const buf=Buffer.from(text,"utf8");await handle.truncate(0);let offset=0;while(offset<buf.length){const{
9
- bytesWritten}=await handle.write(buf,offset,buf.length-offset,offset);offset+=bytesWritten}}function isGitMetadata(abs,cwd){const root=resolve(cwd);return gitMetadataReason(abs,root)!==null||gitMetadataReason(realOrSelf(abs),realOrSelf(root))!==null}function redactPaths(text,cwd,home=homedir()){const roots=[];for(const dir of new Set([resolve(cwd),realOrSelf(resolve(cwd))]))roots.push([dir,"."]);if(home!==""&&home!==sep){for(const dir of new Set([resolve(home),realOrSelf(resolve(home))]))roots.push(
10
- [dir,"~"])}roots.sort((a,b)=>b[0].length-a[0].length);let out=text;for(const[dir,label]of roots){if(dir===sep)continue;const sepClass=sep==="\\"?"[\\\\/]":"/";const escaped=dir.split(sep).map(part=>part.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(sepClass);out=out.replace(new RegExp(`(?<![\\w./\\\\-])${escaped}(?=${sepClass}|$|[^\\w.-]|\\.(?![\\w-]))`,sep==="\\"?"gi":"g"),label)}return out}function realOrSelf(target){let current=target;const rest=[];let hops=0;for(;;){try{const real=realpathSync(
11
- current);return rest.length===0?real:resolve(real,...rest.reverse())}catch{let link=null;try{if(lstatSync(current).isSymbolicLink())link=readlinkSync(current)}catch{link=null}if(link!==null&&hops<40){hops+=1;current=resolve(dirname(current),link);continue}const parent=dirname(current);if(parent===current)return target;rest.push(current.slice(parent.length+1));current=parent}}}function assertNotSecret(absPath,home=homedir(),env=process.env,reported=absPath){const reason=secretReason(absPath,home,
12
- env);if(reason!==null)throw new PathDeniedError(`refusing to access ${reported}: ${reason}`)}function secretReason(absPath,_home=homedir(),env=process.env){const lower=absPath.toLowerCase();const segments=lower.split(sep);const base=segments[segments.length-1]??"";const parent=segments[segments.length-2]??"";if(base===".env"||base.startsWith(".env."))return".env files are denied (design \xA77)";if(segments.includes(".ssh"))return"SSH key material is denied (design \xA77)";if(parent===".git"&&base===
13
- "config"){return".git/config is denied (it can hold a GitHub token in the remote URL)"}if(base===".netrc"||base==="_netrc"||base===".npmrc")return"credential files are denied";if(parent===".aws"&&(base==="credentials"||base==="config"))return"AWS credentials are denied";for(const dir of configReadDirs(env)){if(lower===resolve(dir,"credentials.json").toLowerCase()){return"TWP credentials are denied (design \xA77)"}}if(parent===".twp"&&base==="credentials.json")return"TWP credentials are denied (d\
14
- esign \xA77)";if(parent==="logs"&&base.startsWith("session-")&&base.endsWith(".jsonl")){const grandparent=segments[segments.length-3]??"";if(grandparent===".twp")return"TWP audit logs are denied (design \xA77)";for(const dir of configReadDirs(env)){if(lower.startsWith(resolve(dir,"logs").toLowerCase()+sep)){return"TWP audit logs are denied (design \xA77)"}}}return null}function toolRelative(cwd,absPath){const rel=relative(cwd,absPath);return sep==="\\"?rel.split("\\").join("/"):rel}function isInsideCwd(absPath,cwd){
15
- const root=resolve(cwd);if(!withinLexically(absPath,root))return false;const real=realOrSelf(absPath);return real===absPath||withinLexically(real,realOrSelf(root))}function withinLexically(target,root){const rel=relative(root,target);return!(rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel))}function expandHome(input,home){if(input==="~")return home;if(input.startsWith("~/")||input.startsWith(`~${sep}`))return resolve(home,input.slice(2));return input}export{PathDeniedError,resolveToolPath,realToolPath,specialFileReason,openPlainFile,replaceContent,isGitMetadata,redactPaths,realOrSelf,secretReason,toolRelative,isInsideCwd};
@@ -1,46 +0,0 @@
1
- import { createRequire as __twpCreateRequire } from 'node:module';
2
- const require = __twpCreateRequire(import.meta.url);
3
- import{activateModeFiles,activatePermissionSettings,buildResidentSet,buildSystemPrompt,createAuditLogger,createTwpToolkit,currentBranch,displayCwd,residentInputs,runTurn}from"./chunk-X2C2UVJA.js";import"./chunk-DEIIS7JP.js";import"./chunk-UQP47QOV.js";import"./chunk-N2UVRM3Z.js";import"./chunk-BD7O73GK.js";import"./chunk-QLH5IJQV.js";import"./chunk-3CEGTEI3.js";import"./chunk-CJFIIGSH.js";import"./chunk-HVZUXLQ4.js";import"./chunk-YJP4FUY4.js";
4
- import"./chunk-SBRTBKEZ.js";import"./chunk-STILP3Z6.js";import{RelayError,createRuntime,emptyUsage,pickModel,specFor}from"./chunk-CASLLD23.js";import"./chunk-D233KKXW.js";import"./chunk-PMOUHEJQ.js";import"./chunk-ITFO5GPX.js";import"./chunk-GWVREACM.js";import"./chunk-J7QYPKVK.js";import{checkMinSupportedVersion,enforceMinSupportedVersion,floorNeedsRefresh}from"./chunk-DXXFUNYN.js";import"./chunk-EDF4U5BT.js";import"./chunk-RZVI6PMW.js";
5
- import{getMode}from"./chunk-2LOT54OO.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";var STREAM_JSON_VERSION=1;var fail=reason=>({ok:false,reason});var INPUT_PARSERS={user:obj=>{const content=obj.content;if(typeof content==="string"){return content.trim()===""?fail("user.content \u304C\u7A7A\u3067\u3059"):{ok:true,line:{type:"user",text:content}}}if(!Array.isArray(content)||content.length===0){return fail("user.content \u306F\u6587\u5B57\u5217\u304B\u3001\u30D6\u30ED\u30C3\u30AF\u306E\u914D\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044")}const texts=[];for(const block of content){
6
- if(typeof block!=="object"||block===null)return fail("user.content \u306E\u8981\u7D20\u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");const b=block;if(b.type!=="text"){return fail(`user.content \u306E\u30D6\u30ED\u30C3\u30AF\u7A2E\u5225 ${JSON.stringify(b.type)} \u306B\u306F\u672A\u5BFE\u5FDC\u3067\u3059\uFF08\u5BFE\u5FDC: text\uFF09`)}if(typeof b.text!=="string")return fail("text \u30D6\u30ED\u30C3\u30AF\u306E text \u306F\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
7
- texts.push(b.text)}const text=texts.join("");return text.trim()===""?fail("user.content \u304C\u7A7A\u3067\u3059"):{ok:true,line:{type:"user",text}}},interrupt:()=>({ok:true,line:{type:"interrupt"}}),history:obj=>{if(!Array.isArray(obj.messages))return fail("history.messages \u306F\u914D\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");const messages=[];for(const[i,m]of obj.messages.entries()){if(typeof m!=="object"||m===null)return fail(`history.messages[${i}] \u306F\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`);
8
- const{role,content}=m;if(role!=="user"&&role!=="assistant"){return fail(`history.messages[${i}].role \u306F user \u304B assistant \u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`)}if(typeof content!=="string")return fail(`history.messages[${i}].content \u306F\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`);messages.push({role,content})}return{ok:true,line:{type:"history",messages}}},permission_response:obj=>{const{request_id:requestId,decision,message}=obj;if(typeof requestId!==
9
- "string"||requestId==="")return fail("permission_response.request_id \u306F\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");if(decision!=="allow"&&decision!=="deny"){return fail("permission_response.decision \u306F allow \u304B deny \u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044")}if(message!==void 0&&typeof message!=="string")return fail("permission_response.message \u306F\u6587\u5B57\u5217\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");return{ok:true,
10
- line:{type:"permission_response",request_id:requestId,decision,...message!==void 0?{message}:{}}}}};var INPUT_TYPES=Object.keys(INPUT_PARSERS);function parseInputLine(raw){let obj;try{obj=JSON.parse(raw)}catch{return fail("JSON \u3068\u3057\u3066\u89E3\u91C8\u3067\u304D\u307E\u305B\u3093")}if(typeof obj!=="object"||obj===null||Array.isArray(obj))return fail("\u884C\u306F JSON \u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");const rec=obj;if(rec.v!==void 0&&
11
- rec.v!==STREAM_JSON_VERSION){return fail(`\u672A\u5BFE\u5FDC\u306E\u7248\u3067\u3059: v=${JSON.stringify(rec.v)}\uFF08\u5BFE\u5FDC: ${STREAM_JSON_VERSION}\uFF09`)}const type=rec.type;if(typeof type!=="string"||!Object.hasOwn(INPUT_PARSERS,type)){return fail(`\u672A\u77E5\u306E type \u3067\u3059: ${JSON.stringify(type)}\uFF08\u5BFE\u5FDC: ${INPUT_TYPES.join(" / ")}\uFF09`)}return INPUT_PARSERS[type](rec)}function usageFields(u){return{input_tokens:u.inputTokens,cache_read_tokens:u.cacheReadTokens,
12
- cache_write_tokens:u.cacheWriteTokens,output_tokens:u.outputTokens}}function formatOutputLine(line){return`${JSON.stringify({v:STREAM_JSON_VERSION,...line})}
13
- `}async function runOneShot(opts,deps={}){const out=deps.out??(text=>void process.stdout.write(stripTerminalControls(text)));const err=deps.err??(text=>void process.stderr.write(stripTerminalControls(text)));activateModeFiles(err);const permissionLayers=activatePermissionSettings(err,{...opts.allowedTools?{allowedTools:opts.allowedTools}:{},...opts.disallowedTools?{disallowedTools:opts.disallowedTools}:{}});const streamIn=opts.inputFormat==="stream-json";const streamOut=opts.outputFormat==="stream\
14
- -json";if(streamIn&&!opts.fromStdin){err("--input-format stream-json \u306F `-p -`\uFF08\u6A19\u6E96\u5165\u529B\uFF09\u3068\u7D44\u307F\u5408\u308F\u305B\u3066\u304F\u3060\u3055\u3044\n");return 2}const promptStdio=opts.permissionPrompt==="stdio";if(promptStdio&&!(streamIn&&streamOut)){err("--permission-prompt stdio \u306F --input-format stream-json \u3068 --output-format stream-json \u306E\u4E21\u65B9\u3068\u7D44\u307F\u5408\u308F\u305B\u3066\u304F\u3060\u3055\u3044\n");return 2}const emit=line=>out(
15
- formatOutputLine(line));const prompt=streamIn?"":opts.fromStdin?await(deps.readStdin??readStdin)():opts.prompt;if(!streamIn&&prompt.trim()===""){err('\u30D7\u30ED\u30F3\u30D7\u30C8\u304C\u7A7A\u3067\u3059\u3002`twp -p "\u8CEA\u554F"`\uFF08`-p -` \u3067\u6A19\u6E96\u5165\u529B\uFF09\n');return 2}const runtime=deps.runtime??createRuntime({...opts.profile!==void 0?{profile:opts.profile}:{},...opts.model!==void 0?{model:opts.model}:{},cliVersion:opts.version});const cachedFloor=runtime.loadCachedFloor();
16
- if(await checkMinSupportedVersion({current:opts.version,cachedFloor:cachedFloor.minSupportedVersion,refresh:async()=>(await runtime.loadCatalog()).minSupportedVersion,write:err})){return 1}if(!runtime.loggedIn){err("\u30ED\u30B0\u30A4\u30F3\u3057\u3066\u3044\u307E\u305B\u3093\u3002`twp login` \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002\n");return 1}let model=runtime.configuredModel??"";let catalog=null;if(model===""){catalog=await runtime.loadCatalog();const picked=pickModel(catalog,
17
- void 0);model=picked.model;if(catalog.source!=="server"){err(`\u26A0 \u30E2\u30C7\u30EB\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u306A\u304B\u3063\u305F\u305F\u3081 ${model} \u3067\u5B9F\u884C\u3057\u307E\u3059\uFF08${catalog.source}\uFF09
18
- `)}}else if(floorNeedsRefresh(cachedFloor.fetchedAt)){catalog=await runtime.loadCatalog()}if(catalog!==null&&enforceMinSupportedVersion({current:opts.version,floor:catalog.minSupportedVersion,write:err})){return 1}let controller=new AbortController;let interrupted=false;const sessionStop=new AbortController;const onSigint=()=>{interrupted=true;controller.abort();sessionStop.abort()};process.on("SIGINT",onSigint);let ownedAudit=null;let cancelCatalogRefresh=()=>void 0;try{const mode=getMode(opts.
19
- mode);const toolkit=createTwpToolkit(runtime,opts.version);void toolkit.refreshCatalog();cancelCatalogRefresh=()=>toolkit.cancelCatalogRefresh();const resident=buildResidentSet(mode,{...residentInputs(toolkit),...opts.permissionMode!==void 0?{permissionMode:opts.permissionMode}:{},permissionLayers});const audit=deps.audit??(ownedAudit=createAuditLogger({mode:mode.id,permissionMode:opts.permissionMode,model,cwd:process.cwd(),cliVersion:opts.version,interactive:false,onOpen:file=>err(`audit: ${file}\
20
-
21
- `)}));const spec=specFor(catalog??runtime.loadCachedCatalog?.()??{ids:[],source:"builtin",fetchedAt:null,minSupportedVersion:null},model);const turnTools=spec.tools?resident.tools:[];const system=buildSystemPrompt({cwd:displayCwd(),branch:currentBranch(),modeLabel:mode.label,cliVersion:opts.version,toolNames:turnTools.map(t=>t.name),...mode.prompt!==void 0?{modePrompt:mode.prompt}:{}});const prompter=promptStdio?createStdioPrompter(emit,()=>controller.signal):null;const execute={mode,ctx:{cwd:process.
22
- cwd()},sessionAllow:new Set,permissionLayers,...opts.permissionMode!==void 0?{permissionMode:opts.permissionMode}:{},resolveTool:toolkit.resolveTool,prepareIndirect:toolkit.prepareIndirect,audit,...prompter!==null?{askPermission:prompter.ask,approver:"embedder"}:{}};const runOneTurn=async input=>{controller=new AbortController;if(interrupted)controller.abort();let wroteText=false;let pendingText="";const flushAssistant=()=>{if(pendingText!=="")emit({type:"assistant",content:pendingText});pendingText=
23
- ""};const finish=(code,r,error)=>{if(streamOut){flushAssistant();emit({type:"result",subtype:code===0?"success":code===130?"interrupted":"error",exit_code:code,text:r.text,...error!==void 0?{error}:{},tool_calls:r.toolCalls,dropped_messages:r.droppedMessages,usage:usageFields(r.usage)})}return code};try{const result=await runTurn(runtime.client,runtime.context,{input,model,spec,system,signal:controller.signal,onTextDelta:delta=>{if(streamOut){pendingText+=delta;return}wroteText=true;out(stripTerminalControls(
24
- delta))},tools:turnTools,execute,onToolUse:call=>{if(streamOut){flushAssistant();emit({type:"tool_use",id:call.id,name:call.name,input:call.input});return}if(wroteText){out("\n");wroteText=false}},onToolResult:(call,result2)=>{const status=result2.denied===true?"denied":result2.isError===true?"error":"ok";if(streamOut){emit({type:"tool_result",tool_use_id:call.id,name:call.name,status,content:result2.content});return}err(`tool: ${call.name} \u2192 ${status}
25
- `)},...streamOut?{onUsage:u2=>{flushAssistant();emit({type:"usage",model,...usageFields(u2)})}}:{}});if(!streamOut&&result.text!==""&&!result.text.endsWith("\n"))out("\n");const u=result.usage;if(!streamOut){err(`usage: model=${model} input=${u.inputTokens} cache_read=${u.cacheReadTokens} cache_write=${u.cacheWriteTokens} output=${u.outputTokens}
26
- `)}const warn=message=>streamOut?emit({type:"system",subtype:"warning",message}):err(`\u26A0 ${message}
27
- `);if(result.droppedMessages>0){warn(`\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u4E0A\u9650\u306E\u305F\u3081\u53E4\u3044\u3084\u308A\u53D6\u308A ${result.droppedMessages} \u4EF6\u3092\u843D\u3068\u3057\u307E\u3057\u305F`)}if(result.maxStepsReached){const msg="\u30C4\u30FC\u30EB\u5B9F\u884C\u306E\u5F80\u5FA9\u304C\u4E0A\u9650\u306B\u9054\u3057\u305F\u305F\u3081\u6253\u3061\u5207\u308A\u307E\u3057\u305F\uFF08\u7D9A\u304D\u306F\u540C\u3058\u4F1A\u8A71\u3067\u518D\u5EA6\u6307\u793A\u3057\u3066\u304F\u3060\u3055\u3044\uFF09";
28
- if(!streamOut)err(`\u26A0 ${msg}
29
- `);return finish(1,result,msg)}if(result.upstreamError!==null){const msg=`\u30E2\u30C7\u30EB\u306E\u5FDC\u7B54\u304C\u9014\u4E2D\u3067\u7D42\u308F\u308A\u307E\u3057\u305F: ${result.upstreamError}`;if(!streamOut)err(`${msg}
30
- `);return finish(1,result,msg)}if(result.aborted||interrupted||controller.signal.aborted){const msg="\u4E2D\u65AD\u3057\u307E\u3057\u305F\uFF08\u3053\u3053\u307E\u3067\u306E\u6D88\u8CBB\u306F\u30C6\u30CA\u30F3\u30C8\u306E\u30AF\u30EC\u30B8\u30C3\u30C8\u306B\u8A08\u4E0A\u3055\u308C\u307E\u3059\uFF09";if(!streamOut)err(`${msg}
31
- `);return finish(130,result,msg)}if(result.emptyResponse){const msg="\u30E2\u30C7\u30EB\u304B\u3089\u30C6\u30AD\u30B9\u30C8\u5FDC\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F";if(!streamOut)err(`${msg}
32
- `);return finish(1,result,msg)}return finish(0,result)}catch(e){const partial=e.usage??emptyUsage();if(!streamOut&&partial.inputTokens+partial.outputTokens>0){err(`usage(\u4E2D\u65AD\u307E\u3067): input=${partial.inputTokens} cache_read=${partial.cacheReadTokens} cache_write=${partial.cacheWriteTokens} output=${partial.outputTokens}
33
- `)}const msg=e instanceof RelayError?e.message:`\u30A8\u30E9\u30FC: ${e.message}`;if(!streamOut)err(`${msg}
34
- `);return finish(1,{text:"",usage:partial,toolCalls:0,droppedMessages:0},msg)}};if(streamOut){emit({type:"system",subtype:"init",model,mode:mode.id,cli_version:opts.version,tools:turnTools.map(t=>t.name)})}if(!streamIn)return await runOneTurn(prompt);return await runStreamSession({lines:(deps.readLines??readStdinLines)(sessionStop.signal),runOneTurn,restoreHistory:messages=>runtime.context.restoreHistory(messages),interruptCurrent:()=>controller.abort(),stop:sessionStop.signal,reject:reason=>streamOut?
35
- emit({type:"system",subtype:"input_rejected",reason}):err(`\u5165\u529B\u3092\u62D2\u5426\u3057\u307E\u3057\u305F: ${reason}
36
- `),warn:message=>streamOut?emit({type:"system",subtype:"warning",message}):err(`\u26A0 ${message}
37
- `),respondPermission:line=>{if(prompter===null)return"--permission-prompt stdio \u3067\u306F\u306A\u3044\u305F\u3081 permission_response \u306F\u53D7\u3051\u4ED8\u3051\u307E\u305B\u3093";return prompter.respond(line)},onInputClosed:()=>prompter?.close(),noTurnMessage:()=>err("user \u884C\u304C1\u3064\u3082\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F\uFF08stream-json \u5165\u529B\uFF09\n")})}finally{cancelCatalogRefresh();process.off("SIGINT",onSigint);ownedAudit?.close()}}async function runStreamSession(d){
38
- const queue=[];let eof=false;let wake=null;let running=false;let interruptNext=false;const notify=()=>{const w=wake;wake=null;w?.()};d.stop.addEventListener("abort",notify,{once:true});const reader=(async()=>{try{for await(const raw of d.lines){if(raw.trim()==="")continue;const parsed=parseInputLine(raw);if(!parsed.ok){d.reject(parsed.reason);continue}if(parsed.line.type==="permission_response"){const reason=d.respondPermission?d.respondPermission(parsed.line):"--permission-prompt stdio \u3067\u306F\u306A\u3044\u305F\u3081 p\
39
- ermission_response \u306F\u53D7\u3051\u4ED8\u3051\u307E\u305B\u3093";if(reason!==null)d.reject(reason);continue}if(parsed.line.type==="interrupt"){if(running)d.interruptCurrent();else if(queue.some(l=>l.type==="user"))interruptNext=true;else d.warn("interrupt \u3092\u53D7\u3051\u307E\u3057\u305F\u304C\u3001\u5B9F\u884C\u4E2D\u306E\u30BF\u30FC\u30F3\u304C\u3042\u308A\u307E\u305B\u3093");continue}queue.push(parsed.line);notify()}}catch(e){if(!d.stop.aborted)d.reject(`\u5165\u529B\u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${e.
40
- message}`)}finally{eof=true;d.onInputClosed?.();notify()}})();let lastCode=null;let turnStarted=false;for(;;){if(d.stop.aborted)break;const line=queue.shift();if(line===void 0){if(eof)break;await new Promise(resolve=>{wake=resolve});continue}if(line.type==="history"){if(turnStarted){d.reject("history \u306F\u6700\u521D\u306E user \u884C\u3088\u308A\u524D\u306B\u3060\u3051\u9001\u308C\u307E\u3059");continue}try{const r=d.restoreHistory(line.messages);if(r.skippedLeadingAssistant>0){d.warn(`histor\
41
- y \u306E\u5148\u982D\u306E assistant ${r.skippedLeadingAssistant} \u4EF6\u3092\u7A4D\u307F\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u4F1A\u8A71\u306F user \u304B\u3089\u59CB\u3081\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\uFF09`)}}catch(e){d.reject(e.message)}continue}if(line.type==="user"){turnStarted=true;running=true;try{const turn=d.runOneTurn(line.text);if(interruptNext){interruptNext=false;d.interruptCurrent()}lastCode=await turn}finally{running=false}continue}const unhandled=line;d.
42
- reject(`\u3053\u306E\u5165\u529B\u7A2E\u5225\u306F\u30BF\u30FC\u30F3\u9593\u3067\u306F\u51E6\u7406\u3067\u304D\u307E\u305B\u3093: ${JSON.stringify(unhandled.type)}`)}if(!d.stop.aborted)await reader;else void reader;if(lastCode===null)d.noTurnMessage();if(d.stop.aborted)return 130;return lastCode??2}var INPUT_CLOSED={kind:"unavailable",reason:"the embedder closed its input"};var INTERRUPTED={kind:"unavailable",reason:"the turn was interrupted"};function createStdioPrompter(emit,currentSignal){const pending=new Map;
43
- let seq=0;let closed=false;return{ask:request=>{if(closed)return Promise.resolve(INPUT_CLOSED);seq+=1;const requestId=`perm_${seq}`;const signal=currentSignal();const target=request.target??{tool:request.tool,input:request.input};return new Promise(resolve=>{const settle=answer=>{if(!pending.delete(requestId))return;signal.removeEventListener("abort",onAbort);resolve(answer)};const onAbort=()=>settle(INTERRUPTED);pending.set(requestId,settle);if(signal.aborted){settle(INTERRUPTED);return}signal.
44
- addEventListener("abort",onAbort,{once:true});emit({type:"permission_request",request_id:requestId,tool_use_id:request.callId??null,tool:target.tool.name,input:target.input,preview:request.preview,guard_reason:request.noAlwaysReason})})},respond:line=>{const settle=pending.get(line.request_id);if(settle===void 0){return`\u5F85\u3063\u3066\u3044\u308B\u627F\u8A8D\u8981\u6C42\u304C\u3042\u308A\u307E\u305B\u3093: request_id=${JSON.stringify(line.request_id)}`}if(line.decision==="allow"){settle("yes")}else{
45
- const text=line.message?.trim()??"";settle(text===""?"no":{kind:"instead",text})}return null},close:()=>{closed=true;for(const settle of[...pending.values()])settle(INPUT_CLOSED)}}}async function*readStdinLines(signal){const{createInterface}=await import("readline");const rl=createInterface({input:process.stdin,crlfDelay:Infinity});const close=()=>{rl.close();process.stdin.pause()};if(signal.aborted)close();signal.addEventListener("abort",close,{once:true});try{for await(const line of rl)yield line}finally{
46
- signal.removeEventListener("abort",close)}}async function readStdin(){const chunks=[];for await(const chunk of process.stdin)chunks.push(Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8")}export{createStdioPrompter,runOneShot,runStreamSession};